Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: harden bridge lifecycle and background browser actions

Cody Arnoldd97f4a95bdcc
diff --git a/cmd/pinchtab/cmd_bridge_test.go b/cmd/pinchtab/cmd_bridge_test.go
index 93fcb17d..e9b220aa 100644
--- a/cmd/pinchtab/cmd_bridge_test.go
+++ b/cmd/pinchtab/cmd_bridge_test.go
@@ -68,3 +68,14 @@ func TestResolveBridgeBrowser(t *testing.T) {
})
}
}
+
+func TestBridgeAttachChildFlagContract(t *testing.T) {
+ for _, name := range []string{"cdp-attach", "browser", "remote-browser-name"} {
+ if bridgeCmd.Flags().Lookup(name) == nil {
+ t.Errorf("bridge command missing child flag %q", name)
+ }
+ }
+ if bridgeCmd.Flags().Lookup("browser-provider") != nil {
+ t.Error("bridge command must not register obsolete browser-provider flag")
+ }
+}
diff --git a/cmd/pinchtab/cmd_bridges.go b/cmd/pinchtab/cmd_bridges.go
new file mode 100644
index 00000000..81a36c02
--- /dev/null
+++ b/cmd/pinchtab/cmd_bridges.go
@@ -0,0 +1,71 @@
+package main
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+ "net"
+ "strings"
+
+ "github.com/pinchtab/pinchtab/internal/bridgeregistry"
+ "github.com/spf13/cobra"
+)
+
+var bridgesCmd = &cobra.Command{
+ Use: "bridges",
+ Short: "Inspect standalone bridge processes",
+ GroupID: "management",
+}
+
+var bridgesListCmd = &cobra.Command{
+ Use: "list",
+ Short: "List registered standalone bridges and current liveness",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ SilenceErrors: true,
+ RunE: func(cmd *cobra.Command, _ []string) error {
+ prune, _ := cmd.Flags().GetBool("prune")
+ states, err := bridgeregistry.List(stateDirForConfig(loadConfig()), prune)
+ if err != nil {
+ return fmt.Errorf("pinchtab bridges list: %w", err)
+ }
+ jsonOutput, _ := cmd.Flags().GetBool("json")
+ return writeBridges(cmd.OutOrStdout(), states, jsonOutput)
+ },
+}
+
+func writeBridges(w io.Writer, states []bridgeregistry.State, jsonOutput bool) error {
+ if jsonOutput {
+ enc := json.NewEncoder(w)
+ enc.SetIndent("", " ")
+ return enc.Encode(states)
+ }
+ if len(states) == 0 {
+ _, err := fmt.Fprintln(w, "No registered standalone bridges.")
+ return err
+ }
+ for _, state := range states {
+ host := strings.Trim(strings.TrimSpace(state.Address), "[]")
+ _, err := fmt.Fprintf(w, "%s pid=%d pidStatus=%s reachable=%t bridge=http://%s browser=%q label=%q cdp=%q",
+ state.Status, state.PID, state.PIDStatus, state.Reachable, net.JoinHostPort(host, state.Port), state.BrowserType, state.BrowserLabel, state.CDPIdentity)
+ if err != nil {
+ return err
+ }
+ if state.Pruned {
+ if _, err := io.WriteString(w, " pruned=true"); err != nil {
+ return err
+ }
+ }
+ if _, err := io.WriteString(w, "\n"); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func init() {
+ addJSONFlag(bridgesListCmd)
+ bridgesListCmd.Flags().Bool("prune", false, "Remove records whose original PID is conclusively stale (never signals processes)")
+ bridgesCmd.AddCommand(bridgesListCmd)
+ rootCmd.AddCommand(bridgesCmd)
+}
diff --git a/cmd/pinchtab/cmd_bridges_test.go b/cmd/pinchtab/cmd_bridges_test.go
new file mode 100644
index 00000000..9c690287
--- /dev/null
+++ b/cmd/pinchtab/cmd_bridges_test.go
@@ -0,0 +1,82 @@
+package main
+
+import (
+ "bytes"
+ "encoding/json"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridgeregistry"
+)
+
+func TestWriteBridgesTextIncludesDiagnosticIdentity(t *testing.T) {
+ state := bridgeregistry.State{
+ Record: bridgeregistry.Record{
+ PID: 4242,
+ Address: "127.0.0.1",
+ Port: "9878",
+ CDPIdentity: bridgeregistry.SafeCDPIdentity("ws://user:[email protected]:9222/devtools/browser/browser-guid?token=secret"),
+ BrowserType: "chrome",
+ BrowserLabel: "work-profile",
+ RegisteredAt: time.Unix(1, 0).UTC(),
+ },
+ Status: "live",
+ PIDStatus: "alive",
+ Reachable: true,
+ Live: true,
+ }
+ var out bytes.Buffer
+ if err := writeBridges(&out, []bridgeregistry.State{state}, false); err != nil {
+ t.Fatal(err)
+ }
+ got := out.String()
+ for _, want := range []string{"live", "pid=4242", "pidStatus=alive", "reachable=true", "bridge=http://127.0.0.1:9878", `browser="chrome"`, `label="work-profile"`, `cdp="ws://127.0.0.1:9222/devtools/browser/`} {
+ if !strings.Contains(got, want) {
+ t.Fatalf("output %q missing %q", got, want)
+ }
+ }
+ for _, secret := range []string{"password", "browser-guid", "token=secret"} {
+ if strings.Contains(got, secret) {
+ t.Fatalf("output %q leaked %q", got, secret)
+ }
+ }
+}
+
+func TestWriteBridgesJSONAndEmptyText(t *testing.T) {
+ states := []bridgeregistry.State{{
+ Record: bridgeregistry.Record{PID: 9, Address: "::1", Port: "9871", BrowserType: "cloak"},
+ Status: "stale_pid",
+ PIDStatus: "dead",
+ Stale: true,
+ Pruned: true,
+ }}
+ var out bytes.Buffer
+ if err := writeBridges(&out, states, true); err != nil {
+ t.Fatal(err)
+ }
+ var decoded []bridgeregistry.State
+ if err := json.Unmarshal(out.Bytes(), &decoded); err != nil {
+ t.Fatalf("invalid JSON %q: %v", out.String(), err)
+ }
+ if len(decoded) != 1 || decoded[0].PID != 9 || !decoded[0].Pruned || decoded[0].Status != "stale_pid" {
+ t.Fatalf("decoded output = %+v", decoded)
+ }
+
+ out.Reset()
+ if err := writeBridges(&out, nil, false); err != nil {
+ t.Fatal(err)
+ }
+ if got := out.String(); got != "No registered standalone bridges.\n" {
+ t.Fatalf("empty output = %q", got)
+ }
+}
+
+func TestBridgesCommandContract(t *testing.T) {
+ if bridgesCmd.GroupID != "management" {
+ t.Fatalf("bridges group = %q", bridgesCmd.GroupID)
+ }
+ if bridgesListCmd.Flags().Lookup("json") == nil || bridgesListCmd.Flags().Lookup("prune") == nil {
+ t.Fatal("bridges list must expose --json and --prune")
+ }
+}
diff --git a/cmd/pinchtab/cmd_cli_browser_actions.go b/cmd/pinchtab/cmd_cli_browser_actions.go
index 40147ce1..e5d6a22f 100644
--- a/cmd/pinchtab/cmd_cli_browser_actions.go
+++ b/cmd/pinchtab/cmd_cli_browser_actions.go
@@ -64,7 +64,7 @@ var dblclickCmd = newOptionalRefActionCmd("dblclick <ref>", "Double-click elemen
var typeCmd = newSimpleActionCmd("type <ref> <text>", "Type into element", "type", cobra.MinimumNArgs(2))
-var pressCmd = newSimpleActionCmd("press [ref] <key>", "Press key (Enter, Tab, Escape...), optionally focusing a ref first", "press", cobra.MinimumNArgs(1))
+var pressCmd = newSimpleActionCmd("press [ref] <key|chord>", "Press a key or chord (Enter, Ctrl+A, Shift+ArrowLeft), optionally focusing a ref first", "press", cobra.MinimumNArgs(1))
var fillCmd = newSimpleActionCmd("fill <ref|selector> <text>", "Fill input directly", "fill", cobra.MinimumNArgs(2))
diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.go
index ecb1ffbf..1f6f34bf 100644
--- a/cmd/pinchtab/cmd_cli_register.go
+++ b/cmd/pinchtab/cmd_cli_register.go
@@ -68,10 +68,12 @@ func configureBrowserFlags() {
addPointerActionFlags(clickCmd, "click")
clickCmd.Flags().Bool("wait-nav", false, "Wait for navigation after click")
clickCmd.Flags().Bool("dismiss-banners", false, "Dismiss cookie/consent banners after a wait-nav click (no-op without --wait-nav)")
+ clickCmd.Flags().Bool("dismiss-known-interstitials", false, "Dismiss a recognized portal interstitial before resolving the click target")
addPostActionFlags(clickCmd, "action", true)
clickCmd.Flags().String("dialog-action", "", "Auto-handle a JS dialog opened by the click: accept | dismiss")
clickCmd.Flags().String("dialog-text", "", "Prompt response text (with --dialog-action accept on prompt())")
clickCmd.Flags().String("mode", "", "Click delivery mode override: dom | dispatch")
+ clickCmd.Flags().Bool("submit", false, "Dispatch one DOM click and report bounded post-submit state")
addPointerActionFlags(dblclickCmd, "dblclick")
@@ -201,6 +203,7 @@ func configureBrowserFlags() {
addPostActionFlags(reloadCmd, "reload", true)
reloadCmd.Flags().Bool("dismiss-banners", false, "After reload, dismiss cookie/consent banners")
addPostActionFlags(fillCmd, "fill", true)
+ fillCmd.Flags().Bool("submit", false, "Press Enter after filling the field")
addPostActionFlags(selectCmd, "select", true)
addPostActionFlags(scrollCmd, "scroll", false)
@@ -212,6 +215,7 @@ func configureBrowserFlags() {
snapCmd,
frameCmd,
screenshotCmd,
+ captureCmd,
annotateCmd,
pdfCmd,
findCmd,
diff --git a/cmd/pinchtab/cmd_cli_register_test.go b/cmd/pinchtab/cmd_cli_register_test.go
index cdf29a49..40306f26 100644
--- a/cmd/pinchtab/cmd_cli_register_test.go
+++ b/cmd/pinchtab/cmd_cli_register_test.go
@@ -55,7 +55,7 @@ func TestBrowserCommandRegistration(t *testing.T) {
}
}
- for _, name := range []string{"css", "x", "y", "humanize", "wait-nav", "mode"} {
+ for _, name := range []string{"css", "x", "y", "humanize", "wait-nav", "mode", "submit", "dismiss-known-interstitials"} {
if clickCmd.Flags().Lookup(name) == nil {
t.Errorf("clickCmd missing flag %q", name)
}
@@ -71,6 +71,12 @@ func TestBrowserCommandRegistration(t *testing.T) {
}
}
+func TestCaptureCommandRegistersTabFlag(t *testing.T) {
+ if captureCmd.Flags().Lookup("tab") == nil {
+ t.Fatal("captureCmd missing --tab flag")
+ }
+}
+
// TestPostActionFlagsBundle pins the exact usage strings the shared
// addPostActionFlags helper interpolates per verb, so a future verb edit cannot
// silently drift the --help text, and verifies the no-text commands omit --text.
@@ -89,6 +95,7 @@ func TestPostActionFlagsBundle(t *testing.T) {
wantUsage(clickCmd, "snap", "Output interactive snapshot after action")
wantUsage(clickCmd, "snap-diff", "Output snapshot diff after action (changes only)")
wantUsage(clickCmd, "text", "Output page text after action (for verification)")
+ wantUsage(clickCmd, "submit", "Dispatch one DOM click and report bounded post-submit state")
wantUsage(reloadCmd, "snap", "Output interactive snapshot after reload")
wantUsage(reloadCmd, "snap-diff", "Output snapshot diff after reload (changes only)")
diff --git a/cmd/pinchtab/cmd_server_background.go b/cmd/pinchtab/cmd_server_background.go
index a9e1f060..cea7fa7e 100644
--- a/cmd/pinchtab/cmd_server_background.go
+++ b/cmd/pinchtab/cmd_server_background.go
@@ -16,6 +16,7 @@ import (
"github.com/pinchtab/pinchtab/internal/cli"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/daemon"
"github.com/pinchtab/pinchtab/internal/server"
"github.com/spf13/cobra"
)
@@ -42,6 +43,7 @@ type serverBackgroundOptions struct {
}
var readProcessCommand = defaultReadProcessCommand
+var daemonInstallationStatus = daemon.InstallationStatus
var serverStopCmd = &cobra.Command{
Use: "stop",
@@ -58,23 +60,31 @@ var serverRestartCmd = &cobra.Command{
Use: "restart",
Short: "Restart the running server (stop + start in background)",
Run: func(cmd *cobra.Command, args []string) {
- cfg := loadConfig()
-
- if server.CheckPinchTabRunning(cfg.Port, cfg.Token) {
- fmt.Println("Stopping server...")
- if err := runServerStop(); err != nil {
- fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.WarningStyle, fmt.Sprintf("stop: %v", err)))
- }
- }
-
- fmt.Println("Starting server...")
- if err := runServerBackground(cfg, serverBackgroundOptions{}); err != nil {
+ if err := runServerRestart(loadConfig()); err != nil {
fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, err.Error()))
os.Exit(1)
}
},
}
+func runServerRestart(cfg *config.RuntimeConfig) error {
+ installed, err := daemonInstallationStatus()
+ if err != nil {
+ return fmt.Errorf("cannot determine background-service ownership; refusing restart: %w", err)
+ }
+ if installed {
+ return fmt.Errorf("background service is installed; use `pinchtab daemon restart` so one service manager owns the server")
+ }
+ if server.CheckPinchTabRunning(cfg.Port, cfg.Token) {
+ fmt.Println("Stopping server...")
+ if err := runServerStop(); err != nil {
+ fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.WarningStyle, fmt.Sprintf("stop: %v", err)))
+ }
+ }
+ fmt.Println("Starting server...")
+ return runServerBackground(cfg, serverBackgroundOptions{})
+}
+
func stateDirForConfig(cfg *config.RuntimeConfig) string {
if cfg != nil && strings.TrimSpace(cfg.StateDir) != "" {
return strings.TrimSpace(cfg.StateDir)
diff --git a/cmd/pinchtab/cmd_server_background_test.go b/cmd/pinchtab/cmd_server_background_test.go
index 52b099f9..40ca41f8 100644
--- a/cmd/pinchtab/cmd_server_background_test.go
+++ b/cmd/pinchtab/cmd_server_background_test.go
@@ -1,6 +1,7 @@
package main
import (
+ "errors"
"net/http"
"net/http/httptest"
"os"
@@ -8,9 +9,29 @@ import (
"strings"
"testing"
+ "github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/server"
)
+func TestServerRestartRefusesInstalledOrUnknownServiceOwnership(t *testing.T) {
+ original := daemonInstallationStatus
+ defer func() { daemonInstallationStatus = original }()
+
+ daemonInstallationStatus = func() (bool, error) { return true, nil }
+ err := runServerRestart(&config.RuntimeConfig{})
+ if err == nil || !strings.Contains(err.Error(), "pinchtab daemon restart") {
+ t.Fatalf("installed-service error = %v", err)
+ }
+
+ daemonInstallationStatus = func() (bool, error) {
+ return false, errors.New("service path unreadable")
+ }
+ err = runServerRestart(&config.RuntimeConfig{})
+ if err == nil || !strings.Contains(err.Error(), "refusing restart") {
+ t.Fatalf("unknown-ownership error = %v", err)
+ }
+}
+
func TestIsBackgroundServerReadyRequiresValidPinchTabHealth(t *testing.T) {
tests := []struct {
name string
diff --git a/internal/activity/context.go b/internal/activity/context.go
index 17b2a73a..171db7bb 100644
--- a/internal/activity/context.go
+++ b/internal/activity/context.go
@@ -16,13 +16,14 @@ import (
)
const (
- HeaderAgentID = "X-Agent-Id"
- HeaderPTSessionID = "X-PinchTab-Session-Id"
- HeaderPTSource = "X-PinchTab-Source"
- HeaderPTInstance = "X-PinchTab-Instance-Id"
- HeaderPTProfileID = "X-PinchTab-Profile-Id"
- HeaderPTProfile = "X-PinchTab-Profile-Name"
- HeaderPTTabID = "X-PinchTab-Tab-Id"
+ HeaderAgentID = "X-Agent-Id"
+ HeaderPTSessionID = "X-PinchTab-Session-Id"
+ HeaderPTSource = "X-PinchTab-Source"
+ HeaderPTInstance = "X-PinchTab-Instance-Id"
+ HeaderPTProfileID = "X-PinchTab-Profile-Id"
+ HeaderPTProfile = "X-PinchTab-Profile-Name"
+ HeaderPTTabID = "X-PinchTab-Tab-Id"
+ HeaderPTTabCreated = "X-PinchTab-Tab-Created"
)
type requestStateKey struct{}
diff --git a/internal/bridge/action_form.go b/internal/bridge/action_form.go
index e6570435..0fdb3424 100644
--- a/internal/bridge/action_form.go
+++ b/internal/bridge/action_form.go
@@ -4,10 +4,64 @@ import (
"context"
"encoding/json"
"fmt"
+ "time"
"github.com/chromedp/chromedp"
)
+const checkableStateJS = `function() {
+ var tag = this.tagName ? this.tagName.toLowerCase() : "";
+ var type = (this.type || "").toLowerCase();
+ if (tag === "input" && (type === "checkbox" || type === "radio")) {
+ return {kind: type, state: this.checked ? "true" : "false"};
+ }
+ var role = (this.getAttribute && this.getAttribute("role") || "").toLowerCase();
+ if (role === "checkbox") {
+ var aria = (this.getAttribute("aria-checked") || "").toLowerCase();
+ if (aria === "true" || aria === "false" || aria === "mixed") {
+ return {kind: "aria-checkbox", state: aria};
+ }
+ return {error: "role=checkbox requires aria-checked=true, false, or mixed"};
+ }
+ return {error: "element is not a checkbox, radio, or role=checkbox control (got " + tag + "[type=" + type + "][role=" + role + "])"};
+}`
+
+type checkableState struct {
+ Error string `json:"error"`
+ Kind string `json:"kind"`
+ State string `json:"state"`
+}
+
+func readCheckableState(ctx context.Context, objectID string) (checkableState, error) {
+ var callResult json.RawMessage
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
+ "functionDeclaration": checkableStateJS,
+ "objectId": objectID,
+ "returnByValue": true,
+ }, &callResult)
+ }))
+ if err != nil {
+ return checkableState{}, err
+ }
+ var response struct {
+ Result struct {
+ Value json.RawMessage `json:"value"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(callResult, &response); err != nil {
+ return checkableState{}, err
+ }
+ var state checkableState
+ if err := json.Unmarshal(response.Result.Value, &state); err != nil {
+ return checkableState{}, err
+ }
+ if state.Error != "" {
+ return checkableState{}, fmt.Errorf("%s", state.Error)
+ }
+ return state, nil
+}
+
func (b *Bridge) actionFocus(ctx context.Context, req ActionRequest) (map[string]any, error) {
if req.Selector != "" {
return map[string]any{"focused": true}, chromedp.Run(ctx, chromedp.Focus(req.Selector, chromedp.ByQuery))
@@ -112,53 +166,18 @@ func checkUncheck(ctx context.Context, req ActionRequest, wantChecked bool) (map
return nil, err
}
- // Validate element is a checkbox or radio, and read current checked state.
- var isChecked bool
- err = chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- js := `function() {
- var tag = this.tagName ? this.tagName.toLowerCase() : "";
- var type = (this.type || "").toLowerCase();
- if (tag !== "input" || (type !== "checkbox" && type !== "radio")) {
- return {error: "element is not a checkbox or radio input (got " + tag + "[type=" + type + "])"};
- }
- return {checked: this.checked};
- }`
- var callResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
- "functionDeclaration": js,
- "objectId": objectID,
- "returnByValue": true,
- }, &callResult); err != nil {
- return err
- }
- var cr struct {
- Result struct {
- Value json.RawMessage `json:"value"`
- } `json:"result"`
- }
- if err := json.Unmarshal(callResult, &cr); err != nil {
- return err
- }
- var val struct {
- Error string `json:"error"`
- Checked bool `json:"checked"`
- }
- if err := json.Unmarshal(cr.Result.Value, &val); err != nil {
- return err
- }
- if val.Error != "" {
- return fmt.Errorf("%s", val.Error)
- }
- isChecked = val.Checked
- return nil
- }))
+ state, err := readCheckableState(ctx, objectID)
if err != nil {
return nil, err
}
+ desired := "false"
+ if wantChecked {
+ desired = "true"
+ }
// Click only if state needs to change. Use the JS-dispatch path so the
// toggle isn't gated on the headless=new CDP renderer ack chain.
- if isChecked != wantChecked {
+ if state.State != desired {
if req.NodeID > 0 {
if err := JSClickByBackendNode(ctx, req.NodeID); err != nil {
return nil, err
@@ -174,5 +193,29 @@ func checkUncheck(ctx context.Context, req ActionRequest, wantChecked bool) (map
}
}
- return map[string]any{"checked": wantChecked}, nil
+ // Framework-backed ARIA controls often update state on the next task. Poll
+ // briefly and report the observed value instead of claiming the requested
+ // state without proof.
+ deadline := time.Now().Add(500 * time.Millisecond)
+ for {
+ observed, observeErr := readCheckableState(ctx, objectID)
+ if observeErr == nil && observed.State == desired {
+ return map[string]any{
+ "checked": wantChecked,
+ "controlType": observed.Kind,
+ "verified": true,
+ }, nil
+ }
+ if time.Now().After(deadline) {
+ if observeErr != nil {
+ return nil, fmt.Errorf("verify checked state: %w", observeErr)
+ }
+ return nil, fmt.Errorf("checked state remained %q after requesting %q", observed.State, desired)
+ }
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-time.After(25 * time.Millisecond):
+ }
+ }
}
diff --git a/internal/bridge/action_form_aria_test.go b/internal/bridge/action_form_aria_test.go
new file mode 100644
index 00000000..3dd4ad90
--- /dev/null
+++ b/internal/bridge/action_form_aria_test.go
@@ -0,0 +1,67 @@
+package bridge
+
+import (
+ "context"
+ "encoding/base64"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestCheckUncheckARIACheckboxAndVerifyState(t *testing.T) {
+ chromePath, err := exec.LookPath("chromium")
+ if err != nil {
+ t.Skip("chromium not installed")
+ }
+ profile, err := os.MkdirTemp("", "pinchtab-aria-checkbox-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(chromePath),
+ chromedp.UserDataDir(profile),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ ctx, cancel := chromedp.NewContext(alloc)
+ ctx, cancelTimeout := context.WithTimeout(ctx, 15*time.Second)
+ t.Cleanup(func() {
+ cancelTimeout()
+ cancel()
+ cancelAlloc()
+ _ = os.RemoveAll(profile)
+ })
+
+ html := `<div id="box" role="checkbox" aria-checked="false" onclick="this.setAttribute('aria-checked', this.getAttribute('aria-checked') === 'true' ? 'false' : 'true')">box</div>
+ <div id="stuck" role="checkbox" aria-checked="false">stuck</div>`
+ dataURL := "data:text/html;base64," + base64.StdEncoding.EncodeToString([]byte(html))
+ if err := chromedp.Run(ctx, chromedp.Navigate(dataURL)); err != nil {
+ t.Fatal(err)
+ }
+ b := New(context.Background(), nil, &config.RuntimeConfig{})
+
+ checked, err := b.Actions[ActionCheck](ctx, ActionRequest{Selector: "#box"})
+ if err != nil {
+ t.Fatalf("check ARIA checkbox: %v", err)
+ }
+ if checked["checked"] != true || checked["verified"] != true || checked["controlType"] != "aria-checkbox" {
+ t.Fatalf("check result = %#v", checked)
+ }
+ unchecked, err := b.Actions[ActionUncheck](ctx, ActionRequest{Selector: "#box"})
+ if err != nil {
+ t.Fatalf("uncheck ARIA checkbox: %v", err)
+ }
+ if unchecked["checked"] != false || unchecked["verified"] != true {
+ t.Fatalf("uncheck result = %#v", unchecked)
+ }
+
+ if _, err := b.Actions[ActionCheck](ctx, ActionRequest{Selector: "#stuck"}); err == nil || !strings.Contains(err.Error(), "remained") {
+ t.Fatalf("silent no-op error = %v, want verified-state failure", err)
+ }
+}
diff --git a/internal/bridge/action_pointer.go b/internal/bridge/action_pointer.go
index 0d43411e..3387a0a7 100644
--- a/internal/bridge/action_pointer.go
+++ b/internal/bridge/action_pointer.go
@@ -4,11 +4,12 @@ import (
"context"
"errors"
"fmt"
- "log/slog"
"strings"
"time"
"github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/dom"
+ "github.com/chromedp/cdproto/runtime"
"github.com/chromedp/chromedp"
)
@@ -21,6 +22,7 @@ var clickElementAction = ClickElement
var clickByNodeIDAction = ClickByNodeID
var jsClickByBackendNodeAction = JSClickByBackendNode
var dispatchClickByBackendNodeAction = JSDispatchClickByBackendNode
+var clickFloatingFlyoutItemAction = clickFloatingFlyoutItem
var doubleClickByNodeIDAction = DoubleClickByNodeID
var jsDoubleClickByBackendNodeAction = JSDoubleClickByBackendNode
@@ -61,6 +63,10 @@ func clickByNodeIDWithJSFallback(ctx context.Context, nodeID int64) error {
func clickByNodeIDWithMode(ctx context.Context, nodeID int64, mode string) error {
switch strings.ToLower(strings.TrimSpace(mode)) {
case "", "default":
+ handled, err := clickFloatingFlyoutItemAction(ctx, nodeID)
+ if err != nil || handled {
+ return err
+ }
return clickByNodeIDWithJSFallback(ctx, nodeID)
case "dom":
return jsClickByBackendNodeAction(ctx, nodeID)
@@ -71,6 +77,49 @@ func clickByNodeIDWithMode(ctx context.Context, nodeID int64, mode string) error
}
}
+// clickFloatingFlyoutItem avoids DOM.scrollIntoViewIfNeeded for portal-backed
+// menu options: scrolling their floating owner can rerender and detach the node
+// before the pointer dispatch. A DOM click is intentional for this narrow role
+// and positioning combination; all other nodes retain the trusted pointer path.
+func clickFloatingFlyoutItem(ctx context.Context, nodeID int64) (handled bool, err error) {
+ err = chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ node, err := dom.DescribeNode().WithBackendNodeID(cdp.BackendNodeID(nodeID)).Do(ctx)
+ if err != nil {
+ return err
+ }
+ role := strings.ToLower(strings.TrimSpace(node.AttributeValue("role")))
+ if role != "menuitem" && role != "option" {
+ return nil
+ }
+
+ object, err := dom.ResolveNode().WithBackendNodeID(cdp.BackendNodeID(nodeID)).Do(ctx)
+ if err != nil {
+ return err
+ }
+ result, exception, err := runtime.CallFunctionOn(`function() {
+ if (!this.isConnected) return false;
+ for (var el = this; el && el.nodeType === 1; el = el.parentElement) {
+ var position = getComputedStyle(el).position;
+ if (position === 'fixed' || position === 'absolute') {
+ try { this.focus({preventScroll: true}); } catch (e) {}
+ this.click();
+ return true;
+ }
+ }
+ return false;
+ }`).WithObjectID(object.ObjectID).WithReturnByValue(true).Do(ctx)
+ if err != nil {
+ return err
+ }
+ if exception != nil {
+ return exception
+ }
+ handled = string(result.Value) == "true"
+ return nil
+ }))
+ return handled, err
+}
+
func doubleClickByNodeIDWithJSFallback(ctx context.Context, nodeID int64) error {
trustedCtx, cancel := context.WithTimeout(ctx, trustedNodeClickTimeout)
err := doubleClickByNodeIDAction(trustedCtx, nodeID)
@@ -137,48 +186,6 @@ var scrollViewportCenter = func(ctx context.Context) (float64, float64, error) {
return viewport.X, viewport.Y, nil
}
-// submitFormIfButton checks whether the target element is a submit button and,
-// if so, uses requestSubmit() for a single-shot submission: constraint
-// validation + submit event (so JS handlers run) + actual submission.
-// Falls back to CDP click if the element is not a submit button or on error.
-func submitFormIfButton(ctx context.Context, selector string) (bool, error) {
- var isSubmit bool
- err := chromedp.Run(ctx, chromedp.Evaluate(fmt.Sprintf(`
- (function() {
- var el = document.querySelector(%q);
- if (!el) return false;
- var tag = el.tagName.toLowerCase();
- var type = (el.type || '').toLowerCase();
- return (tag === 'button' && (type === 'submit' || type === '')) ||
- (tag === 'input' && type === 'submit');
- })()
- `, selector), &isSubmit))
- if err != nil || !isSubmit {
- return false, err
- }
- // Fire full event chain via requestSubmit(el):
- // - runs constraint validation
- // - dispatches the submit event (so JS handlers like Odoo's fire)
- // - submits the form if nothing cancels it
- // One call, no double-fire (replaces manual dispatchEvent + form.submit).
- var submitted bool
- err = chromedp.Run(ctx, chromedp.Evaluate(fmt.Sprintf(`
- (function() {
- var el = document.querySelector(%q);
- if (!el) return false;
- el.focus();
- var opts = {bubbles: true, cancelable: true};
- el.dispatchEvent(new MouseEvent('mousedown', opts));
- el.dispatchEvent(new MouseEvent('mouseup', opts));
- el.dispatchEvent(new MouseEvent('click', opts));
- var form = el.closest('form');
- if (form) { form.requestSubmit(el); }
- return true;
- })()
- `, selector), &submitted))
- return submitted, err
-}
-
// settle finalizes the popup auto-switch from a deferred call in the click
// handlers: on success it adopts/focuses any opened tab and augments result; on
// error it cancels — without restore when the error is a blocking dialog, so
@@ -247,7 +254,7 @@ func scaleScreencastCoords(ctx context.Context, req *ActionRequest) {
func (b *Bridge) actionClick(ctx context.Context, req ActionRequest) (result map[string]any, err error) {
scaleScreencastCoords(ctx, &req)
- if b.effectiveHumanize(req) {
+ if !req.Submit && b.effectiveHumanize(req) {
return b.actionHumanizedClick(ctx, req)
}
@@ -282,17 +289,27 @@ func (b *Bridge) actionClick(ctx context.Context, req ActionRequest) (result map
if auto != nil {
auto.prepareWindowOpenCapture(clickCtx)
}
- if req.Selector != "" {
- // For submit buttons, use requestSubmit() to fire constraint validation,
- // JS submit handlers, and actual submission in one shot (issue #411).
- submitted, subErr := submitFormIfButton(clickCtx, req.Selector)
- if subErr != nil {
- slog.Debug("submitFormIfButton failed, falling back to JS click",
- "selector", req.Selector, "error", subErr)
- } else if submitted {
- resultCh <- clickResult{err: nil}
+ if req.Submit {
+ nodeID := req.NodeID
+ if nodeID == 0 && req.Selector != "" {
+ node, nodeErr := firstNodeBySelector(clickCtx, req.Selector)
+ if nodeErr != nil {
+ resultCh <- clickResult{err: nodeErr}
+ return
+ }
+ nodeID = int64(node.BackendNodeID)
+ }
+ if nodeID <= 0 {
+ resultCh <- clickResult{err: fmt.Errorf("click submit requires a selector, ref, or nodeId")}
return
}
+ if auto != nil {
+ auto.prepareNode(clickCtx, nodeID)
+ }
+ // One DOM click only. In particular, do not use the trusted-click
+ // timeout fallback: its second dispatch can double-submit a slow SPA.
+ err = jsClickByBackendNodeAction(clickCtx, nodeID)
+ } else if req.Selector != "" {
node, nodeErr := firstNodeBySelector(clickCtx, req.Selector)
if nodeErr != nil {
resultCh <- clickResult{err: nodeErr}
diff --git a/internal/bridge/action_pointer_flyout_test.go b/internal/bridge/action_pointer_flyout_test.go
new file mode 100644
index 00000000..1a824e07
--- /dev/null
+++ b/internal/bridge/action_pointer_flyout_test.go
@@ -0,0 +1,124 @@
+package bridge
+
+import (
+ "context"
+ "encoding/base64"
+ "os/exec"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestClickPreservesFloatingFlyoutWithoutScroll(t *testing.T) {
+ chromePath, err := exec.LookPath("chromium")
+ if err != nil {
+ t.Skip("chromium not installed")
+ }
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(chromePath),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ defer cancelAlloc()
+ ctx, cancel := chromedp.NewContext(alloc)
+ defer cancel()
+ ctx, cancelTimeout := context.WithTimeout(ctx, 15*time.Second)
+ defer cancelTimeout()
+
+ html := `<style>
+ #portal { position: fixed; inset: 10px auto auto 10px; }
+ #scroller { height: 50px; width: 200px; overflow: auto; }
+ #spacer { height: 200px; }
+ </style>
+ <div id="portal" role="menu">
+ <div id="scroller"><div id="spacer"></div><button id="item" role="menuitem">Content contains</button></div>
+ </div>
+ <script>
+ window.selected = "";
+ window.flyoutDetached = 0;
+ document.getElementById("item").addEventListener("click", () => window.selected = "Content contains");
+ document.getElementById("scroller").addEventListener("scroll", () => {
+ window.flyoutDetached++;
+ document.getElementById("portal").remove();
+ }, {once: true});
+ </script>`
+ dataURL := "data:text/html;base64," + base64.StdEncoding.EncodeToString([]byte(html))
+ if err := chromedp.Run(ctx, chromedp.Navigate(dataURL)); err != nil {
+ t.Fatal(err)
+ }
+ node, err := firstNodeBySelector(ctx, "#item")
+ if err != nil {
+ t.Fatal(err)
+ }
+ b := New(context.Background(), nil, &config.RuntimeConfig{})
+ if _, err := b.Actions[ActionClick](ctx, ActionRequest{NodeID: int64(node.BackendNodeID)}); err != nil {
+ t.Fatalf("click floating menu item: %v", err)
+ }
+
+ var state struct {
+ Selected string `json:"selected"`
+ Detached int `json:"detached"`
+ Present bool `json:"present"`
+ }
+ if err := chromedp.Run(ctx, chromedp.Evaluate(`({
+ selected: window.selected,
+ detached: window.flyoutDetached,
+ present: !!document.getElementById("portal")
+ })`, &state)); err != nil {
+ t.Fatal(err)
+ }
+ if state.Selected != "Content contains" || state.Detached != 0 || !state.Present {
+ t.Fatalf("state after click = %+v, want intended selection with flyout preserved", state)
+ }
+}
+
+func TestDefaultClickUsesNoScrollPathForFloatingFlyout(t *testing.T) {
+ origFlyout := clickFloatingFlyoutItemAction
+ origPointer := clickByNodeIDAction
+ origDOM := jsClickByBackendNodeAction
+ t.Cleanup(func() {
+ clickFloatingFlyoutItemAction = origFlyout
+ clickByNodeIDAction = origPointer
+ jsClickByBackendNodeAction = origDOM
+ })
+
+ clickFloatingFlyoutItemAction = func(context.Context, int64) (bool, error) { return true, nil }
+ clickByNodeIDAction = func(context.Context, int64) error {
+ t.Fatal("floating flyout item reached scrolling pointer path")
+ return nil
+ }
+ jsClickByBackendNodeAction = func(context.Context, int64) error {
+ t.Fatal("atomic flyout click should not be repeated")
+ return nil
+ }
+
+ if err := clickByNodeIDWithMode(context.Background(), 42, "default"); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestDefaultClickKeepsPointerPathForOrdinaryNode(t *testing.T) {
+ origFlyout := clickFloatingFlyoutItemAction
+ origPointer := clickByNodeIDAction
+ t.Cleanup(func() {
+ clickFloatingFlyoutItemAction = origFlyout
+ clickByNodeIDAction = origPointer
+ })
+
+ clickFloatingFlyoutItemAction = func(context.Context, int64) (bool, error) { return false, nil }
+ pointerCalled := false
+ clickByNodeIDAction = func(context.Context, int64) error {
+ pointerCalled = true
+ return nil
+ }
+
+ if err := clickByNodeIDWithMode(context.Background(), 42, "default"); err != nil {
+ t.Fatal(err)
+ }
+ if !pointerCalled {
+ t.Fatal("ordinary node did not use pointer path")
+ }
+}
diff --git a/internal/bridge/action_request.go b/internal/bridge/action_request.go
index 5020e496..bae70e01 100644
--- a/internal/bridge/action_request.go
+++ b/internal/bridge/action_request.go
@@ -78,6 +78,10 @@ type ActionRequest struct {
WaitNav bool `json:"waitNav"`
Fast bool `json:"fast"`
Owner string `json:"owner"`
+ // Submit is an explicit opt-in to a terminal action. Fill dispatches Enter
+ // after filling; click uses one DOM click and lets the handler observe a
+ // bounded post-submit state. Ordinary clicks retain their normal delivery.
+ Submit bool `json:"submit,omitempty"`
// DismissBanners, when true and combined with WaitNav, runs a best-effort
// cookie/consent-banner dismissal pass after a click that triggered a
@@ -85,6 +89,9 @@ type ActionRequest struct {
// invokes the dismissal helper post-action. No effect on actions that
// don't trigger navigation.
DismissBanners bool `json:"dismissBanners,omitempty"`
+ // DismissKnownInterstitials requests the conservative, catalog-backed
+ // pre-action pass. Unlike DismissBanners it never removes generic overlays.
+ DismissKnownInterstitials bool `json:"dismissKnownInterstitials,omitempty"`
// Humanize, when set, overrides the per-instance `humanize` default for
// this action only. nil = use the configured default. true forces the
@@ -158,6 +165,41 @@ func CanonicalActionKind(kind string) string {
return kind
}
+// IsSubmitClick reports whether an action requested the explicit once-only
+// click-submit contract.
+func IsSubmitClick(kind string, req ActionRequest) bool {
+ return req.Submit && CanonicalActionKind(kind) == ActionClick
+}
+
+// ValidateSubmitAction rejects combinations that cannot preserve exactly-once
+// submit dispatch. Fill's existing submit-via-Enter contract is unchanged.
+func ValidateSubmitAction(kind string, req ActionRequest) error {
+ if !req.Submit {
+ return nil
+ }
+ kind = CanonicalActionKind(kind)
+ switch kind {
+ case ActionFill:
+ return nil
+ case ActionClick:
+ if req.HasXY {
+ return fmt.Errorf("click submit requires an element target; coordinates are not supported")
+ }
+ if req.WaitNav {
+ return fmt.Errorf("click submit cannot be combined with waitNav")
+ }
+ if strings.TrimSpace(req.Mode) != "" {
+ return fmt.Errorf("click submit cannot be combined with mode")
+ }
+ if req.Humanize != nil && *req.Humanize {
+ return fmt.Errorf("click submit cannot be combined with humanize=true")
+ }
+ return nil
+ default:
+ return fmt.Errorf("submit is only supported for fill and click actions")
+ }
+}
+
func hasJSONKey(raw map[string]json.RawMessage, key string) bool {
_, ok := raw[key]
return ok
@@ -166,6 +208,12 @@ func hasJSONKey(raw map[string]json.RawMessage, key string) bool {
func (b *Bridge) ExecuteAction(ctx context.Context, kind string, req ActionRequest) (map[string]any, error) {
kind = CanonicalActionKind(kind)
req.Kind = CanonicalActionKind(req.Kind)
+ if req.Kind == "" {
+ req.Kind = kind
+ }
+ if err := ValidateSubmitAction(kind, req); err != nil {
+ return nil, err
+ }
if kind == ActionClick && b.effectiveHumanize(req) && strings.TrimSpace(req.Mode) != "" {
return nil, fmt.Errorf("mode and humanize are mutually exclusive")
}
diff --git a/internal/bridge/action_resolve.go b/internal/bridge/action_resolve.go
index c1f018c5..549f8742 100644
--- a/internal/bridge/action_resolve.go
+++ b/internal/bridge/action_resolve.go
@@ -20,6 +20,11 @@ import (
// error — which must surface as 5xx, not 404. Callers classify with errors.Is.
var ErrSelectorNoMatch = errors.New("selector matched no element")
+// ErrSelectorOutsideScope marks a cached ref that still exists but belongs to
+// the background document rather than the active modal subtree. Callers must
+// not treat this as a stale ref or invoke global semantic recovery.
+var ErrSelectorOutsideScope = errors.New("selector target is outside scope")
+
type FrameElementMeta struct {
TagName string `json:"tagName"`
ID string `json:"id,omitempty"`
@@ -43,20 +48,34 @@ func frameExecutionContextID(ctx context.Context, frameID string) (int64, error)
}
func frameDocumentObjectID(ctx context.Context, frameID string) (string, error) {
+ // Selector and modal discovery run in an isolated world so page script cannot
+ // hide or redirect targets by replacing DOM methods in the main world.
+ if frameID == "" {
+ frameTree, err := FetchFrameTree(ctx)
+ if err != nil {
+ return "", fmt.Errorf("resolve top frame: %w", err)
+ }
+ frameID = frameTree.Frame.ID
+ if frameID == "" {
+ return "", fmt.Errorf("resolve top frame: frame id is empty")
+ }
+ }
+ execID, err := frameExecutionContextID(ctx, frameID)
+ if err != nil {
+ return "", err
+ }
+ if execID == 0 {
+ return "", fmt.Errorf("frame %q has no isolated execution context", frameID)
+ }
+
params := map[string]any{
"expression": "document",
"returnByValue": false,
- }
- if frameID != "" {
- execID, err := frameExecutionContextID(ctx, frameID)
- if err != nil {
- return "", err
- }
- params["contextId"] = execID
+ "contextId": execID,
}
var docResult json.RawMessage
- err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ err = chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.evaluate", params, &docResult)
}))
if err != nil {
@@ -67,11 +86,17 @@ func frameDocumentObjectID(ctx context.Context, frameID string) (string, error)
Result struct {
ObjectID string `json:"objectId"`
} `json:"result"`
+ ExceptionDetails *struct {
+ Text string `json:"text"`
+ } `json:"exceptionDetails,omitempty"`
}
if err := json.Unmarshal(docResult, &doc); err != nil {
return "", err
}
if doc.Result.ObjectID == "" {
+ if doc.ExceptionDetails != nil {
+ return "", fmt.Errorf("resolve document: %s", doc.ExceptionDetails.Text)
+ }
return "", fmt.Errorf("document object not found")
}
return doc.Result.ObjectID, nil
@@ -158,6 +183,250 @@ func resolveNodeInFrame(ctx context.Context, frameID, functionDeclaration string
return backendNodeIDFromObjectID(ctx, call.Result.ObjectID)
}
+// TopmostModalNodeIDInFrame returns the backend node ID of the visually
+// topmost visible modal owner in a frame. A missing dialog is a normal result,
+// not an error. Discovery runs in an isolated world and uses browser hit
+// testing rather than comparing local z-index values, which are not comparable
+// across stacking contexts or the native top layer.
+func TopmostModalNodeIDInFrame(ctx context.Context, frameID string) (int64, bool, error) {
+ const topmostModalFn = `function() {
+ const candidates = [];
+ const seen = new Set();
+ const composedParent = (node) => node && (node.parentNode || node.host || null);
+ const composedContains = (ancestor, node) => {
+ for (let cur = node; cur; cur = composedParent(cur)) if (cur === ancestor) return true;
+ return false;
+ };
+ const visit = (root) => {
+ if (!root || !root.querySelectorAll) return;
+ for (const el of root.querySelectorAll('dialog, [aria-modal="true"]')) {
+ if (!seen.has(el)) { seen.add(el); candidates.push(el); }
+ }
+ for (const el of root.querySelectorAll("*")) if (el.shadowRoot) visit(el.shadowRoot);
+ };
+ visit(this);
+ const visible = candidates.filter((el) => {
+ if (!el || !el.isConnected) return false;
+ let nativeModal = false;
+ try { nativeModal = el.matches(":modal"); } catch (_) {}
+ if (!nativeModal && el.getAttribute("aria-modal") !== "true") return false;
+ for (let cur = el; cur; cur = composedParent(cur)) {
+ if (cur.nodeType !== 1) continue;
+ if (cur.getAttribute("aria-hidden") === "true") return false;
+ const style = cur.ownerDocument.defaultView.getComputedStyle(cur);
+ if (style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse") return false;
+ if (Number.parseFloat(style.opacity || "1") <= 0) return false;
+ }
+ const rect = el.getBoundingClientRect();
+ return rect.width > 0 && rect.height > 0 && rect.right > 0 && rect.bottom > 0 &&
+ rect.left < el.ownerDocument.defaultView.innerWidth && rect.top < el.ownerDocument.defaultView.innerHeight;
+ });
+ if (!visible.length) return null;
+
+ // An inner modal owns interaction before any containing modal, regardless
+ // of the outer element's local z-index.
+ const leaves = visible.filter((candidate) => !visible.some((other) =>
+ other !== candidate && composedContains(candidate, other)));
+ const points = [];
+ const pointKeys = new Set();
+ const addPoint = (x, y) => {
+ x = Math.max(0, Math.min(this.defaultView.innerWidth - 1, x));
+ y = Math.max(0, Math.min(this.defaultView.innerHeight - 1, y));
+ const key = Math.round(x) + ":" + Math.round(y);
+ if (!pointKeys.has(key)) { pointKeys.add(key); points.push([x, y]); }
+ };
+ for (const el of leaves) {
+ const r = el.getBoundingClientRect();
+ const left = Math.max(0, r.left), right = Math.min(this.defaultView.innerWidth, r.right);
+ const top = Math.max(0, r.top), bottom = Math.min(this.defaultView.innerHeight, r.bottom);
+ addPoint((left + right) / 2, (top + bottom) / 2);
+ addPoint(left + (right - left) * .2, top + (bottom - top) * .2);
+ addPoint(right - (right - left) * .2, top + (bottom - top) * .2);
+ addPoint(left + (right - left) * .2, bottom - (bottom - top) * .2);
+ addPoint(right - (right - left) * .2, bottom - (bottom - top) * .2);
+ }
+ const deepHit = (x, y) => {
+ let root = this, hit = null;
+ while (root && root.elementFromPoint) {
+ const next = root.elementFromPoint(x, y);
+ if (!next || next === hit) break;
+ hit = next;
+ root = next.shadowRoot;
+ }
+ return hit;
+ };
+ let best = null, bestHits = 0;
+ for (const candidate of leaves) {
+ let hits = 0;
+ for (const [x, y] of points) if (composedContains(candidate, deepHit(x, y))) hits++;
+ if (hits > bestHits || (hits === bestHits && hits > 0)) {
+ best = candidate;
+ bestHits = hits;
+ }
+ }
+ return bestHits > 0 ? best : null;
+ }`
+
+ nodeID, err := resolveNodeInFrame(ctx, frameID, topmostModalFn, nil)
+ if errors.Is(err, ErrSelectorNoMatch) {
+ return 0, false, nil
+ }
+ if err != nil {
+ return 0, false, fmt.Errorf("resolve topmost dialog: %w", err)
+ }
+ return nodeID, true, nil
+}
+
+// TopmostModalNodeID gives a top-document modal precedence over a caller's
+// current iframe scope. This prevents a stale frame scope from interacting
+// with background content underneath a page-level modal. When the top
+// document has no modal, it falls back to the requested frame.
+func TopmostModalNodeID(ctx context.Context, frameID string) (int64, bool, error) {
+ nodeID, open, err := TopmostModalNodeIDInFrame(ctx, "")
+ if err != nil || open || frameID == "" {
+ return nodeID, open, err
+ }
+ return TopmostModalNodeIDInFrame(ctx, frameID)
+}
+
+// resolveNodeWithinBackendNode invokes functionDeclaration with the scope
+// element as `this` and converts the returned DOM object to a backend node ID.
+func resolveNodeWithinBackendNode(ctx context.Context, scopeBackendNodeID int64, functionDeclaration string, args []map[string]any) (int64, error) {
+ var scopeResult json.RawMessage
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
+ "backendNodeId": scopeBackendNodeID,
+ }, &scopeResult)
+ }))
+ if err != nil {
+ return 0, fmt.Errorf("resolve scope node: %w", err)
+ }
+
+ var scope struct {
+ Object struct {
+ ObjectID string `json:"objectId"`
+ } `json:"object"`
+ }
+ if err := json.Unmarshal(scopeResult, &scope); err != nil {
+ return 0, err
+ }
+ if scope.Object.ObjectID == "" {
+ return 0, fmt.Errorf("dialog scope is no longer attached")
+ }
+
+ params := map[string]any{
+ "functionDeclaration": functionDeclaration,
+ "objectId": scope.Object.ObjectID,
+ "returnByValue": false,
+ }
+ if len(args) > 0 {
+ params["arguments"] = args
+ }
+
+ var callResult json.RawMessage
+ err = chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", params, &callResult)
+ }))
+ if err != nil {
+ return 0, err
+ }
+
+ var call struct {
+ Result struct {
+ Type string `json:"type"`
+ Subtype string `json:"subtype"`
+ ObjectID string `json:"objectId"`
+ } `json:"result"`
+ ExceptionDetails *struct {
+ Text string `json:"text"`
+ } `json:"exceptionDetails,omitempty"`
+ }
+ if err := json.Unmarshal(callResult, &call); err != nil {
+ return 0, err
+ }
+ if call.ExceptionDetails != nil {
+ return 0, fmt.Errorf("scoped selector evaluation: %s", call.ExceptionDetails.Text)
+ }
+ if call.Result.ObjectID == "" || call.Result.Subtype == "null" || call.Result.Type == "undefined" {
+ return 0, fmt.Errorf("%w", ErrSelectorNoMatch)
+ }
+ return backendNodeIDFromObjectID(ctx, call.Result.ObjectID)
+}
+
+// BackendNodeWithinScope reports whether target is the scope node or one of
+// its DOM descendants. It is used to reject stale/background snapshot refs
+// while a modal dialog owns the interaction surface.
+func BackendNodeWithinScope(ctx context.Context, scopeBackendNodeID, targetBackendNodeID int64) (bool, error) {
+ if scopeBackendNodeID == 0 || targetBackendNodeID == 0 {
+ return false, nil
+ }
+
+ resolve := func(ctx context.Context, backendNodeID int64) (string, error) {
+ var raw json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{
+ "backendNodeId": backendNodeID,
+ }, &raw); err != nil {
+ return "", err
+ }
+ var parsed struct {
+ Object struct {
+ ObjectID string `json:"objectId"`
+ } `json:"object"`
+ }
+ if err := json.Unmarshal(raw, &parsed); err != nil {
+ return "", err
+ }
+ if parsed.Object.ObjectID == "" {
+ return "", fmt.Errorf("backend node %d is no longer attached", backendNodeID)
+ }
+ return parsed.Object.ObjectID, nil
+ }
+
+ var contains bool
+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ scopeObjectID, err := resolve(ctx, scopeBackendNodeID)
+ if err != nil {
+ return fmt.Errorf("resolve scope node: %w", err)
+ }
+ targetObjectID, err := resolve(ctx, targetBackendNodeID)
+ if err != nil {
+ return fmt.Errorf("resolve target node: %w", err)
+ }
+
+ var raw json.RawMessage
+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{
+ "functionDeclaration": `function(target) {
+ for (let cur = target; cur; cur = cur.parentNode || cur.host || null) {
+ if (cur === this) return true;
+ }
+ return false;
+ }`,
+ "objectId": scopeObjectID,
+ "arguments": []map[string]any{{"objectId": targetObjectID}},
+ "returnByValue": true,
+ }, &raw); err != nil {
+ return err
+ }
+ var parsed struct {
+ Result struct {
+ Value bool `json:"value"`
+ } `json:"result"`
+ ExceptionDetails *struct {
+ Text string `json:"text"`
+ } `json:"exceptionDetails,omitempty"`
+ }
+ if err := json.Unmarshal(raw, &parsed); err != nil {
+ return err
+ }
+ if parsed.ExceptionDetails != nil {
+ return fmt.Errorf("scope containment check: %s", parsed.ExceptionDetails.Text)
+ }
+ contains = parsed.Result.Value
+ return nil
+ }))
+ return contains, err
+}
+
func resolveElementMetaInFrame(ctx context.Context, frameID, functionDeclaration string, args []map[string]any) (FrameElementMeta, error) {
docObjectID, err := frameDocumentObjectID(ctx, frameID)
if err != nil {
@@ -407,6 +676,7 @@ const resolveSelectorAtFn = `function(kind, value, index, fromEnd) {
const out = [];
const visit = (scope) => {
if (!scope || !scope.querySelectorAll) return;
+ if (scope.nodeType === 1 && scope.matches && scope.matches(selector)) out.push(scope);
const elements = Array.from(scope.querySelectorAll("*"));
out.push(...Array.from(scope.querySelectorAll(selector)));
for (const el of elements) if (el.shadowRoot) visit(el.shadowRoot);
@@ -448,9 +718,13 @@ const resolveSelectorAtFn = `function(kind, value, index, fromEnd) {
case "css":
return pick(deepQueryAll(value));
case "xpath": {
- const result = root.evaluate(value, root, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
+ const document = root.ownerDocument || root;
+ const result = document.evaluate(value, root, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
const items = [];
- for (let i = 0; i < result.snapshotLength; i++) items.push(result.snapshotItem(i));
+ for (let i = 0; i < result.snapshotLength; i++) {
+ const item = result.snapshotItem(i);
+ if (root.nodeType === 9 || item === root || (root.contains && root.contains(item))) items.push(item);
+ }
return pick(items);
}
case "text":
@@ -488,6 +762,26 @@ func resolveSelectorAtInFrame(ctx context.Context, frameID string, sel selector.
return backendNodeID, err
}
+func resolveSelectorAtWithinNode(ctx context.Context, scopeBackendNodeID int64, sel selector.Selector, index int, fromEnd bool) (int64, error) {
+ kind := string(sel.Kind)
+ switch sel.Kind {
+ case selector.KindCSS, selector.KindXPath, selector.KindText:
+ default:
+ return 0, fmt.Errorf("%s selector cannot be used with first/last/nth", sel.Kind)
+ }
+
+ nid, err := resolveNodeWithinBackendNode(ctx, scopeBackendNodeID, resolveSelectorAtFn, []map[string]any{
+ {"value": kind},
+ {"value": sel.Value},
+ {"value": index},
+ {"value": fromEnd},
+ })
+ if err != nil {
+ return 0, fmt.Errorf("%s %q inside topmost dialog: %w", sel.Kind, sel.Value, err)
+ }
+ return nid, nil
+}
+
func parseNthSelectorValue(value string) (int, string, error) {
rawIndex, rawSelector, ok := strings.Cut(value, ":")
if !ok {
@@ -530,6 +824,31 @@ func resolveNestedSelectorAtInFrame(ctx context.Context, frameID string, raw str
}
}
+func resolveNestedSelectorWithinNode(ctx context.Context, scopeBackendNodeID int64, raw string, refCache *RefCache, index int, fromEnd bool) (int64, error) {
+ inner := selector.Parse(raw)
+ switch inner.Kind {
+ case selector.KindFirst:
+ return resolveNestedSelectorWithinNode(ctx, scopeBackendNodeID, inner.Value, refCache, 0, false)
+ case selector.KindLast:
+ return resolveNestedSelectorWithinNode(ctx, scopeBackendNodeID, inner.Value, refCache, 0, true)
+ case selector.KindNth:
+ nth, nestedRaw, err := parseNthSelectorValue(inner.Value)
+ if err != nil {
+ return 0, err
+ }
+ return resolveNestedSelectorWithinNode(ctx, scopeBackendNodeID, nestedRaw, refCache, nth, false)
+ case selector.KindRef:
+ if fromEnd || index != 0 {
+ return 0, fmt.Errorf("ref selector cannot be used with last/nth")
+ }
+ return ResolveUnifiedSelectorWithinNode(ctx, inner, refCache, scopeBackendNodeID)
+ case selector.KindSemantic:
+ return 0, fmt.Errorf("semantic selectors must be resolved at the handler layer via /find")
+ default:
+ return resolveSelectorAtWithinNode(ctx, scopeBackendNodeID, inner, index, fromEnd)
+ }
+}
+
func ResolveCSSToNodeID(ctx context.Context, css string) (int64, error) {
return ResolveCSSToNodeIDInFrame(ctx, "", css)
}
@@ -644,6 +963,61 @@ func ResolveUnifiedSelectorInFrame(ctx context.Context, sel selector.Selector, r
}
}
+// ResolveUnifiedSelectorWithinNode resolves a selector strictly inside a DOM
+// subtree. Ref selectors are accepted only when their cached backend node is
+// still contained by that subtree; all other supported selectors are
+// evaluated with the scope element as their root.
+func ResolveUnifiedSelectorWithinNode(ctx context.Context, sel selector.Selector, refCache *RefCache, scopeBackendNodeID int64) (int64, error) {
+ if scopeBackendNodeID == 0 {
+ return 0, fmt.Errorf("dialog scope is missing")
+ }
+
+ switch sel.Kind {
+ case selector.KindRef:
+ if refCache == nil {
+ return 0, fmt.Errorf("ref %s not in snapshot cache: %w", sel.Value, ErrSelectorNoMatch)
+ }
+ target, ok := refCache.Lookup(sel.Value)
+ if !ok || target.BackendNodeID == 0 {
+ return 0, fmt.Errorf("ref %s not in snapshot cache: %w", sel.Value, ErrSelectorNoMatch)
+ }
+ inside, err := BackendNodeWithinScope(ctx, scopeBackendNodeID, target.BackendNodeID)
+ if err != nil {
+ return 0, fmt.Errorf("validate ref %s against topmost dialog: %w", sel.Value, err)
+ }
+ if !inside {
+ return 0, fmt.Errorf("ref %s is outside the topmost dialog: %w", sel.Value, ErrSelectorOutsideScope)
+ }
+ return target.BackendNodeID, nil
+
+ case selector.KindCSS, selector.KindXPath, selector.KindText:
+ return resolveSelectorAtWithinNode(ctx, scopeBackendNodeID, sel, 0, false)
+
+ case selector.KindSemantic:
+ return 0, fmt.Errorf("semantic selectors must be resolved at the handler layer via /find")
+
+ case selector.KindRole, selector.KindLabel, selector.KindPlaceholder,
+ selector.KindAlt, selector.KindTitle, selector.KindTestID:
+ return 0, fmt.Errorf("%s selectors must be resolved at the handler layer via semantic", sel.Kind)
+
+ case selector.KindFirst:
+ return resolveNestedSelectorWithinNode(ctx, scopeBackendNodeID, sel.Value, refCache, 0, false)
+
+ case selector.KindLast:
+ return resolveNestedSelectorWithinNode(ctx, scopeBackendNodeID, sel.Value, refCache, 0, true)
+
+ case selector.KindNth:
+ index, rawSelector, err := parseNthSelectorValue(sel.Value)
+ if err != nil {
+ return 0, err
+ }
+ return resolveNestedSelectorWithinNode(ctx, scopeBackendNodeID, rawSelector, refCache, index, false)
+
+ default:
+ return 0, fmt.Errorf("unknown selector kind: %q", sel.Kind)
+ }
+}
+
func ResolveUnifiedSelector(ctx context.Context, sel selector.Selector, refCache *RefCache) (int64, error) {
return ResolveUnifiedSelectorInFrame(ctx, sel, refCache, "")
}
diff --git a/internal/bridge/action_resolve_modal_test.go b/internal/bridge/action_resolve_modal_test.go
new file mode 100644
index 00000000..5b3ab10e
--- /dev/null
+++ b/internal/bridge/action_resolve_modal_test.go
@@ -0,0 +1,311 @@
+package bridge
+
+import (
+ "context"
+ "encoding/base64"
+ "errors"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/selector"
+)
+
+func TestDialogScopeReproducesGlobalEscapeAndContainsActionsAndReads(t *testing.T) {
+ chromePath, err := exec.LookPath("chromium")
+ if err != nil {
+ t.Skip("chromium not installed")
+ }
+ profile, err := os.MkdirTemp("", "pinchtab-modal-scope-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(chromePath),
+ chromedp.UserDataDir(profile),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ ctx, cancelBrowser := chromedp.NewContext(alloc)
+ ctx, cancelTimeout := context.WithTimeout(ctx, 20*time.Second)
+ t.Cleanup(func() {
+ cancelTimeout()
+ cancelBrowser()
+ cancelAlloc()
+ _ = os.RemoveAll(profile)
+ })
+
+ html := `<style>
+ [role=dialog] { position: fixed; inset: 20px; background: white; }
+ #lower { z-index: 10; }
+ #top { z-index: 20; }
+ </style>
+ <button id="background-action" onclick="window.backgroundClicks++">Content contains</button>
+ <table><tr><td>Background policy grid</td><td>Select row</td></tr></table>
+ <iframe id="child" srcdoc="<button id='frame-background'>Content contains</button>"></iframe>
+ <div id="lower" role="dialog" aria-modal="true"><button>Content contains</button></div>
+ <div id="top" role="dialog" aria-modal="true">
+ <h2>Sensitive info picker</h2>
+ </div>
+ <div id="shadow-host"></div>
+ <script>
+ window.backgroundClicks = 0; window.dialogClicks = 0;
+ const root = document.getElementById("shadow-host").attachShadow({mode:"open"});
+ root.innerHTML = '<style>#shadow-top { position:fixed; inset:30px; z-index:30; background:white }</style>' +
+ '<div id="shadow-top" role="dialog" aria-modal="true">' +
+ '<h2>Sensitive info picker</h2>' +
+ '<button id="dialog-action">Content contains</button>' +
+ '<div role="row">Dialog option Select row</div></div>';
+ root.getElementById("dialog-action").addEventListener("click", () => window.dialogClicks++);
+ </script>`
+ dataURL := "data:text/html;base64," + base64.StdEncoding.EncodeToString([]byte(html))
+ if err := chromedp.Run(ctx, chromedp.Navigate(dataURL)); err != nil {
+ t.Fatal(err)
+ }
+
+ // Verbatim PT-C018 failure boundary: the old global text resolver chooses
+ // the same-labeled background control that appears first in the document.
+ globalNodeID, err := ResolveTextToNodeIDInFrame(ctx, "", "Content contains")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var globalID string
+ if err := callFunctionOnNodeForTest(ctx, globalNodeID, `function() { return this.id; }`, &globalID); err != nil {
+ t.Fatal(err)
+ }
+ if globalID != "background-action" {
+ t.Fatalf("unscoped reproduction resolved %q, want background-action", globalID)
+ }
+
+ frameTree, err := FetchFrameTree(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ frameIDs := frameIDs(frameTree)
+ if len(frameIDs) < 2 {
+ t.Fatalf("frame ids = %v, want top frame plus child", frameIDs)
+ }
+ childFrameID := frameIDs[1]
+ frameBackgroundNodeID, err := ResolveTextToNodeIDInFrame(ctx, childFrameID, "Content contains")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var frameBackgroundID string
+ if err := callFunctionOnNodeForTest(ctx, frameBackgroundNodeID, `function() { return this.id; }`, &frameBackgroundID); err != nil {
+ t.Fatal(err)
+ }
+ if frameBackgroundID != "frame-background" {
+ t.Fatalf("frame precondition resolved %q, want frame-background", frameBackgroundID)
+ }
+
+ modalNodeID, open, err := TopmostModalNodeID(ctx, childFrameID)
+ if err != nil || !open {
+ t.Fatalf("topmost dialog = (%d, %v, %v), want visible dialog", modalNodeID, open, err)
+ }
+ var modalID string
+ if err := callFunctionOnNodeForTest(ctx, modalNodeID, `function() { return this.id; }`, &modalID); err != nil {
+ t.Fatal(err)
+ }
+ if modalID != "shadow-top" {
+ t.Fatalf("topmost dialog id = %q, want shadow-top", modalID)
+ }
+
+ scopedNodeID, err := ResolveUnifiedSelectorWithinNode(ctx, selector.Parse("text:Content contains"), nil, modalNodeID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var scopedID string
+ if err := callFunctionOnNodeForTest(ctx, scopedNodeID, `function() { return this.id; }`, &scopedID); err != nil {
+ t.Fatal(err)
+ }
+ if scopedID != "dialog-action" {
+ t.Fatalf("dialog-scoped text resolved %q, want dialog-action", scopedID)
+ }
+ if err := JSClickByBackendNode(ctx, scopedNodeID); err != nil {
+ t.Fatal(err)
+ }
+ var clickState struct {
+ Background int `json:"background"`
+ Dialog int `json:"dialog"`
+ }
+ if err := chromedp.Run(ctx, chromedp.Evaluate(`({background: window.backgroundClicks, dialog: window.dialogClicks})`, &clickState)); err != nil {
+ t.Fatal(err)
+ }
+ if clickState.Background != 0 || clickState.Dialog != 1 {
+ t.Fatalf("click state = %+v, want only dialog action", clickState)
+ }
+
+ backgroundRef := RefCache{Targets: map[string]RefTarget{"e0": {BackendNodeID: globalNodeID}, "e1": {BackendNodeID: scopedNodeID}}}
+ if _, err := ResolveUnifiedSelectorWithinNode(ctx, selector.Parse("ref:e0"), &backgroundRef, modalNodeID); !errors.Is(err, ErrSelectorOutsideScope) {
+ t.Fatalf("background ref error = %v, want ErrSelectorOutsideScope", err)
+ }
+ if got, err := ResolveUnifiedSelectorWithinNode(ctx, selector.Parse("ref:e1"), &backgroundRef, modalNodeID); err != nil || got != scopedNodeID {
+ t.Fatalf("dialog ref = (%d, %v), want %d", got, err, scopedNodeID)
+ }
+
+ var dialogText string
+ if err := callFunctionOnNodeForTest(ctx, modalNodeID, `function() { return this.innerText; }`, &dialogText); err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(dialogText, "Dialog option") || strings.Contains(dialogText, "Background policy grid") {
+ t.Fatalf("dialog text leaked background content: %q", dialogText)
+ }
+ rawNodes, err := FetchAXTree(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ flat, _ := BuildSnapshot(FilterSubtree(rawNodes, modalNodeID), "", -1)
+ var snapshotText strings.Builder
+ for _, node := range flat {
+ snapshotText.WriteString(node.Name)
+ snapshotText.WriteByte('\n')
+ }
+ if got := snapshotText.String(); !strings.Contains(got, "Dialog option") || strings.Contains(got, "Background policy grid") {
+ t.Fatalf("dialog snapshot leaked background content: %q", got)
+ }
+}
+
+func TestTopmostModalUsesBrowserPaintOrderAndRejectsFalseOwners(t *testing.T) {
+ chromePath, err := exec.LookPath("chromium")
+ if err != nil {
+ t.Skip("chromium not installed")
+ }
+ profile, err := os.MkdirTemp("", "pinchtab-modal-order-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(chromePath),
+ chromedp.UserDataDir(profile),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ ctx, cancelBrowser := chromedp.NewContext(alloc)
+ ctx, cancelTimeout := context.WithTimeout(ctx, 20*time.Second)
+ t.Cleanup(func() {
+ cancelTimeout()
+ cancelBrowser()
+ cancelAlloc()
+ _ = os.RemoveAll(profile)
+ })
+
+ navigate := func(html string) {
+ t.Helper()
+ dataURL := "data:text/html;base64," + base64.StdEncoding.EncodeToString([]byte(html))
+ if err := chromedp.Run(ctx, chromedp.Navigate(dataURL)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ modalID := func() string {
+ t.Helper()
+ nodeID, open, err := TopmostModalNodeID(ctx, "")
+ if err != nil || !open {
+ t.Fatalf("topmost dialog = (%d, %v, %v), want one", nodeID, open, err)
+ }
+ var id string
+ if err := callFunctionOnNodeForTest(ctx, nodeID, `function() { return this.id; }`, &id); err != nil {
+ t.Fatal(err)
+ }
+ return id
+ }
+
+ t.Run("native top layer follows showModal order", func(t *testing.T) {
+ navigate(`<style>dialog { width:300px; height:180px; padding:0 }</style>
+ <dialog id="first">first</dialog><dialog id="second">second</dialog>
+ <script>second.showModal(); first.showModal();</script>`)
+ if got := modalID(); got != "first" {
+ t.Fatalf("topmost dialog = %q, want last showModal() dialog first", got)
+ }
+ })
+
+ t.Run("nested inner owns interaction despite outer z index", func(t *testing.T) {
+ navigate(`<div id="outer" role="dialog" aria-modal="true"
+ style="position:fixed;inset:0;z-index:100;background:white">
+ <div id="inner" role="dialog" aria-modal="true"
+ style="position:absolute;inset:40px;background:white">inner</div>
+ </div>`)
+ if got := modalID(); got != "inner" {
+ t.Fatalf("topmost dialog = %q, want nested inner", got)
+ }
+ })
+
+ t.Run("modeless and offscreen dialogs do not own scope", func(t *testing.T) {
+ navigate(`<dialog id="modeless" open>modeless</dialog>
+ <div id="offscreen" role="dialog" aria-modal="true"
+ style="position:fixed;left:-10000px;top:0;width:100px;height:100px">offscreen</div>
+ <div id="live" role="dialog" aria-modal="true"
+ style="position:fixed;inset:20px;background:white">live</div>`)
+ if got := modalID(); got != "live" {
+ t.Fatalf("topmost dialog = %q, want live", got)
+ }
+ })
+
+ t.Run("main world DOM poisoning cannot hide modal", func(t *testing.T) {
+ navigate(`<div id="guarded" role="dialog" aria-modal="true"
+ style="position:fixed;inset:20px;background:white">guarded</div>
+ <script>
+ document.querySelectorAll = () => [];
+ Document.prototype.querySelectorAll = () => [];
+ Element.prototype.getBoundingClientRect = () => ({left:-1e4,top:0,right:-9e3,bottom:1,width:1,height:1});
+ </script>`)
+ if got := modalID(); got != "guarded" {
+ t.Fatalf("topmost dialog = %q, want guarded", got)
+ }
+ })
+}
+
+func TestDialogScopeContainmentIncludesOpenShadowDescendants(t *testing.T) {
+ chromePath, err := exec.LookPath("chromium")
+ if err != nil {
+ t.Skip("chromium not installed")
+ }
+ profile, err := os.MkdirTemp("", "pinchtab-modal-shadow-containment-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(chromePath),
+ chromedp.UserDataDir(profile),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ ctx, cancelBrowser := chromedp.NewContext(alloc)
+ ctx, cancelTimeout := context.WithTimeout(ctx, 20*time.Second)
+ t.Cleanup(func() {
+ cancelTimeout()
+ cancelBrowser()
+ cancelAlloc()
+ _ = os.RemoveAll(profile)
+ })
+
+ html := `<div id="dialog" role="dialog" aria-modal="true"
+ style="position:fixed;inset:20px;background:white"><div id="host"></div></div>
+ <script>host.attachShadow({mode:'open'}).innerHTML='<button id="shadow-button">Save</button>'</script>`
+ if err := chromedp.Run(ctx, chromedp.Navigate("data:text/html;base64,"+base64.StdEncoding.EncodeToString([]byte(html)))); err != nil {
+ t.Fatal(err)
+ }
+ modalNodeID, open, err := TopmostModalNodeID(ctx, "")
+ if err != nil || !open {
+ t.Fatalf("topmost dialog = (%d, %v, %v)", modalNodeID, open, err)
+ }
+ buttonNodeID, err := ResolveCSSToNodeID(ctx, "#shadow-button")
+ if err != nil {
+ t.Fatal(err)
+ }
+ inside, err := BackendNodeWithinScope(ctx, modalNodeID, buttonNodeID)
+ if err != nil || !inside {
+ t.Fatalf("shadow button containment = (%v, %v), want true", inside, err)
+ }
+}
+
+// callFunctionOnNodeForTest keeps the real-browser assertions on the same CDP
+// primitive used by the handler without constructing a full Bridge instance.
+func callFunctionOnNodeForTest(ctx context.Context, backendNodeID int64, fn string, result any) error {
+ return new(Bridge).CallFunctionOnNode(ctx, backendNodeID, fn, nil, result)
+}
diff --git a/internal/bridge/action_text.go b/internal/bridge/action_text.go
index 0798f533..09a37e32 100644
--- a/internal/bridge/action_text.go
+++ b/internal/bridge/action_text.go
@@ -3,6 +3,7 @@ package bridge
import (
"context"
"fmt"
+ "strings"
"unicode/utf8"
"github.com/chromedp/chromedp"
@@ -36,26 +37,53 @@ func (b *Bridge) actionType(ctx context.Context, req ActionRequest) (map[string]
}
func (b *Bridge) actionFill(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ result := textEntryResult("filled", req.Text)
if req.Selector != "" {
- return textEntryResult("filled", req.Text), chromedp.Run(ctx, chromedp.SetValue(req.Selector, req.Text, chromedp.ByQuery))
+ if err := chromedp.Run(ctx,
+ chromedp.Focus(req.Selector, chromedp.ByQuery),
+ chromedp.SetValue(req.Selector, req.Text, chromedp.ByQuery),
+ ); err != nil {
+ return nil, err
+ }
+ return finishFill(ctx, result, req.Submit)
}
if req.NodeID > 0 {
if err := FillByNodeID(ctx, req.NodeID, req.Text); err != nil {
return nil, err
}
- result := textEntryResult("filled", req.Text)
if actual, err := ReadInputValue(ctx, req.NodeID); err == nil && req.Text != "" && actual != req.Text {
result["warning"] = "fill may not have been picked up by the page (e.g. React controlled input); try 'type' instead"
}
- return result, nil
+ return finishFill(ctx, result, req.Submit)
}
return nil, fmt.Errorf("need selector or ref")
}
+func finishFill(ctx context.Context, result map[string]any, submit bool) (map[string]any, error) {
+ if !submit {
+ return result, nil
+ }
+ if err := DispatchNamedKey(ctx, "Enter", 0); err != nil {
+ return nil, fmt.Errorf("submit filled field: %w", err)
+ }
+ result["submitted"] = true
+ return result, nil
+}
+
func (b *Bridge) actionPress(ctx context.Context, req ActionRequest) (map[string]any, error) {
if req.Key == "" {
return nil, fmt.Errorf("key required for press")
}
+ key, chordModifiers, chord, err := parsePressChord(req.Key)
+ if err != nil {
+ return nil, err
+ }
+ if chord {
+ if req.Modifiers != 0 {
+ return nil, fmt.Errorf("press chord %q also supplied modifiers; use one chord form", req.Key)
+ }
+ req.Key, req.Modifiers = key, chordModifiers
+ }
if req.NodeID > 0 {
if err := focusBackendNode(ctx, req.NodeID); err != nil {
return nil, err
@@ -68,6 +96,41 @@ func (b *Bridge) actionPress(ctx context.Context, req ActionRequest) (map[string
return map[string]any{"pressed": req.Key}, DispatchNamedKey(ctx, req.Key, req.Modifiers)
}
+func parsePressChord(value string) (key string, modifiers int, chord bool, err error) {
+ if !strings.Contains(value, "+") || value == "+" {
+ return value, 0, false, nil
+ }
+ parts := strings.Split(value, "+")
+ if len(parts) < 2 || strings.TrimSpace(parts[len(parts)-1]) == "" {
+ return "", 0, true, fmt.Errorf(
+ "invalid press chord %q; use modifiers such as Ctrl+A or Shift+ArrowLeft", value,
+ )
+ }
+ seen := 0
+ for _, raw := range parts[:len(parts)-1] {
+ var bit int
+ switch strings.ToLower(strings.TrimSpace(raw)) {
+ case "alt", "option":
+ bit = 1
+ case "ctrl", "control":
+ bit = 2
+ case "meta", "cmd", "command", "super", "win":
+ bit = 4
+ case "shift":
+ bit = 8
+ default:
+ return "", 0, true, fmt.Errorf(
+ "invalid press chord modifier %q; use Ctrl, Alt, Shift, or Meta", strings.TrimSpace(raw),
+ )
+ }
+ if seen&bit != 0 {
+ return "", 0, true, fmt.Errorf("duplicate press chord modifier %q", strings.TrimSpace(raw))
+ }
+ seen |= bit
+ }
+ return strings.TrimSpace(parts[len(parts)-1]), seen, true, nil
+}
+
func (b *Bridge) actionHumanizedType(ctx context.Context, req ActionRequest) (map[string]any, error) {
if req.Text == "" {
return nil, fmt.Errorf("text required for type")
diff --git a/internal/bridge/actions_test.go b/internal/bridge/actions_test.go
index 3014904e..82bb88d3 100644
--- a/internal/bridge/actions_test.go
+++ b/internal/bridge/actions_test.go
@@ -677,6 +677,75 @@ func TestClickByNodeIDWithJSFallback_SkipsFallbackOnCancelledCtx(t *testing.T) {
}
}
+func TestClickSubmitUsesOneJSTransactionWithoutFallback(t *testing.T) {
+ origJS := jsClickByBackendNodeAction
+ origTrusted := clickByNodeIDAction
+ origFlyout := clickFloatingFlyoutItemAction
+ t.Cleanup(func() {
+ jsClickByBackendNodeAction = origJS
+ clickByNodeIDAction = origTrusted
+ clickFloatingFlyoutItemAction = origFlyout
+ })
+
+ jsCalls := 0
+ trustedCalls := 0
+ flyoutCalls := 0
+ jsClickByBackendNodeAction = func(_ context.Context, nodeID int64) error {
+ jsCalls++
+ if nodeID != 42 {
+ t.Fatalf("nodeID = %d, want 42", nodeID)
+ }
+ return context.DeadlineExceeded
+ }
+ clickByNodeIDAction = func(context.Context, int64) error {
+ trustedCalls++
+ return nil
+ }
+ clickFloatingFlyoutItemAction = func(context.Context, int64) (bool, error) {
+ flyoutCalls++
+ return false, nil
+ }
+
+ b := New(context.Background(), nil, &config.RuntimeConfig{Humanize: true})
+ _, err := b.actionClick(context.Background(), ActionRequest{
+ Kind: ActionClick,
+ NodeID: 42,
+ Submit: true,
+ })
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("submit click error = %v, want deadline", err)
+ }
+ if jsCalls != 1 || trustedCalls != 0 || flyoutCalls != 0 {
+ t.Fatalf("dispatch counts = js:%d trusted:%d flyout:%d, want 1/0/0", jsCalls, trustedCalls, flyoutCalls)
+ }
+}
+
+func TestValidateSubmitAction(t *testing.T) {
+ trueValue := true
+ tests := []struct {
+ name string
+ kind string
+ req ActionRequest
+ wantErr bool
+ }{
+ {name: "fill unchanged", kind: ActionFill, req: ActionRequest{Submit: true}},
+ {name: "click element", kind: ActionClick, req: ActionRequest{Submit: true, NodeID: 1}},
+ {name: "coordinates", kind: ActionClick, req: ActionRequest{Submit: true, HasXY: true}, wantErr: true},
+ {name: "wait nav", kind: ActionClick, req: ActionRequest{Submit: true, WaitNav: true}, wantErr: true},
+ {name: "mode", kind: ActionClick, req: ActionRequest{Submit: true, Mode: "dom"}, wantErr: true},
+ {name: "humanize", kind: ActionClick, req: ActionRequest{Submit: true, Humanize: &trueValue}, wantErr: true},
+ {name: "other action", kind: ActionType, req: ActionRequest{Submit: true}, wantErr: true},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ err := ValidateSubmitAction(tt.kind, tt.req)
+ if (err != nil) != tt.wantErr {
+ t.Fatalf("ValidateSubmitAction() error = %v, wantErr %v", err, tt.wantErr)
+ }
+ })
+ }
+}
+
func TestTypeAction_HumanizeOptInUsesHumanizedPath(t *testing.T) {
raw := New(context.TODO(), nil, &config.RuntimeConfig{Humanize: true})
ctx, cancel := context.WithCancel(context.Background())
@@ -887,6 +956,20 @@ func TestUncheckAction_WithSelector_UsesCSSPath(t *testing.T) {
}
}
+func TestFinishFillSubmitIsOptInAndDispatchesEnter(t *testing.T) {
+ result := map[string]any{"filled": true}
+ got, err := finishFill(context.Background(), result, false)
+ if err != nil || got["submitted"] != nil {
+ t.Fatalf("non-submit fill = (%v, %v), want unchanged result", got, err)
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if _, err := finishFill(ctx, map[string]any{"filled": true}, true); err == nil || !strings.Contains(err.Error(), "submit filled field") {
+ t.Fatalf("submit fill error = %v, want Enter dispatch attempt", err)
+ }
+}
+
func TestKeyboardTypeAction_Registered(t *testing.T) {
b := New(context.TODO(), nil, &config.RuntimeConfig{})
if _, ok := b.Actions[ActionKeyboardType]; !ok {
@@ -948,6 +1031,50 @@ func TestKeyDownAction_RequiresKey(t *testing.T) {
}
}
+func TestParsePressChord(t *testing.T) {
+ tests := []struct {
+ input string
+ wantKey string
+ wantModifiers int
+ wantChord bool
+ wantError string
+ }{
+ {input: "Enter", wantKey: "Enter"},
+ {input: "+", wantKey: "+"},
+ {input: "Control+A", wantKey: "A", wantModifiers: 2, wantChord: true},
+ {input: "Ctrl+Shift+ArrowLeft", wantKey: "ArrowLeft", wantModifiers: 10, wantChord: true},
+ {input: "Cmd+C", wantKey: "C", wantModifiers: 4, wantChord: true},
+ {input: "Banana+A", wantChord: true, wantError: "invalid press chord modifier"},
+ {input: "Ctrl+", wantChord: true, wantError: "invalid press chord"},
+ {input: "Ctrl+Control+A", wantChord: true, wantError: "duplicate press chord modifier"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.input, func(t *testing.T) {
+ key, modifiers, chord, err := parsePressChord(tt.input)
+ if key != tt.wantKey || modifiers != tt.wantModifiers || chord != tt.wantChord {
+ t.Fatalf("parsePressChord(%q) = (%q, %d, %v), want (%q, %d, %v)",
+ tt.input, key, modifiers, chord, tt.wantKey, tt.wantModifiers, tt.wantChord)
+ }
+ if tt.wantError == "" && err != nil {
+ t.Fatalf("parsePressChord(%q) unexpected error: %v", tt.input, err)
+ }
+ if tt.wantError != "" && (err == nil || !strings.Contains(err.Error(), tt.wantError)) {
+ t.Fatalf("parsePressChord(%q) error = %v, want %q", tt.input, err, tt.wantError)
+ }
+ })
+ }
+}
+
+func TestPressChordRejectsAmbiguousModifierInputsBeforeDispatch(t *testing.T) {
+ b := New(context.TODO(), nil, &config.RuntimeConfig{})
+ _, err := b.Actions[ActionPress](context.Background(), ActionRequest{
+ Key: "Control+A", Modifiers: 2,
+ })
+ if err == nil || !strings.Contains(err.Error(), "also supplied modifiers") {
+ t.Fatalf("press ambiguous chord error = %v", err)
+ }
+}
+
func TestKeyUpAction_RequiresKey(t *testing.T) {
b := New(context.TODO(), nil, &config.RuntimeConfig{})
_, err := b.Actions[ActionKeyUp](context.Background(), ActionRequest{})
diff --git a/internal/bridge/api.go b/internal/bridge/api.go
index ef3a99b3..6691d3b2 100644
--- a/internal/bridge/api.go
+++ b/internal/bridge/api.go
@@ -15,10 +15,11 @@ import (
)
type TabTarget struct {
- TargetID string `json:"targetId"`
- URL string `json:"url"`
- Title string `json:"title"`
- Type string `json:"type"`
+ TargetID string `json:"targetId"`
+ URL string `json:"url"`
+ Title string `json:"title"`
+ Type string `json:"type"`
+ BrowserContextID string `json:"browserContextId,omitempty"`
}
var ErrBrowserDraining = errors.New("browser restart in progress; retry shortly")
diff --git a/internal/bridge/attach_indicator.go b/internal/bridge/attach_indicator.go
new file mode 100644
index 00000000..c8756557
--- /dev/null
+++ b/internal/bridge/attach_indicator.go
@@ -0,0 +1,164 @@
+package bridge
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/chromedp/cdproto/page"
+ cdpruntime "github.com/chromedp/cdproto/runtime"
+ "github.com/chromedp/chromedp"
+)
+
+const attachIndicatorCleanupTimeout = 500 * time.Millisecond
+
+type attachIndicatorState struct {
+ ctx context.Context
+ scriptID page.ScriptIdentifier
+}
+
+func attachIndicatorScript(port string) (string, error) {
+ value, err := strconv.Atoi(strings.TrimSpace(port))
+ if err != nil || value < 1 || value > 65535 {
+ return "", fmt.Errorf("invalid bridge port %q", port)
+ }
+ portJSON, _ := json.Marshal(value)
+ return fmt.Sprintf(`(() => {
+ const key = "__pinchtabAttachIndicators";
+ const port = %s;
+ const prefixPattern = /^\[PinchTab :\d+(?:,:\d+)*\]\s*/;
+ let state = globalThis[key];
+ if (!state || !(state.ports instanceof Set)) {
+ state = {ports: new Set(), observer: null, start: null, disposed: false};
+ globalThis[key] = state;
+ }
+ state.disposed = false;
+ state.ports.add(port);
+ const apply = () => {
+ const clean = document.title.replace(prefixPattern, "");
+ const ports = Array.from(state.ports).sort((a, b) => a - b);
+ const prefix = ports.length ? "[PinchTab " + ports.map(p => ":" + p).join(",") + "] " : "";
+ if (document.title !== prefix + clean) document.title = prefix + clean;
+ };
+ if (!state.observer) state.observer = new MutationObserver(apply);
+ if (!state.start) state.start = () => {
+ if (state.disposed || !state.ports.size) return;
+ apply();
+ if (document.head) state.observer.observe(document.head, {subtree:true, childList:true, characterData:true});
+ };
+ if (document.head) state.start(); else document.addEventListener("DOMContentLoaded", state.start, {once:true});
+})()`, portJSON), nil
+}
+
+func clearAttachIndicatorScript(port string) (string, error) {
+ value, err := strconv.Atoi(strings.TrimSpace(port))
+ if err != nil || value < 1 || value > 65535 {
+ return "", fmt.Errorf("invalid bridge port %q", port)
+ }
+ portJSON, _ := json.Marshal(value)
+ return fmt.Sprintf(`(() => {
+ const key = "__pinchtabAttachIndicators";
+ const port = %s;
+ const prefixPattern = /^\[PinchTab :\d+(?:,:\d+)*\]\s*/;
+ const state = globalThis[key];
+ if (!state || !(state.ports instanceof Set)) {
+ document.title = document.title.replace(prefixPattern, "");
+ return;
+ }
+ state.ports.delete(port);
+ const clean = document.title.replace(prefixPattern, "");
+ const ports = Array.from(state.ports).sort((a, b) => a - b);
+ if (!ports.length) {
+ state.disposed = true;
+ if (state.observer) state.observer.disconnect();
+ if (state.start) document.removeEventListener("DOMContentLoaded", state.start);
+ delete globalThis[key];
+ document.title = clean;
+ return;
+ }
+ document.title = "[PinchTab " + ports.map(p => ":" + p).join(",") + "] " + clean;
+})()`, portJSON), nil
+}
+
+func (b *Bridge) installAttachIndicator(ctx context.Context, tabID string) error {
+ if b == nil || b.Config == nil {
+ return fmt.Errorf("bridge configuration is required")
+ }
+ script, err := attachIndicatorScript(b.Config.Port)
+ if err != nil {
+ return err
+ }
+ b.attachIndicatorMu.Lock()
+ defer b.attachIndicatorMu.Unlock()
+ if b.attachIndicators != nil {
+ if _, exists := b.attachIndicators[tabID]; exists {
+ return nil
+ }
+ }
+ var scriptID page.ScriptIdentifier
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
+ var addErr error
+ scriptID, addErr = page.AddScriptToEvaluateOnNewDocument(script).Do(ctx)
+ if addErr != nil {
+ return addErr
+ }
+ if b.attachIndicators == nil {
+ b.attachIndicators = make(map[string]attachIndicatorState)
+ }
+ b.attachIndicators[tabID] = attachIndicatorState{ctx: ctx, scriptID: scriptID}
+ _, exception, evalErr := cdpruntime.Evaluate(script).Do(ctx)
+ if evalErr != nil {
+ _ = page.RemoveScriptToEvaluateOnNewDocument(scriptID).Do(ctx)
+ delete(b.attachIndicators, tabID)
+ return evalErr
+ }
+ if exception != nil {
+ _ = page.RemoveScriptToEvaluateOnNewDocument(scriptID).Do(ctx)
+ delete(b.attachIndicators, tabID)
+ return exception
+ }
+ return nil
+ })); err != nil {
+ return fmt.Errorf("install attach indicator: %w", err)
+ }
+ return nil
+}
+
+func (b *Bridge) clearAttachIndicators() {
+ if b == nil || b.Config == nil {
+ return
+ }
+ cleanupScript, err := clearAttachIndicatorScript(b.Config.Port)
+ if err != nil {
+ return
+ }
+ b.attachIndicatorMu.Lock()
+ states := b.attachIndicators
+ b.attachIndicators = nil
+ b.attachIndicatorMu.Unlock()
+ for _, state := range states {
+ tabCtx := state.ctx
+ if tabCtx == nil {
+ continue
+ }
+ if tabCtx.Err() != nil {
+ continue
+ }
+ cleanupCtx, cancel := context.WithTimeout(tabCtx, attachIndicatorCleanupTimeout)
+ if err := chromedp.Run(cleanupCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ removeErr := page.RemoveScriptToEvaluateOnNewDocument(state.scriptID).Do(ctx)
+ _, _, evalErr := cdpruntime.Evaluate(cleanupScript).Do(ctx)
+ if evalErr != nil {
+ return evalErr
+ }
+ return removeErr
+ })); err != nil {
+ slog.Warn("attach indicator cleanup failed", "err", err)
+ }
+ cancel()
+ }
+}
diff --git a/internal/bridge/attach_indicator_test.go b/internal/bridge/attach_indicator_test.go
new file mode 100644
index 00000000..6d35add3
--- /dev/null
+++ b/internal/bridge/attach_indicator_test.go
@@ -0,0 +1,128 @@
+package bridge
+
+import (
+ "context"
+ "encoding/base64"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/stealth"
+)
+
+func TestAttachIndicatorNamesPortPersistsAndClears(t *testing.T) {
+ chromePath, err := exec.LookPath("chromium")
+ if err != nil {
+ t.Skip("chromium not installed")
+ }
+ profile, err := os.MkdirTemp("", "pinchtab-attach-indicator-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(chromePath),
+ chromedp.UserDataDir(profile),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ ctx, cancelBrowser := chromedp.NewContext(alloc)
+ ctx, cancelTimeout := context.WithTimeout(ctx, 20*time.Second)
+ t.Cleanup(func() {
+ cancelTimeout()
+ cancelBrowser()
+ cancelAlloc()
+ _ = os.RemoveAll(profile)
+ })
+ pageURL := func(title string) string {
+ html := "<title>" + title + "</title><p>fixture</p>"
+ return "data:text/html;base64," + base64.StdEncoding.EncodeToString([]byte(html))
+ }
+ if err := chromedp.Run(ctx, chromedp.Navigate(pageURL("Original"))); err != nil {
+ t.Fatal(err)
+ }
+
+ cfg := &config.RuntimeConfig{Port: "9876"}
+ b := New(context.Background(), ctx, cfg)
+ b.stealthLaunchMode = stealth.LaunchModeAttached
+ execCtx := cdp.WithExecutor(ctx, chromedp.FromContext(ctx).Target)
+ b.TabManager.RegisterTab("tab-indicator", execCtx)
+ if err := b.tabSetup(execCtx, "tab-indicator"); err != nil {
+ t.Fatal(err)
+ }
+ // Repeated setup for the same bridge/tab is idempotent and must not
+ // strand a second new-document script.
+ if err := b.tabSetup(execCtx, "tab-indicator"); err != nil {
+ t.Fatal(err)
+ }
+ if got := len(b.attachIndicators); got != 1 {
+ t.Fatalf("attach indicator registrations = %d, want 1", got)
+ }
+ readTitle := func() string {
+ var title string
+ if err := chromedp.Run(ctx, chromedp.Title(&title)); err != nil {
+ t.Fatal(err)
+ }
+ return title
+ }
+ if got := readTitle(); got != "[PinchTab :9876] Original" {
+ t.Fatalf("installed title = %q", got)
+ }
+ if err := chromedp.Run(ctx, chromedp.Evaluate(`document.title = "Updated"`, nil), chromedp.Sleep(50*time.Millisecond)); err != nil {
+ t.Fatal(err)
+ }
+ if got := readTitle(); got != "[PinchTab :9876] Updated" {
+ t.Fatalf("maintained title = %q", got)
+ }
+
+ b2 := New(context.Background(), ctx, &config.RuntimeConfig{Port: "9877"})
+ b2.stealthLaunchMode = stealth.LaunchModeAttached
+ b2.TabManager.RegisterTab("tab-indicator", execCtx)
+ if err := b2.tabSetup(execCtx, "tab-indicator"); err != nil {
+ t.Fatal(err)
+ }
+ if got := readTitle(); got != "[PinchTab :9876,:9877] Updated" {
+ t.Fatalf("two-owner title = %q", got)
+ }
+
+ b.Cleanup()
+ if got := readTitle(); got != "[PinchTab :9877] Updated" {
+ t.Fatalf("first-owner cleanup title = %q", got)
+ }
+ if err := chromedp.Run(ctx, chromedp.Evaluate(`document.title = "Second owner"`, nil), chromedp.Sleep(50*time.Millisecond)); err != nil {
+ t.Fatal(err)
+ }
+ if got := readTitle(); got != "[PinchTab :9877] Second owner" {
+ t.Fatalf("remaining-owner maintained title = %q", got)
+ }
+ b2.Cleanup()
+ if got := readTitle(); got != "Second owner" {
+ t.Fatalf("final cleared title = %q", got)
+ }
+ if err := chromedp.Run(ctx, chromedp.Navigate(pageURL("After detach"))); err != nil {
+ t.Fatal(err)
+ }
+ if got := readTitle(); got != "After detach" {
+ t.Fatalf("new-document script survived detach: %q", got)
+ }
+}
+
+func TestAttachIndicatorRejectsInvalidPort(t *testing.T) {
+ for _, port := range []string{"", "0", "65536", "not-a-port"} {
+ if _, err := attachIndicatorScript(port); err == nil {
+ t.Fatalf("port %q accepted", port)
+ }
+ }
+ script, err := attachIndicatorScript(" 9867 ")
+ if err != nil || !strings.Contains(script, `const port = 9867`) {
+ t.Fatalf("valid port script error=%v", err)
+ }
+ if _, err := clearAttachIndicatorScript(" 9867 "); err != nil {
+ t.Fatalf("valid cleanup script error=%v", err)
+ }
+}
diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.go
index 1510192c..5b5bb855 100644
--- a/internal/bridge/bridge.go
+++ b/internal/bridge/bridge.go
@@ -52,6 +52,8 @@ type Bridge struct {
fingerprintMu sync.RWMutex
fingerprintOverlays map[string]bool
workerStealthTargets sync.Map
+ attachIndicatorMu sync.Mutex
+ attachIndicators map[string]attachIndicatorState
handoffMu sync.RWMutex
handoffs map[string]TabHandoffState
pointerMu sync.RWMutex
@@ -251,6 +253,18 @@ func (b *Bridge) CreateTab(url string) (string, context.Context, context.CancelF
return tabID, ctx, cancel, err
}
+func (b *Bridge) CreateTabInBrowserContext(url, browserContextID string) (string, context.Context, context.CancelFunc, error) {
+ tm, err := b.tabManager()
+ if err != nil {
+ return "", nil, nil, err
+ }
+ tabID, ctx, cancel, err := tm.CreateTabInBrowserContext(url, browserContextID)
+ if err == nil {
+ go b.SaveState()
+ }
+ return tabID, ctx, cancel, err
+}
+
func (b *Bridge) TabContext(tabID string) (*TabHandle, string, error) {
tm, err := b.tabManager()
if err != nil {
@@ -275,10 +289,11 @@ func (b *Bridge) ListTargets() ([]TabTarget, error) {
targets := make([]TabTarget, len(infos))
for i, t := range infos {
targets[i] = TabTarget{
- TargetID: string(t.TargetID),
- URL: t.URL,
- Title: t.Title,
- Type: string(t.Type),
+ TargetID: string(t.TargetID),
+ URL: t.URL,
+ Title: t.Title,
+ Type: string(t.Type),
+ BrowserContextID: string(t.BrowserContextID),
}
}
return targets, nil
@@ -384,6 +399,12 @@ func (b *Bridge) BrowserContext() context.Context {
}
func (b *Bridge) Navigate(ctx context.Context, url string, params NavigateParams) (*NavigateResult, error) {
+ if params.DispatchOnly {
+ if err := DispatchNavigation(ctx, url); err != nil {
+ return nil, fmt.Errorf("dispatch navigation: %w", err)
+ }
+ return &NavigateResult{URL: url}, nil
+ }
if err := NavigatePageWithRedirectLimit(ctx, url, params.MaxRedirects); err != nil {
return nil, err
}
diff --git a/internal/bridge/bridge_cleanup_test.go b/internal/bridge/bridge_cleanup_test.go
index da01a405..e18857f5 100644
--- a/internal/bridge/bridge_cleanup_test.go
+++ b/internal/bridge/bridge_cleanup_test.go
@@ -228,6 +228,46 @@ func TestCleanup_RemoteCDP_SkipsKillLogic(t *testing.T) {
}
}
+func TestCleanup_CDPAttachURLOnly_SkipsKillLogic(t *testing.T) {
+ withShortenedGrace(t, 20*time.Millisecond, 20*time.Millisecond)
+ termCount, killCount := withMockedProcessLookup(t, func() []int { return []int{1} })
+
+ ctx := context.TODO()
+ b := New(ctx, ctx, &config.RuntimeConfig{
+ ProfileDir: "/tmp/pinchtab-test-profile",
+ CDPAttachURL: "http://127.0.0.1:9222",
+ })
+ b.Cleanup()
+
+ if got := termCount.Load(); got != 0 {
+ t.Errorf("CDP attach cleanup must not SIGTERM, got %d", got)
+ }
+ if got := killCount.Load(); got != 0 {
+ t.Errorf("CDP attach cleanup must not SIGKILL, got %d", got)
+ }
+}
+
+func TestRestartBrowser_CDPAttachURLOnly_SkipsKillLogic(t *testing.T) {
+ origDrain := browserRestartDrainWindow
+ browserRestartDrainWindow = time.Millisecond
+ t.Cleanup(func() { browserRestartDrainWindow = origDrain })
+ _, killCount := withMockedProcessLookup(t, func() []int { return []int{1} })
+
+ cfg := &config.RuntimeConfig{
+ ProfileDir: t.TempDir(),
+ CDPAttachURL: "http://127.0.0.1:1",
+ AttachAllowHosts: []string{"127.0.0.1"},
+ AttachAllowSchemes: []string{"http"},
+ }
+ b := New(context.Background(), nil, cfg)
+ if err := b.RestartBrowser(cfg); err == nil {
+ t.Fatal("restart against an unreachable external CDP endpoint unexpectedly succeeded")
+ }
+ if got := killCount.Load(); got != 0 {
+ t.Errorf("external restart must not SIGKILL, got %d", got)
+ }
+}
+
func TestFetchPauseSuppressionLifecycle(t *testing.T) {
b := &Bridge{}
flag := b.fetchPauseSuppression("t1")
diff --git a/internal/bridge/bridge_lifecycle.go b/internal/bridge/bridge_lifecycle.go
index 68926cb9..2b5b0823 100644
--- a/internal/bridge/bridge_lifecycle.go
+++ b/internal/bridge/bridge_lifecycle.go
@@ -3,6 +3,7 @@ package bridge
import (
"context"
"crypto/rand"
+ "errors"
"fmt"
"log/slog"
"math/big"
@@ -11,6 +12,8 @@ import (
"sync"
"time"
+ "github.com/chromedp/cdproto"
+ "github.com/chromedp/cdproto/debugger"
"github.com/chromedp/cdproto/page"
cdpruntime "github.com/chromedp/cdproto/runtime"
"github.com/chromedp/chromedp"
@@ -27,11 +30,24 @@ import (
var BridgeShutdownGracePeriod = 5 * time.Second
var bridgeShutdownTermGrace = 2 * time.Second
var bridgeFastShutdownGrace = 200 * time.Millisecond
+var browserRestartDrainWindow = 2 * time.Second
func (b *Bridge) quietStealthObservers() bool {
return b != nil && b.Config != nil && stealth.NormalizeLevel(b.Config.StealthLevel) == stealth.LevelFull
}
+func (b *Bridge) externalAttachMode() bool {
+ if b == nil {
+ return false
+ }
+ if b.stealthLaunchMode == stealth.LaunchModeAttached ||
+ b.stealthLaunchMode == stealth.LaunchModeRemoteCDP {
+ return true
+ }
+ return b.Config != nil && (strings.TrimSpace(b.Config.CDPAttachURL) != "" ||
+ strings.TrimSpace(b.Config.RemoteCDPURL) != "")
+}
+
func (b *Bridge) RestartStatus() (bool, time.Duration) {
if b == nil {
return false, 0
@@ -82,7 +98,37 @@ func (b *Bridge) applyTargetStealth(ctx context.Context) {
}
}
-func (b *Bridge) tabSetup(ctx context.Context, tabID string) {
+func preventDebuggerPauses(ctx context.Context) error {
+ if _, err := debugger.Enable().Do(ctx); err != nil {
+ return fmt.Errorf("enable debugger domain: %w", err)
+ }
+ if err := debugger.SetSkipAllPauses(true).Do(ctx); err != nil {
+ // Enabling Debugger without the skip guard would make `debugger`
+ // statements pause this CDP session. Restore the safer default before
+ // rejecting the target.
+ _ = debugger.Disable().Do(ctx)
+ return fmt.Errorf("skip debugger pauses: %w", err)
+ }
+ // setSkipAllPauses prevents the next pause but does not release a target
+ // that was already stopped when PinchTab attached. Resume it; Chrome's
+ // normal "not paused" response means there was nothing to release.
+ if err := debugger.Resume().Do(ctx); err != nil {
+ var protocolErr *cdproto.Error
+ alreadyRunning := errors.As(err, &protocolErr) && protocolErr.Code == -32000 &&
+ protocolErr.Message == "Can only perform operation while paused."
+ if !alreadyRunning {
+ _ = debugger.Disable().Do(ctx)
+ return fmt.Errorf("resume paused debugger: %w", err)
+ }
+ }
+ return nil
+}
+
+func (b *Bridge) tabSetup(ctx context.Context, tabID string) error {
+ if err := preventDebuggerPauses(ctx); err != nil {
+ return err
+ }
+
// Fetch auth events are session-scoped, so each new tab needs its own
// proxy-auth listener + Fetch enablement; the initial tab is covered by
// the launch/attach init paths. The suppression flag quiets this
@@ -95,6 +141,17 @@ func (b *Bridge) tabSetup(ctx context.Context, tabID string) {
slog.Debug("per-tab proxy auth enabled", "tab", tabID)
}
}
+ // An externally managed browser already owns its launch fingerprint,
+ // locale, animation policy, and Runtime-domain behavior. Mutating those
+ // targets during attach caused locale-override failures and could alter a
+ // human's live profile. The debugger guard and optional proxy-auth wiring
+ // above are connection safety, not launch emulation, so they remain active.
+ if b.externalAttachMode() {
+ if err := b.installAttachIndicator(ctx, tabID); err != nil {
+ slog.Warn("attach indicator setup failed", "tab", tabID, "err", err)
+ }
+ return nil
+ }
if !config.PinchTabStealthDefaultsDisabled(b.Config) {
b.applyTargetStealth(ctx)
b.installWorkerStealthParity(ctx)
@@ -121,6 +178,7 @@ func (b *Bridge) tabSetup(ctx context.Context, tabID string) {
slog.Warn("runtime.Disable failed", "err", err)
}
}
+ return nil
}
func (b *Bridge) ensureStealthBundle() {
@@ -277,17 +335,22 @@ func (b *Bridge) RestartBrowser(cfg *config.RuntimeConfig) error {
return fmt.Errorf("runtime config is required")
}
- const drainWindow = 2 * time.Second
-
b.initMu.Lock()
b.draining = true
- b.drainUntil = time.Now().Add(drainWindow)
+ b.drainUntil = time.Now().Add(browserRestartDrainWindow)
b.initMu.Unlock()
- slog.Info("browser soft restart: draining requests before restart", "drain_window", drainWindow)
- time.Sleep(drainWindow)
+ slog.Info("browser soft restart: draining requests before restart", "drain_window", browserRestartDrainWindow)
+ time.Sleep(browserRestartDrainWindow)
b.initMu.Lock()
+ externalAttach := b.externalAttachMode()
+ if externalAttach {
+ // The title indicator and its new-document script live in the external
+ // page. Remove them while the target contexts are still usable; context
+ // cancellation below only releases PinchTab's side of the connection.
+ b.clearAttachIndicators()
+ }
if b.BrowserCancel != nil {
b.BrowserCancel()
@@ -298,29 +361,31 @@ func (b *Bridge) RestartBrowser(cfg *config.RuntimeConfig) error {
slog.Info("browser soft restart: cancelled allocator context")
}
- profileDir := ""
- if b.tempProfileDir != "" {
- profileDir = b.tempProfileDir
- } else {
- profileDir = cfg.ProfileDir
- }
- if profileDir != "" {
- time.Sleep(200 * time.Millisecond)
- killed := killChromeByProfileDir(profileDir)
- if killed > 0 {
- slog.Info("browser soft restart: killed surviving chrome processes", "count", killed, "profileDir", profileDir)
+ if !externalAttach {
+ profileDir := ""
+ if b.tempProfileDir != "" {
+ profileDir = b.tempProfileDir
+ } else {
+ profileDir = cfg.ProfileDir
}
- ClearChromeSessions(profileDir)
- }
- b.ClearSavedState()
+ if profileDir != "" {
+ time.Sleep(200 * time.Millisecond)
+ killed := killChromeByProfileDirFunc(profileDir)
+ if killed > 0 {
+ slog.Info("browser soft restart: killed surviving chrome processes", "count", killed, "profileDir", profileDir)
+ }
+ ClearChromeSessions(profileDir)
+ }
+ b.ClearSavedState()
- if b.tempProfileDir != "" {
- if err := os.RemoveAll(b.tempProfileDir); err != nil {
- slog.Warn("failed to remove temp profile dir during restart", "path", b.tempProfileDir, "err", err)
- } else {
- slog.Info("removed temp profile dir during restart", "path", b.tempProfileDir)
+ if b.tempProfileDir != "" {
+ if err := os.RemoveAll(b.tempProfileDir); err != nil {
+ slog.Warn("failed to remove temp profile dir during restart", "path", b.tempProfileDir, "err", err)
+ } else {
+ slog.Info("removed temp profile dir during restart", "path", b.tempProfileDir)
+ }
+ b.tempProfileDir = ""
}
- b.tempProfileDir = ""
}
b.initialized = false
@@ -364,8 +429,14 @@ func (b *Bridge) RestartBrowser(cfg *config.RuntimeConfig) error {
// Cleanup releases browser resources and removes temporary profile directories.
// Must be called on shutdown to prevent Chrome process and disk leaks.
func (b *Bridge) Cleanup() {
- // Remote-CDP: external browser is not owned by PinchTab.
- if b != nil && b.Config != nil && strings.TrimSpace(b.Config.RemoteCDPURL) != "" {
+ if b != nil && b.externalAttachMode() {
+ b.clearAttachIndicators()
+ }
+ // External attach: the browser is not owned by PinchTab. CDPAttachURL is
+ // the current bridge flag; RemoteCDPURL is the legacy/server alias. Use the
+ // resolved launch mode as the source of truth so either configuration form
+ // can never fall through to profile-scoped process termination.
+ if b != nil && b.externalAttachMode() {
if b.BrowserCancel != nil {
b.BrowserCancel()
slog.Debug("remote-CDP: browser context cancelled (external browser left running)")
diff --git a/internal/bridge/bridge_types.go b/internal/bridge/bridge_types.go
index d02509e2..035f6ef2 100644
--- a/internal/bridge/bridge_types.go
+++ b/internal/bridge/bridge_types.go
@@ -125,7 +125,12 @@ type TextResult struct {
}
type NavigateParams struct {
- MaxRedirects int
+ MaxRedirects int
+ // DispatchOnly sends Page.navigate and returns after Chrome accepts it,
+ // without waiting for load/ready state. The caller must poll the explicit
+ // tab for readiness. This is used for headed background tabs whose SPA load
+ // event can remain pending indefinitely without ever activating the window.
+ DispatchOnly bool
AllowInternal bool
TrustedProxyCIDRs []net.IPNet
TrustedResolvedIPs []net.IP
diff --git a/internal/bridge/cdpops/navigation.go b/internal/bridge/cdpops/navigation.go
index 1e77a1a2..60e9796d 100644
--- a/internal/bridge/cdpops/navigation.go
+++ b/internal/bridge/cdpops/navigation.go
@@ -8,6 +8,7 @@ import (
"time"
"github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/fetch"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/cdproto/page"
@@ -28,6 +29,31 @@ func NavigatePage(ctx context.Context, url string) error {
return waitForReadyStateAfterNavigation(ctx)
}
+// DispatchNavigation wakes a headed background renderer without activating its
+// OS window, sends one navigation command, and returns as soon as the target
+// accepts it. Callers retain the tab context and poll readiness separately.
+// Focus emulation is intentionally fail-closed: falling back to Page.bringToFront
+// would violate the background-open contract.
+func DispatchNavigation(ctx context.Context, url string) error {
+ replaceInitialBlank, err := shouldReplaceInitialBlankNavigation(ctx)
+ if err != nil {
+ return fmt.Errorf("inspect initial navigation: %w", err)
+ }
+ return chromedp.Run(ctx, chromedp.ActionFunc(func(execCtx context.Context) error {
+ return dispatchBackgroundNavigation(execCtx, url, replaceInitialBlank)
+ }))
+}
+
+func dispatchBackgroundNavigation(ctx context.Context, url string, replaceInitialBlank bool) error {
+ if err := emulation.SetFocusEmulationEnabled(true).Do(ctx); err != nil {
+ return fmt.Errorf("enable background focus emulation: %w", err)
+ }
+ if err := page.SetWebLifecycleState(page.SetWebLifecycleStateStateActive).Do(ctx); err != nil {
+ return fmt.Errorf("activate background web lifecycle: %w", err)
+ }
+ return startNavigation(ctx, url, replaceInitialBlank)
+}
+
// waitForReadyStateAfterNavigation polls document.readyState every 200ms until it
// reaches "interactive" or "complete", returning nil; it returns ctx.Err() if the
// context ends first. readyState eval errors are ignored and retried.
diff --git a/internal/bridge/cdpops/navigation_background_test.go b/internal/bridge/cdpops/navigation_background_test.go
new file mode 100644
index 00000000..d38acfbb
--- /dev/null
+++ b/internal/bridge/cdpops/navigation_background_test.go
@@ -0,0 +1,88 @@
+package cdpops
+
+import (
+ "context"
+ "errors"
+ "reflect"
+ "testing"
+
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/emulation"
+ "github.com/chromedp/cdproto/page"
+ "github.com/chromedp/cdproto/target"
+)
+
+type backgroundNavigationExecutor struct {
+ methods []string
+ focusFlags []bool
+ emulationErr error
+ lifecycleErr error
+}
+
+func (e *backgroundNavigationExecutor) Execute(_ context.Context, method string, params, _ any) error {
+ e.methods = append(e.methods, method)
+ if method == emulation.CommandSetFocusEmulationEnabled {
+ e.focusFlags = append(e.focusFlags, params.(*emulation.SetFocusEmulationEnabledParams).Enabled)
+ return e.emulationErr
+ }
+ if method == page.CommandSetWebLifecycleState {
+ return e.lifecycleErr
+ }
+ return nil
+}
+
+func TestDispatchBackgroundNavigationEmulatesFocusWithoutActivatingTab(t *testing.T) {
+ exec := &backgroundNavigationExecutor{}
+ ctx := cdp.WithExecutor(context.Background(), exec)
+
+ if err := dispatchBackgroundNavigation(ctx, "https://example.test/", false); err != nil {
+ t.Fatalf("dispatch background navigation: %v", err)
+ }
+
+ wantMethods := []string{
+ emulation.CommandSetFocusEmulationEnabled,
+ page.CommandSetWebLifecycleState,
+ page.CommandNavigate,
+ }
+ if !reflect.DeepEqual(exec.methods, wantMethods) {
+ t.Fatalf("CDP methods = %v, want %v", exec.methods, wantMethods)
+ }
+ if !reflect.DeepEqual(exec.focusFlags, []bool{true}) {
+ t.Fatalf("focus emulation flags = %v, want [true]", exec.focusFlags)
+ }
+ for _, method := range exec.methods {
+ if method == page.CommandBringToFront || method == target.CommandActivateTarget {
+ t.Fatalf("background navigation activated the tab via %s", method)
+ }
+ }
+}
+
+func TestDispatchBackgroundNavigationFailsClosedWhenActiveLifecycleIsUnavailable(t *testing.T) {
+ exec := &backgroundNavigationExecutor{lifecycleErr: errors.New("unsupported")}
+ ctx := cdp.WithExecutor(context.Background(), exec)
+
+ err := dispatchBackgroundNavigation(ctx, "https://example.test/", false)
+ if err == nil {
+ t.Fatal("expected lifecycle error")
+ }
+ wantMethods := []string{
+ emulation.CommandSetFocusEmulationEnabled,
+ page.CommandSetWebLifecycleState,
+ }
+ if !reflect.DeepEqual(exec.methods, wantMethods) {
+ t.Fatalf("CDP methods after lifecycle failure = %v, want no navigation or activation", exec.methods)
+ }
+}
+
+func TestDispatchBackgroundNavigationFailsClosedWhenFocusEmulationIsUnavailable(t *testing.T) {
+ exec := &backgroundNavigationExecutor{emulationErr: errors.New("unsupported")}
+ ctx := cdp.WithExecutor(context.Background(), exec)
+
+ err := dispatchBackgroundNavigation(ctx, "https://example.test/", false)
+ if err == nil {
+ t.Fatal("expected focus-emulation error")
+ }
+ if !reflect.DeepEqual(exec.methods, []string{emulation.CommandSetFocusEmulationEnabled}) {
+ t.Fatalf("CDP methods after focus-emulation failure = %v, want no navigation or activation", exec.methods)
+ }
+}
diff --git a/internal/bridge/cdpops_facade.go b/internal/bridge/cdpops_facade.go
index ca018cae..ba6e4973 100644
--- a/internal/bridge/cdpops_facade.go
+++ b/internal/bridge/cdpops_facade.go
@@ -27,6 +27,10 @@ func NavigatePageWithRedirectLimit(ctx context.Context, url string, maxRedirects
return bridgecdpops.NavigatePageWithRedirectLimit(ctx, url, maxRedirects)
}
+func DispatchNavigation(ctx context.Context, url string) error {
+ return bridgecdpops.DispatchNavigation(ctx, url)
+}
+
func shouldReplaceBlankHistoryEntry(curURL string, cur int64, entryCount int) bool {
return bridgecdpops.ShouldReplaceBlankHistoryEntry(curURL, cur, entryCount)
}
diff --git a/internal/bridge/debugger_guard_test.go b/internal/bridge/debugger_guard_test.go
new file mode 100644
index 00000000..b7b403e9
--- /dev/null
+++ b/internal/bridge/debugger_guard_test.go
@@ -0,0 +1,303 @@
+package bridge
+
+import (
+ "context"
+ "errors"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/chromedp/cdproto"
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/debugger"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/stealth"
+)
+
+type debuggerCommand struct {
+ method string
+ params any
+}
+
+type debuggerRecorder struct {
+ commands []debuggerCommand
+ failAt string
+ failErr error
+}
+
+func (r *debuggerRecorder) Execute(_ context.Context, method string, params, _ any) error {
+ r.commands = append(r.commands, debuggerCommand{method: method, params: params})
+ if method == r.failAt {
+ if r.failErr != nil {
+ return r.failErr
+ }
+ return errors.New("injected CDP failure")
+ }
+ return nil
+}
+
+func TestWireTabManagerReappliesDebuggerGuardAfterReconnect(t *testing.T) {
+ recorder := &debuggerRecorder{}
+ ctx := cdp.WithExecutor(context.Background(), recorder)
+ b := &Bridge{}
+
+ for _, tabID := range []string{"attached-tab", "reconnected-tab"} {
+ b.TabManager = nil
+ b.wireTabManager(context.Background())
+ if b.TabManager.onTabSetup == nil {
+ t.Fatalf("wireTabManager(%q) omitted target setup", tabID)
+ }
+ if err := b.TabManager.onTabSetup(ctx, tabID); err != nil {
+ t.Fatalf("wired tab setup(%q): %v", tabID, err)
+ }
+ }
+
+ want := []string{
+ debugger.CommandEnable,
+ debugger.CommandSetSkipAllPauses,
+ debugger.CommandResume,
+ debugger.CommandEnable,
+ debugger.CommandSetSkipAllPauses,
+ debugger.CommandResume,
+ }
+ if len(recorder.commands) != len(want) {
+ t.Fatalf("CDP commands = %v, want %v", recorder.commands, want)
+ }
+ for i, method := range want {
+ if recorder.commands[i].method != method {
+ t.Fatalf("CDP command %d = %q, want %q", i, recorder.commands[i].method, method)
+ }
+ if method == debugger.CommandSetSkipAllPauses {
+ params, ok := recorder.commands[i].params.(*debugger.SetSkipAllPausesParams)
+ if !ok || !params.Skip {
+ t.Fatalf("CDP command %d must set skip=true, got %#v", i, recorder.commands[i].params)
+ }
+ }
+ }
+}
+
+func TestTabSetupAcceptsChromeAlreadyRunningResponse(t *testing.T) {
+ recorder := &debuggerRecorder{
+ failAt: debugger.CommandResume,
+ failErr: &cdproto.Error{
+ Code: -32000,
+ Message: "Can only perform operation while paused.",
+ },
+ }
+ ctx := cdp.WithExecutor(context.Background(), recorder)
+
+ if err := (&Bridge{}).tabSetup(ctx, "running-tab"); err != nil {
+ t.Fatalf("tabSetup rejected an already-running target: %v", err)
+ }
+}
+
+func TestTabSetupFailsClosedWhenSkipAllPausesFails(t *testing.T) {
+ recorder := &debuggerRecorder{failAt: debugger.CommandSetSkipAllPauses}
+ ctx := cdp.WithExecutor(context.Background(), recorder)
+
+ err := (&Bridge{}).tabSetup(ctx, "attached-tab")
+ if err == nil || !strings.Contains(err.Error(), "skip debugger pauses") {
+ t.Fatalf("tabSetup error = %v, want skip-debugger-pauses failure", err)
+ }
+
+ want := []string{
+ debugger.CommandEnable,
+ debugger.CommandSetSkipAllPauses,
+ debugger.CommandDisable,
+ }
+ if len(recorder.commands) != len(want) {
+ t.Fatalf("CDP commands = %v, want %v", recorder.commands, want)
+ }
+ for i, method := range want {
+ if recorder.commands[i].method != method {
+ t.Fatalf("CDP command %d = %q, want %q", i, recorder.commands[i].method, method)
+ }
+ }
+}
+
+func TestTabSetupFailsClosedWhenPausedTargetCannotResume(t *testing.T) {
+ recorder := &debuggerRecorder{failAt: debugger.CommandResume}
+ ctx := cdp.WithExecutor(context.Background(), recorder)
+
+ err := (&Bridge{}).tabSetup(ctx, "paused-tab")
+ if err == nil || !strings.Contains(err.Error(), "resume paused debugger") {
+ t.Fatalf("tabSetup error = %v, want resume-paused-debugger failure", err)
+ }
+
+ want := []string{
+ debugger.CommandEnable,
+ debugger.CommandSetSkipAllPauses,
+ debugger.CommandResume,
+ debugger.CommandDisable,
+ }
+ if len(recorder.commands) != len(want) {
+ t.Fatalf("CDP commands = %v, want %v", recorder.commands, want)
+ }
+ for i, method := range want {
+ if recorder.commands[i].method != method {
+ t.Fatalf("CDP command %d = %q, want %q", i, recorder.commands[i].method, method)
+ }
+ }
+}
+
+func TestManagedTargetSetupPropagatesDebuggerGuardFailure(t *testing.T) {
+ want := errors.New("guard unavailable")
+ tm := NewTabManager(nil, nil, nil, nil, func(context.Context, string) error { return want })
+
+ if _, err := tm.setupManagedTarget(context.Background(), "tab", "target"); !errors.Is(err, want) {
+ t.Fatalf("setupManagedTarget error = %v, want %v", err, want)
+ }
+}
+
+func TestAttachedTabSetupSkipsLaunchOnlyTargetMutations(t *testing.T) {
+ for _, mode := range []stealth.LaunchMode{stealth.LaunchModeAttached, stealth.LaunchModeRemoteCDP} {
+ t.Run(string(mode), func(t *testing.T) {
+ recorder := &debuggerRecorder{}
+ ctx := cdp.WithExecutor(context.Background(), recorder)
+ b := &Bridge{
+ Config: &config.RuntimeConfig{
+ NoAnimations: true,
+ StealthLevel: "full",
+ Cloak: config.CloakBrowserRuntimeConfig{Locale: "en-GB"},
+ },
+ stealthLaunchMode: mode,
+ }
+ b.ensureStealthBundle()
+
+ if err := b.tabSetup(ctx, "external-tab"); err != nil {
+ t.Fatal(err)
+ }
+ want := []string{debugger.CommandEnable, debugger.CommandSetSkipAllPauses, debugger.CommandResume}
+ if len(recorder.commands) != len(want) {
+ t.Fatalf("attach commands = %v, want debugger guard only %v", recorder.commands, want)
+ }
+ for i, command := range recorder.commands {
+ if command.method != want[i] {
+ t.Fatalf("attach command %d = %q, want %q", i, command.method, want[i])
+ }
+ }
+ status := b.StealthStatus()
+ if status == nil || !status.AttachMutationsSkipped {
+ t.Fatalf("attach status = %+v, want explicit skipped-mutations signal", status)
+ }
+ })
+ }
+}
+
+// This controlled local-Chromium test first reproduces the freeze boundary,
+// releases it, then proves the guard prevents the same statement from pausing.
+// It is opt-in so ordinary unit and race suites do not require a browser.
+func TestDebuggerPauseGuardLive(t *testing.T) {
+ if os.Getenv("PINCHTAB_DEBUGGER_GUARD_LIVE") != "1" {
+ t.Skip("set PINCHTAB_DEBUGGER_GUARD_LIVE=1 for the local Chromium proof")
+ }
+
+ chromePath, err := exec.LookPath("chromium")
+ if err != nil {
+ t.Fatal("chromium is required for the live debugger guard proof")
+ }
+ opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.ExecPath(chromePath))
+ allocCtx, allocCancel := chromedp.NewExecAllocator(context.Background(), opts...)
+ defer allocCancel()
+ tabCtx, tabCancel := chromedp.NewContext(allocCtx)
+ defer tabCancel()
+
+ if err := chromedp.Run(tabCtx); err != nil {
+ t.Fatalf("start local Chromium: %v", err)
+ }
+ paused := make(chan struct{}, 2)
+ chromedp.ListenTarget(tabCtx, func(ev any) {
+ if _, ok := ev.(*debugger.EventPaused); ok {
+ select {
+ case paused <- struct{}{}:
+ default:
+ }
+ }
+ })
+
+ if err := chromedp.Run(tabCtx, chromedp.ActionFunc(func(ctx context.Context) error {
+ if _, err := debugger.Enable().Do(ctx); err != nil {
+ return err
+ }
+ return debugger.SetSkipAllPauses(false).Do(ctx)
+ })); err != nil {
+ t.Fatalf("arm baseline debugger pause: %v", err)
+ }
+
+ baselineDone := make(chan error, 1)
+ go func() {
+ var result string
+ baselineDone <- chromedp.Run(tabCtx, chromedp.Evaluate(`(() => { debugger; return "baseline released"; })()`, &result))
+ }()
+
+ select {
+ case <-paused:
+ t.Log("baseline reproduced: debugger statement paused the attached target")
+ case err := <-baselineDone:
+ t.Fatalf("baseline did not pause; evaluation returned %v", err)
+ case <-time.After(3 * time.Second):
+ t.Fatal("baseline pause was not observed within 3s")
+ }
+
+ if err := chromedp.Run(tabCtx, chromedp.ActionFunc(preventDebuggerPauses)); err != nil {
+ t.Fatalf("install guard and release baseline pause: %v", err)
+ }
+ select {
+ case err := <-baselineDone:
+ if err != nil {
+ t.Fatalf("baseline evaluation after release: %v", err)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("baseline evaluation stayed frozen after release")
+ }
+ var guardedResult string
+ guardedCtx, guardedCancel := context.WithTimeout(tabCtx, 3*time.Second)
+ defer guardedCancel()
+ if err := chromedp.Run(guardedCtx, chromedp.Evaluate(`(() => { debugger; return "guarded"; })()`, &guardedResult)); err != nil {
+ t.Fatalf("guarded debugger statement: %v", err)
+ }
+ if guardedResult != "guarded" {
+ t.Fatalf("guarded result = %q, want guarded", guardedResult)
+ }
+ select {
+ case <-paused:
+ t.Fatal("guarded debugger statement still emitted a pause")
+ default:
+ }
+ t.Log("guarded pass: the same debugger statement completed without a pause")
+
+ newTargetCtx, newTargetCancel := chromedp.NewContext(allocCtx)
+ defer newTargetCancel()
+ newTargetPaused := make(chan struct{}, 1)
+ chromedp.ListenTarget(newTargetCtx, func(ev any) {
+ if _, ok := ev.(*debugger.EventPaused); ok {
+ select {
+ case newTargetPaused <- struct{}{}:
+ default:
+ }
+ }
+ })
+ var newTargetResult string
+ newTargetRunCtx, newTargetRunCancel := context.WithTimeout(newTargetCtx, 3*time.Second)
+ defer newTargetRunCancel()
+ if err := chromedp.Run(newTargetRunCtx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return (&Bridge{}).tabSetup(ctx, "new-target")
+ }),
+ chromedp.Evaluate(`(() => { debugger; return "new target guarded"; })()`, &newTargetResult),
+ ); err != nil {
+ t.Fatalf("new target debugger statement: %v", err)
+ }
+ if newTargetResult != "new target guarded" {
+ t.Fatalf("new target result = %q, want new target guarded", newTargetResult)
+ }
+ select {
+ case <-newTargetPaused:
+ t.Fatal("new target debugger statement emitted a pause")
+ default:
+ }
+ t.Log("new-target pass: per-target setup prevented the first debugger statement from pausing")
+}
diff --git a/internal/bridge/guards.go b/internal/bridge/guards.go
index b1521602..bff6b77e 100644
--- a/internal/bridge/guards.go
+++ b/internal/bridge/guards.go
@@ -50,7 +50,7 @@ func classifyActionError(err error) error {
}
func shouldCheckUnexpectedNavigation(req ActionRequest) bool {
- return !req.WaitNav
+ return !req.WaitNav && !IsSubmitClick(req.Kind, req)
}
func checkUnexpectedNavigation(before, after string) error {
diff --git a/internal/bridge/guards_test.go b/internal/bridge/guards_test.go
index cc9cd377..f47c121e 100644
--- a/internal/bridge/guards_test.go
+++ b/internal/bridge/guards_test.go
@@ -62,6 +62,9 @@ func TestShouldCheckUnexpectedNavigation(t *testing.T) {
if shouldCheckUnexpectedNavigation(ActionRequest{WaitNav: true}) {
t.Fatal("WaitNav=true should disable navigation guard")
}
+ if shouldCheckUnexpectedNavigation(ActionRequest{Kind: ActionClick, Submit: true}) {
+ t.Fatal("click submit should treat navigation as an expected post-state")
+ }
}
func TestReadActionURL_NoChromeDPContext(t *testing.T) {
diff --git a/internal/bridge/observe/network_buffer.go b/internal/bridge/observe/network_buffer.go
index 31a593c8..23886bde 100644
--- a/internal/bridge/observe/network_buffer.go
+++ b/internal/bridge/observe/network_buffer.go
@@ -303,6 +303,7 @@ func (nb *NetworkBuffer) Clear() {
nb.index = make(map[string]int)
nb.head = 0
nb.size = 0
+ nb.retainedBytes = 0
}
func (nb *NetworkBuffer) Len() int {
diff --git a/internal/bridge/observe/network_inflight_test.go b/internal/bridge/observe/network_inflight_test.go
index 09bf6dc6..f51908db 100644
--- a/internal/bridge/observe/network_inflight_test.go
+++ b/internal/bridge/observe/network_inflight_test.go
@@ -139,3 +139,21 @@ func TestNetworkBuffer_ClearPreservesInflight(t *testing.T) {
t.Errorf("Clear must not reset inflight: got count=%d, want 1", count)
}
}
+
+func TestNetworkBuffer_ClearResetsRetainedBytes(t *testing.T) {
+ buf := NewNetworkBuffer(10)
+ buf.Add(NetworkEntry{RequestID: "r1", URL: "https://example.com"})
+ buf.Update("r1", func(entry *NetworkEntry) {
+ entry.ResponseBody = "retained"
+ entry.BodyRetained = true
+ })
+ if got := buf.RetainedBytes(); got != int64(len("retained")) {
+ t.Fatalf("setup retained bytes = %d, want %d", got, len("retained"))
+ }
+
+ buf.Clear()
+
+ if got := buf.RetainedBytes(); got != 0 {
+ t.Fatalf("retained bytes after clear = %d, want 0", got)
+ }
+}
diff --git a/internal/bridge/runtime/init_attach.go b/internal/bridge/runtime/init_attach.go
index aa1170cd..36a59cd5 100644
--- a/internal/bridge/runtime/init_attach.go
+++ b/internal/bridge/runtime/init_attach.go
@@ -2,13 +2,20 @@ package runtime
import (
"context"
+ "errors"
"fmt"
"log/slog"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
"github.com/chromedp/chromedp"
+ "github.com/gobwas/ws"
"github.com/pinchtab/pinchtab/internal/browsers"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/stealth"
+ internalurls "github.com/pinchtab/pinchtab/internal/urls"
)
// initBrowserFromExistingCDP attaches the bridge to a browser that is already
@@ -34,8 +41,33 @@ func initBrowserFromExistingCDP(cfg *config.RuntimeConfig, bundle *stealth.Bundl
if err != nil {
return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("normalize cdpAttachUrl: %w", err)
}
- slog.Info("attaching to existing browser via CDP", "cdpUrl", wsURL)
+ slog.Info("attaching to existing browser via CDP", "cdpUrl", internalurls.RedactForLog(wsURL))
+ remoteAllocCtx, remoteAllocCancel, browserCtx, browserCancel, err := attachExistingCDP(wsURL)
+ if err == nil {
+ slog.Info("attached to existing browser via CDP", "cdpUrl", internalurls.RedactForLog(wsURL))
+ return remoteAllocCtx, remoteAllocCancel, browserCtx, browserCancel, stealth.LaunchModeAttached, nil
+ }
+
+ refreshedURL, refreshErr := refreshStaleCDPURL(cfg.CDPAttachURL, wsURL, err, cfg)
+ if refreshErr != nil {
+ return nil, nil, nil, nil, stealth.LaunchModeUninitialized,
+ fmt.Errorf("%w; stale CDP endpoint refresh failed: %v", err, refreshErr)
+ }
+ if refreshedURL == "" {
+ return nil, nil, nil, nil, stealth.LaunchModeUninitialized, err
+ }
+
+ slog.Info("retrying CDP attach after browser endpoint refresh", "cdpUrl", internalurls.RedactForLog(refreshedURL))
+ remoteAllocCtx, remoteAllocCancel, browserCtx, browserCancel, err = attachExistingCDP(refreshedURL)
+ if err != nil {
+ return nil, nil, nil, nil, stealth.LaunchModeUninitialized, err
+ }
+ slog.Info("attached to existing browser via refreshed CDP endpoint", "cdpUrl", internalurls.RedactForLog(refreshedURL))
+ return remoteAllocCtx, remoteAllocCancel, browserCtx, browserCancel, stealth.LaunchModeAttached, nil
+}
+
+func attachExistingCDP(wsURL string) (context.Context, context.CancelFunc, context.Context, context.CancelFunc, error) {
remoteAllocCtx, remoteAllocCancel, browserCtx, browserCancel := newRemoteCDPContexts(context.Background(), wsURL)
// Touch the browser so we fail fast if the CDP URL is unreachable. We
@@ -48,9 +80,43 @@ func initBrowserFromExistingCDP(cfg *config.RuntimeConfig, bundle *stealth.Bundl
})); err != nil {
browserCancel()
remoteAllocCancel()
- return nil, nil, nil, nil, stealth.LaunchModeUninitialized, fmt.Errorf("failed to attach to CDP at %s: %w", wsURL, err)
+ return nil, nil, nil, nil, fmt.Errorf("failed to attach to CDP at %s: %w", internalurls.RedactForLog(wsURL), err)
}
+ return remoteAllocCtx, remoteAllocCancel, browserCtx, browserCancel, nil
+}
- slog.Info("attached to existing browser via CDP", "cdpUrl", wsURL)
- return remoteAllocCtx, remoteAllocCancel, browserCtx, browserCancel, stealth.LaunchModeAttached, nil
+// refreshStaleCDPURL returns a fresh browser endpoint only when the dial got a
+// typed 404 and /json/version proves the browser GUID changed.
+func refreshStaleCDPURL(rawURL, staleURL string, attachErr error, cfg *config.RuntimeConfig) (string, error) {
+ var status ws.StatusError
+ if !errors.As(attachErr, &status) || status != ws.StatusError(http.StatusNotFound) {
+ return "", nil
+ }
+
+ parsed, err := url.Parse(strings.TrimSpace(rawURL))
+ if err != nil {
+ return "", err
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ probe, pinned, err := probeCDPVersionParsed(ctx, parsed, cfg.AttachAllowHosts, cfg.AttachAllowSchemes)
+ if err != nil {
+ return "", err
+ }
+ refreshedURL, err := normalizeResolvedDevToolsURL(probe.WebSocketDebuggerURL, parsed, pinned, cfg.AttachAllowHosts)
+ if err != nil {
+ return "", err
+ }
+ stale, err := url.Parse(staleURL)
+ if err != nil {
+ return "", err
+ }
+ refreshed, err := url.Parse(refreshedURL)
+ if err != nil {
+ return "", err
+ }
+ if stale.EscapedPath() == refreshed.EscapedPath() {
+ return "", nil
+ }
+ return refreshedURL, nil
}
diff --git a/internal/bridge/runtime/init_attach_stale_test.go b/internal/bridge/runtime/init_attach_stale_test.go
new file mode 100644
index 00000000..4144d600
--- /dev/null
+++ b/internal/bridge/runtime/init_attach_stale_test.go
@@ -0,0 +1,236 @@
+package runtime
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/gobwas/ws"
+ "github.com/gobwas/ws/wsutil"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestInitBrowserFromExistingCDPRefreshesStaleBrowserWebSocket(t *testing.T) {
+ var versionCalls, staleDials, freshDials atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/json/version":
+ id := "stale"
+ if versionCalls.Add(1) > 1 {
+ id = "fresh"
+ }
+ _, _ = fmt.Fprintf(w, `{"webSocketDebuggerUrl":"ws://%s/devtools/browser/%s"}`, r.Host, id)
+ case "/devtools/browser/stale":
+ staleDials.Add(1)
+ http.NotFound(w, r)
+ case "/devtools/browser/fresh":
+ freshDials.Add(1)
+ serveMinimalCDP(t, w, r)
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer server.Close()
+
+ cfg := &config.RuntimeConfig{
+ CDPAttachURL: server.URL,
+ AttachAllowSchemes: []string{"http"},
+ }
+ allocCtx, allocCancel, browserCtx, browserCancel, _, err := initBrowserFromExistingCDP(cfg, nil)
+ if err != nil {
+ t.Fatalf("attach did not refresh the stale browser WebSocket: %v", err)
+ }
+ if allocCtx == nil || browserCtx == nil {
+ t.Fatal("attach returned nil contexts")
+ }
+ browserCancel()
+ allocCancel()
+
+ if got := versionCalls.Load(); got != 2 {
+ t.Fatalf("/json/version calls = %d, want one initial resolution plus one refresh", got)
+ }
+ if got := staleDials.Load(); got != 1 {
+ t.Fatalf("stale WebSocket dials = %d, want 1", got)
+ }
+ if got := freshDials.Load(); got != 1 {
+ t.Fatalf("fresh WebSocket dials = %d, want 1", got)
+ }
+}
+
+func TestInitBrowserFromExistingCDPRefreshesSuppliedStaleBrowserWebSocket(t *testing.T) {
+ var versionCalls, staleDials, freshDials atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/json/version":
+ versionCalls.Add(1)
+ _, _ = fmt.Fprintf(w, `{"webSocketDebuggerUrl":"ws://%s/devtools/browser/fresh"}`, r.Host)
+ case "/devtools/browser/stale":
+ staleDials.Add(1)
+ http.NotFound(w, r)
+ case "/devtools/browser/fresh":
+ freshDials.Add(1)
+ serveMinimalCDP(t, w, r)
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer server.Close()
+
+ cfg := &config.RuntimeConfig{
+ CDPAttachURL: "ws://" + strings.TrimPrefix(server.URL, "http://") + "/devtools/browser/stale",
+ AttachAllowSchemes: []string{"ws"},
+ }
+ _, allocCancel, _, browserCancel, _, err := initBrowserFromExistingCDP(cfg, nil)
+ if err != nil {
+ t.Fatalf("attach did not refresh the supplied stale browser WebSocket: %v", err)
+ }
+ browserCancel()
+ allocCancel()
+
+ if got := versionCalls.Load(); got != 1 {
+ t.Fatalf("/json/version calls = %d, want 1 refresh", got)
+ }
+ if got := staleDials.Load(); got != 1 {
+ t.Fatalf("stale WebSocket dials = %d, want 1", got)
+ }
+ if got := freshDials.Load(); got != 1 {
+ t.Fatalf("fresh WebSocket dials = %d, want 1", got)
+ }
+}
+
+func TestInitBrowserFromExistingCDPRetriesStaleEndpointOnlyOnce(t *testing.T) {
+ var versionCalls, staleDials, freshDials atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/json/version":
+ id := "stale"
+ if versionCalls.Add(1) > 1 {
+ id = "fresh"
+ }
+ _, _ = fmt.Fprintf(w, `{"webSocketDebuggerUrl":"ws://%s/devtools/browser/%s"}`, r.Host, id)
+ case "/devtools/browser/stale":
+ staleDials.Add(1)
+ http.NotFound(w, r)
+ case "/devtools/browser/fresh":
+ freshDials.Add(1)
+ http.NotFound(w, r)
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer server.Close()
+
+ cfg := &config.RuntimeConfig{CDPAttachURL: server.URL, AttachAllowSchemes: []string{"http"}}
+ _, _, _, _, _, err := initBrowserFromExistingCDP(cfg, nil)
+ if err == nil {
+ t.Fatal("expected the refreshed endpoint's 404 to be returned")
+ }
+ if got := versionCalls.Load(); got != 2 {
+ t.Fatalf("/json/version calls = %d, want initial resolution plus one refresh", got)
+ }
+ if got := staleDials.Load(); got != 1 {
+ t.Fatalf("stale WebSocket dials = %d, want 1", got)
+ }
+ if got := freshDials.Load(); got != 1 {
+ t.Fatalf("fresh WebSocket dials = %d, want exactly 1", got)
+ }
+}
+
+func TestRefreshStaleCDPURLDoesNotRefreshOtherFailures(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ err error
+ }{
+ {name: "authentication rejection", err: fmt.Errorf("dial: %w", ws.StatusError(http.StatusUnauthorized))},
+ {name: "server failure", err: fmt.Errorf("dial: %w", ws.StatusError(http.StatusInternalServerError))},
+ {name: "connection failure", err: errors.New("connection refused")},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := refreshStaleCDPURL("http://127.0.0.1:1", "ws://127.0.0.1:1/devtools/browser/stale", tc.err, &config.RuntimeConfig{})
+ if err != nil {
+ t.Fatalf("unexpected refresh error: %v", err)
+ }
+ if got != "" {
+ t.Fatalf("refresh URL = %q, want none", got)
+ }
+ })
+ }
+}
+
+func TestRefreshStaleCDPURLRequiresChangedBrowserPath(t *testing.T) {
+ var versionCalls atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ versionCalls.Add(1)
+ _, _ = fmt.Fprintf(w, `{"webSocketDebuggerUrl":"ws://%s/devtools/browser/stale"}`, r.Host)
+ }))
+ defer server.Close()
+
+ staleURL := "ws://" + strings.TrimPrefix(server.URL, "http://") + "/devtools/browser/stale"
+ got, err := refreshStaleCDPURL(
+ server.URL,
+ staleURL,
+ fmt.Errorf("dial: %w", ws.StatusError(http.StatusNotFound)),
+ &config.RuntimeConfig{AttachAllowSchemes: []string{"http"}},
+ )
+ if err != nil {
+ t.Fatalf("unexpected refresh error: %v", err)
+ }
+ if got != "" {
+ t.Fatalf("refresh URL = %q, want none for the unchanged browser path", got)
+ }
+ if got := versionCalls.Load(); got != 1 {
+ t.Fatalf("/json/version calls = %d, want 1 proof check", got)
+ }
+}
+
+func serveMinimalCDP(t *testing.T, w http.ResponseWriter, r *http.Request) {
+ t.Helper()
+ conn, _, _, err := ws.UpgradeHTTP(r, w)
+ if err != nil {
+ t.Errorf("upgrade fresh WebSocket: %v", err)
+ return
+ }
+ defer func() { _ = conn.Close() }()
+
+ for {
+ payload, op, err := wsutil.ReadClientData(conn)
+ if err != nil {
+ return
+ }
+ if op != ws.OpText {
+ continue
+ }
+ var command struct {
+ ID int64 `json:"id"`
+ Method string `json:"method"`
+ SessionID string `json:"sessionId,omitempty"`
+ }
+ if err := json.Unmarshal(payload, &command); err != nil {
+ t.Errorf("decode CDP command: %v", err)
+ return
+ }
+
+ result := `{}`
+ switch command.Method {
+ case "Target.createTarget":
+ result = `{"targetId":"page-1"}`
+ case "Target.attachToTarget":
+ result = `{"sessionId":"session-1"}`
+ case "Runtime.evaluate":
+ result = `{"result":{"type":"object","className":"Window"}}`
+ }
+ response := fmt.Sprintf(`{"id":%d,"result":%s`, command.ID, result)
+ if command.SessionID != "" {
+ response += fmt.Sprintf(`,"sessionId":%q`, command.SessionID)
+ }
+ response += `}`
+ if err := wsutil.WriteServerMessage(conn, ws.OpText, []byte(response)); err != nil {
+ return
+ }
+ }
+}
diff --git a/internal/bridge/screenshot.go b/internal/bridge/screenshot.go
index c0bf2ac5..85e09d15 100644
--- a/internal/bridge/screenshot.go
+++ b/internal/bridge/screenshot.go
@@ -4,7 +4,10 @@ import (
"context"
"encoding/json"
"fmt"
+ "time"
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/cdptk"
@@ -167,6 +170,26 @@ func captureFromSurface(beyondViewport bool, clip *page.Viewport) bool {
return clip != nil && clip.Scale != 0 && clip.Scale != 1
}
+// captureScreenshotWithoutActivation wakes a background renderer without
+// activating its tab in the operator's browser. Chromium supports focus
+// emulation on attached targets; providers that reject it retain the historical
+// BringToFront fallback so capture availability does not regress.
+func captureScreenshotWithoutActivation(ctx context.Context, shot *page.CaptureScreenshotParams) ([]byte, error) {
+ executor := cdp.ExecutorFromContext(ctx)
+ focusEmulated := emulation.SetFocusEmulationEnabled(true).Do(ctx) == nil
+ if focusEmulated {
+ defer func() {
+ restoreCtx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ restoreCtx = cdp.WithExecutor(restoreCtx, executor)
+ _ = emulation.SetFocusEmulationEnabled(false).Do(restoreCtx)
+ }()
+ } else {
+ _ = page.BringToFront().Do(ctx)
+ }
+ return shot.Do(ctx)
+}
+
// CaptureScreenshot runs Page.captureScreenshot with the supplied options.
// Quality is applied only for JPEG; clip and beyondViewport are mutually
// exclusive (clip wins) — the same rule the handler enforces on input.
@@ -198,15 +221,6 @@ func CaptureScreenshot(ctx context.Context, opts ScreenshotOpts) ([]byte, error)
var buf []byte
err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
- // Wake the target's renderer before capturing. Background / non-foreground
- // tabs (common once target-aware orchestration spreads tabs across
- // providers) throttle their compositor and stop painting, so
- // captureScreenshot blocks until the action deadline (~30s). A best-effort
- // BringToFront resumes painting for the target we are about to capture; the
- // error is ignored so providers whose CDP proxy does not implement it
- // (e.g. Cloak) still capture normally.
- _ = page.BringToFront().Do(ctx)
-
shot := page.CaptureScreenshot().WithFormat(opts.Format).WithFromSurface(fromSurface)
if clip != nil {
shot = shot.WithClip(clip)
@@ -218,7 +232,7 @@ func CaptureScreenshot(ctx context.Context, opts ScreenshotOpts) ([]byte, error)
shot = shot.WithQuality(int64(opts.Quality))
}
var inner error
- buf, inner = shot.Do(ctx)
+ buf, inner = captureScreenshotWithoutActivation(ctx, shot)
return inner
}))
return buf, err
@@ -323,8 +337,8 @@ func ScreenshotClipForNode(ctx context.Context, nodeID int64) (*ScreenshotClip,
// CaptureScreenshot is the provider-aware entry point used across the BridgeAPI
// (screencast polling, recorder, annotated capture). It delegates to the shared
// package-level CaptureScreenshot engine so every provider gets the same
-// rendering path, including the BringToFront + WithFromSurface(false) fixes that
-// keep headed browsers (e.g. Cloak) from blocking on an idle compositor surface.
+// rendering path, including non-activating focus emulation and
+// WithFromSurface(false), so headed browsers can paint without stealing focus.
func (b *Bridge) CaptureScreenshot(ctx context.Context, format string, quality int, clip *cdptk.ScreenshotClip) ([]byte, error) {
cdpFormat := page.CaptureScreenshotFormatJpeg
if format == "png" {
diff --git a/internal/bridge/screenshot_test.go b/internal/bridge/screenshot_test.go
index a425e217..f4493c7c 100644
--- a/internal/bridge/screenshot_test.go
+++ b/internal/bridge/screenshot_test.go
@@ -1,11 +1,71 @@
package bridge
import (
+ "context"
+ "errors"
+ "reflect"
"testing"
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/page"
)
+type screenshotExecutor struct {
+ methods []string
+ focusFlags []bool
+ captureErr error
+}
+
+func (e *screenshotExecutor) Execute(_ context.Context, method string, params, result any) error {
+ e.methods = append(e.methods, method)
+ if method == emulation.CommandSetFocusEmulationEnabled {
+ e.focusFlags = append(e.focusFlags, params.(*emulation.SetFocusEmulationEnabledParams).Enabled)
+ return nil
+ }
+ if method == page.CommandCaptureScreenshot {
+ if e.captureErr != nil {
+ return e.captureErr
+ }
+ result.(*page.CaptureScreenshotReturns).Data = "cG5n"
+ }
+ return nil
+}
+
+func TestCaptureScreenshotWithoutActivationRestoresFocusEmulation(t *testing.T) {
+ exec := &screenshotExecutor{}
+ ctx := cdp.WithExecutor(context.Background(), exec)
+ got, err := captureScreenshotWithoutActivation(ctx, page.CaptureScreenshot())
+ if err != nil {
+ t.Fatalf("capture: %v", err)
+ }
+ if string(got) != "png" {
+ t.Fatalf("capture bytes = %q, want png", got)
+ }
+ wantMethods := []string{
+ emulation.CommandSetFocusEmulationEnabled,
+ page.CommandCaptureScreenshot,
+ emulation.CommandSetFocusEmulationEnabled,
+ }
+ if !reflect.DeepEqual(exec.methods, wantMethods) {
+ t.Fatalf("CDP methods = %v, want %v", exec.methods, wantMethods)
+ }
+ if !reflect.DeepEqual(exec.focusFlags, []bool{true, false}) {
+ t.Fatalf("focus flags = %v, want [true false]", exec.focusFlags)
+ }
+}
+
+func TestCaptureScreenshotWithoutActivationRestoresAfterCaptureError(t *testing.T) {
+ exec := &screenshotExecutor{captureErr: errors.New("capture failed")}
+ ctx := cdp.WithExecutor(context.Background(), exec)
+ if _, err := captureScreenshotWithoutActivation(ctx, page.CaptureScreenshot()); err == nil {
+ t.Fatal("expected capture error")
+ }
+ if !reflect.DeepEqual(exec.focusFlags, []bool{true, false}) {
+ t.Fatalf("focus flags = %v, want [true false]", exec.focusFlags)
+ }
+}
+
func TestClampScale(t *testing.T) {
cases := []struct {
in, want float64
diff --git a/internal/bridge/tab_adopt.go b/internal/bridge/tab_adopt.go
index abc215f2..1f9b95a8 100644
--- a/internal/bridge/tab_adopt.go
+++ b/internal/bridge/tab_adopt.go
@@ -36,9 +36,20 @@ func (tm *TabManager) tabBlockPatterns() []string {
return blockPatterns
}
-func (tm *TabManager) setupManagedTarget(ctx context.Context, tabID, rawCDPID string) bool {
+func (tm *TabManager) setupManagedTarget(ctx context.Context, tabID, rawCDPID string) (bool, error) {
if tm.onTabSetup != nil {
- tm.onTabSetup(ctx, tabID)
+ var err error
+ if chromedp.FromContext(ctx) == nil {
+ // Preserve the direct-executor seam used by focused unit tests.
+ err = tm.onTabSetup(ctx, tabID)
+ } else {
+ err = chromedp.Run(ctx, chromedp.ActionFunc(func(execCtx context.Context) error {
+ return tm.onTabSetup(execCtx, tabID)
+ }))
+ }
+ if err != nil {
+ return false, err
+ }
}
if blockPatterns := tm.tabBlockPatterns(); len(blockPatterns) > 0 {
if err := SetResourceBlocking(ctx, blockPatterns); err != nil {
@@ -61,7 +72,7 @@ func (tm *TabManager) setupManagedTarget(ctx context.Context, tabID, rawCDPID st
if consoleEnabled {
tm.setupConsoleCapture(ctx, rawCDPID)
}
- return consoleEnabled
+ return consoleEnabled, nil
}
func (tm *TabManager) enforceAdoptTabLimit() error {
@@ -128,7 +139,11 @@ func (tm *TabManager) adoptExistingTarget(targetID target.ID, enforceLimit bool)
}
ctx, cancel := chromedp.NewContext(tm.browserCtx, chromedp.WithTargetID(targetID))
- consoleEnabled := tm.setupManagedTarget(ctx, tabID, rawCDPID)
+ consoleEnabled, err := tm.setupManagedTarget(ctx, tabID, rawCDPID)
+ if err != nil {
+ cancel()
+ return "", fmt.Errorf("setup tab %s: %w", tabID, err)
+ }
now := time.Now()
tm.mu.Lock()
diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.go
index 1563765a..54dd69fd 100644
--- a/internal/bridge/tab_manager.go
+++ b/internal/bridge/tab_manager.go
@@ -28,7 +28,7 @@ const (
tabCreateNavTimeout = 20 * time.Second
)
-type TabSetupFunc func(ctx context.Context, tabID string)
+type TabSetupFunc func(ctx context.Context, tabID string) error
type TabManager struct {
browserCtx context.Context
@@ -130,6 +130,17 @@ func browserExecutorContext(ctx context.Context) (context.Context, error) {
}
func (tm *TabManager) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {
+ return tm.createTab(url, "")
+}
+
+func (tm *TabManager) CreateTabInBrowserContext(url, browserContextID string) (string, context.Context, context.CancelFunc, error) {
+ if browserContextID == "" {
+ return "", nil, nil, fmt.Errorf("browser context id required")
+ }
+ return tm.createTab(url, browserContextID)
+}
+
+func (tm *TabManager) createTab(url, browserContextID string) (string, context.Context, context.CancelFunc, error) {
if tm == nil {
return "", nil, nil, fmt.Errorf("tab manager not initialized")
}
@@ -162,16 +173,20 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.Ca
}
// target.CreateTarget works for both local and remote (CDP_URL) allocators.
- // WithBackground(true): open the new tab WITHOUT raising/activating the
- // browser window, so automation never steals the operator's foreground
- // focus. The browser stays fully visible (non-headless) -- only the
- // focus-grab is suppressed. (newWindow stays false, which background requires.)
+ // Chromium's explicit focus=false contract opens a normal rendered tab while
+ // leaving the browser window's OS focus unchanged. Do not set background=true:
+ // heavy headed SPAs can suspend that target before DOM/AX reads. newWindow
+ // remains false, so no additional OS window is created.
var targetID target.ID
createCtx, createCancel := context.WithTimeout(tm.browserCtx, tabCreateTimeout)
if err := chromedp.Run(createCtx,
chromedp.ActionFunc(func(ctx context.Context) error {
+ params := target.CreateTarget("about:blank").WithFocus(false)
+ if browserContextID != "" {
+ params = params.WithBrowserContextID(cdp.BrowserContextID(browserContextID))
+ }
var err error
- targetID, err = target.CreateTarget("about:blank").WithBackground(true).Do(ctx)
+ targetID, err = params.Do(ctx)
return err
}),
); err != nil {
@@ -191,7 +206,15 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.Ca
tabID := tm.idMgr.TabIDFromCDPTarget(rawCDPID)
if tm.onTabSetup != nil {
- tm.onTabSetup(ctx, tabID)
+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(execCtx context.Context) error {
+ return tm.onTabSetup(execCtx, tabID)
+ })); err != nil {
+ cancel()
+ if execCtx, execErr := browserExecutorContext(tm.browserCtx); execErr == nil {
+ _ = target.CloseTarget(targetID).Do(execCtx)
+ }
+ return "", nil, nil, fmt.Errorf("setup new tab: %w", err)
+ }
}
if blockPatterns := tm.tabBlockPatterns(); len(blockPatterns) > 0 {
diff --git a/internal/bridge/tab_manager_background_test.go b/internal/bridge/tab_manager_background_test.go
new file mode 100644
index 00000000..715ef270
--- /dev/null
+++ b/internal/bridge/tab_manager_background_test.go
@@ -0,0 +1,145 @@
+package bridge
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/target"
+ "github.com/chromedp/chromedp"
+ "github.com/gobwas/ws"
+ "github.com/gobwas/ws/wsutil"
+)
+
+func TestCreateTabRequestsRenderedTargetWithoutWindowFocus(t *testing.T) {
+ created := make(chan json.RawMessage, 1)
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ conn, _, _, err := ws.UpgradeHTTP(r, w)
+ if err != nil {
+ return
+ }
+ defer conn.Close()
+
+ for {
+ payload, op, err := wsutil.ReadClientData(conn)
+ if err != nil {
+ return
+ }
+ if op != ws.OpText {
+ continue
+ }
+
+ var command struct {
+ ID int64 `json:"id"`
+ Method string `json:"method"`
+ Params json.RawMessage `json:"params"`
+ SessionID string `json:"sessionId,omitempty"`
+ }
+ if json.Unmarshal(payload, &command) != nil {
+ return
+ }
+
+ result := `{}`
+ switch command.Method {
+ case "Target.attachToTarget":
+ result = `{"sessionId":"session-existing"}`
+ case "Runtime.evaluate":
+ result = `{"result":{"type":"object","className":"Window"}}`
+ case "Page.getFrameTree":
+ result = `{"frameTree":{"frame":{"id":"frame-existing","url":"about:blank"}}}`
+ case "DOM.getDocument":
+ result = `{"root":{"nodeId":1,"backendNodeId":1,"nodeType":9,"nodeName":"#document","localName":"","nodeValue":""}}`
+ case "Target.createTarget":
+ created <- append(json.RawMessage(nil), command.Params...)
+ result = `{"targetId":"created-tab"}`
+ }
+
+ response := fmt.Sprintf(`{"id":%d,"result":%s`, command.ID, result)
+ if command.SessionID != "" {
+ response += fmt.Sprintf(`,"sessionId":%q`, command.SessionID)
+ }
+ if wsutil.WriteServerMessage(conn, ws.OpText, []byte(response+`}`)) != nil {
+ return
+ }
+ }
+ }))
+ defer server.Close()
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/devtools/browser/test"
+ allocCtx, allocCancel := chromedp.NewRemoteAllocator(ctx, wsURL, chromedp.NoModifyURL)
+ defer allocCancel()
+ browserCtx, browserCancel := chromedp.NewContext(allocCtx, chromedp.WithTargetID(target.ID("existing-tab")))
+ defer browserCancel()
+ if err := chromedp.Run(browserCtx); err != nil {
+ t.Fatalf("initialize browser context: %v", err)
+ }
+
+ setupCalled := false
+ tm := NewTabManager(browserCtx, nil, nil, nil, func(ctx context.Context, _ string) error {
+ if cdp.ExecutorFromContext(ctx) == nil {
+ return fmt.Errorf("tab setup received no target executor")
+ }
+ setupCalled = true
+ return nil
+ })
+ _, _, tabCancel, err := tm.CreateTabInBrowserContext("about:blank", "context-profile")
+ if err != nil {
+ t.Fatalf("CreateTab: %v", err)
+ }
+ if !setupCalled {
+ t.Fatal("CreateTab did not run target setup")
+ }
+ defer tabCancel()
+
+ var params struct {
+ Background *bool `json:"background"`
+ NewWindow *bool `json:"newWindow"`
+ Focus *bool `json:"focus"`
+ BrowserContextID string `json:"browserContextId"`
+ }
+ select {
+ case raw := <-created:
+ if err := json.Unmarshal(raw, &params); err != nil {
+ t.Fatalf("decode Target.createTarget params: %v", err)
+ }
+ case <-ctx.Done():
+ t.Fatalf("Target.createTarget request not observed: %v", ctx.Err())
+ }
+
+ if params.Background != nil && *params.Background {
+ t.Fatal("Target.createTarget background = true, want absent or false for a rendered tab")
+ }
+ if params.NewWindow != nil && *params.NewWindow {
+ t.Fatal("Target.createTarget newWindow = true, want absent or false")
+ }
+ if params.Focus != nil && *params.Focus {
+ t.Fatal("Target.createTarget focus = true, want absent or false")
+ }
+ if params.BrowserContextID != "context-profile" {
+ t.Fatalf("Target.createTarget browserContextId = %q, want context-profile", params.BrowserContextID)
+ }
+
+ adoptSetupCalled := false
+ adoptTM := NewTabManager(browserCtx, nil, nil, nil, func(ctx context.Context, _ string) error {
+ if cdp.ExecutorFromContext(ctx) == nil {
+ return fmt.Errorf("adopted tab setup received no target executor")
+ }
+ adoptSetupCalled = true
+ return nil
+ })
+ if _, err := adoptTM.adoptExistingTarget(target.ID("created-tab"), false); err != nil {
+ t.Fatalf("adoptExistingTarget: %v", err)
+ }
+ if !adoptSetupCalled {
+ t.Fatal("adoptExistingTarget did not run target setup")
+ }
+}
diff --git a/internal/bridgeregistry/registry.go b/internal/bridgeregistry/registry.go
new file mode 100644
index 00000000..4cdd4d68
--- /dev/null
+++ b/internal/bridgeregistry/registry.go
@@ -0,0 +1,363 @@
+package bridgeregistry
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io/fs"
+ "net"
+ "net/url"
+ "os"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/shirou/gopsutil/v4/process"
+)
+
+const registryDir = "bridges"
+
+// Record is the durable, non-secret identity of one standalone bridge.
+type Record struct {
+ PID int `json:"pid"`
+ ProcessStartUnixMillis int64 `json:"processStartUnixMillis"`
+ Address string `json:"address"`
+ Port string `json:"port"`
+ CDPIdentity string `json:"cdpIdentity"`
+ BrowserType string `json:"browserType"`
+ BrowserLabel string `json:"browserLabel"`
+ RegisteredAt time.Time `json:"registeredAt"`
+}
+
+// State adds current process and listener evidence to a durable record.
+type State struct {
+ Record
+ Status string `json:"status"`
+ PIDStatus string `json:"pidStatus"`
+ Reachable bool `json:"reachable"`
+ Live bool `json:"live"`
+ Stale bool `json:"stale"`
+ Pruned bool `json:"pruned,omitempty"`
+}
+
+// Registration removes only its own record when closed.
+type Registration struct {
+ root *os.Root
+ name string
+ once sync.Once
+ err error
+}
+
+// Register atomically creates a private record under stateDir/bridges.
+func Register(stateDir string, rec Record) (*Registration, error) {
+ root, err := openRegistry(stateDir, true)
+ if err != nil {
+ return nil, err
+ }
+
+ rec.PID = os.Getpid()
+ rec.ProcessStartUnixMillis, err = processStart(rec.PID)
+ if err != nil {
+ _ = root.Close()
+ return nil, fmt.Errorf("read bridge process identity: %w", err)
+ }
+ rec.Address = strings.TrimSpace(rec.Address)
+ rec.Port = strings.TrimSpace(rec.Port)
+ rec.CDPIdentity = SafeCDPIdentity(rec.CDPIdentity)
+ rec.BrowserType = strings.TrimSpace(rec.BrowserType)
+ rec.BrowserLabel = strings.TrimSpace(rec.BrowserLabel)
+ rec.RegisteredAt = time.Now().UTC()
+ if err := validateRecord(rec); err != nil {
+ _ = root.Close()
+ return nil, err
+ }
+
+ id, err := randomID()
+ if err != nil {
+ _ = root.Close()
+ return nil, fmt.Errorf("generate bridge record id: %w", err)
+ }
+ name := fmt.Sprintf("bridge-%d-%s.json", rec.PID, id)
+ if err := writeAtomic(root, name, rec, id); err != nil {
+ _ = root.Close()
+ return nil, err
+ }
+ return &Registration{root: root, name: name}, nil
+}
+
+// Close removes the registration file without signaling or otherwise touching
+// the bridge process.
+func (r *Registration) Close() error {
+ if r == nil || r.root == nil {
+ return nil
+ }
+ r.once.Do(func() {
+ if err := r.root.Remove(r.name); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ r.err = err
+ }
+ if err := r.root.Close(); r.err == nil {
+ r.err = err
+ }
+ })
+ return r.err
+}
+
+// List returns every bridge record with fresh liveness evidence. When prune is
+// true it removes only records whose original PID is conclusively dead or has
+// been reused; it never signals a process.
+func List(stateDir string, prune bool) ([]State, error) {
+ root, err := openRegistry(stateDir, false)
+ if errors.Is(err, fs.ErrNotExist) {
+ return []State{}, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = root.Close() }()
+
+ entries, err := fs.ReadDir(root.FS(), ".")
+ if err != nil {
+ return nil, fmt.Errorf("read bridge registry: %w", err)
+ }
+ states := make([]State, 0, len(entries))
+ for _, entry := range entries {
+ name := entry.Name()
+ if entry.Type()&fs.ModeSymlink != 0 || !strings.HasPrefix(name, "bridge-") || !strings.HasSuffix(name, ".json") {
+ continue
+ }
+ info, err := root.Lstat(name)
+ if errors.Is(err, fs.ErrNotExist) {
+ continue
+ }
+ if err != nil {
+ return nil, fmt.Errorf("inspect bridge record %q: %w", name, err)
+ }
+ if !info.Mode().IsRegular() {
+ continue
+ }
+ data, err := root.ReadFile(name)
+ if errors.Is(err, fs.ErrNotExist) {
+ continue
+ }
+ if err != nil {
+ return nil, fmt.Errorf("read bridge record %q: %w", name, err)
+ }
+ var rec Record
+ if err := json.Unmarshal(data, &rec); err != nil {
+ return nil, fmt.Errorf("decode bridge record %q: %w", name, err)
+ }
+ state := inspect(rec)
+ if prune && (state.PIDStatus == "dead" || state.PIDStatus == "reused") {
+ if err := root.Remove(name); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ return nil, fmt.Errorf("prune bridge record %q: %w", name, err)
+ }
+ state.Pruned = true
+ }
+ states = append(states, state)
+ }
+
+ sort.Slice(states, func(i, j int) bool {
+ pi, _ := strconv.Atoi(states[i].Port)
+ pj, _ := strconv.Atoi(states[j].Port)
+ if pi != pj {
+ return pi < pj
+ }
+ if states[i].PID != states[j].PID {
+ return states[i].PID < states[j].PID
+ }
+ return states[i].RegisteredAt.Before(states[j].RegisteredAt)
+ })
+ return states, nil
+}
+
+// SafeCDPIdentity preserves enough identity to spot bridges attached to the
+// same browser while dropping credentials, query strings, fragments, and the
+// raw browser GUID.
+func SafeCDPIdentity(raw string) string {
+ u, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil || u.Scheme == "" || u.Hostname() == "" {
+ return ""
+ }
+ host := strings.ToLower(u.Hostname())
+ if port := u.Port(); port != "" {
+ host = net.JoinHostPort(host, port)
+ } else if strings.Contains(host, ":") {
+ host = "[" + host + "]"
+ }
+ identity := strings.ToLower(u.Scheme) + "://" + host
+ const marker = "/devtools/browser/"
+ if idx := strings.Index(u.Path, marker); idx >= 0 {
+ browserID := strings.Split(strings.TrimPrefix(u.Path[idx:], marker), "/")[0]
+ if browserID != "" {
+ sum := sha256.Sum256([]byte(browserID))
+ identity += marker + hex.EncodeToString(sum[:6])
+ }
+ }
+ return identity
+}
+
+func openRegistry(stateDir string, create bool) (*os.Root, error) {
+ stateDir = strings.TrimSpace(stateDir)
+ if stateDir == "" {
+ return nil, fmt.Errorf("bridge registry requires a state directory")
+ }
+ if create {
+ if err := os.MkdirAll(stateDir, 0o700); err != nil {
+ return nil, fmt.Errorf("create state directory: %w", err)
+ }
+ }
+ stateRoot, err := os.OpenRoot(stateDir)
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = stateRoot.Close() }()
+ if create {
+ if err := stateRoot.MkdirAll(registryDir, 0o700); err != nil {
+ return nil, fmt.Errorf("create bridge registry: %w", err)
+ }
+ info, err := stateRoot.Lstat(registryDir)
+ if err != nil {
+ return nil, err
+ }
+ if !info.IsDir() || info.Mode()&fs.ModeSymlink != 0 {
+ return nil, fmt.Errorf("bridge registry is not a real directory")
+ }
+ if err := stateRoot.Chmod(registryDir, 0o700); err != nil {
+ return nil, fmt.Errorf("secure bridge registry: %w", err)
+ }
+ }
+ root, err := stateRoot.OpenRoot(registryDir)
+ if err != nil {
+ return nil, err
+ }
+ return root, nil
+}
+
+func writeAtomic(root *os.Root, name string, rec Record, id string) error {
+ data, err := json.Marshal(rec)
+ if err != nil {
+ return fmt.Errorf("encode bridge record: %w", err)
+ }
+ tmp := ".bridge-" + id + ".tmp"
+ f, err := root.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
+ if err != nil {
+ return fmt.Errorf("create bridge record: %w", err)
+ }
+ ok := false
+ defer func() {
+ _ = f.Close()
+ if !ok {
+ _ = root.Remove(tmp)
+ }
+ }()
+ if err := f.Chmod(0o600); err != nil {
+ return fmt.Errorf("secure bridge record: %w", err)
+ }
+ if _, err := f.Write(append(data, '\n')); err != nil {
+ return fmt.Errorf("write bridge record: %w", err)
+ }
+ if err := f.Sync(); err != nil {
+ return fmt.Errorf("sync bridge record: %w", err)
+ }
+ if err := f.Close(); err != nil {
+ return fmt.Errorf("close bridge record: %w", err)
+ }
+ if err := root.Rename(tmp, name); err != nil {
+ return fmt.Errorf("publish bridge record: %w", err)
+ }
+ ok = true
+ return nil
+}
+
+func validateRecord(rec Record) error {
+ if rec.Address == "" {
+ return fmt.Errorf("bridge registry requires an address")
+ }
+ port, err := strconv.Atoi(rec.Port)
+ if err != nil || port < 1 || port > 65535 {
+ return fmt.Errorf("bridge registry has invalid port %q", rec.Port)
+ }
+ if rec.BrowserType == "" {
+ return fmt.Errorf("bridge registry requires a browser type")
+ }
+ return nil
+}
+
+func inspect(rec Record) State {
+ pidStatus := processStatus(rec)
+ reachable := listenerReachable(rec.Address, rec.Port)
+ state := State{Record: rec, PIDStatus: pidStatus, Reachable: reachable}
+ switch {
+ case pidStatus == "dead":
+ state.Status, state.Stale = "stale_pid", true
+ case pidStatus == "reused":
+ state.Status, state.Stale = "stale_pid_reused", true
+ case pidStatus == "unknown":
+ state.Status = "unknown_pid"
+ case !reachable:
+ state.Status, state.Stale = "stale_listener", true
+ default:
+ state.Status, state.Live = "live", true
+ }
+ return state
+}
+
+func processStatus(rec Record) string {
+ if rec.PID <= 0 {
+ return "dead"
+ }
+ exists, err := process.PidExists(int32(rec.PID))
+ if err != nil {
+ return "unknown"
+ }
+ if !exists {
+ return "dead"
+ }
+ if rec.ProcessStartUnixMillis <= 0 {
+ return "unknown"
+ }
+ started, err := processStart(rec.PID)
+ if err != nil {
+ return "unknown"
+ }
+ if started != rec.ProcessStartUnixMillis {
+ return "reused"
+ }
+ return "alive"
+}
+
+func processStart(pid int) (int64, error) {
+ p, err := process.NewProcess(int32(pid))
+ if err != nil {
+ return 0, err
+ }
+ return p.CreateTime()
+}
+
+func listenerReachable(address, port string) bool {
+ host := strings.Trim(strings.TrimSpace(address), "[]")
+ if host == "" || host == "0.0.0.0" {
+ host = "127.0.0.1"
+ } else if host == "::" {
+ host = "::1"
+ }
+ conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), 250*time.Millisecond)
+ if err != nil {
+ return false
+ }
+ _ = conn.Close()
+ return true
+}
+
+func randomID() (string, error) {
+ b := make([]byte, 8)
+ if _, err := rand.Read(b); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(b), nil
+}
diff --git a/internal/bridgeregistry/registry_test.go b/internal/bridgeregistry/registry_test.go
new file mode 100644
index 00000000..e52d5ec3
--- /dev/null
+++ b/internal/bridgeregistry/registry_test.go
@@ -0,0 +1,174 @@
+package bridgeregistry
+
+import (
+ "encoding/json"
+ "net"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+func TestSafeCDPIdentityDropsSecretsAndKeepsBrowserIdentity(t *testing.T) {
+ raw := "ws://user:[email protected]:9222/devtools/browser/browser-guid?token=secret#fragment"
+ got := SafeCDPIdentity(raw)
+ for _, secret := range []string{"user", "password", "browser-guid", "token", "secret", "fragment"} {
+ if strings.Contains(got, secret) {
+ t.Fatalf("SafeCDPIdentity(%q) leaked %q in %q", raw, secret, got)
+ }
+ }
+ if got == SafeCDPIdentity("ws://127.0.0.1:9222/devtools/browser/other-guid") {
+ t.Fatal("different external browsers produced the same identity")
+ }
+ if got != SafeCDPIdentity("ws://127.0.0.1:9222/devtools/browser/browser-guid?other=value") {
+ t.Fatal("query-only differences changed the external browser identity")
+ }
+ if got := SafeCDPIdentity("https://user:[email protected]:9443/json/version?access_token=nope"); got != "https://cdp.example:9443" {
+ t.Fatalf("HTTP identity = %q, want sanitized origin", got)
+ }
+}
+
+func TestRegisterListAndClose(t *testing.T) {
+ stateDir := t.TempDir()
+ listener, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ port := listener.Addr().(*net.TCPAddr).Port
+
+ registration, err := Register(stateDir, Record{
+ Address: "127.0.0.1",
+ Port: strconv.Itoa(port),
+ CDPIdentity: "ws://user:[email protected]:9222/devtools/browser/browser-guid?token=secret",
+ BrowserType: "chrome",
+ BrowserLabel: "work-profile",
+ })
+ if err != nil {
+ t.Fatalf("Register() error = %v", err)
+ }
+
+ dirInfo, err := os.Stat(filepath.Join(stateDir, registryDir))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := dirInfo.Mode().Perm(); got != 0o700 {
+ t.Fatalf("registry mode = %o, want 700", got)
+ }
+ entries, err := os.ReadDir(filepath.Join(stateDir, registryDir))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(entries) != 1 || strings.HasSuffix(entries[0].Name(), ".tmp") {
+ t.Fatalf("published registry entries = %v, want one JSON record", entries)
+ }
+ fileInfo, err := entries[0].Info()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := fileInfo.Mode().Perm(); got != 0o600 {
+ t.Fatalf("record mode = %o, want 600", got)
+ }
+
+ states, err := List(stateDir, false)
+ if err != nil {
+ t.Fatalf("List() error = %v", err)
+ }
+ if len(states) != 1 {
+ t.Fatalf("List() returned %d records, want 1", len(states))
+ }
+ state := states[0]
+ if !state.Live || state.Stale || !state.Reachable || state.PIDStatus != "alive" || state.Status != "live" {
+ t.Fatalf("live state = %+v", state)
+ }
+ if state.PID != os.Getpid() || state.ProcessStartUnixMillis <= 0 {
+ t.Fatalf("process identity = pid %d start %d", state.PID, state.ProcessStartUnixMillis)
+ }
+ if state.CDPIdentity == "" || strings.Contains(state.CDPIdentity, "password") || strings.Contains(state.CDPIdentity, "browser-guid") {
+ t.Fatalf("unsafe CDP identity %q", state.CDPIdentity)
+ }
+
+ _ = listener.Close()
+ states, err = List(stateDir, true)
+ if err != nil {
+ t.Fatalf("List(prune) error = %v", err)
+ }
+ if len(states) != 1 || states[0].Status != "stale_listener" || states[0].Pruned {
+ t.Fatalf("live PID with closed listener must be retained: %+v", states)
+ }
+
+ if err := registration.Close(); err != nil {
+ t.Fatalf("Close() error = %v", err)
+ }
+ if err := registration.Close(); err != nil {
+ t.Fatalf("second Close() error = %v", err)
+ }
+ states, err = List(stateDir, false)
+ if err != nil || len(states) != 0 {
+ t.Fatalf("records after Close() = %+v, err %v", states, err)
+ }
+}
+
+func TestListPrunesOnlyConclusiveStalePIDs(t *testing.T) {
+ stateDir := t.TempDir()
+ root, err := openRegistry(stateDir, true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ started, err := processStart(os.Getpid())
+ if err != nil {
+ t.Fatal(err)
+ }
+ records := map[string]Record{
+ "bridge-0-dead.json": {PID: 0, Address: "127.0.0.1", Port: "1", BrowserType: "chrome"},
+ "bridge-1-unknown.json": {PID: os.Getpid(), Address: "127.0.0.1", Port: "1", BrowserType: "chrome"},
+ "bridge-2-reused.json": {PID: os.Getpid(), ProcessStartUnixMillis: started + 1, Address: "127.0.0.1", Port: "1", BrowserType: "chrome"},
+ }
+ for name, rec := range records {
+ data, marshalErr := json.Marshal(rec)
+ if marshalErr != nil {
+ t.Fatal(marshalErr)
+ }
+ if err := root.WriteFile(name, data, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ _ = root.Close()
+
+ states, err := List(stateDir, false)
+ if err != nil || len(states) != 3 {
+ t.Fatalf("stale listing = %+v, err %v", states, err)
+ }
+ states, err = List(stateDir, true)
+ if err != nil || len(states) != 3 {
+ t.Fatalf("pruned listing = %+v, err %v", states, err)
+ }
+ for _, state := range states {
+ wantPruned := state.PIDStatus == "dead" || state.PIDStatus == "reused"
+ if state.Pruned != wantPruned {
+ t.Fatalf("state %+v prune = %t, want %t", state.Record, state.Pruned, wantPruned)
+ }
+ }
+ states, err = List(stateDir, false)
+ if err != nil || len(states) != 1 || states[0].PIDStatus != "unknown" {
+ t.Fatalf("records after prune = %+v, err %v", states, err)
+ }
+}
+
+func TestListMissingRegistryIsEmpty(t *testing.T) {
+ states, err := List(t.TempDir(), false)
+ if err != nil || len(states) != 0 {
+ t.Fatalf("List() = %+v, %v; want empty", states, err)
+ }
+}
+
+func TestListRejectsRegistrySymlink(t *testing.T) {
+ stateDir := t.TempDir()
+ outside := t.TempDir()
+ if err := os.Symlink(outside, filepath.Join(stateDir, registryDir)); err != nil {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+ if _, err := Register(stateDir, Record{Address: "127.0.0.1", Port: "9867", BrowserType: "chrome"}); err == nil {
+ t.Fatal("Register() accepted a symlinked registry directory")
+ }
+}
diff --git a/internal/cli/actions/actions_capture_test.go b/internal/cli/actions/actions_capture_test.go
new file mode 100644
index 00000000..2b2ea842
--- /dev/null
+++ b/internal/cli/actions/actions_capture_test.go
@@ -0,0 +1,32 @@
+package actions
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/spf13/cobra"
+)
+
+func TestCaptureThreadsExplicitTabIntoPairedRequest(t *testing.T) {
+ m := newMockServer()
+ m.response = `{"status":"ok","tabId":"tab-target","image":{"format":"png","base64":"aW1n"},"snapshot":{"nodeCount":1,"nodes":[{"ref":"e1","role":"button","name":"Save"}]},"pairing":{"navigated":false}}`
+ defer m.close()
+
+ cmd := &cobra.Command{}
+ cmd.Flags().Bool("json", false, "")
+ cmd.Flags().String("tab", "", "")
+ _ = cmd.Flags().Set("json", "true")
+ _ = cmd.Flags().Set("tab", "tab-target")
+
+ out := captureStdout(t, func() {
+ Capture(m.server.Client(), m.base(), "", cmd)
+ })
+ if m.lastPath != "/capture" || !strings.Contains(m.lastQuery, "tabId=tab-target") {
+ t.Fatalf("paired capture request = %s?%s, want /capture?tabId=tab-target", m.lastPath, m.lastQuery)
+ }
+ for _, want := range []string{`"tabId": "tab-target"`, `"base64": "aW1n"`, `"name": "Save"`} {
+ if !strings.Contains(out, want) {
+ t.Fatalf("capture JSON missing %s: %s", want, out)
+ }
+ }
+}
diff --git a/internal/cli/actions/actions_element.go b/internal/cli/actions/actions_element.go
index 709dc6fb..b9585f25 100644
--- a/internal/cli/actions/actions_element.go
+++ b/internal/cli/actions/actions_element.go
@@ -40,6 +40,12 @@ func Action(client *http.Client, base, token, kind, selectorArg string, cmd *cob
}
if kind == "click" {
+ if submit, _ := cmd.Flags().GetBool("submit"); submit {
+ body["submit"] = true
+ }
+ if dismiss, _ := cmd.Flags().GetBool("dismiss-known-interstitials"); dismiss {
+ body["dismissKnownInterstitials"] = true
+ }
waitNav, _ := cmd.Flags().GetBool("wait-nav")
if waitNav {
body["waitNav"] = true
@@ -179,6 +185,21 @@ func printActionResult(kind string, result map[string]any) {
output.Error(kind, errMsg, output.ExitNotFound)
return
}
+ if actionResult, ok := result["result"].(map[string]any); ok {
+ if postState, ok := actionResult["postState"].(map[string]any); ok {
+ status, _ := postState["status"].(string)
+ signal, _ := postState["signal"].(string)
+ switch status {
+ case "pending":
+ output.Value("PENDING")
+ output.Hint("submit post-state is still pending; do not retry automatically")
+ return
+ case "succeeded":
+ output.Value("SUCCEEDED " + signal)
+ return
+ }
+ }
+ }
output.Success()
}
@@ -393,6 +414,9 @@ func ActionSimple(client *http.Client, base, token, kind string, args []string,
case "fill":
setSelectorBody(body, args[0])
body["text"] = strings.Join(args[1:], " ")
+ if submit, _ := cmd.Flags().GetBool("submit"); submit {
+ body["submit"] = true
+ }
case "press":
if len(args) >= 2 {
setSelectorBody(body, args[0])
diff --git a/internal/cli/actions/actions_element_test.go b/internal/cli/actions/actions_element_test.go
index 7ec0c6bb..ca3a8da4 100644
--- a/internal/cli/actions/actions_element_test.go
+++ b/internal/cli/actions/actions_element_test.go
@@ -12,6 +12,7 @@ func newActionCmd() *cobra.Command {
cmd.Flags().String("css", "", "")
cmd.Flags().Bool("wait-nav", false, "")
cmd.Flags().Bool("dismiss-banners", false, "")
+ cmd.Flags().Bool("dismiss-known-interstitials", false, "")
cmd.Flags().String("tab", "", "")
cmd.Flags().Float64("x", 0, "")
cmd.Flags().Float64("y", 0, "")
@@ -21,6 +22,7 @@ func newActionCmd() *cobra.Command {
cmd.Flags().String("dialog-action", "", "")
cmd.Flags().String("dialog-text", "", "")
cmd.Flags().String("mode", "", "")
+ cmd.Flags().Bool("submit", false, "")
return cmd
}
@@ -30,6 +32,7 @@ func newSimpleCmd() *cobra.Command {
cmd.Flags().Bool("snap", false, "")
cmd.Flags().Bool("snap-diff", false, "")
cmd.Flags().Bool("text", false, "")
+ cmd.Flags().Bool("submit", false, "")
return cmd
}
@@ -53,6 +56,52 @@ func TestClick(t *testing.T) {
}
}
+func TestClickSubmit(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ cmd := newActionCmd()
+ if err := cmd.Flags().Set("submit", "true"); err != nil {
+ t.Fatal(err)
+ }
+
+ Action(m.server.Client(), m.base(), "", "click", "e5", cmd)
+ var body map[string]any
+ if err := json.Unmarshal([]byte(m.lastBody), &body); err != nil {
+ t.Fatal(err)
+ }
+ if body["submit"] != true {
+ t.Fatalf("submit = %v, want true", body["submit"])
+ }
+}
+
+func TestPrintActionResultSubmitPendingIsNotOK(t *testing.T) {
+ got := captureStdout(t, func() {
+ printActionResult("click", map[string]any{
+ "success": true,
+ "result": map[string]any{
+ "postState": map[string]any{"status": "pending"},
+ },
+ })
+ })
+ if got != "PENDING\n" {
+ t.Fatalf("pending output = %q, want PENDING", got)
+ }
+}
+
+func TestPrintActionResultSubmitSuccessNamesObservedSignal(t *testing.T) {
+ got := captureStdout(t, func() {
+ printActionResult("click", map[string]any{
+ "success": true,
+ "result": map[string]any{
+ "postState": map[string]any{"status": "succeeded", "signal": "dialog_closed"},
+ },
+ })
+ })
+ if got != "SUCCEEDED dialog_closed\n" {
+ t.Fatalf("success output = %q, want observed submit signal", got)
+ }
+}
+
func TestClickWaitNav(t *testing.T) {
m := newMockServer()
defer m.close()
@@ -102,6 +151,22 @@ func TestClickDismissBannersWithoutWaitNavIsNoop(t *testing.T) {
}
}
+func TestClickDismissKnownInterstitialsIsIndependentOfWaitNav(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ cmd := newActionCmd()
+ _ = cmd.Flags().Set("dismiss-known-interstitials", "true")
+
+ Action(m.server.Client(), m.base(), "", "click", "e5", cmd)
+ var body map[string]any
+ if err := json.Unmarshal([]byte(m.lastBody), &body); err != nil {
+ t.Fatal(err)
+ }
+ if body["dismissKnownInterstitials"] != true {
+ t.Fatalf("dismissKnownInterstitials = %v, want true", body["dismissKnownInterstitials"])
+ }
+}
+
func TestClickMode(t *testing.T) {
m := newMockServer()
defer m.close()
@@ -466,6 +531,24 @@ func TestFill(t *testing.T) {
}
}
+func TestFillSubmit(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+ cmd := newSimpleCmd()
+ if err := cmd.Flags().Set("submit", "true"); err != nil {
+ t.Fatal(err)
+ }
+
+ ActionSimple(m.server.Client(), m.base(), "", "fill", []string{"#search", "needle"}, cmd)
+ var body map[string]any
+ if err := json.Unmarshal([]byte(m.lastBody), &body); err != nil {
+ t.Fatal(err)
+ }
+ if body["submit"] != true {
+ t.Fatalf("submit = %v, want true", body["submit"])
+ }
+}
+
func TestScroll(t *testing.T) {
m := newMockServer()
defer m.close()
diff --git a/internal/cli/actions/actions_network.go b/internal/cli/actions/actions_network.go
index 54d24ae2..dd5a189f 100644
--- a/internal/cli/actions/actions_network.go
+++ b/internal/cli/actions/actions_network.go
@@ -105,7 +105,7 @@ func NetworkClear(client *http.Client, base, token string, cmd *cobra.Command) {
if v, _ := cmd.Flags().GetString("tab"); v != "" {
params.Set("tabId", v)
}
- result := apiclient.DoPost(client, base, token, "/network/clear", map[string]any{})
+ result := apiclient.DoPost(client, base, token, "/network/clear?"+params.Encode(), map[string]any{})
if result == nil {
fmt.Fprintln(os.Stderr, "Failed to clear network data")
}
diff --git a/internal/cli/actions/actions_network_test.go b/internal/cli/actions/actions_network_test.go
new file mode 100644
index 00000000..89b2bcc2
--- /dev/null
+++ b/internal/cli/actions/actions_network_test.go
@@ -0,0 +1,21 @@
+package actions
+
+import (
+ "testing"
+
+ "github.com/spf13/cobra"
+)
+
+func TestNetworkClearPreservesExplicitTab(t *testing.T) {
+ m := newMockServer()
+ defer m.close()
+
+ cmd := &cobra.Command{}
+ cmd.Flags().String("tab", "", "")
+ _ = cmd.Flags().Set("tab", "tab-target")
+ NetworkClear(m.server.Client(), m.base(), "", cmd)
+
+ if m.lastPath != "/network/clear" || m.lastQuery != "tabId=tab-target" {
+ t.Fatalf("network clear request = %s?%s, want /network/clear?tabId=tab-target", m.lastPath, m.lastQuery)
+ }
+}
diff --git a/internal/daemon/manager.go b/internal/daemon/manager.go
index 7a8d86b6..cc6f1e20 100644
--- a/internal/daemon/manager.go
+++ b/internal/daemon/manager.go
@@ -56,12 +56,25 @@ func CurrentManager() (Manager, error) {
}
func IsInstalled() bool {
+ installed, err := InstallationStatus()
+ return err == nil && installed
+}
+
+// InstallationStatus distinguishes an absent service from an unreadable service
+// location so lifecycle callers can fail closed instead of starting a second owner.
+func InstallationStatus() (bool, error) {
manager, err := CurrentManager()
if err != nil {
- return false
+ return false, err
}
_, err = os.Stat(manager.ServicePath())
- return err == nil
+ if err == nil {
+ return true, nil
+ }
+ if os.IsNotExist(err) {
+ return false, nil
+ }
+ return false, err
}
func IsRunning() bool {
diff --git a/internal/daemon/systemd_test.go b/internal/daemon/systemd_test.go
index e4a1c95e..5cfe90a8 100644
--- a/internal/daemon/systemd_test.go
+++ b/internal/daemon/systemd_test.go
@@ -107,3 +107,20 @@ func TestSystemdUserManagerLogsFallsBackToJournalctl(t *testing.T) {
t.Fatalf("journalctl call = %v, want %q", runner.calls, expected)
}
}
+
+func TestSystemdUserManagerRestartUsesExactlyOneManagerCommand(t *testing.T) {
+ root := t.TempDir()
+ runner := &fakeCommandRunner{}
+ manager := &systemdUserManager{
+ env: environment{homeDir: root, osName: "linux"},
+ runner: runner,
+ }
+
+ if _, err := manager.Restart(); err != nil {
+ t.Fatalf("Restart returned error: %v", err)
+ }
+ want := []string{"systemctl --user restart pinchtab.service"}
+ if strings.Join(runner.calls, "\n") != strings.Join(want, "\n") {
+ t.Fatalf("restart calls = %v, want %v", runner.calls, want)
+ }
+}
diff --git a/internal/dashboard/agent_session_api.go b/internal/dashboard/agent_session_api.go
index 2b953f31..ad5f69ce 100644
--- a/internal/dashboard/agent_session_api.go
+++ b/internal/dashboard/agent_session_api.go
@@ -16,6 +16,15 @@ import (
type SessionAPI struct {
store *session.Store
browsersAvailable []string
+ sessionTabIDs func(string) []string
+}
+
+// SetSessionTabSource wires the orchestrator's successful-creation ledger into
+// revoke responses without coupling the dashboard package to the orchestrator.
+func (a *SessionAPI) SetSessionTabSource(source func(string) []string) {
+ if a != nil {
+ a.sessionTabIDs = source
+ }
}
// NewSessionAPI creates a new session API handler.
@@ -137,9 +146,16 @@ func (a *SessionAPI) handleRevoke(w http.ResponseWriter, r *http.Request) {
httpx.ErrorCode(w, http.StatusForbidden, "forbidden", "not allowed to revoke this session", false, nil)
return
}
+ remainingTabIDs := []string{}
+ if a.sessionTabIDs != nil {
+ remainingTabIDs = append(remainingTabIDs, a.sessionTabIDs(id)...)
+ }
if !a.store.Revoke(id) {
httpx.ErrorCode(w, http.StatusNotFound, "session_not_found", "session not found", false, nil)
return
}
- httpx.JSON(w, http.StatusOK, map[string]string{"status": "ok"})
+ httpx.JSON(w, http.StatusOK, map[string]any{
+ "status": "ok",
+ "remainingTabIds": remainingTabIDs,
+ })
}
diff --git a/internal/dashboard/agent_session_api_test.go b/internal/dashboard/agent_session_api_test.go
index 664d1003..56a159dc 100644
--- a/internal/dashboard/agent_session_api_test.go
+++ b/internal/dashboard/agent_session_api_test.go
@@ -243,6 +243,37 @@ func TestAgentSessionAPI_Revoke(t *testing.T) {
}
}
+func TestAgentSessionAPI_RevokeReturnsRemainingOwnedTabIDs(t *testing.T) {
+ store := newTestSessionStore()
+ id, _, _ := store.Create("agent-1", "", "")
+ api := NewSessionAPI(store, nil)
+ api.SetSessionTabSource(func(gotID string) []string {
+ if gotID != id {
+ t.Fatalf("tab source session id = %q, want %q", gotID, id)
+ }
+ if _, ok := store.Get(id); !ok {
+ t.Fatal("tab source must be read before the session is revoked")
+ }
+ return []string{"tab-a", "tab-b"}
+ })
+ mux := http.NewServeMux()
+ api.RegisterHandlers(mux)
+
+ req := httptest.NewRequest("POST", "/sessions/"+id+"/revoke", nil)
+ req.Header.Set("Authorization", "Bearer dashboard-token")
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ resp := decodeSessionResponse(t, w)
+ tabs, ok := resp["remainingTabIds"].([]any)
+ if !ok || len(tabs) != 2 || tabs[0] != "tab-a" || tabs[1] != "tab-b" {
+ t.Fatalf("remainingTabIds = %#v, want [tab-a tab-b]", resp["remainingTabIds"])
+ }
+}
+
func TestAgentSessionAPI_Revoke_NotFound(t *testing.T) {
store := newTestSessionStore()
mux := newTestSessionMux(store)
diff --git a/internal/handlers/action_execution.go b/internal/handlers/action_execution.go
index 6c26e47f..999d62f4 100644
--- a/internal/handlers/action_execution.go
+++ b/internal/handlers/action_execution.go
@@ -13,6 +13,117 @@ import (
"github.com/pinchtab/semantic/recovery"
)
+const (
+ postSubmitPollTimeout = 3 * time.Second
+ postSubmitPollInterval = 250 * time.Millisecond
+)
+
+var readTopmostSubmitModal = bridge.TopmostModalNodeIDInFrame
+
+type submitStateSnapshot struct {
+ URL string `json:"url"`
+ DialogOpen bool `json:"dialogOpen"`
+}
+
+type submitPostState struct {
+ Status string `json:"status"`
+ Signal string `json:"signal"`
+ Dispatch string `json:"dispatch"`
+ ActionTimedOut bool `json:"actionTimedOut"`
+ ElapsedMS int64 `json:"elapsedMs"`
+ Before submitStateSnapshot `json:"before"`
+ After submitStateSnapshot `json:"after"`
+}
+
+func (h *Handlers) captureSubmitState(ctx context.Context, tabID string) (submitStateSnapshot, error) {
+ currentURL, err := h.Bridge.CurrentURL(ctx)
+ if err != nil {
+ return submitStateSnapshot{}, fmt.Errorf("read current URL: %w", err)
+ }
+ _, dialogOpen, err := readTopmostSubmitModal(ctx, h.selectorFrameID(tabID))
+ if err != nil {
+ return submitStateSnapshot{}, fmt.Errorf("read topmost dialog: %w", err)
+ }
+ return submitStateSnapshot{
+ URL: strings.TrimSpace(currentURL),
+ DialogOpen: dialogOpen,
+ }, nil
+}
+
+func submitTransitionSignal(before, after submitStateSnapshot) string {
+ if before.URL != after.URL {
+ return "url_changed"
+ }
+ if before.DialogOpen && !after.DialogOpen {
+ return "dialog_closed"
+ }
+ return ""
+}
+
+func pendingSubmitPostState(before, after submitStateSnapshot, dispatch string, actionTimedOut bool, started time.Time) submitPostState {
+ return submitPostState{
+ Status: "pending",
+ Signal: "no_terminal_change",
+ Dispatch: dispatch,
+ ActionTimedOut: actionTimedOut,
+ ElapsedMS: time.Since(started).Milliseconds(),
+ Before: before,
+ After: after,
+ }
+}
+
+// pollSubmitPostState observes only conservative terminal signals. The caller
+// supplies a fresh bounded child of the live tab context, never the action
+// context that may already have reached its deadline.
+func (h *Handlers) pollSubmitPostState(ctx context.Context, tabID string, before submitStateSnapshot, dispatch string, actionTimedOut bool) (submitPostState, error) {
+ started := time.Now()
+ after := before
+ observedPostState := false
+ var lastReadErr error
+ ticker := time.NewTicker(postSubmitPollInterval)
+ defer ticker.Stop()
+
+ for {
+ observed, err := h.captureSubmitState(ctx, tabID)
+ if err == nil {
+ observedPostState = true
+ lastReadErr = nil
+ after = observed
+ if signal := submitTransitionSignal(before, after); signal != "" {
+ return submitPostState{
+ Status: "succeeded",
+ Signal: signal,
+ Dispatch: dispatch,
+ ActionTimedOut: actionTimedOut,
+ ElapsedMS: time.Since(started).Milliseconds(),
+ Before: before,
+ After: after,
+ }, nil
+ }
+ } else {
+ lastReadErr = err
+ }
+
+ select {
+ case <-ctx.Done():
+ if !errors.Is(ctx.Err(), context.DeadlineExceeded) {
+ return submitPostState{}, fmt.Errorf("post-submit observation canceled: %w", ctx.Err())
+ }
+ if !observedPostState {
+ if lastReadErr == nil {
+ lastReadErr = ctx.Err()
+ }
+ return submitPostState{}, fmt.Errorf("post-submit state was never observable: %w", lastReadErr)
+ }
+ if lastReadErr != nil && !errors.Is(lastReadErr, context.DeadlineExceeded) {
+ return submitPostState{}, fmt.Errorf("post-submit observation failed: %w", lastReadErr)
+ }
+ return pendingSubmitPostState(before, after, dispatch, actionTimedOut, started), nil
+ case <-ticker.C:
+ }
+ }
+}
+
func (h *Handlers) cacheActionIntent(tabID string, req bridge.ActionRequest) {
if h.Recovery == nil || req.Ref == "" {
return
@@ -54,7 +165,11 @@ func (h *Handlers) executeAction(ctx context.Context, req bridge.ActionRequest,
// per-step failure) before calling — refMissing=true assumes h.Recovery != nil.
// req.NodeID is mutated in place, as the inline action/batch/macro paths did.
func (h *Handlers) executeActionResilient(ctx context.Context, req *bridge.ActionRequest, cfg *config.RuntimeConfig, resolvedTabID string, refMissing bool) (map[string]any, string, *recovery.RecoveryResult, error) {
+ submitClick := bridge.IsSubmitClick(req.Kind, *req)
if refMissing {
+ if submitClick {
+ return nil, "", nil, fmt.Errorf("click submit target is unresolved; automatic recovery is disabled")
+ }
rr, recRes, recErr := h.Recovery.Attempt(
ctx, resolvedTabID, req.Ref, req.Kind,
func(c context.Context, _ string, nodeID int64) (map[string]any, error) {
@@ -70,7 +185,7 @@ func (h *Handlers) executeActionResilient(ctx context.Context, req *bridge.Actio
}
result, backend, err := h.executeAction(ctx, *req, cfg)
- if err != nil && shouldRetryPointerAction(*req, err) {
+ if err != nil && !submitClick && shouldRetryPointerAction(*req, err) {
if req.Ref != "" && shouldRetryStaleRef(err) {
recordStaleRefRetry()
h.refreshRefCache(ctx, resolvedTabID)
@@ -86,7 +201,7 @@ func (h *Handlers) executeActionResilient(ctx context.Context, req *bridge.Actio
}
var rr *recovery.RecoveryResult
- if err != nil && req.Ref != "" && h.Recovery != nil && h.Recovery.ShouldAttempt(err, req.Ref) {
+ if err != nil && !submitClick && req.Ref != "" && h.Recovery != nil && h.Recovery.ShouldAttempt(err, req.Ref) {
r2, recRes, recErr := h.Recovery.AttemptWithClassification(
ctx, resolvedTabID, req.Ref, req.Kind,
recovery.ClassifyFailure(err),
diff --git a/internal/handlers/action_selector_modal_test.go b/internal/handlers/action_selector_modal_test.go
new file mode 100644
index 00000000..27ad74d9
--- /dev/null
+++ b/internal/handlers/action_selector_modal_test.go
@@ -0,0 +1,163 @@
+package handlers
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestActionSelectorResolutionDefaultsToTopmostDialog(t *testing.T) {
+ chromePath, err := exec.LookPath("chromium")
+ if err != nil {
+ t.Skip("chromium not installed")
+ }
+ profile, err := os.MkdirTemp("", "pinchtab-handler-modal-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(chromePath),
+ chromedp.UserDataDir(profile),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ )...)
+ ctx, cancelBrowser := chromedp.NewContext(alloc)
+ ctx, cancelTimeout := context.WithTimeout(ctx, 20*time.Second)
+ t.Cleanup(func() {
+ cancelTimeout()
+ cancelBrowser()
+ cancelAlloc()
+ _ = os.RemoveAll(profile)
+ })
+
+ html := `<button id="background">Content contains</button><p>Background only</p>
+ <div id="dialog" role="dialog" aria-modal="true" style="position:fixed;inset:10px;z-index:50;background:white">
+ <button id="inside">Content contains</button><p>Dialog only</p>
+ <div id="hidden" aria-hidden="true">Hidden AX target</div>
+ </div>`
+ if err := chromedp.Run(ctx, chromedp.Navigate("data:text/html;base64,"+base64.StdEncoding.EncodeToString([]byte(html)))); err != nil {
+ t.Fatal(err)
+ }
+
+ cfg := &config.RuntimeConfig{ActionTimeout: 5 * time.Second, DefaultBrowser: config.BrowserChrome, StateDir: t.TempDir()}
+ b := bridge.New(context.Background(), ctx, cfg)
+ b.TabManager.RegisterTab("tab-modal", ctx)
+ h := New(b, cfg, nil, nil, nil)
+
+ req := bridge.ActionRequest{Selector: "text:Content contains"}
+ resolution, err := h.resolveActionRequestSelector(ctx, "tab-modal", &req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resolution.refMissing || req.NodeID == 0 {
+ t.Fatalf("resolution = %+v request = %+v", resolution, req)
+ }
+ var id string
+ if err := b.CallFunctionOnNode(ctx, req.NodeID, `function() { return this.id; }`, nil, &id); err != nil {
+ t.Fatal(err)
+ }
+ if id != "inside" {
+ t.Fatalf("handler resolved %q, want inside", id)
+ }
+
+ var backgroundNodeID int64
+ backgroundNodeID, err = bridge.ResolveCSSToNodeID(ctx, "#background")
+ if err != nil {
+ t.Fatal(err)
+ }
+ b.SetRefCache("tab-modal", &bridge.RefCache{Targets: map[string]bridge.RefTarget{
+ "e0": {BackendNodeID: backgroundNodeID},
+ "e1": {BackendNodeID: req.NodeID},
+ }})
+ backgroundRef := bridge.ActionRequest{Selector: "ref:e0"}
+ resolution, err = h.resolveActionRequestSelector(ctx, "tab-modal", &backgroundRef)
+ if err == nil || resolution.httpStatus() != 400 || resolution.refMissing || backgroundRef.NodeID != 0 {
+ t.Fatalf("background ref escaped dialog: resolution=%+v request=%+v", resolution, backgroundRef)
+ }
+ insideRef := bridge.ActionRequest{Selector: "ref:e1"}
+ resolution, err = h.resolveActionRequestSelector(ctx, "tab-modal", &insideRef)
+ if err != nil || resolution.refMissing || insideRef.NodeID != req.NodeID || insideRef.Ref != "" {
+ t.Fatalf("inside ref = resolution=%+v request=%+v error=%v", resolution, insideRef, err)
+ }
+
+ t.Run("text handler reads only the modal", func(t *testing.T) {
+ httpReq := httptest.NewRequest(http.MethodGet, "/text?tabId=tab-modal&mode=raw", nil)
+ w := httptest.NewRecorder()
+ h.HandleText(w, httpReq)
+ if w.Code != http.StatusOK {
+ t.Fatalf("text status = %d body=%s", w.Code, w.Body.String())
+ }
+ var payload struct {
+ Text string `json:"text"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(payload.Text, "Dialog only") || strings.Contains(payload.Text, "Background only") {
+ t.Fatalf("text leaked outside modal: %q", payload.Text)
+ }
+ })
+
+ t.Run("snapshot handler reads only the modal", func(t *testing.T) {
+ httpReq := httptest.NewRequest(http.MethodGet, "/snapshot?tabId=tab-modal", nil)
+ w := httptest.NewRecorder()
+ h.HandleSnapshot(w, httpReq)
+ if w.Code != http.StatusOK {
+ t.Fatalf("snapshot status = %d body=%s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "Dialog only") || strings.Contains(w.Body.String(), "Background only") {
+ t.Fatalf("snapshot leaked outside modal: %s", w.Body.String())
+ }
+ })
+
+ t.Run("AX-missing selector returns empty scope", func(t *testing.T) {
+ httpReq := httptest.NewRequest(http.MethodGet, "/snapshot?tabId=tab-modal&selector=%23hidden", nil)
+ w := httptest.NewRecorder()
+ h.HandleSnapshot(w, httpReq)
+ if w.Code != http.StatusOK {
+ t.Fatalf("snapshot status = %d body=%s", w.Code, w.Body.String())
+ }
+ var payload struct {
+ Count int `json:"count"`
+ Hint string `json:"hint"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
+ t.Fatal(err)
+ }
+ if payload.Count != 0 || payload.Hint == "" {
+ t.Fatalf("AX-missing selector payload = %+v, want empty with hint", payload)
+ }
+ })
+}
+
+func TestSelectorResolutionHTTPStatus(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ want int
+ }{
+ {name: "no match", err: bridge.ErrSelectorNoMatch, want: http.StatusNotFound},
+ {name: "outside modal", err: bridge.ErrSelectorOutsideScope, want: http.StatusBadRequest},
+ {name: "deadline", err: context.DeadlineExceeded, want: http.StatusGatewayTimeout},
+ {name: "transport", err: context.Canceled, want: http.StatusInternalServerError},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := selectorResolutionHTTPStatus(tt.err); got != tt.want {
+ t.Fatalf("status = %d, want %d", got, tt.want)
+ }
+ })
+ }
+}
diff --git a/internal/handlers/action_selector_resolution.go b/internal/handlers/action_selector_resolution.go
index 8c735bcb..527eed5e 100644
--- a/internal/handlers/action_selector_resolution.go
+++ b/internal/handlers/action_selector_resolution.go
@@ -2,6 +2,7 @@ package handlers
import (
"context"
+ "errors"
"fmt"
"net/http"
@@ -25,75 +26,124 @@ func frameScopedSelectorError(kind string, err error) error {
return fmt.Errorf("%s in current frame: %w", kind, err)
}
+func selectorResolutionHTTPStatus(err error) int {
+ switch {
+ case err == nil:
+ return http.StatusOK
+ case errors.Is(err, bridge.ErrSelectorNoMatch):
+ return http.StatusNotFound
+ case errors.Is(err, bridge.ErrSelectorOutsideScope):
+ return http.StatusBadRequest
+ case errors.Is(err, context.DeadlineExceeded):
+ return http.StatusGatewayTimeout
+ default:
+ return http.StatusInternalServerError
+ }
+}
+
func (h *Handlers) resolveActionRequestSelector(ctx context.Context, tabID string, req *bridge.ActionRequest) (actionSelectorResolution, error) {
- req.NormalizeSelector()
- if req.NodeID != 0 {
+ original := *req
+ original.NormalizeSelector()
+ if original.NodeID != 0 {
+ *req = original
return actionSelectorResolution{}, nil
}
- if req.Selector == "" {
- if req.Ref != "" {
+ if original.Selector == "" {
+ *req = original
+ if original.Ref != "" {
return actionSelectorResolution{refMissing: true}, nil
}
return actionSelectorResolution{}, nil
}
+ frameID := h.selectorFrameID(tabID)
+ for attempt := 0; attempt < 2; attempt++ {
+ modalNodeID, modalOpen, err := bridge.TopmostModalNodeID(ctx, frameID)
+ if err != nil {
+ return actionSelectorResolution{status: selectorResolutionHTTPStatus(err)}, frameScopedSelectorError("topmost dialog", err)
+ }
+
+ attemptReq := original
+ resolution, resolveErr := h.resolveActionRequestSelectorInScope(ctx, tabID, frameID, modalNodeID, modalOpen, &attemptReq)
+
+ afterNodeID, afterOpen, scopeErr := bridge.TopmostModalNodeID(ctx, frameID)
+ if scopeErr != nil {
+ return actionSelectorResolution{status: selectorResolutionHTTPStatus(scopeErr)}, frameScopedSelectorError("recheck topmost dialog", scopeErr)
+ }
+ if modalNodeID == afterNodeID && modalOpen == afterOpen {
+ *req = attemptReq
+ return resolution, resolveErr
+ }
+ }
+
+ return actionSelectorResolution{status: http.StatusConflict}, fmt.Errorf("topmost dialog changed twice during selector resolution; retry after the page settles")
+}
+
+func (h *Handlers) resolveActionRequestSelectorInScope(
+ ctx context.Context,
+ tabID, frameID string,
+ modalNodeID int64,
+ modalOpen bool,
+ req *bridge.ActionRequest,
+) (actionSelectorResolution, error) {
sel := selector.Parse(req.Selector)
- if handled, err := h.applySemanticActionSelector(ctx, tabID, sel, req); handled {
+
+ if handled, err := h.applySemanticActionSelectorInScope(ctx, tabID, frameID, modalNodeID, sel, req); handled {
if err != nil {
return actionSelectorResolution{status: semanticSelectorHTTPStatus(err)}, err
}
return actionSelectorResolution{}, nil
}
+ resolve := func(sel selector.Selector) (int64, error) {
+ if modalOpen {
+ return bridge.ResolveUnifiedSelectorWithinNode(ctx, sel, h.Bridge.GetRefCache(tabID), modalNodeID)
+ }
+ return bridge.ResolveUnifiedSelectorInFrame(ctx, sel, h.Bridge.GetRefCache(tabID), frameID)
+ }
switch sel.Kind {
case selector.KindRef:
req.Ref = sel.Value
req.Selector = ""
- cache := h.Bridge.GetRefCache(tabID)
- if cache != nil {
- if target, ok := cache.Lookup(sel.Value); ok {
- req.NodeID = target.BackendNodeID
+ nid, err := resolve(sel)
+ if err != nil {
+ if errors.Is(err, bridge.ErrSelectorNoMatch) {
+ if modalOpen {
+ return actionSelectorResolution{status: http.StatusNotFound}, frameScopedSelectorError("ref selector inside topmost dialog", err)
+ }
+ return actionSelectorResolution{refMissing: true}, nil
}
+ return actionSelectorResolution{status: selectorResolutionHTTPStatus(err)}, frameScopedSelectorError("ref selector", err)
}
- if req.NodeID == 0 {
+ req.NodeID = nid
+ if nid == 0 {
return actionSelectorResolution{refMissing: true}, nil
}
- case selector.KindCSS:
- req.Ref = ""
- nid, err := bridge.ResolveCSSToNodeIDInFrame(ctx, h.selectorFrameID(tabID), sel.Value)
- if err != nil {
- return actionSelectorResolution{}, frameScopedSelectorError("css selector", err)
+ if modalOpen {
+ // The backend node is already validated against the active modal.
+ // Clear the ref so stale-ref recovery cannot later refresh a global
+ // snapshot and accidentally execute against a background ref with
+ // the same ordinal.
+ req.Ref = ""
}
- req.NodeID = nid
- req.Selector = ""
- case selector.KindXPath:
- nid, err := bridge.ResolveXPathToNodeIDInFrame(ctx, h.selectorFrameID(tabID), sel.Value)
+ case selector.KindCSS, selector.KindXPath, selector.KindText:
+ nid, err := resolve(sel)
if err != nil {
- return actionSelectorResolution{}, frameScopedSelectorError("xpath selector", err)
+ return actionSelectorResolution{status: selectorResolutionHTTPStatus(err)}, frameScopedSelectorError(string(sel.Kind)+" selector", err)
}
- req.NodeID = nid
- req.Selector = ""
- req.Ref = ""
- case selector.KindText:
- nid, err := bridge.ResolveTextToNodeIDInFrame(ctx, h.selectorFrameID(tabID), sel.Value)
- if err != nil {
- return actionSelectorResolution{}, frameScopedSelectorError("text selector", err)
- }
- req.NodeID = nid
- req.Selector = ""
- req.Ref = ""
+ req.NodeID, req.Selector, req.Ref = nid, "", ""
case selector.KindRole, selector.KindLabel, selector.KindPlaceholder,
selector.KindAlt, selector.KindTitle, selector.KindTestID,
selector.KindFirst, selector.KindLast, selector.KindNth:
- nid, err := bridge.ResolveUnifiedSelectorInFrame(ctx, sel, h.Bridge.GetRefCache(tabID), h.selectorFrameID(tabID))
+ nid, err := resolve(sel)
if err != nil {
- return actionSelectorResolution{}, frameScopedSelectorError("selector", err)
+ return actionSelectorResolution{status: selectorResolutionHTTPStatus(err)}, frameScopedSelectorError("selector", err)
}
req.NodeID = nid
req.Selector = ""
req.Ref = ""
case selector.KindSemantic:
- return actionSelectorResolution{}, fmt.Errorf("semantic selector requires a non-empty query")
+ return actionSelectorResolution{status: http.StatusBadRequest}, fmt.Errorf("semantic selector requires a non-empty query")
}
return actionSelectorResolution{}, nil
diff --git a/internal/handlers/action_submit_test.go b/internal/handlers/action_submit_test.go
new file mode 100644
index 00000000..7ee48294
--- /dev/null
+++ b/internal/handlers/action_submit_test.go
@@ -0,0 +1,352 @@
+package handlers
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type submitActionBridge struct {
+ *mockBridge
+ tabCtx context.Context
+ urls []string
+ currentURLErr error
+ urlCalls int
+ urlContexts []context.Context
+ urlContextErrs []error
+ actionCalls int
+ actionCtx context.Context
+ executeActionFn func(context.Context, string, bridge.ActionRequest) (map[string]any, error)
+}
+
+func newSubmitActionBridge(ctx context.Context) *submitActionBridge {
+ return &submitActionBridge{
+ mockBridge: &mockBridge{},
+ tabCtx: ctx,
+ urls: []string{"https://example.test/wizard"},
+ }
+}
+
+func (b *submitActionBridge) TabContext(string) (*bridge.TabHandle, string, error) {
+ return bridge.NewTabHandle(b.tabCtx), "tab1", nil
+}
+
+func (b *submitActionBridge) CurrentURL(ctx context.Context) (string, error) {
+ b.urlContexts = append(b.urlContexts, ctx)
+ b.urlContextErrs = append(b.urlContextErrs, ctx.Err())
+ if b.currentURLErr != nil {
+ return "", b.currentURLErr
+ }
+ index := b.urlCalls
+ b.urlCalls++
+ if index >= len(b.urls) {
+ index = len(b.urls) - 1
+ }
+ return b.urls[index], nil
+}
+
+func (b *submitActionBridge) ExecuteAction(ctx context.Context, kind string, req bridge.ActionRequest) (map[string]any, error) {
+ b.actionCalls++
+ b.actionCtx = ctx
+ if b.executeActionFn != nil {
+ return b.executeActionFn(ctx, kind, req)
+ }
+ return map[string]any{"clicked": true}, nil
+}
+
+func installSubmitModalReader(t *testing.T, fn func(context.Context, string) (int64, bool, error)) {
+ t.Helper()
+ original := readTopmostSubmitModal
+ readTopmostSubmitModal = fn
+ t.Cleanup(func() { readTopmostSubmitModal = original })
+}
+
+func postSubmitRequest(t *testing.T, h *Handlers, body string) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodPost, "/action", bytes.NewBufferString(body))
+ req.Header.Set("Content-Type", "application/json")
+ w := httptest.NewRecorder()
+ h.HandleAction(w, req)
+ return w
+}
+
+func TestHandleClickSubmitTimeoutUsesFreshTabContextAndReportsDialogClose(t *testing.T) {
+ parentCtx, parentCancel := context.WithCancel(context.Background())
+ defer parentCancel()
+ b := newSubmitActionBridge(parentCtx)
+ b.executeActionFn = func(ctx context.Context, _ string, _ bridge.ActionRequest) (map[string]any, error) {
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }
+ modalReads := 0
+ installSubmitModalReader(t, func(context.Context, string) (int64, bool, error) {
+ modalReads++
+ if modalReads == 1 {
+ return 71, true, nil
+ }
+ return 0, false, nil
+ })
+
+ h := New(b, &config.RuntimeConfig{ActionTimeout: 10 * time.Millisecond}, nil, nil, nil)
+ w := postSubmitRequest(t, h, `{"kind":"click","tabId":"tab1","nodeId":42,"submit":true}`)
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())
+ }
+ var response struct {
+ Success bool `json:"success"`
+ Result struct {
+ PostState submitPostState `json:"postState"`
+ } `json:"result"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ post := response.Result.PostState
+ if !response.Success || post.Status != "succeeded" || post.Signal != "dialog_closed" ||
+ post.Dispatch != "unconfirmed" || !post.ActionTimedOut {
+ t.Fatalf("unexpected post-state: %+v", post)
+ }
+ if b.actionCalls != 1 {
+ t.Fatalf("action calls = %d, want 1", b.actionCalls)
+ }
+ if !errors.Is(b.actionCtx.Err(), context.DeadlineExceeded) {
+ t.Fatalf("action context error = %v, want deadline", b.actionCtx.Err())
+ }
+ if len(b.urlContexts) < 2 {
+ t.Fatalf("URL context calls = %d, want baseline and post-state", len(b.urlContexts))
+ }
+ if b.urlContexts[0] != b.actionCtx {
+ t.Fatal("pre-state was not captured with the action context")
+ }
+ if b.urlContexts[1] == b.actionCtx || b.urlContextErrs[1] != nil {
+ t.Fatalf("post-state reused expired action context: same=%v errAtRead=%v", b.urlContexts[1] == b.actionCtx, b.urlContextErrs[1])
+ }
+ if parentCtx.Err() != nil {
+ t.Fatalf("live parent tab context was canceled: %v", parentCtx.Err())
+ }
+}
+
+func TestPollClickSubmitReportsURLChange(t *testing.T) {
+ b := newSubmitActionBridge(context.Background())
+ b.urls = []string{"https://example.test/done"}
+ installSubmitModalReader(t, func(context.Context, string) (int64, bool, error) {
+ return 0, false, nil
+ })
+ h := &Handlers{Bridge: b}
+
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ post, err := h.pollSubmitPostState(ctx, "tab1", submitStateSnapshot{
+ URL: "https://example.test/wizard",
+ }, "acknowledged", false)
+ if err != nil {
+ t.Fatalf("poll post-state: %v", err)
+ }
+ if post.Status != "succeeded" || post.Signal != "url_changed" || post.Dispatch != "acknowledged" || post.ActionTimedOut {
+ t.Fatalf("unexpected post-state: %+v", post)
+ }
+}
+
+func TestHandleClickSubmitGETParsesSubmitFlag(t *testing.T) {
+ b := newSubmitActionBridge(context.Background())
+ b.urls = []string{"https://example.test/wizard", "https://example.test/done"}
+ installSubmitModalReader(t, func(context.Context, string) (int64, bool, error) {
+ return 0, false, nil
+ })
+ h := New(b, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)
+ req := httptest.NewRequest(http.MethodGet, "/action?kind=click&tabId=tab1&nodeId=42&submit=true", nil)
+ w := httptest.NewRecorder()
+ h.HandleAction(w, req)
+ if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"signal":"url_changed"`) {
+ t.Fatalf("GET submit status=%d response=%s", w.Code, w.Body.String())
+ }
+ if b.actionCalls != 1 {
+ t.Fatalf("action calls = %d, want 1", b.actionCalls)
+ }
+}
+
+func TestPollClickSubmitReportsPendingWithoutTerminalChange(t *testing.T) {
+ b := newSubmitActionBridge(context.Background())
+ installSubmitModalReader(t, func(context.Context, string) (int64, bool, error) {
+ return 8, true, nil
+ })
+ h := &Handlers{Bridge: b}
+ before := submitStateSnapshot{URL: "https://example.test/wizard", DialogOpen: true}
+
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
+ defer cancel()
+ post, err := h.pollSubmitPostState(ctx, "tab1", before, "unconfirmed", true)
+ if err != nil {
+ t.Fatalf("poll post-state: %v", err)
+ }
+ if post.Status != "pending" || post.Signal != "no_terminal_change" || post.After != before {
+ t.Fatalf("unexpected post-state: %+v", post)
+ }
+}
+
+func TestPollClickSubmitCancellationAndUnobservableStateAreErrors(t *testing.T) {
+ t.Run("canceled tab context", func(t *testing.T) {
+ b := newSubmitActionBridge(context.Background())
+ installSubmitModalReader(t, func(context.Context, string) (int64, bool, error) {
+ return 8, true, nil
+ })
+ h := &Handlers{Bridge: b}
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ _, err := h.pollSubmitPostState(ctx, "tab1", submitStateSnapshot{URL: b.urls[0], DialogOpen: true}, "unconfirmed", true)
+ if err == nil || !strings.Contains(err.Error(), "observation canceled") {
+ t.Fatalf("canceled observation error = %v", err)
+ }
+ })
+
+ t.Run("no readable post-state", func(t *testing.T) {
+ b := newSubmitActionBridge(context.Background())
+ b.currentURLErr = errors.New("target closed")
+ installSubmitModalReader(t, func(context.Context, string) (int64, bool, error) {
+ return 0, false, nil
+ })
+ h := &Handlers{Bridge: b}
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
+ defer cancel()
+ _, err := h.pollSubmitPostState(ctx, "tab1", submitStateSnapshot{}, "unconfirmed", true)
+ if err == nil || !strings.Contains(err.Error(), "never observable") || !strings.Contains(err.Error(), "target closed") {
+ t.Fatalf("unobservable post-state error = %v", err)
+ }
+ })
+}
+
+func TestHandleClickSubmitPostDispatchErrorIsNotRetryable(t *testing.T) {
+ parentCtx, parentCancel := context.WithCancel(context.Background())
+ defer parentCancel()
+ b := newSubmitActionBridge(parentCtx)
+ b.executeActionFn = func(context.Context, string, bridge.ActionRequest) (map[string]any, error) {
+ return nil, bridge.ErrElementStale
+ }
+ installSubmitModalReader(t, func(context.Context, string) (int64, bool, error) {
+ return 11, true, nil
+ })
+ h := New(b, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)
+
+ w := postSubmitRequest(t, h, `{"kind":"click","tabId":"tab1","ref":"e1","nodeId":42,"submit":true}`)
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("status = %d, want 500: %s", w.Code, w.Body.String())
+ }
+ var failure struct {
+ Code string `json:"code"`
+ Retryable bool `json:"retryable"`
+ Details struct {
+ DoNotRetry bool `json:"doNotRetry"`
+ } `json:"details"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &failure); err != nil {
+ t.Fatalf("decode failure: %v", err)
+ }
+ if failure.Code != "action_failed" || failure.Retryable || !failure.Details.DoNotRetry {
+ t.Fatalf("unexpected failure contract: %+v body=%s", failure, w.Body.String())
+ }
+ if b.actionCalls != 1 {
+ t.Fatalf("action calls = %d, want 1", b.actionCalls)
+ }
+}
+
+func TestHandleClickSubmitNativeDialogKeepsDialogBlockingContract(t *testing.T) {
+ parentCtx, parentCancel := context.WithCancel(context.Background())
+ defer parentCancel()
+ b := newSubmitActionBridge(parentCtx)
+ b.executeActionFn = func(ctx context.Context, _ string, _ bridge.ActionRequest) (map[string]any, error) {
+ b.GetDialogManager().SetPending("tab1", &bridge.DialogState{Type: "confirm", Message: "Continue?"})
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }
+ installSubmitModalReader(t, func(context.Context, string) (int64, bool, error) {
+ return 0, false, nil
+ })
+ h := New(b, &config.RuntimeConfig{ActionTimeout: 10 * time.Millisecond}, nil, nil, nil)
+
+ w := postSubmitRequest(t, h, `{"kind":"click","tabId":"tab1","nodeId":42,"submit":true}`)
+ if w.Code != http.StatusInternalServerError || !strings.Contains(w.Body.String(), `"code":"dialog_blocking"`) {
+ t.Fatalf("native dialog contract changed: status=%d body=%s", w.Code, w.Body.String())
+ }
+ if b.urlCalls != 1 {
+ t.Fatalf("URL reads = %d, want baseline only (no DOM poll while native dialog blocks)", b.urlCalls)
+ }
+}
+
+func TestHandleClickSubmitTabClosureIsPostStateFailureNotPending(t *testing.T) {
+ parentCtx, parentCancel := context.WithCancel(context.Background())
+ b := newSubmitActionBridge(parentCtx)
+ b.executeActionFn = func(context.Context, string, bridge.ActionRequest) (map[string]any, error) {
+ parentCancel()
+ return map[string]any{"clicked": true}, nil
+ }
+ installSubmitModalReader(t, func(context.Context, string) (int64, bool, error) {
+ return 11, true, nil
+ })
+ h := New(b, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)
+
+ w := postSubmitRequest(t, h, `{"kind":"click","tabId":"tab1","nodeId":42,"submit":true}`)
+ if w.Code != http.StatusInternalServerError {
+ t.Fatalf("status = %d, want 500: %s", w.Code, w.Body.String())
+ }
+ var failure struct {
+ Code string `json:"code"`
+ Retryable bool `json:"retryable"`
+ Details struct {
+ DoNotRetry bool `json:"doNotRetry"`
+ } `json:"details"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &failure); err != nil {
+ t.Fatalf("decode failure: %v", err)
+ }
+ if failure.Code != "submit_post_state_failed" || failure.Retryable || !failure.Details.DoNotRetry || strings.Contains(w.Body.String(), `"status":"pending"`) {
+ t.Fatalf("tab closure was softened: %+v body=%s", failure, w.Body.String())
+ }
+}
+
+func TestClickSubmitRejectsConflictingSingleActionOptions(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)
+ tests := []string{
+ `{"kind":"click","submit":true,"x":1,"hasXY":true}`,
+ `{"kind":"click","submit":true,"waitNav":true,"nodeId":1}`,
+ `{"kind":"click","submit":true,"mode":"dom","nodeId":1}`,
+ `{"kind":"click","submit":true,"humanize":true,"nodeId":1}`,
+ `{"kind":"type","submit":true,"nodeId":1}`,
+ }
+ for _, body := range tests {
+ w := postSubmitRequest(t, h, body)
+ if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "invalid_submit_action") {
+ t.Fatalf("body %s: status=%d response=%s", body, w.Code, w.Body.String())
+ }
+ }
+}
+
+func TestClickSubmitRejectedInBatchAndMacroButFillSubmitAllowed(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{ActionTimeout: time.Second, AllowMacro: true}, nil, nil, nil)
+
+ batchReq := httptest.NewRequest(http.MethodPost, "/actions", bytes.NewBufferString(`{"actions":[{"kind":"click","submit":true,"nodeId":1}]}`))
+ batch := httptest.NewRecorder()
+ h.HandleActions(batch, batchReq)
+ if batch.Code != http.StatusBadRequest || !strings.Contains(batch.Body.String(), "click_submit_requires_single_action") {
+ t.Fatalf("batch status=%d response=%s", batch.Code, batch.Body.String())
+ }
+
+ macroReq := httptest.NewRequest(http.MethodPost, "/macro", bytes.NewBufferString(`{"steps":[{"kind":"click","submit":true,"nodeId":1}]}`))
+ macro := httptest.NewRecorder()
+ h.HandleMacro(macro, macroReq)
+ if macro.Code != http.StatusBadRequest || !strings.Contains(macro.Body.String(), "click_submit_requires_single_action") {
+ t.Fatalf("macro status=%d response=%s", macro.Code, macro.Body.String())
+ }
+
+ if !rejectMultiStepSubmitClicks(httptest.NewRecorder(), []bridge.ActionRequest{{Kind: bridge.ActionFill, Submit: true}}, "batch", "actions") {
+ t.Fatal("fill submit should retain its existing multi-step behavior")
+ }
+}
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.go
index 49ee57de..0ac003f2 100644
--- a/internal/handlers/actions.go
+++ b/internal/handlers/actions.go
@@ -99,6 +99,23 @@ func rejectMixedBrowsers(w http.ResponseWriter, actions []bridge.ActionRequest,
return requestBrowser, true
}
+func rejectMultiStepSubmitClicks(w http.ResponseWriter, actions []bridge.ActionRequest, noun, field string) bool {
+ for i, action := range actions {
+ if bridge.IsSubmitClick(action.Kind, action) {
+ httpx.ErrorCode(
+ w,
+ http.StatusBadRequest,
+ "click_submit_requires_single_action",
+ fmt.Sprintf("%s %s[%d] uses click submit; use a single /action request so its bounded post-state can be reported", noun, field, i),
+ false,
+ nil,
+ )
+ return false
+ }
+ }
+ return true
+}
+
// dialogAwareActionError shapes a per-action error message: it surfaces a blocking
// dialog's own message, or a hint when a click timed out with a pending dialog,
// otherwise the caller-supplied fallback.
@@ -144,7 +161,7 @@ func (h *Handlers) runResolvedActionStep(
} else {
nextCtx = switchedCtx
nextTabID = switchedTabID
- w.Header().Set(activity.HeaderPTTabID, nextTabID)
+ markCreatedTab(w, nextTabID)
h.recordResolvedTab(r, nextTabID)
}
}
@@ -188,6 +205,8 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
req.HasXY = req.HasXY || hasXYParam
req.Button = q.Get("button")
d.Bool("dismissBanners", &req.DismissBanners)
+ d.Bool("dismissKnownInterstitials", &req.DismissKnownInterstitials)
+ d.Bool("submit", &req.Submit)
if d.present("autoSwitch") {
var autoSwitch bool
d.Bool("autoSwitch", &autoSwitch)
@@ -232,6 +251,10 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
httpx.Error(w, 400, fmt.Errorf("dialogAction must be 'accept' or 'dismiss'"))
return
}
+ if err := bridge.ValidateSubmitAction(req.Kind, req); err != nil {
+ httpx.ErrorCode(w, http.StatusBadRequest, "invalid_submit_action", err.Error(), false, nil)
+ return
+ }
h.recordActionRequest(r, req)
if available := h.Bridge.AvailableActions(); len(available) > 0 {
known := false
@@ -291,12 +314,32 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
defer tCancel()
go httpx.CancelOnClientDone(r.Context(), tCancel)
+ if req.DismissKnownInterstitials {
+ if _, err := h.dismissKnownInterstitials(tCtx, resolvedTabID); err != nil {
+ httpx.ErrorCode(w, http.StatusConflict, "known_interstitial_not_dismissed", err.Error(), true, nil)
+ return
+ }
+ }
+
selectorResolution, err := h.resolveActionRequestSelector(tCtx, resolvedTabID, &req)
if err != nil {
httpx.Error(w, selectorResolution.httpStatus(), err)
return
}
refMissing := selectorResolution.refMissing
+ submitClick := bridge.IsSubmitClick(req.Kind, req)
+ if submitClick && refMissing {
+ httpx.ErrorCode(w, http.StatusNotFound, "submit_target_not_found", fmt.Sprintf("ref %s not found - take a /snapshot first", req.Ref), false, map[string]any{
+ "dispatched": false,
+ })
+ return
+ }
+ if submitClick && req.NodeID <= 0 {
+ httpx.ErrorCode(w, http.StatusBadRequest, "invalid_submit_target", "click submit requires a selector, ref, or nodeId", false, map[string]any{
+ "dispatched": false,
+ })
+ return
+ }
// Cache intent before execution so recovery can reconstruct the query.
// Only cache when the ref IS in the snapshot — otherwise we'd overwrite
@@ -312,7 +355,47 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
httpx.Error(w, 404, fmt.Errorf("ref %s not found - take a /snapshot first", req.Ref))
return
}
+
+ var submitBefore submitStateSnapshot
+ if submitClick {
+ submitBefore, err = h.captureSubmitState(tCtx, resolvedTabID)
+ if err != nil {
+ httpx.ErrorCode(w, http.StatusInternalServerError, "submit_pre_state_failed", fmt.Sprintf("capture pre-submit state: %v", err), true, map[string]any{
+ "dispatched": false,
+ })
+ return
+ }
+ }
+
result, actionBackend, recoveryResult, actionErr := h.executeActionResilient(tCtx, &req, effectiveCfg, resolvedTabID, refMissing)
+ submitTimeoutWithDialog := submitClick && isClickTimeoutWithPendingDialog(actionErr, req.Kind, resolvedTabID, h.Bridge)
+ if submitClick && !submitTimeoutWithDialog && (actionErr == nil || errors.Is(actionErr, context.DeadlineExceeded)) {
+ actionTimedOut := errors.Is(actionErr, context.DeadlineExceeded)
+ dispatch := "acknowledged"
+ if actionTimedOut {
+ dispatch = "unconfirmed"
+ }
+
+ // tCtx may be expired here. Keep the live tab context as the parent and
+ // give post-state observation its own bounded, client-cancelable child.
+ postCtx, postCancel := context.WithTimeout(ctx, postSubmitPollTimeout)
+ go httpx.CancelOnClientDone(r.Context(), postCancel)
+ postState, postErr := h.pollSubmitPostState(postCtx, resolvedTabID, submitBefore, dispatch, actionTimedOut)
+ postCancel()
+ if postErr != nil {
+ httpx.ErrorCode(w, http.StatusInternalServerError, "submit_post_state_failed", postErr.Error(), false, map[string]any{
+ "dispatch": dispatch,
+ "actionTimedOut": actionTimedOut,
+ "doNotRetry": true,
+ })
+ return
+ }
+ if result == nil {
+ result = make(map[string]any)
+ }
+ result["postState"] = postState
+ actionErr = nil
+ }
if actionErr != nil {
if strings.HasPrefix(actionErr.Error(), "unknown action") {
kinds := h.Bridge.AvailableActions()
@@ -350,7 +433,15 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
})
return
}
- httpx.ErrorCode(w, 500, "action_failed", fmt.Sprintf("action %s: %v", req.Kind, actionErr), true, nil)
+ retryable := !submitClick
+ var details map[string]any
+ if submitClick {
+ details = map[string]any{
+ "dispatch": "unconfirmed",
+ "doNotRetry": true,
+ }
+ }
+ httpx.ErrorCode(w, 500, "action_failed", fmt.Sprintf("action %s: %v", req.Kind, actionErr), retryable, details)
return
}
@@ -371,7 +462,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
// request-scoped current tab at it so the next action lands there.
if switched := switchedTabFromActionResult(result); switched != "" {
h.setCurrentTabForRequest(r, switched)
- w.Header().Set(activity.HeaderPTTabID, switched)
+ markCreatedTab(w, switched)
h.recordResolvedTab(r, switched)
}
actionRoute := buildActionRoute(resolvedBrowser, requestBrowser, handleDecision)
@@ -399,6 +490,9 @@ func (h *Handlers) HandleActions(w http.ResponseWriter, r *http.Request) {
httpx.Error(w, 400, fmt.Errorf("actions array is empty"))
return
}
+ if !rejectMultiStepSubmitClicks(w, req.Actions, "batch", "actions") {
+ return
+ }
h.handleActionsBatch(w, r, req)
}
@@ -607,6 +701,9 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
httpx.ErrorCode(w, 400, "bad_request", "steps array is empty", false, nil)
return
}
+ if !rejectMultiStepSubmitClicks(w, req.Steps, "macro", "steps") {
+ return
+ }
owner := resolveOwner(r, req.Owner)
// Browser resolution: use the first step's browser field as the request
diff --git a/internal/handlers/activity_helpers.go b/internal/handlers/activity_helpers.go
index 5903be0d..de31809d 100644
--- a/internal/handlers/activity_helpers.go
+++ b/internal/handlers/activity_helpers.go
@@ -80,6 +80,14 @@ func (h *Handlers) recordResolvedTab(r *http.Request, tabID string) {
h.recordActivity(r, activity.Update{TabID: tabID})
}
+func markCreatedTab(w http.ResponseWriter, tabID string) {
+ if w == nil || strings.TrimSpace(tabID) == "" {
+ return
+ }
+ w.Header().Set(activity.HeaderPTTabID, tabID)
+ w.Header().Set(activity.HeaderPTTabCreated, "true")
+}
+
func (h *Handlers) setCurrentTabForRequest(r *http.Request, tabID string) {
if h == nil || h.CurrentTabs == nil {
return
diff --git a/internal/handlers/checked.go b/internal/handlers/checked.go
index b15f96dd..3763e07c 100644
--- a/internal/handlers/checked.go
+++ b/internal/handlers/checked.go
@@ -33,5 +33,8 @@ func (h *Handlers) HandleTabGetChecked(w http.ResponseWriter, r *http.Request) {
// getElementChecked resolves a unified selector to a DOM node and checks whether it is checked.
func (h *Handlers) getElementChecked(ctx context.Context, tabID, sel string) (bool, error) {
- return callOnResolvedElement[bool](h, ctx, tabID, sel, `function() { return !!this.checked; }`, nil)
+ return callOnResolvedElement[bool](h, ctx, tabID, sel, `function() {
+ if (typeof this.checked === "boolean") return this.checked;
+ return (this.getAttribute && this.getAttribute("role") === "checkbox" && this.getAttribute("aria-checked") === "true");
+ }`, nil)
}
diff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.go
index b58c1c0a..70055fde 100644
--- a/internal/handlers/handlers_test.go
+++ b/internal/handlers/handlers_test.go
@@ -8,6 +8,7 @@ import (
"net"
"net/http"
"net/http/httptest"
+ "reflect"
"strings"
"testing"
"time"
@@ -42,9 +43,10 @@ type mockBridge struct {
staticEscalate *bridge.StaticEscalateError
navigateParams []bridge.NavigateParams
- evaluateCalls int
- evaluateExprs []string
- evaluateFn func(expression string, result any) error
+ evaluateCalls int
+ evaluateExprs []string
+ evaluateFn func(expression string, result any) error
+ createTabContexts []string
}
func (m *mockBridge) TabContext(tabID string) (*bridge.TabHandle, string, error) {
@@ -57,7 +59,7 @@ func (m *mockBridge) TabContext(tabID string) (*bridge.TabHandle, string, error)
}
func (m *mockBridge) ListTargets() ([]bridge.TabTarget, error) {
- return []bridge.TabTarget{{TargetID: "tab1", Type: "page"}}, nil
+ return []bridge.TabTarget{{TargetID: "tab1", Type: "page", BrowserContextID: "context-profile"}}, nil
}
func (m *mockBridge) AvailableActions() []string {
@@ -81,6 +83,14 @@ func (m *mockBridge) CreateTab(url string) (string, context.Context, context.Can
return "tab_abc12345", ctx, cancel, nil
}
+func (m *mockBridge) CreateTabInBrowserContext(url, browserContextID string) (string, context.Context, context.CancelFunc, error) {
+ m.createTabURLs = append(m.createTabURLs, url)
+ m.createTabContexts = append(m.createTabContexts, browserContextID)
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ return "tab_abc12345", ctx, cancel, nil
+}
+
func (m *mockBridge) CloseTab(tabID string) error {
if tabID == "fail" {
return fmt.Errorf("close failed")
@@ -516,6 +526,32 @@ func TestHandleTab(t *testing.T) {
if m.createTabURLs[0] != "" {
t.Fatalf("expected HandleTab to create a blank tab first, got %q", m.createTabURLs[0])
}
+ if got := w.Header().Get(activity.HeaderPTTabID); got != "tab_abc12345" {
+ t.Fatalf("created tab header = %q, want tab_abc12345", got)
+ }
+ if got := w.Header().Get(activity.HeaderPTTabCreated); got != "true" {
+ t.Fatalf("created marker header = %q, want true", got)
+ }
+}
+
+func TestHandleTabCreatesBlankTabInAttestedBrowserContext(t *testing.T) {
+ m := &mockBridge{}
+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(
+ `{"action":"new","browserContextId":"context-profile"}`,
+ )))
+ w := httptest.NewRecorder()
+ h.HandleTab(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d: %s", w.Code, w.Body.String())
+ }
+ if !reflect.DeepEqual(m.createTabContexts, []string{"context-profile"}) {
+ t.Fatalf("created contexts = %v, want context-profile", m.createTabContexts)
+ }
+ if !strings.Contains(w.Body.String(), `"browserContextId":"context-profile"`) {
+ t.Fatalf("browser context receipt missing: %s", w.Body.String())
+ }
}
func TestHandleTabCloseByID(t *testing.T) {
diff --git a/internal/handlers/health_tabs.go b/internal/handlers/health_tabs.go
index f266ffbc..ac3f3f65 100644
--- a/internal/handlers/health_tabs.go
+++ b/internal/handlers/health_tabs.go
@@ -35,7 +35,6 @@ func (h *Handlers) HandleHealth(w http.ResponseWriter, r *http.Request) {
httpx.JSON(w, 503, map[string]any{"status": "error", "reason": fmt.Sprintf("browser initialization failed: %v", err)})
return
}
-
targets, err := h.Bridge.ListTargets()
if err != nil {
httpx.JSON(w, 503, map[string]any{"status": "error", "reason": err.Error()})
@@ -148,6 +147,9 @@ func (h *Handlers) HandleTabs(w http.ResponseWriter, r *http.Request) {
httpx.ErrorCode(w, http.StatusServiceUnavailable, "browser_draining", bridge.ErrBrowserDraining.Error(), true, map[string]any{"retryAfterSeconds": seconds})
return
}
+ if !h.ensureBrowserOrRespond(w, h.Config) {
+ return
+ }
targets, err := h.Bridge.ListTargets()
if err != nil {
@@ -173,6 +175,9 @@ func (h *Handlers) HandleTabs(w http.ResponseWriter, r *http.Request) {
"title": t.Title,
"type": t.Type,
}
+ if t.BrowserContextID != "" {
+ entry["browserContextId"] = t.BrowserContextID
+ }
if hr, ok := h.Bridge.(tabHandoffReader); ok {
if hs, ok := hr.TabHandoffState(tabID); ok {
entry["status"] = hs.Status
diff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.go
index ec6ee4d1..3c4a44a6 100644
--- a/internal/handlers/health_tabs_test.go
+++ b/internal/handlers/health_tabs_test.go
@@ -164,6 +164,31 @@ func TestHandleTabs_Success(t *testing.T) {
if len(tabs) != 2 {
t.Errorf("expected 2 tabs, got %d", len(tabs))
}
+ if !mockBridge.ensureBrowserCalled {
+ t.Fatal("expected tab listing to initialize the browser before enumerating existing pages")
+ }
+ if mockBridge.createTabCalled {
+ t.Fatal("tab listing must not create a new page")
+ }
+}
+
+func TestHandleTabs_EnsureBrowserFailureStopsBeforeEnumeration(t *testing.T) {
+ mockBridge := &MockBridge{ensureBrowserErr: "attach failed"}
+ h := &Handlers{Bridge: mockBridge, Config: &config.RuntimeConfig{}}
+ req := httptest.NewRequest("GET", "/tabs", nil)
+ w := httptest.NewRecorder()
+
+ h.HandleTabs(w, req)
+
+ if w.Code == http.StatusOK {
+ t.Fatalf("expected initialization failure, got %d: %s", w.Code, w.Body.String())
+ }
+ if !mockBridge.ensureBrowserCalled {
+ t.Fatal("expected EnsureBrowser to be called")
+ }
+ if mockBridge.listTargetsCalled {
+ t.Fatal("ListTargets must not run after initialization fails")
+ }
}
func TestHandleTabs_CurrentTrackedTabIsReturnedFirst(t *testing.T) {
@@ -302,9 +327,12 @@ type MockBridge struct {
currentTabID string
draining bool
retryAfter time.Duration
+ listTargetsCalled bool
+ createTabCalled bool
}
func (m *MockBridge) ListTargets() ([]bridge.TabTarget, error) {
+ m.listTargetsCalled = true
if m.listTargetsErr != "" {
return nil, fmt.Errorf("%s", m.listTargetsErr)
}
@@ -323,6 +351,7 @@ func (m *MockBridge) TabContext(tabID string) (*bridge.TabHandle, string, error)
}
func (m *MockBridge) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {
+ m.createTabCalled = true
return "", context.Background(), func() {}, nil
}
diff --git a/internal/handlers/interstitial_dismiss.go b/internal/handlers/interstitial_dismiss.go
new file mode 100644
index 00000000..7639e9c0
--- /dev/null
+++ b/internal/handlers/interstitial_dismiss.go
@@ -0,0 +1,80 @@
+package handlers
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+const knownInterstitialTimeout = time.Second
+
+type knownInterstitialResult struct {
+ Action string `json:"action"`
+ CatalogID string `json:"catalogId,omitempty"`
+ Label string `json:"label,omitempty"`
+}
+
+// knownInterstitialDismissJS is intentionally a small allowlist, not another
+// generic modal heuristic. A catalog entry must match the current host, text in
+// a visible modal, and the exact dismissal label before one click is allowed.
+const knownInterstitialDismissJS = `(async () => {
+ const normalize = (value) => String(value || "").replace(/\s+/g, " ").trim().toLowerCase();
+ const visible = (el) => {
+ if (!el || !el.isConnected) return false;
+ const rect = el.getBoundingClientRect();
+ const style = getComputedStyle(el);
+ return rect.width > 0 && rect.height > 0 && style.display !== "none" &&
+ style.visibility !== "hidden" && style.opacity !== "0";
+ };
+ const catalog = [{
+ id: "m365_purview_pay_as_you_go",
+ hosts: ["purview.microsoft.com", "compliance.microsoft.com"],
+ phrases: ["pay-as-you-go", "pay as you go"],
+ dismissLabel: "not now"
+ }];
+ const hostname = normalize(location.hostname).replace(/\.$/, "");
+ for (const entry of catalog) {
+ if (!entry.hosts.some(host => hostname === host || hostname.endsWith("." + host))) continue;
+ const modals = Array.from(document.querySelectorAll(
+ 'dialog[open], [role="dialog"][aria-modal="true"], [aria-modal="true"]'
+ )).filter(visible);
+ for (const modal of modals) {
+ const modalText = normalize(modal.innerText || modal.textContent);
+ if (!entry.phrases.some(phrase => modalText.includes(phrase))) continue;
+ const control = Array.from(modal.querySelectorAll('button, [role="button"]')).find(el =>
+ visible(el) && normalize(el.innerText || el.textContent || el.getAttribute("aria-label")) === entry.dismissLabel
+ );
+ if (!control) return {action: "blocked", catalogId: entry.id, label: entry.dismissLabel};
+ control.click();
+ const deadline = Date.now() + 700;
+ while (Date.now() < deadline) {
+ if (!visible(modal)) return {action: "dismissed", catalogId: entry.id, label: entry.dismissLabel};
+ await new Promise(resolve => setTimeout(resolve, 25));
+ }
+ return {action: "blocked", catalogId: entry.id, label: entry.dismissLabel};
+ }
+ }
+ return {action: "none"};
+})()`
+
+func (h *Handlers) dismissKnownInterstitials(ctx context.Context, tabID string) (knownInterstitialResult, error) {
+ if ctx == nil || tabID == "" {
+ return knownInterstitialResult{}, fmt.Errorf("known interstitial dismissal requires a live tab")
+ }
+ tCtx, cancel := context.WithTimeout(ctx, knownInterstitialTimeout)
+ defer cancel()
+ var result knownInterstitialResult
+ if err := h.Bridge.Evaluate(tCtx, knownInterstitialDismissJS, &result, bridge.EvalOpts{AwaitPromise: true}); err != nil {
+ return result, fmt.Errorf("inspect known interstitials: %w", err)
+ }
+ switch result.Action {
+ case "none", "dismissed":
+ return result, nil
+ case "blocked":
+ return result, fmt.Errorf("recognized interstitial %q could not be dismissed with %q", result.CatalogID, result.Label)
+ default:
+ return result, fmt.Errorf("known interstitial probe returned invalid action %q", result.Action)
+ }
+}
diff --git a/internal/handlers/interstitial_dismiss_test.go b/internal/handlers/interstitial_dismiss_test.go
new file mode 100644
index 00000000..cec8b8d8
--- /dev/null
+++ b/internal/handlers/interstitial_dismiss_test.go
@@ -0,0 +1,119 @@
+package handlers
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestKnownInterstitialDismissalIsCatalogAndModalScoped(t *testing.T) {
+ chromePath, err := exec.LookPath("chromium")
+ if err != nil {
+ t.Skip("chromium not installed")
+ }
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Query().Get("case") {
+ case "known":
+ fmt.Fprint(w, `<div id="payg" role="dialog" aria-modal="true" style="position:fixed;inset:10px;background:white">Pay-as-you-go billing<button id="dismiss" onclick="window.dismissals++;this.parentElement.remove()">Not now</button></div>`)
+ case "missing-control":
+ fmt.Fprint(w, `<div role="dialog" aria-modal="true" style="position:fixed;inset:10px;background:white">Pay as you go billing<button onclick="window.dismissals++">Continue</button></div>`)
+ default:
+ fmt.Fprint(w, `<div role="dialog" aria-modal="true" style="position:fixed;inset:10px;background:white">Ordinary wizard<button onclick="window.dismissals++">Continue</button></div><button id="outside" onclick="window.dismissals++">Not now</button>`)
+ }
+ fmt.Fprint(w, `<script>window.dismissals=0</script>`)
+ }))
+ defer server.Close()
+ serverURL, err := url.Parse(server.URL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ profile, err := os.MkdirTemp("", "pinchtab-interstitial-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
+ chromedp.DefaultExecAllocatorOptions[:],
+ chromedp.ExecPath(chromePath),
+ chromedp.UserDataDir(profile),
+ chromedp.Flag("headless", true),
+ chromedp.Flag("no-sandbox", true),
+ chromedp.Flag("host-resolver-rules", "MAP purview.microsoft.com 127.0.0.1"),
+ )...)
+ ctx, cancelBrowser := chromedp.NewContext(alloc)
+ ctx, cancelTimeout := context.WithTimeout(ctx, 20*time.Second)
+ t.Cleanup(func() {
+ cancelTimeout()
+ cancelBrowser()
+ cancelAlloc()
+ _ = os.RemoveAll(profile)
+ })
+
+ cfg := &config.RuntimeConfig{ActionTimeout: 5 * time.Second, DefaultBrowser: config.BrowserChrome, StateDir: t.TempDir()}
+ b := bridge.New(context.Background(), ctx, cfg)
+ b.TabManager.RegisterTab("tab-interstitial", ctx)
+ h := New(b, cfg, nil, nil, nil)
+ pageURL := func(testCase string) string {
+ return "http://purview.microsoft.com:" + serverURL.Port() + "/?case=" + testCase
+ }
+
+ if err := chromedp.Run(ctx, chromedp.Navigate(pageURL("known"))); err != nil {
+ t.Fatal(err)
+ }
+ result, err := h.dismissKnownInterstitials(ctx, "tab-interstitial")
+ if err != nil || result.Action != "dismissed" || result.CatalogID != "m365_purview_pay_as_you_go" {
+ t.Fatalf("known result=%+v error=%v", result, err)
+ }
+ var dismissals int
+ if err := chromedp.Run(ctx, chromedp.Evaluate(`window.dismissals`, &dismissals)); err != nil {
+ t.Fatal(err)
+ }
+ if dismissals != 1 {
+ t.Fatalf("known interstitial clicks = %d, want exactly 1", dismissals)
+ }
+
+ if err := chromedp.Run(ctx, chromedp.Navigate(pageURL("ordinary"))); err != nil {
+ t.Fatal(err)
+ }
+ result, err = h.dismissKnownInterstitials(ctx, "tab-interstitial")
+ if err != nil || result.Action != "none" {
+ t.Fatalf("ordinary result=%+v error=%v", result, err)
+ }
+ if err := chromedp.Run(ctx, chromedp.Evaluate(`window.dismissals`, &dismissals)); err != nil {
+ t.Fatal(err)
+ }
+ if dismissals != 0 {
+ t.Fatalf("ordinary page clicks = %d, want 0", dismissals)
+ }
+
+ if err := chromedp.Run(ctx, chromedp.Navigate(pageURL("missing-control"))); err != nil {
+ t.Fatal(err)
+ }
+ result, err = h.dismissKnownInterstitials(ctx, "tab-interstitial")
+ if err == nil || result.Action != "blocked" || !strings.Contains(err.Error(), "could not be dismissed") {
+ t.Fatalf("missing-control result=%+v error=%v", result, err)
+ }
+}
+
+func TestKnownInterstitialScriptNeverHardRemovesOrClicksGenericDialogs(t *testing.T) {
+ for _, forbidden := range []string{".remove()", `labels.some`, `document.querySelectorAll('button`} {
+ if strings.Contains(knownInterstitialDismissJS, forbidden) {
+ t.Fatalf("known interstitial script contains generic behavior %q", forbidden)
+ }
+ }
+ for _, required := range []string{"purview.microsoft.com", "compliance.microsoft.com", "pay-as-you-go", "not now"} {
+ if !strings.Contains(knownInterstitialDismissJS, required) {
+ t.Fatalf("known interstitial script missing catalog key %q", required)
+ }
+ }
+}
diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.go
index 15ba83b7..23df9d78 100644
--- a/internal/handlers/navigation.go
+++ b/internal/handlers/navigation.go
@@ -71,6 +71,7 @@ type navigateRequest struct {
WaitFor string `json:"waitFor"`
WaitSelector string `json:"waitSelector"`
DismissBanners bool `json:"dismissBanners"`
+ DispatchOnly bool `json:"dispatchOnly"`
Browser string `json:"browser,omitempty"`
}
@@ -87,6 +88,7 @@ func decodeNavigateRequest(w http.ResponseWriter, r *http.Request) (navigateRequ
req.WaitFor = q.Get("waitFor")
req.WaitSelector = q.Get("waitSelector")
d.Bool("dismissBanners", &req.DismissBanners)
+ d.Bool("dispatchOnly", &req.DispatchOnly)
req.Browser = q.Get("browser")
d.Float("waitTitle", &req.WaitTitle)
d.Float("timeout", &req.Timeout)
@@ -337,6 +339,7 @@ func (h *Handlers) tryStaticFirstNavigate(w http.ResponseWriter, r *http.Request
}
h.setCurrentTabForRequest(r, navResult.TabID)
h.recordResolvedURL(r, navResult.URL)
+ markCreatedTab(w, navResult.TabID)
httpx.JSON(w, 200, map[string]any{"tabId": navResult.TabID, "url": navResult.URL, "title": navResult.Title, "route": navRoute})
return staticFirstOutcome{handled: true}
}
@@ -456,6 +459,7 @@ func (h *Handlers) executeNavigate(w http.ResponseWriter, r *http.Request, req n
waitSelector: req.WaitSelector,
titleWait: titleWait,
dismissBanners: req.DismissBanners,
+ dispatchOnly: req.DispatchOnly,
target: targets.target,
trustedCIDRs: targets.trustedCIDRs,
blockPatterns: blockPatterns,
@@ -478,6 +482,7 @@ type navExec struct {
waitSelector string
titleWait time.Duration
dismissBanners bool
+ dispatchOnly bool
target *validatedNavigateTarget
trustedCIDRs []*net.IPNet
blockPatterns []string
@@ -504,6 +509,7 @@ func (h *Handlers) runNavigate(w http.ResponseWriter, r *http.Request, ex navExe
navResult, navErr := h.Bridge.Navigate(ex.ctx, ex.url, bridge.NavigateParams{
MaxRedirects: ex.maxRedirects,
SkipStatic: ex.skipStatic,
+ DispatchOnly: ex.dispatchOnly,
})
if navErr != nil {
if ex.isNewTab {
@@ -538,6 +544,17 @@ func (h *Handlers) runNavigate(w http.ResponseWriter, r *http.Request, ex navExe
h.Bridge.DeleteRefCache(ex.tabID)
h.clearTabFrameScope(ex.tabID)
}
+ if ex.dispatchOnly {
+ h.setCurrentTabForRequest(r, ex.tabID)
+ h.recordResolvedURL(r, ex.url)
+ h.recordActivity(r, activity.Update{
+ Action: "navigate.dispatch", TabID: ex.tabID, URL: ex.url,
+ })
+ httpx.JSON(w, 200, map[string]any{
+ "tabId": ex.tabID, "url": ex.url, "dispatched": true,
+ })
+ return
+ }
// The ghost-chrome adapter may serve a navigate from a static tab instead of
// the tab this handler drove; its result is authoritative. The static
@@ -551,6 +568,7 @@ func (h *Handlers) runNavigate(w http.ResponseWriter, r *http.Request, ex navExe
h.setCurrentTabForRequest(r, navResult.TabID)
if ex.isNewTab {
h.recordResolvedTab(r, navResult.TabID)
+ markCreatedTab(w, navResult.TabID)
}
h.recordResolvedURL(r, navResult.URL)
httpx.JSON(w, 200, navResponse(navResult.TabID, navResult.URL, navResult.Title, route, !ex.isNewTab))
@@ -570,6 +588,7 @@ func (h *Handlers) runNavigate(w http.ResponseWriter, r *http.Request, ex navExe
h.setCurrentTabForRequest(r, ex.tabID)
if ex.isNewTab {
h.recordResolvedTab(r, ex.tabID)
+ markCreatedTab(w, ex.tabID)
}
h.recordResolvedURL(r, navURL)
diff --git a/internal/handlers/navigation_browser_test.go b/internal/handlers/navigation_browser_test.go
index 0aaccdbc..97e114a9 100644
--- a/internal/handlers/navigation_browser_test.go
+++ b/internal/handlers/navigation_browser_test.go
@@ -11,6 +11,7 @@ import (
"strings"
"testing"
+ "github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/browserops"
"github.com/pinchtab/pinchtab/internal/config"
@@ -468,6 +469,9 @@ func TestHandleNavigate_AdapterServedTab_ExistingTab_ReturnsAdapterResult(t *tes
if resp["title"] != "Static Page" {
t.Fatalf("title = %v, want adapter title", resp["title"])
}
+ if got := w.Header().Get(activity.HeaderPTTabCreated); got != "" {
+ t.Fatalf("existing-tab navigate marked tab created: %q", got)
+ }
}
func TestHandleNavigate_AdapterServedTab_NewTab_ClosesUnusedBlankTab(t *testing.T) {
@@ -499,6 +503,12 @@ func TestHandleNavigate_AdapterServedTab_NewTab_ClosesUnusedBlankTab(t *testing.
if len(m.closedTabs) != 1 || m.closedTabs[0] != "tab_abc12345" {
t.Fatalf("closedTabs = %v, want the unused blank tab [tab_abc12345]", m.closedTabs)
}
+ if got := w.Header().Get(activity.HeaderPTTabID); got != "lite-1" {
+ t.Fatalf("created tab header = %q, want lite-1", got)
+ }
+ if got := w.Header().Get(activity.HeaderPTTabCreated); got != "true" {
+ t.Fatalf("created marker header = %q, want true", got)
+ }
}
// When the adapter's result identifies the same tab the handler drove (chrome,
@@ -666,6 +676,12 @@ func TestHandleNavigate_StaticFirstServesWithoutChromeLaunch(t *testing.T) {
if len(m.createTabURLs) != 0 {
t.Fatalf("a Chrome tab was created for a static-served navigate: %v", m.createTabURLs)
}
+ if got := w.Header().Get(activity.HeaderPTTabID); got != "lite-1" {
+ t.Fatalf("created tab header = %q, want lite-1", got)
+ }
+ if got := w.Header().Get(activity.HeaderPTTabCreated); got != "true" {
+ t.Fatalf("created marker header = %q, want true", got)
+ }
}
// On escalation the handler launches Chrome, retries with SkipStatic, and the
diff --git a/internal/handlers/navigation_test.go b/internal/handlers/navigation_test.go
index ebae4987..09759193 100644
--- a/internal/handlers/navigation_test.go
+++ b/internal/handlers/navigation_test.go
@@ -10,6 +10,7 @@ import (
"strings"
"testing"
+ "github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/navguard"
"github.com/pinchtab/pinchtab/internal/netguard"
@@ -305,6 +306,28 @@ func TestHandleNavigate_RejectsUnsupportedSchemeForExistingTab(t *testing.T) {
}
}
+func TestHandleNavigateDispatchOnlyReturnsAfterAcceptedBackgroundNavigation(t *testing.T) {
+ m := &mockBridge{navigateResult: &bridge.NavigateResult{
+ URL: "http://localhost:8765/slow-spa",
+ }}
+ h := New(m, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(
+ `{"tabId":"tab1","url":"http://localhost:8765/slow-spa","dispatchOnly":true}`,
+ )))
+ w := httptest.NewRecorder()
+ h.HandleNavigate(w, req)
+
+ if w.Code != 200 {
+ t.Fatalf("dispatch-only status = %d: %s", w.Code, w.Body.String())
+ }
+ if len(m.navigateParams) != 1 || !m.navigateParams[0].DispatchOnly {
+ t.Fatalf("navigate params = %+v, want DispatchOnly", m.navigateParams)
+ }
+ if !strings.Contains(w.Body.String(), `"dispatched":true`) {
+ t.Fatalf("dispatch-only receipt missing: %s", w.Body.String())
+ }
+}
+
func TestValidateNavigateTarget_AllowsPrivateIPWithTrustedResolveCIDR(t *testing.T) {
stubNavigateHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {
return []net.IP{net.ParseIP("10.0.0.5")}, nil
diff --git a/internal/handlers/network.go b/internal/handlers/network.go
index d35f2355..1c358f26 100644
--- a/internal/handlers/network.go
+++ b/internal/handlers/network.go
@@ -12,6 +12,7 @@ import (
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/bridge/observe"
"github.com/pinchtab/pinchtab/internal/httpx"
+ "github.com/pinchtab/pinchtab/internal/routes"
)
const (
@@ -281,6 +282,10 @@ func (h *Handlers) HandleNetwork(w http.ResponseWriter, r *http.Request) {
// @Response 200 application/json Network entry details
// @Response 404 application/json Request not found
func (h *Handlers) HandleNetworkByID(w http.ResponseWriter, r *http.Request) {
+ if !h.networkInterceptEnabled() {
+ h.writeCapabilityDisabled(w, routes.CapNetworkIntercept)
+ return
+ }
if !h.ensureBrowserReady(w) {
return
}
@@ -366,6 +371,10 @@ func (h *Handlers) HandleNetworkByID(w http.ResponseWriter, r *http.Request) {
//
// @Response 200 application/json Success
func (h *Handlers) HandleNetworkClear(w http.ResponseWriter, r *http.Request) {
+ if !h.networkInterceptEnabled() {
+ h.writeCapabilityDisabled(w, routes.CapNetworkIntercept)
+ return
+ }
nm := h.Bridge.NetworkMonitor()
if nm == nil {
httpx.JSON(w, 200, map[string]any{"cleared": true})
diff --git a/internal/handlers/network_route_test.go b/internal/handlers/network_route_test.go
index 0f235878..9cf1c3d4 100644
--- a/internal/handlers/network_route_test.go
+++ b/internal/handlers/network_route_test.go
@@ -125,6 +125,30 @@ func TestHandleTabNetworkRoute_CapabilityDisabled(t *testing.T) {
}
}
+func TestNetworkInterceptSecurityStateIncludesEveryGatedDirectRoute(t *testing.T) {
+ h := New(newRouteMockBridge(), &config.RuntimeConfig{}, nil, nil, nil)
+ state := h.endpointSecurityStates()["networkIntercept"]
+ want := []string{
+ "GET /network/{requestId}",
+ "GET /tabs/{id}/network/{requestId}",
+ "POST /network/clear",
+ "GET /network/route",
+ "POST /network/route",
+ "DELETE /network/route",
+ "GET /tabs/{id}/network/route",
+ "POST /tabs/{id}/network/route",
+ "DELETE /tabs/{id}/network/route",
+ }
+ if len(state.Paths) != len(want) {
+ t.Fatalf("security paths = %v, want %v", state.Paths, want)
+ }
+ for i := range want {
+ if state.Paths[i] != want[i] {
+ t.Fatalf("security path[%d] = %q, want %q", i, state.Paths[i], want[i])
+ }
+ }
+}
+
func TestHandleTabNetworkUnroute_CapabilityDisabled(t *testing.T) {
b := newRouteMockBridge()
h := New(b, &config.RuntimeConfig{}, nil, nil, nil)
diff --git a/internal/handlers/network_test.go b/internal/handlers/network_test.go
index 20f7a12c..92a6e402 100644
--- a/internal/handlers/network_test.go
+++ b/internal/handlers/network_test.go
@@ -51,7 +51,36 @@ func (m *networkMockBridge) NetworkMonitor() *bridge.NetworkMonitor {
func newNetworkTestHandler(nm *bridge.NetworkMonitor) *Handlers {
b := &networkMockBridge{nm: nm}
- return New(b, &config.RuntimeConfig{}, nil, nil, nil)
+ return New(b, &config.RuntimeConfig{AllowNetworkIntercept: true}, nil, nil, nil)
+}
+
+func TestNetworkDetailAndClearRequireNetworkIntercept(t *testing.T) {
+ h := New(&networkMockBridge{nm: bridge.NewNetworkMonitor(100)}, &config.RuntimeConfig{}, nil, nil, nil)
+ mux := http.NewServeMux()
+ h.RegisterRoutes(mux, nil)
+
+ for _, tc := range []struct {
+ method string
+ path string
+ }{
+ {http.MethodGet, "/network/request-1"},
+ {http.MethodGet, "/tabs/tab1/network/request-1"},
+ {http.MethodPost, "/network/clear"},
+ } {
+ t.Run(tc.method+" "+tc.path, func(t *testing.T) {
+ req := httptest.NewRequest(tc.method, tc.path, nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want 403: %s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "network_intercept_disabled") ||
+ !strings.Contains(w.Body.String(), "security.allowNetworkIntercept") {
+ t.Fatalf("disabled response missing catalog metadata: %s", w.Body.String())
+ }
+ })
+ }
}
func seedBuffer(nm *bridge.NetworkMonitor, tabID string) {
diff --git a/internal/handlers/screenshot.go b/internal/handlers/screenshot.go
index 363c79ca..6abe015c 100644
--- a/internal/handlers/screenshot.go
+++ b/internal/handlers/screenshot.go
@@ -97,8 +97,9 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
// Route through the shared bridge.CaptureScreenshot engine: it carries the
// scale/beyondViewport clip synthesis and the provider-runtime fixes
- // (BringToFront + WithFromSurface(false)) so capture works on chrome and
- // cloak alike; tCtx already targets the active provider's CDP session.
+ // (non-activating focus emulation + WithFromSurface(false)) so capture works
+ // without switching the operator's active tab; tCtx already targets the
+ // active provider's CDP session.
cdpFormat := bridge.ScreenshotFormatJpeg
if req.format == "png" {
cdpFormat = bridge.ScreenshotFormatPng
diff --git a/internal/handlers/security.go b/internal/handlers/security.go
index 01276389..3800ec0a 100644
--- a/internal/handlers/security.go
+++ b/internal/handlers/security.go
@@ -90,6 +90,7 @@ func (h *Handlers) endpointSecurityStates() map[string]endpointSecurityState {
}),
"networkIntercept": capState(routes.CapNetworkIntercept, h.networkInterceptEnabled(),
[]string{
+ "GET /network/{requestId}", "GET /tabs/{id}/network/{requestId}", "POST /network/clear",
"GET /network/route", "POST /network/route", "DELETE /network/route",
"GET /tabs/{id}/network/route", "POST /tabs/{id}/network/route", "DELETE /tabs/{id}/network/route",
}),
diff --git a/internal/handlers/semantic_selectors.go b/internal/handlers/semantic_selectors.go
index f6750266..2f18f90f 100644
--- a/internal/handlers/semantic_selectors.go
+++ b/internal/handlers/semantic_selectors.go
@@ -12,10 +12,14 @@ import (
)
func (h *Handlers) applySemanticActionSelector(ctx context.Context, tabID string, sel selector.Selector, req *bridge.ActionRequest) (bool, error) {
- return h.applySemanticActionSelectorInFrame(ctx, tabID, h.selectorFrameID(tabID), sel, req)
+ return h.applySemanticActionSelectorInScope(ctx, tabID, h.selectorFrameID(tabID), 0, sel, req)
}
func (h *Handlers) applySemanticActionSelectorInFrame(ctx context.Context, tabID, frameID string, sel selector.Selector, req *bridge.ActionRequest) (bool, error) {
+ return h.applySemanticActionSelectorInScope(ctx, tabID, frameID, 0, sel, req)
+}
+
+func (h *Handlers) applySemanticActionSelectorInScope(ctx context.Context, tabID, frameID string, scopeBackendNodeID int64, sel selector.Selector, req *bridge.ActionRequest) (bool, error) {
query, ok := sel.SemanticQuery()
if !ok {
return false, nil
@@ -24,7 +28,37 @@ func (h *Handlers) applySemanticActionSelectorInFrame(ctx context.Context, tabID
return true, fmt.Errorf("semantic selectors require a matcher (not configured)")
}
- descs, err := h.semanticDescriptorsForTabInFrame(ctx, tabID, frameID)
+ var (
+ descs []semantic.ElementDescriptor
+ nodes []bridge.A11yNode
+ err error
+ )
+ if scopeBackendNodeID != 0 {
+ var rawNodes []bridge.RawAXNode
+ rawNodes, err = bridge.FetchAXTree(ctx)
+ if err == nil {
+ foundScope := false
+ for _, node := range rawNodes {
+ if node.BackendDOMNodeID == scopeBackendNodeID {
+ foundScope = true
+ break
+ }
+ }
+ if !foundScope {
+ err = fmt.Errorf("semantic selector: topmost dialog is absent from the accessibility tree")
+ } else {
+ rawNodes = bridge.FilterSubtree(rawNodes, scopeBackendNodeID)
+ nodes, _ = bridge.BuildSnapshot(rawNodes, "", -1)
+ _ = bridge.EnrichA11yNodesWithDOMMetadata(ctx, nodes)
+ descs = semanticDescriptorsFromNodes(nodes)
+ if len(descs) == 0 {
+ err = fmt.Errorf("semantic selector: no elements found in topmost dialog")
+ }
+ }
+ }
+ } else {
+ descs, err = h.semanticDescriptorsForTabInFrame(ctx, tabID, frameID)
+ }
if err != nil {
return true, err
}
@@ -39,6 +73,18 @@ func (h *Handlers) applySemanticActionSelectorInFrame(ctx context.Context, tabID
return true, fmt.Errorf("semantic selector %q: no matching element found", query)
}
+ if scopeBackendNodeID != 0 {
+ for _, node := range nodes {
+ if node.Ref == result.BestRef && node.NodeID != 0 {
+ req.Ref = ""
+ req.NodeID = node.NodeID
+ req.Selector = ""
+ return true, nil
+ }
+ }
+ return true, fmt.Errorf("semantic selector %q matched ref %s but no dialog node is available", query, result.BestRef)
+ }
+
cache := h.Bridge.GetRefCache(tabID)
if cache == nil {
return true, fmt.Errorf("semantic selector %q: no snapshot cache available", query)
@@ -47,7 +93,6 @@ func (h *Handlers) applySemanticActionSelectorInFrame(ctx context.Context, tabID
if !ok || target.BackendNodeID == 0 {
return true, fmt.Errorf("semantic selector %q matched ref %s but no node is available", query, result.BestRef)
}
-
req.Ref = result.BestRef
req.NodeID = target.BackendNodeID
req.Selector = ""
diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.go
index 1c749bb2..d649caad 100644
--- a/internal/handlers/snapshot.go
+++ b/internal/handlers/snapshot.go
@@ -1,6 +1,7 @@
package handlers
import (
+ "context"
"encoding/json"
"fmt"
"net/http"
@@ -12,7 +13,9 @@ import (
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/browsers"
+ "github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/httpx"
+ selectorpkg "github.com/pinchtab/pinchtab/internal/selector"
"gopkg.in/yaml.v3"
)
@@ -110,23 +113,46 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
var scopeNodeID int64
frameScope := h.selectorFrameID(resolvedTabID)
- if frameScope != "" || selector != "" {
+ ghostRoute := snapChromeRoute != nil && snapChromeRoute.UsedBrowser == config.BrowserGhostChrome
+ var modalOpen bool
+ if frameScope != "" || selector != "" || !ghostRoute {
// Frame-scoped or selector-scoped: inline AX tree fetch with scoping.
- rawNodes, err := bridge.FetchAXTree(tCtx)
- if err != nil {
- httpx.Error(w, 500, fmt.Errorf("a11y tree: %w", err))
- return
- }
- rawNodes = bridge.FilterAXNodesByFrame(rawNodes, frameScope)
+ var rawNodes []bridge.RawAXNode
+ stable := false
+ for attempt := 0; attempt < 2; attempt++ {
+ var modalNodeID int64
+ var modalErr error
+ if !ghostRoute {
+ modalNodeID, modalOpen, modalErr = bridge.TopmostModalNodeID(tCtx, frameScope)
+ if modalErr != nil {
+ httpx.Error(w, selectorResolutionHTTPStatus(modalErr), fmt.Errorf("resolve topmost dialog: %w", modalErr))
+ return
+ }
+ }
- if selector != "" {
- var scopeErr error
- scopeNodeID, scopeErr = h.resolveSelectorNodeID(tCtx, resolvedTabID, selector)
+ candidateNodes, candidateScope, scopeErr := h.scopedSnapshotNodes(
+ tCtx, resolvedTabID, frameScope, selector, modalNodeID, modalOpen,
+ )
+ if !ghostRoute {
+ afterNodeID, afterOpen, recheckErr := bridge.TopmostModalNodeID(tCtx, frameScope)
+ if recheckErr != nil {
+ httpx.Error(w, selectorResolutionHTTPStatus(recheckErr), fmt.Errorf("recheck topmost dialog: %w", recheckErr))
+ return
+ }
+ if modalNodeID != afterNodeID || modalOpen != afterOpen {
+ continue
+ }
+ }
if scopeErr != nil {
- httpx.Error(w, 400, frameScopedSelectorError("selector", scopeErr))
+ httpx.Error(w, selectorResolutionHTTPStatus(scopeErr), scopeErr)
return
}
- rawNodes = bridge.FilterSubtree(rawNodes, scopeNodeID)
+ rawNodes, scopeNodeID, stable = candidateNodes, candidateScope, true
+ break
+ }
+ if !stable {
+ httpx.Error(w, http.StatusConflict, fmt.Errorf("topmost dialog changed twice during snapshot; retry after the page settles"))
+ return
}
flat, refs = bridge.BuildSnapshot(rawNodes, filter, maxDepth)
@@ -432,6 +458,57 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
}
}
+func (h *Handlers) scopedSnapshotNodes(
+ ctx context.Context,
+ tabID, frameScope, rawSelector string,
+ modalNodeID int64,
+ modalOpen bool,
+) ([]bridge.RawAXNode, int64, error) {
+ rawNodes, err := bridge.FetchAXTree(ctx)
+ if err != nil {
+ return nil, 0, fmt.Errorf("a11y tree: %w", err)
+ }
+ if !modalOpen {
+ rawNodes = bridge.FilterAXNodesByFrame(rawNodes, frameScope)
+ }
+ scopeNodeID := int64(0)
+ if modalOpen {
+ if !axTreeContainsBackendNode(rawNodes, modalNodeID) {
+ return nil, 0, fmt.Errorf("topmost dialog is absent from the accessibility tree")
+ }
+ rawNodes = bridge.FilterSubtree(rawNodes, modalNodeID)
+ scopeNodeID = modalNodeID
+ }
+
+ if rawSelector == "" {
+ return rawNodes, scopeNodeID, nil
+ }
+ if modalOpen {
+ scopeNodeID, err = bridge.ResolveUnifiedSelectorWithinNode(ctx, selectorpkg.Parse(rawSelector), h.Bridge.GetRefCache(tabID), modalNodeID)
+ } else {
+ scopeNodeID, err = h.resolveSelectorNodeID(ctx, tabID, rawSelector)
+ }
+ if err != nil {
+ return nil, 0, frameScopedSelectorError("selector", err)
+ }
+ if !axTreeContainsBackendNode(rawNodes, scopeNodeID) {
+ // A valid DOM element can be absent from the accessibility tree. Return
+ // an empty scoped result so FilterSubtree's legacy not-found fallback
+ // cannot expose the surrounding modal or page.
+ return nil, scopeNodeID, nil
+ }
+ return bridge.FilterSubtree(rawNodes, scopeNodeID), scopeNodeID, nil
+}
+
+func axTreeContainsBackendNode(nodes []bridge.RawAXNode, backendNodeID int64) bool {
+ for _, node := range nodes {
+ if node.BackendDOMNodeID == backendNodeID {
+ return true
+ }
+ }
+ return false
+}
+
// @Endpoint GET /tabs/{id}/snapshot
func (h *Handlers) HandleTabSnapshot(w http.ResponseWriter, r *http.Request) {
h.withPathTabID(w, r, h.HandleSnapshot)
diff --git a/internal/handlers/tab_lifecycle.go b/internal/handlers/tab_lifecycle.go
index 5917a694..cac2f3c3 100644
--- a/internal/handlers/tab_lifecycle.go
+++ b/internal/handlers/tab_lifecycle.go
@@ -1,6 +1,7 @@
package handlers
import (
+ "context"
"encoding/json"
"errors"
"fmt"
@@ -14,11 +15,16 @@ import (
const tabActionNew = "new"
+type browserContextTabCreator interface {
+ CreateTabInBrowserContext(url, browserContextID string) (string, context.Context, context.CancelFunc, error)
+}
+
func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {
var req struct {
- Action string `json:"action"`
- TabID string `json:"tabId"`
- URL string `json:"url"`
+ Action string `json:"action"`
+ TabID string `json:"tabId"`
+ URL string `json:"url"`
+ BrowserContextID string `json:"browserContextId"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
httpx.Error(w, 400, fmt.Errorf("decode: %w", err))
@@ -35,7 +41,7 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {
h.navigateToURL(w, r, navigateRequest{URL: req.URL, NewTab: true})
return
}
- h.createBlankTab(w, r)
+ h.createBlankTab(w, r, strings.TrimSpace(req.BrowserContextID))
case "focus":
if req.TabID == "" {
@@ -64,12 +70,42 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {
// about:blank form of POST /tab {"action":"new"}. The URL form converges onto the
// shared navigate pipeline (navigateToURL); this path has no URL to validate,
// route, or navigate, so it reports {tabId,url,title} and a tab.new activity.
-func (h *Handlers) createBlankTab(w http.ResponseWriter, r *http.Request) {
+func (h *Handlers) createBlankTab(w http.ResponseWriter, r *http.Request, browserContextID string) {
if !h.ensureBrowserOrRespond(w, h.Config) {
return
}
- newTabID, ctx, _, err := h.Bridge.CreateTab("")
+ var (
+ newTabID string
+ ctx context.Context
+ err error
+ )
+ if browserContextID == "" {
+ newTabID, ctx, _, err = h.Bridge.CreateTab("")
+ } else {
+ contextExists := false
+ targets, listErr := h.Bridge.ListTargets()
+ if listErr != nil {
+ httpx.Error(w, 503, fmt.Errorf("list browser contexts: %w", listErr))
+ return
+ }
+ for _, candidate := range targets {
+ if candidate.BrowserContextID == browserContextID {
+ contextExists = true
+ break
+ }
+ }
+ if !contextExists {
+ httpx.Error(w, 400, fmt.Errorf("browserContextId is not owned by an attached page"))
+ return
+ }
+ creator, ok := h.Bridge.(browserContextTabCreator)
+ if !ok {
+ httpx.Error(w, 501, fmt.Errorf("browser-context tab creation is unavailable"))
+ return
+ }
+ newTabID, ctx, _, err = creator.CreateTabInBrowserContext("", browserContextID)
+ }
if err != nil {
httpx.Error(w, 500, err)
return
@@ -80,7 +116,12 @@ func (h *Handlers) createBlankTab(w http.ResponseWriter, r *http.Request) {
h.setCurrentTabForRequest(r, newTabID)
h.recordActivity(r, activity.Update{Action: "tab.new", TabID: newTabID, URL: curURL})
- httpx.JSON(w, 200, map[string]any{"tabId": newTabID, "url": curURL, "title": title})
+ markCreatedTab(w, newTabID)
+ response := map[string]any{"tabId": newTabID, "url": curURL, "title": title}
+ if browserContextID != "" {
+ response["browserContextId"] = browserContextID
+ }
+ httpx.JSON(w, 200, response)
}
// HandleTabClose closes the tab identified by the path. It is the tab-scoped
diff --git a/internal/handlers/tab_policy.go b/internal/handlers/tab_policy.go
index 1692de0e..eb8aebdf 100644
--- a/internal/handlers/tab_policy.go
+++ b/internal/handlers/tab_policy.go
@@ -2,6 +2,7 @@ package handlers
import (
"context"
+ "errors"
"fmt"
"net/http"
"time"
@@ -48,6 +49,21 @@ func (h *Handlers) enforceCurrentTabDomainPolicy(w http.ResponseWriter, r *http.
currentURL, err := h.Bridge.CurrentURL(lookupCtx)
if err != nil {
+ if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
+ httpx.ErrorCode(
+ w,
+ http.StatusServiceUnavailable,
+ "tab_unresponsive",
+ fmt.Sprintf("tab %s is busy, suspended, or unresponsive; activate it or open a fresh tab, then retry the same explicit tab", tabID),
+ true,
+ map[string]any{
+ "tabId": tabID,
+ "classification": "suspended_or_busy",
+ "requiresStateChange": true,
+ },
+ )
+ return "", false
+ }
httpx.Error(w, 500, fmt.Errorf("resolve current tab url: %w", err))
return "", false
}
diff --git a/internal/handlers/tab_policy_test.go b/internal/handlers/tab_policy_test.go
index 62b4b25a..be95f5ee 100644
--- a/internal/handlers/tab_policy_test.go
+++ b/internal/handlers/tab_policy_test.go
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"net/http/httptest"
+ "strings"
"testing"
"time"
@@ -12,6 +13,24 @@ import (
"github.com/pinchtab/pinchtab/internal/config"
)
+type busyPolicyBridge struct {
+ policyMockBridge
+ currentURLErr error
+ tabContextIDs []string
+}
+
+func (b *busyPolicyBridge) TabContext(tabID string) (*bridge.TabHandle, string, error) {
+ b.tabContextIDs = append(b.tabContextIDs, tabID)
+ return bridge.NewTabHandle(context.Background()), tabID, nil
+}
+
+func (b *busyPolicyBridge) CurrentURL(context.Context) (string, error) {
+ if b.currentURLErr != nil {
+ return "", b.currentURLErr
+ }
+ return "https://example.com/report", nil
+}
+
type policyMockBridge struct {
mockBridge
state bridge.TabPolicyState
@@ -136,3 +155,49 @@ func TestHandleBackIgnoresCachedTabPolicyBlock(t *testing.T) {
t.Fatalf("expected back to bypass current-tab policy enforcement, got %d: %s", w.Code, w.Body.String())
}
}
+
+func TestExplicitTabWaitReturnsRetryableBusyWithoutLosingTab(t *testing.T) {
+ b := &busyPolicyBridge{currentURLErr: context.DeadlineExceeded}
+ b.mockBridge.evaluateFn = func(_ string, result any) error {
+ *(result.(*bool)) = true
+ return nil
+ }
+ h := New(b, &config.RuntimeConfig{
+ AllowedDomains: []string{"example.com"},
+ IDPI: config.IDPIConfig{Enabled: true, StrictMode: true},
+ }, nil, nil, nil)
+
+ req := httptest.NewRequest("POST", "/tabs/exact-tab/wait", nil)
+ w := httptest.NewRecorder()
+ h.handleWaitCore(w, req, waitRequest{TabID: "exact-tab", Text: "ready"})
+
+ if w.Code != 503 {
+ t.Fatalf("expected 503 tab_busy, got %d: %s", w.Code, w.Body.String())
+ }
+ var failure struct {
+ Code string `json:"code"`
+ Retryable bool `json:"retryable"`
+ Details struct {
+ TabID string `json:"tabId"`
+ } `json:"details"`
+ }
+ if err := json.Unmarshal(w.Body.Bytes(), &failure); err != nil {
+ t.Fatalf("decode busy response: %v", err)
+ }
+ if failure.Code != "tab_unresponsive" || !failure.Retryable || failure.Details.TabID != "exact-tab" ||
+ !strings.Contains(w.Body.String(), "activate it or open a fresh tab") {
+ t.Fatalf("unexpected busy response: %+v", failure)
+ }
+
+ b.currentURLErr = nil
+ retry := httptest.NewRecorder()
+ h.handleWaitCore(retry, req, waitRequest{TabID: "exact-tab", Text: "ready"})
+ if retry.Code != 200 {
+ t.Fatalf("same explicit tab did not recover: %d %s", retry.Code, retry.Body.String())
+ }
+ for _, got := range b.tabContextIDs {
+ if got != "exact-tab" {
+ t.Fatalf("explicit tab changed across retry: %v", b.tabContextIDs)
+ }
+ }
+}
diff --git a/internal/handlers/text.go b/internal/handlers/text.go
index 49e57c78..b20d2730 100644
--- a/internal/handlers/text.go
+++ b/internal/handlers/text.go
@@ -13,7 +13,9 @@ import (
"github.com/pinchtab/pinchtab/internal/bridge/observe"
"github.com/pinchtab/pinchtab/internal/browserops"
"github.com/pinchtab/pinchtab/internal/browsers"
+ "github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/httpx"
+ "github.com/pinchtab/pinchtab/internal/selector"
)
// @Endpoint GET /text
@@ -50,30 +52,64 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
// reach at least "interactive" before extracting text. Prevents empty or
// partial results when text is called before the page finishes loading.
h.waitForReadyState(tCtx)
-
selectorParam := r.URL.Query().Get("selector")
refParam := r.URL.Query().Get("ref")
- if selectorParam != "" || refParam != "" {
- h.writeElementText(w, r, tCtx, resolvedTabID, selectorParam, refParam)
- return
- }
+ ghostRoute := textRoute != nil && textRoute.UsedBrowser == config.BrowserGhostChrome
+ for attempt := 0; attempt < 2; attempt++ {
+ var modalNodeID int64
+ var modalOpen bool
+ var err error
+ if !ghostRoute {
+ modalNodeID, modalOpen, err = bridge.TopmostModalNodeID(tCtx, targetFrameID)
+ if err != nil {
+ httpx.Error(w, selectorResolutionHTTPStatus(err), fmt.Errorf("resolve topmost dialog: %w", err))
+ return
+ }
+ }
- text, err := h.extractDocumentText(tCtx, mode, targetFrameID)
- if err != nil {
- httpx.Error(w, 500, err)
+ var text string
+ if selectorParam != "" || refParam != "" {
+ text, err = h.extractElementText(tCtx, resolvedTabID, selectorParam, refParam, modalNodeID)
+ } else if modalOpen {
+ err = h.Bridge.CallFunctionOnNode(tCtx, modalNodeID,
+ `function() { return this.innerText || this.textContent || ''; }`, nil, &text)
+ } else {
+ text, err = h.extractDocumentText(tCtx, mode, targetFrameID)
+ }
+
+ stable := true
+ if !ghostRoute {
+ afterNodeID, afterOpen, scopeErr := bridge.TopmostModalNodeID(tCtx, targetFrameID)
+ if scopeErr != nil {
+ httpx.Error(w, selectorResolutionHTTPStatus(scopeErr), fmt.Errorf("recheck topmost dialog: %w", scopeErr))
+ return
+ }
+ stable = modalNodeID == afterNodeID && modalOpen == afterOpen
+ }
+ if !stable {
+ continue
+ }
+ if err != nil {
+ status := http.StatusInternalServerError
+ if selectorParam != "" || refParam != "" {
+ status = selectorResolutionHTTPStatus(err)
+ err = fmt.Errorf("element text extract: %w", err)
+ }
+ httpx.Error(w, status, err)
+ return
+ }
+ if selectorParam != "" || refParam != "" {
+ h.writeElementTextResponse(w, r, tCtx, text)
+ } else {
+ h.writeTextResponse(w, r, tCtx, text, maxChars, format, textRoute)
+ }
return
}
- h.writeTextResponse(w, r, tCtx, text, maxChars, format, textRoute)
+ httpx.Error(w, http.StatusConflict, fmt.Errorf("topmost dialog changed twice during text extraction; retry after the page settles"))
}
-// writeElementText extracts text for a single selector/ref-targeted element and
-// writes the {url,title,text} JSON response.
-func (h *Handlers) writeElementText(w http.ResponseWriter, r *http.Request, tCtx context.Context, resolvedTabID, selectorParam, refParam string) {
- text, err := h.extractElementText(tCtx, resolvedTabID, selectorParam, refParam)
- if err != nil {
- httpx.Error(w, 500, fmt.Errorf("element text extract: %w", err))
- return
- }
+// writeElementTextResponse writes an already scope-validated element read.
+func (h *Handlers) writeElementTextResponse(w http.ResponseWriter, r *http.Request, tCtx context.Context, text string) {
url, _ := h.Bridge.CurrentURL(tCtx)
title, _ := h.Bridge.CurrentTitle(tCtx)
h.recordResolvedURL(r, url)
@@ -195,17 +231,34 @@ func (h *Handlers) evalTextInFrame(ctx context.Context, script, frameID string)
return text, nil
}
-func (h *Handlers) extractElementText(ctx context.Context, tabID, selector, ref string) (string, error) {
+func (h *Handlers) extractElementText(ctx context.Context, tabID, selectorValue, ref string, scopeBackendNodeID int64) (string, error) {
var text string
+ if scopeBackendNodeID != 0 {
+ var sel selector.Selector
+ if ref != "" {
+ sel = selector.Parse("ref:" + ref)
+ } else {
+ sel = selector.Parse(selectorValue)
+ }
+ nodeID, err := bridge.ResolveUnifiedSelectorWithinNode(ctx, sel, h.Bridge.GetRefCache(tabID), scopeBackendNodeID)
+ if err != nil {
+ return "", err
+ }
+ if err := h.Bridge.CallFunctionOnNode(ctx, nodeID,
+ `function() { return this.innerText || this.textContent || ''; }`, nil, &text); err != nil {
+ return "", err
+ }
+ return text, nil
+ }
if ref != "" {
cache := h.Bridge.GetRefCache(tabID)
if cache == nil {
- return "", fmt.Errorf("ref not found: %s (no snapshot cache)", ref)
+ return "", fmt.Errorf("ref not found: %s (no snapshot cache): %w", ref, bridge.ErrSelectorNoMatch)
}
target, ok := cache.Lookup(ref)
if !ok {
- return "", fmt.Errorf("ref not found: %s", ref)
+ return "", fmt.Errorf("ref not found: %s: %w", ref, bridge.ErrSelectorNoMatch)
}
nodeID := target.BackendNodeID
@@ -220,26 +273,26 @@ func (h *Handlers) extractElementText(ctx context.Context, tabID, selector, ref
var script string
switch {
- case strings.HasPrefix(selector, "xpath:"):
- xpath := selector[len("xpath:"):]
+ case strings.HasPrefix(selectorValue, "xpath:"):
+ xpath := selectorValue[len("xpath:"):]
script = fmt.Sprintf(`(function(){var r=document.evaluate(%q,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);var n=r.singleNodeValue;return n?(n.innerText||n.textContent||''):null})()`, xpath)
- case strings.HasPrefix(selector, "//") || strings.HasPrefix(selector, "(//"):
- script = fmt.Sprintf(`(function(){var r=document.evaluate(%q,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);var n=r.singleNodeValue;return n?(n.innerText||n.textContent||''):null})()`, selector)
- case strings.HasPrefix(selector, "text:"):
- textVal := selector[len("text:"):]
+ case strings.HasPrefix(selectorValue, "//") || strings.HasPrefix(selectorValue, "(//"):
+ script = fmt.Sprintf(`(function(){var r=document.evaluate(%q,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);var n=r.singleNodeValue;return n?(n.innerText||n.textContent||''):null})()`, selectorValue)
+ case strings.HasPrefix(selectorValue, "text:"):
+ textVal := selectorValue[len("text:"):]
script = fmt.Sprintf(`(function(){var w=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);while(w.nextNode()){if(w.currentNode.textContent.includes(%q))return w.currentNode.parentElement.innerText||w.currentNode.parentElement.textContent||''}return null})()`, textVal)
- case strings.HasPrefix(selector, "css:"):
- css := selector[len("css:"):]
+ case strings.HasPrefix(selectorValue, "css:"):
+ css := selectorValue[len("css:"):]
script = fmt.Sprintf(`(function(){var n=document.querySelector(%q);return n?(n.innerText||n.textContent||''):null})()`, css)
default:
- script = fmt.Sprintf(`(function(){var n=document.querySelector(%q);return n?(n.innerText||n.textContent||''):null})()`, selector)
+ script = fmt.Sprintf(`(function(){var n=document.querySelector(%q);return n?(n.innerText||n.textContent||''):null})()`, selectorValue)
}
if err := h.Bridge.Evaluate(ctx, script, &text, bridge.EvalOpts{}); err != nil {
return "", err
}
if text == "" {
- return "", fmt.Errorf("no element matches selector: %s", selector)
+ return "", fmt.Errorf("no element matches selector %q: %w", selectorValue, bridge.ErrSelectorNoMatch)
}
return text, nil
}
diff --git a/internal/orchestrator/bindings.go b/internal/orchestrator/bindings.go
index 7733b096..dd27f28b 100644
--- a/internal/orchestrator/bindings.go
+++ b/internal/orchestrator/bindings.go
@@ -16,11 +16,12 @@ import (
// have no lifecycle signal, so agent bindings are bounded by an idle TTL and
// an LRU cap to prevent unbounded growth.
type Bindings struct {
- mu sync.RWMutex
- session map[string]string // sessionID → instanceID
- agent map[string]string // agentID → instanceID
- agentSeen map[string]time.Time // agentID → last access
- now func() time.Time
+ mu sync.RWMutex
+ session map[string]string // sessionID → instanceID
+ sessionTabs map[string]map[string]string // sessionID → tabID → instanceID
+ agent map[string]string // agentID → instanceID
+ agentSeen map[string]time.Time // agentID → last access
+ now func() time.Time
}
// NewBindings returns an empty bindings table. Pass nil for `now` to use
@@ -30,10 +31,11 @@ func NewBindings(now func() time.Time) *Bindings {
now = time.Now
}
return &Bindings{
- session: make(map[string]string),
- agent: make(map[string]string),
- agentSeen: make(map[string]time.Time),
- now: now,
+ session: make(map[string]string),
+ sessionTabs: make(map[string]map[string]string),
+ agent: make(map[string]string),
+ agentSeen: make(map[string]time.Time),
+ now: now,
}
}
@@ -75,6 +77,58 @@ func (b *Bindings) BindSession(id, instanceID string) {
b.mu.Unlock()
}
+// OwnSessionTab records a tab created for a session after the bridge confirms
+// the creation succeeded. A tab is listed under only the session that created it.
+func (b *Bindings) OwnSessionTab(sessionID, instanceID, tabID string) {
+ if b == nil || sessionID == "" || instanceID == "" || tabID == "" {
+ return
+ }
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ for id, tabs := range b.sessionTabs {
+ if id != sessionID {
+ delete(tabs, tabID)
+ if len(tabs) == 0 {
+ delete(b.sessionTabs, id)
+ }
+ }
+ }
+ if b.sessionTabs[sessionID] == nil {
+ b.sessionTabs[sessionID] = make(map[string]string)
+ }
+ b.sessionTabs[sessionID][tabID] = instanceID
+}
+
+// ReleaseTab removes a closed tab from every session ownership set.
+func (b *Bindings) ReleaseTab(tabID string) {
+ if b == nil || tabID == "" {
+ return
+ }
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ for id, tabs := range b.sessionTabs {
+ delete(tabs, tabID)
+ if len(tabs) == 0 {
+ delete(b.sessionTabs, id)
+ }
+ }
+}
+
+// SessionTabIDs returns a stable snapshot of tabs created for a session.
+func (b *Bindings) SessionTabIDs(sessionID string) []string {
+ if b == nil || sessionID == "" {
+ return []string{}
+ }
+ b.mu.RLock()
+ ids := make([]string, 0, len(b.sessionTabs[sessionID]))
+ for tabID := range b.sessionTabs[sessionID] {
+ ids = append(ids, tabID)
+ }
+ b.mu.RUnlock()
+ sort.Strings(ids)
+ return ids
+}
+
// BindAgent associates an agent id with an instance and updates its idle
// timestamp.
func (b *Bindings) BindAgent(id, instanceID string) {
@@ -94,6 +148,7 @@ func (b *Bindings) ClearSession(id string) {
}
b.mu.Lock()
delete(b.session, id)
+ delete(b.sessionTabs, id)
b.mu.Unlock()
}
@@ -121,6 +176,16 @@ func (b *Bindings) ClearInstance(instanceID string) {
delete(b.session, id)
}
}
+ for sessionID, tabs := range b.sessionTabs {
+ for tabID, target := range tabs {
+ if target == instanceID {
+ delete(tabs, tabID)
+ }
+ }
+ if len(tabs) == 0 {
+ delete(b.sessionTabs, sessionID)
+ }
+ }
for id, target := range b.agent {
if target == instanceID {
delete(b.agent, id)
diff --git a/internal/orchestrator/bindings_test.go b/internal/orchestrator/bindings_test.go
index 0507c612..57088c6e 100644
--- a/internal/orchestrator/bindings_test.go
+++ b/internal/orchestrator/bindings_test.go
@@ -19,6 +19,36 @@ func TestBindings_SessionRoundTrip(t *testing.T) {
}
}
+func TestBindings_SessionTabsAreIsolatedAndReleased(t *testing.T) {
+ b := NewBindings(nil)
+ b.OwnSessionTab("ses_1", "inst_a", "tab_b")
+ b.OwnSessionTab("ses_1", "inst_a", "tab_a")
+ b.OwnSessionTab("ses_2", "inst_b", "tab_c")
+
+ if got := b.SessionTabIDs("ses_1"); len(got) != 2 || got[0] != "tab_a" || got[1] != "tab_b" {
+ t.Fatalf("ses_1 tabs = %v, want [tab_a tab_b]", got)
+ }
+ if got := b.SessionTabIDs("ses_2"); len(got) != 1 || got[0] != "tab_c" {
+ t.Fatalf("ses_2 tabs = %v, want [tab_c]", got)
+ }
+
+ b.ReleaseTab("tab_a")
+ if got := b.SessionTabIDs("ses_1"); len(got) != 1 || got[0] != "tab_b" {
+ t.Fatalf("ses_1 tabs after close = %v, want [tab_b]", got)
+ }
+ if got := b.SessionTabIDs("ses_2"); len(got) != 1 || got[0] != "tab_c" {
+ t.Fatalf("closing ses_1 tab changed ses_2 tabs: %v", got)
+ }
+
+ b.ClearSession("ses_1")
+ if got := b.SessionTabIDs("ses_1"); len(got) != 0 {
+ t.Fatalf("cleared session tabs = %v, want empty", got)
+ }
+ if got := b.SessionTabIDs("ses_2"); len(got) != 1 || got[0] != "tab_c" {
+ t.Fatalf("clearing ses_1 changed ses_2 tabs: %v", got)
+ }
+}
+
func TestBindings_AgentResolveBumpsIdle(t *testing.T) {
t0 := time.Unix(1_700_000_000, 0)
clock := t0
@@ -86,6 +116,8 @@ func TestBindings_ClearInstanceDropsEveryReference(t *testing.T) {
b.BindSession("ses_2", "inst_b")
b.BindAgent("agent-1", "inst_a")
b.BindAgent("agent-2", "inst_b")
+ b.OwnSessionTab("ses_1", "inst_a", "tab-a")
+ b.OwnSessionTab("ses_2", "inst_b", "tab-b")
b.ClearInstance("inst_a")
@@ -101,6 +133,12 @@ func TestBindings_ClearInstanceDropsEveryReference(t *testing.T) {
if _, ok := b.ResolveAgent("agent-2"); !ok {
t.Fatal("agent for surviving instance should remain")
}
+ if got := b.SessionTabIDs("ses_1"); len(got) != 0 {
+ t.Fatalf("tabs for cleared instance = %v, want empty", got)
+ }
+ if got := b.SessionTabIDs("ses_2"); len(got) != 1 || got[0] != "tab-b" {
+ t.Fatalf("tabs for surviving instance = %v, want [tab-b]", got)
+ }
}
func TestBindings_NilSafe(t *testing.T) {
@@ -114,6 +152,11 @@ func TestBindings_NilSafe(t *testing.T) {
t.Fatal("nil should resolve nothing")
}
b.ClearInstance("anything")
+ b.OwnSessionTab("a", "b", "c")
+ b.ReleaseTab("c")
+ if got := b.SessionTabIDs("a"); len(got) != 0 {
+ t.Fatalf("nil SessionTabIDs = %v, want empty", got)
+ }
b.PruneAgents(time.Hour, 1)
}
diff --git a/internal/orchestrator/handlers_instances_test.go b/internal/orchestrator/handlers_instances_test.go
index 34ea389a..93a2aeb0 100644
--- a/internal/orchestrator/handlers_instances_test.go
+++ b/internal/orchestrator/handlers_instances_test.go
@@ -6,6 +6,7 @@ import (
"net/http"
"net/http/httptest"
"os"
+ "slices"
"strings"
"testing"
@@ -420,8 +421,9 @@ func TestHandleAttachInstanceExplicitBrowserTargetRoutes(t *testing.T) {
if instances[0].Browser != config.BrowserCloak {
t.Fatalf("internal Browser = %q, want cloak", instances[0].Browser)
}
- if !strings.Contains(strings.Join(runner.args, " "), "--browser-provider cloak") {
- t.Fatalf("runner args = %v, want cloak provider", runner.args)
+ wantArgs := []string{"bridge", "--cdp-attach", "ws://127.0.0.1:9222/devtools/browser/abc", "--browser", "cloak", "--remote-browser-name", "attached-cloak"}
+ if !slices.Equal(runner.args, wantArgs) {
+ t.Fatalf("runner args = %v, want supported bridge command surface %v", runner.args, wantArgs)
}
var inst bridge.Instance
diff --git a/internal/orchestrator/instance_attach.go b/internal/orchestrator/instance_attach.go
index 5321ce59..402e4cc6 100644
--- a/internal/orchestrator/instance_attach.go
+++ b/internal/orchestrator/instance_attach.go
@@ -167,7 +167,7 @@ func (o *Orchestrator) AttachWithOptions(name, cdpURL string, opts AttachOptions
args := []string{
"bridge",
"--cdp-attach", cdpURL,
- "--browser-provider", resolved.Browser,
+ "--browser", resolved.Browser,
"--remote-browser-name", name,
}
slog.Info("starting CDP attach bridge child",
diff --git a/internal/orchestrator/instance_stop.go b/internal/orchestrator/instance_stop.go
index 7ca1da07..eeed553a 100644
--- a/internal/orchestrator/instance_stop.go
+++ b/internal/orchestrator/instance_stop.go
@@ -16,6 +16,14 @@ import (
"github.com/pinchtab/pinchtab/internal/config"
)
+var (
+ shutdownRequestTimeout = 4 * time.Second
+ registeredBridgeStopTimeout = 5 * time.Second
+ gracefulProcessStopTimeout = 5 * time.Second
+ termProcessStopTimeout = 3 * time.Second
+ killProcessStopTimeout = 2 * time.Second
+)
+
func (o *Orchestrator) Stop(id string) error {
o.mu.Lock()
inst, ok := o.instances[id]
@@ -32,16 +40,10 @@ func (o *Orchestrator) Stop(id string) error {
o.mu.Unlock()
if inst.cmd == nil {
- if inst.AttachType == "bridge" {
- reqCtx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
- defer cancel()
- targetURL, targetErr := o.instancePathURL(inst, "/shutdown", "")
- if targetErr == nil {
- req, _ := http.NewRequestWithContext(reqCtx, http.MethodPost, targetURL.String(), nil)
- o.applyInstanceAuth(req, inst)
- if resp, err := o.client.Do(req); err == nil {
- _ = resp.Body.Close()
- }
+ if inst.AttachType == "bridge" || inst.AttachType == "cdp-bridge" {
+ if err := o.stopRegisteredBridge(inst); err != nil {
+ o.setStopError(id, err.Error())
+ return err
}
}
o.markStopped(id)
@@ -50,7 +52,7 @@ func (o *Orchestrator) Stop(id string) error {
pid := inst.cmd.PID()
- reqCtx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
+ reqCtx, cancel := context.WithTimeout(context.Background(), shutdownRequestTimeout)
defer cancel()
if targetURL, targetErr := o.instancePathURL(inst, "/shutdown", ""); targetErr == nil {
req, _ := http.NewRequestWithContext(reqCtx, http.MethodPost, targetURL.String(), nil)
@@ -62,7 +64,7 @@ func (o *Orchestrator) Stop(id string) error {
}
if pid > 0 {
- if waitForProcessExit(pid, 5*time.Second) {
+ if waitForProcessExit(pid, gracefulProcessStopTimeout) {
o.markStopped(id)
return nil
}
@@ -70,7 +72,7 @@ func (o *Orchestrator) Stop(id string) error {
if err := killProcessGroup(pid, sigTERM); err != nil {
slog.Warn("failed to send SIGTERM to instance", "id", id, "pid", pid, "err", err)
}
- if waitForProcessExit(pid, 3*time.Second) {
+ if waitForProcessExit(pid, termProcessStopTimeout) {
o.markStopped(id)
return nil
}
@@ -83,7 +85,7 @@ func (o *Orchestrator) Stop(id string) error {
inst.cmd.Cancel()
if pid > 0 {
- if waitForProcessExit(pid, 2*time.Second) {
+ if waitForProcessExit(pid, killProcessStopTimeout) {
o.markStopped(id)
return nil
}
@@ -95,6 +97,60 @@ func (o *Orchestrator) Stop(id string) error {
return nil
}
+func (o *Orchestrator) stopRegisteredBridge(inst *InstanceInternal) error {
+ shutdownURL, err := o.instancePathURL(inst, "/shutdown", "")
+ if err != nil {
+ return fmt.Errorf("cannot stop registered bridge %q: %w", inst.ID, err)
+ }
+ requestCtx, cancel := context.WithTimeout(context.Background(), shutdownRequestTimeout)
+ request, requestErr := http.NewRequestWithContext(requestCtx, http.MethodPost, shutdownURL.String(), nil)
+ if requestErr == nil {
+ o.applyInstanceAuth(request, inst)
+ response, doErr := o.client.Do(request)
+ if response != nil {
+ _ = response.Body.Close()
+ if response.StatusCode < 200 || response.StatusCode >= 300 {
+ requestErr = fmt.Errorf("shutdown returned HTTP %d", response.StatusCode)
+ }
+ }
+ if doErr != nil {
+ requestErr = doErr
+ }
+ }
+ cancel()
+
+ if o.waitForBridgeEndpointExit(inst, registeredBridgeStopTimeout) {
+ return nil
+ }
+ if requestErr != nil {
+ return fmt.Errorf("registered bridge %q did not stop: %w", inst.ID, requestErr)
+ }
+ return fmt.Errorf("registered bridge %q acknowledged shutdown but its endpoint is still reachable", inst.ID)
+}
+
+func (o *Orchestrator) waitForBridgeEndpointExit(inst *InstanceInternal, timeout time.Duration) bool {
+ healthURL, err := o.instancePathURL(inst, "/health", "")
+ if err != nil {
+ return false
+ }
+ deadline := time.Now().Add(timeout)
+ for time.Now().Before(deadline) {
+ probeCtx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
+ request, _ := http.NewRequestWithContext(probeCtx, http.MethodGet, healthURL.String(), nil)
+ o.applyInstanceAuth(request, inst)
+ response, probeErr := o.client.Do(request)
+ if response != nil {
+ _ = response.Body.Close()
+ }
+ cancel()
+ if probeErr != nil {
+ return true
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ return false
+}
+
func (o *Orchestrator) StopProfile(name string) error {
o.mu.RLock()
ids := make([]string, 0, 1)
diff --git a/internal/orchestrator/instance_stop_process_unix_test.go b/internal/orchestrator/instance_stop_process_unix_test.go
new file mode 100644
index 00000000..f9206f51
--- /dev/null
+++ b/internal/orchestrator/instance_stop_process_unix_test.go
@@ -0,0 +1,73 @@
+//go:build !windows
+
+package orchestrator
+
+import (
+ "context"
+ "io"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+func TestStopReapsOwnedBridgeProcessGroup(t *testing.T) {
+ originalRequest := shutdownRequestTimeout
+ originalGrace := gracefulProcessStopTimeout
+ originalTerm := termProcessStopTimeout
+ originalKill := killProcessStopTimeout
+ shutdownRequestTimeout = 50 * time.Millisecond
+ gracefulProcessStopTimeout = 50 * time.Millisecond
+ termProcessStopTimeout = 100 * time.Millisecond
+ killProcessStopTimeout = time.Second
+ t.Cleanup(func() {
+ shutdownRequestTimeout = originalRequest
+ gracefulProcessStopTimeout = originalGrace
+ termProcessStopTimeout = originalTerm
+ killProcessStopTimeout = originalKill
+ })
+
+ runner := &LocalRunner{}
+ cmd, err := runner.Run(
+ context.Background(), "/bin/sh",
+ []string{"-c", `trap '' TERM; while :; do sleep 1; done`},
+ os.Environ(), io.Discard, io.Discard,
+ )
+ if err != nil {
+ t.Fatalf("start helper bridge process: %v", err)
+ }
+ t.Cleanup(func() {
+ _ = killProcessGroup(cmd.PID(), sigKILL)
+ cmd.Cancel()
+ })
+ waited := make(chan struct{})
+ go func() {
+ _ = cmd.Wait()
+ close(waited)
+ }()
+
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ o.instances["owned"] = &InstanceInternal{
+ Instance: bridge.Instance{
+ ID: "owned", URL: "http://127.0.0.1:1", Status: "running",
+ Attached: true, AttachType: "cdp-bridge",
+ },
+ URL: "http://127.0.0.1:1",
+ cmd: cmd,
+ }
+ if err := o.Stop("owned"); err != nil {
+ t.Fatalf("Stop failed: %v", err)
+ }
+ select {
+ case <-waited:
+ case <-time.After(2 * time.Second):
+ t.Fatal("owned bridge process was not reaped")
+ }
+ if isProcessAlive(cmd.PID()) {
+ t.Fatalf("owned bridge PID %d is still alive", cmd.PID())
+ }
+ if _, present := o.instances["owned"]; present {
+ t.Fatal("stopped instance remains registered")
+ }
+}
diff --git a/internal/orchestrator/instance_stop_registered_test.go b/internal/orchestrator/instance_stop_registered_test.go
new file mode 100644
index 00000000..3deb78f5
--- /dev/null
+++ b/internal/orchestrator/instance_stop_registered_test.go
@@ -0,0 +1,62 @@
+package orchestrator
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+func TestStopRegisteredBridgeRequiresEndpointExit(t *testing.T) {
+ original := registeredBridgeStopTimeout
+ registeredBridgeStopTimeout = 100 * time.Millisecond
+ t.Cleanup(func() { registeredBridgeStopTimeout = original })
+
+ for _, test := range []struct {
+ name string
+ close bool
+ wantErr bool
+ wantPresent bool
+ }{
+ {name: "acknowledged but still alive", wantErr: true, wantPresent: true},
+ {name: "acknowledged and exited", close: true},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ var server *httptest.Server
+ server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/shutdown":
+ w.WriteHeader(http.StatusOK)
+ if test.close {
+ go server.Close()
+ }
+ case "/health":
+ w.WriteHeader(http.StatusOK)
+ default:
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ defer server.Close()
+
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.instances["registered"] = &InstanceInternal{
+ Instance: bridge.Instance{
+ ID: "registered", URL: server.URL, Status: "running",
+ Attached: true, AttachType: "bridge",
+ },
+ URL: server.URL,
+ }
+
+ err := o.Stop("registered")
+ if (err != nil) != test.wantErr {
+ t.Fatalf("Stop error = %v, wantErr=%v", err, test.wantErr)
+ }
+ _, present := o.instances["registered"]
+ if present != test.wantPresent {
+ t.Fatalf("instance present=%v, want %v", present, test.wantPresent)
+ }
+ })
+ }
+}
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index f1868c96..2e7f3f13 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -260,6 +260,15 @@ func (o *Orchestrator) Bindings() *Bindings {
return o.bindings
}
+// SessionTabIDs reports tabs created for a session and still present in the
+// orchestrator's ownership ledger.
+func (o *Orchestrator) SessionTabIDs(sessionID string) []string {
+ if o == nil || o.bindings == nil {
+ return []string{}
+ }
+ return o.bindings.SessionTabIDs(sessionID)
+}
+
func (o *Orchestrator) SetStrictCrossInstanceTab(strict bool) {
if o == nil {
return
diff --git a/internal/orchestrator/orchestrator_test.go b/internal/orchestrator/orchestrator_test.go
index 1429b048..9a2dd240 100644
--- a/internal/orchestrator/orchestrator_test.go
+++ b/internal/orchestrator/orchestrator_test.go
@@ -12,6 +12,7 @@ import (
"net/url"
"os"
"path/filepath"
+ "slices"
"strconv"
"strings"
"sync/atomic"
@@ -507,18 +508,9 @@ func TestOrchestrator_Attach_SpawnsChildBridgeWithCDPFlags(t *testing.T) {
if !runner.runCalled {
t.Fatal("expected runner.Run to be called for child bridge")
}
- args := strings.Join(runner.args, " ")
- if !strings.Contains(args, "bridge") {
- t.Fatalf("expected child args to contain 'bridge': %v", runner.args)
- }
- if !strings.Contains(args, "--cdp-attach "+cdpURL) {
- t.Fatalf("expected --cdp-attach flag with cdp url: %v", runner.args)
- }
- if !strings.Contains(args, "--browser-provider cloak") {
- t.Fatalf("expected --browser-provider cloak: %v", runner.args)
- }
- if !strings.Contains(args, "--remote-browser-name ext-cloak") {
- t.Fatalf("expected --remote-browser-name flag: %v", runner.args)
+ wantArgs := []string{"bridge", "--cdp-attach", cdpURL, "--browser", "cloak", "--remote-browser-name", "ext-cloak"}
+ if !slices.Equal(runner.args, wantArgs) {
+ t.Fatalf("child args = %v, want supported bridge command surface %v", runner.args, wantArgs)
}
}
diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.go
index 66fdb912..d3dbc9ff 100644
--- a/internal/orchestrator/proxy.go
+++ b/internal/orchestrator/proxy.go
@@ -391,12 +391,20 @@ func (o *Orchestrator) handleProxyResponseHeaders(origReq *http.Request, resp *h
// a successful proxy response so failed requests never create or move
// routing state.
if o.bindings != nil && targetInstanceID != "" {
- if id := sessionIDForRouting(origReq); id != "" {
- o.bindings.BindSession(id, targetInstanceID)
+ if sessionID := sessionIDForRouting(origReq); sessionID != "" {
+ o.bindings.BindSession(sessionID, targetInstanceID)
+ if strings.EqualFold(strings.TrimSpace(resp.Header.Get(activity.HeaderPTTabCreated)), "true") {
+ if tabID := strings.TrimSpace(resp.Header.Get(activity.HeaderPTTabID)); tabID != "" {
+ o.bindings.OwnSessionTab(sessionID, targetInstanceID, tabID)
+ }
+ }
}
if id := strings.TrimSpace(origReq.Header.Get(activity.HeaderAgentID)); id != "" {
o.bindings.BindAgent(id, targetInstanceID)
}
+ if tabID := closedTabID(origReq, resp); tabID != "" {
+ o.bindings.ReleaseTab(tabID)
+ }
}
// Tabs cache invalidation. Any successful response that may have
@@ -407,6 +415,20 @@ func (o *Orchestrator) handleProxyResponseHeaders(origReq *http.Request, resp *h
}
}
+func closedTabID(req *http.Request, resp *http.Response) string {
+ if req == nil || resp == nil || req.Method != http.MethodPost {
+ return ""
+ }
+ path := strings.TrimSpace(req.URL.Path)
+ if path != "/close" && !(strings.HasPrefix(path, "/tabs/") && strings.HasSuffix(path, "/close")) {
+ return ""
+ }
+ if tabID := strings.TrimSpace(resp.Header.Get(activity.HeaderPTTabID)); tabID != "" {
+ return tabID
+ }
+ return tabClosePathID(req)
+}
+
// tabsCacheRequestAffectsTabs reports whether a successful response should
// invalidate the per-instance tabs cache. Errs on the side of invalidating
// rather than serving stale data — the cache is a perf optimization, not
diff --git a/internal/orchestrator/proxy_test.go b/internal/orchestrator/proxy_test.go
index 28e78935..c196eb5a 100644
--- a/internal/orchestrator/proxy_test.go
+++ b/internal/orchestrator/proxy_test.go
@@ -13,8 +13,55 @@ import (
"github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/session"
)
+func TestProxyResponseTracksOnlySuccessfullyCreatedSessionTabs(t *testing.T) {
+ o := NewOrchestrator(t.TempDir())
+
+ created := func(sessionID, instanceID, tabID string) {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodPost, "/tab", nil)
+ req = session.WithSession(req, &session.Session{ID: sessionID})
+ resp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}}
+ resp.Header.Set(activity.HeaderPTTabID, tabID)
+ resp.Header.Set(activity.HeaderPTTabCreated, "true")
+ o.handleProxyResponseHeaders(req, resp, instanceID)
+ }
+
+ created("ses_1", "inst_a", "tab_2")
+ created("ses_1", "inst_a", "tab_1")
+ created("ses_2", "inst_b", "tab_3")
+
+ // Merely using another tab must not silently claim it for this session.
+ used := httptest.NewRequest(http.MethodGet, "/tabs/tab_foreign/title", nil)
+ used = session.WithSession(used, &session.Session{ID: "ses_1"})
+ usedResp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}}
+ usedResp.Header.Set(activity.HeaderPTTabID, "tab_foreign")
+ o.handleProxyResponseHeaders(used, usedResp, "inst_b")
+
+ if got := o.SessionTabIDs("ses_1"); len(got) != 2 || got[0] != "tab_1" || got[1] != "tab_2" {
+ t.Fatalf("ses_1 tabs = %v, want [tab_1 tab_2]", got)
+ }
+ if got := o.SessionTabIDs("ses_2"); len(got) != 1 || got[0] != "tab_3" {
+ t.Fatalf("ses_2 tabs = %v, want [tab_3]", got)
+ }
+
+ closed := httptest.NewRequest(http.MethodPost, "/tabs/tab_1/close", nil)
+ closed.SetPathValue("id", "tab_1")
+ closed = session.WithSession(closed, &session.Session{ID: "ses_2"})
+ closedResp := &http.Response{StatusCode: http.StatusOK, Header: http.Header{}}
+ closedResp.Header.Set(activity.HeaderPTTabID, "tab_1")
+ o.handleProxyResponseHeaders(closed, closedResp, "inst_a")
+
+ if got := o.SessionTabIDs("ses_1"); len(got) != 1 || got[0] != "tab_2" {
+ t.Fatalf("ses_1 tabs after close = %v, want [tab_2]", got)
+ }
+ if got := o.SessionTabIDs("ses_2"); len(got) != 1 || got[0] != "tab_3" {
+ t.Fatalf("close crossed session boundary: ses_2 tabs = %v", got)
+ }
+}
+
func startLocalHTTPServer(t *testing.T, h http.Handler) (*httptest.Server, string) {
t.Helper()
ln, err := net.Listen("tcp", "localhost:0")
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index 30650db1..b34d7685 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -132,8 +132,8 @@ var coreEndpoints = []Endpoint{
{"GET", "/network/stream", "Network SSE stream", CapNone, true},
{"GET", "/network/export", "Export HAR", CapNone, true},
{"GET", "/network/export/stream", "Export HAR stream", CapNone, true},
- {"GET", "/network/{requestId}", "Single network request", CapNone, true},
- {"POST", "/network/clear", "Clear network log", CapNone, false},
+ {"GET", "/network/{requestId}", "Single network request", CapNetworkIntercept, true},
+ {"POST", "/network/clear", "Clear network log", CapNetworkIntercept, false},
{"GET", "/network/route", "List interception rules for a tab", CapNetworkIntercept, true},
{"POST", "/network/route", "Install an interception rule", CapNetworkIntercept, true},
{"DELETE", "/network/route", "Remove interception rule(s)", CapNetworkIntercept, true},
diff --git a/internal/routes/routes_test.go b/internal/routes/routes_test.go
index 91a13132..602712a8 100644
--- a/internal/routes/routes_test.go
+++ b/internal/routes/routes_test.go
@@ -31,6 +31,27 @@ func TestCaptureEndpointIsShorthandAndTabScoped(t *testing.T) {
}
}
+func TestSensitiveNetworkEndpointsRequireInterceptCapability(t *testing.T) {
+ want := map[string]bool{
+ "GET /network/{requestId}": false,
+ "POST /network/clear": false,
+ }
+ for _, ep := range Core() {
+ if _, ok := want[ep.Route()]; !ok {
+ continue
+ }
+ if ep.Capability != CapNetworkIntercept {
+ t.Errorf("%s capability = %q, want %q", ep.Route(), ep.Capability, CapNetworkIntercept)
+ }
+ want[ep.Route()] = true
+ }
+ for route, found := range want {
+ if !found {
+ t.Errorf("Core() missing %s", route)
+ }
+ }
+}
+
func TestFrameEndpointsAreShorthandAndTabScoped(t *testing.T) {
found := map[string]bool{
"GET /frame": false,
diff --git a/internal/server/bridge.go b/internal/server/bridge.go
index ba6c5872..47576260 100644
--- a/internal/server/bridge.go
+++ b/internal/server/bridge.go
@@ -3,15 +3,18 @@ package server
import (
"context"
"log/slog"
+ "net"
"net/http"
"os"
"os/signal"
+ "strings"
"sync"
"syscall"
"time"
"github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/bridgeregistry"
_ "github.com/pinchtab/pinchtab/internal/browsers/all"
"github.com/pinchtab/pinchtab/internal/browsers/providerhooks"
"github.com/pinchtab/pinchtab/internal/cli"
@@ -88,16 +91,43 @@ func RunBridgeServer(cfg *config.RuntimeConfig, version string) {
IdleTimeout: 120 * time.Second,
}
- go func() {
- if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
- slog.Error("server error", "err", err)
- os.Exit(1)
+ listener, err := net.Listen("tcp", listenAddr)
+ if err != nil {
+ slog.Error("server error", "err", err)
+ os.Exit(1)
+ }
+ applyBoundBridgePort(cfg, listener.Addr())
+ registration, err := registerBridge(cfg, listener.Addr())
+ if err != nil {
+ _ = listener.Close()
+ slog.Error("bridge registry", "err", err)
+ os.Exit(1)
+ }
+ defer func() {
+ if err := registration.Close(); err != nil {
+ slog.Warn("remove bridge registry record", "err", err)
}
}()
+ serveErr := make(chan error, 1)
+ go func() {
+ serveErr <- server.Serve(listener)
+ }()
+
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
- <-sigChan
+ defer signal.Stop(sigChan)
+ select {
+ case <-sigChan:
+ case err := <-serveErr:
+ doShutdown()
+ if err != nil && err != http.ErrServerClosed {
+ _ = registration.Close()
+ slog.Error("server error", "err", err)
+ os.Exit(1)
+ }
+ return
+ }
doShutdown()
@@ -108,6 +138,44 @@ func RunBridgeServer(cfg *config.RuntimeConfig, version string) {
}
}
+func applyBoundBridgePort(cfg *config.RuntimeConfig, listenerAddr net.Addr) {
+ if cfg == nil || listenerAddr == nil {
+ return
+ }
+ _, port, err := net.SplitHostPort(listenerAddr.String())
+ if err == nil && strings.TrimSpace(port) != "" {
+ cfg.Port = port
+ }
+}
+
+func registerBridge(cfg *config.RuntimeConfig, listenerAddr net.Addr) (*bridgeregistry.Registration, error) {
+ cdpIdentity := strings.TrimSpace(cfg.CDPAttachURL)
+ if cdpIdentity == "" {
+ cdpIdentity = strings.TrimSpace(cfg.RemoteCDPURL)
+ }
+ browserType := strings.TrimSpace(cfg.DefaultBrowser)
+ if browserType == "" {
+ browserType = config.BrowserChrome
+ }
+ address := strings.TrimSpace(cfg.Bind)
+ port := strings.TrimSpace(cfg.Port)
+ if listenerAddr != nil {
+ if listenerHost, listenerPort, err := net.SplitHostPort(listenerAddr.String()); err == nil {
+ port = listenerPort
+ if address == "" {
+ address = listenerHost
+ }
+ }
+ }
+ return bridgeregistry.Register(cfg.StateDir, bridgeregistry.Record{
+ Address: address,
+ Port: port,
+ CDPIdentity: cdpIdentity,
+ BrowserType: browserType,
+ BrowserLabel: cfg.RemoteBrowserName,
+ })
+}
+
func configureBridgeRouter(h *handlers.Handlers, cfg *config.RuntimeConfig) {
decorated := providerhooks.DecorateBridge(config.NormalizeBrowser(cfg.DefaultBrowser), h.Bridge, cfg)
if decorated == h.Bridge {
diff --git a/internal/server/bridge_test.go b/internal/server/bridge_test.go
index fbcf4db7..6d3494d9 100644
--- a/internal/server/bridge_test.go
+++ b/internal/server/bridge_test.go
@@ -1,11 +1,14 @@
package server
import (
+ "net"
"net/http"
"net/http/httptest"
+ "strings"
"testing"
"github.com/pinchtab/pinchtab/internal/activity"
+ "github.com/pinchtab/pinchtab/internal/bridgeregistry"
"github.com/pinchtab/pinchtab/internal/config"
"github.com/pinchtab/pinchtab/internal/handlers"
)
@@ -35,6 +38,73 @@ func TestConfigureBridgeRouter(t *testing.T) {
}
}
+func TestRegisterBridgeMapsRuntimeIdentityAndCleansUp(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ StateDir: t.TempDir(),
+ Bind: "127.0.0.1",
+ Port: "9878",
+ CDPAttachURL: "ws://user:[email protected]:9222/devtools/browser/browser-guid?token=secret",
+ DefaultBrowser: "cloak",
+ RemoteBrowserName: "work-profile",
+ }
+ registration, err := registerBridge(cfg, &net.TCPAddr{IP: net.ParseIP(cfg.Bind), Port: 9878})
+ if err != nil {
+ t.Fatalf("registerBridge() error = %v", err)
+ }
+ states, err := bridgeregistry.List(cfg.StateDir, false)
+ if err != nil {
+ t.Fatalf("List() error = %v", err)
+ }
+ if len(states) != 1 {
+ t.Fatalf("List() returned %d records, want 1", len(states))
+ }
+ got := states[0]
+ if got.Address != cfg.Bind || got.Port != cfg.Port || got.BrowserType != "cloak" || got.BrowserLabel != "work-profile" {
+ t.Fatalf("registered bridge = %+v", got)
+ }
+ if got.CDPIdentity == "" || strings.Contains(got.CDPIdentity, "password") || strings.Contains(got.CDPIdentity, "browser-guid") {
+ t.Fatalf("unsafe CDP identity %q", got.CDPIdentity)
+ }
+ if err := registration.Close(); err != nil {
+ t.Fatalf("Close() error = %v", err)
+ }
+ states, err = bridgeregistry.List(cfg.StateDir, false)
+ if err != nil || len(states) != 0 {
+ t.Fatalf("records after cleanup = %+v, err %v", states, err)
+ }
+}
+
+func TestRegisterBridgeUsesBoundEphemeralPort(t *testing.T) {
+ cfg := &config.RuntimeConfig{
+ StateDir: t.TempDir(),
+ Bind: "127.0.0.1",
+ Port: "0",
+ DefaultBrowser: config.BrowserChrome,
+ }
+ registration, err := registerBridge(cfg, &net.TCPAddr{IP: net.ParseIP(cfg.Bind), Port: 43210})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = registration.Close() }()
+ states, err := bridgeregistry.List(cfg.StateDir, false)
+ if err != nil || len(states) != 1 {
+ t.Fatalf("registered states = %+v, error = %v", states, err)
+ }
+ if states[0].Port != "43210" {
+ t.Fatalf("registered port = %q, want bound port 43210", states[0].Port)
+ }
+}
+
+func TestApplyBoundBridgePortUpdatesRuntimeConfig(t *testing.T) {
+ cfg := &config.RuntimeConfig{Port: "0"}
+ applyBoundBridgePort(cfg, &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 43210})
+ if cfg.Port != "43210" {
+ t.Fatalf("runtime port = %q, want bound port 43210", cfg.Port)
+ }
+ applyBoundBridgePort(nil, &net.TCPAddr{Port: 1})
+ applyBoundBridgePort(cfg, nil)
+}
+
func TestBridgeHandlerChainAppliesRateLimit(t *testing.T) {
cfg := &config.RuntimeConfig{Token: "secret"}
mux := http.NewServeMux()
diff --git a/internal/server/server.go b/internal/server/server.go
index 9f4f4b21..59faa3ef 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -81,6 +81,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
var sessionAPI *dashboard.SessionAPI
if sessionStore.Enabled() {
sessionAPI = dashboard.NewSessionAPI(sessionStore, cfg.BrowsersAvailable)
+ sessionAPI.SetSessionTabSource(orch.SessionTabIDs)
}
orch.OnEvent(func(evt orchestrator.InstanceEvent) {
diff --git a/internal/stealth/bundle.go b/internal/stealth/bundle.go
index 2945cbd6..6b88c1f9 100644
--- a/internal/stealth/bundle.go
+++ b/internal/stealth/bundle.go
@@ -65,9 +65,10 @@ type Status struct {
Flags map[string]bool `json:"flags"`
Capabilities map[string]bool `json:"capabilities"`
// ProviderCapabilities is advisory; omitted for empty/unknown providers to preserve legacy JSON shape.
- ProviderCapabilities []string `json:"providerCapabilities,omitempty"`
- Tradeoffs []string `json:"tradeoffs,omitempty"`
- TabOverrides map[string]bool `json:"tabOverrides"`
+ ProviderCapabilities []string `json:"providerCapabilities,omitempty"`
+ Tradeoffs []string `json:"tradeoffs,omitempty"`
+ TabOverrides map[string]bool `json:"tabOverrides"`
+ AttachMutationsSkipped bool `json:"attachMutationsSkipped,omitempty"`
}
func NewBundle(cfg *config.RuntimeConfig, seed int64) *Bundle {
@@ -174,6 +175,11 @@ func StatusFromBundle(bundle *Bundle, cfg *config.RuntimeConfig, launchMode Laun
if status.LaunchMode == "" {
status.LaunchMode = LaunchModeUninitialized
}
+ if status.LaunchMode == LaunchModeAttached || status.LaunchMode == LaunchModeRemoteCDP {
+ status.AttachMutationsSkipped = true
+ status.Tradeoffs = append(status.Tradeoffs,
+ "external attach: PinchTab skips launch-only stealth, locale, animation, and Runtime-domain mutations")
+ }
return status
}