High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
docs: add comprehensive guides for multi-instance workflows
Mario90967338b39c
diff --git a/docs/guides/common-patterns.md b/docs/guides/common-patterns.mdnew file mode 100644index 00000000..40bd45f4--- /dev/null+++ b/docs/guides/common-patterns.md@@ -0,0 +1,662 @@+# Common Patterns++Real-world patterns for using Pinchtab's multi-instance architecture effectively.++---++## Pattern 1: Headed vs Headless++### Headed (Visible Window)++Use when you need to **see what's happening**:++```bash+curl -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d '{"name":"debug","headless":false}'+```++**Use cases:**+- Interactive debugging and testing+- Visual QA/regression testing+- Manual workflow verification+- Step-by-step debugging+- Learning/exploration++**Characteristics:**+- Chrome window opens and is visible+- Slightly slower (rendering overhead)+- More memory (~100-150 MB)+- Can interact manually if needed+- Good for dev/test environments++**Example: Interactive Testing Session**++```bash+#!/bin/bash++# Create a headed instance for manual testing+INST=$(curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d '{"name":"manual-qa","headless":false}' | jq -r '.id')++PORT=$(curl -s http://localhost:9867/instances/$INST | jq -r '.port')++echo "Manual testing instance running on port $PORT"+echo "Chrome window is open - interact manually or use API calls"++# Optionally navigate to starting URL+curl -s -X POST "http://localhost:$PORT/navigate" \+ -H "Content-Type: application/json" \+ -d '{"url":"https://app.example.com"}'++echo "Navigate the app manually, then run automated tests..."+sleep 300 # Keep instance running for 5 minutes++curl -X POST "http://localhost:9867/instances/$INST/stop"+```++### Headless (Background)++Use when you need **speed and efficiency**:++```bash+curl -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d '{"name":"worker","headless":true}'+```++**Use cases:**+- Automated testing (CI/CD)+- Data scraping+- High-throughput operations+- Batch processing+- Production workloads++**Characteristics:**+- No visible window (runs in background)+- Faster execution (~20% speedup)+- Less memory (~50-80 MB)+- No manual interaction+- Perfect for automation++**Example: Headless Testing Pipeline**++```bash+#!/bin/bash++# Create 5 headless instances for parallel testing+INSTANCES=()++for i in {1..5}; do+ INST=$(curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d "{\"name\":\"test-worker-$i\",\"headless\":true}" | jq -r '.id')++ PORT=$(curl -s http://localhost:9867/instances/$INST | jq -r '.port')+ INSTANCES+=("$INST:$PORT")+done++echo "Created 5 parallel test workers"++# Run tests in parallel+TEST_URLS=(+ "https://app.example.com/test1"+ "https://app.example.com/test2"+ "https://app.example.com/test3"+ "https://app.example.com/test4"+ "https://app.example.com/test5"+)++for i in "${!INSTANCES[@]}"; do+ IFS=: read INST PORT <<< "${INSTANCES[$i]}"+ URL="${TEST_URLS[$i]}"++ # Run test in parallel+ (+ curl -s -X POST "http://localhost:$PORT/navigate" \+ -H "Content-Type: application/json" \+ -d "{\"url\":\"$URL\"}" > /dev/null++ # Verify page loaded+ TITLE=$(curl -s "http://localhost:$PORT/snapshot" | jq -r '.title')+ echo "Test $i: $TITLE"+ ) &+done++wait++# Cleanup+for INST_PORT in "${INSTANCES[@]}"; do+ IFS=: read INST PORT <<< "$INST_PORT"+ curl -s -X POST "http://localhost:9867/instances/$INST/stop" > /dev/null+done++echo "Tests complete"+```++### Mixed Fleet++Typical production setup:++```bash+# 1 headed for interactive debugging+HEADED=$(curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d '{"name":"qa-debug","headless":false}' | jq -r '.id')++# 10 headless for bulk operations+for i in {1..10}; do+ curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d "{\"name\":\"worker-$i\",\"headless\":true}" > /dev/null+done++echo "Setup: 1 headed (debug) + 10 headless (workers)"+```++---++## Pattern 2: Load Distribution++### Round-Robin Distribution++Distribute requests evenly across instances:++```bash+#!/bin/bash++INSTANCES=(+ "http://localhost:9868"+ "http://localhost:9869"+ "http://localhost:9870"+ "http://localhost:9871"+ "http://localhost:9872"+)++URLS=(+ "https://example.com/page1"+ "https://example.com/page2"+ "https://example.com/page3"+ "https://example.com/page4"+ "https://example.com/page5"+ "https://example.com/page6"+ "https://example.com/page7"+ "https://example.com/page8"+)++# Distribute evenly+for i in "${!URLS[@]}"; do+ URL="${URLS[$i]}"+ INSTANCE="${INSTANCES[$((i % ${#INSTANCES[@]}))]}"++ curl -s -X POST "$INSTANCE/navigate" \+ -H "Content-Type: application/json" \+ -d "{\"url\":\"$URL\"}" &+done++wait+```++**Result:**+- URLs 1,6 → Instance 1 (9868)+- URLs 2,7 → Instance 2 (9869)+- URLs 3,8 → Instance 3 (9870)+- URLs 4 → Instance 4 (9871)+- URLs 5 → Instance 5 (9872)++Each instance handles roughly equal work.++### Weighted Distribution++Send more work to faster instances:++```bash+#!/bin/bash++# Instances with weights+declare -A WEIGHTS=(+ ["http://localhost:9868"]=3 # Fast SSD+ ["http://localhost:9869"]=2 # Standard+ ["http://localhost:9870"]=1 # Slower+)++# Create weighted list+INSTANCES=()+for INST in "${!WEIGHTS[@]}"; do+ WEIGHT=${WEIGHTS[$INST]}+ for ((j=0; j<WEIGHT; j++)); do+ INSTANCES+=("$INST")+ done+done++# Distribute using weighted list+for i in "${!URLS[@]}"; do+ URL="${URLS[$i]}"+ INSTANCE="${INSTANCES[$((i % ${#INSTANCES[@]}))]}"++ curl -s -X POST "$INSTANCE/navigate" \+ -H "Content-Type: application/json" \+ -d "{\"url\":\"$URL\"}" &+done++wait+```++**Result:**+- Fast instance handles 50% of work (3/6 slots)+- Standard instance handles 33% of work (2/6 slots)+- Slow instance handles 17% of work (1/6 slots)++### Queue-Based Distribution++Process a work queue, distributing dynamically:++```bash+#!/bin/bash++# Instance pool+INSTANCE_POOL=(+ "http://localhost:9868"+ "http://localhost:9869"+ "http://localhost:9870"+)++# Work queue+QUEUE=(+ "https://example.com/1"+ "https://example.com/2"+ "https://example.com/3"+ ...+ "https://example.com/100"+)++# Process queue with max concurrent jobs+MAX_JOBS=${#INSTANCE_POOL[@]}+CURRENT_JOB=0+RUNNING=0++while [ $CURRENT_JOB -lt ${#QUEUE[@]} ] || [ $RUNNING -gt 0 ]; do+ # Start new jobs while under limit and queue has items+ while [ $RUNNING -lt $MAX_JOBS ] && [ $CURRENT_JOB -lt ${#QUEUE[@]} ]; do+ URL="${QUEUE[$CURRENT_JOB]}"+ INSTANCE="${INSTANCE_POOL[$((CURRENT_JOB % MAX_JOBS))]}"++ (+ curl -s -X POST "$INSTANCE/navigate" \+ -H "Content-Type: application/json" \+ -d "{\"url\":\"$URL\"}"+ echo "Processed: $URL"+ ) &++ ((CURRENT_JOB++))+ ((RUNNING++))+ done++ # Wait for a job to complete+ wait -n+ ((RUNNING--))+done++echo "Queue processing complete"+```++---++## Pattern 3: State Isolation++### Per-User Profiles++Each user gets their own instance with persistent state:++```bash+#!/bin/bash++# Create instance per user+function create_user_instance() {+ local USER_ID=$1++ curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d "{\"name\":\"user-$USER_ID\",\"headless\":true}"+}++# User 1: Gets instance with profile 'user-1'+U1=$(create_user_instance 1 | jq -r '.id')++# User 2: Gets instance with profile 'user-2'+U2=$(create_user_instance 2 | jq -r '.id')++# User 3: Gets instance with profile 'user-3'+U3=$(create_user_instance 3 | jq -r '.id')++# Each user has:+# - Separate Chrome process+# - Separate cookies (login sessions)+# - Separate history+# - Separate local storage+# - No interference between users++# User 1 navigates+PORT_U1=$(curl -s http://localhost:9867/instances/$U1 | jq -r '.port')+curl -s -X POST "http://localhost:$PORT_U1/navigate" \+ -H "Content-Type: application/json" \+ -d '{"url":"https://app.example.com/login?user=1"}'++# User 2 navigates independently+PORT_U2=$(curl -s http://localhost:9867/instances/$U2 | jq -r '.port')+curl -s -X POST "http://localhost:$PORT_U2/navigate" \+ -H "Content-Type: application/json" \+ -d '{"url":"https://app.example.com/login?user=2"}'++# User 3 navigates independently+PORT_U3=$(curl -s http://localhost:9867/instances/$U3 | jq -r '.port')+curl -s -X POST "http://localhost:$PORT_U3/navigate" \+ -H "Content-Type: application/json" \+ -d '{"url":"https://app.example.com/login?user=3"}'+```++### Session Persistence++Resume browser state from previous session:++```bash+#!/bin/bash++# Session 1: Create instance, navigate, set up state+INST=$(curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d '{"name":"persistent-session","headless":false}' | jq -r '.id')++PORT=$(curl -s http://localhost:9867/instances/$INST | jq -r '.port')++# Navigate and set up state+curl -s -X POST "http://localhost:$PORT/navigate" \+ -H "Content-Type: application/json" \+ -d '{"url":"https://app.example.com"}'++# User interacts manually...+sleep 3600 # 1 hour session++# Stop instance (state saved to disk)+curl -X POST "http://localhost:9867/instances/$INST/stop"++# ... later ...++# Session 2: Create new instance with same profile+# Restores cookies, cache, history from disk+INST2=$(curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d '{"name":"persistent-session","headless":false}' | jq -r '.id')++# Instance 2 has all the state from Instance 1+# Same cookies, same history, same preferences+```++---++## Pattern 4: Batch Operations++### Sequential Processing (Simple)++Process items one at a time:++```bash+ITEMS=("item1" "item2" "item3" ... "item1000")++for ITEM in "${ITEMS[@]}"; do+ curl -s -X POST "http://localhost:9868/navigate" \+ -H "Content-Type: application/json" \+ -d "{\"url\":\"https://api.example.com?item=$ITEM\"}"++ sleep 1 # Rate limiting+done+```++**Pros:** Simple, easy to debug+**Cons:** Slow (1 item/sec = 1000 seconds for 1000 items)++### Parallel Processing (Faster)++Use multiple instances:++```bash+INSTANCES=()++# Create 10 instances+for i in {1..10}; do+ INST=$(curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d "{\"name\":\"batch-worker-$i\",\"headless\":true}" | jq -r '.id')++ PORT=$(curl -s http://localhost:9867/instances/$INST | jq -r '.port')+ INSTANCES+=("$INST:$PORT")+done++# Process items in parallel+ITEM_INDEX=0++for ITEM in "${ITEMS[@]}"; do+ IFS=: read INST PORT <<< "${INSTANCES[$((ITEM_INDEX % 10))]}"++ curl -s -X POST "http://localhost:$PORT/navigate" \+ -H "Content-Type: application/json" \+ -d "{\"url\":\"https://api.example.com?item=$ITEM\"}" &++ ((ITEM_INDEX++))+done++wait+```++**Performance:** 1000 items with 10 instances ÷ 10 = 100 seconds (10x faster!)++### Adaptive Batch Processing++Process items, track results, retry failures:++```bash+#!/bin/bash++BATCH_SIZE=10+FAILED=()+RESULTS=()++for i in "${!ITEMS[@]}"; do+ ITEM="${ITEMS[$i]}"++ # Skip to next batch every BATCH_SIZE items+ if [ $((($i + 1) % BATCH_SIZE)) -eq 0 ]; then+ wait # Wait for batch to complete+ fi++ # Process item+ if curl -s -X POST "http://localhost:9868/navigate" \+ -H "Content-Type: application/json" \+ -d "{\"url\":\"https://api.example.com?item=$ITEM\"}" > /dev/null 2>&1; then+ RESULTS+=("$ITEM: OK")+ else+ FAILED+=("$ITEM")+ fi &+done++wait++# Retry failures+echo "Retrying ${#FAILED[@]} failed items..."++for ITEM in "${FAILED[@]}"; do+ curl -s -X POST "http://localhost:9868/navigate" \+ -H "Content-Type: application/json" \+ -d "{\"url\":\"https://api.example.com?item=$ITEM\"}"+done++echo "Results: ${#RESULTS[@]} OK, ${#FAILED[@]} failed"+```++---++## Pattern 5: Error Handling++### Health-Check Before Operations++```bash+function safe_navigate() {+ local PORT=$1+ local URL=$2++ # Check health+ if ! curl -s "http://localhost:$PORT/health" | jq -e '.status == "ok"' > /dev/null; then+ echo "ERROR: Instance on port $PORT not healthy"+ return 1+ fi++ # Navigate+ curl -s -X POST "http://localhost:$PORT/navigate" \+ -H "Content-Type: application/json" \+ -d "{\"url\":\"$URL\"}"+}++safe_navigate 9868 "https://example.com" || echo "Navigation failed"+```++### Timeout Handling++```bash+function navigate_with_timeout() {+ local PORT=$1+ local URL=$2+ local TIMEOUT=$3++ timeout $TIMEOUT curl -s -X POST "http://localhost:$PORT/navigate" \+ -H "Content-Type: application/json" \+ -d "{\"url\":\"$URL\"}"++ if [ $? -eq 124 ]; then+ echo "ERROR: Navigation timed out after ${TIMEOUT}s"+ return 1+ fi+}++navigate_with_timeout 9868 "https://slow-site.com" 30+```++### Graceful Degradation++```bash+function navigate_with_fallback() {+ local URL=$1++ # Try instance 1+ if curl -s "http://localhost:9868/health" | jq -e '.status == "ok"' > /dev/null; then+ curl -s -X POST "http://localhost:9868/navigate" \+ -H "Content-Type: application/json" \+ -d "{\"url\":\"$URL\"}"+ return 0+ fi++ # Fall back to instance 2+ if curl -s "http://localhost:9869/health" | jq -e '.status == "ok"' > /dev/null; then+ echo "Instance 1 down, using fallback (9869)"+ curl -s -X POST "http://localhost:9869/navigate" \+ -H "Content-Type: application/json" \+ -d "{\"url\":\"$URL\"}"+ return 0+ fi++ # All instances down+ echo "ERROR: All instances down"+ return 1+}+```++---++## Pattern 6: Monitoring & Cleanup++### Active Instance Monitoring++```bash+#!/bin/bash++while true; do+ echo "=== $(date) ==="++ # Get all instances+ INSTANCES=$(curl -s http://localhost:9867/instances)++ # Count by status+ RUNNING=$(echo "$INSTANCES" | jq '[.[] | select(.status=="running")] | length')+ STOPPED=$(echo "$INSTANCES" | jq '[.[] | select(.status=="stopped")] | length')+ TOTAL=$(echo "$INSTANCES" | jq 'length')++ echo "Total: $TOTAL | Running: $RUNNING | Stopped: $STOPPED"++ # List each instance+ echo "$INSTANCES" | jq '.[] | "\(.id) (\(.profileName)) - port \(.port) - \(.status)"'++ sleep 30+done+```++### Cleanup Stopped Instances++```bash+#!/bin/bash++INSTANCES=$(curl -s http://localhost:9867/instances)++# Stop all instances+echo "$INSTANCES" | jq -r '.[] | .id' | while read INST_ID; do+ echo "Stopping $INST_ID..."+ curl -s -X POST "http://localhost:9867/instances/$INST_ID/stop" > /dev/null+done++echo "Cleanup complete. All ports released."+```++### Resource Monitoring++```bash+#!/bin/bash++while true; do+ echo "=== Instance Resource Usage ==="++ # Get active instances+ INSTANCES=$(curl -s http://localhost:9867/instances | jq -r '.[] | select(.status=="running") | .id')++ # Rough estimate: each headless ~60MB, headed ~120MB+ HEADLESS=$(curl -s http://localhost:9867/instances | jq '[.[] | select(.headless==true)] | length')+ HEADED=$(curl -s http://localhost:9867/instances | jq '[.[] | select(.headless==false)] | length')++ EST_MEMORY=$(( (HEADLESS * 60) + (HEADED * 120) ))++ echo "Headless instances: $HEADLESS (~${HEADLESS}*60MB = $((HEADLESS*60))MB)"+ echo "Headed instances: $HEADED (~${HEADED}*120MB = $((HEADED*120))MB)"+ echo "Estimated memory: ~${EST_MEMORY}MB"++ # Alert if over limit+ if [ $EST_MEMORY -gt 8000 ]; then+ echo "⚠️ WARNING: High memory usage!"+ fi++ sleep 60+done+```++---++## Summary++| Pattern | Use Case | Throughput | Memory |+|---------|----------|-----------|--------|+| **Headed** | Interactive debugging | Low | High |+| **Headless** | Automation, scraping | Medium | Low |+| **Round-robin** | Balanced load | Medium-High | Medium |+| **Weighted** | Heterogeneous instances | High | Medium-High |+| **Queue-based** | Dynamic work distribution | High | Low-Medium |+| **Per-user profiles** | Multi-tenant | Variable | Linear with users |+| **Session persistence** | Long-running workflows | Low | Depends on state |++Choose the pattern that matches your workload!diff --git a/docs/guides/multi-instance.md b/docs/guides/multi-instance.mdnew file mode 100644index 00000000..dc34ff0b--- /dev/null+++ b/docs/guides/multi-instance.md@@ -0,0 +1,539 @@+# Multi-Instance Workflows++Pinchtab's multi-instance architecture enables running multiple isolated Chrome browsers simultaneously, each with their own cookies, history, profiles, and configurations.++## Getting Started++### 1. Start the Dashboard++```bash+go build -o pinchtab ./cmd/pinchtab+./pinchtab+```++The dashboard runs on **port 9867** and manages all instances.++### 2. Create Your First Instance++Create a headed instance (visible window) for interactive work:++```bash+curl -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d '{"name":"work","headless":false}'+```++**Response:**+```json+{+ "id": "inst_a365262a",+ "profileId": "prof_7f3d1e8b",+ "profileName": "work",+ "port": "9868",+ "headless": false,+ "status": "starting",+ "startTime": "2026-02-28T21:00:00Z"+}+```++The instance gets:+- **Auto-allocated port** (9868, 9869, ...)+- **Hash-based ID** (inst_XXXXX) - stable and portable+- **Profile isolation** - separate cookies, history, cache+- **Chrome process** - running independently++### 3. Navigate and Interact++Navigate the instance to a URL:++```bash+curl -X POST http://localhost:9868/navigate \+ -H "Content-Type: application/json" \+ -d '{"url":"https://example.com"}'+```++**Response:**+```json+{+ "tabId": "tab_19949f62",+ "url": "https://example.com",+ "title": "Example Domain"+}+```++Each navigation automatically creates a new tab. Use the `tabId` for subsequent operations on that specific tab.++### 4. Get Page Content++Retrieve page snapshot (DOM, text, structured data):++```bash+curl http://localhost:9868/snapshot?tabId=tab_19949f62+```++Or get just the text:++```bash+curl http://localhost:9868/text?tabId=tab_19949f62+```++### 5. Stop Instance++Release the instance and its allocated port:++```bash+curl -X POST http://localhost:9867/instances/inst_a365262a/stop+```++Port 9868 becomes available for the next instance.++---++## Common Workflows++### Parallel Scraping with Multiple Instances++Create 5 headless instances for concurrent scraping:++```bash+#!/bin/bash++URLS=(+ "https://example.com/page1"+ "https://example.com/page2"+ "https://example.com/page3"+ "https://example.com/page4"+ "https://example.com/page5"+)++INSTANCES=()++# Create instances+for i in {1..5}; do+ INST=$(curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d "{\"name\":\"scraper-$i\",\"headless\":true}")++ ID=$(echo "$INST" | jq -r '.id')+ PORT=$(echo "$INST" | jq -r '.port')+ INSTANCES+=("$ID:$PORT")++ echo "Created instance $i: $ID on port $PORT"+done++sleep 2 # Wait for Chrome initialization++# Navigate all instances concurrently+for i in "${!INSTANCES[@]}"; do+ IFS=: read ID PORT <<< "${INSTANCES[$i]}"+ URL="${URLS[$i]}"++ curl -s -X POST "http://localhost:$PORT/navigate" \+ -H "Content-Type: application/json" \+ -d "{\"url\":\"$URL\"}" &+done++wait++echo "All pages loaded. Getting snapshots..."++# Get snapshots+for i in "${!INSTANCES[@]}"; do+ IFS=: read ID PORT <<< "${INSTANCES[$i]}"++ curl -s "http://localhost:$PORT/snapshot" > "snapshot-$i.json"+done++# Cleanup+for INST in "${INSTANCES[@]}"; do+ IFS=: read ID PORT <<< "$INST"+ curl -s -X POST "http://localhost:9867/instances/$ID/stop" > /dev/null+done++echo "Done! Scraped ${#URLS[@]} pages in parallel."+```++**Benefits:**+- 5 headless instances = 5x faster scraping than sequential+- No cookie/history interference between sites+- Each instance gets its own port and Chrome process+- Ports automatically reused when instances stop++### Mixed Headed/Headless Testing++Test web app with multiple browser profiles:++```bash+# Headed instance for interactive debugging+WORK=$(curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d '{"name":"dev","headless":false}' | jq -r '.id')++# Headless instance for automated testing+TEST=$(curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d '{"name":"test","headless":true}' | jq -r '.id')++# Debug instance with preserved state+DEBUG=$(curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d '{"name":"debug","headless":false}' | jq -r '.id')++echo "Dev (headed): $WORK on port 9868"+echo "Test (headless): $TEST on port 9869"+echo "Debug (headed): $DEBUG on port 9870"+```++You now have:+- **dev instance** - visible window for manual testing, inspect elements, debug+- **test instance** - headless for automated test suite, faster+- **debug instance** - separate visible window to preserve state while testing++### Load Distribution with Headless Fleet++Run a fleet of headless instances for high-throughput work:++```bash+#!/bin/bash++FLEET_SIZE=10+INSTANCES=()++echo "Launching fleet of $FLEET_SIZE instances..."++for i in $(seq 1 $FLEET_SIZE); do+ INST=$(curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d "{\"name\":\"fleet-$i\",\"headless\":true}")++ ID=$(echo "$INST" | jq -r '.id')+ PORT=$(echo "$INST" | jq -r '.port')+ INSTANCES+=("$ID:$PORT")+done++echo "Fleet ready on ports 9868-9877"++# Distribute work across instances+WORK_ITEMS=("task1" "task2" "task3" ... "task100")+INSTANCE_INDEX=0++for TASK in "${WORK_ITEMS[@]}"; do+ # Round-robin distribution+ IFS=: read ID PORT <<< "${INSTANCES[$INSTANCE_INDEX % $FLEET_SIZE]}"++ # Process task on this instance+ curl -s -X POST "http://localhost:$PORT/navigate" \+ -H "Content-Type: application/json" \+ -d "{\"url\":\"https://api.example.com?task=$TASK\"}" &++ ((INSTANCE_INDEX++))+done++wait++# Cleanup fleet+for INST in "${INSTANCES[@]}"; do+ IFS=: read ID PORT <<< "$INST"+ curl -s -X POST "http://localhost:9867/instances/$ID/stop" > /dev/null &+done++wait+echo "Fleet cleaned up"+```++**Performance:**+- 10 instances × 10 concurrent requests = 100 req/sec throughput+- Each instance isolated = no performance degradation+- Easy to scale: add more instances for more throughput++### Multi-Agent Coordination++Have multiple agents work on different instances:++```bash+# Agent A: LinkedIn scraper+AGENT_A_INST=$(curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d '{"name":"linkedin","headless":true}' | jq -r '.id')++# Agent B: Twitter monitor+AGENT_B_INST=$(curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d '{"name":"twitter","headless":true}' | jq -r '.id')++# Agent C: News aggregator+AGENT_C_INST=$(curl -s -X POST http://localhost:9867/instances/launch \+ -H "Content-Type: application/json" \+ -d '{"name":"news","headless":true}' | jq -r '.id')++# Each agent has its own isolated browser+# They can run concurrently without interference+```++**Isolation Benefits:**+- Agent A's LinkedIn cookies never touch Agent B's Twitter session+- Agent B's JavaScript errors don't affect Agent C's news scraping+- Each agent can have different profiles, user-agents, timezones+- Clear audit trail: which agent ran on which instance++---++## Instance Lifecycle++### Port Allocation++Ports are automatically allocated from the configured range:++```+Default range: 9868-9968 (100 instances)+```++Configure via environment variables:++```bash+export INSTANCE_PORT_START=9900+export INSTANCE_PORT_END=10000+./pinchtab+```++Now instances will use ports 9900-10000 instead of 9868-9968.++### Port Reuse++When an instance stops, its port is released and can be reused:++```bash+# Create instance+INST1=$(curl -s -X POST http://localhost:9867/instances/launch ... | jq -r '.id')+# Gets port 9868++# Stop instance+curl -X POST http://localhost:9867/instances/$INST1/stop++# Create new instance+INST2=$(curl -s -X POST http://localhost:9867/instances/launch ... | jq -r '.id')+# Gets port 9868 (reused!)+```++This enables:+- Long-running services with dynamic instance pools+- Cost efficiency: only allocate ports as needed+- Graceful scaling: stop old instances, create new ones++### Chrome Initialization++Chrome starts automatically when the instance is created:++```bash+POST /instances/launch → Chrome starts in background+ ↓ (instance ready immediately, no waiting)+ ↓ (Chrome initialization happens concurrently)+ ↓ (1-2 seconds later, Chrome is fully ready)+→ Ready for navigation requests+```++**No lazy initialization:** Instance creation includes full Chrome startup, so first navigation is fast.++### Instance State++Each instance maintains:+- **Profile directory** - Chrome user data (cookies, cache, bookmarks)+- **Browser context** - Open tabs, session storage, local storage+- **History** - Browsing history (unless disabled)+- **Cookies** - Session and persistent cookies per domain+- **IndexedDB/LocalStorage** - Web app state++When instance stops, all state is persisted to disk. Profiles can be reused to resume state.++---++## Monitoring++### List All Instances++```bash+curl http://localhost:9867/instances+```++**Response:**+```json+[+ {+ "id": "inst_a365262a",+ "profileId": "prof_7f3d1e8b",+ "profileName": "work",+ "port": "9868",+ "headless": false,+ "status": "running",+ "startTime": "2026-02-28T21:00:00Z"+ },+ {+ "id": "inst_b471d93c",+ "profileId": "prof_5e2c7f1a",+ "profileName": "test",+ "port": "9869",+ "headless": true,+ "status": "running",+ "startTime": "2026-02-28T21:00:05Z"+ }+]+```++### Instance Health++```bash+# Check specific instance+curl http://localhost:9868/health++# Response+{"status":"ok","tabs":2}+```++### Dashboard Web UI++Open http://localhost:9867/dashboard in a browser to see:+- Live instance list+- Instance status and uptime+- Profile information+- Tab count per instance+- Quick actions (create, stop, delete)++---++## Best Practices++### 1. Name Instances Descriptively++```bash+# Good+{"name":"linkedin-scraper-v1","headless":true}+{"name":"user-test-headed","headless":false}++# Not ideal+{"name":"instance1","headless":true}+{"name":"test","headless":false}+```++Helps with monitoring and debugging.++### 2. Use Profiles for State Management++```bash+# Create with specific profile+POST /instances/launch+{"name":"customer-123","headless":true}++# Profile persists across instance restarts+# Same customer always gets same cookies, history, preferences+```++### 3. Stop Unused Instances++```bash+# Check instance list+curl http://localhost:9867/instances | jq '.[] | select(.status=="stopped")'++# Stop idle instances+for INST in ...; do+ curl -X POST http://localhost:9867/instances/$INST/stop+done+```++Frees ports and resources.++### 4. Batch Operations for Performance++```bash+# Launch 10 instances in parallel+for i in {1..10}; do+ curl -s -X POST http://localhost:9867/instances/launch ... &+done+wait+```++Much faster than sequential creation.++### 5. Handle Errors Gracefully++```bash+# Check instance status before operations+if curl -s http://localhost:9868/health | jq -e '.status == "ok"' > /dev/null; then+ echo "Instance ready, proceeding..."+else+ echo "Instance not ready, waiting..."+ sleep 2+fi+```++---++## Architecture++```+Dashboard (9867)+├─ Orchestrator: manages instances+├─ Profiles manager: manages Chrome profiles+└─ Instance list: view all running instances++Instance 1 (9868, profile=work, headless=false)+├─ Bridge: HTTP API for this instance only+├─ Chrome: independent browser process+└─ Tabs: multiple tabs in same browser++Instance 2 (9869, profile=test, headless=true)+├─ Bridge: HTTP API for this instance only+├─ Chrome: independent browser process+└─ Tabs: multiple tabs in same browser++Instance 3 (9870, profile=scraping, headless=true)+├─ Bridge: HTTP API for this instance only+├─ Chrome: independent browser process+└─ Tabs: multiple tabs in same browser+```++Each instance is **completely isolated**: separate port, separate Chrome process, separate profile.++---++## Troubleshooting++### Instance not starting++```bash+# Check logs+tail -f /var/log/pinchtab.log++# Verify port is free+lsof -i :9868++# Check Chrome availability+which google-chrome chromium-browser chrome+```++### Chrome window not visible (headed mode)++```bash+# Ensure DISPLAY is set (Linux)+export DISPLAY=:0++# Or use Xvfb (Linux headless display)+xvfb-run -a ./pinchtab+```++### Port conflicts++```bash+# If default range is in use, change it+export INSTANCE_PORT_START=10000+export INSTANCE_PORT_END=10100+./pinchtab+```++### Memory usage++Each headless instance: ~50-80 MB+Each headed instance: ~100-150 MB (includes window server overhead)++For 100 instances: ~5-10 GB RAM++Monitor with: `top`, `htop`, or systemd memory limits