From a8661616ae0fd76c9f6e959084f18b92613303fc Mon Sep 17 00:00:00 2001 From: lvladika Date: Tue, 17 Nov 2026 19:34:33 +0100 Subject: [PATCH] fix(devicelab): connecting to Chrome leaves the tabs that were open before Each connect to Chrome's DevTools closed every page target but the one it kept (closeOtherTabs, added so that openLink's new tabs do not pile up). On a phone in use that closed all of its owner's tabs at the runner's first connect, with no option to turn it off. The manager now remembers the page targets Chrome listed the first time it read them, and never closes those: they are tabs the runner did not open. Later connects close the other page targets but the kept one, as before, so the tabs openLink opens after that first look are still cleaned up. The set survives openLink's disconnect and a cleanup. A runner process can leave up to two tabs of its own open: the page kept at its first look, when an openLink came before its first connect (it is one of the remembered ones), and the page kept at its last connect, which upstream also left. Upstream left that one only, and the next process closed it; now the next process takes both for tabs that were there before. A test with a fake DevTools endpoint on a Unix socket: the first connect closes nothing, a later one only the tab opened after the first look, across a disconnect and a cleanup. It fails without the change (the first connect closed the three tabs that were open). --- pkg/driver/devicelab/webview.go | 33 +++++++-- pkg/driver/devicelab/webview_tabs_test.go | 82 +++++++++++++++++++++++ 2 files changed, 110 insertions(+), 5 deletions(-) create mode 100644 pkg/driver/devicelab/webview_tabs_test.go diff --git a/pkg/driver/devicelab/webview.go b/pkg/driver/devicelab/webview.go index 5b1e2d2e..a279016f 100644 --- a/pkg/driver/devicelab/webview.go +++ b/pkg/driver/devicelab/webview.go @@ -70,6 +70,13 @@ type webViewManager struct { // (re)connect. helperBroken bool + // preexistingTabs holds the page targets Chrome listed the first time + // this manager read them: tabs the runner did not open (the device + // user's own), which closeOtherTabs never closes. nil until that first + // read; disconnect and cleanup keep it, since openLink disconnects every + // time. + preexistingTabs map[string]bool + forwarder CDPForwarder } @@ -955,8 +962,9 @@ func (m *webViewManager) connectBrowserViaHTTP(cdpInfo *core.CDPInfo, cdpType st } logger.Info("[cdp:5-discover] found page target: id=%s title=%q url=%s", pageTarget.ID, pageTarget.Title, pageTarget.URL) - // Close all other tabs to prevent tab accumulation and stale connections. - // Each openLink creates a new Chrome tab; without cleanup, tabs pile up indefinitely. + // Close the other tabs this runner opened, to prevent tab accumulation and + // stale connections: each openLink creates a new Chrome tab, and without + // cleanup they pile up indefinitely. Tabs that were open before are left. m.closeOtherTabs(socketPath, targets, pageTarget.ID) // Step 6: Connect WebSocket to PAGE-level endpoint (not browser level) @@ -1059,9 +1067,24 @@ func (m *webViewManager) fetchCDPTargets(socketPath string) ([]cdpTarget, error) return targets, nil } -// closeOtherTabs closes all Chrome tabs except the one we're connecting to. -// Uses HTTP /json/close/ via the forwarded Unix socket. Best-effort — errors are logged but ignored. +// closeOtherTabs closes the Chrome tabs this runner opened except the one +// we're connecting to. A tab that was already open the first time the runner +// read Chrome's targets is not one it opened, and is never closed: the first +// call only remembers those, every later one closes the rest. Uses HTTP +// /json/close/ via the forwarded Unix socket. Best-effort — errors are +// logged but ignored. Called with m.mu held. func (m *webViewManager) closeOtherTabs(socketPath string, targets []cdpTarget, keepID string) { + if m.preexistingTabs == nil { + m.preexistingTabs = map[string]bool{} + for _, t := range targets { + if t.Type == "page" { + m.preexistingTabs[t.ID] = true + } + } + logger.Info("[cdp:5-cleanup] %d tab(s) were open at the first look; they stay open", len(m.preexistingTabs)) + return + } + transport := &http.Transport{ DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { var dialer net.Dialer @@ -1072,7 +1095,7 @@ func (m *webViewManager) closeOtherTabs(socketPath string, targets []cdpTarget, closed := 0 for _, t := range targets { - if t.ID == keepID || t.Type != "page" { + if t.ID == keepID || t.Type != "page" || m.preexistingTabs[t.ID] { continue } resp, err := httpClient.Get(fmt.Sprintf("http://localhost/json/close/%s", t.ID)) diff --git a/pkg/driver/devicelab/webview_tabs_test.go b/pkg/driver/devicelab/webview_tabs_test.go new file mode 100644 index 00000000..43ec2157 --- /dev/null +++ b/pkg/driver/devicelab/webview_tabs_test.go @@ -0,0 +1,82 @@ +package devicelab + +import ( + "net" + "net/http" + "os" + "path/filepath" + "reflect" + "strings" + "sync" + "testing" +) + +// fakeDevTools is Chrome's DevTools HTTP endpoint on a Unix socket, as the +// ADB forward exposes it; it records the tabs it is asked to close. +func fakeDevTools(t *testing.T) (socketPath string, closed func() []string) { + t.Helper() + dir, err := os.MkdirTemp("", "cdp") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + socketPath = filepath.Join(dir, "s") + ln, err := net.Listen("unix", socketPath) + if err != nil { + t.Fatal(err) + } + var mu sync.Mutex + var ids []string + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if id, ok := strings.CutPrefix(r.URL.Path, "/json/close/"); ok { + mu.Lock() + ids = append(ids, id) + mu.Unlock() + _, _ = w.Write([]byte("Target is closing")) + return + } + http.NotFound(w, r) + })} + go func() { _ = srv.Serve(ln) }() + t.Cleanup(func() { _ = srv.Close() }) + return socketPath, func() []string { + mu.Lock() + defer mu.Unlock() + return append([]string(nil), ids...) + } +} + +func pages(ids ...string) []cdpTarget { + targets := []cdpTarget{{ID: "worker", Type: "service_worker"}} + for _, id := range ids { + targets = append(targets, cdpTarget{ID: id, Type: "page"}) + } + return targets +} + +// The tabs Chrome had open when the runner first read its targets are the +// device user's, not the runner's: connecting never closes them. A tab an +// openLink opened after that is closed at a later connect, as before, so the +// runner's own tabs do not pile up, and openLink's disconnect in between +// does not make the runner forget which tabs were there first. The page kept +// at the first look is one of those, so it stays open too. +func TestCloseOtherTabsLeavesTabsOpenBeforeTheFirstLook(t *testing.T) { + socket, closed := fakeDevTools(t) + m := newWebViewManager(nil) + + // First look: the user's three tabs and the one the flow's openLink opened. + m.closeOtherTabs(socket, pages("11", "12", "13", "20"), "20") + if got := closed(); len(got) != 0 { + t.Fatalf("the first connect closed %v; the tabs open before the runner looked must stay open", got) + } + + // Two more openLinks, each followed by openLink's disconnect. + m.disconnect() + m.closeOtherTabs(socket, pages("11", "12", "13", "20", "21"), "21") + m.cleanup() + m.closeOtherTabs(socket, pages("11", "12", "13", "20", "21", "22"), "22") + + if got, want := closed(), []string{"21"}; !reflect.DeepEqual(got, want) { + t.Errorf("closed %v; want only %v, the tab the runner opened after its first look", got, want) + } +}