High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat(bridge,handlers,plugin): improve DOM sync and add human handoff flow
Djain9122c10d01c9ae7
diff --git a/cmd/pinchtab/cmd_cli_browser_actions.go b/cmd/pinchtab/cmd_cli_browser_actions.goindex 6185485c..dfb77f95 100644--- a/cmd/pinchtab/cmd_cli_browser_actions.go+++ b/cmd/pinchtab/cmd_cli_browser_actions.go@@ -56,6 +56,19 @@ var fillCmd = newSimpleActionCmd("fill <ref|selector> <text>", "Fill input direcvar hoverCmd = newOptionalRefActionCmd("hover <ref>", "Hover element", "hover")+var mouseCmd = &cobra.Command{+ Use: "mouse",+ Short: "Low-level mouse actions (move, down, up, wheel)",+}++var mouseMoveCmd = newOptionalRefActionCmd("move [ref|selector]", "Move mouse to coordinates or element center", "mousemove")++var mouseDownCmd = newOptionalRefActionCmd("down [ref|selector]", "Press mouse button", "mousedown")++var mouseUpCmd = newOptionalRefActionCmd("up [ref|selector]", "Release mouse button", "mouseup")++var mouseWheelCmd = newOptionalRefActionCmd("wheel [ref|selector]", "Dispatch mouse wheel deltas", "mousewheel")+var focusCmd = newOptionalRefActionCmd("focus <ref>", "Focus element", "focus")var scrollCmd = newSimpleActionCmd("scroll <ref|pixels>", "Scroll to element or by pixels", "scroll", cobra.MinimumNArgs(1))diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.goindex f0e2c435..ee77e417 100644--- a/cmd/pinchtab/cmd_cli_register.go+++ b/cmd/pinchtab/cmd_cli_register.go@@ -23,6 +23,7 @@ func registerBrowserCommands() {pressCmd,fillCmd,hoverCmd,+ mouseCmd,focusCmd,scrollCmd,evalCmd,@@ -53,6 +54,7 @@ func registerBrowserCommands() {clipboardCmd.AddCommand(clipboardReadCmd, clipboardWriteCmd, clipboardCopyCmd, clipboardPasteCmd)keyboardCmd.AddCommand(keyboardTypeCmd, keyboardInsertTextCmd)dialogCmd.AddCommand(dialogAcceptCmd, dialogDismissCmd)+ mouseCmd.AddCommand(mouseMoveCmd, mouseDownCmd, mouseUpCmd, mouseWheelCmd)configureBrowserFlags()@@ -71,6 +73,7 @@ func registerBrowserCommands() {pressCmd,fillCmd,hoverCmd,+ mouseCmd,focusCmd,scrollCmd,evalCmd,@@ -123,6 +126,22 @@ func configureBrowserFlags() {hoverCmd.Flags().String("css", "", "CSS selector instead of ref")addPointFlags(hoverCmd, "hover")+ mouseMoveCmd.Flags().String("css", "", "CSS selector instead of ref")+ addPointFlags(mouseMoveCmd, "mousemove")++ mouseDownCmd.Flags().String("css", "", "CSS selector instead of ref")+ addPointFlags(mouseDownCmd, "mousedown")+ mouseDownCmd.Flags().String("button", "left", "Mouse button: left, right, middle")++ mouseUpCmd.Flags().String("css", "", "CSS selector instead of ref")+ addPointFlags(mouseUpCmd, "mouseup")+ mouseUpCmd.Flags().String("button", "left", "Mouse button: left, right, middle")++ mouseWheelCmd.Flags().String("css", "", "CSS selector instead of ref")+ addPointFlags(mouseWheelCmd, "mousewheel")+ mouseWheelCmd.Flags().Int("wheel-delta-x", 0, "Wheel delta X")+ mouseWheelCmd.Flags().Int("wheel-delta-y", 0, "Wheel delta Y")+focusCmd.Flags().String("css", "", "CSS selector instead of ref")snapCmd.Flags().BoolP("interactive", "i", false, "Filter interactive elements only")@@ -178,6 +197,10 @@ func configureBrowserFlags() {clickCmd,dblclickCmd,hoverCmd,+ mouseMoveCmd,+ mouseDownCmd,+ mouseUpCmd,+ mouseWheelCmd,focusCmd,typeCmd,pressCmd,diff --git a/cmd/pinchtab/cmd_cli_test.go b/cmd/pinchtab/cmd_cli_test.goindex 8fa7d606..9b9775e7 100644--- a/cmd/pinchtab/cmd_cli_test.go+++ b/cmd/pinchtab/cmd_cli_test.go@@ -1,6 +1,25 @@package main-import "testing"+import (+ "testing"++ "github.com/spf13/cobra"+)++func findCommand(cmd *cobra.Command, use string) *cobra.Command {+ if cmd == nil {+ return nil+ }+ if cmd.Name() == use || cmd.Use == use {+ return cmd+ }+ for _, child := range cmd.Commands() {+ if found := findCommand(child, use); found != nil {+ return found+ }+ }+ return nil+}func TestNormalizeRequiredURL(t *testing.T) {t.Run("normalizes bare hostname", func(t *testing.T) {@@ -17,3 +36,25 @@ func TestNormalizeRequiredURL(t *testing.T) {}})}++func TestMouseCommandGroupRegistered(t *testing.T) {+ m := findCommand(rootCmd, "mouse")+ if m == nil {+ t.Fatal("expected mouse command to be registered")+ }+ if m.GroupID != "browser" {+ t.Fatalf("expected mouse command group browser, got %q", m.GroupID)+ }+}++func TestMouseSubCommandsRegistered(t *testing.T) {+ m := findCommand(rootCmd, "mouse")+ if m == nil {+ t.Fatal("expected mouse command to be registered")+ }+ for _, name := range []string{"move", "down", "up", "wheel"} {+ if findCommand(m, name) == nil {+ t.Fatalf("expected mouse subcommand %q to be registered", name)+ }+ }+}diff --git a/dashboard/src/components/molecules/TabsChart.tsx b/dashboard/src/components/molecules/TabsChart.tsxindex 00f0da11..71e0ea48 100644--- a/dashboard/src/components/molecules/TabsChart.tsx+++ b/dashboard/src/components/molecules/TabsChart.tsx@@ -106,7 +106,7 @@ function GlassTooltip({return (<div- key={entry.dataKey}+ key={String(entry.dataKey)}style={{display: "flex",alignItems: "center",@@ -268,9 +268,9 @@ export default function TabsChart({return vals;}, [mergedData, instances, instanceColors]);- const tooltipContent = (props: TooltipContentProps<number, string>) => (- <GlassTooltip {...props} instances={instances} />- );+ const tooltipContent = ((props: TooltipContentProps<number, string>) => (+ <GlassTooltip {...props} instances={instances} />+ )) as any;if (mergedData.length < 2) {return (diff --git a/internal/bridge/action_pointer.go b/internal/bridge/action_pointer.goindex 9dff9beb..540b3058 100644--- a/internal/bridge/action_pointer.go+++ b/internal/bridge/action_pointer.go@@ -90,7 +90,11 @@ func (b *Bridge) actionClick(ctx context.Context, req ActionRequest) (map[string}return map[string]any{"clicked": true, "submitted": true}, nil}- err = chromedp.Run(ctx, chromedp.Click(req.Selector, chromedp.ByQuery))+ node, nodeErr := firstNodeBySelector(ctx, req.Selector)+ if nodeErr != nil {+ return nil, nodeErr+ }+ err = ClickByNodeID(ctx, int64(node.BackendNodeID))} else if req.NodeID > 0 {err = ClickByNodeID(ctx, req.NodeID)} else if req.HasXY {@@ -110,7 +114,11 @@ func (b *Bridge) actionClick(ctx context.Context, req ActionRequest) (map[stringfunc (b *Bridge) actionDoubleClick(ctx context.Context, req ActionRequest) (map[string]any, error) {var err errorif req.Selector != "" {- err = chromedp.Run(ctx, chromedp.DoubleClick(req.Selector, chromedp.ByQuery))+ node, nodeErr := firstNodeBySelector(ctx, req.Selector)+ if nodeErr != nil {+ return nil, nodeErr+ }+ err = DoubleClickByNodeID(ctx, int64(node.BackendNodeID))} else if req.NodeID > 0 {err = DoubleClickByNodeID(ctx, req.NodeID)} else if req.HasXY {@@ -141,6 +149,84 @@ func (b *Bridge) actionHover(ctx context.Context, req ActionRequest) (map[stringreturn nil, fmt.Errorf("need selector, ref, nodeId, or x/y coordinates")}+func pointerCoordinatesFromRequest(ctx context.Context, req ActionRequest) (float64, float64, error) {+ if req.HasXY {+ return req.X, req.Y, nil+ }+ if req.NodeID > 0 {+ return PointerPointForNode(ctx, req.NodeID, false)+ }+ if req.Selector != "" {+ node, err := firstNodeBySelector(ctx, req.Selector)+ if err != nil {+ return 0, 0, err+ }+ return PointerPointForNode(ctx, int64(node.BackendNodeID), false)+ }+ return 0, 0, fmt.Errorf("need selector, ref, nodeId, or x/y coordinates")+}++func (b *Bridge) actionMouseMove(ctx context.Context, req ActionRequest) (map[string]any, error) {+ x, y, err := pointerCoordinatesFromRequest(ctx, req)+ if err != nil {+ return nil, err+ }+ if err := MouseMoveByCoordinate(ctx, x, y); err != nil {+ return nil, err+ }+ return map[string]any{"moved": true, "x": x, "y": y}, nil+}++func (b *Bridge) actionMouseDown(ctx context.Context, req ActionRequest) (map[string]any, error) {+ x, y, err := pointerCoordinatesFromRequest(ctx, req)+ if err != nil {+ return nil, err+ }+ button := req.Button+ if button == "" {+ button = "left"+ }+ if err := MouseDownByCoordinate(ctx, x, y, button); err != nil {+ return nil, err+ }+ return map[string]any{"down": true, "x": x, "y": y, "button": button}, nil+}++func (b *Bridge) actionMouseUp(ctx context.Context, req ActionRequest) (map[string]any, error) {+ x, y, err := pointerCoordinatesFromRequest(ctx, req)+ if err != nil {+ return nil, err+ }+ button := req.Button+ if button == "" {+ button = "left"+ }+ if err := MouseUpByCoordinate(ctx, x, y, button); err != nil {+ return nil, err+ }+ return map[string]any{"up": true, "x": x, "y": y, "button": button}, nil+}++func (b *Bridge) actionMouseWheel(ctx context.Context, req ActionRequest) (map[string]any, error) {+ x, y, err := pointerCoordinatesFromRequest(ctx, req)+ if err != nil {+ return nil, err+ }+ deltaX := req.WheelDeltaX+ deltaY := req.WheelDeltaY+ if deltaX == 0 && deltaY == 0 {+ deltaX = req.ScrollX+ deltaY = req.ScrollY+ }+ if deltaX == 0 && deltaY == 0 {+ deltaY = 800+ }+ if err := scrollByCoordinateAction(ctx, x, y, deltaX, deltaY); err != nil {+ return nil, err+ }+ return map[string]any{"wheel": true, "x": x, "y": y, "deltaX": deltaX, "deltaY": deltaY}, nil+}+func (b *Bridge) actionScroll(ctx context.Context, req ActionRequest) (map[string]any, error) {if req.NodeID > 0 {return map[string]any{"scrolled": true}, ScrollByNodeID(ctx, req.NodeID)diff --git a/internal/bridge/action_registry.go b/internal/bridge/action_registry.goindex 18cfaf6b..bae656c1 100644--- a/internal/bridge/action_registry.go+++ b/internal/bridge/action_registry.go@@ -10,6 +10,10 @@ const (ActionHover = "hover"ActionSelect = "select"ActionScroll = "scroll"+ ActionMouseMove = "mousemove"+ ActionMouseDown = "mousedown"+ ActionMouseUp = "mouseup"+ ActionMouseWheel = "mousewheel"ActionDrag = "drag"ActionHumanClick = "humanClick"ActionHumanType = "humanType"@@ -33,6 +37,10 @@ func (b *Bridge) InitActionRegistry() {ActionHover: b.actionHover,ActionSelect: b.actionSelect,ActionScroll: b.actionScroll,+ ActionMouseMove: b.actionMouseMove,+ ActionMouseDown: b.actionMouseDown,+ ActionMouseUp: b.actionMouseUp,+ ActionMouseWheel: b.actionMouseWheel,ActionDrag: b.actionDrag,ActionHumanClick: b.actionHumanClick,ActionHumanType: b.actionHumanType,diff --git a/internal/bridge/action_resolve.go b/internal/bridge/action_resolve.goindex 2c26d019..1c86f9fe 100644--- a/internal/bridge/action_resolve.go+++ b/internal/bridge/action_resolve.go@@ -117,22 +117,74 @@ func ResolveTextToNodeID(ctx context.Context, text string) (int64, error) {if (!root) {return null;}++ const normalize = (value) => String(value || "")+ .toLowerCase()+ .replace(/\s+/g, " ")+ .trim();++ const semanticWeight = (el) => {+ const tag = (el.tagName || "").toLowerCase();+ if (tag === "button" || tag === "a" || tag === "input") {+ return 0.25;+ }+ const role = normalize(el.getAttribute && el.getAttribute("role"));+ if (role === "button" || role === "link" || role === "textbox") {+ return 0.2;+ }+ return 0;+ };++ const needleNorm = normalize(needle);+ if (!needleNorm) {+ return null;+ }+const elements = root.querySelectorAll("*");+ let best = null;+ let bestScore = 0;+for (const el of elements) {- const text = el.innerText || "";- if (!text.includes(needle)) {+ const rawText = el.innerText || el.textContent || "";+ const textNorm = normalize(rawText);+ if (!textNorm) {continue;}- let childContainsText = false;++ let childContains = false;for (const child of el.children) {- if ((child.innerText || "").includes(needle)) {- childContainsText = true;+ const childNorm = normalize(child.innerText || child.textContent || "");+ if (childNorm && childNorm.includes(needleNorm)) {+ childContains = true;break;}}- if (!childContainsText) {++ if (textNorm.includes(needleNorm) && !childContains) {return el;}++ // Fuzzy fallback: token-overlap score with semantic weighting.+ const tokens = needleNorm.split(" ").filter(Boolean);+ if (tokens.length === 0) {+ continue;+ }+ let hits = 0;+ for (const token of tokens) {+ if (textNorm.includes(token)) {+ hits++;+ }+ }+ let score = hits / tokens.length;+ score += semanticWeight(el);+ if (score > bestScore) {+ bestScore = score;+ best = el;+ }+ }++ if (best && bestScore >= 0.7) {+ return best;}return null;}`diff --git a/internal/bridge/actions_test.go b/internal/bridge/actions_test.goindex b60e3fb9..e606b9e8 100644--- a/internal/bridge/actions_test.go+++ b/internal/bridge/actions_test.go@@ -53,6 +53,108 @@ func TestHoverAction_UsesCoordinatePath(t *testing.T) {}}+func TestMouseMoveAction_Registered(t *testing.T) {+ b := New(context.TODO(), nil, &config.RuntimeConfig{})+ if _, ok := b.Actions[ActionMouseMove]; !ok {+ t.Fatal("ActionMouseMove not registered in action registry")+ }+}++func TestMouseDownAction_Registered(t *testing.T) {+ b := New(context.TODO(), nil, &config.RuntimeConfig{})+ if _, ok := b.Actions[ActionMouseDown]; !ok {+ t.Fatal("ActionMouseDown not registered in action registry")+ }+}++func TestMouseUpAction_Registered(t *testing.T) {+ b := New(context.TODO(), nil, &config.RuntimeConfig{})+ if _, ok := b.Actions[ActionMouseUp]; !ok {+ t.Fatal("ActionMouseUp not registered in action registry")+ }+}++func TestMouseWheelAction_Registered(t *testing.T) {+ b := New(context.TODO(), nil, &config.RuntimeConfig{})+ if _, ok := b.Actions[ActionMouseWheel]; !ok {+ t.Fatal("ActionMouseWheel not registered in action registry")+ }+}++func TestMouseDownAction_UsesCoordinatePath(t *testing.T) {+ b := New(context.TODO(), nil, &config.RuntimeConfig{})++ ctx, cancel := context.WithCancel(context.Background())+ cancel()++ _, err := b.Actions[ActionMouseDown](ctx, ActionRequest{HasXY: true, X: 0, Y: 0, Button: "right"})+ if err == nil {+ t.Fatal("expected error from cancelled context")+ }+ if strings.Contains(err.Error(), "need selector") {+ t.Fatalf("expected coordinate path, got selector/ref validation error: %v", err)+ }+}++func TestMouseUpAction_UsesCoordinatePath(t *testing.T) {+ b := New(context.TODO(), nil, &config.RuntimeConfig{})++ ctx, cancel := context.WithCancel(context.Background())+ cancel()++ _, err := b.Actions[ActionMouseUp](ctx, ActionRequest{HasXY: true, X: 0, Y: 0})+ if err == nil {+ t.Fatal("expected error from cancelled context")+ }+ if strings.Contains(err.Error(), "need selector") {+ t.Fatalf("expected coordinate path, got selector/ref validation error: %v", err)+ }+}++func TestMouseWheelAction_UsesExplicitWheelDeltas(t *testing.T) {+ b := New(context.TODO(), nil, &config.RuntimeConfig{})++ origScrollByCoordinate := scrollByCoordinateAction+ origScrollViewportCenter := scrollViewportCenter+ t.Cleanup(func() {+ scrollByCoordinateAction = origScrollByCoordinate+ scrollViewportCenter = origScrollViewportCenter+ })++ called := false+ scrollByCoordinateAction = func(ctx context.Context, x, y float64, deltaX, deltaY int) error {+ called = true+ if x != 50 || y != 75 {+ t.Fatalf("wheel coordinates = (%v, %v), want (50, 75)", x, y)+ }+ if deltaX != 123 || deltaY != -456 {+ t.Fatalf("wheel delta = (%d, %d), want (123, -456)", deltaX, deltaY)+ }+ return nil+ }+ scrollViewportCenter = func(context.Context) (float64, float64, error) {+ t.Fatal("viewport center should not be used when explicit coordinates are provided")+ return 0, 0, nil+ }++ res, err := b.Actions[ActionMouseWheel](context.Background(), ActionRequest{+ HasXY: true,+ X: 50,+ Y: 75,+ WheelDeltaX: 123,+ WheelDeltaY: -456,+ })+ if err != nil {+ t.Fatalf("mouse wheel returned error: %v", err)+ }+ if !called {+ t.Fatal("expected wheel path to be used")+ }+ if !res["wheel"].(bool) {+ t.Fatalf("expected wheel=true in result payload, got %#v", res)+ }+}+func TestScrollAction_UsesCoordinateWheelPath(t *testing.T) {b := New(context.TODO(), nil, &config.RuntimeConfig{})diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.goindex 03db9d10..3f03a1b9 100644--- a/internal/bridge/bridge.go+++ b/internal/bridge/bridge.go@@ -55,6 +55,8 @@ type Bridge struct {fingerprintMu sync.RWMutexfingerprintOverlays map[string]boolworkerStealthTargets sync.Map+ handoffMu sync.RWMutex+ handoffs map[string]TabHandoffState// Lazy initialization / restart coordinationinitMu sync.Mutex@@ -83,6 +85,7 @@ func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *BridgIdMgr: idMgr,netMonitor: NewNetworkMonitor(netBufSize),fingerprintOverlays: make(map[string]bool),+ handoffs: make(map[string]TabHandoffState),LogStore: logStore,stealthLaunchMode: stealth.LaunchModeUninitialized,}@@ -616,14 +619,19 @@ type ActionRequest struct {Value string `json:"value"`NodeID int64 `json:"nodeId"`- X float64 `json:"x"`- Y float64 `json:"y"`- HasXY bool `json:"hasXY,omitempty"`+ X float64 `json:"x"`+ Y float64 `json:"y"`+ HasXY bool `json:"hasXY,omitempty"`+ Button string `json:"button,omitempty"`ScrollX int `json:"scrollX"`ScrollY int `json:"scrollY"`- DragX int `json:"dragX"`- DragY int `json:"dragY"`+ // WheelDeltaX/WheelDeltaY are explicit mouse-wheel deltas for low-level+ // mousewheel actions. ScrollX/ScrollY remain for backward compatibility.+ WheelDeltaX int `json:"wheelDeltaX,omitempty"`+ WheelDeltaY int `json:"wheelDeltaY,omitempty"`+ DragX int `json:"dragX"`+ DragY int `json:"dragY"`WaitNav bool `json:"waitNav"`Fast bool `json:"fast"`diff --git a/internal/bridge/cdp_geometry_test.go b/internal/bridge/cdp_geometry_test.goindex f9fc6da7..9911791d 100644--- a/internal/bridge/cdp_geometry_test.go+++ b/internal/bridge/cdp_geometry_test.go@@ -35,3 +35,13 @@ func TestGetElementCenterJS_ContextCancelled(t *testing.T) {t.Error("expected error for cancelled context, got nil")}}++func TestPointerPointForNode_ContextCancelled(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ cancel()++ _, _, err := PointerPointForNode(ctx, 1, true)+ if err == nil {+ t.Error("expected error for cancelled context, got nil")+ }+}diff --git a/internal/bridge/cdp_pointer_test.go b/internal/bridge/cdp_pointer_test.goindex 0dd524c7..19859ffe 100644--- a/internal/bridge/cdp_pointer_test.go+++ b/internal/bridge/cdp_pointer_test.go@@ -25,6 +25,46 @@ func TestHoverByCoordinate_ContextCancelled(t *testing.T) {}}+func TestMouseMoveByCoordinate_ContextCancelled(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ cancel()++ err := MouseMoveByCoordinate(ctx, 10, 20)+ if err == nil {+ t.Fatal("expected error for cancelled context")+ }+}++func TestMouseDownByCoordinate_ContextCancelled(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ cancel()++ err := MouseDownByCoordinate(ctx, 10, 20, "left")+ if err == nil {+ t.Fatal("expected error for cancelled context")+ }+}++func TestMouseUpByCoordinate_ContextCancelled(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ cancel()++ err := MouseUpByCoordinate(ctx, 10, 20, "left")+ if err == nil {+ t.Fatal("expected error for cancelled context")+ }+}++func TestMouseWheelByCoordinate_ContextCancelled(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ cancel()++ err := MouseWheelByCoordinate(ctx, 10, 20, 0, 120)+ if err == nil {+ t.Fatal("expected error for cancelled context")+ }+}+func TestDoubleClickByCoordinate_ContextCancelled(t *testing.T) {ctx, cancel := context.WithCancel(context.Background())cancel()@@ -56,4 +96,16 @@ func TestCoordinateActions_RejectNegativeCoordinates(t *testing.T) {if err := HoverByCoordinate(ctx, 0, -1); err == nil {t.Fatal("expected hover negative coordinate to fail")}+ if err := MouseMoveByCoordinate(ctx, -1, 0); err == nil {+ t.Fatal("expected mouse move negative coordinate to fail")+ }+ if err := MouseDownByCoordinate(ctx, 0, -1, "right"); err == nil {+ t.Fatal("expected mouse down negative coordinate to fail")+ }+ if err := MouseUpByCoordinate(ctx, -1, 0, "middle"); err == nil {+ t.Fatal("expected mouse up negative coordinate to fail")+ }+ if err := MouseWheelByCoordinate(ctx, 0, -1, 0, 100); err == nil {+ t.Fatal("expected mouse wheel negative coordinate to fail")+ }}diff --git a/internal/bridge/cdpops/pointer.go b/internal/bridge/cdpops/pointer.goindex bbb2b4e8..5dc4b7d1 100644--- a/internal/bridge/cdpops/pointer.go+++ b/internal/bridge/cdpops/pointer.go@@ -4,47 +4,114 @@ import ("context""fmt""math"+ "strings""github.com/chromedp/chromedp")-func ClickByCoordinate(ctx context.Context, x, y float64) error {+func normalizeMouseButton(button string) string {+ switch strings.ToLower(strings.TrimSpace(button)) {+ case "right":+ return "right"+ case "middle":+ return "middle"+ default:+ return "left"+ }+}++func validatePointerCoordinates(x, y float64) error {if x < 0 || y < 0 {return fmt.Errorf("x/y coordinates must be >= 0")}+ return nil+}++func dispatchMouseEvent(ctx context.Context, payload map[string]any) error {+ return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", payload, nil)+ }))+}++func MouseMoveByCoordinate(ctx context.Context, x, y float64) error {+ if err := validatePointerCoordinates(x, y); err != nil {+ return err+ }+ return dispatchMouseEvent(ctx, map[string]any{+ "type": "mouseMoved",+ "x": x,+ "y": y,+ })+}++func MouseDownByCoordinate(ctx context.Context, x, y float64, button string) error {+ if err := validatePointerCoordinates(x, y); err != nil {+ return err+ }+ return dispatchMouseEvent(ctx, map[string]any{+ "type": "mousePressed",+ "button": normalizeMouseButton(button),+ "clickCount": 1,+ "x": x,+ "y": y,+ })+}++func MouseUpByCoordinate(ctx context.Context, x, y float64, button string) error {+ if err := validatePointerCoordinates(x, y); err != nil {+ return err+ }+ return dispatchMouseEvent(ctx, map[string]any{+ "type": "mouseReleased",+ "button": normalizeMouseButton(button),+ "clickCount": 1,+ "x": x,+ "y": y,+ })+}++func MouseWheelByCoordinate(ctx context.Context, x, y float64, deltaX, deltaY int) error {+ if err := validatePointerCoordinates(x, y); err != nil {+ return err+ }return chromedp.Run(ctx,chromedp.ActionFunc(func(ctx context.Context) error {return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{- "type": "mousePressed",- "button": "left",- "clickCount": 1,- "x": x,- "y": y,+ "type": "mouseMoved",+ "x": x,+ "y": y,}, nil)}),chromedp.ActionFunc(func(ctx context.Context) error {return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{- "type": "mouseReleased",- "button": "left",- "clickCount": 1,- "x": x,- "y": y,+ "type": "mouseWheel",+ "x": x,+ "y": y,+ "deltaX": deltaX,+ "deltaY": deltaY,}, nil)}),)}+func ClickByCoordinate(ctx context.Context, x, y float64) error {+ if err := validatePointerCoordinates(x, y); err != nil {+ return err+ }+ if err := MouseDownByCoordinate(ctx, x, y, "left"); err != nil {+ return err+ }+ return MouseUpByCoordinate(ctx, x, y, "left")+}+func ClickByNodeID(ctx context.Context, nodeID int64) error {- x, y, err := GetElementCenter(ctx, nodeID)+ x, y, err := PointerPointForNode(ctx, nodeID, true)if err != nil {return err}return chromedp.Run(ctx,- chromedp.ActionFunc(func(ctx context.Context) error {- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)- }),chromedp.ActionFunc(func(ctx context.Context) error {return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)}),@@ -68,8 +135,8 @@ func ClickByNodeID(ctx context.Context, nodeID int64) error {}func DoubleClickByCoordinate(ctx context.Context, x, y float64) error {- if x < 0 || y < 0 {- return fmt.Errorf("x/y coordinates must be >= 0")+ if err := validatePointerCoordinates(x, y); err != nil {+ return err}return chromedp.Run(ctx,@@ -95,15 +162,12 @@ func DoubleClickByCoordinate(ctx context.Context, x, y float64) error {}func DoubleClickByNodeID(ctx context.Context, nodeID int64) error {- x, y, err := GetElementCenter(ctx, nodeID)+ x, y, err := PointerPointForNode(ctx, nodeID, true)if err != nil {return err}return chromedp.Run(ctx,- chromedp.ActionFunc(func(ctx context.Context) error {- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)- }),chromedp.ActionFunc(func(ctx context.Context) error {return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)}),@@ -128,7 +192,7 @@ func DoubleClickByNodeID(ctx context.Context, nodeID int64) error {// DragByNodeID drags an element by (dx, dy) pixels using mousePressed → mouseMoved → mouseReleased.func DragByNodeID(ctx context.Context, nodeID int64, dx, dy int) error {- x, y, err := GetElementCenter(ctx, nodeID)+ x, y, err := PointerPointForNode(ctx, nodeID, true)if err != nil {return err}@@ -145,9 +209,6 @@ func DragByNodeID(ctx context.Context, nodeID int64, dx, dy int) error {}return chromedp.Run(ctx,- chromedp.ActionFunc(func(ctx context.Context) error {- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)- }),chromedp.ActionFunc(func(ctx context.Context) error {return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{"type": "mouseMoved",@@ -189,54 +250,20 @@ func DragByNodeID(ctx context.Context, nodeID int64, dx, dy int) error {}func HoverByCoordinate(ctx context.Context, x, y float64) error {- if x < 0 || y < 0 {- return fmt.Errorf("x/y coordinates must be >= 0")- }-- return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{- "type": "mouseMoved",- "x": x,- "y": y,- }, nil)- }))+ return MouseMoveByCoordinate(ctx, x, y)}func ScrollByCoordinate(ctx context.Context, x, y float64, deltaX, deltaY int) error {- if x < 0 || y < 0 {- return fmt.Errorf("x/y coordinates must be >= 0")- }-- return chromedp.Run(ctx,- chromedp.ActionFunc(func(ctx context.Context) error {- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{- "type": "mouseMoved",- "x": x,- "y": y,- }, nil)- }),- chromedp.ActionFunc(func(ctx context.Context) error {- return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{- "type": "mouseWheel",- "x": x,- "y": y,- "deltaX": deltaX,- "deltaY": deltaY,- }, nil)- }),- )+ return MouseWheelByCoordinate(ctx, x, y, deltaX, deltaY)}func HoverByNodeID(ctx context.Context, nodeID int64) error {- x, y, err := GetElementCenter(ctx, nodeID)+ x, y, err := PointerPointForNode(ctx, nodeID, true)if err != nil {return err}return chromedp.Run(ctx,- chromedp.ActionFunc(func(ctx context.Context) error {- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)- }),chromedp.ActionFunc(func(ctx context.Context) error {return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{"type": "mouseMoved",diff --git a/internal/bridge/cdpops/validation.go b/internal/bridge/cdpops/validation.gonew file mode 100644index 00000000..d636a090--- /dev/null+++ b/internal/bridge/cdpops/validation.go@@ -0,0 +1,128 @@+package cdpops++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "strings"++ "github.com/chromedp/chromedp"+)++var (+ ErrElementOccluded = errors.New("element is occluded")+ ErrElementHidden = errors.New("element is hidden")+ ErrElementBlocked = errors.New("element is blocked from pointer interaction")+ ErrElementOffscreen = errors.New("element center is outside viewport")+)++type pointerProbe struct {+ X float64 `json:"x"`+ Y float64 `json:"y"`+ Width float64 `json:"width"`+ Height float64 `json:"height"`+ InViewport bool `json:"inViewport"`+ Visible bool `json:"visible"`+ PointerEvent string `json:"pointerEvent"`+ Occluded bool `json:"occluded"`+ TopTag string `json:"topTag"`+}++// PointerPointForNode validates clickability assumptions and returns a+// stable pointer coordinate for the backend node.+func PointerPointForNode(ctx context.Context, backendNodeID int64, requireTopMost bool) (float64, float64, error) {+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": backendNodeID}, nil)+ })); err != nil {+ return 0, 0, fmt.Errorf("scroll into view: %w", err)+ }++ var resolveResult json.RawMessage+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{+ "backendNodeId": backendNodeID,+ }, &resolveResult)+ })); err != nil {+ return 0, 0, 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 0, 0, err+ }+ if strings.TrimSpace(resolved.Object.ObjectID) == "" {+ return 0, 0, fmt.Errorf("resolve node: backend node %d not found", backendNodeID)+ }++ const probeJS = `function() {+ const r = this.getBoundingClientRect();+ const style = window.getComputedStyle(this);+ const x = r.left + (r.width / 2);+ const y = r.top + (r.height / 2);+ const inViewport = x >= 0 && y >= 0 && x <= window.innerWidth && y <= window.innerHeight;+ const visible = !!style && style.display !== 'none' && style.visibility !== 'hidden' && Number(style.opacity || '1') > 0;+ const pointerEvent = style ? String(style.pointerEvents || '') : '';+ let occluded = false;+ let topTag = '';+ if (inViewport) {+ const top = document.elementFromPoint(x, y);+ if (top) {+ topTag = String(top.tagName || '').toLowerCase();+ const related = top === this || this.contains(top) || top.contains(this);+ occluded = !related;+ }+ }+ return {+ x,+ y,+ width: r.width,+ height: r.height,+ inViewport,+ visible,+ pointerEvent,+ occluded,+ topTag+ };+ }`++ var probeRaw json.RawMessage+ if err := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", map[string]any{+ "functionDeclaration": probeJS,+ "objectId": resolved.Object.ObjectID,+ "returnByValue": true,+ }, &probeRaw)+ })); err != nil {+ return 0, 0, fmt.Errorf("pointer probe: %w", err)+ }++ var callRes struct {+ Result struct {+ Value pointerProbe `json:"value"`+ } `json:"result"`+ }+ if err := json.Unmarshal(probeRaw, &callRes); err != nil {+ return 0, 0, err+ }+ probe := callRes.Result.Value++ if probe.Width <= 0 || probe.Height <= 0 || !probe.Visible {+ return 0, 0, fmt.Errorf("%w: width=%.2f height=%.2f", ErrElementHidden, probe.Width, probe.Height)+ }+ if !probe.InViewport {+ return 0, 0, fmt.Errorf("%w: x=%.2f y=%.2f", ErrElementOffscreen, probe.X, probe.Y)+ }+ if strings.EqualFold(strings.TrimSpace(probe.PointerEvent), "none") {+ return 0, 0, fmt.Errorf("%w: pointer-events=none", ErrElementBlocked)+ }+ if requireTopMost && probe.Occluded {+ return 0, 0, fmt.Errorf("%w: top=%s", ErrElementOccluded, probe.TopTag)+ }++ return probe.X, probe.Y, nil+}diff --git a/internal/bridge/cdpops_facade.go b/internal/bridge/cdpops_facade.goindex 865a7b4a..a8d3dd04 100644--- a/internal/bridge/cdpops_facade.go+++ b/internal/bridge/cdpops_facade.go@@ -13,6 +13,10 @@ var (ImageBlockPatterns = bridgecdpops.ImageBlockPatternsMediaBlockPatterns = bridgecdpops.MediaBlockPatternsErrTooManyRedirects = bridgecdpops.ErrTooManyRedirects+ ErrElementOccluded = bridgecdpops.ErrElementOccluded+ ErrElementHidden = bridgecdpops.ErrElementHidden+ ErrElementBlocked = bridgecdpops.ErrElementBlocked+ ErrElementOffscreen = bridgecdpops.ErrElementOffscreen)func NavigatePage(ctx context.Context, url string) error {@@ -43,6 +47,10 @@ func ScrollIntoViewAndGetBox(ctx context.Context, nodeID int64) (map[string]any,return bridgecdpops.ScrollIntoViewAndGetBox(ctx, nodeID)}+func PointerPointForNode(ctx context.Context, nodeID int64, requireTopMost bool) (float64, float64, error) {+ return bridgecdpops.PointerPointForNode(ctx, nodeID, requireTopMost)+}+func ClickByCoordinate(ctx context.Context, x, y float64) error {return bridgecdpops.ClickByCoordinate(ctx, x, y)}@@ -67,6 +75,22 @@ func HoverByCoordinate(ctx context.Context, x, y float64) error {return bridgecdpops.HoverByCoordinate(ctx, x, y)}+func MouseMoveByCoordinate(ctx context.Context, x, y float64) error {+ return bridgecdpops.MouseMoveByCoordinate(ctx, x, y)+}++func MouseDownByCoordinate(ctx context.Context, x, y float64, button string) error {+ return bridgecdpops.MouseDownByCoordinate(ctx, x, y, button)+}++func MouseUpByCoordinate(ctx context.Context, x, y float64, button string) error {+ return bridgecdpops.MouseUpByCoordinate(ctx, x, y, button)+}++func MouseWheelByCoordinate(ctx context.Context, x, y float64, deltaX, deltaY int) error {+ return bridgecdpops.MouseWheelByCoordinate(ctx, x, y, deltaX, deltaY)+}+func ScrollByCoordinate(ctx context.Context, x, y float64, deltaX, deltaY int) error {return bridgecdpops.ScrollByCoordinate(ctx, x, y, deltaX, deltaY)}diff --git a/internal/bridge/handoff.go b/internal/bridge/handoff.gonew file mode 100644index 00000000..55f72adc--- /dev/null+++ b/internal/bridge/handoff.go@@ -0,0 +1,62 @@+package bridge++import (+ "fmt"+ "strings"+ "time"+)++// TabHandoffState tracks manual handoff pauses per tab.+type TabHandoffState struct {+ Status string `json:"status"`+ Reason string `json:"reason,omitempty"`+ PausedAt time.Time `json:"pausedAt"`+ LastUpdatedAt time.Time `json:"lastUpdatedAt"`+}++func (b *Bridge) SetTabHandoff(tabID, reason string) error {+ if b == nil {+ return fmt.Errorf("bridge not initialized")+ }+ if strings.TrimSpace(tabID) == "" {+ return fmt.Errorf("tab id required")+ }+ now := time.Now().UTC()+ state := TabHandoffState{+ Status: "paused_handoff",+ Reason: strings.TrimSpace(reason),+ PausedAt: now,+ LastUpdatedAt: now,+ }+ if state.Reason == "" {+ state.Reason = "manual_handoff"+ }++ b.handoffMu.Lock()+ defer b.handoffMu.Unlock()+ b.handoffs[tabID] = state+ return nil+}++func (b *Bridge) ResumeTabHandoff(tabID string) error {+ if b == nil {+ return fmt.Errorf("bridge not initialized")+ }+ if strings.TrimSpace(tabID) == "" {+ return fmt.Errorf("tab id required")+ }+ b.handoffMu.Lock()+ defer b.handoffMu.Unlock()+ delete(b.handoffs, tabID)+ return nil+}++func (b *Bridge) TabHandoffState(tabID string) (TabHandoffState, bool) {+ if b == nil {+ return TabHandoffState{}, false+ }+ b.handoffMu.RLock()+ defer b.handoffMu.RUnlock()+ state, ok := b.handoffs[tabID]+ return state, ok+}diff --git a/internal/bridge/input_human.go b/internal/bridge/input_human.goindex 96d7116a..6cde1f4c 100644--- a/internal/bridge/input_human.go+++ b/internal/bridge/input_human.go@@ -51,7 +51,9 @@ func MouseMove(ctx context.Context, fromX, fromY, toX, toY float64) error {cp2Y := fromY + (toY-fromY)*0.75 + (humanRand.Float64()-0.5)*50for i := 0; i <= steps; i++ {- t := float64(i) / float64(steps)+ rawT := float64(i) / float64(steps)+ // Ease-in-out velocity curve to avoid perfectly linear timing.+ t := 0.5 - (math.Cos(math.Pi*rawT) / 2.0)oneMinusT := 1 - tx := oneMinusT*oneMinusT*oneMinusT*fromX +@@ -79,6 +81,20 @@ func MouseMove(ctx context.Context, fromX, fromY, toX, toY float64) error {time.Sleep(delay)}+ // End-frame micro-jitter near target to emulate tiny hand stabilization.+ for i := 0; i < 2; i++ {+ jx := toX + (humanRand.Float64()-0.5)*1.2+ jy := toY + (humanRand.Float64()-0.5)*1.2+ if err := chromedp.Run(ctx,+ chromedp.ActionFunc(func(ctx context.Context) error {+ return input.DispatchMouseEvent(input.MouseMoved, jx, jy).Do(ctx)+ }),+ ); err != nil {+ return err+ }+ time.Sleep(10 * time.Millisecond)+ }+return nil}diff --git a/internal/bridge/state.go b/internal/bridge/state.goindex fa351998..318e2244 100644--- a/internal/bridge/state.go+++ b/internal/bridge/state.go@@ -22,9 +22,11 @@ var crashedPrefsReplacer = strings.NewReplacer()type TabState struct {- ID string `json:"id"`- URL string `json:"url"`- Title string `json:"title"`+ ID string `json:"id"`+ URL string `json:"url"`+ Title string `json:"title"`+ Status string `json:"status,omitempty"`+ HandoffReason string `json:"handoffReason,omitempty"`}type SessionState struct {@@ -147,10 +149,18 @@ func (b *Bridge) SaveState() {continue}seen[t.URL] = true+ status := "active"+ handoffReason := ""+ if hs, ok := b.TabHandoffState(string(t.TargetID)); ok {+ status = hs.Status+ handoffReason = hs.Reason+ }tabs = append(tabs, TabState{- ID: string(t.TargetID),- URL: t.URL,- Title: t.Title,+ ID: string(t.TargetID),+ URL: t.URL,+ Title: t.Title,+ Status: status,+ HandoffReason: handoffReason,})}diff --git a/internal/cli/actions/actions_element.go b/internal/cli/actions/actions_element.goindex 6a31ba4a..87f5c190 100644--- a/internal/cli/actions/actions_element.go+++ b/internal/cli/actions/actions_element.go@@ -26,6 +26,20 @@ func Action(client *http.Client, base, token, kind, selectorArg string, cmd *cobbody["hasXY"] = true}+ if button, _ := cmd.Flags().GetString("button"); button != "" {+ body["button"] = button+ }+ if cmd.Flags().Changed("wheel-delta-x") {+ if deltaX, err := cmd.Flags().GetInt("wheel-delta-x"); err == nil {+ body["wheelDeltaX"] = deltaX+ }+ }+ if cmd.Flags().Changed("wheel-delta-y") {+ if deltaY, err := cmd.Flags().GetInt("wheel-delta-y"); err == nil {+ body["wheelDeltaY"] = deltaY+ }+ }+if css != "" {// Explicit --css flag: send as plain CSS selectorbody["selector"] = cssdiff --git a/internal/cli/actions/actions_element_test.go b/internal/cli/actions/actions_element_test.goindex 2146c523..87b0d2bc 100644--- a/internal/cli/actions/actions_element_test.go+++ b/internal/cli/actions/actions_element_test.go@@ -12,6 +12,11 @@ func newActionCmd() *cobra.Command {cmd.Flags().String("css", "", "")cmd.Flags().Bool("wait-nav", false, "")cmd.Flags().String("tab", "", "")+ cmd.Flags().Float64("x", 0, "")+ cmd.Flags().Float64("y", 0, "")+ cmd.Flags().String("button", "", "")+ cmd.Flags().Int("wheel-delta-x", 0, "")+ cmd.Flags().Int("wheel-delta-y", 0, "")return cmd}@@ -127,6 +132,57 @@ func TestClickWithCSS_AndWaitNav(t *testing.T) {}}+func TestMouseDownIncludesButton(t *testing.T) {+ m := newMockServer()+ defer m.close()+ client := m.server.Client()++ cmd := newActionCmd()+ _ = cmd.Flags().Set("button", "right")+ _ = cmd.Flags().Set("x", "25")+ _ = cmd.Flags().Set("y", "40")++ Action(client, m.base(), "", "mousedown", "", cmd)++ var body map[string]any+ _ = json.Unmarshal([]byte(m.lastBody), &body)+ if body["kind"] != "mousedown" {+ t.Errorf("expected kind=mousedown, got %v", body["kind"])+ }+ if body["button"] != "right" {+ t.Errorf("expected button=right, got %v", body["button"])+ }+ if body["hasXY"] != true {+ t.Errorf("expected hasXY=true, got %v", body["hasXY"])+ }+}++func TestMouseWheelIncludesExplicitDeltas(t *testing.T) {+ m := newMockServer()+ defer m.close()+ client := m.server.Client()++ cmd := newActionCmd()+ _ = cmd.Flags().Set("wheel-delta-x", "120")+ _ = cmd.Flags().Set("wheel-delta-y", "-300")+ _ = cmd.Flags().Set("x", "10")+ _ = cmd.Flags().Set("y", "20")++ Action(client, m.base(), "", "mousewheel", "", cmd)++ var body map[string]any+ _ = json.Unmarshal([]byte(m.lastBody), &body)+ if body["kind"] != "mousewheel" {+ t.Errorf("expected kind=mousewheel, got %v", body["kind"])+ }+ if body["wheelDeltaX"] != float64(120) {+ t.Errorf("expected wheelDeltaX=120, got %v", body["wheelDeltaX"])+ }+ if body["wheelDeltaY"] != float64(-300) {+ t.Errorf("expected wheelDeltaY=-300, got %v", body["wheelDeltaY"])+ }+}+func TestHoverWithCSS(t *testing.T) {m := newMockServer()defer m.close()diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex f564a341..331da533 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -83,6 +83,17 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {req.HasXY = b}}+ req.Button = q.Get("button")+ if v := q.Get("wheelDeltaX"); v != "" {+ if n, err := strconv.Atoi(v); err == nil {+ req.WheelDeltaX = n+ }+ }+ if v := q.Get("wheelDeltaY"); v != "" {+ if n, err := strconv.Atoi(v); err == nil {+ req.WheelDeltaY = n+ }+ }} else {if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {httpx.Error(w, 400, fmt.Errorf("decode: %w", err))@@ -286,15 +297,19 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {return} else {result, engineName, actionErr = h.executeAction(tCtx, req)- if actionErr != nil && req.Ref != "" && shouldRetryStaleRef(actionErr) {- recordStaleRefRetry()- h.refreshRefCache(tCtx, resolvedTabID)- if cache := h.Bridge.GetRefCache(resolvedTabID); cache != nil {- if nid, ok := cache.Refs[req.Ref]; ok {- req.NodeID = nid- result, engineName, actionErr = h.executeAction(tCtx, req)+ if actionErr != nil && shouldRetryPointerAction(req, actionErr) {+ if req.Ref != "" && shouldRetryStaleRef(actionErr) {+ recordStaleRefRetry()+ h.refreshRefCache(tCtx, resolvedTabID)+ if cache := h.Bridge.GetRefCache(resolvedTabID); cache != nil {+ if nid, ok := cache.Refs[req.Ref]; ok {+ req.NodeID = nid+ }}}+ h.refreshActionNodeIDFromSelector(tCtx, &req)+ time.Sleep(pointerRetryDelay)+ result, engineName, actionErr = h.executeAction(tCtx, req)}// Semantic self-healing: if stale-ref retry still failed, attempt// recovery via the semantic matcher.@@ -668,15 +683,19 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, recontinue} else {actionRes, _, err = h.executeAction(tCtx, action)- if err != nil && action.Ref != "" && shouldRetryStaleRef(err) {- recordStaleRefRetry()- h.refreshRefCache(tCtx, resolvedTabID)- if cache := h.Bridge.GetRefCache(resolvedTabID); cache != nil {- if nid, ok := cache.Refs[action.Ref]; ok {- action.NodeID = nid- actionRes, _, err = h.executeAction(tCtx, action)+ if err != nil && shouldRetryPointerAction(action, err) {+ if action.Ref != "" && shouldRetryStaleRef(err) {+ recordStaleRefRetry()+ h.refreshRefCache(tCtx, resolvedTabID)+ if cache := h.Bridge.GetRefCache(resolvedTabID); cache != nil {+ if nid, ok := cache.Refs[action.Ref]; ok {+ action.NodeID = nid+ }}}+ h.refreshActionNodeIDFromSelector(tCtx, &action)+ time.Sleep(pointerRetryDelay)+ actionRes, _, err = h.executeAction(tCtx, action)}// Semantic self-healing for batched actions.if err != nil && action.Ref != "" && h.Recovery != nil && h.Recovery.ShouldAttempt(err, action.Ref) {@@ -931,15 +950,19 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {continue} else {res, _, err = h.executeAction(tCtx, step)- if err != nil && step.Ref != "" && shouldRetryStaleRef(err) {- recordStaleRefRetry()- h.refreshRefCache(tCtx, resolvedTabID)- if cache := h.Bridge.GetRefCache(resolvedTabID); cache != nil {- if nid, ok := cache.Refs[step.Ref]; ok {- step.NodeID = nid- res, _, err = h.executeAction(tCtx, step)+ if err != nil && shouldRetryPointerAction(step, err) {+ if step.Ref != "" && shouldRetryStaleRef(err) {+ recordStaleRefRetry()+ h.refreshRefCache(tCtx, resolvedTabID)+ if cache := h.Bridge.GetRefCache(resolvedTabID); cache != nil {+ if nid, ok := cache.Refs[step.Ref]; ok {+ step.NodeID = nid+ }}}+ h.refreshActionNodeIDFromSelector(tCtx, &step)+ time.Sleep(pointerRetryDelay)+ res, _, err = h.executeAction(tCtx, step)}// Semantic self-healing for macro steps.if err != nil && step.Ref != "" && h.Recovery != nil && h.Recovery.ShouldAttempt(err, step.Ref) {@@ -1083,6 +1106,41 @@ func actionCapability(kind string) (engine.Capability, bool) {}}+const pointerRetryDelay = 50 * time.Millisecond++func shouldRetryPointerAction(req bridge.ActionRequest, err error) bool {+ if err == nil {+ return false+ }+ kind := strings.ToLower(strings.TrimSpace(req.Kind))+ switch kind {+ case bridge.ActionClick, bridge.ActionDoubleClick, bridge.ActionHover, bridge.ActionDrag,+ bridge.ActionMouseDown, bridge.ActionMouseUp, bridge.ActionMouseWheel:+ // pointer action kinds+ default:+ return false+ }++ if errors.Is(err, bridge.ErrElementOccluded) ||+ errors.Is(err, bridge.ErrElementBlocked) ||+ errors.Is(err, bridge.ErrElementOffscreen) {+ return true+ }++ return shouldRetryStaleRef(err)+}++func (h *Handlers) refreshActionNodeIDFromSelector(ctx context.Context, req *bridge.ActionRequest) {+ if req == nil || req.NodeID > 0 || strings.TrimSpace(req.Selector) == "" {+ return+ }+ nid, err := bridge.ResolveCSSToNodeID(ctx, req.Selector)+ if err != nil {+ return+ }+ req.NodeID = nid+}+func shouldRetryStaleRef(err error) bool {if err == nil {return falsediff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.goindex 26bb9c4a..1d72b288 100644--- a/internal/handlers/handlers.go+++ b/internal/handlers/handlers.go@@ -158,6 +158,9 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {mux.HandleFunc("GET /tabs/{id}/screenshot", h.HandleTabScreenshot)mux.HandleFunc("POST /tabs/{id}/action", h.HandleTabAction)mux.HandleFunc("POST /tabs/{id}/actions", h.HandleTabActions)+ mux.HandleFunc("POST /tabs/{id}/handoff", h.HandleTabHandoff)+ mux.HandleFunc("POST /tabs/{id}/resume", h.HandleTabResume)+ mux.HandleFunc("GET /tabs/{id}/handoff", h.HandleTabHandoffStatus)mux.HandleFunc("GET /tabs/{id}/text", h.HandleTabText)mux.HandleFunc("GET /tabs/{id}/metrics", h.HandleTabMetrics)mux.HandleFunc("GET /metrics", h.HandleMetrics)diff --git a/internal/handlers/handoff.go b/internal/handlers/handoff.gonew file mode 100644index 00000000..a816036c--- /dev/null+++ b/internal/handlers/handoff.go@@ -0,0 +1,190 @@+package handlers++import (+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"+ "strings"+ "time"++ "github.com/pinchtab/pinchtab/internal/activity"+ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/dashboard"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++type tabHandoffController interface {+ SetTabHandoff(tabID, reason string) error+ ResumeTabHandoff(tabID string) error+ TabHandoffState(tabID string) (bridge.TabHandoffState, bool)+}++func (h *Handlers) handoffController() (tabHandoffController, bool) {+ ctrl, ok := h.Bridge.(tabHandoffController)+ return ctrl, ok+}++func (h *Handlers) HandleTabHandoff(w http.ResponseWriter, r *http.Request) {+ tabID := strings.TrimSpace(r.PathValue("id"))+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ var req struct {+ Reason string `json:"reason"`+ TimeoutMs int `json:"timeoutMs"`+ }+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil && !errors.Is(err, io.EOF) {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ ctx, resolvedTabID, err := h.tabContext(r, tabID)+ if err != nil {+ httpx.Error(w, 404, err)+ return+ }+ owner := resolveOwner(r, "")+ if err := h.enforceTabLease(resolvedTabID, owner); err != nil {+ httpx.ErrorCode(w, 423, "tab_locked", err.Error(), false, nil)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }++ ctrl, ok := h.handoffController()+ if !ok {+ httpx.ErrorCode(w, 501, "handoff_not_supported", "bridge does not support handoff state", false, nil)+ return+ }++ reason := strings.TrimSpace(req.Reason)+ if reason == "" {+ reason = "manual_handoff"+ }+ if err := ctrl.SetTabHandoff(resolvedTabID, reason); err != nil {+ httpx.ErrorCode(w, 500, "handoff_failed", err.Error(), false, nil)+ return+ }++ h.recordActivity(r, activity.Update{Action: "handoff", TabID: resolvedTabID})+ if h.Dashboard != nil {+ h.Dashboard.BroadcastSystemEvent(dashboard.SystemEvent{+ Type: "tab.handoff",+ Instance: map[string]any{+ "tabId": resolvedTabID,+ "status": "paused_handoff",+ "reason": reason,+ "timeoutMs": req.TimeoutMs,+ "requestedAt": time.Now().UTC().Format(time.RFC3339),+ },+ })+ }++ httpx.JSON(w, 200, map[string]any{+ "tabId": resolvedTabID,+ "status": "paused_handoff",+ "reason": reason,+ "timeoutMs": req.TimeoutMs,+ })+}++func (h *Handlers) HandleTabResume(w http.ResponseWriter, r *http.Request) {+ tabID := strings.TrimSpace(r.PathValue("id"))+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ var req struct {+ Status string `json:"status"`+ Data map[string]any `json:"resolvedData"`+ }+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil && !errors.Is(err, io.EOF) {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ ctx, resolvedTabID, err := h.tabContext(r, tabID)+ if err != nil {+ httpx.Error(w, 404, err)+ return+ }+ owner := resolveOwner(r, "")+ if err := h.enforceTabLease(resolvedTabID, owner); err != nil {+ httpx.ErrorCode(w, 423, "tab_locked", err.Error(), false, nil)+ return+ }+ if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {+ return+ }++ ctrl, ok := h.handoffController()+ if !ok {+ httpx.ErrorCode(w, 501, "handoff_not_supported", "bridge does not support handoff state", false, nil)+ return+ }+ if err := ctrl.ResumeTabHandoff(resolvedTabID); err != nil {+ httpx.ErrorCode(w, 500, "resume_failed", err.Error(), false, nil)+ return+ }++ h.recordActivity(r, activity.Update{Action: "resume", TabID: resolvedTabID})+ if h.Dashboard != nil {+ h.Dashboard.BroadcastSystemEvent(dashboard.SystemEvent{+ Type: "tab.resume",+ Instance: map[string]any{+ "tabId": resolvedTabID,+ "status": strings.TrimSpace(req.Status),+ "resolvedData": req.Data,+ "resumedAt": time.Now().UTC().Format(time.RFC3339),+ },+ })+ }++ httpx.JSON(w, 200, map[string]any{+ "tabId": resolvedTabID,+ "status": "active",+ "resumeStatus": strings.TrimSpace(req.Status),+ "resolvedData": req.Data,+ })+}++func (h *Handlers) HandleTabHandoffStatus(w http.ResponseWriter, r *http.Request) {+ tabID := strings.TrimSpace(r.PathValue("id"))+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ _, resolvedTabID, err := h.tabContext(r, tabID)+ if err != nil {+ httpx.Error(w, 404, err)+ return+ }++ ctrl, ok := h.handoffController()+ if !ok {+ httpx.ErrorCode(w, 501, "handoff_not_supported", "bridge does not support handoff state", false, nil)+ return+ }+ if state, ok := ctrl.TabHandoffState(resolvedTabID); ok {+ httpx.JSON(w, 200, map[string]any{+ "tabId": resolvedTabID,+ "status": state.Status,+ "reason": state.Reason,+ "pausedAt": state.PausedAt.Format(time.RFC3339),+ "lastUpdatedAt": state.LastUpdatedAt.Format(time.RFC3339),+ })+ return+ }++ httpx.JSON(w, 200, map[string]any{+ "tabId": resolvedTabID,+ "status": "active",+ })+}diff --git a/internal/handlers/health_tabs.go b/internal/handlers/health_tabs.goindex 25197941..2e840180 100644--- a/internal/handlers/health_tabs.go+++ b/internal/handlers/health_tabs.go@@ -11,6 +11,10 @@ import ("github.com/pinchtab/pinchtab/internal/httpx")+type tabHandoffReader interface {+ TabHandoffState(tabID string) (bridge.TabHandoffState, bool)+}+func (h *Handlers) HandleHealth(w http.ResponseWriter, r *http.Request) {if h.Router != nil && h.Router.Mode() == engine.ModeLite {resp := map[string]any{@@ -177,6 +181,15 @@ func (h *Handlers) HandleTabs(w http.ResponseWriter, r *http.Request) {"title": t.Title,"type": t.Type,}+ if hr, ok := h.Bridge.(tabHandoffReader); ok {+ if hs, ok := hr.TabHandoffState(tabID); ok {+ entry["status"] = hs.Status+ entry["handoffReason"] = hs.Reason+ entry["pausedAt"] = hs.PausedAt.Format(time.RFC3339)+ } else {+ entry["status"] = "active"+ }+ }if lock := h.Bridge.TabLockInfo(tabID); lock != nil {entry["owner"] = lock.Ownerentry["lockedUntil"] = lock.ExpiresAt.Format(time.RFC3339)diff --git a/internal/handlers/openapi.go b/internal/handlers/openapi.goindex c82fa4ec..c9f77378 100644--- a/internal/handlers/openapi.go+++ b/internal/handlers/openapi.go@@ -44,6 +44,8 @@ func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {"/health": map[string]any{"get": map[string]any{"summary": "Health"}},"/browser/restart": map[string]any{"post": map[string]any{"summary": "Soft restart the browser process without restarting the bridge"}},"/tabs": map[string]any{"get": map[string]any{"summary": "List tabs"}},+ "/tabs/{id}/handoff": map[string]any{"post": map[string]any{"summary": "Pause tab automation for human handoff"}, "get": map[string]any{"summary": "Get tab handoff status"}},+ "/tabs/{id}/resume": map[string]any{"post": map[string]any{"summary": "Resume tab automation after handoff"}},"/metrics": map[string]any{"get": map[string]any{"summary": "Runtime metrics"}},"/help": map[string]any{"get": map[string]any{"summary": "Alias for /openapi.json"}},"/text": map[string]any{"get": map[string]any{"summary": "Extract text", "parameters": []map[string]any{{"name": "maxChars", "in": "query", "schema": map[string]string{"type": "integer"}}, {"name": "format", "in": "query", "schema": map[string]string{"type": "string"}}}}},diff --git a/plugin/README.md b/plugin/README.mdindex 9fd64687..59251b3d 100644--- a/plugin/README.md+++ b/plugin/README.md@@ -56,6 +56,9 @@ One tool definition, many actions — keeps context lean:| `navigate` | Go to URL | — || `snapshot` | Accessibility tree (refs for interactions) | ~3,600 (interactive) || `click/type/press/fill/hover/scroll/select/focus` | Act on element by ref | — |+| `mousemove/mousedown/mouseup/mousewheel` | Low-level mouse controls by ref/selector/coordinates | — |+| `wait` | Wait for selector/text/url/load/fn/ms conditions | — |+| `handoff` | Human-in-the-loop pause/resume for CAPTCHA/login/2FA | — || `text` | Extract readable text (cheapest) | ~800 || `tabs` | List/open/close tabs | — || `screenshot` | JPEG screenshot (vision fallback) | ~2K |@@ -78,8 +81,54 @@ One tool definition, many actions — keeps context lean:→ Readable results (~800 tokens)```+## Manual Mouse Tests (OpenClaw)++Use these calls to validate low-level mouse behavior through the plugin:++```+1. pinchtab({ action: "navigate", url: "https://pinchtab.com" })+2. pinchtab({ action: "snapshot", filter: "interactive", format: "compact" })+ → Pick a target ref like e5+3. pinchtab({ action: "mousemove", ref: "e5" })+4. pinchtab({ action: "mousedown", ref: "e5", button: "left" })+5. pinchtab({ action: "mouseup", ref: "e5", button: "left" })+6. pinchtab({ action: "mousewheel", ref: "e5", wheelDeltaY: 240 })+```++Coordinate-driven test (viewport):++```+pinchtab({ action: "mousemove", x: 400, y: 300 })+pinchtab({ action: "mousedown", x: 400, y: 300, button: "left" })+pinchtab({ action: "mouseup", x: 400, y: 300, button: "left" })+pinchtab({ action: "mousewheel", x: 400, y: 300, wheelDeltaY: -320 })+```+**Token strategy:** `text` for reading, `snapshot` with `filter=interactive&format=compact` for interactions, `diff=true` on subsequent snapshots, `screenshot` only for visual verification.+## Human Handoff (CAPTCHA / Login / 2FA)++Use `handoff` when manual intervention is required, then resume with a wait condition:++```+1. pinchtab({ action: "handoff", humanReason: "captcha", humanPrompt: "Please solve CAPTCHA in headed browser" })+2. pinchtab({ action: "handoff", selector: "text:Dashboard", timeout: 120000 })+ → resumes when condition is met or returns a timeout error+```++You can also call `wait` directly:++```+pinchtab({ action: "wait", text: "Welcome back", timeout: 120000 })+```++## Built-In DOM Sync Safeguards++- Ref-like selectors (for example `selector: "e56"`) are normalized to `ref` automatically.+- Element actions perform one bounded stale-ref recovery attempt after refreshing interactive snapshot.+- `fill` auto-falls back to `type` once when controlled inputs reject direct fill.+- `tabs` list uses instance-scoped fallback if global `/tabs` returns empty.+## Security Notes- **`evaluate`** executes arbitrary JavaScript in the page — restrict to trusted agents and domainsdiff --git a/plugin/index.ts b/plugin/index.tsindex 2bc4df36..0b71bd2a 100644--- a/plugin/index.ts+++ b/plugin/index.ts@@ -16,6 +16,41 @@ interface PluginApi {registerTool: (tool: any, opts?: { optional?: boolean }) => void;}+function isRefToken(value: unknown): value is string {+ return typeof value === "string" && /^e\d+$/i.test(value.trim());+}++function normalizeActionParams(input: any): any {+ const params = { ...input };+ // Some agents send ref-like values (e.g. "e56") in selector.+ // Normalize to ref so action routing stays stable.+ if (!params.ref && isRefToken(params.selector)) {+ params.ref = String(params.selector).trim();+ delete params.selector;+ }+ if (typeof params.ref === "string") {+ params.ref = params.ref.trim();+ }+ return params;+}++function actionErrorText(result: any): string {+ return `${result?.error || ""} ${result?.body || ""}`.toLowerCase();+}++function looksLikeStaleRef(result: any): boolean {+ if (!result?.error) return false;+ const text = actionErrorText(result);+ return (+ text.includes("stale") ||+ text.includes("context canceled") ||+ text.includes("ref") ||+ text.includes("not found") ||+ text.includes("no node") ||+ text.includes("unknown element")+ );+}+function getConfig(api: PluginApi): PluginConfig {return api.config?.plugins?.entries?.pinchtab?.config ?? {};}@@ -77,8 +112,11 @@ export default function register(api: PluginApi) {description: `Browser control via Pinchtab. Actions:- navigate: go to URL (url, tabId?, newTab?, blockImages?, timeout?)- snapshot: accessibility tree (filter?, format?, selector?, maxTokens?, depth?, diff?, tabId?)-- click/type/press/fill/hover/scroll/select/focus: act on element (ref, text?, key?, value?, scrollY?, waitNav?, tabId?)+ - click/type/press/fill/hover/scroll/select/focus: act on element (ref, text?, key?, value?, scrollY?, waitNav?, tabId?)+ - mousemove/mousedown/mouseup/mousewheel: low-level mouse controls (ref|selector|x+y, button?, wheelDeltaX?, wheelDeltaY?, tabId?)- text: extract readable text (mode?, tabId?)+- wait: pause until condition (selector|text|url|load|fn|ms, tabId?, timeout?, state?)+- handoff: request human intervention mid-flow (captcha/login/2FA/credentials), optionally wait for resume condition- tabs: list/new/close tabs (tabAction?, url?, tabId?)- screenshot: JPEG screenshot (quality?, tabId?)- evaluate: run JS (expression, tabId?)@@ -99,10 +137,16 @@ Token strategy: use "text" for reading (~800 tokens), "snapshot" with filter=int"press","fill","hover",+ "mousemove",+ "mousedown",+ "mouseup",+ "mousewheel","scroll","select","focus","text",+ "wait",+ "handoff","tabs","screenshot","evaluate",@@ -153,6 +197,27 @@ Token strategy: use "text" for reading (~800 tokens), "snapshot" with filter=inttype: "number",description: "Pixels to scroll vertically",},+ x: {+ type: "number",+ description: "Mouse X coordinate (used by low-level mouse actions)",+ },+ y: {+ type: "number",+ description: "Mouse Y coordinate (used by low-level mouse actions)",+ },+ button: {+ type: "string",+ enum: ["left", "right", "middle"],+ description: "Mouse button for mousedown/mouseup",+ },+ wheelDeltaX: {+ type: "number",+ description: "Mouse wheel horizontal delta for mousewheel",+ },+ wheelDeltaY: {+ type: "number",+ description: "Mouse wheel vertical delta for mousewheel",+ },waitNav: {type: "boolean",description: "Wait for navigation after action",@@ -178,6 +243,33 @@ Token strategy: use "text" for reading (~800 tokens), "snapshot" with filter=intenum: ["readability", "raw"],description: "Text extraction mode",},+ ms: {+ type: "number",+ description: "Wait milliseconds for wait/handoff actions",+ },+ state: {+ type: "string",+ enum: ["visible", "hidden", "attached", "detached"],+ description: "Wait state for selector waits",+ },+ load: {+ type: "string",+ enum: ["load", "domcontentloaded", "networkidle"],+ description: "Document load state for wait action",+ },+ fn: {+ type: "string",+ description: "JavaScript predicate string for wait action",+ },+ humanReason: {+ type: "string",+ description:+ "Reason for manual handoff (captcha/login/2FA/credential input)",+ },+ humanPrompt: {+ type: "string",+ description: "Instruction shown when handing off to a human",+ },landscape: { type: "boolean", description: "PDF landscape orientation" },scale: { type: "number", description: "PDF print scale (default: 1.0)" },},@@ -185,28 +277,29 @@ Token strategy: use "text" for reading (~800 tokens), "snapshot" with filter=int},async execute(_id: string, params: any) {const cfg = getConfig(api);- const { action } = params;+ const normalized = normalizeActionParams(params);+ const { action } = normalized;// --- navigate ---if (action === "navigate") {- const body: any = { url: params.url };- if (params.tabId) body.tabId = params.tabId;- if (params.newTab) body.newTab = true;- if (params.blockImages) body.blockImages = true;- if (params.timeout) body.timeout = params.timeout;+ const body: any = { url: normalized.url };+ if (normalized.tabId) body.tabId = normalized.tabId;+ if (normalized.newTab) body.newTab = true;+ if (normalized.blockImages) body.blockImages = true;+ if (normalized.timeout) body.timeout = normalized.timeout;return textResult(await pinchtabFetch(cfg, "/navigate", { body }));}// --- snapshot ---if (action === "snapshot") {const query = new URLSearchParams();- if (params.tabId) query.set("tabId", params.tabId);- if (params.filter) query.set("filter", params.filter);- if (params.format) query.set("format", params.format);- if (params.selector) query.set("selector", params.selector);- if (params.maxTokens) query.set("maxTokens", String(params.maxTokens));- if (params.depth) query.set("depth", String(params.depth));- if (params.diff) query.set("diff", "true");+ if (normalized.tabId) query.set("tabId", normalized.tabId);+ if (normalized.filter) query.set("filter", normalized.filter);+ if (normalized.format) query.set("format", normalized.format);+ if (normalized.selector) query.set("selector", normalized.selector);+ if (normalized.maxTokens) query.set("maxTokens", String(normalized.maxTokens));+ if (normalized.depth) query.set("depth", String(normalized.depth));+ if (normalized.diff) query.set("diff", "true");const qs = query.toString();return textResult(await pinchtabFetch(cfg, `/snapshot${qs ? `?${qs}` : ""}`),@@ -220,6 +313,10 @@ Token strategy: use "text" for reading (~800 tokens), "snapshot" with filter=int"press","fill","hover",+ "mousemove",+ "mousedown",+ "mouseup",+ "mousewheel","scroll","select","focus",@@ -233,42 +330,176 @@ Token strategy: use "text" for reading (~800 tokens), "snapshot" with filter=int"selector","value","scrollY",+ "x",+ "y",+ "button",+ "wheelDeltaX",+ "wheelDeltaY","tabId","waitNav",]) {- if (params[k] !== undefined) body[k] = params[k];+ if (normalized[k] !== undefined) body[k] = normalized[k];+ }++ let result = await pinchtabFetch(cfg, "/action", { body });++ // One bounded retry: refresh snapshot once when refs look stale.+ if (body.ref && looksLikeStaleRef(result)) {+ const q = new URLSearchParams();+ q.set("filter", "interactive");+ q.set("format", "compact");+ if (body.tabId) q.set("tabId", body.tabId);+ await pinchtabFetch(cfg, `/snapshot?${q.toString()}`);+ const retried = await pinchtabFetch(cfg, "/action", { body });+ if (!retried?.error) {+ result = {+ ...retried,+ warning:+ "Action succeeded after one automatic snapshot refresh (stale ref recovery).",+ };+ } else {+ result = {+ ...retried,+ warning:+ "Action retried once after snapshot refresh but still failed. Refresh refs and retry.",+ };+ }}- return textResult(await pinchtabFetch(cfg, "/action", { body }));++ // Controlled input fallback: if fill fails, try type once.+ if (+ action === "fill" &&+ result?.error &&+ body.ref &&+ (typeof body.text === "string" || typeof body.value === "string")+ ) {+ const typeBody: any = { ...body, kind: "type" };+ if (typeof typeBody.text !== "string" && typeof typeBody.value === "string") {+ typeBody.text = typeBody.value;+ }+ delete typeBody.value;+ const typed = await pinchtabFetch(cfg, "/action", { body: typeBody });+ if (!typed?.error) {+ result = {+ ...typed,+ warning:+ "Fill failed; type fallback succeeded (useful for controlled inputs).",+ };+ }+ }++ return textResult(result);}// --- text ---if (action === "text") {const query = new URLSearchParams();- if (params.tabId) query.set("tabId", params.tabId);- if (params.mode) query.set("mode", params.mode);+ if (normalized.tabId) query.set("tabId", normalized.tabId);+ if (normalized.mode) query.set("mode", normalized.mode);const qs = query.toString();return textResult(await pinchtabFetch(cfg, `/text${qs ? `?${qs}` : ""}`),);}+ // --- wait ---+ if (action === "wait") {+ const body: any = {};+ for (const k of ["selector", "text", "url", "load", "fn", "ms", "tabId", "timeout", "state"]) {+ if (normalized[k] !== undefined) body[k] = normalized[k];+ }+ return textResult(await pinchtabFetch(cfg, "/wait", { body }));+ }++ // --- handoff ---+ if (action === "handoff") {+ const hasWaitCondition = ["selector", "text", "url", "load", "fn", "ms"].some(+ (k) => normalized[k] !== undefined,+ );++ const handoffMeta = {+ status: "human_handoff_required",+ reason:+ normalized.humanReason ||+ "Manual intervention required (captcha/login/2FA/credential entry).",+ instructions:+ normalized.humanPrompt ||+ "Please complete the step in the headed browser, then resume automation.",+ };++ if (!hasWaitCondition) {+ return textResult({+ ...handoffMeta,+ resumed: false,+ next:+ "Call action='handoff' with a wait condition (selector/text/url/load/fn/ms) or use action='wait' to resume when ready.",+ });+ }++ const waitBody: any = {};+ for (const k of ["selector", "text", "url", "load", "fn", "ms", "tabId", "timeout", "state"]) {+ if (normalized[k] !== undefined) waitBody[k] = normalized[k];+ }+ const waitResult = await pinchtabFetch(cfg, "/wait", { body: waitBody });+ return textResult({+ ...handoffMeta,+ resumed: !waitResult?.error,+ waitResult,+ });+ }+// --- tabs ---if (action === "tabs") {- const tabAction = params.tabAction || "list";+ const tabAction = normalized.tabAction || "list";if (tabAction === "list") {- return textResult(await pinchtabFetch(cfg, "/tabs"));+ const listed = await pinchtabFetch(cfg, "/tabs");+ const tabs = Array.isArray(listed?.tabs)+ ? listed.tabs+ : Array.isArray(listed)+ ? listed+ : [];+ if (tabs.length > 0) {+ return textResult(listed);+ }++ // Fallback: when global /tabs is empty, try the first running instance.+ const instances = await pinchtabFetch(cfg, "/instances");+ const list = Array.isArray(instances?.value)+ ? instances.value+ : Array.isArray(instances)+ ? instances+ : [];+ const running = list.find((i: any) => i?.status === "running" && i?.id);+ if (!running) {+ return textResult({+ ...listed,+ warning:+ "No tabs returned from /tabs and no running instance found for fallback.",+ });+ }+ const instanceTabs = await pinchtabFetch(+ cfg,+ `/instances/${running.id}/tabs`,+ );+ return textResult({+ source: "instance-fallback",+ instanceId: running.id,+ tabs: instanceTabs?.tabs ?? instanceTabs,+ warning:+ "Global /tabs was empty; used /instances/{id}/tabs fallback.",+ });}const body: any = { action: tabAction };- if (params.url) body.url = params.url;- if (params.tabId) body.tabId = params.tabId;+ if (normalized.url) body.url = normalized.url;+ if (normalized.tabId) body.tabId = normalized.tabId;return textResult(await pinchtabFetch(cfg, "/tab", { body }));}// --- screenshot ---if (action === "screenshot") {const query = new URLSearchParams();- if (params.tabId) query.set("tabId", params.tabId);- if (params.quality) query.set("quality", String(params.quality));+ if (normalized.tabId) query.set("tabId", normalized.tabId);+ if (normalized.quality) query.set("quality", String(normalized.quality));const qs = query.toString();try {const res = await pinchtabFetch(@@ -296,17 +527,17 @@ Token strategy: use "text" for reading (~800 tokens), "snapshot" with filter=int// --- evaluate ---if (action === "evaluate") {- const body: any = { expression: params.expression };- if (params.tabId) body.tabId = params.tabId;+ const body: any = { expression: normalized.expression };+ if (normalized.tabId) body.tabId = normalized.tabId;return textResult(await pinchtabFetch(cfg, "/evaluate", { body }));}// --- pdf ---if (action === "pdf") {const query = new URLSearchParams();- if (params.tabId) query.set("tabId", params.tabId);- if (params.landscape) query.set("landscape", "true");- if (params.scale) query.set("scale", String(params.scale));+ if (normalized.tabId) query.set("tabId", normalized.tabId);+ if (normalized.landscape) query.set("landscape", "true");+ if (normalized.scale) query.set("scale", String(normalized.scale));const qs = query.toString();return textResult(await pinchtabFetch(cfg, `/pdf${qs ? `?${qs}` : ""}`),diff --git a/plugin/openclaw.plugin.json b/plugin/openclaw.plugin.jsonindex de48b976..923be7e3 100644--- a/plugin/openclaw.plugin.json+++ b/plugin/openclaw.plugin.json@@ -1,9 +1,9 @@{"id": "pinchtab","name": "Pinchtab",- "description": "Browser control for AI agents via Pinchtab. Single tool, all actions: navigate, snapshot, click, type, text, screenshot, evaluate, pdf. Minimal context bloat.",+ "description": "Browser control for AI agents via Pinchtab. Single tool, all actions: navigate, snapshot, click/type/press/fill/hover/scroll/select/focus, mousemove/mousedown/mouseup/mousewheel, text, screenshot, evaluate, pdf. Minimal context bloat.","version": "0.1.0",- "skills": ["../skill/pinchtab"],+ "skills": ["../skills/pinchtab"],"configSchema": {"type": "object","additionalProperties": false,