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
22 changes: 14 additions & 8 deletions docs/knowledge/findings/playwright-cli-attach-model.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@ description: How the bundled playwright-cli 0.1.20 decides to attach vs launch,
tags: [playwright-cli, cuttle-pw, drivers, docker]
status: stable
stale_after: "2027-03-18T00:00:00+00:00"
generated: { by: claude-code/claude-opus-5, at: "2026-09-18T21:02:55+00:00" }
generated: { by: claude-code/claude-opus-5, at: "2026-09-18T21:27:40+00:00" }
sources:
- id: src
resource: https://github.com/microsoft/playwright-cli
title: microsoft/playwright-cli v0.1.20 (logic lives in its pinned playwright-core dependency)
- id: core
resource: "playwright-core 1.64.0-alpha-2026-09-14 as installed by @playwright/cli 0.1.20 in the image: lib/tools/cli-client/program.js (startSession, case open) and help.json"
resource: "playwright-core 1.64.0-alpha-2026-09-14 as installed by @playwright/cli 0.1.20 in the image: lib/tools/cli-client/program.js (startSession, case open), session.js (Session.run), output.js and help.json"
title: playwright-core cli-client source at the pinned version
- id: live
resource: "live validation against a local cuttle image build, 2026-09-18: smoke harness plus manual kill/restart experiments"
Expand Down Expand Up @@ -53,12 +53,18 @@ safe; re-verify on every pin bump.
command: help`). Global help is `playwright-cli --help`, which `cuttle pw`
intercepts for its own wrapper help; per-verb help, `<verb> --help`, passes
through.[^core]
- A verb with no live session exits 1 printing
`The browser '<session>' is not open, please run open first`; the wrapper
matches `is not open, please run` to trigger its single auto-attach
retry. Attached sessions have no idle timeout; `detach` refuses sessions
not created by attach; `close` on an attached browser disconnects only -
cuttle's browser, tabs and logins survive both.[^src][^live]
- A verb with no live session exits 1 in one of two wordings. With no
session file it prints `The browser '<session>' is not open, please run
open first` (output.js); a clean container stop leaves it this way. When a
session file outlives its daemon - `docker kill`, an unclean restart, the
daemon process killed - the socket connect fails and it throws an uncaught
`Browser '<session>' is not open. Run` (session.js), stack trace and all, on
every verb until something re-attaches. The wrapper matches both
(`is not open, please run`, `is not open. Run`) to trigger its single
auto-attach retry.[^core][^live] Attached sessions have no idle timeout;
`detach` refuses sessions not created by attach; `close` on an attached
browser disconnects only - cuttle's browser, tabs and logins survive
both.[^src][^live]
- Element refs served through cuttle's CDP mux come back frame-prefixed
(`f1e2`), not bare (`e2`) as against a directly-launched browser -
anything parsing snapshots must accept both.[^live]
Expand Down
39 changes: 23 additions & 16 deletions packages/cuttle/internal/cli/playwright.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"io"
"os/exec"
"slices"
"strings"
"syscall"

Expand Down Expand Up @@ -40,27 +41,33 @@ const (
// daemon's downloads dir; all three are unexported in packages this one must
// not import (internal/fingerprint importing back would cycle its pin test).
playwrightWorkdir = "/data/__default__/Downloads"
// playwrightNotOpenMarker is what the driver prints when a verb runs with no
// live session ("The browser 'cuttle' is not open, please run open first").
// Matching on its wording is safe only because the driver version is pinned in
// lockstep with the image (versions.env, the Dockerfile ARG and the pin test),
// so it cannot drift underneath us without someone seeing it.
//
// It is also the ONLY wording a browser that dies mid-session produces: the
// session daemon holds the CDP connection and exits with it, so there is no
// "daemon alive, browser gone" state to match separately, and re-attaching is
// the whole recovery. Re-attach cannot reach a foreign browser here - the
// endpoint is cuttle's own, and with it unset the driver fails loudly rather
// than launching one ("Chromium distribution 'chrome' is not found at
// /opt/google/chrome/chrome"; the image downloads no playwright browser).
// The smoke harness's driver-attachment-drift check is what holds that.
playwrightNotOpenMarker = "is not open, please run"
// verbAttach is the driver verb that starts a session daemon; `open` starts one
// too, and in this image it can only attach as well.
verbAttach = "attach"
verbOpen = "open"
)

// playwrightNotOpenMarkers are the two ways the driver says a verb found no live
// session, and re-attaching is the whole recovery for both:
// - "The browser 'cuttle' is not open, please run open first" (output.js) when
// there is no session file at all, as after a clean container stop.
// - "Browser 'cuttle' is not open. Run" (session.js, thrown as a Node stack trace)
// when a session file survived but its daemon did not: `docker kill`, an
// unclean restart, or the driver process dying on its own.
//
// Matching on wording is safe only because the driver version is pinned in
// lockstep with the image (versions.env, the Dockerfile ARG and the pin test), so
// it cannot drift underneath us without someone seeing it.
//
// A browser that dies mid-session needs no third marker: the session daemon holds
// the CDP connection and exits with it, so the next verb reports the first one.
// Re-attach cannot reach a foreign browser here - the endpoint is cuttle's own,
// and with it unset the driver fails loudly rather than launching one ("Chromium
// distribution 'chrome' is not found at /opt/google/chrome/chrome"; the image
// downloads no playwright browser). The smoke harness's driver-attachment-drift
// check is what holds that.
var playwrightNotOpenMarkers = []string{"is not open, please run", "is not open. Run"}

var (
errPlaywrightRedirect = errors.New("--endpoint/--extension would point the driver at another browser - drop it, `cuttle pw` already targets cuttle's")
errNoExec = errors.New("`cuttle pw` needs a container to exec into, which the direct backend has none of - run playwright-cli yourself against that browser's CDP endpoint")
Expand Down Expand Up @@ -347,7 +354,7 @@ func playwrightNeedsAttach(args []string, combined string) bool {
if len(args) == 0 || args[0] == verbAttach || args[0] == verbOpen {
return false
}
return strings.Contains(combined, playwrightNotOpenMarker)
return slices.ContainsFunc(playwrightNotOpenMarkers, func(m string) bool { return strings.Contains(combined, m) })
}

func replay(cmd *cobra.Command, stdout, stderr []byte) {
Expand Down
50 changes: 50 additions & 0 deletions packages/cuttle/internal/cli/playwright_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"bytes"
"context"
"errors"
"os"
"path/filepath"
"slices"
"strings"
"testing"
Expand Down Expand Up @@ -76,6 +78,7 @@ func TestPlaywrightNeedsAttach(t *testing.T) {
t.Parallel()
const notOpen = "Error: The browser 'cuttle' is not open, please run open first"
const browserDied = "The browser 'cuttle' is not open, please run open first\n\n playwright-cli -s=cuttle open [params]\n"
const staleSession = "Error: Browser 'cuttle' is not open. Run\n\n playwright-cli -s=cuttle open\n\nto start the browser session.\n at Session.run (session.js:60:13)"
tests := []struct {
name string
args []string
Expand All @@ -88,10 +91,14 @@ func TestPlaywrightNeedsAttach(t *testing.T) {
// exit 1, no distinct "browser closed" wording to match. Re-attach is the
// right answer because cuttle has a replacement browser up by then.
{name: "a browser killed mid-session reports the same marker", args: []string{"snapshot"}, combined: browserDied, want: true},
// A session file that outlived its daemon (`docker kill`, the driver process
// killed) gets the other wording, as an uncaught Node error on stderr.
{name: "a stale session file after the daemon died", args: []string{"snapshot"}, combined: staleSession, want: true},
{name: "the marker on stdout counts", args: []string{"goto", "https://example.com"}, combined: notOpen, want: true},
{name: "any other failure is real", args: []string{"click", "e17"}, combined: "Error: no element e17", want: false},
{name: "attach failing is real", args: []string{"attach"}, combined: notOpen, want: false},
{name: "open failing is real", args: []string{"open", "https://example.com"}, combined: notOpen, want: false},
{name: "attach failing on a stale session is real", args: []string{"attach"}, combined: staleSession, want: false},
{name: "no args", args: nil, combined: notOpen, want: false},
}
for _, tt := range tests {
Expand Down Expand Up @@ -201,6 +208,49 @@ func TestWriteDriverHelpWithoutTheDriver(t *testing.T) {
}
}

// sessionlessDriver stands in for a driver with no live session: every verb
// fails with the given wording until `attach` has run once.
type sessionlessDriver struct{ dir string }

func (d sessionlessDriver) ExecCommand(_ string, argv []string) (string, []string) {
const script = `cd "$0" || exit 2
echo "$*" >> calls
if [ "$2" = attach ]; then touch attached; exit 0; fi
if [ -e attached ]; then echo "ran $2"; exit 0; fi
cat marker >&2; exit 1`
return "sh", append([]string{"-c", script, d.dir}, argv...)
}

// The jev-browse runner re-attaches on both "not open" wordings and retries the
// verb once, so a stale session left by a restart never reaches the loop.
func TestPlaywrightRunnerReattaches(t *testing.T) {
t.Parallel()
for name, marker := range map[string]string{
"no session file": "The browser 'cuttle' is not open, please run open first\n",
"stale session": "Error: Browser 'cuttle' is not open. Run\n\n playwright-cli -s=cuttle open\n",
} {
t.Run(name, func(t *testing.T) {
t.Parallel()
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "marker"), []byte(marker), 0o600); err != nil {
t.Fatal(err)
}
out, err := newPlaywrightRunner(sessionlessDriver{dir})(context.Background(), "snapshot")
if err != nil || out != "ran snapshot\n" {
t.Fatalf("runner = %q, %v; want the retried verb's output", out, err)
}
calls, err := os.ReadFile(filepath.Join(dir, "calls"))
if err != nil {
t.Fatal(err)
}
want := "playwright-cli snapshot\nplaywright-cli attach --cdp=http://127.0.0.1:9222\nplaywright-cli snapshot\n"
if string(calls) != want {
t.Fatalf("driver calls:\n%s\nwant:\n%s", calls, want)
}
})
}
}

// With no instance to exec into, the wrapper help still prints and says why the
// driver's own help is missing, instead of failing the --help.
func TestPlaywrightHelpWithoutAnInstance(t *testing.T) {
Expand Down
Loading