Skip to content

fix(serve): dismiss a native dialog the driver leaves open - #87

Merged
tenequm merged 4 commits into
mainfrom
fix/pw-dialog-freeze
Sep 18, 2026
Merged

tenequm merged 4 commits into
mainfrom
fix/pw-dialog-freeze

Conversation

@tenequm

@tenequm tenequm commented Sep 18, 2026 •

Copy link
Copy Markdown
Member

What broke

A native dialog (alert, confirm, prompt, "Leave site?") still open when the driver session ends (pw detach, pw close, a killed driver daemon) froze every later cuttle pw verb: each one hung 30s and died with a Node stack (Daemon process exited with code 1 / Timeout 30000ms exceeded), and nothing but closing the tab over raw CDP recovered it.

Chrome binds a pending dialog to the DevTools sessions that saw it open. Once they are gone, no session can answer it (Page.handleJavaScriptDialog -> "No dialog is showing") while the renderer stays blocked inside it, so Page.enable and every Runtime call on that tab never return. A playwright attach enables every page, so that one tab hangs every attach, and cuttle pw attaches per invocation.

Mechanism: dismiss on the way out, in the proxy

Every CDP client already goes through cuttle serve's websocket proxy. It now watches Page.javascriptDialogOpening / Page.javascriptDialogClosed per session, and when a client leaves (disconnect or Browser.close) with a dialog still showing, it sends Page.handleJavaScriptDialog {accept:false} over that client's own session and waits up to 2s for the answer before closing the browser side. It then waits 250ms for a dialog the dismissal set off (a cancelled confirm that alerts) and dismisses that too, for up to 3 rounds.

Picked over "detect a timed-out verb, then close the frozen tab and retry" because:

  • it is the only moment the dialog is still answerable. Afterwards the dialog can only be cleared by closing the tab.
  • it is exact: only a dialog Chrome announced and nobody answered is touched. There is no guessing from "this page did not answer", so a page that is just busy is never closed.
  • the tab and its state survive. A dismissed confirm returns false and a "Leave site?" stays on the page, which is what an unanswered dialog means.
  • it covers every CDP client (jev-browse, a raw playwright/puppeteer attach), not only cuttle pw, and adds no retry latency.

Cost on the hot path is one 16-byte bytes.Contains per browser frame (vectorized, same pattern as the existing prefilters). The dismissal goes through the humanizer's callWithin machinery (callOn, the same call over the browser-side context and send), so its id and the swallowing of its reply come from the humanizer's range. The fake browser in the test refuses ids above 2^31, as Chrome does, because a first draft used its own id range above that and was never answered.

To keep the browser connection open for the dismissal, the proxy now uses two contexts. A failed write to the client, from either goroutine, cancels only the client side: the humanizer stops at once and its sends are refused from then on, so a dead driver's half-typed text is not finished and no last press or key lands. The browser side stays up until the dismissal is done.

