High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: CDP_URL mode tab creation (issue #13) (#14)
luigiagentd2b28f9f4f81
diff --git a/README.md b/README.mdindex 4e16e734..43ba8908 100644--- a/README.md+++ b/README.md@@ -109,6 +109,31 @@ Chrome runs invisibly in the background — no window, pure API. Best for serverAll core API flows are validated in headless mode.+### Remote Chrome via CDP_URL++Instead of launching your own Chrome, connect to an existing instance:++```bash+# Start Chrome with debugging enabled (localhost only)+chrome --remote-debugging-port=9222 &++# Get the WebSocket URL+CDP_URL=$(curl http://localhost:9222/json/version | jq -r '.webSocketDebuggerUrl')++# Connect Pinchtab to it+export CDP_URL+./pinchtab+```++**Use cases:**+- 🤝 **Multi-agent resource sharing** — All agents share one Chrome (save 1.3GB per agent)+- 🧪 **Integration testing** — Multiple test scripts use the same browser and session+- 🐳 **Docker/containers** — Chrome in one container, Pinchtab in another++**⚠️ Security:** Chrome's DevTools Protocol has no authentication. Only expose the CDP port locally or via SSH tunnel. See **[docs/cdp-url-shared-chrome.md#security](docs/cdp-url-shared-chrome.md#security)** for details.++See **[docs/cdp-url-shared-chrome.md](docs/cdp-url-shared-chrome.md)** for detailed setup and use cases.+### Headed Mode (operator-in-the-loop)<img src="assets/pinchtab-headed.png" width="128" alt="Pinchtab headed mode" />@@ -389,6 +414,7 @@ When you log into sites through Pinchtab's Chrome window, those sessions — coo- **Set `BRIDGE_TOKEN`** — without it, anyone on your network can control your browser. In production, this is non-negotiable.- **Treat `~/.pinchtab/` as sensitive** — it contains your Chrome profile with all saved sessions and cookies. Guard it like you'd guard your passwords.- **Pinchtab binds to all interfaces by default** — use a firewall or reverse proxy if you're on a shared network.+- **If using `CDP_URL`:** Chrome's DevTools Protocol has no authentication. **Never expose the CDP port to the network.** Only use localhost or SSH tunnels. See [docs/cdp-url-shared-chrome.md#security](docs/cdp-url-shared-chrome.md#security) for details.- **Start with low-risk accounts.** Don't point an experimental agent at your primary email or bank account on day one. Test with throwaway accounts first.- **No data leaves your machine** — all processing is local. But the agents you connect might send data wherever they want.diff --git a/cmd/pinchtab/browser.go b/cmd/pinchtab/browser.goindex 8921b65c..e2096f50 100644--- a/cmd/pinchtab/browser.go+++ b/cmd/pinchtab/browser.go@@ -11,9 +11,11 @@ import ("strconv""strings""syscall"+ "time""github.com/chromedp/cdproto/emulation""github.com/chromedp/cdproto/page"+ "github.com/chromedp/cdproto/target""github.com/chromedp/chromedp""github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/config"@@ -150,12 +152,55 @@ func buildChromeOpts(cfg *config.RuntimeConfig) []chromedp.ExecAllocatorOption {return opts}-func startChrome(allocCtx context.Context, seededScript string) (context.Context, context.CancelFunc, error) {- bCtx, bCancel := chromedp.NewContext(allocCtx)-+func startChrome(allocCtx context.Context, cfg *config.RuntimeConfig, seededScript string) (context.Context, context.CancelFunc, error) {startCtx, startDone := context.WithTimeout(context.Background(), chromeStartTimeout)defer startDone()+ // For CDP_URL (remote allocator), ensure we have a target available.+ // Remote Chrome instances may not have any windows open yet.+ if cfg.CdpURL != "" {+ // Get or create a target for the remote browser+ getCtx, getCancel := context.WithTimeout(context.Background(), 5*time.Second)+ targets, err := func() ([]*target.Info, error) {+ var tgts []*target.Info+ getErr := chromedp.Run(getCtx,+ chromedp.ActionFunc(func(ctx context.Context) error {+ var err error+ tgts, err = target.GetTargets().Do(ctx)+ return err+ }),+ )+ return tgts, getErr+ }()+ getCancel()++ targetID := target.ID("")+ if err == nil && len(targets) > 0 {+ // Use first existing target+ targetID = targets[0].TargetID+ } else {+ // Try to create a new target+ createCtx, createCancel := context.WithTimeout(context.Background(), 5*time.Second)+ _ = chromedp.Run(createCtx,+ chromedp.ActionFunc(func(ctx context.Context) error {+ tID, err := target.CreateTarget("about:blank").Do(ctx)+ if err == nil {+ targetID = tID+ }+ return nil // Don't fail, will try with browser context+ }),+ )+ createCancel()+ }++ bCtx, bCancel := chromedp.NewContext(allocCtx,+ chromedp.WithTargetID(targetID),+ )+ return bCtx, bCancel, nil+ }++ bCtx, bCancel := chromedp.NewContext(allocCtx)+errCh := make(chan error, 1)go func() {errCh <- chromedp.Run(bCtx,diff --git a/cmd/pinchtab/main.go b/cmd/pinchtab/main.goindex 9d7a1505..375aa143 100644--- a/cmd/pinchtab/main.go+++ b/cmd/pinchtab/main.go@@ -74,7 +74,7 @@ func main() {human.SetHumanRandSeed(int64(stealthSeed))seededScript := fmt.Sprintf("var __pinchtab_seed = %d;\nvar __pinchtab_stealth_level = %q;\n", stealthSeed, cfg.StealthLevel) + assets.StealthScript- browserCtx, browserCancel, err := startChrome(allocCtx, seededScript)+ browserCtx, browserCancel, err := startChrome(allocCtx, cfg, seededScript)if err != nil {slog.Warn("Chrome startup failed, clearing sessions and retrying once", "err", err)@@ -85,7 +85,7 @@ func main() {allocCtx, allocCancel, _ = setupAllocator(cfg)_ = chromeOpts // used implicitly via setupAllocator- browserCtx, browserCancel, err = startChrome(allocCtx, seededScript)+ browserCtx, browserCancel, err = startChrome(allocCtx, cfg, seededScript)if err != nil {slog.Error("Chrome failed to start after retry","err", err,@@ -112,9 +112,15 @@ func main() {orch.SetProfileManager(profMgr)dash.SetInstanceLister(orch)- initTargetID := chromedp.FromContext(browserCtx).Target.TargetID- b.RegisterTab(string(initTargetID), browserCtx)- slog.Info("initial tab", "id", string(initTargetID))+ // For CDP_URL mode, the initial target might not exist yet.+ // Tabs will be registered when they're created or discovered.+ if cfg.CdpURL == "" {+ initTargetID := chromedp.FromContext(browserCtx).Target.TargetID+ b.RegisterTab(string(initTargetID), browserCtx)+ slog.Info("initial tab", "id", string(initTargetID))+ } else {+ slog.Info("CDP_URL mode: skipping initial tab registration")+ }if !cfg.Headless {go func() {diff --git a/docs/cdp-url-shared-chrome.md b/docs/cdp-url-shared-chrome.mdnew file mode 100644index 00000000..c903ed3a--- /dev/null+++ b/docs/cdp-url-shared-chrome.md@@ -0,0 +1,372 @@+# Remote Chrome via CDP_URL++By default, Pinchtab launches its own isolated Chrome instance. But sometimes you want to **connect to an existing Chrome** instead — to share one browser across multiple agents, save memory in container environments, or integrate with external Chrome setups.++That's what `CDP_URL` does.++## What is CDP_URL?++`CDP_URL` is a WebSocket URL that points to Chrome's DevTools Protocol server:++```bash+CDP_URL=ws://localhost:9222/devtools/browser/b041f900-...+./pinchtab+# Instead of launching Chrome, Pinchtab connects to the existing instance at port 9222+```++When you set `CDP_URL`, Pinchtab:+- ✅ Skips launching its own Chrome+- ✅ Connects to the browser at that URL+- ✅ Creates tabs in the existing browser+- ✅ Shares that browser's session (cookies, localStorage, etc.)++## Use Cases++### 1. Multi-Agent Resource Sharing++**Problem:** Multiple agents on the same machine each launching their own Chrome eats memory:++```+Agent 1 → launches Chrome (1.3GB)+Agent 2 → launches Chrome (1.3GB)+Agent 3 → launches Chrome (1.3GB)+──────────────────────────────────+Total: 3.9GB+ just for browser instances 😬+```++**Solution:** All agents share one Chrome via CDP_URL:++```bash+# Start shared Chrome once+/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \+ --remote-debugging-port=9222 &++# Get the CDP URL+CDP_WS=$(curl -s http://localhost:9222/json/version | jq -r '.webSocketDebuggerUrl')++# All agents connect to it+export CDP_URL="$CDP_WS"+./agent-1+./agent-2+./agent-3+```++**Benefit:** 1.3GB for Chrome + lightweight agent processes. **Save 2.6GB per agent.**++**Typical setup:**+- Agent A handles browser operations (creates/controls tabs)+- Agent B handles data processing (reads via Agent A's HTTP API)+- Agent C handles orchestration (no browser needed)++All three can point to the same Pinchtab instance instead of each running their own.++### 2. Integration Testing++**Problem:** Test scripts need to control the same browser in sequence:++```bash+./test-screenshot.sh+./test-login.sh+./test-checkout.sh+# Each script might have its own isolated Chrome+```++**Solution:** Start one Chrome, all scripts target it:++```bash+# Start test Chrome once+chrome --remote-debugging-port=9222 &++# All test scripts use the same browser+CDP_URL=ws://localhost:9222/... ./test-screenshot.sh+CDP_URL=ws://localhost:9222/... ./test-login.sh+CDP_URL=ws://localhost:9222/... ./test-checkout.sh+```++**Benefits:**+- Persistent session across tests (log in once, reuse)+- Simpler test setup (no per-test Chrome cleanup)+- Faster iteration (no Chrome startup overhead per test)++### 3. Container/Docker Deployments++**Problem:** Chrome runs in one container, your application in another:++```dockerfile+# Chrome container (separate)+FROM chromium:latest+EXPOSE 9222++# App container (separate)+FROM golang:latest+ENV CDP_URL=http://chrome-service:9222/...+RUN ./pinchtab+```++**Solution:** Pinchtab connects to the Chrome container via CDP_URL:++```bash+# Start Chrome container+docker run -d --name chrome \+ -p 9222:9222 \+ chromium:latest --remote-debugging-port=9222++# Start Pinchtab container, pointing at Chrome+docker run -d \+ -e CDP_URL=http://chrome:9222/devtools/browser/... \+ -p 9867:9867 \+ pinchtab/pinchtab+```++**Benefits:**+- Separate scaling (one Chrome for 10 Pinchtab instances)+- Simpler networking (Chrome container = stable endpoint)+- Cleaner orchestration (containers talk via service names)++## How to Use++### Find the CDP URL++Start Chrome with `--remote-debugging-port` and query the endpoint:++```bash+# macOS+/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \+ --remote-debugging-port=9222 &++# Linux+google-chrome --remote-debugging-port=9222 &++# Docker+docker run -p 9222:9222 chromium:latest --remote-debugging-port=9222 &+```++Get the WebSocket URL:++```bash+curl http://localhost:9222/json/version | jq -r '.webSocketDebuggerUrl'+# Output: ws://localhost:9222/devtools/browser/b041f900-b164-4ad2-872d-359456b4e198+```++### Connect Pinchtab++```bash+export CDP_URL="ws://localhost:9222/devtools/browser/b041f900-..."+./pinchtab+```++That's it. Pinchtab will:+1. Connect to the existing Chrome+2. Discover existing tabs (if any)+3. Create new tabs as requested+4. Serve the HTTP API normally++### Multi-Agent Example++```bash+#!/bin/bash++# Start shared Chrome+chrome --remote-debugging-port=9222 &+CHROME_PID=$!++# Get the CDP URL+CDP_WS=$(curl -s http://localhost:9222/json/version | jq -r '.webSocketDebuggerUrl')++# Launch all agents pointing to the same Chrome+export CDP_URL="$CDP_WS"++# Start multiple agent instances+./agent-browser & # Handles browser operations+./agent-processor & # Processes data (uses HTTP)+./agent-orchestrator & # Coordinates workflow++wait+```++## Limitations & Notes++**What works:**+- ✅ Creating tabs in existing Chrome+- ✅ Navigating to URLs+- ✅ Snapshots and actions+- ✅ Session persistence (cookies are stored in Chrome's profile)+- ✅ Multiple Pinchtab instances sharing one Chrome++**What doesn't work yet:**+- ❌ Launching Chrome from scratch (you have to start Chrome separately)+- ❌ Profile management (profiles belong to the remote Chrome, not Pinchtab)++**Performance:**+- Slightly higher latency per request (WebSocket to remote Chrome instead of local IPC)+- Memory savings: **~1.3GB per agent** when sharing++## Troubleshooting++### "Connection refused" or "Failed to open new tab"++Chrome might not have any windows open yet. Solution:++```bash+# Ensure Chrome has at least one window+chrome --remote-debugging-port=9222 --new-window &+```++### "invalid memory address"++Pinchtab failed to find a valid target. Make sure:++1. Chrome is running with `--remote-debugging-port`+2. The CDP_URL is correct (test with `curl`)+3. Chrome has at least one window/tab open++### Ports and networking++**Local machine only:**+```bash+export CDP_URL="ws://localhost:9222/..."+```++**Docker/Kubernetes (inter-container):**+```bash+export CDP_URL="ws://chrome-service:9222/..." # Use service name+```++**Remote machine:**+```bash+# SSH tunnel (recommended for security)+ssh -L 9222:remote-chrome:9222 user@remote-host &+export CDP_URL="ws://localhost:9222/..."++# Or direct (less secure)+export CDP_URL="ws://remote-chrome.example.com:9222/..."+```++## Configuration Reference++| Env Var | Default | Effect |+|---------|---------|--------|+| `CDP_URL` | *(none)* | WebSocket URL to remote Chrome. When set, Pinchtab connects instead of launching |+| `BRIDGE_PORT` | `9867` | Local HTTP port (independent of Chrome port) |+| `BRIDGE_HEADLESS` | `true` | Ignored when using CDP_URL (remote Chrome state is independent) |+| `BRIDGE_PROFILE` | `~/.pinchtab/chrome-profile` | Session storage directory (still used even with CDP_URL) |+| `BRIDGE_NO_RESTORE` | `false` | Skip restoring tabs from previous session |++## Security ⚠️++**Important:** Chrome's DevTools Protocol has **no built-in authentication**. Anyone with access to the CDP port can fully control Chrome — steal cookies, read pages, make transactions, access any logged-in account.++### Local Machine (Safe)++If Chrome and Pinchtab run on the same local machine:++```bash+# ✅ Safe — listens on localhost only by default+chrome --remote-debugging-port=9222+export CDP_URL="ws://localhost:9222/..."+```++**What's safe:**+- Only processes on your machine can access it+- Other users on shared systems can still access it+- Docker containers on same host can access it++**Defense:** Use file permissions on Chrome's profile directory:+```bash+chmod 700 ~/.chrome-profile # Only you can read+```++### Network Exposure (Critical Risk 🚨)++**Never expose the CDP port to the network:**++```bash+# ❌ DANGEROUS — exposes to entire network+chrome --remote-debugging-address=0.0.0.0 --remote-debugging-port=9222++# ❌ DANGEROUS — Docker exposes to host network+docker run -p 9222:9222 chromium:latest --remote-debugging-port=9222+```++**What attackers can do with network access:**+- Read every page Chrome visits+- Steal all cookies and auth tokens+- Make purchases, send emails, access bank accounts+- Execute arbitrary JavaScript+- Access sensitive data in localStorage/IndexedDB++### Safe Network Access: SSH Tunnel++If Chrome runs on a remote machine:++```bash+# On local machine, create secure tunnel+ssh -L 9222:localhost:9222 user@remote-host &++# Now Pinchtab uses the tunneled connection (encrypted via SSH)+export CDP_URL="ws://localhost:9222/..."+./pinchtab+```++This way:+- ✅ Communication is encrypted (SSH tunnel)+- ✅ Remote Chrome is not exposed to the network+- ✅ Only you can access it (requires SSH login)++### Docker/Kubernetes Best Practices++**Option 1: Internal Network Only**+```yaml+# Kubernetes Pod with Chrome + Pinchtab sidecars+spec:+ containers:+ - name: chrome+ ports:+ - containerPort: 9222 # No hostPort = not exposed to outside++ - name: pinchtab+ env:+ - name: CDP_URL+ value: "ws://localhost:9222/..." # Talk within pod+```++**Option 2: Internal Service Only**+```yaml+# Don't expose Chrome service outside the cluster+apiVersion: v1+kind: Service+metadata:+ name: chrome+spec:+ type: ClusterIP # ✅ Internal only, not LoadBalancer or NodePort+ ports:+ - port: 9222+```++**Option 3: SSH Tunnel for External Access**+```bash+# From outside cluster, use kubectl port-forward+kubectl port-forward service/chrome 9222:9222++# Then connect via tunnel+export CDP_URL="ws://localhost:9222/..."+```++### Checklist++- [ ] Chrome listens on `127.0.0.1` (localhost only) or is SSH-tunneled+- [ ] CDP port (9222) is not exposed to the network/internet+- [ ] No `--remote-debugging-address=0.0.0.0` flag+- [ ] Firewall blocks external access to the port (if on a server)+- [ ] Chrome profile directory has restricted permissions+- [ ] Only trusted agents/code have access to `CDP_URL`+- [ ] In containers: Chrome service is `ClusterIP`, not `LoadBalancer`++### Principle++Treat Chrome's CDP port like you'd treat:+- An SSH port (gives shell access to a machine)+- A database port (gives data access)+- An admin panel (gives system control)++**Restrict access ruthlessly. Use SSH tunnels for anything remote.**diff --git a/docs/pinchtab-architecture.md b/docs/pinchtab-architecture.mdindex 59a07fc2..1a26378a 100644--- a/docs/pinchtab-architecture.md+++ b/docs/pinchtab-architecture.md@@ -3,16 +3,29 @@## OverviewPinchtab is an HTTP server (Go binary, ~12MB) that wraps Chrome DevTools Protocol (CDP)-to give AI agents browser control via a simple REST API. It self-launches Chrome,-manages tabs, and exposes the accessibility tree as flat JSON with stable refs.+to give AI agents browser control via a simple REST API.++**Self-hosted mode (default):** Pinchtab launches and manages its own Chrome instance.```┌─────────────┐ HTTP ┌──────────────┐ CDP ┌──────────────┐│ AI Agent │ ────────────▶ │ Pinchtab │ ─────────────▶ │ Chrome │-│ (any LLM) │ ◀──────────── │ (Go binary) │ ◀───────────── │ headed/headless │+│ (any LLM) │ ◀──────────── │ (Go binary) │ ◀───────────── │ self-launched │└─────────────┘ JSON/text └──────────────┘ WebSocket └──────────────┘```+**Remote Chrome mode (CDP_URL):** Pinchtab connects to an existing Chrome instance via CDP_URL.++```+┌─────────────┐ HTTP ┌──────────────┐ CDP ┌──────────────┐+│ Multiple │ ────────────▶ │ Multiple │ ─────────────▶ │ Shared │+│ Agents │ ◀──────────── │ Pinchtab │ ◀───────────── │ Chrome │+│ │ JSON/text │ instances │ WebSocket │ instance │+└─────────────┘ └──────────────┘ └──────────────┘+```++See [docs/cdp-url-shared-chrome.md](cdp-url-shared-chrome.md) for multi-agent resource sharing and container deployment patterns.+Agents never touch CDP directly. They send HTTP requests, get back JSON.The accessibility tree (a11y) is the primary interface — not screenshots, not DOM.diff --git a/internal/bridge/bridge_test.go b/internal/bridge/bridge_test.goindex ec26e677..f153367e 100644--- a/internal/bridge/bridge_test.go+++ b/internal/bridge/bridge_test.go@@ -1,8 +1,11 @@package bridgeimport (+ "context""sync""testing"++ "github.com/pinchtab/pinchtab/internal/config")func newTestBridge() *Bridge {@@ -64,3 +67,25 @@ func TestRefCacheLookup(t *testing.T) {t.Error("e99 should not exist")}}++func TestTabManagerRemoteAllocatorInitialization(t *testing.T) {+ // Test that TabManager can be initialized without a valid browser context.+ // This is the case for remote allocators (CDP_URL mode) where the browser+ // context is established lazily.+ cfg := &config.RuntimeConfig{+ CdpURL: "ws://localhost:9222/devtools/browser/test",+ }++ // Use context.TODO() instead of nil to avoid lint warnings+ ctx := context.TODO()+ tm := NewTabManager(ctx, cfg, nil)+ if tm == nil {+ t.Error("TabManager should be created")+ }++ // Attempting to create a tab with an invalid context should fail gracefully+ _, _, _, err := tm.CreateTab("about:blank")+ if err == nil {+ t.Error("CreateTab should fail when browserCtx is invalid")+ }+}diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.goindex 838cf94b..edf2bbba 100644--- a/internal/bridge/tab_manager.go+++ b/internal/bridge/tab_manager.go@@ -115,7 +115,32 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.Careturn "", nil, nil, fmt.Errorf("tab limit reached (%d/%d) — close a tab first", len(targets), tm.config.MaxTabs)}}- ctx, cancel := chromedp.NewContext(tm.browserCtx)++ // Use target.CreateTarget CDP protocol call to create a new tab.+ // This works for both local and remote (CDP_URL) allocators.+ navURL := "about:blank"+ if url != "" {+ navURL = url+ }++ var targetID target.ID+ createCtx, createCancel := context.WithTimeout(tm.browserCtx, 10*time.Second)+ if err := chromedp.Run(createCtx,+ chromedp.ActionFunc(func(ctx context.Context) error {+ var err error+ targetID, err = target.CreateTarget(navURL).Do(ctx)+ return err+ }),+ ); err != nil {+ createCancel()+ return "", nil, nil, fmt.Errorf("create target: %w", err)+ }+ createCancel()++ // Create a context for the new tab+ ctx, cancel := chromedp.NewContext(tm.browserCtx,+ chromedp.WithTargetID(targetID),+ )if tm.onTabSetup != nil {tm.onTabSetup(ctx)@@ -127,16 +152,7 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.Ca_ = SetResourceBlocking(ctx, ImageBlockPatterns)}- navURL := "about:blank"- if url != "" {- navURL = url- }- if err := NavigatePage(ctx, navURL); err != nil {- cancel()- return "", nil, nil, fmt.Errorf("new tab: %w", err)- }-- newTargetID := string(chromedp.FromContext(ctx).Target.TargetID)+ newTargetID := string(targetID)tm.mu.Lock()tm.tabs[newTargetID] = &TabEntry{Ctx: ctx, Cancel: cancel}tm.accessed[newTargetID] = truediff --git a/skill/pinchtab/SKILL.md b/skill/pinchtab/SKILL.mdindex 96578e38..a3f2c389 100644--- a/skill/pinchtab/SKILL.md+++ b/skill/pinchtab/SKILL.md@@ -1,5 +1,6 @@---name: pinchtab+version: 0.6.2description: >Control a headless or headed Chrome browser via Pinchtab's HTTP API. Use for web automation,scraping, form filling, navigation, and multi-tab workflows. Pinchtab exposes the accessibilitydiff --git a/tests/cf3-cdp-create-tab-repro.md b/tests/cf3-cdp-create-tab-repro.mdnew file mode 100644index 00000000..1f45e799--- /dev/null+++ b/tests/cf3-cdp-create-tab-repro.md@@ -0,0 +1,145 @@+# CF3-Extended: Create Tab via POST in CDP_URL Mode++**Status:** 🔴 FAILING (Issue #13)++**Goal:** Reproduce the crash when creating a new tab via `POST /tab` in CDP_URL mode.++## Prerequisites++- Chrome/Chromium installed+- `curl` CLI+- `jq` for JSON parsing (optional, but helpful)++## Test Steps++### Step 1: Start Chrome with Remote Debugging++```bash+# Kill any existing Chrome instances on port 9222+pkill -f "remote-debugging-port=9222" || true++# Start Chrome with CDP port open (macOS)+# IMPORTANT: Use --headless=chrome NOT --headless (legacy mode with GUI support)+/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome \+ --remote-debugging-port=9222 \+ --no-first-run \+ --no-default-browser-check \+ --disable-background-networking \+ --new-window &++sleep 3++# Verify it's listening+curl -s http://localhost:9222/json/version | jq . && echo "✅ Chrome listening on port 9222"+```++### Step 2: Get the CDP WebSocket URL++```bash+CDP_WS=$(curl -s http://localhost:9222/json/version | jq -r '.webSocketDebuggerUrl')+echo "CDP WebSocket URL: $CDP_WS"+```++Example: `ws://localhost:9222/devtools/browser/12345...`++### Step 3: Start Pinchtab in CDP_URL Mode++```bash+# From pinchtab root+CDP_URL="$CDP_WS" ./pinchtab &+sleep 2++curl http://localhost:9222/health && echo "✅ Pinchtab started"+```++Expected: Pinchtab should start and connect to remote Chrome without launching its own.++### Step 4: Verify Initial Connection (Should Pass)++```bash+curl -s http://localhost:9222/snapshot | jq '.nodes | length' && echo "✅ Can snapshot"+```++### Step 5: Pinchtab Startup Fails (Reproducible ❌)++Pinchtab doesn't even start successfully. It crashes during initialization when trying to set up the remote browser context.++**Actual broken behavior:**+```+2026/02/23 12:29:59 WARN Chrome startup failed, clearing sessions and retrying once+err="Failed to open new tab - no browser is open (-32000)"+2026/02/23 12:29:59 ERROR Chrome failed to start after retry+err="Failed to open new tab - no browser is open (-32000)"+```++**Why it happens:**+- Pinchtab's `startChrome()` function (browser.go line 94) calls `NavigatePage()` to open about:blank+- When using a remote allocator, `NavigatePage()` fails because the remote Chrome instance has no open window/tab to attach to+- No graceful fallback: Pinchtab retries once then exits+- The error should be handled differently for CDP_URL mode (don't require initial tab, respect existing Chrome state)++## Cleanup++```bash+pkill -f "pinchtab"+pkill -f "remote-debugging-port=9222"+```++## Root Cause++**Primary:** In `cmd/pinchtab/browser.go`, `startChrome()` (line 94) always calls `NavigatePage(ctx, "about:blank")` to set up initial state. This assumes a tab already exists or can be created.++**For CDP_URL mode:** Remote Chrome instances may have no windows open, so `NavigatePage()` fails with `-32000` ("Failed to open new tab - no browser is open").++**Secondary:** In `internal/bridge/tab_manager.go`, `CreateTab()` (line 65) doesn't distinguish between:+- Local allocator (can create tabs freely)+- Remote allocator (must use `target.CreateTarget` CDP protocol call, or check browser state first)++## Affected Code++```go+// browser.go, line 94-99+func startChrome(allocCtx context.Context, seededScript string) (context.Context, context.CancelFunc, error) {+ bCtx, bCancel := chromedp.NewContext(allocCtx)+ // ...+ if err := NavigatePage(ctx, "about:blank"); err != nil { // ← FAILS for CDP_URL mode+ bCancel()+ return nil, nil, err+ }+}++// tab_manager.go, line 65+func (tm *TabManager) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {+ ctx, cancel := chromedp.NewContext(tm.browserCtx) // ← CRASHES for remote+ if err := NavigatePage(ctx, navURL); err != nil {+ cancel()+ return "", nil, nil, fmt.Errorf("new tab: %w", err)+ }+}+```++## Fix Strategy++1. **In `browser.go` `startChrome()`:**+ - Check if we're using CDP_URL mode (can detect via allocator type or config)+ - If CDP_URL: Skip `NavigatePage()` during startup (browser may have no windows yet)+ - If local: Keep existing behavior (ensure about:blank is open)++2. **In `tab_manager.go` `CreateTab()`:**+ - Use `target.CreateTarget` CDP protocol call instead of relying on `chromedp.NewContext`+ - This works for both local and remote allocators+ - Example:+ ```go+ targetID, err := target.CreateTarget("about:blank").Do(ctx) // Use CDP protocol directly+ ```++3. **Test coverage:**+ - Add unit test: `TestCreateTabCDPURL` in `tab_manager_test.go`+ - Add integration test: CF3-ext in TEST-PLAN.md++## Status++✅ **Issue is reproducible and scoped.**+- Failure point: `startChrome()` in CDP_URL mode+- Secondary: `CreateTab()` also needs CDP protocol-based approach+- Test: This markdown file documents the repro steps