Skip to content

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

feat: add wait commands for element, text, URL, and network waits (#306) (#308)

Alice Losassod567c7d1690f
diff --git a/cmd/pinchtab/cmd_cli.go b/cmd/pinchtab/cmd_cli.go
index c24b214f..36105064 100644
--- a/cmd/pinchtab/cmd_cli.go
+++ b/cmd/pinchtab/cmd_cli.go
@@ -346,6 +346,18 @@ var findCmd = &cobra.Command{
},
}
+var waitCmd = &cobra.Command{
+ Use: "wait [selector|ms]",
+ Short: "Wait for element, text, URL, network idle, JS expression, or fixed duration",
+ Args: cobra.MaximumNArgs(1),
+ Run: func(cmd *cobra.Command, args []string) {
+ cfg := config.Load()
+ runCLIWith(cfg, func(client *http.Client, base, token string) {
+ browseractions.Wait(client, base, token, args, cmd)
+ })
+ },
+}
+
var dialogCmd = &cobra.Command{
Use: "dialog",
Short: "Handle JavaScript dialogs (alert, confirm, prompt)",
@@ -512,6 +524,7 @@ func init() {
uncheckCmd.GroupID = "browser"
networkCmd.GroupID = "browser"
dialogCmd.GroupID = "browser"
+ waitCmd.GroupID = "browser"
keyboardCmd.GroupID = "browser"
keydownCmd.GroupID = "browser"
keyupCmd.GroupID = "browser"
@@ -654,6 +667,7 @@ func init() {
rootCmd.AddCommand(checkCmd)
rootCmd.AddCommand(uncheckCmd)
rootCmd.AddCommand(networkCmd)
+ rootCmd.AddCommand(waitCmd)
rootCmd.AddCommand(keyboardCmd)
rootCmd.AddCommand(keydownCmd)
rootCmd.AddCommand(keyupCmd)
@@ -672,6 +686,14 @@ func init() {
networkCmd.Flags().String("buffer-size", "", "Per-tab network buffer size (default 100)")
networkCmd.Flags().Bool("stream", false, "Stream network entries in real-time (like tail -f)")
+ waitCmd.Flags().String("text", "", "Wait for text on page")
+ waitCmd.Flags().String("url", "", "Wait for URL glob match")
+ waitCmd.Flags().String("load", "", "Wait for load state (networkidle)")
+ waitCmd.Flags().String("fn", "", "Wait for JS expression to be truthy")
+ waitCmd.Flags().String("state", "", "Element state: visible (default) or hidden")
+ waitCmd.Flags().Int("timeout", 0, "Timeout in milliseconds (default 10000, max 30000)")
+ waitCmd.Flags().String("tab", "", "Tab ID")
+
dialogAcceptCmd.Flags().String("tab", "", "Tab ID")
dialogDismissCmd.Flags().String("tab", "", "Tab ID")
dialogCmd.AddCommand(dialogAcceptCmd)
diff --git a/internal/cli/actions/actions_wait.go b/internal/cli/actions/actions_wait.go
new file mode 100644
index 00000000..0eec0e41
--- /dev/null
+++ b/internal/cli/actions/actions_wait.go
@@ -0,0 +1,58 @@
+package actions
+
+import (
+ "fmt"
+ "net/http"
+ "strconv"
+
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+ "github.com/spf13/cobra"
+)
+
+// Wait sends a wait request to the server.
+func Wait(client *http.Client, base, token string, args []string, cmd *cobra.Command) {
+ body := map[string]any{}
+
+ textFlag, _ := cmd.Flags().GetString("text")
+ urlFlag, _ := cmd.Flags().GetString("url")
+ loadFlag, _ := cmd.Flags().GetString("load")
+ fnFlag, _ := cmd.Flags().GetString("fn")
+ stateFlag, _ := cmd.Flags().GetString("state")
+ timeoutFlag, _ := cmd.Flags().GetInt("timeout")
+ tabID, _ := cmd.Flags().GetString("tab")
+
+ switch {
+ case textFlag != "":
+ body["text"] = textFlag
+ case urlFlag != "":
+ body["url"] = urlFlag
+ case loadFlag != "":
+ body["load"] = loadFlag
+ case fnFlag != "":
+ body["fn"] = fnFlag
+ case len(args) > 0:
+ // Check if arg is a number (ms wait) or a selector
+ if ms, err := strconv.Atoi(args[0]); err == nil {
+ body["ms"] = ms
+ } else {
+ body["selector"] = args[0]
+ if stateFlag != "" {
+ body["state"] = stateFlag
+ }
+ }
+ default:
+ fmt.Println("Usage: pinchtab wait <selector|ms> [--text|--url|--load|--fn] [--timeout ms] [--tab id]")
+ return
+ }
+
+ if timeoutFlag > 0 {
+ body["timeout"] = timeoutFlag
+ }
+
+ path := "/wait"
+ if tabID != "" {
+ path = fmt.Sprintf("/tabs/%s/wait", tabID)
+ }
+
+ apiclient.DoPost(client, base, token, path, body)
+}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
index 025a4b97..76ba4f1b 100644
--- a/internal/handlers/handlers.go
+++ b/internal/handlers/handlers.go
@@ -155,6 +155,8 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {
mux.HandleFunc("GET /tabs/{id}/network/{requestId}", h.HandleTabNetworkByID)
mux.HandleFunc("POST /dialog", h.HandleDialog)
mux.HandleFunc("POST /tabs/{id}/dialog", h.HandleTabDialog)
+ mux.HandleFunc("POST /wait", h.HandleWait)
+ mux.HandleFunc("POST /tabs/{id}/wait", h.HandleTabWait)
mux.HandleFunc("GET /welcome", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write([]byte(assets.WelcomeHTML))
diff --git a/internal/handlers/wait.go b/internal/handlers/wait.go
new file mode 100644
index 00000000..7f240a67
--- /dev/null
+++ b/internal/handlers/wait.go
@@ -0,0 +1,301 @@
+package handlers
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+const (
+ maxWaitTimeout = 30_000 // 30s max
+ defaultTimeout = 10_000 // 10s default
+ pollInterval = 250 * time.Millisecond
+ maxFixedWaitMS = 30_000
+)
+
+// waitRequest is the JSON body for POST /wait and POST /tabs/{id}/wait.
+type waitRequest struct {
+ TabID string `json:"tabId,omitempty"`
+ Selector string `json:"selector,omitempty"` // CSS/XPath/text selector
+ State string `json:"state,omitempty"` // "visible" (default) or "hidden"
+ Text string `json:"text,omitempty"` // wait for text on page
+ URL string `json:"url,omitempty"` // wait for URL glob match
+ Load string `json:"load,omitempty"` // "networkidle"
+ Fn string `json:"fn,omitempty"` // JS expression to poll for truthy
+ Ms *int `json:"ms,omitempty"` // fixed duration wait
+ Timeout *int `json:"timeout,omitempty"` // timeout in ms
+}
+
+// waitResponse is the JSON response for wait endpoints.
+type waitResponse struct {
+ Waited bool `json:"waited"`
+ Elapsed int64 `json:"elapsed"`
+ Match string `json:"match,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+func (wr *waitRequest) mode() string {
+ switch {
+ case wr.Ms != nil:
+ return "ms"
+ case wr.Selector != "":
+ return "selector"
+ case wr.Text != "":
+ return "text"
+ case wr.URL != "":
+ return "url"
+ case wr.Load != "":
+ return "load"
+ case wr.Fn != "":
+ return "fn"
+ default:
+ return ""
+ }
+}
+
+func (wr *waitRequest) resolvedTimeout() time.Duration {
+ ms := defaultTimeout
+ if wr.Timeout != nil {
+ ms = *wr.Timeout
+ }
+ if ms < 100 {
+ ms = 100
+ }
+ if ms > maxWaitTimeout {
+ ms = maxWaitTimeout
+ }
+ return time.Duration(ms) * time.Millisecond
+}
+
+// HandleWait handles POST /wait.
+//
+// @Endpoint POST /wait
+func (h *Handlers) HandleWait(w http.ResponseWriter, r *http.Request) {
+ var req waitRequest
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+
+ h.handleWaitCore(w, r, req)
+}
+
+// HandleTabWait handles POST /tabs/{id}/wait.
+//
+// @Endpoint POST /tabs/{id}/wait
+func (h *Handlers) HandleTabWait(w http.ResponseWriter, r *http.Request) {
+ tabID := r.PathValue("id")
+ if tabID == "" {
+ web.Error(w, 400, fmt.Errorf("tab id required"))
+ return
+ }
+
+ body := map[string]any{}
+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))
+ if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+
+ if rawTabID, ok := body["tabId"]; ok {
+ if provided, ok := rawTabID.(string); !ok || provided == "" {
+ web.Error(w, 400, fmt.Errorf("invalid tabId"))
+ return
+ } else if provided != tabID {
+ web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))
+ return
+ }
+ }
+
+ body["tabId"] = tabID
+
+ payload, err := json.Marshal(body)
+ if err != nil {
+ web.Error(w, 500, fmt.Errorf("encode: %w", err))
+ return
+ }
+
+ cloned := r.Clone(r.Context())
+ cloned.Body = io.NopCloser(bytes.NewReader(payload))
+ cloned.ContentLength = int64(len(payload))
+ cloned.Header = r.Header.Clone()
+ cloned.Header.Set("Content-Type", "application/json")
+ h.HandleWait(w, cloned)
+}
+
+func (h *Handlers) handleWaitCore(w http.ResponseWriter, r *http.Request, req waitRequest) {
+ start := time.Now()
+
+ mode := req.mode()
+ if mode == "" {
+ web.Error(w, 400, fmt.Errorf("one of selector, text, url, load, fn, or ms is required"))
+ return
+ }
+
+ // Fixed duration wait doesn't need a browser tab.
+ if mode == "ms" {
+ ms := *req.Ms
+ if ms < 0 {
+ ms = 0
+ }
+ if ms > maxFixedWaitMS {
+ ms = maxFixedWaitMS
+ }
+ select {
+ case <-time.After(time.Duration(ms) * time.Millisecond):
+ web.JSON(w, 200, waitResponse{
+ Waited: true,
+ Elapsed: time.Since(start).Milliseconds(),
+ Match: fmt.Sprintf("%dms", ms),
+ })
+ case <-r.Context().Done():
+ web.JSON(w, 200, waitResponse{
+ Waited: false,
+ Elapsed: time.Since(start).Milliseconds(),
+ Error: "cancelled",
+ })
+ }
+ return
+ }
+
+ // All other modes need a browser tab.
+ ctx, _, err := h.Bridge.TabContext(req.TabID)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+
+ timeout := req.resolvedTimeout()
+ tCtx, tCancel := context.WithTimeout(ctx, timeout)
+ defer tCancel()
+ go web.CancelOnClientDone(r.Context(), tCancel)
+
+ var js string
+ var matchLabel string
+
+ switch mode {
+ case "selector":
+ js, matchLabel = buildSelectorJS(req.Selector, req.State)
+ case "text":
+ js = fmt.Sprintf(`document.body && document.body.innerText.includes(%s)`, jsonStr(req.Text))
+ matchLabel = req.Text
+ case "url":
+ js = buildURLMatchJS(req.URL)
+ matchLabel = req.URL
+ case "load":
+ if req.Load == "networkidle" {
+ js = `document.readyState === 'complete'`
+ matchLabel = "networkidle"
+ } else {
+ web.Error(w, 400, fmt.Errorf("unsupported load state: %s (supported: networkidle)", req.Load))
+ return
+ }
+ case "fn":
+ js = fmt.Sprintf(`!!(function(){try{return %s}catch(e){return false}})()`, req.Fn)
+ matchLabel = "fn"
+ }
+
+ // Poll loop
+ for {
+ var result bool
+ evalErr := chromedp.Run(tCtx, chromedp.Evaluate(js, &result))
+ if evalErr == nil && result {
+ web.JSON(w, 200, waitResponse{
+ Waited: true,
+ Elapsed: time.Since(start).Milliseconds(),
+ Match: matchLabel,
+ })
+ return
+ }
+
+ select {
+ case <-tCtx.Done():
+ elapsed := time.Since(start).Milliseconds()
+ web.JSON(w, 200, waitResponse{
+ Waited: false,
+ Elapsed: elapsed,
+ Error: fmt.Sprintf("timeout after %dms waiting for %s", elapsed, mode),
+ })
+ return
+ case <-time.After(pollInterval):
+ // continue polling
+ }
+ }
+}
+
+// buildSelectorJS builds a JS expression for selector wait.
+// Supports css:, xpath:, text: prefixes and bare CSS selectors.
+func buildSelectorJS(sel, state string) (string, string) {
+ hidden := state == "hidden"
+
+ var js string
+ switch {
+ case hasPrefix(sel, "xpath:"):
+ xpath := sel[len("xpath:"):]
+ if hidden {
+ js = fmt.Sprintf(`(function(){try{var r=document.evaluate(%s,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);return r.singleNodeValue===null}catch(e){return true}})()`, jsonStr(xpath))
+ } else {
+ js = fmt.Sprintf(`(function(){try{var r=document.evaluate(%s,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);return r.singleNodeValue!==null}catch(e){return false}})()`, jsonStr(xpath))
+ }
+ case hasPrefix(sel, "//") || hasPrefix(sel, "(//"):
+ if hidden {
+ js = fmt.Sprintf(`(function(){try{var r=document.evaluate(%s,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);return r.singleNodeValue===null}catch(e){return true}})()`, jsonStr(sel))
+ } else {
+ js = fmt.Sprintf(`(function(){try{var r=document.evaluate(%s,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);return r.singleNodeValue!==null}catch(e){return false}})()`, jsonStr(sel))
+ }
+ case hasPrefix(sel, "text:"):
+ text := sel[len("text:"):]
+ if hidden {
+ js = fmt.Sprintf(`(function(){var w=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);while(w.nextNode()){if(w.currentNode.textContent.includes(%s))return false}return true})()`, jsonStr(text))
+ } else {
+ js = fmt.Sprintf(`(function(){var w=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);while(w.nextNode()){if(w.currentNode.textContent.includes(%s))return true}return false})()`, jsonStr(text))
+ }
+ default:
+ css := sel
+ if hasPrefix(sel, "css:") {
+ css = sel[len("css:"):]
+ }
+ if hidden {
+ js = fmt.Sprintf(`document.querySelector(%s) === null`, jsonStr(css))
+ } else {
+ js = fmt.Sprintf(`document.querySelector(%s) !== null`, jsonStr(css))
+ }
+ }
+
+ return js, sel
+}
+
+// buildURLMatchJS builds a JS expression that checks if the current URL matches a glob pattern.
+func buildURLMatchJS(pattern string) string {
+ // Convert glob to regex: ** → .*, * → [^/]*, ? → .
+ // For simplicity, we use a JS function that does basic glob matching.
+ return fmt.Sprintf(`(function(){
+ var p = %s;
+ var u = window.location.href;
+ // Convert glob to regex
+ var re = p.replace(/[.+^${}()|[\\]\\\\]/g, '\\\\$&')
+ .replace(/\\*\\*/g, '<<<DOUBLESTAR>>>')
+ .replace(/\\*/g, '[^/]*')
+ .replace(/<<<DOUBLESTAR>>>/g, '.*')
+ .replace(/\\?/g, '.');
+ return new RegExp(re).test(u);
+ })()`, jsonStr(pattern))
+}
+
+// jsonStr returns a JSON-encoded string (with quotes).
+func jsonStr(s string) string {
+ b, _ := json.Marshal(s)
+ return string(b)
+}
+
+func hasPrefix(s, prefix string) bool {
+ return len(s) >= len(prefix) && s[:len(prefix)] == prefix
+}
diff --git a/internal/handlers/wait_test.go b/internal/handlers/wait_test.go
new file mode 100644
index 00000000..c2d0b072
--- /dev/null
+++ b/internal/handlers/wait_test.go
@@ -0,0 +1,407 @@
+package handlers
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// ── Request validation tests ───────────────────────────────────────────
+
+func TestHandleWait_InvalidJSON(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/wait", bytes.NewReader([]byte(`not json`)))
+ w := httptest.NewRecorder()
+ h.HandleWait(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleWait_EmptyBody(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/wait", bytes.NewReader([]byte(`{}`)))
+ w := httptest.NewRecorder()
+ h.HandleWait(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+// ── Fixed duration (ms) tests ──────────────────────────────────────────
+
+func TestHandleWait_FixedMs(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/wait", bytes.NewReader([]byte(`{"ms": 50}`)))
+ w := httptest.NewRecorder()
+ h.HandleWait(w, req)
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp waitResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if !resp.Waited {
+ t.Error("expected waited=true")
+ }
+ if resp.Elapsed < 50 {
+ t.Errorf("expected elapsed >= 50, got %d", resp.Elapsed)
+ }
+ if resp.Match != "50ms" {
+ t.Errorf("expected match='50ms', got %q", resp.Match)
+ }
+}
+
+func TestHandleWait_FixedMsZero(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/wait", bytes.NewReader([]byte(`{"ms": 0}`)))
+ w := httptest.NewRecorder()
+ h.HandleWait(w, req)
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp waitResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if !resp.Waited {
+ t.Error("expected waited=true for ms=0")
+ }
+}
+
+func TestHandleWait_FixedMsNegativeClamped(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/wait", bytes.NewReader([]byte(`{"ms": -100}`)))
+ w := httptest.NewRecorder()
+ h.HandleWait(w, req)
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp waitResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if !resp.Waited {
+ t.Error("expected waited=true for negative ms (clamped to 0)")
+ }
+ if resp.Match != "0ms" {
+ t.Errorf("expected match='0ms', got %q", resp.Match)
+ }
+}
+
+func TestHandleWait_FixedMsClampedAt30s(t *testing.T) {
+ // Verify the clamping logic: ms > 30000 gets clamped to 30000.
+ // We don't actually wait 30s — just verify mode detection and clamping.
+ wr := waitRequest{}
+ ms := 99999
+ wr.Ms = &ms
+ if wr.mode() != "ms" {
+ t.Errorf("expected mode 'ms', got %q", wr.mode())
+ }
+}
+
+// ── Timeout clamping tests ─────────────────────────────────────────────
+
+func TestWaitRequest_TimeoutClamping(t *testing.T) {
+ tests := []struct {
+ name string
+ timeout *int
+ wantMs int
+ }{
+ {"default", nil, 10000},
+ {"custom", intPtr(5000), 5000},
+ {"too low", intPtr(10), 100},
+ {"too high", intPtr(60000), 30000},
+ {"max boundary", intPtr(30000), 30000},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ wr := waitRequest{Timeout: tt.timeout}
+ got := wr.resolvedTimeout().Milliseconds()
+ if got != int64(tt.wantMs) {
+ t.Errorf("resolvedTimeout() = %d, want %d", got, tt.wantMs)
+ }
+ })
+ }
+}
+
+// ── Mode detection tests ───────────────────────────────────────────────
+
+func TestWaitRequest_Mode(t *testing.T) {
+ tests := []struct {
+ name string
+ req waitRequest
+ want string
+ }{
+ {"empty", waitRequest{}, ""},
+ {"selector", waitRequest{Selector: "#foo"}, "selector"},
+ {"text", waitRequest{Text: "hello"}, "text"},
+ {"url", waitRequest{URL: "**/dash"}, "url"},
+ {"load", waitRequest{Load: "networkidle"}, "load"},
+ {"fn", waitRequest{Fn: "true"}, "fn"},
+ {"ms", waitRequest{Ms: intPtr(100)}, "ms"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := tt.req.mode(); got != tt.want {
+ t.Errorf("mode() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+// ── Selector wait (needs browser — tests validation only) ──────────────
+
+func TestHandleWait_SelectorNoTab(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/wait", bytes.NewReader([]byte(`{"selector":"#results"}`)))
+ w := httptest.NewRecorder()
+ h.HandleWait(w, req)
+ if w.Code != 404 {
+ t.Errorf("expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleWait_TextNoTab(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/wait", bytes.NewReader([]byte(`{"text":"Order confirmed"}`)))
+ w := httptest.NewRecorder()
+ h.HandleWait(w, req)
+ if w.Code != 404 {
+ t.Errorf("expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleWait_URLNoTab(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/wait", bytes.NewReader([]byte(`{"url":"**/dashboard"}`)))
+ w := httptest.NewRecorder()
+ h.HandleWait(w, req)
+ if w.Code != 404 {
+ t.Errorf("expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleWait_FnNoTab(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/wait", bytes.NewReader([]byte(`{"fn":"document.readyState === 'complete'"}`)))
+ w := httptest.NewRecorder()
+ h.HandleWait(w, req)
+ if w.Code != 404 {
+ t.Errorf("expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleWait_LoadNoTab(t *testing.T) {
+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/wait", bytes.NewReader([]byte(`{"load":"networkidle"}`)))
+ w := httptest.NewRecorder()
+ h.HandleWait(w, req)
+ if w.Code != 404 {
+ t.Errorf("expected 404, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+func TestHandleWait_InvalidLoadState(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{ActionTimeout: 5e9}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/wait", bytes.NewReader([]byte(`{"load":"invalid"}`)))
+ w := httptest.NewRecorder()
+ h.HandleWait(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())
+ }
+}
+
+// ── Tab-scoped wait tests ──────────────────────────────────────────────
+
+func TestHandleTabWait_MissingTabID(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/tabs//wait", bytes.NewReader([]byte(`{"ms":50}`)))
+ w := httptest.NewRecorder()
+ h.HandleTabWait(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleTabWait_TabIDMismatch(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/tabs/tab_abc/wait", bytes.NewReader([]byte(`{"tabId":"tab_other","ms":50}`)))
+ req.SetPathValue("id", "tab_abc")
+ w := httptest.NewRecorder()
+ h.HandleTabWait(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleTabWait_FixedMs(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/tabs/tab_abc/wait", bytes.NewReader([]byte(`{"ms":10}`)))
+ req.SetPathValue("id", "tab_abc")
+ w := httptest.NewRecorder()
+ h.HandleTabWait(w, req)
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var resp waitResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if !resp.Waited {
+ t.Error("expected waited=true")
+ }
+}
+
+// ── Response format tests ──────────────────────────────────────────────
+
+func TestWaitResponse_Format(t *testing.T) {
+ resp := waitResponse{
+ Waited: true,
+ Elapsed: 3420,
+ Match: "#results",
+ }
+ data, err := json.Marshal(resp)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ var got map[string]any
+ if err := json.Unmarshal(data, &got); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if got["waited"] != true {
+ t.Error("expected waited=true")
+ }
+ if got["elapsed"].(float64) != 3420 {
+ t.Errorf("expected elapsed=3420, got %v", got["elapsed"])
+ }
+ if got["match"] != "#results" {
+ t.Errorf("expected match='#results', got %v", got["match"])
+ }
+ if _, ok := got["error"]; ok {
+ t.Error("expected no error field when empty")
+ }
+}
+
+func TestWaitResponse_ErrorFormat(t *testing.T) {
+ resp := waitResponse{
+ Waited: false,
+ Elapsed: 10000,
+ Error: "timeout after 10000ms waiting for selector",
+ }
+ data, err := json.Marshal(resp)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ var got map[string]any
+ if err := json.Unmarshal(data, &got); err != nil {
+ t.Fatalf("unmarshal: %v", err)
+ }
+ if got["waited"] != false {
+ t.Error("expected waited=false")
+ }
+ if got["error"] == nil || got["error"] == "" {
+ t.Error("expected error field")
+ }
+}
+
+// ── JS builder tests ───────────────────────────────────────────────────
+
+func TestBuildSelectorJS_CSS(t *testing.T) {
+ js, match := buildSelectorJS("#results", "")
+ if js == "" {
+ t.Error("expected non-empty JS")
+ }
+ if match != "#results" {
+ t.Errorf("expected match='#results', got %q", match)
+ }
+}
+
+func TestBuildSelectorJS_CSSPrefix(t *testing.T) {
+ js, match := buildSelectorJS("css:#results", "")
+ if js == "" {
+ t.Error("expected non-empty JS")
+ }
+ if match != "css:#results" {
+ t.Errorf("expected match='css:#results', got %q", match)
+ }
+}
+
+func TestBuildSelectorJS_XPath(t *testing.T) {
+ js, _ := buildSelectorJS("xpath://div[@id='test']", "")
+ if js == "" {
+ t.Error("expected non-empty JS for xpath")
+ }
+}
+
+func TestBuildSelectorJS_XPathBare(t *testing.T) {
+ js, _ := buildSelectorJS("//div[@id='test']", "")
+ if js == "" {
+ t.Error("expected non-empty JS for bare xpath")
+ }
+}
+
+func TestBuildSelectorJS_Text(t *testing.T) {
+ js, _ := buildSelectorJS("text:Submit", "")
+ if js == "" {
+ t.Error("expected non-empty JS for text selector")
+ }
+}
+
+func TestBuildSelectorJS_Hidden(t *testing.T) {
+ js, _ := buildSelectorJS("#spinner", "hidden")
+ if js == "" {
+ t.Error("expected non-empty JS for hidden state")
+ }
+ // Hidden should check for null
+ jsVisible, _ := buildSelectorJS("#spinner", "")
+ if js == jsVisible {
+ t.Error("hidden JS should differ from visible JS")
+ }
+}
+
+func TestBuildSelectorJS_HiddenXPath(t *testing.T) {
+ js, _ := buildSelectorJS("xpath://div", "hidden")
+ if js == "" {
+ t.Error("expected non-empty JS for hidden xpath")
+ }
+}
+
+func TestBuildSelectorJS_HiddenText(t *testing.T) {
+ js, _ := buildSelectorJS("text:Loading", "hidden")
+ if js == "" {
+ t.Error("expected non-empty JS for hidden text")
+ }
+}
+
+func TestBuildURLMatchJS(t *testing.T) {
+ js := buildURLMatchJS("**/dashboard")
+ if js == "" {
+ t.Error("expected non-empty JS for URL match")
+ }
+}
+
+// ── Route registration test ────────────────────────────────────────────
+
+func TestWaitRouteRegistered(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ mux := httptest.NewServer(nil).Config.Handler
+ _ = mux
+ // Just verify the handler methods exist and are callable
+ req := httptest.NewRequest("POST", "/wait", bytes.NewReader([]byte(`{"ms":1}`)))
+ w := httptest.NewRecorder()
+ h.HandleWait(w, req)
+ if w.Code != 200 {
+ t.Errorf("expected 200, got %d", w.Code)
+ }
+}
+
+// ── Helpers ────────────────────────────────────────────────────────────
+
+func intPtr(v int) *int {
+ return &v
+}
diff --git a/internal/mcp/handlers.go b/internal/mcp/handlers.go
index 373cbe9f..70a0aaef 100644
--- a/internal/mcp/handlers.go
+++ b/internal/mcp/handlers.go
@@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"net/url"
- "strings"
"time"
"github.com/mark3labs/mcp-go/mcp"
@@ -55,6 +54,10 @@ func handlerMap(c *Client) map[string]func(context.Context, mcp.CallToolRequest)
// Utility
"pinchtab_wait": handleWait(),
"pinchtab_wait_for_selector": handleWaitForSelector(c),
+ "pinchtab_wait_for_text": handleWaitForText(c),
+ "pinchtab_wait_for_url": handleWaitForURL(c),
+ "pinchtab_wait_for_load": handleWaitForLoad(c),
+ "pinchtab_wait_for_function": handleWaitForFunction(c),
// Network monitoring
"pinchtab_network": handleNetwork(c),
@@ -500,72 +503,106 @@ func handleWaitForSelector(c *Client) func(context.Context, mcp.CallToolRequest)
if err != nil {
return mcp.NewToolResultError(err.Error()), nil
}
- timeoutMS := 10000.0
+ payload := map[string]any{"selector": sel}
if t, ok := optFloat(r, "timeout"); ok {
- timeoutMS = t
- }
- if timeoutMS > maxWaitMS {
- timeoutMS = maxWaitMS
- }
- if timeoutMS < 100 {
- timeoutMS = 100
- }
-
- // Build the appropriate JavaScript check based on selector type.
- var js string
- switch {
- case strings.HasPrefix(sel, "xpath:"):
- xpath := sel[len("xpath:"):]
- js = fmt.Sprintf(`(function(){try{var r=document.evaluate(%s,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);return r.singleNodeValue!==null}catch(e){return false}})()`, jsonString(xpath))
- case strings.HasPrefix(sel, "//") || strings.HasPrefix(sel, "(//"):
- js = fmt.Sprintf(`(function(){try{var r=document.evaluate(%s,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null);return r.singleNodeValue!==null}catch(e){return false}})()`, jsonString(sel))
- case strings.HasPrefix(sel, "text:"):
- text := sel[len("text:"):]
- js = fmt.Sprintf(`(function(){var w=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);while(w.nextNode()){if(w.currentNode.textContent.includes(%s))return true}return false})()`, jsonString(text))
- case strings.HasPrefix(sel, "css:"):
- css := sel[len("css:"):]
- js = fmt.Sprintf(`document.querySelector(%s) !== null`, jsonString(css))
- default:
- // Bare selector — treat as CSS (backward compatible)
- js = fmt.Sprintf(`document.querySelector(%s) !== null`, jsonString(sel))
- }
-
- payload := map[string]any{"expression": js}
+ payload["timeout"] = int(t)
+ }
+ if state := optString(r, "state"); state != "" {
+ payload["state"] = state
+ }
if tabID := optString(r, "tabId"); tabID != "" {
payload["tabId"] = tabID
}
+ body, code, err := c.Post(ctx, "/wait", payload)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
- deadline := time.Now().Add(time.Duration(timeoutMS) * time.Millisecond)
- interval := 250 * time.Millisecond
-
- for {
- body, code, err := c.Post(ctx, "/evaluate", payload)
- if err == nil && code < 400 {
- var resp struct {
- Result any `json:"result"`
- }
- if json.Unmarshal(body, &resp) == nil && resp.Result == true {
- return mcp.NewToolResultText(fmt.Sprintf(`{"found":true,"selector":%s}`, jsonString(sel))), nil
- }
- }
+func handleWaitForText(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ text, err := r.RequireString("text")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ payload := map[string]any{"text": text}
+ if t, ok := optFloat(r, "timeout"); ok {
+ payload["timeout"] = int(t)
+ }
+ if tabID := optString(r, "tabId"); tabID != "" {
+ payload["tabId"] = tabID
+ }
+ body, code, err := c.Post(ctx, "/wait", payload)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
- if time.Now().After(deadline) {
- return mcp.NewToolResultError(fmt.Sprintf("timeout: selector %q not found within %dms", sel, int(timeoutMS))), nil
- }
+func handleWaitForURL(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ u, err := r.RequireString("url")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ payload := map[string]any{"url": u}
+ if t, ok := optFloat(r, "timeout"); ok {
+ payload["timeout"] = int(t)
+ }
+ if tabID := optString(r, "tabId"); tabID != "" {
+ payload["tabId"] = tabID
+ }
+ body, code, err := c.Post(ctx, "/wait", payload)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
- select {
- case <-time.After(interval):
- case <-ctx.Done():
- return mcp.NewToolResultError("wait_for_selector cancelled"), nil
- }
+func handleWaitForLoad(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ load, err := r.RequireString("load")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ payload := map[string]any{"load": load}
+ if t, ok := optFloat(r, "timeout"); ok {
+ payload["timeout"] = int(t)
}
+ if tabID := optString(r, "tabId"); tabID != "" {
+ payload["tabId"] = tabID
+ }
+ body, code, err := c.Post(ctx, "/wait", payload)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
}
}
-// jsonString returns a JSON-encoded string (with quotes).
-func jsonString(s string) string {
- b, _ := json.Marshal(s)
- return string(b)
+func handleWaitForFunction(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ fn, err := r.RequireString("fn")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ payload := map[string]any{"fn": fn}
+ if t, ok := optFloat(r, "timeout"); ok {
+ payload["timeout"] = int(t)
+ }
+ if tabID := optString(r, "tabId"); tabID != "" {
+ payload["tabId"] = tabID
+ }
+ body, code, err := c.Post(ctx, "/wait", payload)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
}
// ── Network monitoring handlers ────────────────────────────────────────
diff --git a/internal/mcp/handlers_test.go b/internal/mcp/handlers_test.go
index 0143d8bd..68bb98fb 100644
--- a/internal/mcp/handlers_test.go
+++ b/internal/mcp/handlers_test.go
@@ -42,6 +42,13 @@ func mockPinchTab() *httptest.Server {
resp["result"] = true
}
+ // Special: /wait returns a successful wait response
+ if r.URL.Path == "/wait" {
+ resp["waited"] = true
+ resp["elapsed"] = 100
+ resp["match"] = "selector"
+ }
+
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_ = json.NewEncoder(w).Encode(resp)
@@ -522,8 +529,8 @@ func TestHandleWaitForSelector(t *testing.T) {
}, srv)
text := resultText(t, r)
- if !strings.Contains(text, "found") {
- t.Errorf("expected found, got %s", text)
+ if !strings.Contains(text, "waited") {
+ t.Errorf("expected waited, got %s", text)
}
}
diff --git a/internal/mcp/server_test.go b/internal/mcp/server_test.go
index 137ae4b6..2fe93abd 100644
--- a/internal/mcp/server_test.go
+++ b/internal/mcp/server_test.go
@@ -18,8 +18,8 @@ func TestNewServerRegistersAllTools(t *testing.T) {
// The server should have registered all tools.
// We verify by checking that NewServer doesn't panic — the panic
// in NewServer fires if any tool lacks a handler.
- if len(tools) != 30 {
- t.Errorf("expected 30 tools, got %d", len(tools))
+ if len(tools) != 34 {
+ t.Errorf("expected 34 tools, got %d", len(tools))
}
}
diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go
index 564ab282..03babaf3 100644
--- a/internal/mcp/tools.go
+++ b/internal/mcp/tools.go
@@ -151,9 +151,34 @@ func allTools() []mcp.Tool {
mcp.WithNumber("ms", mcp.Required(), mcp.Description("Milliseconds to wait (max 30000)")),
),
mcp.NewTool("pinchtab_wait_for_selector",
- mcp.WithDescription("Wait for an element matching a selector to appear on the page"),
+ mcp.WithDescription("Wait for an element matching a selector to appear or disappear on the page"),
mcp.WithString("selector", mcp.Required(), mcp.Description("Unified selector to wait for (CSS, XPath, text, or ref)")),
mcp.WithNumber("timeout", mcp.Description("Timeout in milliseconds (default: 10000, max: 30000)")),
+ mcp.WithString("state", mcp.Description("Element state to wait for: 'visible' (default) or 'hidden'")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+ mcp.NewTool("pinchtab_wait_for_text",
+ mcp.WithDescription("Wait for specific text to appear on the page"),
+ mcp.WithString("text", mcp.Required(), mcp.Description("Text to wait for")),
+ mcp.WithNumber("timeout", mcp.Description("Timeout in milliseconds (default: 10000, max: 30000)")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+ mcp.NewTool("pinchtab_wait_for_url",
+ mcp.WithDescription("Wait for the page URL to match a glob pattern"),
+ mcp.WithString("url", mcp.Required(), mcp.Description("URL glob pattern to match (e.g. '**/dashboard')")),
+ mcp.WithNumber("timeout", mcp.Description("Timeout in milliseconds (default: 10000, max: 30000)")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+ mcp.NewTool("pinchtab_wait_for_load",
+ mcp.WithDescription("Wait for a page load state (e.g. networkidle)"),
+ mcp.WithString("load", mcp.Required(), mcp.Description("Load state to wait for: 'networkidle'")),
+ mcp.WithNumber("timeout", mcp.Description("Timeout in milliseconds (default: 10000, max: 30000)")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+ mcp.NewTool("pinchtab_wait_for_function",
+ mcp.WithDescription("Wait for a JavaScript expression to return a truthy value"),
+ mcp.WithString("fn", mcp.Required(), mcp.Description("JavaScript expression to evaluate")),
+ mcp.WithNumber("timeout", mcp.Description("Timeout in milliseconds (default: 10000, max: 30000)")),
mcp.WithString("tabId", mcp.Description("Target tab ID")),
),