Known trade-off, confirmed live in pool mode: a dialog belongs to the page, so any departing client that saw it dismisses it for every other client on that tab too (a second client's own accept then gets "No dialog is showing"). Leaving it to the last departing session would need per-seed shared state, and would keep the tab blocked for as long as a passive client stays attached.

Not covered: a dialog that opens while no client is attached (a timer firing after pw detach) was never seen by any session, so nothing can answer it, and the next attach still times out after 30s. Closing that tab over Target.closeTarget is the only recovery.

Also in here

  • Lease gate --help bypass: a help flag anywhere in the args skipped the lease gate, so pw fill <ref> -- --help drove the page while jev-browse held the lease. Help now counts only where the driver's parser (minimist) reads it as help: before a --. help and docs are dropped from the read-verb list, since neither is a driver verb. The same classifier took the first non-flag word as the verb, so pw -s snapshot click e5 passed as a read even though the driver runs click. A bare flag in front of the verb that is not one of the driver's booleans, spelled exactly (--json, not -json, which minimist reads as -j -s -o -n), now counts as driving.
  • Parallel auto-attach race: every invocation that found the session gone attached, and an attach replaces the session, so concurrent ones killed each other's daemons mid-start (ENOENT/EADDRINUSE on the socket, "Session closed"). The auto-attach now runs under flock in the container and skips when an invocation ahead of it already brought the session back (playwright-cli list shows only sessions whose daemon answers). A queued attach gives up after 60s with a message rather than waiting behind a hung one, since an attach to a tab that never answers runs to the driver's own 30s timeout. jev-browse's runner uses the same attach argv.
  • /json/close/<id> (and activate, new, protocol) fell into the GET /json/ catch-all and answered 200 with the tab list, closing nothing. /json/ now matches exactly, and every other /json/... returns a 404 naming the CDP Target.* equivalent.
  • SKILL.md says a dialog left open when the session ends gets dismissed. The cuttle up briefing's dialog-accept/dialog-dismiss advice was already right for a live session, so it is unchanged.

Verification

Live, throwaway --ephemeral containers from main (a1df361) and from this branch:

check main this branch
data: page, pw click opens alert, pw detach, pw snapshot rc=1 after 31s, Node timeout stack rc=0 in 2s, snapshot shows the page; daemon log dismissing 1 native dialog(s), answered in 3ms
confirm left open, then pw close / pkill -9 cliDaemon.js, then pw eval document.title - "false" both ways, in 3s; a prompt gives "null"
if(!confirm(1)){alert(2)} left open, pw detach, pw eval - both dismissed (two rounds 250ms apart), the handler ran to the end
pool mode, two clients on one tab with Page enabled, one leaves - the dialog is dismissed for the other too (the trade-off above)
lock held by another attach for 75s - cuttle: gave up after 60s waiting for another invocation's attach
pkill -9 chrome, then 10 parallel pw snapshot 2/10 and 7/10 ok on two runs 10/10 ok on three runs
lease held, pw fill e2 -- --help reached the driver refused naming the holder; pw -s snapshot click e2 also refused; pw --help fill and pw snapshot still pass
GET /json/close/X 200 + tab list 404 + CDP pointer; /json/ still 200

Unit tests: TestLeftOpenDialogIsDismissed (disconnect, Browser.close, a dismissal that sets off a second dialog, and a dialog the driver answered itself, which must not be dismissed again; it fails without the fix), TestUnproxiedJSONEndpointsAre404, and new TestPlaywrightReadOnly cases. just check passes.

Release notes

A native dialog left open when a cuttle pw session ends no longer freezes every later cuttle pw command. cuttle dismisses it. pw fill ... -- --help now respects the session lease, and parallel cuttle pw calls after a browser crash no longer fail while re-attaching.

@tenequm
tenequm force-pushed the fix/pw-dialog-freeze branch from a7765fe to 8ddff3b Compare September 18, 2026 23:13
… more for a gone client

Dismissal now awaits Chrome's answer on the browser-side context, so it holds
on a clean disconnect too, then waits briefly for a dialog the answer set off
(a cancelled confirm that alerts) and dismisses that as well. The humanizer's
sends are cut off with the client, so a dead driver's in-flight sequence cannot
land one more press or key. The lease gate matches boolean flags exactly
(-json is not --json), and a queued auto-attach gives up after 60s with a
message instead of waiting behind a hung one indefinitely.
@tenequm
tenequm force-pushed the fix/pw-dialog-freeze branch from 8ddff3b to 6032a31 Compare September 18, 2026 23:42
@tenequm
tenequm merged commit 14f24cb into main Sep 18, 2026
10 checks passed
@tenequm
tenequm deleted the fix/pw-dialog-freeze branch September 18, 2026 23:47
tenequm added a commit that referenced this pull request Sep 19, 2026
…ts (#86)

Pool-mode and daemon fixes from the stress test: a leaked Chrome per
discovery probe, a capture tab that clients attached to and then lost,
tabs that stopped answering for good under churn, cold-launch bursts
that failed, and stub profile dirs left behind by reaps. Plus two
`cuttle secret` exit-code fixes.

Each item was measured on throwaway pool containers running the release
image with this branch's binary mounted in, against the same image on
`origin/main` (`--mode=pool --idle-timeout=30`).

## 1. Pool seeds that no client ever connected to were never reaped

**Root cause:** the idle timer was armed only in `disconnect()`. A seed
launched by HTTP discovery alone (`GET /json/version?fingerprint=X`, a
health check, a `connectOverCDP` that fails before its WebSocket opens)
never disconnects, so it ran a whole Chrome until shutdown.

**Fix:** `getOrLaunch` arms the timer when it launches and nothing is
connected. It arms it only after the snapshot re-inject, so a reap
cannot kill a browser mid-inject. A client that arrives cancels it in
`connect()`.

**Evidence:** on `main`, the probe seed was still running long after the
30s timeout. With the fix it was reaped 30s after the probe. Tests:
`TestIdleReapWithoutAnyClient`, `TestLaunchTimerYieldsToAClient`.

## 2. State capture opened a scratch tab that clients attached to

**Root cause:** `cdp.Extract` went through `chromedp.Run`, which opens
an `about:blank` tab first. In pool mode the capture fires on every last
disconnect. A driver that reconnected at once saw that tab first in
`Target.getTargets`, attached to it, and then had it closed under it
("Session with given id not found").

**Fix:** the capture needs no tab. Cookies (`Storage.getCookies`) and
the target list are calls on the browser session, and localStorage is
already read from the open tabs in place. `Extract` now uses
`chromedp.Targets` to connect the browser without opening a tab.
`Inject` still uses a tab: it has to navigate to write localStorage, and
it runs at launch, before any client.

**Evidence:** reconnect loop (`recon3`, 10 iterations): 1/10 failed on
`main`, 0/10 with the fix. The capture still records localStorage (`1
cookies / 1 domains / 1 origins`). Test: `TestExtractOpensNoTab`, which
fails on the old code.

## 3. Tabs hung for good in pool mode under churn

**Root cause, isolated on raw CDP straight to Chrome's own port (no
daemon involved):** the hung tab's renderer had **crashed**.
`Inspector.targetCrashed` arrives about 30ms after the attach. A crashed
tab stays listed and answers no `Page.*` or `Runtime.*` command until
something reloads it (`Page.reload` brings it back), so every client
sees a permanent hang. The trigger is the daemon's focus pin
(`Emulation.setFocusEmulationEnabled`) being in flight when
`Page.navigate` arrives. A driver hits this whenever it creates a tab
and navigates at once. Crash rate per createTarget+attach+navigate,
30-100 runs per variant:

| sequence | crashed |
|---|---|
| no pin | 0/100 (and 0/30) |
| locale pin only | 0/30 |
| focus pin sent, navigate sent right after | 4/100, 2/30, 1/30, 1/50 |
| focus pin, **await its reply**, then navigate | 0/100 |
| navigate, then focus pin | 0/100 |

The crash itself is in Chromium: a renderer crashes when a
focus-emulation change and a navigation overlap. cuttle removes the
trigger instead of trying to recover from the crash.

**Fix:** `pinGates` in the ws proxy holds a page session's client
commands until the replies to the pins the proxy sent on that session
come back. It is armed on `Target.attachedToTarget`, before the client
can learn the session id, and bounded at 2s. The renderer answers the
pins, so a tab that is busy or blocked on a dialog holds the
connection's commands for that 2s once per attach (such a tab does not
answer the driver's own commands either). Nothing is decoded while no
gate is armed. Pages still get the pin, so playwright's actionability
waits in background tabs keep working.

**Evidence:**
- via the daemon, warm seed, 100 create+navigate cycles (`ct2 same`):
5/100 hung on `main`, 0/100 with the fix.
- churn, 6 workers over 20 seeds for 180s: on `main`, 13 of 20
connections finished, with 69 `Runtime.evaluate` timeouts, and every
worker was stuck by the deadline. With the fix, 616/616 finished with no
errors.
- `cuttle pw` goto / snapshot / tab-new / eval / fill against a
session-mode container: all ok at normal latency (0.3-0.9s per verb). No
gate ever hit its timeout.

Tests: `TestPinGateHoldsNavigateUntilPinAnswered`, which fails without
the gate, and `TestPinGateExpires`.

The gate only ever released on its 2s bound during the 24-seeds-on-1-CPU
run (9 sessions), where a starved Chrome was slow to answer anything.
All 24 of those launches still succeeded.

## 4. Concurrent cold launches returned HTTP 502

**Root cause:** launches had no concurrency bound, and readiness was a
fixed 10s wait. A burst of distinct seeds cold-starts every Chrome at
once, and they starve each other on CPU past the 10s wait.

**Fix:** launches queue for a slot, sized `max(2, GOMAXPROCS)`
(GOMAXPROCS follows the container's CPU limit). The readiness wait is
now 30s, but it ends the moment Chrome exits, so a browser that dies
during startup still fails fast.

**Evidence:** 24 concurrent cold seeds on a `--cpus 1` container: 0/24
on `main` (24 "readiness window" failures), 24/24 with the fix (130s
wall time, no cookie bleed). With no CPU limit, `main` passed 30/30 and
45/45 on this host, so the stress test's 2/24 needed CPU contention to
show up. Tests: `TestColdLaunchesAreBounded`,
`TestReadinessWaitEndsWhenChromeExits`.

## 5. Reaped seeds left `/data/<seed>/Default` stubs behind

**Root cause:** each stub held a single
`Default/.org.chromium.Chromium.XXXXXX` temp file, written seconds after
the reap deleted the dir. The pool treated "the browser process exited"
as the end of Chrome, but helpers in its process group were still
flushing into the profile. A helper finishing a write recreated
`Default/` after the delete. A forced kill was not waited for at all
before the delete.

**Fix:** `waitExit`/`wait` now fire only once the Chrome's whole process
group is gone. Helpers get 2s to exit on their own, then SIGKILL.
`running()` still turns false with the browser process, so nothing hands
out a dead browser; the relaunch itself waits for the drain, since it
reuses the profile dir. `stopProcess` waits for that drain before the
caller deletes the profile, including after a forced kill and for a
Chrome that exited on its own.

**Evidence:** `main` left 15 stub dirs from 141 reaps. The fix left 0
from 89 reaps under the same workloads. Test:
`TestChromeExitWaitsForItsHelpers`, which fails without the drain.

## Review pass (polish)

A two-agent review (cleanliness/design, efficiency/side-effect gating)
produced these fixes, all in the last commit:
- Arm the launch timer after the re-inject (above).
- Pin a page-endpoint session before the client pump starts. That
ordering was already wrong on `main`, and without the move its first
frame could overtake the gate.
- Expire gates whose tab never answers, so an armed gate cannot leave a
per-frame decode behind for the rest of the connection.
- Keep `running()` tied to the browser process (above).
- Let a launch still queued at shutdown give up instead of starting a
Chrome.
- Fix comments made stale by the no-tab capture (`cdp.go`, `http.go`,
`auth.go`).

Dropped after validation:
- Merging the new `Extract` test fake into the `cookieJar` fake: that
one is a different transport.
- `launch_seconds` now including time spent queued: its help text
already says "from launch request".

## Independent review pass

A second, four-agent review (cleanliness, design, efficiency,
side-effect gating) with fresh measurements added two commits:
- **Idle reap vs relaunch (pre-existing, widened here):** the reap
dropped the seed's launch lock before tearing the browser down, so a
relaunch of the same seed started Chrome in the stable profile dir the
reap then deleted. The reap now holds the lock until the dir is gone; a
caller queued on a retired lock retries on the current one. Test:
`TestRelaunchWaitsOutTheReap`, which fails without it.
- The pin gate now runs ahead of the humanizer and secret paths, which
send their own commands on the frame's session.
- After rebasing onto #87's dialog dismissal, a gated frame stops
waiting once its client is gone, so the dismissal is not delayed by the
gate.
- A queued launch re-checks shutdown after taking a slot (`select` picks
at random when both are ready).
- De-flaked `TestLaunchTimerYieldsToAClient` (30ms timer vs an
unsynchronized `connect`), and corrected the pin-gate, drain and TTL
comments.

Dropped after validation: re-using `preprocessClient`'s decode for the
gate's session id (only while a gate is armed, ms windows); the
pre-existing 3+8+5s shutdown worst case vs `docker stop -t 15` (the
drain runs inside the existing grace); folding `auth.go`'s cookie reader
into `internal/cdp` (separate refactor).

## 6. `cuttle secret` minors

- `secret rm` of a name the session never held, and that had no recipe,
printed "nothing to remove" and exited 0. It now returns an error, so
the exit is non-zero. The wording is unchanged.
- A negative or sub-second `--ttl` (`-5s`, `500ms`) silently became the
15m default, because the CLI dropped `ttl <= 0`. `set`, `refresh`,
`prompt` and `capture` now refuse it before any value is taken. The
daemon API answers 400 to a negative `ttl_seconds`.

Tests: `TestSecretRemoveOfAnUnknownNameFails`,
`TestSecretTTLRefusesWhatTheDaemonWouldIgnore`,
`TestPutRefusesANegativeTTL`.

## Not in this PR

- The smoke harness hardcoding the container name and the canvas
`toDataURL` instability went to separate PRs.
- `down` printing "profile kept" on an ephemeral container, and a re-`up
--ephemeral` warning about an unchanged setting, live in
`commands.go`/`backend`, which the lifecycle work owns. Left for that
PR.

## Release notes

Pool mode: HTTP-only probes are now idle-reaped, reconnects no longer
land on a closing capture tab, tabs no longer hang after
create-and-navigate, launch bursts queue, and a seed relaunched mid-reap
keeps its profile. `secret rm` of an unknown name and a negative `--ttl`
now fail.
tenequm added a commit that referenced this pull request Sep 19, 2026
…#91)

## Problem

A native dialog that opens while no CDP client is attached (a page timer
that fires after `cuttle pw detach`, or after the driver dropped) is
seen by no session, so the dismiss-on-disconnect from #87 never runs.
Chrome binds a pending dialog to the DevTools sessions that were
Page-enabled when it opened: a later client's `Page.enable` waits on the
blocked renderer, and its `Page.handleJavaScriptDialog` gets "No dialog
is showing". Every later `cuttle pw` auto-attach hung until playwright's
30s timeout, and only closing the tab recovered.

## Fix

Each launched browser now gets a `dialogWatch`: the daemon's own
browser-level CDP connection that auto-attaches to every page (existing
and future, pages only), enables Page on each, and tracks which tabs
have a dialog showing. When a client connects to a seed that had no
other client, `serveWS` has the watch dismiss those dialogs before the
client is proxied, including any a dismissal sets off (same rounds as
#87). The watch reuses #87's `openDialogs` tracking and dismissal
rounds, and writes on a context detached from the connecting client
(coder/websocket closes the whole connection when a write's context
ends).

An idle reap or shutdown also has the watch dismiss any dialog before
the teardown capture: an orphaned dialog otherwise held the capture for
the full 30s `captureTimeout` with the seed lock held (measured live in
pool mode: 30s before, 0.27s after).

It does not dismiss at open time: with no client attached the dialog may
be the person's in the viewer, and with a client attached it is that
client's to answer (it still surfaces to playwright as a modal state).
Works the same in session and pool mode, since every instance comes from
`spawn`. Best-effort: a browser the watch cannot dial simply has none.

## Verification

Live, against an image built from this branch, with a page doing
`setTimeout(() => alert('x'), 3000)`: `pw goto`, `pw detach`, wait 6s,
`pw snapshot`.

- Before: `pw snapshot` failed after 32s (playwright attach timeout).
- After: `pw snapshot` returned the page in 3s; the log shows
`dismissing 1 native dialog(s) no client answered`.
- Same result for a dialog in a tab opened after launch (`pw tab-new`).
- With the driver attached when the alert fires, `pw snapshot` still
reports `Modal state: ["alert" dialog with message "x"]` and `pw
dialog-dismiss` clears it.
- Pool mode (`--mode=pool --idle-timeout=10`, raw CDP client per seed):
the next attach's `Page.enable` answers in ~260ms after an orphaned
dialog; after an idle reap the relaunched browser gets a fresh watch and
the same fix holds.
- With no client, the dialog stays up (the page title set after
`alert()` does not change in `/json/list`) until the next client
connects.

New unit test `TestDialogWatchDismissesADialogNoClientSaw` drives the
watch against the fake browser harness; it fails when dismissal is
disabled. `just check` passes.

## Release notes

A native dialog (alert, confirm, "Leave site?") that opens while no
driver is attached no longer hangs the next `cuttle pw` command for 30s:
cuttle dismisses it when the next client connects. A dialog that opens
while a driver is attached still reaches the driver.
tenequm added a commit that referenced this pull request Sep 21, 2026
🤖 I have created a release *beep* *boop*
---


## [0.15.0](v0.14.2...v0.15.0)
(2026-09-21)


### Features

* bundle playwright-cli into the image with a cuttle pw passthrough
([#67](#67))
([28d9846](28d9846))
* **cli:** center the skill and briefing on cuttle pw, drop host driver
routing ([#75](#75))
([33eca16](33eca16))
* **cli:** colored jev-browse output
([#70](#70))
([cf6f109](cf6f109))
* **cli:** cuttle jev-browse - autonomous browsing loop on the bundled
driver ([#66](#66))
([0496957](0496957))
* **cli:** deliver pw action snapshots as a host file, secrets masked
([#103](#103))
([78adbbb](78adbbb))
* **cli:** make --context/--name global so pw and jev-browse reach any
instance ([#74](#74))
([9df5c33](9df5c33))
* **cli:** zero-ceremony cuttle pw - auto-attach on demand, allow open
([a7e6491](a7e6491))
* **jev:** withhold write actions and halve jev-browse run time
([#102](#102))
([9ca9386](9ca9386))
* **serve:** mask password field values in /snapshot
([#109](#109))
([2a352b5](2a352b5))
* **serve:** session lease - one driver at a time, with takeover
([#69](#69))
([87724c8](87724c8))


### Bug Fixes

* **backend:** keep profile cleanup and remote argv from reaching past
their own ([#92](#92))
([f52cfd3](f52cfd3))
* **cli:** close the gaps a review of the lifecycle fixes found
([#90](#90))
([c46aa5e](c46aa5e))
* **cli:** close the lifecycle gaps a stress run left open
([#88](#88))
([899a535](899a535))
* **cli:** discarding the profile removes the instance's host snapshot
dir ([#113](#113))
([57cd07a](57cd07a))
* **cli:** downloads --wait accepts a finished download, logs drops
D-Bus spam ([#111](#111))
([dcc2f46](dcc2f46))
* **cli:** name the in-page dialog behind a pw click timeout
([#99](#99))
([11beeeb](11beeeb))
* **cli:** never fall back to another instance when the selected one is
stopped ([#78](#78))
([a1df361](a1df361))
* **cli:** re-attach the driver after a restart leaves a stale session
([#77](#77))
([bbeb0f0](bbeb0f0))
* **cli:** run --extract on every ending, not only done
([#71](#71))
([4954195](4954195))
* **jev:** judge done on the page that landed, and end done on a none
above even odds ([#108](#108))
([a9cb5a8](a9cb5a8))
* **jev:** offer filter-apply controls the write gate withheld
([#114](#114))
([bdf440a](bdf440a))
* **jev:** read quoted snapshot lines and keep field values out of
--extract ([#89](#89))
([09111a2](09111a2))
* **pw:** compact find output, downloads into a directory, quieter logs
([#116](#116))
([62f2ca8](62f2ca8))
* **pw:** snapshot links a host file like an action, and the console log
line names its verb
([#110](#110))
([c902c58](c902c58))
* **serve:** dismiss a native dialog the driver leaves open
([#87](#87))
([14f24cb](14f24cb))
* **serve:** keep the default seed's downloads across browser relaunch
([aac8e40](aac8e40))
* **serve:** keep the dialog watch alive through a signal shutdown
([#94](#94))
([4f4f1d0](4f4f1d0))
* **serve:** pool-mode reaping, capture tab, hung tabs and launch bursts
([#86](#86))
([3b42ea2](3b42ea2))
* **serve:** skip an idle reap whose timer a launch has since re-armed
([#93](#93))
([c667868](c667868))
* **smoke:** never exec into a container the run was not pointed at
([#79](#79))
([9075244](9075244))
* **viewer:** keep websocket inside proxy prefix
([#62](#62))
([3b10ba7](3b10ba7))


### Performance Improvements

* **cli:** run a pw verb in one docker exec, lease check included
([#100](#100))
([a9c3c90](a9c3c90))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant