Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 28 additions & 5 deletions pkg/driver/devicelab/webview.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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/<id> 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/<id> 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
Expand All @@ -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))
Expand Down
82 changes: 82 additions & 0 deletions pkg/driver/devicelab/webview_tabs_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading