High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: add check/uncheck CLI commands for checkboxes and radios (#295) (#297)
Alice Losasso0e5f49061cd1
diff --git a/cmd/pinchtab/cmd_cli.go b/cmd/pinchtab/cmd_cli.goindex dd1abf65..dbe1fec7 100644--- a/cmd/pinchtab/cmd_cli.go+++ b/cmd/pinchtab/cmd_cli.go@@ -331,6 +331,30 @@ var selectCmd = &cobra.Command{},}+var checkCmd = &cobra.Command{+ Use: "check <selector>",+ Short: "Check a checkbox or radio",+ Args: cobra.ExactArgs(1),+ Run: func(cmd *cobra.Command, args []string) {+ cfg := config.Load()+ runCLIWith(cfg, func(client *http.Client, base, token string) {+ browseractions.Action(client, base, token, "check", args[0], cmd)+ })+ },+}++var uncheckCmd = &cobra.Command{+ Use: "uncheck <selector>",+ Short: "Uncheck a checkbox or radio",+ Args: cobra.ExactArgs(1),+ Run: func(cmd *cobra.Command, args []string) {+ cfg := config.Load()+ runCLIWith(cfg, func(client *http.Client, base, token string) {+ browseractions.Action(client, base, token, "uncheck", args[0], cmd)+ })+ },+}+func init() {quickCmd.GroupID = "browser"navCmd.GroupID = "browser"@@ -356,6 +380,8 @@ func init() {uploadCmd.GroupID = "browser"findCmd.GroupID = "browser"selectCmd.GroupID = "browser"+ checkCmd.GroupID = "browser"+ uncheckCmd.GroupID = "browser"tabsCmd.AddCommand(&cobra.Command{Use: "new [url]",@@ -456,6 +482,8 @@ func init() {scrollCmd.Flags().String("tab", "", "Tab ID")selectCmd.Flags().String("tab", "", "Tab ID")evalCmd.Flags().String("tab", "", "Tab ID")+ checkCmd.Flags().String("tab", "", "Tab ID")+ uncheckCmd.Flags().String("tab", "", "Tab ID")rootCmd.AddCommand(quickCmd)rootCmd.AddCommand(navCmd)@@ -482,6 +510,8 @@ func init() {rootCmd.AddCommand(uploadCmd)rootCmd.AddCommand(findCmd)rootCmd.AddCommand(selectCmd)+ rootCmd.AddCommand(checkCmd)+ rootCmd.AddCommand(uncheckCmd)instanceCmd.GroupID = "management"diff --git a/internal/bridge/actions.go b/internal/bridge/actions.goindex f782d0f0..c55598b6 100644--- a/internal/bridge/actions.go+++ b/internal/bridge/actions.go@@ -25,6 +25,8 @@ const (ActionDrag = "drag"ActionHumanClick = "humanClick"ActionHumanType = "humanType"+ ActionCheck = "check"+ ActionUncheck = "uncheck")func (b *Bridge) InitActionRegistry() {@@ -239,7 +241,135 @@ func (b *Bridge) InitActionRegistry() {return map[string]any{"typed": req.Text, "human": true}, nil},+ ActionCheck: func(ctx context.Context, req ActionRequest) (map[string]any, error) {+ return checkUncheck(ctx, req, true)+ },+ ActionUncheck: func(ctx context.Context, req ActionRequest) (map[string]any, error) {+ return checkUncheck(ctx, req, false)+ },+ }+}++// checkUncheck implements both check and uncheck actions.+// If wantChecked is true, it ensures the element is checked; if false, unchecked.+// It only clicks if the current state differs from the desired state.+func checkUncheck(ctx context.Context, req ActionRequest, wantChecked bool) (map[string]any, error) {+ // Resolve the element to an objectId via backendNodeId or CSS selector.+ var resolveJS string+ if req.NodeID > 0 {+ // Resolve via backendNodeId using DOM.resolveNode (done below).+ } else if req.Selector != "" {+ resolveJS = req.Selector+ } else {+ return nil, fmt.Errorf("need selector, ref, or nodeId")+ }++ var objectID string+ err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ if req.NodeID > 0 {+ var result json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{+ "backendNodeId": req.NodeID,+ }, &result); err != nil {+ return err+ }+ var resolved struct {+ Object struct {+ ObjectID string `json:"objectId"`+ } `json:"object"`+ }+ if err := json.Unmarshal(result, &resolved); err != nil {+ return err+ }+ objectID = resolved.Object.ObjectID+ return nil+ }+ // CSS selector path+ var evalResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.evaluate", map[string]any{+ "expression": fmt.Sprintf(`document.querySelector(%q)`, resolveJS),+ "returnByValue": false,+ }, &evalResult); err != nil {+ return err+ }+ var er struct {+ Result struct {+ ObjectID string `json:"objectId"`+ Type string `json:"type"`+ Subtype string `json:"subtype"`+ } `json:"result"`+ }+ if err := json.Unmarshal(evalResult, &er); err != nil {+ return err+ }+ if er.Result.ObjectID == "" || er.Result.Subtype == "null" {+ return fmt.Errorf("element not found: %s", resolveJS)+ }+ objectID = er.Result.ObjectID+ return nil+ }))+ if err != nil {+ return nil, err+ }++ // Validate element is a checkbox or radio, and read current checked state.+ var isChecked bool+ err = chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ js := `function() {+ var tag = this.tagName ? this.tagName.toLowerCase() : "";+ var type = (this.type || "").toLowerCase();+ if (tag !== "input" || (type !== "checkbox" && type !== "radio")) {+ return {error: "element is not a checkbox or radio input (got " + tag + "[type=" + type + "])"};+ }+ return {checked: this.checked};+ }`+ var callResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{+ "functionDeclaration": js,+ "objectId": objectID,+ "returnByValue": true,+ }, &callResult); err != nil {+ return err+ }+ var cr struct {+ Result struct {+ Value json.RawMessage `json:"value"`+ } `json:"result"`+ }+ if err := json.Unmarshal(callResult, &cr); err != nil {+ return err+ }+ var val struct {+ Error string `json:"error"`+ Checked bool `json:"checked"`+ }+ if err := json.Unmarshal(cr.Result.Value, &val); err != nil {+ return err+ }+ if val.Error != "" {+ return fmt.Errorf("%s", val.Error)+ }+ isChecked = val.Checked+ return nil+ }))+ if err != nil {+ return nil, err+ }++ // Click only if state needs to change.+ if isChecked != wantChecked {+ if req.NodeID > 0 {+ if err := ClickByNodeID(ctx, req.NodeID); err != nil {+ return nil, err+ }+ } else {+ if err := chromedp.Run(ctx, chromedp.Click(req.Selector, chromedp.ByQuery)); err != nil {+ return nil, err+ }+ }}++ return map[string]any{"checked": wantChecked}, nil}// ResolveXPathToNodeID resolves an XPath expression to a backend node IDdiff --git a/internal/bridge/actions_test.go b/internal/bridge/actions_test.goindex 0b4d6776..2c76d0b9 100644--- a/internal/bridge/actions_test.go+++ b/internal/bridge/actions_test.go@@ -53,6 +53,73 @@ func TestHoverAction_UsesCoordinatePath(t *testing.T) {}}+func TestCheckAction_Registered(t *testing.T) {+ b := New(context.TODO(), nil, &config.RuntimeConfig{})+ if _, ok := b.Actions[ActionCheck]; !ok {+ t.Fatal("ActionCheck not registered in action registry")+ }+}++func TestUncheckAction_Registered(t *testing.T) {+ b := New(context.TODO(), nil, &config.RuntimeConfig{})+ if _, ok := b.Actions[ActionUncheck]; !ok {+ t.Fatal("ActionUncheck not registered in action registry")+ }+}++func TestCheckAction_RequiresSelectorOrRef(t *testing.T) {+ b := New(context.TODO(), nil, &config.RuntimeConfig{})+ _, err := b.Actions[ActionCheck](context.Background(), ActionRequest{})+ if err == nil {+ t.Fatal("expected error when no selector/ref/nodeId provided")+ }+ if !strings.Contains(err.Error(), "need selector") {+ t.Fatalf("expected 'need selector' error, got: %v", err)+ }+}++func TestUncheckAction_RequiresSelectorOrRef(t *testing.T) {+ b := New(context.TODO(), nil, &config.RuntimeConfig{})+ _, err := b.Actions[ActionUncheck](context.Background(), ActionRequest{})+ if err == nil {+ t.Fatal("expected error when no selector/ref/nodeId provided")+ }+ if !strings.Contains(err.Error(), "need selector") {+ t.Fatalf("expected 'need selector' error, got: %v", err)+ }+}++func TestCheckAction_WithNodeID_UsesResolveNode(t *testing.T) {+ b := New(context.TODO(), nil, &config.RuntimeConfig{})++ ctx, cancel := context.WithCancel(context.Background())+ cancel()++ _, err := b.Actions[ActionCheck](ctx, ActionRequest{NodeID: 42})+ if err == nil {+ t.Fatal("expected error from cancelled context")+ }+ // Should NOT be a validation error — it should attempt the CDP path+ if strings.Contains(err.Error(), "need selector") {+ t.Fatalf("expected CDP path, got validation error: %v", err)+ }+}++func TestUncheckAction_WithSelector_UsesCSSPath(t *testing.T) {+ b := New(context.TODO(), nil, &config.RuntimeConfig{})++ ctx, cancel := context.WithCancel(context.Background())+ cancel()++ _, err := b.Actions[ActionUncheck](ctx, ActionRequest{Selector: "#my-checkbox"})+ if err == nil {+ t.Fatal("expected error from cancelled context")+ }+ if strings.Contains(err.Error(), "need selector") {+ t.Fatalf("expected CSS path, got validation error: %v", err)+ }+}+func TestXpathString(t *testing.T) {tests := []struct {input stringdiff --git a/internal/cli/actions/actions_element_test.go b/internal/cli/actions/actions_element_test.goindex b1b72dfa..99f9fe61 100644--- a/internal/cli/actions/actions_element_test.go+++ b/internal/cli/actions/actions_element_test.go@@ -236,6 +236,94 @@ func TestScroll(t *testing.T) {}}+func TestCheck(t *testing.T) {+ m := newMockServer()+ defer m.close()+ client := m.server.Client()++ cmd := newActionCmd()+ Action(client, m.base(), "", "check", "e7", cmd)+ if m.lastPath != "/action" {+ t.Errorf("expected /action, got %s", m.lastPath)+ }+ var body map[string]any+ _ = json.Unmarshal([]byte(m.lastBody), &body)+ if body["kind"] != "check" {+ t.Errorf("expected kind=check, got %v", body["kind"])+ }+ if body["ref"] != "e7" {+ t.Errorf("expected ref=e7, got %v", body["ref"])+ }+ if _, hasSelector := body["selector"]; hasSelector {+ t.Error("should not set selector when using ref")+ }+}++func TestCheckWithCSS(t *testing.T) {+ m := newMockServer()+ defer m.close()+ client := m.server.Client()++ cmd := newActionCmd()+ _ = cmd.Flags().Set("css", "input[type=checkbox]")+ Action(client, m.base(), "", "check", "", cmd)+ var body map[string]any+ _ = json.Unmarshal([]byte(m.lastBody), &body)+ if body["kind"] != "check" {+ t.Errorf("expected kind=check, got %v", body["kind"])+ }+ if body["selector"] != "input[type=checkbox]" {+ t.Errorf("expected selector=input[type=checkbox], got %v", body["selector"])+ }+ if _, hasRef := body["ref"]; hasRef {+ t.Error("should not set ref when --css is provided")+ }+}++func TestUncheck(t *testing.T) {+ m := newMockServer()+ defer m.close()+ client := m.server.Client()++ cmd := newActionCmd()+ Action(client, m.base(), "", "uncheck", "e9", cmd)+ if m.lastPath != "/action" {+ t.Errorf("expected /action, got %s", m.lastPath)+ }+ var body map[string]any+ _ = json.Unmarshal([]byte(m.lastBody), &body)+ if body["kind"] != "uncheck" {+ t.Errorf("expected kind=uncheck, got %v", body["kind"])+ }+ if body["ref"] != "e9" {+ t.Errorf("expected ref=e9, got %v", body["ref"])+ }+ if _, hasSelector := body["selector"]; hasSelector {+ t.Error("should not set selector when using ref")+ }+}++func TestUncheckWithCSS(t *testing.T) {+ m := newMockServer()+ defer m.close()+ client := m.server.Client()++ cmd := newActionCmd()+ _ = cmd.Flags().Set("css", "#agree-checkbox")+ Action(client, m.base(), "", "uncheck", "", cmd)+ var body map[string]any+ _ = json.Unmarshal([]byte(m.lastBody), &body)+ if body["kind"] != "uncheck" {+ t.Errorf("expected kind=uncheck, got %v", body["kind"])+ }+ if body["selector"] != "#agree-checkbox" {+ t.Errorf("expected selector=#agree-checkbox, got %v", body["selector"])+ }+ if _, hasRef := body["ref"]; hasRef {+ t.Error("should not set ref when --css is provided")+ }+}+func TestSelect(t *testing.T) {m := newMockServer()defer m.close()