Skip to content
Merged
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
8 changes: 6 additions & 2 deletions packages/cuttle/internal/serve/pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ type chromeInstance struct {
// is read and written under its own mutex, never captured by value.
keepAliveMu sync.Mutex
keepAlive string

dialogs *dialogWatch
}

// keepAliveID returns the tab currently holding this browser open.
Expand Down Expand Up @@ -233,13 +235,14 @@ func (p *chromePool) lockSeed(key string) *sync.Mutex {
}

// connect increments a seed's connection refcount and cancels any pending idle
// reap.
func (p *chromePool) connect(seedKey string) {
// reap. It reports whether this is the seed's only client.
func (p *chromePool) connect(seedKey string) bool {
p.mu.Lock()
defer p.mu.Unlock()
p.cancelIdleLocked(seedKey)
p.conns[seedKey]++
p.metrics.attaches.Inc()
return p.conns[seedKey] == 1
}

// disconnect decrements a seed's refcount and, when the last client detaches,
Expand Down Expand Up @@ -742,6 +745,7 @@ func (p *chromePool) spawn(seedKey, actualSeed string, chromeArgs []string, time
locale: locale,
proxy: proxy,
keepAlive: keepAliveID,
dialogs: watchDialogs(p.baseCtx, port),
}, nil
}

