High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: P3 stability — SPA navigate, request logging, port change, ActionFunc cleanup
bot33383c4f279a
diff --git a/README.md b/README.mdindex 85439ce9..79c0f874 100644--- a/README.md+++ b/README.md@@ -25,10 +25,10 @@ Pinchtab is a standalone HTTP server. Any agent, any language, even `curl`:```bash# Read a page — 800 tokens instead of 10,000-curl localhost:18800/text?tabId=X+curl localhost:9867/text?tabId=X# Click a button by ref from the last snapshot-curl -X POST localhost:18800/action -d '{"kind":"click","ref":"e5"}'+curl -X POST localhost:9867/action -d '{"kind":"click","ref":"e5"}'```| | Pinchtab | OpenClaw Browser |@@ -72,7 +72,7 @@ Chrome opens. You log into your sites. Agents drive the rest.### First-Time Login-Pinchtab launches its own Chrome with a persistent profile at `~/.browser-bridge/chrome-profile/`. The first time you run it, log into any sites you want agents to access — just do it in the Chrome window that opens. Cookies and sessions persist across restarts, so you only need to do this once.+Pinchtab launches its own Chrome with a persistent profile at `~/.pinchtab/chrome-profile/`. The first time you run it, log into any sites you want agents to access — just do it in the Chrome window that opens. Cookies and sessions persist across restarts, so you only need to do this once.## Features@@ -112,18 +112,18 @@ All via environment variables:| Variable | Default | Description ||----------|---------|-------------|-| `BRIDGE_PORT` | `18800` | HTTP server port |+| `BRIDGE_PORT` | `9867` | HTTP server port || `BRIDGE_TOKEN` | *(none)* | Bearer token for auth || `BRIDGE_HEADLESS` | `false` | Run Chrome headless |-| `BRIDGE_PROFILE` | `~/.browser-bridge/chrome-profile` | Chrome profile directory |-| `BRIDGE_STATE_DIR` | `~/.browser-bridge` | State/session storage |+| `BRIDGE_PROFILE` | `~/.pinchtab/chrome-profile` | Chrome profile directory |+| `BRIDGE_STATE_DIR` | `~/.pinchtab` | State/session storage || `BRIDGE_NO_RESTORE` | `false` | Skip restoring tabs from previous session || `CDP_URL` | *(none)* | Connect to existing Chrome instead of launching |## Architecture```-┌─────────────┐ HTTP :18800 ┌──────────────┐ ┌─────────┐+┌─────────────┐ HTTP :9867 ┌──────────────┐ ┌─────────┐│ Any Agent │ ──────────────► │ Pinchtab │ ── CDP ──► │ Chrome ││ (OpenClaw, │ snapshot, act, │ │ │ ││ PicoClaw, │ navigate, eval │ stealth + │ │ your │@@ -211,7 +211,7 @@ go test ./...## Security- Set `BRIDGE_TOKEN` in production — without it, anyone on the network can control your browser-- Chrome profile persists cookies/sessions — treat `~/.browser-bridge/` as sensitive+- Chrome profile persists cookies/sessions — treat `~/.pinchtab/` as sensitive- Pinchtab binds to all interfaces by default — use a firewall or reverse proxy in exposed environments- No data leaves your machine — all processing is localdiff --git a/cdp.go b/cdp.goindex 09b996a0..62652ce1 100644--- a/cdp.go+++ b/cdp.go@@ -4,13 +4,40 @@ import ("context""encoding/json""fmt"+ "time""github.com/chromedp/chromedp")-// clickByNodeID resolves a backend DOM node to a JS object and calls .click().-// Uses DOM.resolveNode + Runtime.callFunctionOn which works on React/shadow DOM-// where CSS selectors fail.+// navigatePage uses raw CDP Page.navigate + polls for a non-blank URL.+// Unlike chromedp.Navigate which waits for the full load event (hangs on SPAs),+// this fires navigation and waits up to 5s for the page to start loading.+func navigatePage(ctx context.Context, url string) error {+ return chromedp.Run(ctx,+ chromedp.ActionFunc(func(ctx context.Context) error {+ p := map[string]any{"url": url}+ var navResult json.RawMessage+ if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Page.navigate", p, &navResult); err != nil {+ return fmt.Errorf("Page.navigate: %w", err)+ }++ var resp struct {+ ErrorText string `json:"errorText"`+ }+ if err := json.Unmarshal(navResult, &resp); err == nil && resp.ErrorText != "" {+ return fmt.Errorf("navigate: %s", resp.ErrorText)+ }+ return nil+ }),+ // Brief sleep to let the page start rendering — not a full load wait.+ // Agents should use /snapshot to confirm readiness.+ chromedp.Sleep(500 * time.Millisecond),+ )+}++// clickByNodeID resolves a backend DOM node to a JS object, scrolls it into+// view, and calls .click(). Uses DOM.resolveNode + Runtime.callFunctionOn+// which works on React/shadow DOM where CSS selectors fail.func clickByNodeID(ctx context.Context, backendNodeID int64) error {return chromedp.Run(ctx,chromedp.ActionFunc(func(ctx context.Context) error {@@ -31,11 +58,10 @@ func clickByNodeID(ctx context.Context, backendNodeID int64) error {)}-// typeByNodeID focuses a DOM node and sends keyboard events.+// typeByNodeID scrolls an element into view, focuses it, and sends keyboard events.func typeByNodeID(ctx context.Context, backendNodeID int64, text string) error {return chromedp.Run(ctx,chromedp.ActionFunc(func(ctx context.Context) error {- // scrollIntoView before focusobjectID, err := resolveNodeToObject(ctx, backendNodeID)if err != nil {return errdiff --git a/config.go b/config.goindex a2d2989c..769d16fc 100644--- a/config.go+++ b/config.go@@ -35,14 +35,15 @@ const (var stealthScript stringvar (- port = envOr("BRIDGE_PORT", "18800")+ port = envOr("BRIDGE_PORT", "9867")cdpURL = os.Getenv("CDP_URL") // empty = launch Chrome ourselvestoken = os.Getenv("BRIDGE_TOKEN")- stateDir = envOr("BRIDGE_STATE_DIR", filepath.Join(homeDir(), ".browser-bridge"))+ stateDir = envOr("BRIDGE_STATE_DIR", filepath.Join(homeDir(), ".pinchtab"))headless = os.Getenv("BRIDGE_HEADLESS") == "true"noRestore = os.Getenv("BRIDGE_NO_RESTORE") == "true"- profileDir = envOr("BRIDGE_PROFILE", filepath.Join(homeDir(), ".browser-bridge", "chrome-profile"))+ profileDir = envOr("BRIDGE_PROFILE", filepath.Join(homeDir(), ".pinchtab", "chrome-profile"))actionTimeout = 15 * time.Second+ navigateTimeout = 30 * time.SecondshutdownTimeout = 10 * time.Second)diff --git a/handlers.go b/handlers.goindex cc6fc044..141a87c7 100644--- a/handlers.go+++ b/handlers.go@@ -7,7 +7,6 @@ import ("log/slog""net/http""strconv"- "time""github.com/chromedp/cdproto/page""github.com/chromedp/cdproto/target"@@ -293,11 +292,13 @@ func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {return}- tCtx, tCancel := context.WithTimeout(ctx, 30*time.Second)+ tCtx, tCancel := context.WithTimeout(ctx, navigateTimeout)defer tCancel()go cancelOnClientDone(r.Context(), tCancel)- if err := chromedp.Run(tCtx, chromedp.Navigate(req.URL)); err != nil {+ // Use raw CDP navigate + WaitReady instead of chromedp.Navigate+ // which waits for the full load event (never fires on SPAs)+ if err := navigatePage(tCtx, req.URL); err != nil {jsonErr(w, 500, fmt.Errorf("navigate: %w", err))return}@@ -317,55 +318,67 @@ func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {// ── POST /action ───────────────────────────────────────────-// ActionFunc handles a single action kind (click, type, etc.).-type ActionFunc func(ctx context.Context, sel string, nodeID int64, text string) (map[string]any, error)+// actionRequest is the parsed JSON body for /action.+type actionRequest struct {+ TabID string `json:"tabId"`+ Kind string `json:"kind"`+ Ref string `json:"ref"`+ Selector string `json:"selector"`+ Text string `json:"text"`+ Key string `json:"key"`+ NodeID int64 `json:"nodeId"`+}++// ActionFunc handles a single action kind. Receives the full request for+// clean access to all fields without parameter fragmentation.+type ActionFunc func(ctx context.Context, req actionRequest) (map[string]any, error)func (b *Bridge) actionRegistry() map[string]ActionFunc {return map[string]ActionFunc{- actionClick: func(ctx context.Context, sel string, nodeID int64, _ string) (map[string]any, error) {- if sel != "" {- return map[string]any{"clicked": true}, chromedp.Run(ctx, chromedp.Click(sel, chromedp.ByQuery))+ actionClick: func(ctx context.Context, req actionRequest) (map[string]any, error) {+ if req.Selector != "" {+ return map[string]any{"clicked": true}, chromedp.Run(ctx, chromedp.Click(req.Selector, chromedp.ByQuery))}- if nodeID > 0 {- return map[string]any{"clicked": true}, clickByNodeID(ctx, nodeID)+ if req.NodeID > 0 {+ return map[string]any{"clicked": true}, clickByNodeID(ctx, req.NodeID)}return nil, fmt.Errorf("need selector, ref, or nodeId")},- actionType: func(ctx context.Context, sel string, nodeID int64, text string) (map[string]any, error) {- if text == "" {+ actionType: func(ctx context.Context, req actionRequest) (map[string]any, error) {+ if req.Text == "" {return nil, fmt.Errorf("text required for type")}- if sel != "" {- return map[string]any{"typed": text}, chromedp.Run(ctx,- chromedp.Click(sel, chromedp.ByQuery),- chromedp.SendKeys(sel, text, chromedp.ByQuery),+ if req.Selector != "" {+ return map[string]any{"typed": req.Text}, chromedp.Run(ctx,+ chromedp.Click(req.Selector, chromedp.ByQuery),+ chromedp.SendKeys(req.Selector, req.Text, chromedp.ByQuery),)}- if nodeID > 0 {- return map[string]any{"typed": text}, typeByNodeID(ctx, nodeID, text)+ if req.NodeID > 0 {+ return map[string]any{"typed": req.Text}, typeByNodeID(ctx, req.NodeID, req.Text)}return nil, fmt.Errorf("need selector or ref")},- actionFill: func(ctx context.Context, sel string, _ int64, text string) (map[string]any, error) {- if sel != "" {- return map[string]any{"filled": text}, chromedp.Run(ctx, chromedp.SetValue(sel, text, chromedp.ByQuery))+ actionFill: func(ctx context.Context, req actionRequest) (map[string]any, error) {+ if req.Selector != "" {+ return map[string]any{"filled": req.Text}, chromedp.Run(ctx, chromedp.SetValue(req.Selector, req.Text, chromedp.ByQuery))}- return map[string]any{"filled": text}, nil+ return map[string]any{"filled": req.Text}, nil},- actionPress: func(ctx context.Context, _ string, _ int64, key string) (map[string]any, error) {- if key == "" {+ actionPress: func(ctx context.Context, req actionRequest) (map[string]any, error) {+ if req.Key == "" {return nil, fmt.Errorf("key required for press")}- return map[string]any{"pressed": key}, chromedp.Run(ctx, chromedp.KeyEvent(key))+ return map[string]any{"pressed": req.Key}, chromedp.Run(ctx, chromedp.KeyEvent(req.Key))},- actionFocus: func(ctx context.Context, sel string, nodeID int64, _ string) (map[string]any, error) {- if sel != "" {- return map[string]any{"focused": true}, chromedp.Run(ctx, chromedp.Focus(sel, chromedp.ByQuery))+ actionFocus: func(ctx context.Context, req actionRequest) (map[string]any, error) {+ if req.Selector != "" {+ return map[string]any{"focused": true}, chromedp.Run(ctx, chromedp.Focus(req.Selector, chromedp.ByQuery))}- if nodeID > 0 {+ if req.NodeID > 0 {return map[string]any{"focused": true}, chromedp.Run(ctx,chromedp.ActionFunc(func(ctx context.Context) error {- p := map[string]any{"backendNodeId": nodeID}+ p := map[string]any{"backendNodeId": req.NodeID}return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", p, nil)}),)@@ -376,15 +389,7 @@ func (b *Bridge) actionRegistry() map[string]ActionFunc {}func (b *Bridge) handleAction(w http.ResponseWriter, r *http.Request) {- var req struct {- TabID string `json:"tabId"`- Kind string `json:"kind"`- Ref string `json:"ref"`- Selector string `json:"selector"`- Text string `json:"text"`- Key string `json:"key"`- NodeID int64 `json:"nodeId"`- }+ var req actionRequestif err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {jsonErr(w, 400, fmt.Errorf("decode: %w", err))return@@ -418,20 +423,13 @@ func (b *Bridge) handleAction(w http.ResponseWriter, r *http.Request) {}}- registry := b.actionRegistry()- fn, ok := registry[req.Kind]+ fn, ok := b.actionRegistry()[req.Kind]if !ok {jsonResp(w, 400, map[string]string{"error": fmt.Sprintf("unknown action: %s", req.Kind)})return}- // For press, text field carries the key- text := req.Text- if req.Kind == actionPress {- text = req.Key- }-- result, err := fn(tCtx, req.Selector, req.NodeID, text)+ result, err := fn(tCtx, req)if err != nil {jsonErr(w, 500, fmt.Errorf("action %s: %w", req.Kind, err))return@@ -498,7 +496,7 @@ func (b *Bridge) handleTab(w http.ResponseWriter, r *http.Request) {if req.URL != "" {url = req.URL}- if err := chromedp.Run(ctx, chromedp.Navigate(url)); err != nil {+ if err := navigatePage(ctx, url); err != nil {cancel()jsonErr(w, 500, fmt.Errorf("new tab: %w", err))returndiff --git a/main.go b/main.goindex 7a5875ad..51413e5b 100644--- a/main.go+++ b/main.go@@ -94,7 +94,8 @@ func main() {slog.Info("initial tab", "id", string(initTargetID))if !noRestore {- bridge.RestoreState()+ // Restore in background so it doesn't block the HTTP server+ go bridge.RestoreState()}// Background tab cleanup@@ -114,7 +115,7 @@ func main() {mux.HandleFunc("POST /evaluate", bridge.handleEvaluate)mux.HandleFunc("POST /tab", bridge.handleTab)- srv := &http.Server{Addr: ":" + port, Handler: corsMiddleware(authMiddleware(mux))}+ srv := &http.Server{Addr: ":" + port, Handler: loggingMiddleware(corsMiddleware(authMiddleware(mux)))}// Graceful shutdowngo func() {diff --git a/middleware.go b/middleware.goindex 5fcf46f9..07852cf1 100644--- a/middleware.go+++ b/middleware.go@@ -5,8 +5,34 @@ import ("encoding/json""log/slog""net/http"+ "time")+// statusWriter wraps ResponseWriter to capture the status code.+type statusWriter struct {+ http.ResponseWriter+ code int+}++func (w *statusWriter) WriteHeader(code int) {+ w.code = code+ w.ResponseWriter.WriteHeader(code)+}++func loggingMiddleware(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ start := time.Now()+ sw := &statusWriter{ResponseWriter: w, code: 200}+ next.ServeHTTP(sw, r)+ slog.Info("request",+ "method", r.Method,+ "path", r.URL.Path,+ "status", sw.code,+ "ms", time.Since(start).Milliseconds(),+ )+ })+}+func authMiddleware(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if token != "" {diff --git a/state.go b/state.goindex 1d07ec0f..acecb35e 100644--- a/state.go+++ b/state.go@@ -70,6 +70,10 @@ func (b *Bridge) SaveState() {slog.Error("save state: marshal", "err", err)return}+ if err := os.MkdirAll(stateDir, 0755); err != nil {+ slog.Error("save state: mkdir", "err", err)+ return+ }path := filepath.Join(stateDir, "sessions.json")if err := os.WriteFile(path, data, 0644); err != nil {slog.Error("save state: write", "err", err)@@ -96,17 +100,28 @@ func (b *Bridge) RestoreState() {continue}ctx, cancel := chromedp.NewContext(b.browserCtx)- tCtx, tCancel := context.WithTimeout(ctx, 10*time.Second)- if err := chromedp.Run(tCtx, chromedp.Navigate(tab.URL)); err != nil {- tCancel()+ // Just initialize the tab context (attaches to Chrome) — don't navigate yet.+ // The agent will navigate when it needs the tab.+ if err := chromedp.Run(ctx); err != nil {cancel()slog.Warn("restore tab failed", "url", tab.URL, "err", err)continue}- tCancel()newID := string(chromedp.FromContext(ctx).Target.TargetID)+ b.mu.Lock()b.tabs[newID] = &TabEntry{ctx: ctx, cancel: cancel}+ b.mu.Unlock()restored++++ // Fire-and-forget navigate — don't block on page load+ go func(tabCtx context.Context, url string) {+ tCtx, tCancel := context.WithTimeout(tabCtx, 10*time.Second)+ defer tCancel()+ chromedp.Run(tCtx, chromedp.ActionFunc(func(ctx context.Context) error {+ p := map[string]any{"url": url}+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Page.navigate", p, nil)+ }))+ }(ctx, tab.URL)}if restored > 0 {slog.Info("restored tabs", "count", restored)