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
4 changes: 3 additions & 1 deletion packages/cuttle/internal/cli/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,9 @@ opens or closes a tab.
`snapshot` and `click` print a `Modal state` block, but a `goto` into one can
return empty with exit 0. Clear it with `cuttle pw dialog-accept` or
`dialog-dismiss`. **`beforeunload` is inverted: ACCEPT leaves the page, DISMISS
stays.** If you asked for the navigation, accept. Never stub `window.alert` or
stays.** If you asked for the navigation, accept. A dialog still open when the
driver session ends (`detach`, `close`, a crashed driver) is dismissed for you,
so a `confirm` left open answers "cancel". Never stub `window.alert` or
`confirm` from page script: it is detectable and misses `beforeunload`. The same
symptom with no dialog is usually a backgrounded tab - select yours.

Expand Down
32 changes: 26 additions & 6 deletions packages/cuttle/internal/cli/lease.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,23 +218,43 @@ var playwrightReadVerbs = map[string]bool{
"sessionstorage-list": true, "sessionstorage-get": true,
"requests": true, "request": true, "request-headers": true, "request-body": true,
"response-headers": true, "response-body": true,
"help": true, "docs": true,
}

// playwrightReadOnly reports whether a pw invocation only reads. The verb is the
// first non-flag argument; a help flag anywhere makes it a help request.
// first non-flag argument. A help flag makes the whole invocation a help request
// wherever the driver's parser (minimist) reads it as one - anywhere before a
// `--` - but after it, it is a value to type or fill.
func playwrightReadOnly(args []string) bool {
if slices.ContainsFunc(args, isHelpFlag) {
flags := args
if end := slices.Index(args, "--"); end >= 0 {
flags = args[:end]
}
if slices.ContainsFunc(flags, isHelpFlag) {
return true
}
for _, a := range args {
if !strings.HasPrefix(a, "-") {
for _, a := range flags {
switch {
case !strings.HasPrefix(a, "-"):
return playwrightReadVerbs[a]
case strings.Contains(a, "=") || playwrightBoolFlags[a]:
// Takes no next arg, so the verb is still ahead.
default:
// A flag that takes a value swallows the next arg, so `-s snapshot click`
// runs click: the word after it is not the verb.
return false
}
}
return true // flags only, such as --version
// Flags only, such as --version. A verb seen only after a `--` is refused
// rather than guessed at.
return len(flags) == len(args)
}

// playwrightBoolFlags are the boolean flags an invocation puts in front of its
// verb, spelled exactly: minimist reads `-json` as `-j -s -o -n`, and the last
// of those takes the next arg. Any other bare flag there is taken to swallow the
// next arg, which only ever errs toward refusing.
var playwrightBoolFlags = map[string]bool{"--json": true, "--raw": true, "--version": true, "--all": true, "-g": true, "--global": true}

// gatePlaywright refuses a verb that drives the page while another client holds
// the lease. It only ever decides whether the command runs, never changes it.
// self is the cuttle invocation that reaches this instance ([cuttleCmd]), so the
Expand Down
11 changes: 11 additions & 0 deletions packages/cuttle/internal/cli/lease_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,17 @@ func TestPlaywrightReadOnly(t *testing.T) {
{[]string{"eval", "document.title"}, false},
{[]string{"attach"}, false},
{[]string{"some-future-verb"}, false},
{[]string{"--help", "fill"}, true},
{[]string{"fill", "e5", "-h", "--", "x"}, true},
{[]string{"fill", "e5", "--", "--help"}, false},
{[]string{"type", "--", "-h"}, false},
{[]string{"help"}, false},
{[]string{"docs"}, false},
{[]string{"-s", "snapshot", "click", "e5"}, false},
{[]string{"--filename", "snapshot", "click", "e5"}, false},
{[]string{"--json", "snapshot"}, true},
{[]string{"-json", "snapshot", "click", "e5"}, false},
{[]string{"--", "snapshot"}, false},
}
for _, tt := range tests {
if got := playwrightReadOnly(tt.args); got != tt.want {
Expand Down
15 changes: 14 additions & 1 deletion packages/cuttle/internal/cli/playwright.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,8 +344,21 @@ const helpFlag = "--help"

func isHelpFlag(a string) bool { return a == "-h" || a == helpFlag }

// playwrightAttachArgv is the auto-attach. Every invocation that finds the
// session gone attaches, and an attach replaces the session, so concurrent ones -
// parallel agents right after a crash - kill each other's daemons mid-start
// (ENOENT or EADDRINUSE on its socket, "Session closed") and all but one fail. So
// the attach runs under a container-wide lock and is skipped when an invocation
// ahead of it already brought the session back; `list` shows only sessions whose
// daemon answers. The wait for the lock is bounded: an attach to a tab that never
// answers runs to the driver's own 30s timeout, and a queue of those must not
// hold every invocation behind it for minutes.
func playwrightAttachArgv() []string {
return []string{driverPlaywright, verbAttach, "--cdp=" + playwrightCDPEndpoint}
attach := driverPlaywright + " " + verbAttach + " --cdp=" + playwrightCDPEndpoint
script := driverPlaywright + ` list | grep -qxF -- "- $PLAYWRIGHT_CLI_SESSION:" || exec ` + attach
locked := `flock -w 60 -E 75 /tmp/cuttle-pw-attach.lock sh -c "$0"; rc=$?; ` +
`[ "$rc" -ne 75 ] || echo "cuttle: gave up after 60s waiting for another invocation's attach" >&2; exit "$rc"`
return []string{"sh", "-c", locked, script}
}

func execPlaywright(ctx context.Context, stdin io.Reader, ex backend.Execer, argv []string, stdout, stderr io.Writer) error {
Expand Down
8 changes: 6 additions & 2 deletions packages/cuttle/internal/cli/playwright_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ 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
case "$*" in *" attach --cdp="*) touch attached; exit 0 ;; esac
if [ -e attached ]; then echo "ran $2"; exit 0; fi
cat marker >&2; exit 1`
return "sh", append([]string{"-c", script, d.dir}, argv...)
Expand Down Expand Up @@ -259,7 +259,11 @@ func TestPlaywrightRunnerReattaches(t *testing.T) {
if err != nil {
t.Fatal(err)
}
want := "playwright-cli snapshot\nplaywright-cli attach --cdp=http://127.0.0.1:9222\nplaywright-cli snapshot\n"
attach := strings.Join(playwrightAttachArgv(), " ")
if !strings.Contains(attach, "playwright-cli attach --cdp=http://127.0.0.1:9222") {
t.Fatalf("auto-attach %q does not attach to the container's CDP endpoint", attach)
}
want := "playwright-cli snapshot\n" + attach + "\nplaywright-cli snapshot\n"
if string(calls) != want {
t.Fatalf("driver calls:\n%s\nwant:\n%s", calls, want)
}
Expand Down
35 changes: 33 additions & 2 deletions packages/cuttle/internal/serve/cdpharness_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package serve
import (
"context"
"encoding/json"
"math"
"net/http"
"net/http/httptest"
"strings"
Expand Down Expand Up @@ -34,6 +35,15 @@ func (f *cdpRecorder) received() []map[string]any {
// startCDPRecorder serves a websocket that records each command and acks it. result
// supplies the ack's "result" object for a given command; nil means an empty one.
func startCDPRecorder(t *testing.T, result func(cmd map[string]any) map[string]any) (*cdpRecorder, string) {
t.Helper()
return startCDPBrowser(t, result, nil)
}

// startCDPBrowser is startCDPRecorder whose ack carries the command's sessionId,
// with the events announce returns for a command sent around that ack, the way
// Chrome orders them: before it, then after it. Like Chrome, it refuses an id
// past 2^31 without echoing it.
func startCDPBrowser(t *testing.T, result func(cmd map[string]any) map[string]any, announce func(cmd map[string]any) (before, after []map[string]any)) (*cdpRecorder, string) {
t.Helper()
f := &cdpRecorder{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand All @@ -42,6 +52,10 @@ func startCDPRecorder(t *testing.T, result func(cmd map[string]any) map[string]a
return
}
defer conn.Close(websocket.StatusNormalClosure, "")
send := func(v map[string]any) {
b, _ := json.Marshal(v)
_ = conn.Write(context.Background(), websocket.MessageText, b)
}
for {
_, data, rerr := conn.Read(context.Background())
if rerr != nil {
Expand All @@ -51,15 +65,32 @@ func startCDPRecorder(t *testing.T, result func(cmd map[string]any) map[string]a
if json.Unmarshal(data, &m) != nil {
continue
}
if id, _ := m["id"].(float64); id > math.MaxInt32 {
send(map[string]any{"error": map[string]any{"message": "Message must have integer 'id' property"}})
continue
}
f.mu.Lock()
f.got = append(f.got, m)
f.mu.Unlock()
res := map[string]any{}
if result != nil {
res = result(m)
}
ack, _ := json.Marshal(map[string]any{"id": m["id"], "result": res})
_ = conn.Write(context.Background(), websocket.MessageText, ack)
var before, after []map[string]any
if announce != nil {
before, after = announce(m)
}
for _, ev := range before {
send(ev)
}
ack := map[string]any{"id": m["id"], "result": res}
if sid, ok := m["sessionId"]; ok {
ack["sessionId"] = sid
}
send(ack)
for _, ev := range after {
send(ev)
}
}
}))
t.Cleanup(srv.Close)
Expand Down
12 changes: 11 additions & 1 deletion packages/cuttle/internal/serve/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,13 @@ func (m *multiplexer) routes() *http.ServeMux {
for _, p := range []string{"GET /json/version", "GET /json/version/"} {
mux.HandleFunc(p, m.handleJSONVersion)
}
for _, p := range []string{"GET /json/list", "GET /json/list/", "GET /json", "GET /json/"} {
for _, p := range []string{"GET /json/list", "GET /json/list/", "GET /json", "GET /json/{$}"} {
mux.HandleFunc(p, m.handleJSONList)
}
// Chrome's other /json endpoints (close, activate, new, protocol) are not
// proxied. Without this they fell through to the list, so a /json/close/<id>
// answered 200 with the tab list and closed nothing.
mux.HandleFunc("/json/", handleJSONUnsupported)
mux.HandleFunc("GET /profile/{seed}/state", m.handleGetState)
mux.HandleFunc("PUT /profile/{seed}/state", m.handlePutState)
mux.HandleFunc("GET /auth", m.handleAuthStatus)
Expand Down Expand Up @@ -347,6 +351,12 @@ func (m *multiplexer) handleJSONList(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, data)
}

func handleJSONUnsupported(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusNotFound, map[string]any{
keyError: r.Method + " " + r.URL.Path + " is not served by cuttle, which proxies only GET /json/version and GET /json/list - use the CDP Target domain (Target.closeTarget, Target.activateTarget, Target.createTarget) instead",
})
}

func writeLaunchError(w http.ResponseWriter, err error) {
if le, ok := errors.AsType[*launchError](err); ok {
writeJSON(w, le.status, map[string]any{keyError: le.msg})
Expand Down
41 changes: 41 additions & 0 deletions packages/cuttle/internal/serve/http_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package serve

import (
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
)

Expand Down Expand Up @@ -102,3 +106,40 @@ func TestOriginIsAllowed(t *testing.T) {
})
}
}

// Chrome's /json endpoints that act on a tab are not proxied, and must say so.
func TestUnproxiedJSONEndpointsAre404(t *testing.T) {
t.Parallel()
cdp := newFakeCDP(t)
pool := newTestPool(t, serveConfig{}, (&fakeLauncher{port: cdp.port}).toLauncher())
front := httptest.NewServer((&multiplexer{pool: pool, port: 9222}).routes())
t.Cleanup(front.Close)
for _, tc := range []struct {
method, path string
want int
}{
{http.MethodGet, "/json/close/PAGE9", http.StatusNotFound},
{http.MethodGet, "/json/activate/PAGE9", http.StatusNotFound},
{http.MethodPut, "/json/new", http.StatusNotFound},
{http.MethodGet, "/json/", http.StatusOK},
{http.MethodGet, "/json", http.StatusOK},
} {
// Pool mode, so the list needs a seed; the 404s must not care.
req, err := http.NewRequestWithContext(t.Context(), tc.method, front.URL+tc.path+"?fingerprint=seedX", nil)
if err != nil {
t.Fatal(err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
if resp.StatusCode != tc.want {
t.Errorf("%s %s = %d %s, want %d", tc.method, tc.path, resp.StatusCode, body, tc.want)
}
if tc.want == http.StatusNotFound && !strings.Contains(string(body), "Target.closeTarget") {
t.Errorf("%s %s: 404 does not name the CDP alternative: %s", tc.method, tc.path, body)
}
}
}
11 changes: 9 additions & 2 deletions packages/cuttle/internal/serve/humanize.go
Original file line number Diff line number Diff line change
Expand Up @@ -1077,6 +1077,13 @@ func probeRectsMatch(a, b map[string]any) bool {
// Bounded by the caller's timeout and the connection ctx; a miss returns
// ok=false so the caller falls back.
func (h *humanizer) callWithin(sid, method string, params map[string]any, timeout time.Duration) ([]byte, bool) {
return h.callOn(h.ctx, h.cdpSend, sid, method, params, timeout)
}

// callOn is callWithin over the caller's own connection context and send, for a
// command that must still go out after the humanizer's own are cut off with the
// client (see openDialogs.dismiss). The response is matched and swallowed the same way.
func (h *humanizer) callOn(ctx context.Context, send func(websocket.MessageType, []byte) error, sid, method string, params map[string]any, timeout time.Duration) ([]byte, bool) {
id := h.allocID()
ch := make(chan []byte, 1)
h.mu.Lock()
Expand All @@ -1092,13 +1099,13 @@ func (h *humanizer) callWithin(sid, method string, params map[string]any, timeou
h.mu.Unlock()
}()

if err := h.cdpSend(websocket.MessageText, dispatchCmd(id, method, sid, params)); err != nil {
if err := send(websocket.MessageText, dispatchCmd(id, method, sid, params)); err != nil {
h.releaseID(id) // the command never left; no response will ever reconcile it
return nil, false
}

select {
case <-h.ctx.Done():
case <-ctx.Done():
return nil, false
case <-time.After(timeout):
return nil, false
Expand Down
Loading
Loading