Expand Down
3 changes: 3 additions & 0 deletions packages/cuttle/internal/serve/supervise.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,9 @@ func (p *chromePool) captureSupervised(seedKey string, inst *chromeInstance) {
func (p *chromePool) captureAndTerminate(ctx context.Context, seedKey string, inst *chromeInstance, supervise bool) {
captured := true
if supervise {
// A dialog left showing blocks the capture's page reads until captureTimeout,
// with the seed lock held, and the browser is going away regardless.
inst.dialogs.dismiss(ctx, "seed="+seedKey+" teardown")
mu := p.captureMu(seedKey)
mu.Lock()
captured = p.doCapture(ctx, seedKey, inst)
Expand Down
116 changes: 111 additions & 5 deletions packages/cuttle/internal/serve/wsproxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,11 @@ func (m *multiplexer) serveWS(w http.ResponseWriter, r *http.Request, cp *chrome
return
}

m.pool.connect(seedKey)
// A dialog that opened with no client attached blocks this one's attach, and
// only the daemon's own session on the tab can still answer it.
if m.pool.connect(seedKey) {
cp.dialogs.dismiss(r.Context(), label)
}
defer m.pool.disconnect(seedKey)

target := "ws://127.0.0.1:" + strconv.Itoa(cp.cdpPort) + "/devtools/" + path
Expand Down Expand Up @@ -534,16 +538,24 @@ func (d *openDialogs) take() []string {
// open, and awaits each answer on it: the humanizer's own context and send end
// with the client.
func (d *openDialogs) dismiss(ctx context.Context, h *humanizer, send func(websocket.MessageType, []byte) error, label string) {
d.dismissRounds(ctx, label, "the client left open", func(sid string) {
if _, ok := h.callOn(ctx, send, sid, methodHandleDialog, map[string]any{"accept": false}, dismissTimeout); !ok && ctx.Err() == nil {
logWarn("%s: dismissing a dialog the client left open got no answer", label)
}
})
}

// dismissRounds takes the dialogs showing and answers each, then waits for any
// the answers set off, up to maxDismissRounds times.
func (d *openDialogs) dismissRounds(ctx context.Context, label, which string, answer func(sid string)) {
for range maxDismissRounds {
sids := d.take()
if len(sids) == 0 || ctx.Err() != nil {
return
}
logInfo("%s: dismissing %d native dialog(s) the client left open", label, len(sids))
logInfo("%s: dismissing %d native dialog(s) %s", label, len(sids), which)
for _, sid := range sids {
if _, ok := h.callOn(ctx, send, sid, methodHandleDialog, map[string]any{"accept": false}, dismissTimeout); !ok && ctx.Err() == nil {
logWarn("%s: dismissing a dialog the client left open got no answer", label)
}
answer(sid)
}
t := time.NewTimer(chainedDialogWait)
select {
Expand Down Expand Up @@ -656,6 +668,100 @@ func (g *pinGates) wait(ctx context.Context, frame []byte) {
}
}

// dialogWatch is the daemon's own Page-enabled session on every tab of one
// browser, for the dialog no client saw: one that opens while no client is
// attached (a timer that fires after the driver detached). Chrome binds a dialog
// to the sessions enabled when it opened (see openDialogs), so a later client
// can neither answer it nor attach past it; this session, enabled on each tab
// from the start, can.
//
// It dismisses only when a client arrives to an otherwise empty browser: with no
// client the dialog may be the person's in the viewer, and with one attached it
// is left to that client.
type dialogWatch struct {
dialogs openDialogs
mu sync.Mutex // guards ws and nextID
ws *websocket.Conn // nil until the watch has dialed the browser
nextID int64
}

func newDialogWatch() *dialogWatch {
return &dialogWatch{dialogs: openDialogs{sessions: map[string]struct{}{}}}
}

// watchDialogs starts a dialogWatch on the browser at port. Best-effort: on a
// browser it cannot reach the watch stays inert, and it ends with the browser.
func watchDialogs(ctx context.Context, port int) *dialogWatch {
w := newDialogWatch()
go func() {
dialCtx, cancel := context.WithTimeout(ctx, keepAliveTimeout)
conn, err := dialBrowser(dialCtx, port)
cancel()
if err != nil {
logWarn("dialog watch not started (port=%d): %v", port, err)
return
}
w.run(ctx, conn.ws)
}()
return w
}

// run attaches to every page, current and future, enables Page on each and
// tracks their dialogs until the browser connection ends.
func (w *dialogWatch) run(ctx context.Context, ws *websocket.Conn) {
defer ws.Close(websocket.StatusNormalClosure, "")
w.mu.Lock()
w.ws = ws
w.mu.Unlock()
w.send(ctx, "", "Target.setAutoAttach", map[string]any{
"autoAttach": true, "waitForDebuggerOnStart": false, "flatten": true,
"filter": []any{map[string]any{"type": targetPage}},
})
for {
_, data, err := ws.Read(ctx)
if err != nil {
return
}
if bytes.Contains(data, attachedToTargetBytes) {
if sid := attachedPageSession(data); sid != "" {
w.send(ctx, sid, "Page.enable", nil)
}
continue
}
w.dialogs.observe(data)
}
}

// send fires one command without awaiting its answer: Page.enable on a tab
// already blocked in a dialog is never answered, and a dismissal that lands shows
// up as the javascriptDialogClosed observe already tracks.
func (w *dialogWatch) send(ctx context.Context, sid, method string, params map[string]any) {
w.mu.Lock()
w.nextID++
id, ws := w.nextID, w.ws
w.mu.Unlock()
cmd := dispatchCmd(id, method, sid, params)
if ws == nil || cmd == nil {
return
}
// Detached from the caller: coder/websocket closes the whole connection when a
// write's context ends, and a client leaving mid-dismissal must not end the watch.
wctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), dismissTimeout)
defer cancel()
_ = ws.Write(wctx, websocket.MessageText, cmd)
}

// dismiss answers every dialog showing on the browser, then any the answers set
// off. nil-safe, and free when nothing is showing.
func (w *dialogWatch) dismiss(ctx context.Context, label string) {
if w == nil {
return
}
w.dialogs.dismissRounds(ctx, label, "no client answered", func(sid string) {
w.send(ctx, sid, methodHandleDialog, map[string]any{"accept": false})
})
}

// keepAliveClose returns the target id when this frame is a close of the seed's
// keep-alive tab, or "". One decode: the id is needed twice on that path, and
// closeTargetID walks the whole frame.
Expand Down
60 changes: 60 additions & 0 deletions packages/cuttle/internal/serve/wsproxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -745,3 +745,63 @@ func TestPinGateExpires(t *testing.T) {
t.Fatalf("expired gate still armed: %v", g.gates)
}
}

// A dialog that opens while no client is attached is seen by no client, so only
// the daemon's own session can answer it; it does so when the next client
// arrives, and only then.
func TestDialogWatchDismissesADialogNoClientSaw(t *testing.T) {
t.Parallel()
browser, target := startCDPBrowser(t, nil, func(cmd map[string]any) ([]map[string]any, []map[string]any) {
sid := cmd["sessionId"]
switch cmd["method"] {
case "Target.setAutoAttach":
return nil, []map[string]any{{"method": methodAttachedToTarget, "params": map[string]any{
"sessionId": "S1", "targetInfo": map[string]any{"type": targetPage},
}}}
case "Page.enable": // the page's timer fires once the watch is on the tab
return nil, []map[string]any{{"method": methodDialogOpening, "sessionId": sid, "params": map[string]any{"type": "alert"}}}
case methodHandleDialog:
return []map[string]any{{"method": methodDialogClosed, "sessionId": sid, "params": map[string]any{"result": false}}}, nil
}
return nil, nil
})
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
ws, _, err := websocket.Dial(ctx, target, nil)
if err != nil {
t.Fatal(err)
}
w := newDialogWatch()
go w.run(ctx, ws)

handled := func() []map[string]any {
var out []map[string]any
for _, m := range browser.received() {
if m["method"] == methodHandleDialog {
out = append(out, m)
}
}
return out
}
for ctx.Err() == nil {
w.dialogs.mu.Lock()
seen := len(w.dialogs.sessions)
w.dialogs.mu.Unlock()
if seen > 0 {
break
}
time.Sleep(10 * time.Millisecond)
}
if got := handled(); len(got) != 0 {
t.Fatalf("dismissed before any client arrived: %v", got)
}
w.dismiss(ctx, "test")
w.dismiss(ctx, "test") // nothing left showing: no second answer
got := handled()
if len(got) != 1 {
t.Fatalf("browser got %d Page.handleJavaScriptDialog, want 1: %v", len(got), browser.received())
}
if got[0]["sessionId"] != "S1" || got[0]["params"].(map[string]any)["accept"] != false {
t.Errorf("Page.handleJavaScriptDialog = %v, want a dismissal on session S1", got[0])
}
}
Loading