High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: add emulation, inspection, and cookie endpoints with CLI and plugin improvements
Mario69bd4fc9fd43
diff --git a/cmd/pinchtab/cmd_cli_browser_inspect.go b/cmd/pinchtab/cmd_cli_browser_inspect.goindex 729c71dd..085cb419 100644--- a/cmd/pinchtab/cmd_cli_browser_inspect.go+++ b/cmd/pinchtab/cmd_cli_browser_inspect.go@@ -116,6 +116,83 @@ var stylesCmd = &cobra.Command{},}+var valueCmd = &cobra.Command{+ Use: "value <ref>",+ Short: "Get the current value of a form element by ref",+ Args: cobra.ExactArgs(1),+ Run: func(cmd *cobra.Command, args []string) {+ runCLI(func(rt cliRuntime) {+ browseractions.Value(rt.client, rt.base, rt.token, cmd, args)+ })+ },+}++var attrCmd = &cobra.Command{+ Use: "attr <ref> <name>",+ Short: "Get the value of an HTML attribute by ref",+ Args: cobra.ExactArgs(2),+ Run: func(cmd *cobra.Command, args []string) {+ runCLI(func(rt cliRuntime) {+ browseractions.Attr(rt.client, rt.base, rt.token, cmd, args)+ })+ },+}++var boxCmd = &cobra.Command{+ Use: "box <ref>",+ Short: "Get the bounding box of an element by ref",+ Args: cobra.ExactArgs(1),+ Run: func(cmd *cobra.Command, args []string) {+ runCLI(func(rt cliRuntime) {+ browseractions.Box(rt.client, rt.base, rt.token, cmd, args)+ })+ },+}++var visibleCmd = &cobra.Command{+ Use: "visible <ref>",+ Short: "Check if an element is visible by ref",+ Args: cobra.ExactArgs(1),+ Run: func(cmd *cobra.Command, args []string) {+ runCLI(func(rt cliRuntime) {+ browseractions.Visible(rt.client, rt.base, rt.token, cmd, args)+ })+ },+}++var enabledCmd = &cobra.Command{+ Use: "enabled <ref>",+ Short: "Check if an element is enabled by ref",+ Args: cobra.ExactArgs(1),+ Run: func(cmd *cobra.Command, args []string) {+ runCLI(func(rt cliRuntime) {+ browseractions.Enabled(rt.client, rt.base, rt.token, cmd, args)+ })+ },+}++var checkedCmd = &cobra.Command{+ Use: "checked <ref>",+ Short: "Check if an element is checked by ref",+ Args: cobra.ExactArgs(1),+ Run: func(cmd *cobra.Command, args []string) {+ runCLI(func(rt cliRuntime) {+ browseractions.Checked(rt.client, rt.base, rt.token, cmd, args)+ })+ },+}++var countCmd = &cobra.Command{+ Use: "count <selector>",+ Short: "Count elements matching a CSS selector",+ Args: cobra.ExactArgs(1),+ Run: func(cmd *cobra.Command, args []string) {+ runCLI(func(rt cliRuntime) {+ browseractions.Count(rt.client, rt.base, rt.token, cmd, args)+ })+ },+}+var downloadCmd = &cobra.Command{Use: "download <url>",Short: "Download a file via browser session",diff --git a/cmd/pinchtab/cmd_cli_cookies.go b/cmd/pinchtab/cmd_cli_cookies.gonew file mode 100644index 00000000..1ecd499a--- /dev/null+++ b/cmd/pinchtab/cmd_cli_cookies.go@@ -0,0 +1,27 @@+package main++import (+ browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"+ "github.com/spf13/cobra"+)++var cookiesCmd = &cobra.Command{+ Use: "cookies",+ Short: "Manage browser cookies",+ Long: "Commands for managing browser cookies.",+}++var cookiesClearCmd = &cobra.Command{+ Use: "clear",+ Short: "Clear all browser cookies",+ Long: "Clear all browser cookies via CDP. This affects all origins.",+ Run: func(cmd *cobra.Command, args []string) {+ runCLI(func(rt cliRuntime) {+ browseractions.CookiesClear(rt.client, rt.base, rt.token, cmd)+ })+ },+}++func init() {+ cookiesCmd.AddCommand(cookiesClearCmd)+}diff --git a/cmd/pinchtab/cmd_cli_emulation.go b/cmd/pinchtab/cmd_cli_emulation.gonew file mode 100644index 00000000..13f97697--- /dev/null+++ b/cmd/pinchtab/cmd_cli_emulation.go@@ -0,0 +1,97 @@+package main++import (+ browseractions "github.com/pinchtab/pinchtab/internal/cli/actions"+ "github.com/spf13/cobra"+)++var setCmd = &cobra.Command{+ Use: "set",+ Short: "Set browser emulation properties",+ Long: "Commands for setting browser emulation properties such as viewport, geolocation, and network conditions.",+}++var setViewportCmd = &cobra.Command{+ Use: "viewport <width> <height>",+ Short: "Set browser viewport dimensions",+ Long: "Set the browser viewport dimensions using CDP emulation. Accepts optional --dpr and --mobile flags.",+ Args: cobra.ExactArgs(2),+ Run: func(cmd *cobra.Command, args []string) {+ runCLI(func(rt cliRuntime) {+ browseractions.SetViewport(rt.client, rt.base, rt.token, cmd, args)+ })+ },+}++var setGeoCmd = &cobra.Command{+ Use: "geo <latitude> <longitude>",+ Short: "Set browser geolocation",+ Long: "Set the browser geolocation using CDP emulation. Accepts optional --accuracy flag.",+ Args: cobra.ExactArgs(2),+ Run: func(cmd *cobra.Command, args []string) {+ runCLI(func(rt cliRuntime) {+ browseractions.SetGeolocation(rt.client, rt.base, rt.token, cmd, args)+ })+ },+}++var setOfflineCmd = &cobra.Command{+ Use: "offline <true|false>",+ Short: "Enable or disable network offline emulation",+ Long: "Enable or disable network offline emulation using CDP network.EmulateNetworkConditions.",+ Args: cobra.ExactArgs(1),+ Run: func(cmd *cobra.Command, args []string) {+ runCLI(func(rt cliRuntime) {+ browseractions.SetOffline(rt.client, rt.base, rt.token, cmd, args)+ })+ },+}++var setHeadersCmd = &cobra.Command{+ Use: "headers '<json>'",+ Short: "Set extra HTTP headers for all network requests",+ Long: "Set extra HTTP headers using CDP network.SetExtraHTTPHeaders. Pass a JSON object as a single argument. An empty object {} clears extra headers.",+ Args: cobra.ExactArgs(1),+ Run: func(cmd *cobra.Command, args []string) {+ runCLI(func(rt cliRuntime) {+ browseractions.SetHeaders(rt.client, rt.base, rt.token, cmd, args)+ })+ },+}++var setCredentialsCmd = &cobra.Command{+ Use: "credentials <username> <password>",+ Short: "Set HTTP basic auth credentials",+ Long: "Set HTTP basic auth credentials using CDP Fetch domain. The browser will automatically respond to 401/407 auth challenges.",+ Args: cobra.ExactArgs(2),+ Run: func(cmd *cobra.Command, args []string) {+ runCLI(func(rt cliRuntime) {+ browseractions.SetCredentials(rt.client, rt.base, rt.token, cmd, args)+ })+ },+}++var setMediaCmd = &cobra.Command{+ Use: "media <feature> <value>",+ Short: "Emulate a CSS media feature",+ Long: "Emulate a CSS media feature using CDP emulation.SetEmulatedMedia. Example: pinchtab set media prefers-color-scheme dark",+ Args: cobra.ExactArgs(2),+ Run: func(cmd *cobra.Command, args []string) {+ runCLI(func(rt cliRuntime) {+ browseractions.SetMedia(rt.client, rt.base, rt.token, cmd, args)+ })+ },+}++func init() {+ setViewportCmd.Flags().Float64("dpr", 0, "Device pixel ratio (default 1.0)")+ setViewportCmd.Flags().Bool("mobile", false, "Emulate mobile device")+ setGeoCmd.Flags().Float64("accuracy", 0, "Geolocation accuracy in meters (default 1.0)")++ setCmd.AddCommand(setViewportCmd)+ setCmd.AddCommand(setGeoCmd)+ setCmd.AddCommand(setOfflineCmd)+ setCmd.AddCommand(setHeadersCmd)+ setCmd.AddCommand(setCredentialsCmd)+ setCmd.AddCommand(setMediaCmd)+}diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.goindex a0215e5c..0526c45a 100644--- a/cmd/pinchtab/cmd_cli_register.go+++ b/cmd/pinchtab/cmd_cli_register.go@@ -46,6 +46,13 @@ func registerBrowserCommands() {urlCmd,htmlCmd,stylesCmd,+ valueCmd,+ attrCmd,+ countCmd,+ boxCmd,+ visibleCmd,+ enabledCmd,+ checkedCmd,downloadCmd,uploadCmd,findCmd,@@ -63,6 +70,8 @@ func registerBrowserCommands() {errorsCmd,clipboardCmd,cacheCmd,+ cookiesCmd,+ setCmd,storageCmd,stateCmd,closeCmd,@@ -114,6 +123,13 @@ func registerBrowserCommands() {urlCmd,htmlCmd,stylesCmd,+ valueCmd,+ attrCmd,+ countCmd,+ boxCmd,+ visibleCmd,+ enabledCmd,+ checkedCmd,downloadCmd,uploadCmd,findCmd,@@ -131,6 +147,8 @@ func registerBrowserCommands() {errorsCmd,clipboardCmd,cacheCmd,+ cookiesCmd,+ setCmd,storageCmd,stateCmd,closeCmd,@@ -255,6 +273,13 @@ func configureBrowserFlags() {stylesCmd.Flags().StringP("selector", "s", "", "Element selector to extract styles from (ref/CSS/XPath/text). If omitted, returns computed styles for the root element.")stylesCmd.Flags().String("prop", "", "Return only a single computed style property")stylesCmd.Flags().Bool("json", false, "Output full JSON response instead of just styles")+ valueCmd.Flags().Bool("json", false, "Output full JSON response instead of just value")+ attrCmd.Flags().Bool("json", false, "Output full JSON response instead of just attribute value")+ countCmd.Flags().Bool("json", false, "Output full JSON response instead of just count")+ boxCmd.Flags().Bool("json", false, "Output full JSON response instead of just bounding box")+ visibleCmd.Flags().Bool("json", false, "Output full JSON response instead of just visibility")+ enabledCmd.Flags().Bool("json", false, "Output full JSON response instead of just enabled state")+ checkedCmd.Flags().Bool("json", false, "Output full JSON response instead of just checked state")navCmd.Flags().Bool("new-tab", false, "Open in new tab")navCmd.Flags().Bool("block-images", false, "Block image loading")@@ -295,6 +320,13 @@ func configureBrowserFlags() {urlCmd,htmlCmd,stylesCmd,+ valueCmd,+ attrCmd,+ countCmd,+ boxCmd,+ visibleCmd,+ enabledCmd,+ checkedCmd,clickCmd,dblclickCmd,hoverCmd,@@ -321,6 +353,12 @@ func configureBrowserFlags() {waitCmd,dialogAcceptCmd,dialogDismissCmd,+ setViewportCmd,+ setGeoCmd,+ setOfflineCmd,+ setHeadersCmd,+ setCredentialsCmd,+ setMediaCmd,)evalCmd.Flags().Bool("await-promise", false, "Resolve a returned Promise before responding")@@ -373,8 +411,15 @@ func configureBrowserFlags() {healthCmd,cacheClearCmd,cacheStatusCmd,+ cookiesClearCmd,frameCmd,networkCmd,+ setViewportCmd,+ setGeoCmd,+ setOfflineCmd,+ setHeadersCmd,+ setCredentialsCmd,+ setMediaCmd,)scrollintoviewCmd.Flags().String("css", "", "CSS selector instead of ref")diff --git a/internal/bridge/api.go b/internal/bridge/api.goindex 8bf56e78..0c9fe866 100644--- a/internal/bridge/api.go+++ b/internal/bridge/api.go@@ -77,6 +77,9 @@ type BridgeAPI interface {// Cache managementClearCache(ctx context.Context) errorCanClearCache(ctx context.Context) (bool, error)++ // Cookie management+ ClearCookies(ctx context.Context) error}type LockInfo = bridgetabs.LockInfodiff --git a/internal/bridge/cookies.go b/internal/bridge/cookies.gonew file mode 100644index 00000000..094c4ebf--- /dev/null+++ b/internal/bridge/cookies.go@@ -0,0 +1,15 @@+package bridge++import (+ "context"++ "github.com/chromedp/chromedp"+)++// ClearCookies clears all browser cookies.+// This affects all origins and does not require an active tab.+func (b *Bridge) ClearCookies(ctx context.Context) error {+ return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Network.clearBrowserCookies", nil, nil)+ }))+}diff --git a/internal/bridge/semantic_metadata.go b/internal/bridge/semantic_metadata.goindex 2e1cb51b..71312a2e 100644--- a/internal/bridge/semantic_metadata.go+++ b/internal/bridge/semantic_metadata.go@@ -16,6 +16,7 @@ type nodeDOMMetadata struct {Title string `json:"title"`TestID string `json:"testid"`Text string `json:"text"`+ InputType string `json:"inputType"`}// EnrichA11yNodesWithDOMMetadata adds DOM-backed descriptor fields used by the@@ -110,6 +111,9 @@ func applyNodeDOMMetadata(node *A11yNode, meta nodeDOMMetadata) {node.Title = strings.TrimSpace(meta.Title)node.TestID = strings.TrimSpace(meta.TestID)node.Text = strings.TrimSpace(meta.Text)+ if strings.EqualFold(strings.TrimSpace(meta.InputType), "password") {+ node.Value = "••••••••"+ }}const domMetadataFn = `function() {@@ -166,6 +170,7 @@ const domMetadataFn = `function() {alt: attr("alt"),title: attr("title"),testid: testID(),- text: text.length > 500 ? text.slice(0, 500) : text+ text: text.length > 500 ? text.slice(0, 500) : text,+ inputType: (el.tagName && el.tagName.toLowerCase() === "input") ? (el.type || "") : ""};}`diff --git a/internal/bridge/semantic_metadata_test.go b/internal/bridge/semantic_metadata_test.gonew file mode 100644index 00000000..b51ba5ff--- /dev/null+++ b/internal/bridge/semantic_metadata_test.go@@ -0,0 +1,89 @@+package bridge++import "testing"++func TestApplyNodeDOMMetadataRedactsPassword(t *testing.T) {+ node := A11yNode{+ Role: "textbox",+ Name: "Password",+ Value: "supersecret123",+ }+ meta := nodeDOMMetadata{+ Tag: "input",+ InputType: "password",+ }+ applyNodeDOMMetadata(&node, meta)++ if node.Value != "••••••••" {+ t.Errorf("password value = %q, want redacted", node.Value)+ }+ if node.Tag != "input" {+ t.Errorf("tag = %q, want input", node.Tag)+ }+}++func TestApplyNodeDOMMetadataPreservesTextInput(t *testing.T) {+ node := A11yNode{+ Role: "textbox",+ Name: "Username",+ Value: "mario",+ }+ meta := nodeDOMMetadata{+ Tag: "input",+ InputType: "text",+ }+ applyNodeDOMMetadata(&node, meta)++ if node.Value != "mario" {+ t.Errorf("text value = %q, want mario", node.Value)+ }+}++func TestApplyNodeDOMMetadataRedactsPasswordCaseInsensitive(t *testing.T) {+ node := A11yNode{+ Role: "textbox",+ Name: "Password",+ Value: "secret",+ }+ meta := nodeDOMMetadata{+ Tag: "input",+ InputType: "Password",+ }+ applyNodeDOMMetadata(&node, meta)++ if node.Value != "••••••••" {+ t.Errorf("password value = %q, want redacted", node.Value)+ }+}++func TestApplyNodeDOMMetadataNoInputType(t *testing.T) {+ node := A11yNode{+ Role: "textbox",+ Name: "Search",+ Value: "query",+ }+ meta := nodeDOMMetadata{+ Tag: "input",+ }+ applyNodeDOMMetadata(&node, meta)++ if node.Value != "query" {+ t.Errorf("value = %q, want query", node.Value)+ }+}++func TestApplyNodeDOMMetadataEmptyPasswordValue(t *testing.T) {+ node := A11yNode{+ Role: "textbox",+ Name: "Password",+ }+ meta := nodeDOMMetadata{+ Tag: "input",+ InputType: "password",+ }+ applyNodeDOMMetadata(&node, meta)++ if node.Value != "••••••••" {+ t.Errorf("empty password = %q, want redacted placeholder", node.Value)+ }+}diff --git a/internal/cli/actions/actions_attr.go b/internal/cli/actions/actions_attr.gonew file mode 100644index 00000000..8e59542a--- /dev/null+++ b/internal/cli/actions/actions_attr.go@@ -0,0 +1,48 @@+package actions++import (+ "encoding/json"+ "net/http"+ "net/url"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/pinchtab/pinchtab/internal/cli/output"+ "github.com/spf13/cobra"+)++// Attr retrieves the value of an HTML attribute on an element identified by ref.+func Attr(client *http.Client, base, token string, cmd *cobra.Command, args []string) {+ if len(args) < 2 {+ output.Error("attr", "ref and name arguments are required", 1)+ return+ }+ ref := args[0]+ name := args[1]++ params := url.Values{}+ params.Set("ref", ref)+ params.Set("name", name)+ if v, _ := cmd.Flags().GetString("tab"); v != "" {+ params.Set("tabId", v)+ }++ jsonOutput, _ := cmd.Flags().GetBool("json")+ if jsonOutput {+ apiclient.DoGet(client, base, token, "/attr", params)+ return+ }++ body := apiclient.DoGetRaw(client, base, token, "/attr", params)+ var result struct {+ Value *string `json:"value"`+ }+ if err := json.Unmarshal(body, &result); err != nil {+ output.Value(string(body))+ return+ }+ if result.Value == nil {+ output.Value("null")+ } else {+ output.Value(*result.Value)+ }+}diff --git a/internal/cli/actions/actions_box.go b/internal/cli/actions/actions_box.gonew file mode 100644index 00000000..41239cda--- /dev/null+++ b/internal/cli/actions/actions_box.go@@ -0,0 +1,54 @@+package actions++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/url"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/pinchtab/pinchtab/internal/cli/output"+ "github.com/spf13/cobra"+)++// Box retrieves the bounding box of an element identified by ref.+func Box(client *http.Client, base, token string, cmd *cobra.Command, args []string) {+ if len(args) == 0 {+ output.Error("box", "ref argument is required", 1)+ return+ }+ ref := args[0]++ params := url.Values{}+ params.Set("ref", ref)+ if v, _ := cmd.Flags().GetString("tab"); v != "" {+ params.Set("tabId", v)+ }++ jsonOutput, _ := cmd.Flags().GetBool("json")+ if jsonOutput {+ apiclient.DoGet(client, base, token, "/box", params)+ return+ }++ body := apiclient.DoGetRaw(client, base, token, "/box", params)+ var result struct {+ Box struct {+ X float64 `json:"x"`+ Y float64 `json:"y"`+ Width float64 `json:"width"`+ Height float64 `json:"height"`+ Top float64 `json:"top"`+ Right float64 `json:"right"`+ Bottom float64 `json:"bottom"`+ Left float64 `json:"left"`+ } `json:"box"`+ }+ if err := json.Unmarshal(body, &result); err != nil {+ output.Value(string(body))+ return+ }+ output.Value(fmt.Sprintf("x:%.0f y:%.0f width:%.0f height:%.0f top:%.0f right:%.0f bottom:%.0f left:%.0f",+ result.Box.X, result.Box.Y, result.Box.Width, result.Box.Height,+ result.Box.Top, result.Box.Right, result.Box.Bottom, result.Box.Left))+}diff --git a/internal/cli/actions/actions_checked.go b/internal/cli/actions/actions_checked.gonew file mode 100644index 00000000..9890b08f--- /dev/null+++ b/internal/cli/actions/actions_checked.go@@ -0,0 +1,46 @@+package actions++import (+ "encoding/json"+ "net/http"+ "net/url"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/pinchtab/pinchtab/internal/cli/output"+ "github.com/spf13/cobra"+)++// Checked checks whether an element identified by ref is checked.+func Checked(client *http.Client, base, token string, cmd *cobra.Command, args []string) {+ if len(args) == 0 {+ output.Error("checked", "ref argument is required", 1)+ return+ }+ ref := args[0]++ params := url.Values{}+ params.Set("ref", ref)+ if v, _ := cmd.Flags().GetString("tab"); v != "" {+ params.Set("tabId", v)+ }++ jsonOutput, _ := cmd.Flags().GetBool("json")+ if jsonOutput {+ apiclient.DoGet(client, base, token, "/checked", params)+ return+ }++ body := apiclient.DoGetRaw(client, base, token, "/checked", params)+ var result struct {+ Checked bool `json:"checked"`+ }+ if err := json.Unmarshal(body, &result); err != nil {+ output.Value(string(body))+ return+ }+ if result.Checked {+ output.Value("true")+ } else {+ output.Value("false")+ }+}diff --git a/internal/cli/actions/actions_cookies.go b/internal/cli/actions/actions_cookies.gonew file mode 100644index 00000000..cdf80a18--- /dev/null+++ b/internal/cli/actions/actions_cookies.go@@ -0,0 +1,28 @@+package actions++import (+ "encoding/json"+ "fmt"+ "net/http"+ "os"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/spf13/cobra"+)++// CookiesClear clears all browser cookies.+func CookiesClear(client *http.Client, base, token string, cmd *cobra.Command) {+ result := apiclient.DoDelete(client, base, token, "/cookies", nil)+ if result == nil {+ fmt.Fprintln(os.Stderr, "ERROR: cookies: clear failed")+ os.Exit(2)+ }++ jsonOut, _ := cmd.Flags().GetBool("json")+ if jsonOut {+ out, _ := json.MarshalIndent(result, "", " ")+ fmt.Println(string(out))+ } else {+ fmt.Println("OK")+ }+}diff --git a/internal/cli/actions/actions_count.go b/internal/cli/actions/actions_count.gonew file mode 100644index 00000000..38175ebe--- /dev/null+++ b/internal/cli/actions/actions_count.go@@ -0,0 +1,43 @@+package actions++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/url"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/pinchtab/pinchtab/internal/cli/output"+ "github.com/spf13/cobra"+)++// Count returns the number of elements matching a CSS selector.+func Count(client *http.Client, base, token string, cmd *cobra.Command, args []string) {+ if len(args) == 0 {+ output.Error("count", "selector argument is required", 1)+ return+ }+ selector := args[0]++ params := url.Values{}+ params.Set("selector", selector)+ if v, _ := cmd.Flags().GetString("tab"); v != "" {+ params.Set("tabId", v)+ }++ jsonOutput, _ := cmd.Flags().GetBool("json")+ if jsonOutput {+ apiclient.DoGet(client, base, token, "/count", params)+ return+ }++ body := apiclient.DoGetRaw(client, base, token, "/count", params)+ var result struct {+ Count int `json:"count"`+ }+ if err := json.Unmarshal(body, &result); err != nil {+ output.Value(string(body))+ return+ }+ output.Value(fmt.Sprintf("%d", result.Count))+}diff --git a/internal/cli/actions/actions_credentials.go b/internal/cli/actions/actions_credentials.gonew file mode 100644index 00000000..c63a1a97--- /dev/null+++ b/internal/cli/actions/actions_credentials.go@@ -0,0 +1,45 @@+package actions++import (+ "encoding/json"+ "fmt"+ "net/http"+ "os"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/spf13/cobra"+)++// SetCredentials sets HTTP auth credentials via the HTTP API.+func SetCredentials(client *http.Client, base, token string, cmd *cobra.Command, args []string) {+ if len(args) < 2 {+ fmt.Fprintln(os.Stderr, "ERROR: set credentials requires <username> <password> arguments")+ os.Exit(2)+ }++ body := map[string]any{+ "username": args[0],+ "password": args[1],+ }++ tab, _ := cmd.Flags().GetString("tab")+ path := "/emulation/credentials"+ if tab != "" {+ path = "/tabs/" + tab + "/emulation/credentials"+ }++ result := apiclient.DoPostQuiet(client, base, token, path, body)+ if result == nil {+ fmt.Fprintln(os.Stderr, "ERROR: set credentials failed")+ os.Exit(2)+ }++ jsonOut, _ := cmd.Flags().GetBool("json")+ if jsonOut {+ out, _ := json.MarshalIndent(result, "", " ")+ fmt.Println(string(out))+ } else {+ status, _ := result["status"].(string)+ fmt.Println(status)+ }+}diff --git a/internal/cli/actions/actions_emulation.go b/internal/cli/actions/actions_emulation.gonew file mode 100644index 00000000..bd5ad14a--- /dev/null+++ b/internal/cli/actions/actions_emulation.go@@ -0,0 +1,61 @@+package actions++import (+ "encoding/json"+ "fmt"+ "net/http"+ "os"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/spf13/cobra"+)++// SetViewport sets the browser viewport dimensions via the HTTP API.+func SetViewport(client *http.Client, base, token string, cmd *cobra.Command, args []string) {+ if len(args) < 2 {+ fmt.Fprintln(os.Stderr, "ERROR: set viewport requires <width> <height> arguments")+ os.Exit(2)+ }++ var width, height int+ if _, err := fmt.Sscanf(args[0], "%d", &width); err != nil || width <= 0 {+ fmt.Fprintf(os.Stderr, "ERROR: invalid width %q: must be a positive integer\n", args[0])+ os.Exit(2)+ }+ if _, err := fmt.Sscanf(args[1], "%d", &height); err != nil || height <= 0 {+ fmt.Fprintf(os.Stderr, "ERROR: invalid height %q: must be a positive integer\n", args[1])+ os.Exit(2)+ }++ body := map[string]any{+ "width": width,+ "height": height,+ }++ if dpr, _ := cmd.Flags().GetFloat64("dpr"); dpr > 0 {+ body["deviceScaleFactor"] = dpr+ }+ if mobile, _ := cmd.Flags().GetBool("mobile"); mobile {+ body["mobile"] = true+ }++ tab, _ := cmd.Flags().GetString("tab")+ path := "/emulation/viewport"+ if tab != "" {+ path = "/tabs/" + tab + "/emulation/viewport"+ }++ result := apiclient.DoPostQuiet(client, base, token, path, body)+ if result == nil {+ fmt.Fprintln(os.Stderr, "ERROR: set viewport failed")+ os.Exit(2)+ }++ jsonOut, _ := cmd.Flags().GetBool("json")+ if jsonOut {+ out, _ := json.MarshalIndent(result, "", " ")+ fmt.Println(string(out))+ } else {+ fmt.Printf("%dx%d\n", width, height)+ }+}diff --git a/internal/cli/actions/actions_enabled.go b/internal/cli/actions/actions_enabled.gonew file mode 100644index 00000000..1a2c35c6--- /dev/null+++ b/internal/cli/actions/actions_enabled.go@@ -0,0 +1,46 @@+package actions++import (+ "encoding/json"+ "net/http"+ "net/url"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/pinchtab/pinchtab/internal/cli/output"+ "github.com/spf13/cobra"+)++// Enabled checks whether an element identified by ref is enabled (not disabled).+func Enabled(client *http.Client, base, token string, cmd *cobra.Command, args []string) {+ if len(args) == 0 {+ output.Error("enabled", "ref argument is required", 1)+ return+ }+ ref := args[0]++ params := url.Values{}+ params.Set("ref", ref)+ if v, _ := cmd.Flags().GetString("tab"); v != "" {+ params.Set("tabId", v)+ }++ jsonOutput, _ := cmd.Flags().GetBool("json")+ if jsonOutput {+ apiclient.DoGet(client, base, token, "/enabled", params)+ return+ }++ body := apiclient.DoGetRaw(client, base, token, "/enabled", params)+ var result struct {+ Enabled bool `json:"enabled"`+ }+ if err := json.Unmarshal(body, &result); err != nil {+ output.Value(string(body))+ return+ }+ if result.Enabled {+ output.Value("true")+ } else {+ output.Value("false")+ }+}diff --git a/internal/cli/actions/actions_geolocation.go b/internal/cli/actions/actions_geolocation.gonew file mode 100644index 00000000..b108a26e--- /dev/null+++ b/internal/cli/actions/actions_geolocation.go@@ -0,0 +1,61 @@+package actions++import (+ "encoding/json"+ "fmt"+ "net/http"+ "os"+ "strconv"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/spf13/cobra"+)++// SetGeolocation sets the browser geolocation via the HTTP API.+func SetGeolocation(client *http.Client, base, token string, cmd *cobra.Command, args []string) {+ if len(args) < 2 {+ fmt.Fprintln(os.Stderr, "ERROR: set geo requires <latitude> <longitude> arguments")+ os.Exit(2)+ }++ latitude, err := strconv.ParseFloat(args[0], 64)+ if err != nil {+ fmt.Fprintf(os.Stderr, "ERROR: invalid latitude %q: must be a number\n", args[0])+ os.Exit(2)+ }++ longitude, err := strconv.ParseFloat(args[1], 64)+ if err != nil {+ fmt.Fprintf(os.Stderr, "ERROR: invalid longitude %q: must be a number\n", args[1])+ os.Exit(2)+ }++ body := map[string]any{+ "latitude": latitude,+ "longitude": longitude,+ }++ if accuracy, _ := cmd.Flags().GetFloat64("accuracy"); accuracy > 0 {+ body["accuracy"] = accuracy+ }++ tab, _ := cmd.Flags().GetString("tab")+ path := "/emulation/geolocation"+ if tab != "" {+ path = "/tabs/" + tab + "/emulation/geolocation"+ }++ result := apiclient.DoPostQuiet(client, base, token, path, body)+ if result == nil {+ fmt.Fprintln(os.Stderr, "ERROR: set geo failed")+ os.Exit(2)+ }++ jsonOut, _ := cmd.Flags().GetBool("json")+ if jsonOut {+ out, _ := json.MarshalIndent(result, "", " ")+ fmt.Println(string(out))+ } else {+ fmt.Printf("%.6f,%.6f\n", latitude, longitude)+ }+}diff --git a/internal/cli/actions/actions_headers.go b/internal/cli/actions/actions_headers.gonew file mode 100644index 00000000..73c7d1d8--- /dev/null+++ b/internal/cli/actions/actions_headers.go@@ -0,0 +1,49 @@+package actions++import (+ "encoding/json"+ "fmt"+ "net/http"+ "os"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/spf13/cobra"+)++// SetHeaders sets extra HTTP headers via the HTTP API.+func SetHeaders(client *http.Client, base, token string, cmd *cobra.Command, args []string) {+ if len(args) < 1 {+ fmt.Fprintln(os.Stderr, "ERROR: set headers requires a JSON object argument")+ os.Exit(2)+ }++ var headers map[string]string+ if err := json.Unmarshal([]byte(args[0]), &headers); err != nil {+ fmt.Fprintf(os.Stderr, "ERROR: invalid JSON: %v\n", err)+ os.Exit(2)+ }++ body := map[string]any{+ "headers": headers,+ }++ tab, _ := cmd.Flags().GetString("tab")+ path := "/emulation/headers"+ if tab != "" {+ path = "/tabs/" + tab + "/emulation/headers"+ }++ result := apiclient.DoPostQuiet(client, base, token, path, body)+ if result == nil {+ fmt.Fprintln(os.Stderr, "ERROR: set headers failed")+ os.Exit(2)+ }++ jsonOut, _ := cmd.Flags().GetBool("json")+ if jsonOut {+ out, _ := json.MarshalIndent(result, "", " ")+ fmt.Println(string(out))+ } else {+ fmt.Println("applied")+ }+}diff --git a/internal/cli/actions/actions_media.go b/internal/cli/actions/actions_media.gonew file mode 100644index 00000000..c439fc3e--- /dev/null+++ b/internal/cli/actions/actions_media.go@@ -0,0 +1,45 @@+package actions++import (+ "encoding/json"+ "fmt"+ "net/http"+ "os"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/spf13/cobra"+)++// SetMedia emulates a CSS media feature via the HTTP API.+func SetMedia(client *http.Client, base, token string, cmd *cobra.Command, args []string) {+ if len(args) < 2 {+ fmt.Fprintln(os.Stderr, "ERROR: set media requires <feature> <value> arguments")+ os.Exit(2)+ }++ body := map[string]any{+ "feature": args[0],+ "value": args[1],+ }++ tab, _ := cmd.Flags().GetString("tab")+ path := "/emulation/media"+ if tab != "" {+ path = "/tabs/" + tab + "/emulation/media"+ }++ result := apiclient.DoPostQuiet(client, base, token, path, body)+ if result == nil {+ fmt.Fprintln(os.Stderr, "ERROR: set media failed")+ os.Exit(2)+ }++ jsonOut, _ := cmd.Flags().GetBool("json")+ if jsonOut {+ out, _ := json.MarshalIndent(result, "", " ")+ fmt.Println(string(out))+ } else {+ status, _ := result["status"].(string)+ fmt.Println(status)+ }+}diff --git a/internal/cli/actions/actions_offline.go b/internal/cli/actions/actions_offline.gonew file mode 100644index 00000000..b94c9f9a--- /dev/null+++ b/internal/cli/actions/actions_offline.go@@ -0,0 +1,54 @@+package actions++import (+ "encoding/json"+ "fmt"+ "net/http"+ "os"+ "strconv"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/spf13/cobra"+)++// SetOffline enables or disables network offline emulation via the HTTP API.+func SetOffline(client *http.Client, base, token string, cmd *cobra.Command, args []string) {+ if len(args) < 1 {+ fmt.Fprintln(os.Stderr, "ERROR: set offline requires <true|false> argument")+ os.Exit(2)+ }++ offline, err := strconv.ParseBool(args[0])+ if err != nil {+ fmt.Fprintf(os.Stderr, "ERROR: invalid offline value %q: must be true or false\n", args[0])+ os.Exit(2)+ }++ body := map[string]any{+ "offline": offline,+ }++ tab, _ := cmd.Flags().GetString("tab")+ path := "/emulation/offline"+ if tab != "" {+ path = "/tabs/" + tab + "/emulation/offline"+ }++ result := apiclient.DoPostQuiet(client, base, token, path, body)+ if result == nil {+ fmt.Fprintln(os.Stderr, "ERROR: set offline failed")+ os.Exit(2)+ }++ jsonOut, _ := cmd.Flags().GetBool("json")+ if jsonOut {+ out, _ := json.MarshalIndent(result, "", " ")+ fmt.Println(string(out))+ } else {+ if offline {+ fmt.Println("offline")+ } else {+ fmt.Println("online")+ }+ }+}diff --git a/internal/cli/actions/actions_value.go b/internal/cli/actions/actions_value.gonew file mode 100644index 00000000..27bba4b7--- /dev/null+++ b/internal/cli/actions/actions_value.go@@ -0,0 +1,46 @@+package actions++import (+ "encoding/json"+ "net/http"+ "net/url"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/pinchtab/pinchtab/internal/cli/output"+ "github.com/spf13/cobra"+)++// Value retrieves the .value property of a form element identified by ref.+func Value(client *http.Client, base, token string, cmd *cobra.Command, args []string) {+ if len(args) == 0 {+ output.Error("value", "ref argument is required", 1)+ return+ }+ ref := args[0]++ params := url.Values{}+ params.Set("ref", ref)+ if v, _ := cmd.Flags().GetString("tab"); v != "" {+ params.Set("tabId", v)+ }++ jsonOutput, _ := cmd.Flags().GetBool("json")+ if jsonOutput {+ apiclient.DoGet(client, base, token, "/value", params)+ return+ }++ body := apiclient.DoGetRaw(client, base, token, "/value", params)+ var result struct {+ Value *string `json:"value"`+ }+ if err := json.Unmarshal(body, &result); err != nil {+ output.Value(string(body))+ return+ }+ if result.Value == nil {+ output.Value("null")+ } else {+ output.Value(*result.Value)+ }+}diff --git a/internal/cli/actions/actions_visible.go b/internal/cli/actions/actions_visible.gonew file mode 100644index 00000000..a11f5d8a--- /dev/null+++ b/internal/cli/actions/actions_visible.go@@ -0,0 +1,46 @@+package actions++import (+ "encoding/json"+ "net/http"+ "net/url"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/pinchtab/pinchtab/internal/cli/output"+ "github.com/spf13/cobra"+)++// Visible checks whether an element identified by ref is visible on the page.+func Visible(client *http.Client, base, token string, cmd *cobra.Command, args []string) {+ if len(args) == 0 {+ output.Error("visible", "ref argument is required", 1)+ return+ }+ ref := args[0]++ params := url.Values{}+ params.Set("ref", ref)+ if v, _ := cmd.Flags().GetString("tab"); v != "" {+ params.Set("tabId", v)+ }++ jsonOutput, _ := cmd.Flags().GetBool("json")+ if jsonOutput {+ apiclient.DoGet(client, base, token, "/visible", params)+ return+ }++ body := apiclient.DoGetRaw(client, base, token, "/visible", params)+ var result struct {+ Visible bool `json:"visible"`+ }+ if err := json.Unmarshal(body, &result); err != nil {+ output.Value(string(body))+ return+ }+ if result.Visible {+ output.Value("true")+ } else {+ output.Value("false")+ }+}diff --git a/internal/handlers/attr.go b/internal/handlers/attr.gonew file mode 100644index 00000000..6effa144--- /dev/null+++ b/internal/handlers/attr.go@@ -0,0 +1,169 @@+package handlers++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++type attrResponse struct {+ Ref string `json:"ref"`+ Name string `json:"name"`+ Value *string `json:"value"` // null when the attribute does not exist+}++// HandleGetAttr returns the value of a specific HTML attribute on an element identified by ref.+//+// @Endpoint GET /attr+func (h *Handlers) HandleGetAttr(w http.ResponseWriter, r *http.Request) {+ tabID := r.URL.Query().Get("tabId")+ h.recordReadRequest(r, "inspect.attr", tabID)++ ref := r.URL.Query().Get("ref")+ if ref == "" {+ httpx.Error(w, 400, fmt.Errorf("ref query parameter is required"))+ return+ }++ name := r.URL.Query().Get("name")+ if name == "" {+ httpx.Error(w, 400, fmt.Errorf("name query parameter is required"))+ return+ }++ if err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))+ return+ }++ ctx, resolvedTabID, err := h.tabContextWithHeader(w, r, tabID)+ if err != nil {+ WriteTabContextError(w, err, 404)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }+ defer h.armAutoCloseIfEnabled(resolvedTabID)++ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)+ defer tCancel()+ go httpx.CancelOnClientDone(r.Context(), tCancel)++ val, err := h.getElementAttr(tCtx, resolvedTabID, ref, name)+ if err != nil {+ httpx.Error(w, 500, err)+ return+ }++ httpx.JSON(w, 200, attrResponse{Ref: ref, Name: name, Value: val})+}++// HandleTabGetAttr returns the attribute value for a tab identified by path ID.+//+// @Endpoint GET /tabs/{id}/attr+func (h *Handlers) HandleTabGetAttr(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ q := r.URL.Query()+ q.Set("tabId", tabID)++ req := r.Clone(r.Context())+ u := *r.URL+ u.RawQuery = q.Encode()+ req.URL = &u++ h.HandleGetAttr(w, req)+}++// getElementAttr resolves a ref to a DOM node and returns the value of the+// named HTML attribute. Returns a nil pointer when the attribute does not exist.+func (h *Handlers) getElementAttr(ctx context.Context, tabID, ref, name string) (*string, error) {+ cache := h.Bridge.GetRefCache(tabID)+ if cache == nil {+ return nil, fmt.Errorf("ref not found: %s (no snapshot cache — run /snapshot first)", ref)+ }+ target, ok := cache.Lookup(ref)+ if !ok {+ return nil, fmt.Errorf("ref not found: %s", ref)+ }++ nodeID := target.BackendNodeID+ if nodeID == 0 {+ return nil, fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)+ }++ var result *string+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ // Step 1: Resolve backend node ID to a remote object+ var resolveResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{+ "backendNodeId": nodeID,+ }, &resolveResult); err != nil {+ return fmt.Errorf("resolve node: %w", err)+ }++ var resolved struct {+ Object struct {+ ObjectID string `json:"objectId"`+ } `json:"object"`+ }+ if err := json.Unmarshal(resolveResult, &resolved); err != nil {+ return fmt.Errorf("parse resolved node: %w", err)+ }+ if resolved.Object.ObjectID == "" {+ return fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)+ }++ // Step 2: Call getAttribute(name) on the element+ var callResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{+ "functionDeclaration": `function(n) { var v = this.getAttribute(n); return v !== null ? v : null; }`,+ "objectId": resolved.Object.ObjectID,+ "arguments": []map[string]any{{"value": name}},+ "returnByValue": true,+ }, &callResult); err != nil {+ return fmt.Errorf("get element attribute: %w", err)+ }++ var callParsed struct {+ Result struct {+ Type string `json:"type"`+ Value any `json:"value"`+ } `json:"result"`+ ExceptionDetails *struct {+ Text string `json:"text"`+ } `json:"exceptionDetails,omitempty"`+ }+ if err := json.Unmarshal(callResult, &callParsed); err != nil {+ return fmt.Errorf("parse attribute result: %w", err)+ }+ if callParsed.ExceptionDetails != nil && callParsed.ExceptionDetails.Text != "" {+ return fmt.Errorf("get element attribute: %s", callParsed.ExceptionDetails.Text)+ }++ // null means the attribute does not exist on the element+ if callParsed.Result.Value == nil {+ result = nil+ } else {+ s := fmt.Sprint(callParsed.Result.Value)+ result = &s+ }+ return nil+ }))+ if err != nil {+ return nil, err+ }+ return result, nil+}diff --git a/internal/handlers/attr_test.go b/internal/handlers/attr_test.gonew file mode 100644index 00000000..6ebd9b37--- /dev/null+++ b/internal/handlers/attr_test.go@@ -0,0 +1,129 @@+package handlers++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config"+)++func TestHandleGetAttr_MissingRef(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/attr?name=href", nil)+ w := httptest.NewRecorder()+ h.HandleGetAttr(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "ref") {+ t.Fatalf("expected error about ref, got %s", w.Body.String())+ }+}++func TestHandleGetAttr_MissingName(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/attr?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleGetAttr(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "name") {+ t.Fatalf("expected error about name, got %s", w.Body.String())+ }+}++func TestHandleGetAttr_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/attr?ref=e5&name=href", nil)+ w := httptest.NewRecorder()+ h.HandleGetAttr(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleGetAttr_NoSnapshotCache(t *testing.T) {+ mb := &attrMockBridge{refCache: nil}+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/attr?ref=e5&name=href", nil)+ w := httptest.NewRecorder()+ h.HandleGetAttr(w, req)+ if w.Code != http.StatusInternalServerError {+ t.Fatalf("expected 500, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "no snapshot cache") {+ t.Fatalf("expected snapshot cache error, got %s", w.Body.String())+ }+}++func TestHandleGetAttr_RefNotFound(t *testing.T) {+ mb := &attrMockBridge{+ refCache: &bridge.RefCache{+ Refs: map[string]int64{"e1": 100},+ Targets: map[string]bridge.RefTarget{"e1": {BackendNodeID: 100}},+ },+ }+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/attr?ref=e99&name=href", nil)+ w := httptest.NewRecorder()+ h.HandleGetAttr(w, req)+ if w.Code != http.StatusInternalServerError {+ t.Fatalf("expected 500, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "ref not found: e99") {+ t.Fatalf("expected ref not found error, got %s", w.Body.String())+ }+}++func TestHandleTabGetAttr_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs//attr?ref=e5&name=href", nil)+ w := httptest.NewRecorder()+ h.HandleTabGetAttr(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabGetAttr_ForwardsTabID(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs/tab_abc/attr?ref=e5&name=href", nil)+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabGetAttr(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestAttrRoutesRegistered(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)++ paths := []string{"/attr?ref=e1&name=href", "/tabs/tab1/attr?ref=e1&name=href"}+ for _, path := range paths {+ t.Run(path, func(t *testing.T) {+ req := httptest.NewRequest("GET", path, nil)+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)+ if w.Code == http.StatusNotFound && strings.Contains(w.Body.String(), "404 page not found") {+ t.Fatalf("route %s not registered", path)+ }+ })+ }+}++// attrMockBridge extends mockBridge with GetRefCache support.+type attrMockBridge struct {+ mockBridge+ refCache *bridge.RefCache+}++func (m *attrMockBridge) GetRefCache(tabID string) *bridge.RefCache {+ return m.refCache+}diff --git a/internal/handlers/box.go b/internal/handlers/box.gonew file mode 100644index 00000000..8ff0f476--- /dev/null+++ b/internal/handlers/box.go@@ -0,0 +1,165 @@+package handlers++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++type boundingBox struct {+ X float64 `json:"x"`+ Y float64 `json:"y"`+ Width float64 `json:"width"`+ Height float64 `json:"height"`+ Top float64 `json:"top"`+ Right float64 `json:"right"`+ Bottom float64 `json:"bottom"`+ Left float64 `json:"left"`+}++type boxResponse struct {+ Ref string `json:"ref"`+ Box boundingBox `json:"box"`+}++// HandleGetBox returns the bounding box of an element identified by ref.+//+// @Endpoint GET /box+func (h *Handlers) HandleGetBox(w http.ResponseWriter, r *http.Request) {+ tabID := r.URL.Query().Get("tabId")+ h.recordReadRequest(r, "inspect.box", tabID)++ ref := r.URL.Query().Get("ref")+ if ref == "" {+ httpx.Error(w, 400, fmt.Errorf("ref query parameter is required"))+ return+ }++ if err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))+ return+ }++ ctx, resolvedTabID, err := h.tabContextWithHeader(w, r, tabID)+ if err != nil {+ WriteTabContextError(w, err, 404)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }+ defer h.armAutoCloseIfEnabled(resolvedTabID)++ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)+ defer tCancel()+ go httpx.CancelOnClientDone(r.Context(), tCancel)++ box, err := h.getElementBox(tCtx, resolvedTabID, ref)+ if err != nil {+ httpx.Error(w, 500, err)+ return+ }++ httpx.JSON(w, 200, boxResponse{Ref: ref, Box: *box})+}++// HandleTabGetBox returns the bounding box for a tab identified by path ID.+//+// @Endpoint GET /tabs/{id}/box+func (h *Handlers) HandleTabGetBox(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ q := r.URL.Query()+ q.Set("tabId", tabID)++ req := r.Clone(r.Context())+ u := *r.URL+ u.RawQuery = q.Encode()+ req.URL = &u++ h.HandleGetBox(w, req)+}++// getElementBox resolves a ref to a DOM node and returns its bounding client rect.+func (h *Handlers) getElementBox(ctx context.Context, tabID, ref string) (*boundingBox, error) {+ cache := h.Bridge.GetRefCache(tabID)+ if cache == nil {+ return nil, fmt.Errorf("ref not found: %s (no snapshot cache — run /snapshot first)", ref)+ }+ target, ok := cache.Lookup(ref)+ if !ok {+ return nil, fmt.Errorf("ref not found: %s", ref)+ }++ nodeID := target.BackendNodeID+ if nodeID == 0 {+ return nil, fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)+ }++ var result boundingBox+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ // Step 1: Resolve backend node ID to a remote object+ var resolveResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{+ "backendNodeId": nodeID,+ }, &resolveResult); err != nil {+ return fmt.Errorf("resolve node: %w", err)+ }++ var resolved struct {+ Object struct {+ ObjectID string `json:"objectId"`+ } `json:"object"`+ }+ if err := json.Unmarshal(resolveResult, &resolved); err != nil {+ return fmt.Errorf("parse resolved node: %w", err)+ }+ if resolved.Object.ObjectID == "" {+ return fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)+ }++ // Step 2: Call getBoundingClientRect() and extract into a plain object+ var callResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{+ "functionDeclaration": `function() { var r = this.getBoundingClientRect(); return {x: r.x, y: r.y, width: r.width, height: r.height, top: r.top, right: r.right, bottom: r.bottom, left: r.left}; }`,+ "objectId": resolved.Object.ObjectID,+ "returnByValue": true,+ }, &callResult); err != nil {+ return fmt.Errorf("get bounding box: %w", err)+ }++ var callParsed struct {+ Result struct {+ Type string `json:"type"`+ Value boundingBox `json:"value"`+ } `json:"result"`+ ExceptionDetails *struct {+ Text string `json:"text"`+ } `json:"exceptionDetails,omitempty"`+ }+ if err := json.Unmarshal(callResult, &callParsed); err != nil {+ return fmt.Errorf("parse box result: %w", err)+ }+ if callParsed.ExceptionDetails != nil && callParsed.ExceptionDetails.Text != "" {+ return fmt.Errorf("get bounding box: %s", callParsed.ExceptionDetails.Text)+ }++ result = callParsed.Result.Value+ return nil+ }))+ if err != nil {+ return nil, err+ }+ return &result, nil+}diff --git a/internal/handlers/box_test.go b/internal/handlers/box_test.gonew file mode 100644index 00000000..51f184a9--- /dev/null+++ b/internal/handlers/box_test.go@@ -0,0 +1,116 @@+package handlers++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config"+)++func TestHandleGetBox_MissingRef(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/box", nil)+ w := httptest.NewRecorder()+ h.HandleGetBox(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "ref") {+ t.Fatalf("expected error about ref, got %s", w.Body.String())+ }+}++func TestHandleGetBox_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/box?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleGetBox(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleGetBox_NoSnapshotCache(t *testing.T) {+ mb := &boxMockBridge{refCache: nil}+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/box?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleGetBox(w, req)+ if w.Code != http.StatusInternalServerError {+ t.Fatalf("expected 500, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "no snapshot cache") {+ t.Fatalf("expected snapshot cache error, got %s", w.Body.String())+ }+}++func TestHandleGetBox_RefNotFound(t *testing.T) {+ mb := &boxMockBridge{+ refCache: &bridge.RefCache{+ Refs: map[string]int64{"e1": 100},+ Targets: map[string]bridge.RefTarget{"e1": {BackendNodeID: 100}},+ },+ }+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/box?ref=e99", nil)+ w := httptest.NewRecorder()+ h.HandleGetBox(w, req)+ if w.Code != http.StatusInternalServerError {+ t.Fatalf("expected 500, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "ref not found: e99") {+ t.Fatalf("expected ref not found error, got %s", w.Body.String())+ }+}++func TestHandleTabGetBox_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs//box?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleTabGetBox(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabGetBox_ForwardsTabID(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs/tab_abc/box?ref=e5", nil)+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabGetBox(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestBoxRoutesRegistered(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)++ paths := []string{"/box?ref=e1", "/tabs/tab1/box?ref=e1"}+ for _, path := range paths {+ t.Run(path, func(t *testing.T) {+ req := httptest.NewRequest("GET", path, nil)+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)+ if w.Code == http.StatusNotFound && strings.Contains(w.Body.String(), "404 page not found") {+ t.Fatalf("route %s not registered", path)+ }+ })+ }+}++// boxMockBridge extends mockBridge with GetRefCache support.+type boxMockBridge struct {+ mockBridge+ refCache *bridge.RefCache+}++func (m *boxMockBridge) GetRefCache(tabID string) *bridge.RefCache {+ return m.refCache+}diff --git a/internal/handlers/checked.go b/internal/handlers/checked.gonew file mode 100644index 00000000..6489dc03--- /dev/null+++ b/internal/handlers/checked.go@@ -0,0 +1,156 @@+package handlers++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++type checkedResponse struct {+ Ref string `json:"ref"`+ Checked bool `json:"checked"`+}++// HandleGetChecked returns whether an element identified by ref is checked.+//+// @Endpoint GET /checked+func (h *Handlers) HandleGetChecked(w http.ResponseWriter, r *http.Request) {+ tabID := r.URL.Query().Get("tabId")+ h.recordReadRequest(r, "inspect.checked", tabID)++ ref := r.URL.Query().Get("ref")+ if ref == "" {+ httpx.Error(w, 400, fmt.Errorf("ref query parameter is required"))+ return+ }++ if err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))+ return+ }++ ctx, resolvedTabID, err := h.tabContextWithHeader(w, r, tabID)+ if err != nil {+ WriteTabContextError(w, err, 404)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }+ defer h.armAutoCloseIfEnabled(resolvedTabID)++ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)+ defer tCancel()+ go httpx.CancelOnClientDone(r.Context(), tCancel)++ checked, err := h.getElementChecked(tCtx, resolvedTabID, ref)+ if err != nil {+ httpx.Error(w, 500, err)+ return+ }++ httpx.JSON(w, 200, checkedResponse{Ref: ref, Checked: checked})+}++// HandleTabGetChecked returns checked state for a tab identified by path ID.+//+// @Endpoint GET /tabs/{id}/checked+func (h *Handlers) HandleTabGetChecked(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ q := r.URL.Query()+ q.Set("tabId", tabID)++ req := r.Clone(r.Context())+ u := *r.URL+ u.RawQuery = q.Encode()+ req.URL = &u++ h.HandleGetChecked(w, req)+}++// getElementChecked resolves a ref to a DOM node and checks whether it is checked.+func (h *Handlers) getElementChecked(ctx context.Context, tabID, ref string) (bool, error) {+ cache := h.Bridge.GetRefCache(tabID)+ if cache == nil {+ return false, fmt.Errorf("ref not found: %s (no snapshot cache — run /snapshot first)", ref)+ }+ target, ok := cache.Lookup(ref)+ if !ok {+ return false, fmt.Errorf("ref not found: %s", ref)+ }++ nodeID := target.BackendNodeID+ if nodeID == 0 {+ return false, fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)+ }++ var checked bool+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ // Step 1: Resolve backend node ID to a remote object+ var resolveResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{+ "backendNodeId": nodeID,+ }, &resolveResult); err != nil {+ return fmt.Errorf("resolve node: %w", err)+ }++ var resolved struct {+ Object struct {+ ObjectID string `json:"objectId"`+ } `json:"object"`+ }+ if err := json.Unmarshal(resolveResult, &resolved); err != nil {+ return fmt.Errorf("parse resolved node: %w", err)+ }+ if resolved.Object.ObjectID == "" {+ return fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)+ }++ // Step 2: Evaluate checked check on the element+ var callResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{+ "functionDeclaration": `function() { return !!this.checked; }`,+ "objectId": resolved.Object.ObjectID,+ "returnByValue": true,+ }, &callResult); err != nil {+ return fmt.Errorf("check element checked state: %w", err)+ }++ var callParsed struct {+ Result struct {+ Type string `json:"type"`+ Value any `json:"value"`+ } `json:"result"`+ ExceptionDetails *struct {+ Text string `json:"text"`+ } `json:"exceptionDetails,omitempty"`+ }+ if err := json.Unmarshal(callResult, &callParsed); err != nil {+ return fmt.Errorf("parse checked result: %w", err)+ }+ if callParsed.ExceptionDetails != nil && callParsed.ExceptionDetails.Text != "" {+ return fmt.Errorf("check element checked state: %s", callParsed.ExceptionDetails.Text)+ }++ if b, ok := callParsed.Result.Value.(bool); ok {+ checked = b+ }+ return nil+ }))+ if err != nil {+ return false, err+ }+ return checked, nil+}diff --git a/internal/handlers/checked_test.go b/internal/handlers/checked_test.gonew file mode 100644index 00000000..69ded8e9--- /dev/null+++ b/internal/handlers/checked_test.go@@ -0,0 +1,116 @@+package handlers++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config"+)++func TestHandleGetChecked_MissingRef(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/checked", nil)+ w := httptest.NewRecorder()+ h.HandleGetChecked(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "ref") {+ t.Fatalf("expected error about ref, got %s", w.Body.String())+ }+}++func TestHandleGetChecked_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/checked?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleGetChecked(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleGetChecked_NoSnapshotCache(t *testing.T) {+ mb := &checkedMockBridge{refCache: nil}+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/checked?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleGetChecked(w, req)+ if w.Code != http.StatusInternalServerError {+ t.Fatalf("expected 500, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "no snapshot cache") {+ t.Fatalf("expected snapshot cache error, got %s", w.Body.String())+ }+}++func TestHandleGetChecked_RefNotFound(t *testing.T) {+ mb := &checkedMockBridge{+ refCache: &bridge.RefCache{+ Refs: map[string]int64{"e1": 100},+ Targets: map[string]bridge.RefTarget{"e1": {BackendNodeID: 100}},+ },+ }+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/checked?ref=e99", nil)+ w := httptest.NewRecorder()+ h.HandleGetChecked(w, req)+ if w.Code != http.StatusInternalServerError {+ t.Fatalf("expected 500, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "ref not found: e99") {+ t.Fatalf("expected ref not found error, got %s", w.Body.String())+ }+}++func TestHandleTabGetChecked_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs//checked?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleTabGetChecked(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabGetChecked_ForwardsTabID(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs/tab_abc/checked?ref=e5", nil)+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabGetChecked(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestCheckedRoutesRegistered(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)++ paths := []string{"/checked?ref=e1", "/tabs/tab1/checked?ref=e1"}+ for _, path := range paths {+ t.Run(path, func(t *testing.T) {+ req := httptest.NewRequest("GET", path, nil)+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)+ if w.Code == http.StatusNotFound && strings.Contains(w.Body.String(), "404 page not found") {+ t.Fatalf("route %s not registered", path)+ }+ })+ }+}++// checkedMockBridge extends mockBridge with GetRefCache support.+type checkedMockBridge struct {+ mockBridge+ refCache *bridge.RefCache+}++func (m *checkedMockBridge) GetRefCache(tabID string) *bridge.RefCache {+ return m.refCache+}diff --git a/internal/handlers/cookies.go b/internal/handlers/cookies.goindex dd0ef48b..4dd3030e 100644--- a/internal/handlers/cookies.go+++ b/internal/handlers/cookies.go@@ -128,6 +128,48 @@ type cookieSetRequest struct {Expires float64 `json:"expires"`}+// HandleClearCookies clears all browser cookies.+//+// @Endpoint DELETE /cookies+func (h *Handlers) HandleClearCookies(w http.ResponseWriter, r *http.Request) {+ if err := h.ensureChrome(); err != nil {+ httpx.Error(w, http.StatusServiceUnavailable, err)+ return+ }++ ctx := h.Bridge.BrowserContext()+ if err := h.Bridge.ClearCookies(ctx); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }+ httpx.Error(w, http.StatusInternalServerError, fmt.Errorf("clear cookies: %w", err))+ return+ }++ h.recordActivity(r, activity.Update{Action: "cookies.clear"})++ httpx.JSON(w, http.StatusOK, map[string]any{"status": "cleared"})+}++// HandleTabClearCookies clears all browser cookies (tab-scoped variant for API consistency).+//+// @Endpoint DELETE /tabs/{id}/cookies+func (h *Handlers) HandleTabClearCookies(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ // Verify tab exists before clearing.+ if _, _, err := h.tabContext(r, tabID); err != nil {+ WriteTabContextError(w, err, 404)+ return+ }++ h.HandleClearCookies(w, r)+}+func (h *Handlers) HandleSetCookies(w http.ResponseWriter, r *http.Request) {var req cookieRequestif err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {diff --git a/internal/handlers/cookies_test.go b/internal/handlers/cookies_test.goindex 6c6a10f3..815f7b00 100644--- a/internal/handlers/cookies_test.go+++ b/internal/handlers/cookies_test.go@@ -2,7 +2,9 @@ package handlersimport ("bytes"+ "context""encoding/json"+ "net/http""net/http/httptest""testing"@@ -97,3 +99,120 @@ func TestHandleTabSetCookies_NoTab(t *testing.T) {t.Errorf("expected 404, got %d", w.Code)}}++// cookieClearMockBridge provides BrowserContext and ClearCookies for handler tests.+type cookieClearMockBridge struct {+ mockBridge+ clearCookiesCalled bool+ clearCookiesErr error+}++func (m *cookieClearMockBridge) BrowserContext() context.Context {+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ return ctx+}++func (m *cookieClearMockBridge) ClearCookies(ctx context.Context) error {+ m.clearCookiesCalled = true+ return m.clearCookiesErr+}++func TestHandleClearCookies_Success(t *testing.T) {+ b := &cookieClearMockBridge{}+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)++ req := httptest.NewRequest("DELETE", "/cookies", nil)+ w := httptest.NewRecorder()+ h.HandleClearCookies(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if !b.clearCookiesCalled {+ t.Fatal("expected ClearCookies to be called")+ }++ var resp map[string]any+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["status"] != "cleared" {+ t.Errorf("expected status=cleared, got %v", resp["status"])+ }+}++func TestHandleTabClearCookies_Success(t *testing.T) {+ b := &cookieClearMockBridge{}+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)++ req := httptest.NewRequest("DELETE", "/tabs/tab1/cookies", nil)+ req.SetPathValue("id", "tab1")+ w := httptest.NewRecorder()+ h.HandleTabClearCookies(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if !b.clearCookiesCalled {+ t.Fatal("expected ClearCookies to be called")+ }++ var resp map[string]any+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["status"] != "cleared" {+ t.Errorf("expected status=cleared, got %v", resp["status"])+ }+}++func TestHandleTabClearCookies_MissingTabID(t *testing.T) {+ h := New(&cookieClearMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ req := httptest.NewRequest("DELETE", "/tabs//cookies", nil)+ w := httptest.NewRecorder()+ h.HandleTabClearCookies(w, req)++ if w.Code != http.StatusBadRequest {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabClearCookies_NoTab(t *testing.T) {+ b := &cookieClearMockBridge{}+ b.failTab = true+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)++ req := httptest.NewRequest("DELETE", "/tabs/nonexistent/cookies", nil)+ req.SetPathValue("id", "nonexistent")+ w := httptest.NewRecorder()+ h.HandleTabClearCookies(w, req)++ if w.Code != http.StatusNotFound {+ t.Errorf("expected 404, got %d", w.Code)+ }+}++func TestHandleClearCookies_RouteRegistration(t *testing.T) {+ b := &cookieClearMockBridge{}+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)++ req := httptest.NewRequest("DELETE", "/cookies", nil)+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected DELETE /cookies to be registered, got %d: %s", w.Code, w.Body.String())+ }++ req = httptest.NewRequest("DELETE", "/tabs/tab1/cookies", nil)+ w = httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected DELETE /tabs/{id}/cookies to be registered, got %d: %s", w.Code, w.Body.String())+ }+}diff --git a/internal/handlers/count.go b/internal/handlers/count.gonew file mode 100644index 00000000..47531129--- /dev/null+++ b/internal/handlers/count.go@@ -0,0 +1,95 @@+package handlers++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"++ "github.com/pinchtab/pinchtab/internal/httpx"+)++type countResponse struct {+ Selector string `json:"selector"`+ Count int `json:"count"`+}++// HandleCount returns the number of elements matching a CSS selector.+//+// @Endpoint GET /count+func (h *Handlers) HandleCount(w http.ResponseWriter, r *http.Request) {+ tabID := r.URL.Query().Get("tabId")+ h.recordReadRequest(r, "inspect.count", tabID)++ selector := r.URL.Query().Get("selector")+ if selector == "" {+ httpx.Error(w, 400, fmt.Errorf("selector query parameter is required"))+ return+ }++ if err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))+ return+ }++ ctx, resolvedTabID, err := h.tabContextWithHeader(w, r, tabID)+ if err != nil {+ WriteTabContextError(w, err, 404)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }+ defer h.armAutoCloseIfEnabled(resolvedTabID)++ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)+ defer tCancel()+ go httpx.CancelOnClientDone(r.Context(), tCancel)++ count, err := h.countElements(tCtx, selector)+ if err != nil {+ httpx.Error(w, 500, fmt.Errorf("count elements: %w", err))+ return+ }++ httpx.JSON(w, 200, countResponse{Selector: selector, Count: count})+}++// HandleTabCount returns the element count for a tab identified by path ID.+//+// @Endpoint GET /tabs/{id}/count+func (h *Handlers) HandleTabCount(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ q := r.URL.Query()+ q.Set("tabId", tabID)++ req := r.Clone(r.Context())+ u := *r.URL+ u.RawQuery = q.Encode()+ req.URL = &u++ h.HandleCount(w, req)+}++// countElements evaluates document.querySelectorAll(selector).length in the page.+func (h *Handlers) countElements(ctx context.Context, selector string) (int, error) {+ selectorJSON, err := json.Marshal(selector)+ if err != nil {+ return 0, fmt.Errorf("encode selector: %w", err)+ }+ expr := fmt.Sprintf("document.querySelectorAll(%s).length", string(selectorJSON))++ var count int+ if err := h.evalRuntime(ctx, expr, &count); err != nil {+ return 0, err+ }+ return count, nil+}diff --git a/internal/handlers/count_test.go b/internal/handlers/count_test.gonew file mode 100644index 00000000..7ef839c7--- /dev/null+++ b/internal/handlers/count_test.go@@ -0,0 +1,107 @@+package handlers++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/config"+)++func TestHandleCount_MissingSelector(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/count", nil)+ w := httptest.NewRecorder()+ h.HandleCount(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "selector") {+ t.Fatalf("expected error about selector, got %s", w.Body.String())+ }+}++func TestHandleCount_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/count?selector=button", nil)+ w := httptest.NewRecorder()+ h.HandleCount(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleCount_ValidCount(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ h.evalRuntime = func(ctx context.Context, expression string, out any, opts ...chromedp.EvaluateOption) error {+ // Verify the expression is safely constructed+ if !strings.Contains(expression, "document.querySelectorAll") {+ t.Fatalf("expected querySelectorAll expression, got %s", expression)+ }+ if ptr, ok := out.(*int); ok {+ *ptr = 5+ }+ return nil+ }++ req := httptest.NewRequest("GET", "/count?selector=button.submit", nil)+ w := httptest.NewRecorder()+ h.HandleCount(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var resp countResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if resp.Selector != "button.submit" {+ t.Fatalf("expected selector button.submit, got %s", resp.Selector)+ }+ if resp.Count != 5 {+ t.Fatalf("expected count 5, got %d", resp.Count)+ }+}++func TestHandleTabCount_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs//count?selector=button", nil)+ w := httptest.NewRecorder()+ h.HandleTabCount(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabCount_ForwardsTabID(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs/tab_abc/count?selector=button", nil)+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabCount(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestCountRoutesRegistered(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)++ paths := []string{"/count?selector=button", "/tabs/tab1/count?selector=button"}+ for _, path := range paths {+ t.Run(path, func(t *testing.T) {+ req := httptest.NewRequest("GET", path, nil)+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)+ if w.Code == http.StatusNotFound && strings.Contains(w.Body.String(), "404 page not found") {+ t.Fatalf("route %s not registered", path)+ }+ })+ }+}diff --git a/internal/handlers/credentials.go b/internal/handlers/credentials.gonew file mode 100644index 00000000..f7d824e3--- /dev/null+++ b/internal/handlers/credentials.go@@ -0,0 +1,189 @@+package handlers++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "sync"+ "time"++ "github.com/chromedp/cdproto/fetch"+ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++// credentialPair holds HTTP basic auth credentials for a tab.+type credentialPair struct {+ Username string+ Password string+}++// credentialStore provides thread-safe per-tab credential storage.+type credentialStore struct {+ mu sync.RWMutex+ credentials map[string]*credentialPair+}++func newCredentialStore() *credentialStore {+ return &credentialStore{+ credentials: make(map[string]*credentialPair),+ }+}++func (cs *credentialStore) Set(tabID string, cred *credentialPair) {+ cs.mu.Lock()+ defer cs.mu.Unlock()+ cs.credentials[tabID] = cred+}++func (cs *credentialStore) Get(tabID string) (*credentialPair, bool) {+ cs.mu.RLock()+ defer cs.mu.RUnlock()+ cred, ok := cs.credentials[tabID]+ return cred, ok+}++func (cs *credentialStore) Delete(tabID string) {+ cs.mu.Lock()+ defer cs.mu.Unlock()+ delete(cs.credentials, tabID)+}++type credentialsRequest struct {+ TabID string `json:"tabId"`+ Username *string `json:"username"`+ Password string `json:"password"`+}++// HandleSetCredentials sets HTTP auth credentials via CDP Fetch domain.+// POST /emulation/credentials+func (h *Handlers) HandleSetCredentials(w http.ResponseWriter, r *http.Request) {+ var req credentialsRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ h.setCredentials(w, r, req)+}++// HandleTabSetCredentials sets HTTP auth credentials for a specific tab.+// POST /tabs/{id}/emulation/credentials+func (h *Handlers) HandleTabSetCredentials(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("missing tab ID"))+ return+ }++ var req credentialsRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ if req.TabID != "" && req.TabID != tabID {+ httpx.Error(w, 400, fmt.Errorf("tabId in body %q does not match URL path %q", req.TabID, tabID))+ return+ }+ req.TabID = tabID++ h.setCredentials(w, r, req)+}++func (h *Handlers) setCredentials(w http.ResponseWriter, r *http.Request, req credentialsRequest) {+ if req.Username == nil {+ httpx.Error(w, 400, fmt.Errorf("missing required field: username"))+ return+ }++ username := *req.Username++ // Non-empty username requires password field (empty password is allowed).+ // Empty username means "clear credentials".++ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)+ if err != nil {+ WriteTabContextError(w, err, 404)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, 5*time.Second)+ defer tCancel()++ if username == "" {+ // Clear credentials: disable fetch domain and remove stored credentials.+ h.credentialStore.Delete(resolvedTabID)++ if err := chromedp.Run(tCtx,+ chromedp.ActionFunc(func(ctx context.Context) error {+ return fetch.Disable().Do(ctx)+ }),+ ); err != nil {+ httpx.Error(w, 500, fmt.Errorf("CDP fetch disable: %w", err))+ return+ }++ h.recordActivity(r, activity.Update{Action: "emulation.credentials", TabID: resolvedTabID})++ httpx.JSON(w, 200, map[string]any{+ "status": "cleared",+ })+ return+ }++ // Store credentials for the event listener to reference.+ h.credentialStore.Set(resolvedTabID, &credentialPair{+ Username: username,+ Password: req.Password,+ })++ // Enable Fetch domain with auth request interception.+ if err := chromedp.Run(tCtx,+ chromedp.ActionFunc(func(ctx context.Context) error {+ return fetch.Enable().WithHandleAuthRequests(true).Do(ctx)+ }),+ ); err != nil {+ httpx.Error(w, 500, fmt.Errorf("CDP fetch enable: %w", err))+ return+ }++ // Install event listener for auth challenges and paused requests.+ // Use the non-timeout tab context so the listener persists beyond this request.+ chromedp.ListenTarget(ctx, func(ev interface{}) {+ switch e := ev.(type) {+ case *fetch.EventAuthRequired:+ go func() {+ cred, ok := h.credentialStore.Get(resolvedTabID)+ if !ok {+ return+ }+ _ = chromedp.Run(ctx, chromedp.ActionFunc(func(innerCtx context.Context) error {+ return fetch.ContinueWithAuth(e.RequestID, &fetch.AuthChallengeResponse{+ Response: fetch.AuthChallengeResponseResponseProvideCredentials,+ Username: cred.Username,+ Password: cred.Password,+ }).Do(innerCtx)+ }))+ }()+ case *fetch.EventRequestPaused:+ go func() {+ _ = chromedp.Run(ctx, chromedp.ActionFunc(func(innerCtx context.Context) error {+ return fetch.ContinueRequest(e.RequestID).Do(innerCtx)+ }))+ }()+ }+ })++ h.recordActivity(r, activity.Update{Action: "emulation.credentials", TabID: resolvedTabID})++ httpx.JSON(w, 200, map[string]any{+ "username": username,+ "status": "applied",+ })+}diff --git a/internal/handlers/credentials_test.go b/internal/handlers/credentials_test.gonew file mode 100644index 00000000..b3aa620d--- /dev/null+++ b/internal/handlers/credentials_test.go@@ -0,0 +1,130 @@+package handlers++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++func TestHandleSetCredentials_Valid(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"username":"admin","password":"secret"}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/credentials", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetCredentials(w, req)++ // The mock bridge returns a cancelled context, so chromedp.Run will fail+ // with a context error. We accept 200 or 500 (CDP failure on mock).+ if w.Code != 200 && w.Code != 500 {+ t.Fatalf("expected 200 or 500, got %d: %s", w.Code, w.Body.String())+ }++ if w.Code == 200 {+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["status"] != "applied" {+ t.Fatalf("expected status=applied, got %v", resp["status"])+ }+ if resp["username"] != "admin" {+ t.Fatalf("expected username=admin, got %v", resp["username"])+ }+ }+}++func TestHandleSetCredentials_ClearCredentials(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"username":""}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/credentials", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetCredentials(w, req)++ // Accept 200 (cleared) or 500 (CDP failure on mock context).+ if w.Code != 200 && w.Code != 500 {+ t.Fatalf("expected 200 or 500, got %d: %s", w.Code, w.Body.String())+ }++ if w.Code == 200 {+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["status"] != "cleared" {+ t.Fatalf("expected status=cleared, got %v", resp["status"])+ }+ }+}++func TestHandleSetCredentials_InvalidJSON(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ req := httptest.NewRequest(http.MethodPost, "/emulation/credentials", bytes.NewReader([]byte(`not json`)))+ w := httptest.NewRecorder()+ h.HandleSetCredentials(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for invalid JSON, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetCredentials_MissingUsername(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"password":"secret"}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/credentials", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetCredentials(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for missing username, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabSetCredentials_TabIDMismatch(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"username":"admin","password":"secret","tabId":"tab_other"}`+ req := httptest.NewRequest(http.MethodPost, "/tabs/tab_abc/emulation/credentials", bytes.NewReader([]byte(body)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabSetCredentials(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for tab ID mismatch, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabSetCredentials_NoTab(t *testing.T) {+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"username":"admin","password":"secret"}`+ req := httptest.NewRequest(http.MethodPost, "/tabs/tab_abc/emulation/credentials", bytes.NewReader([]byte(body)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabSetCredentials(w, req)++ if w.Code != 404 {+ t.Fatalf("expected 404 for nonexistent tab, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetCredentials_EmptyPassword(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"username":"admin","password":""}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/credentials", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetCredentials(w, req)++ // Empty password is valid — some auth schemes allow it.+ if w.Code != 200 && w.Code != 500 {+ t.Fatalf("expected 200 or 500, got %d: %s", w.Code, w.Body.String())+ }+}diff --git a/internal/handlers/enabled.go b/internal/handlers/enabled.gonew file mode 100644index 00000000..c8dcadb0--- /dev/null+++ b/internal/handlers/enabled.go@@ -0,0 +1,156 @@+package handlers++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++type enabledResponse struct {+ Ref string `json:"ref"`+ Enabled bool `json:"enabled"`+}++// HandleGetEnabled returns whether an element identified by ref is enabled (not disabled).+//+// @Endpoint GET /enabled+func (h *Handlers) HandleGetEnabled(w http.ResponseWriter, r *http.Request) {+ tabID := r.URL.Query().Get("tabId")+ h.recordReadRequest(r, "inspect.enabled", tabID)++ ref := r.URL.Query().Get("ref")+ if ref == "" {+ httpx.Error(w, 400, fmt.Errorf("ref query parameter is required"))+ return+ }++ if err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))+ return+ }++ ctx, resolvedTabID, err := h.tabContextWithHeader(w, r, tabID)+ if err != nil {+ WriteTabContextError(w, err, 404)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }+ defer h.armAutoCloseIfEnabled(resolvedTabID)++ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)+ defer tCancel()+ go httpx.CancelOnClientDone(r.Context(), tCancel)++ enabled, err := h.getElementEnabled(tCtx, resolvedTabID, ref)+ if err != nil {+ httpx.Error(w, 500, err)+ return+ }++ httpx.JSON(w, 200, enabledResponse{Ref: ref, Enabled: enabled})+}++// HandleTabGetEnabled returns enabled state for a tab identified by path ID.+//+// @Endpoint GET /tabs/{id}/enabled+func (h *Handlers) HandleTabGetEnabled(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ q := r.URL.Query()+ q.Set("tabId", tabID)++ req := r.Clone(r.Context())+ u := *r.URL+ u.RawQuery = q.Encode()+ req.URL = &u++ h.HandleGetEnabled(w, req)+}++// getElementEnabled resolves a ref to a DOM node and checks whether it is enabled.+func (h *Handlers) getElementEnabled(ctx context.Context, tabID, ref string) (bool, error) {+ cache := h.Bridge.GetRefCache(tabID)+ if cache == nil {+ return false, fmt.Errorf("ref not found: %s (no snapshot cache — run /snapshot first)", ref)+ }+ target, ok := cache.Lookup(ref)+ if !ok {+ return false, fmt.Errorf("ref not found: %s", ref)+ }++ nodeID := target.BackendNodeID+ if nodeID == 0 {+ return false, fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)+ }++ var enabled bool+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ // Step 1: Resolve backend node ID to a remote object+ var resolveResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{+ "backendNodeId": nodeID,+ }, &resolveResult); err != nil {+ return fmt.Errorf("resolve node: %w", err)+ }++ var resolved struct {+ Object struct {+ ObjectID string `json:"objectId"`+ } `json:"object"`+ }+ if err := json.Unmarshal(resolveResult, &resolved); err != nil {+ return fmt.Errorf("parse resolved node: %w", err)+ }+ if resolved.Object.ObjectID == "" {+ return fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)+ }++ // Step 2: Evaluate enabled check on the element+ var callResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{+ "functionDeclaration": `function() { return !this.disabled; }`,+ "objectId": resolved.Object.ObjectID,+ "returnByValue": true,+ }, &callResult); err != nil {+ return fmt.Errorf("check element enabled state: %w", err)+ }++ var callParsed struct {+ Result struct {+ Type string `json:"type"`+ Value any `json:"value"`+ } `json:"result"`+ ExceptionDetails *struct {+ Text string `json:"text"`+ } `json:"exceptionDetails,omitempty"`+ }+ if err := json.Unmarshal(callResult, &callParsed); err != nil {+ return fmt.Errorf("parse enabled result: %w", err)+ }+ if callParsed.ExceptionDetails != nil && callParsed.ExceptionDetails.Text != "" {+ return fmt.Errorf("check element enabled state: %s", callParsed.ExceptionDetails.Text)+ }++ if b, ok := callParsed.Result.Value.(bool); ok {+ enabled = b+ }+ return nil+ }))+ if err != nil {+ return false, err+ }+ return enabled, nil+}diff --git a/internal/handlers/enabled_test.go b/internal/handlers/enabled_test.gonew file mode 100644index 00000000..d2766b1e--- /dev/null+++ b/internal/handlers/enabled_test.go@@ -0,0 +1,116 @@+package handlers++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config"+)++func TestHandleGetEnabled_MissingRef(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/enabled", nil)+ w := httptest.NewRecorder()+ h.HandleGetEnabled(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "ref") {+ t.Fatalf("expected error about ref, got %s", w.Body.String())+ }+}++func TestHandleGetEnabled_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/enabled?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleGetEnabled(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleGetEnabled_NoSnapshotCache(t *testing.T) {+ mb := &enabledMockBridge{refCache: nil}+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/enabled?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleGetEnabled(w, req)+ if w.Code != http.StatusInternalServerError {+ t.Fatalf("expected 500, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "no snapshot cache") {+ t.Fatalf("expected snapshot cache error, got %s", w.Body.String())+ }+}++func TestHandleGetEnabled_RefNotFound(t *testing.T) {+ mb := &enabledMockBridge{+ refCache: &bridge.RefCache{+ Refs: map[string]int64{"e1": 100},+ Targets: map[string]bridge.RefTarget{"e1": {BackendNodeID: 100}},+ },+ }+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/enabled?ref=e99", nil)+ w := httptest.NewRecorder()+ h.HandleGetEnabled(w, req)+ if w.Code != http.StatusInternalServerError {+ t.Fatalf("expected 500, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "ref not found: e99") {+ t.Fatalf("expected ref not found error, got %s", w.Body.String())+ }+}++func TestHandleTabGetEnabled_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs//enabled?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleTabGetEnabled(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabGetEnabled_ForwardsTabID(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs/tab_abc/enabled?ref=e5", nil)+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabGetEnabled(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestEnabledRoutesRegistered(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)++ paths := []string{"/enabled?ref=e1", "/tabs/tab1/enabled?ref=e1"}+ for _, path := range paths {+ t.Run(path, func(t *testing.T) {+ req := httptest.NewRequest("GET", path, nil)+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)+ if w.Code == http.StatusNotFound && strings.Contains(w.Body.String(), "404 page not found") {+ t.Fatalf("route %s not registered", path)+ }+ })+ }+}++// enabledMockBridge extends mockBridge with GetRefCache support.+type enabledMockBridge struct {+ mockBridge+ refCache *bridge.RefCache+}++func (m *enabledMockBridge) GetRefCache(tabID string) *bridge.RefCache {+ return m.refCache+}diff --git a/internal/handlers/geolocation.go b/internal/handlers/geolocation.gonew file mode 100644index 00000000..0cac29f4--- /dev/null+++ b/internal/handlers/geolocation.go@@ -0,0 +1,115 @@+package handlers++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "time"++ "github.com/chromedp/cdproto/emulation"+ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++type geolocationRequest struct {+ TabID string `json:"tabId"`+ Latitude float64 `json:"latitude"`+ Longitude float64 `json:"longitude"`+ Accuracy float64 `json:"accuracy"`+}++// HandleSetGeolocation sets the browser geolocation via CDP emulation.+// POST /emulation/geolocation+func (h *Handlers) HandleSetGeolocation(w http.ResponseWriter, r *http.Request) {+ var req geolocationRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ h.setGeolocation(w, r, req)+}++// HandleTabSetGeolocation sets the browser geolocation for a specific tab.+// POST /tabs/{id}/emulation/geolocation+func (h *Handlers) HandleTabSetGeolocation(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("missing tab ID"))+ return+ }++ var req geolocationRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ if req.TabID != "" && req.TabID != tabID {+ httpx.Error(w, 400, fmt.Errorf("tabId in body %q does not match URL path %q", req.TabID, tabID))+ return+ }+ req.TabID = tabID++ h.setGeolocation(w, r, req)+}++func (h *Handlers) setGeolocation(w http.ResponseWriter, r *http.Request, req geolocationRequest) {+ if req.Latitude < -90 || req.Latitude > 90 {+ httpx.Error(w, 400, fmt.Errorf("latitude must be between -90 and 90"))+ return+ }++ if req.Longitude < -180 || req.Longitude > 180 {+ httpx.Error(w, 400, fmt.Errorf("longitude must be between -180 and 180"))+ return+ }++ if req.Accuracy < 0 {+ httpx.Error(w, 400, fmt.Errorf("accuracy must be >= 0"))+ return+ }++ if req.Accuracy == 0 {+ req.Accuracy = 1.0+ }++ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)+ if err != nil {+ WriteTabContextError(w, err, 404)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, 5*time.Second)+ defer tCancel()++ if err := chromedp.Run(tCtx,+ chromedp.ActionFunc(func(ctx context.Context) error {+ if err := emulation.SetGeolocationOverride().+ WithLatitude(req.Latitude).+ WithLongitude(req.Longitude).+ WithAccuracy(req.Accuracy).+ Do(ctx); err != nil {+ return fmt.Errorf("setGeolocationOverride: %w", err)+ }+ return nil+ }),+ ); err != nil {+ httpx.Error(w, 500, fmt.Errorf("CDP geolocation override: %w", err))+ return+ }++ h.recordActivity(r, activity.Update{Action: "emulation.geolocation", TabID: resolvedTabID})++ httpx.JSON(w, 200, map[string]any{+ "latitude": req.Latitude,+ "longitude": req.Longitude,+ "accuracy": req.Accuracy,+ "status": "applied",+ })+}diff --git a/internal/handlers/geolocation_test.go b/internal/handlers/geolocation_test.gonew file mode 100644index 00000000..e4839f4f--- /dev/null+++ b/internal/handlers/geolocation_test.go@@ -0,0 +1,184 @@+package handlers++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++func TestHandleSetGeolocation_ValidCoords(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"latitude":37.7749,"longitude":-122.4194}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/geolocation", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetGeolocation(w, req)++ // The mock bridge returns a cancelled context, so chromedp.Run will fail+ // with a context error. We accept 200 or 500 (CDP failure on mock).+ if w.Code != 200 && w.Code != 500 {+ t.Fatalf("expected 200 or 500, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetGeolocation_LatitudeTooHigh(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"latitude":91,"longitude":0}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/geolocation", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetGeolocation(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for latitude > 90, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetGeolocation_LatitudeTooLow(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"latitude":-91,"longitude":0}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/geolocation", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetGeolocation(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for latitude < -90, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetGeolocation_LongitudeTooHigh(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"latitude":0,"longitude":181}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/geolocation", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetGeolocation(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for longitude > 180, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetGeolocation_LongitudeTooLow(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"latitude":0,"longitude":-181}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/geolocation", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetGeolocation(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for longitude < -180, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetGeolocation_DefaultAccuracy(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"latitude":37.7749,"longitude":-122.4194}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/geolocation", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetGeolocation(w, req)++ // Even if chromedp fails (mock context), verify the response contains+ // default accuracy when the request succeeds (200) or the validation passed.+ if w.Code == 200 {+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if acc, ok := resp["accuracy"].(float64); !ok || acc != 1.0 {+ t.Fatalf("expected accuracy=1.0, got %v", resp["accuracy"])+ }+ }+}++func TestHandleSetGeolocation_CustomAccuracy(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"latitude":37.7749,"longitude":-122.4194,"accuracy":50}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/geolocation", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetGeolocation(w, req)++ if w.Code == 200 {+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if acc, ok := resp["accuracy"].(float64); !ok || acc != 50.0 {+ t.Fatalf("expected accuracy=50.0, got %v", resp["accuracy"])+ }+ }+}++func TestHandleSetGeolocation_InvalidJSON(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ req := httptest.NewRequest(http.MethodPost, "/emulation/geolocation", bytes.NewReader([]byte(`not json`)))+ w := httptest.NewRecorder()+ h.HandleSetGeolocation(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for invalid JSON, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetGeolocation_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"latitude":37.7749,"longitude":-122.4194,"tabId":"nonexistent"}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/geolocation", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetGeolocation(w, req)++ if w.Code != 404 {+ t.Fatalf("expected 404 for nonexistent tab, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabSetGeolocation_TabIDMismatch(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"latitude":37.7749,"longitude":-122.4194,"tabId":"tab_other"}`+ req := httptest.NewRequest(http.MethodPost, "/tabs/tab_abc/emulation/geolocation", bytes.NewReader([]byte(body)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabSetGeolocation(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for tab ID mismatch, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabSetGeolocation_NoTab(t *testing.T) {+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"latitude":37.7749,"longitude":-122.4194}`+ req := httptest.NewRequest(http.MethodPost, "/tabs/tab_abc/emulation/geolocation", bytes.NewReader([]byte(body)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabSetGeolocation(w, req)++ if w.Code != 404 {+ t.Fatalf("expected 404 for nonexistent tab, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetGeolocation_NegativeAccuracy(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"latitude":0,"longitude":0,"accuracy":-1}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/geolocation", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetGeolocation(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for negative accuracy, got %d: %s", w.Code, w.Body.String())+ }+}diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.goindex 37b992a0..23751e04 100644--- a/internal/handlers/handlers.go+++ b/internal/handlers/handlers.go@@ -22,20 +22,21 @@ import ()type Handlers struct {- Bridge bridge.BridgeAPI- Config *config.RuntimeConfig- Profiles bridge.ProfileService- Dashboard *dashboard.Dashboard- Orchestrator bridge.OrchestratorService- IdMgr *ids.Manager- Matcher semantic.ElementMatcher- IntentCache *recovery.IntentCache- Recovery *recovery.RecoveryEngine- Router *engine.Router // optional; nil ⇒ chrome-only- IDPIGuard idpi.Guard- CurrentTabs *CurrentTabStore- Version string // build version injected at startup- clipboard clipboardStore+ Bridge bridge.BridgeAPI+ Config *config.RuntimeConfig+ Profiles bridge.ProfileService+ Dashboard *dashboard.Dashboard+ Orchestrator bridge.OrchestratorService+ IdMgr *ids.Manager+ Matcher semantic.ElementMatcher+ IntentCache *recovery.IntentCache+ Recovery *recovery.RecoveryEngine+ Router *engine.Router // optional; nil ⇒ chrome-only+ IDPIGuard idpi.Guard+ CurrentTabs *CurrentTabStore+ Version string // build version injected at startup+ clipboard clipboardStore+ credentialStore *credentialStore// emptyPointerPolicy controls behavior when an identified caller omits// tabId and has no stored scoped current tab. See EmptyPointerPolicy.@@ -52,16 +53,17 @@ func New(b bridge.BridgeAPI, cfg *config.RuntimeConfig, p bridge.ProfileService,intentCache := recovery.NewIntentCache(200, 10*time.Minute)h := &Handlers{- Bridge: b,- Config: cfg,- Profiles: p,- Dashboard: d,- Orchestrator: o,- IdMgr: ids.NewManager(),- Matcher: matcher,- IntentCache: intentCache,- IDPIGuard: idpi.NewGuard(cfg.IDPI, cfg.AllowedDomains),- CurrentTabs: NewCurrentTabStore(),+ Bridge: b,+ Config: cfg,+ Profiles: p,+ Dashboard: d,+ Orchestrator: o,+ IdMgr: ids.NewManager(),+ Matcher: matcher,+ IntentCache: intentCache,+ IDPIGuard: idpi.NewGuard(cfg.IDPI, cfg.AllowedDomains),+ CurrentTabs: NewCurrentTabStore(),+ credentialStore: newCredentialStore(),}// Wire up the recovery engine with callbacks that delegate back to@@ -225,6 +227,9 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {mux.HandleFunc("GET /tabs/{id}/url", h.HandleTabURL)mux.HandleFunc("GET /tabs/{id}/html", h.HandleTabHTML)mux.HandleFunc("GET /tabs/{id}/styles", h.HandleTabStyles)+ mux.HandleFunc("GET /tabs/{id}/value", h.HandleTabGetValue)+ mux.HandleFunc("GET /tabs/{id}/attr", h.HandleTabGetAttr)+ mux.HandleFunc("GET /tabs/{id}/count", h.HandleTabCount)mux.HandleFunc("GET /tabs/{id}/metrics", h.HandleTabMetrics)mux.HandleFunc("GET /metrics", h.HandleMetrics)mux.HandleFunc("GET /snapshot", h.HandleSnapshot)@@ -240,6 +245,17 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {mux.HandleFunc("GET /url", h.HandleURL)mux.HandleFunc("GET /html", h.HandleHTML)mux.HandleFunc("GET /styles", h.HandleStyles)+ mux.HandleFunc("GET /value", h.HandleGetValue)+ mux.HandleFunc("GET /attr", h.HandleGetAttr)+ mux.HandleFunc("GET /count", h.HandleCount)+ mux.HandleFunc("GET /box", h.HandleGetBox)+ mux.HandleFunc("GET /tabs/{id}/box", h.HandleTabGetBox)+ mux.HandleFunc("GET /visible", h.HandleGetVisible)+ mux.HandleFunc("GET /tabs/{id}/visible", h.HandleTabGetVisible)+ mux.HandleFunc("GET /enabled", h.HandleGetEnabled)+ mux.HandleFunc("GET /tabs/{id}/enabled", h.HandleTabGetEnabled)+ mux.HandleFunc("GET /checked", h.HandleGetChecked)+ mux.HandleFunc("GET /tabs/{id}/checked", h.HandleTabGetChecked)mux.HandleFunc("GET /openapi.json", h.HandleOpenAPI)mux.HandleFunc("GET /help", h.HandleOpenAPI) // aliasmux.HandleFunc("POST /navigate", h.HandleNavigate)@@ -261,8 +277,10 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {mux.HandleFunc("POST /tabs/{id}/unlock", h.HandleTabUnlockByID)mux.HandleFunc("GET /tabs/{id}/cookies", h.HandleTabGetCookies)mux.HandleFunc("POST /tabs/{id}/cookies", h.HandleTabSetCookies)+ mux.HandleFunc("DELETE /tabs/{id}/cookies", h.HandleTabClearCookies)mux.HandleFunc("GET /cookies", h.HandleGetCookies)mux.HandleFunc("POST /cookies", h.HandleSetCookies)+ mux.HandleFunc("DELETE /cookies", h.HandleClearCookies)mux.HandleFunc("GET /solvers", h.HandleListSolvers)mux.HandleFunc("GET /config/autosolver", h.HandleAutoSolverConfig)mux.HandleFunc("POST /solve", h.HandleSolve)@@ -310,6 +328,19 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {mux.HandleFunc("POST /console/clear", h.HandleClearConsoleLogs)mux.HandleFunc("GET /errors", h.HandleGetErrorLogs)mux.HandleFunc("POST /errors/clear", h.HandleClearErrorLogs)+ mux.HandleFunc("POST /emulation/viewport", h.HandleSetViewport)+ mux.HandleFunc("POST /tabs/{id}/emulation/viewport", h.HandleTabSetViewport)+ mux.HandleFunc("POST /emulation/geolocation", h.HandleSetGeolocation)+ mux.HandleFunc("POST /tabs/{id}/emulation/geolocation", h.HandleTabSetGeolocation)+ mux.HandleFunc("POST /emulation/offline", h.HandleSetOffline)+ mux.HandleFunc("POST /tabs/{id}/emulation/offline", h.HandleTabSetOffline)+ mux.HandleFunc("POST /emulation/headers", h.HandleSetHeaders)+ mux.HandleFunc("POST /tabs/{id}/emulation/headers", h.HandleTabSetHeaders)+ mux.HandleFunc("POST /emulation/credentials", h.HandleSetCredentials)+ mux.HandleFunc("POST /tabs/{id}/emulation/credentials", h.HandleTabSetCredentials)+ mux.HandleFunc("POST /emulation/media", h.HandleSetMedia)+ mux.HandleFunc("POST /tabs/{id}/emulation/media", h.HandleTabSetMedia)+mux.HandleFunc("POST /cache/clear", h.HandleCacheClear)mux.HandleFunc("GET /cache/status", h.HandleCacheStatus)diff --git a/internal/handlers/headers.go b/internal/handlers/headers.gonew file mode 100644index 00000000..0d7bcf00--- /dev/null+++ b/internal/handlers/headers.go@@ -0,0 +1,98 @@+package handlers++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "time"++ "github.com/chromedp/cdproto/network"+ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++type headersRequest struct {+ TabID string `json:"tabId"`+ Headers map[string]string `json:"headers"`+}++// HandleSetHeaders sets extra HTTP headers via CDP.+// POST /emulation/headers+func (h *Handlers) HandleSetHeaders(w http.ResponseWriter, r *http.Request) {+ var req headersRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ h.setHeaders(w, r, req)+}++// HandleTabSetHeaders sets extra HTTP headers for a specific tab.+// POST /tabs/{id}/emulation/headers+func (h *Handlers) HandleTabSetHeaders(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("missing tab ID"))+ return+ }++ var req headersRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ if req.TabID != "" && req.TabID != tabID {+ httpx.Error(w, 400, fmt.Errorf("tabId in body %q does not match URL path %q", req.TabID, tabID))+ return+ }+ req.TabID = tabID++ h.setHeaders(w, r, req)+}++func (h *Handlers) setHeaders(w http.ResponseWriter, r *http.Request, req headersRequest) {+ if req.Headers == nil {+ httpx.Error(w, 400, fmt.Errorf("missing required field: headers"))+ return+ }++ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)+ if err != nil {+ WriteTabContextError(w, err, 404)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, 5*time.Second)+ defer tCancel()++ hdrs := make(network.Headers, len(req.Headers))+ for k, v := range req.Headers {+ hdrs[k] = v+ }++ if err := chromedp.Run(tCtx,+ chromedp.ActionFunc(func(ctx context.Context) error {+ if err := network.SetExtraHTTPHeaders(hdrs).Do(ctx); err != nil {+ return fmt.Errorf("setExtraHTTPHeaders: %w", err)+ }+ return nil+ }),+ ); err != nil {+ httpx.Error(w, 500, fmt.Errorf("CDP set extra HTTP headers: %w", err))+ return+ }++ h.recordActivity(r, activity.Update{Action: "emulation.headers", TabID: resolvedTabID})++ httpx.JSON(w, 200, map[string]any{+ "headers": req.Headers,+ "status": "applied",+ })+}diff --git a/internal/handlers/headers_test.go b/internal/handlers/headers_test.gonew file mode 100644index 00000000..13544309--- /dev/null+++ b/internal/handlers/headers_test.go@@ -0,0 +1,126 @@+package handlers++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++func TestHandleSetHeaders_Single(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"headers":{"X-Auth-Token":"abc123"}}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/headers", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetHeaders(w, req)++ // The mock bridge returns a cancelled context, so chromedp.Run will fail+ // with a context error. We accept 200 or 500 (CDP failure on mock).+ if w.Code != 200 && w.Code != 500 {+ t.Fatalf("expected 200 or 500, got %d: %s", w.Code, w.Body.String())+ }++ if w.Code == 200 {+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["status"] != "applied" {+ t.Fatalf("expected status=applied, got %v", resp["status"])+ }+ }+}++func TestHandleSetHeaders_Multiple(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"headers":{"X-Auth-Token":"abc123","X-Request-ID":"req-456"}}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/headers", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetHeaders(w, req)++ if w.Code != 200 && w.Code != 500 {+ t.Fatalf("expected 200 or 500, got %d: %s", w.Code, w.Body.String())+ }++ if w.Code == 200 {+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["status"] != "applied" {+ t.Fatalf("expected status=applied, got %v", resp["status"])+ }+ }+}++func TestHandleSetHeaders_EmptyMap(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"headers":{}}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/headers", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetHeaders(w, req)++ // Empty headers map is valid — clears extra headers.+ if w.Code != 200 && w.Code != 500 {+ t.Fatalf("expected 200 or 500, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetHeaders_InvalidJSON(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ req := httptest.NewRequest(http.MethodPost, "/emulation/headers", bytes.NewReader([]byte(`not json`)))+ w := httptest.NewRecorder()+ h.HandleSetHeaders(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for invalid JSON, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetHeaders_MissingHeaders(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"tabId":"tab_123"}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/headers", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetHeaders(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for missing headers, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabSetHeaders_TabIDMismatch(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"headers":{"X-Auth":"tok"},"tabId":"tab_other"}`+ req := httptest.NewRequest(http.MethodPost, "/tabs/tab_abc/emulation/headers", bytes.NewReader([]byte(body)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabSetHeaders(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for tab ID mismatch, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabSetHeaders_NoTab(t *testing.T) {+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"headers":{"X-Auth":"tok"}}`+ req := httptest.NewRequest(http.MethodPost, "/tabs/tab_abc/emulation/headers", bytes.NewReader([]byte(body)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabSetHeaders(w, req)++ if w.Code != 404 {+ t.Fatalf("expected 404 for nonexistent tab, got %d: %s", w.Code, w.Body.String())+ }+}diff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.goindex 37f01cf9..629d97f8 100644--- a/internal/handlers/health_tabs_test.go+++ b/internal/handlers/health_tabs_test.go@@ -504,6 +504,10 @@ func (m *MockBridge) CanClearCache(ctx context.Context) (bool, error) {return true, nil}+func (m *MockBridge) ClearCookies(ctx context.Context) error {+ return nil+}+type mockBridgeDisconnected struct {mockBridge}diff --git a/internal/handlers/media.go b/internal/handlers/media.gonew file mode 100644index 00000000..4cd02e78--- /dev/null+++ b/internal/handlers/media.go@@ -0,0 +1,101 @@+package handlers++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "time"++ "github.com/chromedp/cdproto/emulation"+ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++type mediaRequest struct {+ TabID string `json:"tabId"`+ Feature string `json:"feature"`+ Value string `json:"value"`+}++// HandleSetMedia emulates a CSS media feature via CDP.+// POST /emulation/media+func (h *Handlers) HandleSetMedia(w http.ResponseWriter, r *http.Request) {+ var req mediaRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ h.setMedia(w, r, req)+}++// HandleTabSetMedia emulates a CSS media feature for a specific tab.+// POST /tabs/{id}/emulation/media+func (h *Handlers) HandleTabSetMedia(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("missing tab ID"))+ return+ }++ var req mediaRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ if req.TabID != "" && req.TabID != tabID {+ httpx.Error(w, 400, fmt.Errorf("tabId in body %q does not match URL path %q", req.TabID, tabID))+ return+ }+ req.TabID = tabID++ h.setMedia(w, r, req)+}++func (h *Handlers) setMedia(w http.ResponseWriter, r *http.Request, req mediaRequest) {+ if req.Feature == "" {+ httpx.Error(w, 400, fmt.Errorf("missing required field: feature"))+ return+ }+ if req.Value == "" {+ httpx.Error(w, 400, fmt.Errorf("missing required field: value"))+ return+ }++ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)+ if err != nil {+ WriteTabContextError(w, err, 404)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, 5*time.Second)+ defer tCancel()++ if err := chromedp.Run(tCtx,+ chromedp.ActionFunc(func(ctx context.Context) error {+ if err := emulation.SetEmulatedMedia().+ WithFeatures([]*emulation.MediaFeature{{Name: req.Feature, Value: req.Value}}).+ Do(ctx); err != nil {+ return fmt.Errorf("setEmulatedMedia: %w", err)+ }+ return nil+ }),+ ); err != nil {+ httpx.Error(w, 500, fmt.Errorf("CDP set emulated media: %w", err))+ return+ }++ h.recordActivity(r, activity.Update{Action: "emulation.media", TabID: resolvedTabID})++ httpx.JSON(w, 200, map[string]any{+ "feature": req.Feature,+ "value": req.Value,+ "status": "applied",+ })+}diff --git a/internal/handlers/media_test.go b/internal/handlers/media_test.gonew file mode 100644index 00000000..effa4bd7--- /dev/null+++ b/internal/handlers/media_test.go@@ -0,0 +1,102 @@+package handlers++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++func TestHandleSetMedia_Valid(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"feature":"prefers-color-scheme","value":"dark"}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/media", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetMedia(w, req)++ // The mock bridge returns a cancelled context, so chromedp.Run will fail+ // with a context error. We accept 200 or 500 (CDP failure on mock).+ if w.Code != 200 && w.Code != 500 {+ t.Fatalf("expected 200 or 500, got %d: %s", w.Code, w.Body.String())+ }++ if w.Code == 200 {+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["status"] != "applied" {+ t.Fatalf("expected status=applied, got %v", resp["status"])+ }+ }+}++func TestHandleSetMedia_MissingFeature(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"value":"dark"}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/media", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetMedia(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for missing feature, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetMedia_MissingValue(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"feature":"prefers-color-scheme"}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/media", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetMedia(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for missing value, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetMedia_InvalidJSON(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ req := httptest.NewRequest(http.MethodPost, "/emulation/media", bytes.NewReader([]byte(`not json`)))+ w := httptest.NewRecorder()+ h.HandleSetMedia(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for invalid JSON, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabSetMedia_TabIDMismatch(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"feature":"prefers-color-scheme","value":"dark","tabId":"tab_other"}`+ req := httptest.NewRequest(http.MethodPost, "/tabs/tab_abc/emulation/media", bytes.NewReader([]byte(body)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabSetMedia(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for tab ID mismatch, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabSetMedia_NoTab(t *testing.T) {+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"feature":"prefers-color-scheme","value":"dark"}`+ req := httptest.NewRequest(http.MethodPost, "/tabs/tab_abc/emulation/media", bytes.NewReader([]byte(body)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabSetMedia(w, req)++ if w.Code != 404 {+ t.Fatalf("expected 404 for nonexistent tab, got %d: %s", w.Code, w.Body.String())+ }+}diff --git a/internal/handlers/offline.go b/internal/handlers/offline.gonew file mode 100644index 00000000..8316afc3--- /dev/null+++ b/internal/handlers/offline.go@@ -0,0 +1,105 @@+package handlers++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "time"++ "github.com/chromedp/cdproto/network"+ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++type offlineRequest struct {+ TabID string `json:"tabId"`+ Offline bool `json:"offline"`+ Latency float64 `json:"latency"`+ DownloadThroughput float64 `json:"downloadThroughput"`+ UploadThroughput float64 `json:"uploadThroughput"`+}++// HandleSetOffline enables or disables network offline emulation via CDP.+// POST /emulation/offline+func (h *Handlers) HandleSetOffline(w http.ResponseWriter, r *http.Request) {+ var req offlineRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ h.setOffline(w, r, req)+}++// HandleTabSetOffline enables or disables network offline emulation for a specific tab.+// POST /tabs/{id}/emulation/offline+func (h *Handlers) HandleTabSetOffline(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("missing tab ID"))+ return+ }++ var req offlineRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ if req.TabID != "" && req.TabID != tabID {+ httpx.Error(w, 400, fmt.Errorf("tabId in body %q does not match URL path %q", req.TabID, tabID))+ return+ }+ req.TabID = tabID++ h.setOffline(w, r, req)+}++func (h *Handlers) setOffline(w http.ResponseWriter, r *http.Request, req offlineRequest) {+ // Apply defaults for throughput: -1 means no throttling.+ if req.DownloadThroughput == 0 {+ req.DownloadThroughput = -1+ }+ if req.UploadThroughput == 0 {+ req.UploadThroughput = -1+ }++ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)+ if err != nil {+ WriteTabContextError(w, err, 404)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, 5*time.Second)+ defer tCancel()++ if err := chromedp.Run(tCtx,+ chromedp.ActionFunc(func(ctx context.Context) error {+ if err := network.OverrideNetworkState(req.Offline, req.Latency, req.DownloadThroughput, req.UploadThroughput).+ Do(ctx); err != nil {+ return fmt.Errorf("overrideNetworkState: %w", err)+ }+ return nil+ }),+ ); err != nil {+ httpx.Error(w, 500, fmt.Errorf("CDP network offline emulation: %w", err))+ return+ }++ h.recordActivity(r, activity.Update{Action: "emulation.offline", TabID: resolvedTabID})++ status := "online"+ if req.Offline {+ status = "offline"+ }++ httpx.JSON(w, 200, map[string]any{+ "offline": req.Offline,+ "status": status,+ })+}diff --git a/internal/handlers/offline_test.go b/internal/handlers/offline_test.gonew file mode 100644index 00000000..fa92392e--- /dev/null+++ b/internal/handlers/offline_test.go@@ -0,0 +1,105 @@+package handlers++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++func TestHandleSetOffline_True(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"offline":true}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/offline", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetOffline(w, req)++ // The mock bridge returns a cancelled context, so chromedp.Run will fail+ // with a context error. We accept 200 or 500 (CDP failure on mock).+ if w.Code != 200 && w.Code != 500 {+ t.Fatalf("expected 200 or 500, got %d: %s", w.Code, w.Body.String())+ }++ if w.Code == 200 {+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["offline"] != true {+ t.Fatalf("expected offline=true, got %v", resp["offline"])+ }+ if resp["status"] != "offline" {+ t.Fatalf("expected status=offline, got %v", resp["status"])+ }+ }+}++func TestHandleSetOffline_False(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"offline":false}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/offline", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetOffline(w, req)++ if w.Code != 200 && w.Code != 500 {+ t.Fatalf("expected 200 or 500, got %d: %s", w.Code, w.Body.String())+ }++ if w.Code == 200 {+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["offline"] != false {+ t.Fatalf("expected offline=false, got %v", resp["offline"])+ }+ if resp["status"] != "online" {+ t.Fatalf("expected status=online, got %v", resp["status"])+ }+ }+}++func TestHandleSetOffline_InvalidJSON(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ req := httptest.NewRequest(http.MethodPost, "/emulation/offline", bytes.NewReader([]byte(`not json`)))+ w := httptest.NewRecorder()+ h.HandleSetOffline(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for invalid JSON, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabSetOffline_TabIDMismatch(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"offline":true,"tabId":"tab_other"}`+ req := httptest.NewRequest(http.MethodPost, "/tabs/tab_abc/emulation/offline", bytes.NewReader([]byte(body)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabSetOffline(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for tab ID mismatch, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabSetOffline_NoTab(t *testing.T) {+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"offline":true}`+ req := httptest.NewRequest(http.MethodPost, "/tabs/tab_abc/emulation/offline", bytes.NewReader([]byte(body)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabSetOffline(w, req)++ if w.Code != 404 {+ t.Fatalf("expected 404 for nonexistent tab, got %d: %s", w.Code, w.Body.String())+ }+}diff --git a/internal/handlers/value.go b/internal/handlers/value.gonew file mode 100644index 00000000..4b51d7f3--- /dev/null+++ b/internal/handlers/value.go@@ -0,0 +1,161 @@+package handlers++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++type valueResponse struct {+ Ref string `json:"ref"`+ Value *string `json:"value"` // null when element has no .value property+}++// HandleGetValue returns the current .value of a form element identified by ref.+//+// @Endpoint GET /value+func (h *Handlers) HandleGetValue(w http.ResponseWriter, r *http.Request) {+ tabID := r.URL.Query().Get("tabId")+ h.recordReadRequest(r, "inspect.value", tabID)++ ref := r.URL.Query().Get("ref")+ if ref == "" {+ httpx.Error(w, 400, fmt.Errorf("ref query parameter is required"))+ return+ }++ if err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))+ return+ }++ ctx, resolvedTabID, err := h.tabContextWithHeader(w, r, tabID)+ if err != nil {+ WriteTabContextError(w, err, 404)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }+ defer h.armAutoCloseIfEnabled(resolvedTabID)++ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)+ defer tCancel()+ go httpx.CancelOnClientDone(r.Context(), tCancel)++ val, err := h.getElementValue(tCtx, resolvedTabID, ref)+ if err != nil {+ httpx.Error(w, 500, err)+ return+ }++ httpx.JSON(w, 200, valueResponse{Ref: ref, Value: val})+}++// HandleTabGetValue returns the .value for a tab identified by path ID.+//+// @Endpoint GET /tabs/{id}/value+func (h *Handlers) HandleTabGetValue(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ q := r.URL.Query()+ q.Set("tabId", tabID)++ req := r.Clone(r.Context())+ u := *r.URL+ u.RawQuery = q.Encode()+ req.URL = &u++ h.HandleGetValue(w, req)+}++// getElementValue resolves a ref to a DOM node and returns its .value property.+// Returns a nil pointer when the element has no value property.+func (h *Handlers) getElementValue(ctx context.Context, tabID, ref string) (*string, error) {+ cache := h.Bridge.GetRefCache(tabID)+ if cache == nil {+ return nil, fmt.Errorf("ref not found: %s (no snapshot cache — run /snapshot first)", ref)+ }+ target, ok := cache.Lookup(ref)+ if !ok {+ return nil, fmt.Errorf("ref not found: %s", ref)+ }++ nodeID := target.BackendNodeID+ if nodeID == 0 {+ return nil, fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)+ }++ var result *string+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ // Step 1: Resolve backend node ID to a remote object+ var resolveResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{+ "backendNodeId": nodeID,+ }, &resolveResult); err != nil {+ return fmt.Errorf("resolve node: %w", err)+ }++ var resolved struct {+ Object struct {+ ObjectID string `json:"objectId"`+ } `json:"object"`+ }+ if err := json.Unmarshal(resolveResult, &resolved); err != nil {+ return fmt.Errorf("parse resolved node: %w", err)+ }+ if resolved.Object.ObjectID == "" {+ return fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)+ }++ // Step 2: Call .value on the element+ var callResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{+ "functionDeclaration": `function() { return this.value !== undefined ? String(this.value) : null; }`,+ "objectId": resolved.Object.ObjectID,+ "returnByValue": true,+ }, &callResult); err != nil {+ return fmt.Errorf("get element value: %w", err)+ }++ var callParsed struct {+ Result struct {+ Type string `json:"type"`+ Value any `json:"value"`+ } `json:"result"`+ ExceptionDetails *struct {+ Text string `json:"text"`+ } `json:"exceptionDetails,omitempty"`+ }+ if err := json.Unmarshal(callResult, &callParsed); err != nil {+ return fmt.Errorf("parse value result: %w", err)+ }+ if callParsed.ExceptionDetails != nil && callParsed.ExceptionDetails.Text != "" {+ return fmt.Errorf("get element value: %s", callParsed.ExceptionDetails.Text)+ }++ // null means the element has no .value property+ if callParsed.Result.Value == nil {+ result = nil+ } else {+ s := fmt.Sprint(callParsed.Result.Value)+ result = &s+ }+ return nil+ }))+ if err != nil {+ return nil, err+ }+ return result, nil+}diff --git a/internal/handlers/value_test.go b/internal/handlers/value_test.gonew file mode 100644index 00000000..17932c8f--- /dev/null+++ b/internal/handlers/value_test.go@@ -0,0 +1,117 @@+package handlers++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config"+)++func TestHandleGetValue_MissingRef(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/value", nil)+ w := httptest.NewRecorder()+ h.HandleGetValue(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "ref") {+ t.Fatalf("expected error about ref, got %s", w.Body.String())+ }+}++func TestHandleGetValue_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/value?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleGetValue(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleGetValue_NoSnapshotCache(t *testing.T) {+ // mockBridge does not implement GetRefCache, so we use a valueMockBridge+ mb := &valueMockBridge{refCache: nil}+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/value?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleGetValue(w, req)+ if w.Code != http.StatusInternalServerError {+ t.Fatalf("expected 500, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "no snapshot cache") {+ t.Fatalf("expected snapshot cache error, got %s", w.Body.String())+ }+}++func TestHandleGetValue_RefNotFound(t *testing.T) {+ mb := &valueMockBridge{+ refCache: &bridge.RefCache{+ Refs: map[string]int64{"e1": 100},+ Targets: map[string]bridge.RefTarget{"e1": {BackendNodeID: 100}},+ },+ }+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/value?ref=e99", nil)+ w := httptest.NewRecorder()+ h.HandleGetValue(w, req)+ if w.Code != http.StatusInternalServerError {+ t.Fatalf("expected 500, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "ref not found: e99") {+ t.Fatalf("expected ref not found error, got %s", w.Body.String())+ }+}++func TestHandleTabGetValue_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs//value?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleTabGetValue(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabGetValue_ForwardsTabID(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs/tab_abc/value?ref=e5", nil)+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabGetValue(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestValueRoutesRegistered(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)++ paths := []string{"/value?ref=e1", "/tabs/tab1/value?ref=e1"}+ for _, path := range paths {+ t.Run(path, func(t *testing.T) {+ req := httptest.NewRequest("GET", path, nil)+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)+ if w.Code == http.StatusNotFound && strings.Contains(w.Body.String(), "404 page not found") {+ t.Fatalf("route %s not registered", path)+ }+ })+ }+}++// valueMockBridge extends mockBridge with GetRefCache support.+type valueMockBridge struct {+ mockBridge+ refCache *bridge.RefCache+}++func (m *valueMockBridge) GetRefCache(tabID string) *bridge.RefCache {+ return m.refCache+}diff --git a/internal/handlers/viewport.go b/internal/handlers/viewport.gonew file mode 100644index 00000000..6c20bdf8--- /dev/null+++ b/internal/handlers/viewport.go@@ -0,0 +1,106 @@+package handlers++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "time"++ "github.com/chromedp/cdproto/emulation"+ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++type viewportRequest struct {+ TabID string `json:"tabId"`+ Width int `json:"width"`+ Height int `json:"height"`+ DeviceScaleFactor float64 `json:"deviceScaleFactor"`+ Mobile bool `json:"mobile"`+}++// HandleSetViewport sets the browser viewport dimensions via CDP emulation.+// POST /emulation/viewport+func (h *Handlers) HandleSetViewport(w http.ResponseWriter, r *http.Request) {+ var req viewportRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ h.setViewport(w, r, req)+}++// HandleTabSetViewport sets the browser viewport dimensions for a specific tab.+// POST /tabs/{id}/emulation/viewport+func (h *Handlers) HandleTabSetViewport(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("missing tab ID"))+ return+ }++ var req viewportRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ if req.TabID != "" && req.TabID != tabID {+ httpx.Error(w, 400, fmt.Errorf("tabId in body %q does not match URL path %q", req.TabID, tabID))+ return+ }+ req.TabID = tabID++ h.setViewport(w, r, req)+}++func (h *Handlers) setViewport(w http.ResponseWriter, r *http.Request, req viewportRequest) {+ if req.Width <= 0 || req.Height <= 0 {+ httpx.Error(w, 400, fmt.Errorf("width and height must be positive integers"))+ return+ }++ if req.DeviceScaleFactor <= 0 {+ req.DeviceScaleFactor = 1.0+ }++ ctx, resolvedTabID, err := h.tabContext(r, req.TabID)+ if err != nil {+ WriteTabContextError(w, err, 404)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, 5*time.Second)+ defer tCancel()++ if err := chromedp.Run(tCtx,+ chromedp.ActionFunc(func(ctx context.Context) error {+ if err := emulation.SetDeviceMetricsOverride(int64(req.Width), int64(req.Height), req.DeviceScaleFactor, req.Mobile).+ WithScreenWidth(int64(req.Width)).+ WithScreenHeight(int64(req.Height)).+ Do(ctx); err != nil {+ return fmt.Errorf("setDeviceMetricsOverride: %w", err)+ }+ return nil+ }),+ ); err != nil {+ httpx.Error(w, 500, fmt.Errorf("CDP viewport override: %w", err))+ return+ }++ h.recordActivity(r, activity.Update{Action: "emulation.viewport", TabID: resolvedTabID})++ httpx.JSON(w, 200, map[string]any{+ "width": req.Width,+ "height": req.Height,+ "deviceScaleFactor": req.DeviceScaleFactor,+ "mobile": req.Mobile,+ "status": "applied",+ })+}diff --git a/internal/handlers/viewport_test.go b/internal/handlers/viewport_test.gonew file mode 100644index 00000000..567aae9f--- /dev/null+++ b/internal/handlers/viewport_test.go@@ -0,0 +1,161 @@+package handlers++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+)++func TestHandleSetViewport_ValidDimensions(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"width":1920,"height":1080}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/viewport", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetViewport(w, req)++ // The mock bridge returns a cancelled context, so chromedp.Run will fail+ // with a context error. We accept 200 or 500 (CDP failure on mock).+ if w.Code != 200 && w.Code != 500 {+ t.Fatalf("expected 200 or 500, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetViewport_ZeroWidth(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"width":0,"height":1080}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/viewport", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetViewport(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for zero width, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetViewport_NegativeHeight(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"width":1920,"height":-1}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/viewport", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetViewport(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for negative height, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetViewport_MissingDimensions(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/viewport", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetViewport(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for missing dimensions, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetViewport_DefaultDPR(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"width":1920,"height":1080}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/viewport", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetViewport(w, req)++ // Even if chromedp fails (mock context), verify the response contains+ // default DPR when the request succeeds (200) or the validation passed.+ if w.Code == 200 {+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if dpr, ok := resp["deviceScaleFactor"].(float64); !ok || dpr != 1.0 {+ t.Fatalf("expected deviceScaleFactor=1.0, got %v", resp["deviceScaleFactor"])+ }+ }+}++func TestHandleSetViewport_CustomDPRAndMobile(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"width":375,"height":812,"deviceScaleFactor":3,"mobile":true}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/viewport", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetViewport(w, req)++ if w.Code == 200 {+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if dpr, ok := resp["deviceScaleFactor"].(float64); !ok || dpr != 3.0 {+ t.Fatalf("expected deviceScaleFactor=3.0, got %v", resp["deviceScaleFactor"])+ }+ if mobile, ok := resp["mobile"].(bool); !ok || !mobile {+ t.Fatalf("expected mobile=true, got %v", resp["mobile"])+ }+ }+}++func TestHandleSetViewport_InvalidJSON(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ req := httptest.NewRequest(http.MethodPost, "/emulation/viewport", bytes.NewReader([]byte(`not json`)))+ w := httptest.NewRecorder()+ h.HandleSetViewport(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for invalid JSON, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleSetViewport_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"width":1920,"height":1080,"tabId":"nonexistent"}`+ req := httptest.NewRequest(http.MethodPost, "/emulation/viewport", bytes.NewReader([]byte(body)))+ w := httptest.NewRecorder()+ h.HandleSetViewport(w, req)++ if w.Code != 404 {+ t.Fatalf("expected 404 for nonexistent tab, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabSetViewport_TabIDMismatch(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"width":1920,"height":1080,"tabId":"tab_other"}`+ req := httptest.NewRequest(http.MethodPost, "/tabs/tab_abc/emulation/viewport", bytes.NewReader([]byte(body)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabSetViewport(w, req)++ if w.Code != 400 {+ t.Fatalf("expected 400 for tab ID mismatch, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabSetViewport_NoTab(t *testing.T) {+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)++ body := `{"width":1920,"height":1080}`+ req := httptest.NewRequest(http.MethodPost, "/tabs/tab_abc/emulation/viewport", bytes.NewReader([]byte(body)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabSetViewport(w, req)++ if w.Code != 404 {+ t.Fatalf("expected 404 for nonexistent tab, got %d: %s", w.Code, w.Body.String())+ }+}diff --git a/internal/handlers/visible.go b/internal/handlers/visible.gonew file mode 100644index 00000000..e258b7ef--- /dev/null+++ b/internal/handlers/visible.go@@ -0,0 +1,163 @@+package handlers++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++type visibleResponse struct {+ Ref string `json:"ref"`+ Visible bool `json:"visible"`+}++// HandleGetVisible returns whether an element identified by ref is visible on the page.+//+// @Endpoint GET /visible+func (h *Handlers) HandleGetVisible(w http.ResponseWriter, r *http.Request) {+ tabID := r.URL.Query().Get("tabId")+ h.recordReadRequest(r, "inspect.visible", tabID)++ ref := r.URL.Query().Get("ref")+ if ref == "" {+ httpx.Error(w, 400, fmt.Errorf("ref query parameter is required"))+ return+ }++ if err := h.ensureChrome(); err != nil {+ if h.writeBridgeUnavailable(w, err) {+ return+ }+ httpx.Error(w, 500, fmt.Errorf("chrome initialization: %w", err))+ return+ }++ ctx, resolvedTabID, err := h.tabContextWithHeader(w, r, tabID)+ if err != nil {+ WriteTabContextError(w, err, 404)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }+ defer h.armAutoCloseIfEnabled(resolvedTabID)++ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)+ defer tCancel()+ go httpx.CancelOnClientDone(r.Context(), tCancel)++ visible, err := h.getElementVisible(tCtx, resolvedTabID, ref)+ if err != nil {+ httpx.Error(w, 500, err)+ return+ }++ httpx.JSON(w, 200, visibleResponse{Ref: ref, Visible: visible})+}++// HandleTabGetVisible returns visibility for a tab identified by path ID.+//+// @Endpoint GET /tabs/{id}/visible+func (h *Handlers) HandleTabGetVisible(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ q := r.URL.Query()+ q.Set("tabId", tabID)++ req := r.Clone(r.Context())+ u := *r.URL+ u.RawQuery = q.Encode()+ req.URL = &u++ h.HandleGetVisible(w, req)+}++// getElementVisible resolves a ref to a DOM node and checks whether it is visible.+func (h *Handlers) getElementVisible(ctx context.Context, tabID, ref string) (bool, error) {+ cache := h.Bridge.GetRefCache(tabID)+ if cache == nil {+ return false, fmt.Errorf("ref not found: %s (no snapshot cache — run /snapshot first)", ref)+ }+ target, ok := cache.Lookup(ref)+ if !ok {+ return false, fmt.Errorf("ref not found: %s", ref)+ }++ nodeID := target.BackendNodeID+ if nodeID == 0 {+ return false, fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)+ }++ var visible bool+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ // Step 1: Resolve backend node ID to a remote object+ var resolveResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{+ "backendNodeId": nodeID,+ }, &resolveResult); err != nil {+ return fmt.Errorf("resolve node: %w", err)+ }++ var resolved struct {+ Object struct {+ ObjectID string `json:"objectId"`+ } `json:"object"`+ }+ if err := json.Unmarshal(resolveResult, &resolved); err != nil {+ return fmt.Errorf("parse resolved node: %w", err)+ }+ if resolved.Object.ObjectID == "" {+ return fmt.Errorf("element not found in DOM (backendNodeId=%d)", nodeID)+ }++ // Step 2: Evaluate visibility checks on the element+ var callResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{+ "functionDeclaration": `function() {+ var el = this;+ if (!el.offsetParent && el.style.position !== 'fixed' && el.style.position !== 'sticky') return false;+ var style = window.getComputedStyle(el);+ if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') return false;+ var rect = el.getBoundingClientRect();+ return rect.width > 0 && rect.height > 0;+}`,+ "objectId": resolved.Object.ObjectID,+ "returnByValue": true,+ }, &callResult); err != nil {+ return fmt.Errorf("check element visibility: %w", err)+ }++ var callParsed struct {+ Result struct {+ Type string `json:"type"`+ Value any `json:"value"`+ } `json:"result"`+ ExceptionDetails *struct {+ Text string `json:"text"`+ } `json:"exceptionDetails,omitempty"`+ }+ if err := json.Unmarshal(callResult, &callParsed); err != nil {+ return fmt.Errorf("parse visibility result: %w", err)+ }+ if callParsed.ExceptionDetails != nil && callParsed.ExceptionDetails.Text != "" {+ return fmt.Errorf("check element visibility: %s", callParsed.ExceptionDetails.Text)+ }++ if b, ok := callParsed.Result.Value.(bool); ok {+ visible = b+ }+ return nil+ }))+ if err != nil {+ return false, err+ }+ return visible, nil+}diff --git a/internal/handlers/visible_test.go b/internal/handlers/visible_test.gonew file mode 100644index 00000000..176c38bb--- /dev/null+++ b/internal/handlers/visible_test.go@@ -0,0 +1,116 @@+package handlers++import (+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config"+)++func TestHandleGetVisible_MissingRef(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/visible", nil)+ w := httptest.NewRecorder()+ h.HandleGetVisible(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "ref") {+ t.Fatalf("expected error about ref, got %s", w.Body.String())+ }+}++func TestHandleGetVisible_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/visible?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleGetVisible(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleGetVisible_NoSnapshotCache(t *testing.T) {+ mb := &visibleMockBridge{refCache: nil}+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/visible?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleGetVisible(w, req)+ if w.Code != http.StatusInternalServerError {+ t.Fatalf("expected 500, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "no snapshot cache") {+ t.Fatalf("expected snapshot cache error, got %s", w.Body.String())+ }+}++func TestHandleGetVisible_RefNotFound(t *testing.T) {+ mb := &visibleMockBridge{+ refCache: &bridge.RefCache{+ Refs: map[string]int64{"e1": 100},+ Targets: map[string]bridge.RefTarget{"e1": {BackendNodeID: 100}},+ },+ }+ h := New(mb, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/visible?ref=e99", nil)+ w := httptest.NewRecorder()+ h.HandleGetVisible(w, req)+ if w.Code != http.StatusInternalServerError {+ t.Fatalf("expected 500, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "ref not found: e99") {+ t.Fatalf("expected ref not found error, got %s", w.Body.String())+ }+}++func TestHandleTabGetVisible_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs//visible?ref=e5", nil)+ w := httptest.NewRecorder()+ h.HandleTabGetVisible(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabGetVisible_ForwardsTabID(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs/tab_abc/visible?ref=e5", nil)+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabGetVisible(w, req)+ if w.Code != http.StatusNotFound {+ t.Fatalf("expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++func TestVisibleRoutesRegistered(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)++ paths := []string{"/visible?ref=e1", "/tabs/tab1/visible?ref=e1"}+ for _, path := range paths {+ t.Run(path, func(t *testing.T) {+ req := httptest.NewRequest("GET", path, nil)+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)+ if w.Code == http.StatusNotFound && strings.Contains(w.Body.String(), "404 page not found") {+ t.Fatalf("route %s not registered", path)+ }+ })+ }+}++// visibleMockBridge extends mockBridge with GetRefCache support.+type visibleMockBridge struct {+ mockBridge+ refCache *bridge.RefCache+}++func (m *visibleMockBridge) GetRefCache(tabID string) *bridge.RefCache {+ return m.refCache+}diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex 6378f420..e8225663 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -61,6 +61,13 @@ var coreEndpoints = []Endpoint{{"GET", "/url", "Read page URL", CapNone, true},{"GET", "/html", "Read page HTML", CapNone, true},{"GET", "/styles", "Read computed styles", CapNone, true},+ {"GET", "/value", "Read form element value by ref", CapNone, true},+ {"GET", "/attr", "Read element HTML attribute by ref", CapNone, true},+ {"GET", "/count", "Count elements matching selector", CapNone, true},+ {"GET", "/box", "Get element bounding box by ref", CapNone, true},+ {"GET", "/visible", "Check if element is visible by ref", CapNone, true},+ {"GET", "/enabled", "Check if element is enabled by ref", CapNone, true},+ {"GET", "/checked", "Check if element is checked by ref", CapNone, true},{"GET", "/pdf", "Export as PDF (GET)", CapNone, true},{"POST", "/pdf", "Export as PDF (POST)", CapNone, true},@@ -85,6 +92,7 @@ var coreEndpoints = []Endpoint{// Cookies{"GET", "/cookies", "Get cookies", CapNone, true},{"POST", "/cookies", "Set cookies", CapNone, true},+ {"DELETE", "/cookies", "Clear all cookies", CapNone, true},// Metrics{"GET", "/metrics", "Runtime metrics", CapNone, true},@@ -122,6 +130,14 @@ var coreEndpoints = []Endpoint{{"POST", "/solve", "Run default solver", CapNone, true},{"POST", "/solve/{name}", "Run named solver", CapNone, true},+ // Emulation+ {"POST", "/emulation/viewport", "Set browser viewport dimensions", CapNone, true},+ {"POST", "/emulation/geolocation", "Set geolocation", CapNone, true},+ {"POST", "/emulation/offline", "Enable/disable offline mode", CapNone, true},+ {"POST", "/emulation/headers", "Set extra HTTP headers", CapNone, true},+ {"POST", "/emulation/credentials", "Set HTTP auth credentials", CapNone, true},+ {"POST", "/emulation/media", "Emulate CSS media features", CapNone, true},+// Cache{"POST", "/cache/clear", "Clear browser cache", CapNone, false},{"GET", "/cache/status", "Cache status", CapNone, false},diff --git a/plugin/tools/pinchtab.ts b/plugin/tools/pinchtab.tsindex 11381fcd..7648cdd3 100644--- a/plugin/tools/pinchtab.ts+++ b/plugin/tools/pinchtab.ts@@ -382,8 +382,22 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Proif (normalized.savePath) {query.set("output", "file");query.set("path", normalized.savePath);+ return textResult(await pinchtabFetch(cfg, `/download?${query.toString()}`));+ }+ query.set("raw", "true");+ try {+ const res = await pinchtabFetch(cfg, `/download?${query.toString()}`, { rawResponse: true });+ if (res instanceof Response) {+ if (!res.ok) return textResult({ error: `download failed: ${res.status} ${await res.text()}` });+ const buf = await res.arrayBuffer();+ const b64 = Buffer.from(buf).toString("base64");+ const mimeType = res.headers.get("content-type") || "application/octet-stream";+ return resourceResult("download://file", mimeType, b64);+ }+ return textResult(res);+ } catch (err: any) {+ return textResult({ error: `download failed: ${err?.message}` });}- return textResult(await pinchtabFetch(cfg, `/download?${query.toString()}`));}// --- upload ---diff --git a/skills/pinchtab-todo/SKILL.md b/skills/pinchtab-todo/SKILL.mdnew file mode 100644index 00000000..40fb3f18--- /dev/null+++ b/skills/pinchtab-todo/SKILL.md@@ -0,0 +1,142 @@+---+name: pinchtab-todo+description: "Process the next task from the todo pipeline. Prepares or executes one task per cycle using todo.md (backlog) and todo-next.md (current task). Use when asked to 'run todo', 'process todo', 'next task', or 'work on the next todo'."+---++# PinchTab Todo Runner++Two-phase pipeline: **prepare** a task (research + write up), then **execute** it next cycle. One action per invocation.++## Path Resolution++```bash+PROJECT_ROOT=$(git rev-parse --show-toplevel)+TODO_FILE="$PROJECT_ROOT/todo.md"+TODO_NEXT="$PROJECT_ROOT/todo-next.md"+```++## Execution++### 0. Ensure recurring schedule exists++Before doing any work, check whether a schedule (routine) is already active for this skill:++1. Use `CronList` to list existing routines.+2. Look for one whose name or prompt references `pinchtab-todo`.+3. **If a matching schedule exists** — continue to step 1.+4. **If no matching schedule exists** — create one using `CronCreate` that runs every 30 minutes with the prompt `/pinchtab-todo`. Then continue to step 1.++### 1. Check for `todo-next.md`++- **If `todo-next.md` does NOT exist** → go to **Phase A** (prepare).+- **If `todo-next.md` EXISTS** → go to **Phase B** (execute).++---++## Phase A — Prepare the next task++Goal: pick the first incomplete task from `todo.md`, research it, and write a detailed `todo-next.md`. Do NOT implement anything.++### A1. Read `todo.md`++If the file does not exist, is empty, or every task is marked `[x]`, report that the backlog is clear and stop.++### A2. Pick the first `- [ ]` task++Take the first incomplete item from the list.++### A3. Research the task++Investigate the current codebase to understand:+- What files/packages are involved+- How similar features are implemented+- What the right approach is+- Any edge cases or risks++### A4. Write `todo-next.md`++Create `todo-next.md` with this structure:++```markdown+# <task title>++> **Source:** `todo.md` line N+> **Status:** ready++## User Story++As an [agent/user/developer], I want [what] so that [why].++## TLDR++One paragraph summary of what needs to happen and the approach.++## Details++- Files to change: ...+- Approach: ...+- Edge cases: ...+- Tests needed: ...++## Acceptance Criteria++- [ ] Criterion 1+- [ ] Criterion 2+- [ ] `./dev all` passes+```++### A5. Stop++Report that the next task has been prepared. Do not start implementation — that happens in Phase B on the next cycle.++---++## Phase B — Execute the current task++Goal: implement the task described in `todo-next.md`, verify the build, then prepare the next one.++### B1. Read `todo-next.md`++Understand the task, user story, approach, and acceptance criteria.++### B2. Implement the task++Spawn a subagent to perform the work. Replace `{PROJECT_ROOT}` and `{TASK_DETAILS}` with actual values:++```+You are working on the PinchTab project at {PROJECT_ROOT}.++Your task is described below:+{TASK_DETAILS}++Start by reading the development skill for context:+1. Read `{PROJECT_ROOT}/skills/pinchtab-dev/SKILL.md` — dev commands, architecture, and workflow.+2. Read `{PROJECT_ROOT}/skills/pinchtab/SKILL.md` — PinchTab command reference (if needed).++Then implement the task following the approach and acceptance criteria.+When done, report what you changed.+```++Wait for the subagent to complete and review its output.++### B3. Verify the build++```bash+cd "$PROJECT_ROOT" && ./dev all+```++- **If `./dev all` passes**: continue to B4.+- **If `./dev all` fails**: read the failure, fix the issues, re-run. Up to 3 attempts. If still failing after 3 attempts, report the failure and stop — leave `todo-next.md` in place for the next cycle.++### B4. Mark done and clean up++1. Mark the corresponding task as `[x]` in `todo.md`.+2. Delete `todo-next.md`.++### B5. Prepare the next task++Now run **Phase A** (steps A1–A5) to prepare the next `todo-next.md` from the backlog. This way the next cycle can jump straight into execution.++### B6. Stop++Report what was completed and what was prepared for next cycle.diff --git a/tests/e2e/docker-compose-multi.yml b/tests/e2e/docker-compose-multi.ymlindex c1f0b610..d91db0c4 100644--- a/tests/e2e/docker-compose-multi.yml+++ b/tests/e2e/docker-compose-multi.yml@@ -27,7 +27,7 @@ services:- ./fixtures/test-extension-api:/extensions/test-extension-apicommand: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab.json /data/e2e-config/pinchtab.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]ports:- - "9999:9999"+ - "127.0.0.1:9999:9999"healthcheck: *pinchtab-healthcheckpinchtab-secure:@@ -38,7 +38,7 @@ services:- ./config/pinchtab-secure.json:/fixture-config/pinchtab-secure.json:rocommand: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-secure.json /data/e2e-config/pinchtab-secure.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]ports:- - "9998:9999"+ - "127.0.0.1:9998:9999"healthcheck: *pinchtab-healthcheckpinchtab-autoclose:@@ -60,7 +60,7 @@ services:- ./fixtures/test-extension:/extensions/test-extensioncommand: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-medium-permissive.json /data/e2e-config/pinchtab-medium-permissive.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]ports:- - "9994:9999"+ - "127.0.0.1:9994:9999"healthcheck: *pinchtab-healthcheckpinchtab-full:@@ -72,7 +72,7 @@ services:- ./fixtures/test-extension:/extensions/test-extensioncommand: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-full-permissive.json /data/e2e-config/pinchtab-full-permissive.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]ports:- - "9995:9999"+ - "127.0.0.1:9995:9999"healthcheck: *pinchtab-healthcheckpinchtab-lite:@@ -82,7 +82,7 @@ services:volumes:- ./config/pinchtab-lite.json:/fixture-config/pinchtab-lite.json:roports:- - "9997:9999"+ - "127.0.0.1:9997:9999"command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-lite.json /data/e2e-config/pinchtab-lite.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab bridge"]healthcheck: *pinchtab-healthcheck@@ -93,7 +93,7 @@ services:volumes:- ./config/pinchtab-bridge.json:/fixture-config/pinchtab-bridge.json:roports:- - "9996:9999"+ - "127.0.0.1:9996:9999"command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-bridge.json /data/e2e-config/pinchtab-bridge.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab bridge"]healthcheck:# Bridge-mode pinchtab uses a different auth token. Same tighteneddiff --git a/tests/e2e/docker-compose.yml b/tests/e2e/docker-compose.ymlindex 8df3718c..f92251cf 100644--- a/tests/e2e/docker-compose.yml+++ b/tests/e2e/docker-compose.yml@@ -11,7 +11,7 @@ services:- ./fixtures/test-extension-api:/extensions/test-extension-api:rocommand: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab.json /data/e2e-config/pinchtab.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]ports:- - "9999:9999"+ - "127.0.0.1:9999:9999"shm_size: '2gb'healthcheck:test: ["CMD-SHELL", "wget --header='Authorization: Bearer e2e-token' -q -O /dev/null http://localhost:9999/health"]diff --git a/tests/e2e/scenarios/api/emulation-basic.sh b/tests/e2e/scenarios/api/emulation-basic.shnew file mode 100755index 00000000..83a0b4e3--- /dev/null+++ b/tests/e2e/scenarios/api/emulation-basic.sh@@ -0,0 +1,84 @@+#!/bin/bash+# emulation-basic.sh — API happy-path emulation scenarios.++GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+source "${GROUP_DIR}/../../helpers/api.sh"++# Navigate to a fixtures page so there is an active tab for emulation commands.+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/form.html\"}"++# ─────────────────────────────────────────────────────────────────+start_test "emulation: set viewport 1024x768"++pt_post /emulation/viewport '{"width":1024,"height":768}'+assert_ok "set viewport"+assert_json_eq "$RESULT" '.status' 'applied' "viewport status applied"+assert_json_eq "$RESULT" '.width' '1024' "viewport width"+assert_json_eq "$RESULT" '.height' '768' "viewport height"++end_test++# ─────────────────────────────────────────────────────────────────+start_test "emulation: set geolocation"++pt_post /emulation/geolocation '{"latitude":51.5074,"longitude":-0.1278}'+assert_ok "set geolocation"+assert_json_eq "$RESULT" '.status' 'applied' "geolocation status applied"+assert_json_contains "$RESULT" '.latitude' '51.5074' "latitude set"+assert_json_contains "$RESULT" '.longitude' '-0.1278' "longitude set"++end_test++# ─────────────────────────────────────────────────────────────────+start_test "emulation: offline mode toggle"++pt_post /emulation/offline '{"offline":true}'+assert_ok "enable offline"+assert_json_eq "$RESULT" '.offline' 'true' "offline flag true"+assert_json_eq "$RESULT" '.status' 'offline' "status is offline"++# MUST disable offline immediately to avoid breaking subsequent tests.+pt_post /emulation/offline '{"offline":false}'+assert_ok "disable offline"+assert_json_eq "$RESULT" '.offline' 'false' "offline flag false"+assert_json_eq "$RESULT" '.status' 'online' "status is online"++end_test++# ─────────────────────────────────────────────────────────────────+start_test "emulation: set custom headers"++pt_post /emulation/headers '{"headers":{"X-Custom-Test":"pinchtab-e2e","Accept-Language":"en-GB"}}'+assert_ok "set custom headers"+assert_json_eq "$RESULT" '.status' 'applied' "headers status applied"+assert_json_exists "$RESULT" '.headers' "response has headers field"++end_test++# ─────────────────────────────────────────────────────────────────+start_test "emulation: clear headers with empty map"++pt_post /emulation/headers '{"headers":{}}'+assert_ok "clear headers"+assert_json_eq "$RESULT" '.status' 'applied' "headers cleared"++end_test++# ─────────────────────────────────────────────────────────────────+start_test "emulation: set media prefers-color-scheme dark"++pt_post /emulation/media '{"feature":"prefers-color-scheme","value":"dark"}'+assert_ok "set media feature"+assert_json_eq "$RESULT" '.status' 'applied' "media status applied"+assert_json_eq "$RESULT" '.feature' 'prefers-color-scheme' "feature echoed"+assert_json_eq "$RESULT" '.value' 'dark' "value echoed"++end_test++# ─────────────────────────────────────────────────────────────────+start_test "emulation: invalid JSON to /emulation/viewport returns 400"++pt_post_raw /emulation/viewport '{broken json!!'+assert_http_status "400" "bad JSON returns 400"++end_testdiff --git a/tests/e2e/scenarios/api/inspect-basic.sh b/tests/e2e/scenarios/api/inspect-basic.shnew file mode 100755index 00000000..fe3d272b--- /dev/null+++ b/tests/e2e/scenarios/api/inspect-basic.sh@@ -0,0 +1,141 @@+#!/bin/bash+# inspect-basic.sh — API happy-path inspection + cookie clearing scenarios.++GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+source "${GROUP_DIR}/../../helpers/api.sh"++# Navigate to form.html and take a snapshot to populate the ref cache.+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/form.html\"}"+assert_ok "navigate to form.html"++pt_get /snapshot+assert_ok "snapshot to populate ref cache"++# Extract refs for various elements we will inspect.+# form.html has: textbox (username), textbox (email), textbox (password),+# combobox (country), checkbox (terms), button (Submit/Reset).+INPUT_REF=$(find_ref_by_role "textbox")+CHECKBOX_REF=$(echo "$RESULT" | jq -r '[.nodes[] | select(.role == "checkbox") | .ref] | first // empty')+BUTTON_REF=$(find_ref_by_name "Submit")++# ─────────────────────────────────────────────────────────────────+start_test "inspect: GET /count?selector=input"++pt_get "/count?selector=input"+assert_ok "count inputs"++COUNT=$(echo "$RESULT" | jq '.count')+if [ "$COUNT" -ge 3 ]; then+ echo -e " ${GREEN}✓${NC} count >= 3 (got: $COUNT)"+ ((ASSERTIONS_PASSED++)) || true+else+ echo -e " ${RED}✗${NC} count < 3 (got: $COUNT)"+ ((ASSERTIONS_FAILED++)) || true+fi++assert_json_eq "$RESULT" '.selector' 'input' "selector echoed back"++end_test++# ─────────────────────────────────────────────────────────────────+start_test "inspect: GET /value by ref"++if assert_ref_found "$INPUT_REF" "textbox ref for /value"; then+ pt_get "/value?ref=${INPUT_REF}"+ assert_ok "get value of textbox"+ assert_json_eq "$RESULT" '.ref' "$INPUT_REF" "ref echoed back"+fi++end_test++# ─────────────────────────────────────────────────────────────────+start_test "inspect: GET /attr (type attribute)"++if assert_ref_found "$INPUT_REF" "textbox ref for /attr"; then+ pt_get "/attr?ref=${INPUT_REF}&name=type"+ assert_ok "get type attribute"+ assert_json_eq "$RESULT" '.ref' "$INPUT_REF" "ref echoed back"+ assert_json_eq "$RESULT" '.name' 'type' "attr name echoed back"+ assert_json_exists "$RESULT" '.value' "attr value present"+fi++end_test++# ─────────────────────────────────────────────────────────────────+start_test "inspect: GET /box (bounding box)"++if assert_ref_found "$INPUT_REF" "textbox ref for /box"; then+ pt_get "/box?ref=${INPUT_REF}"+ assert_ok "get bounding box"+ assert_json_eq "$RESULT" '.ref' "$INPUT_REF" "ref echoed back"++ BOX_WIDTH=$(echo "$RESULT" | jq '.box.width')+ if [ "$(echo "$BOX_WIDTH > 0" | bc -l 2>/dev/null || echo 0)" = "1" ]; then+ echo -e " ${GREEN}✓${NC} box width > 0 (got: $BOX_WIDTH)"+ ((ASSERTIONS_PASSED++)) || true+ else+ # Fallback check for environments without bc+ if echo "$BOX_WIDTH" | grep -qvE '^0(\.0+)?$'; then+ echo -e " ${GREEN}✓${NC} box width > 0 (got: $BOX_WIDTH)"+ ((ASSERTIONS_PASSED++)) || true+ else+ echo -e " ${RED}✗${NC} box width is 0 or invalid (got: $BOX_WIDTH)"+ ((ASSERTIONS_FAILED++)) || true+ fi+ fi+fi++end_test++# ─────────────────────────────────────────────────────────────────+start_test "inspect: GET /visible (element is visible)"++if assert_ref_found "$INPUT_REF" "textbox ref for /visible"; then+ pt_get "/visible?ref=${INPUT_REF}"+ assert_ok "get visible state"+ assert_json_eq "$RESULT" '.ref' "$INPUT_REF" "ref echoed back"+ assert_json_eq "$RESULT" '.visible' 'true' "input is visible"+fi++end_test++# ─────────────────────────────────────────────────────────────────+start_test "inspect: GET /enabled (element is enabled)"++if assert_ref_found "$INPUT_REF" "textbox ref for /enabled"; then+ pt_get "/enabled?ref=${INPUT_REF}"+ assert_ok "get enabled state"+ assert_json_eq "$RESULT" '.ref' "$INPUT_REF" "ref echoed back"+ assert_json_eq "$RESULT" '.enabled' 'true' "input is enabled"+fi++end_test++# ─────────────────────────────────────────────────────────────────+start_test "inspect: GET /checked (checkbox is not checked)"++if assert_ref_found "$CHECKBOX_REF" "checkbox ref for /checked"; then+ pt_get "/checked?ref=${CHECKBOX_REF}"+ assert_ok "get checked state"+ assert_json_eq "$RESULT" '.ref' "$CHECKBOX_REF" "ref echoed back"+ assert_json_eq "$RESULT" '.checked' 'false' "checkbox is not checked"+fi++end_test++# ─────────────────────────────────────────────────────────────────+start_test "inspect: GET /value missing ref returns 400"++pt_get "/value"+assert_http_status "400" "missing ref returns 400"++end_test++# ─────────────────────────────────────────────────────────────────+start_test "inspect: DELETE /cookies clears cookies"++pt_delete /cookies+assert_ok "clear cookies"+assert_json_eq "$RESULT" '.status' 'cleared' "cookies status cleared"++end_testdiff --git a/tests/tools/docker-compose.yml b/tests/tools/docker-compose.ymlindex 2bc72037..eb039bfc 100644--- a/tests/tools/docker-compose.yml+++ b/tests/tools/docker-compose.yml@@ -17,7 +17,7 @@ services:- ./config/pinchtab.json:/fixture-config/pinchtab.json:ro- ./config/pinchtab-benchmark.json:/fixture-config/pinchtab-benchmark.json:roports:- - "9867:9867"+ - "127.0.0.1:9867:9867"shm_size: '2gb'dns:- 8.8.8.8@@ -39,7 +39,7 @@ services:volumes:- ./fixtures:/usr/share/nginx/html:roports:- - "8080:80"+ - "127.0.0.1:8080:80"healthcheck:test: ["CMD-SHELL", "wget -q -O /dev/null http://localhost:80/"]interval: 2s