High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
docs: reference section update
Luigi Agostiec7bd0ad0837
diff --git a/docs/references/cli-design.md b/docs/architecture/cli-design.mdsimilarity index 100%rename from docs/references/cli-design.mdrename to docs/architecture/cli-design.mddiff --git a/docs/references/cli-quick-reference.md b/docs/architecture/cli-quick-reference.mdsimilarity index 100%rename from docs/references/cli-quick-reference.mdrename to docs/architecture/cli-quick-reference.mddiff --git a/docs/architecture/dashboard-ui.md b/docs/architecture/dashboard-ui.mddeleted file mode 100644index fd47aa42..00000000--- a/docs/architecture/dashboard-ui.md+++ /dev/null@@ -1,419 +0,0 @@-# Dashboard UI Architecture--The PinchTab dashboard is a modern React SPA that provides visual control and monitoring of Chrome instances.--## Overview--**Technology Stack:**-- React 19 + TypeScript-- Tailwind CSS v4 (dark theme)-- Zustand (state management)-- Vite (build)-- Vitest (testing)-- Hash-based routing--**Build Flow:**-```-dashboard/src (React source)- ↓-bun run build- ↓-dashboard/dist (optimized bundle)- ↓-scripts/build-dashboard.sh (copies to Go binary)- ↓-internal/dashboard/dashboard/ (embedded)- ↓-//go:embed dashboard/* (compiled into binary)-```--## Visual Guide--### Overall Dashboard Layout--```-┌─────────────────────────────────────────────────────────────────┐-│ PinchTab Monitoring Agents Profiles Settings ↻ ☰ │ ← NavBar (sticky)-├─────────────────────────────────────────────────────────────────┤-│ │-│ MAIN CONTENT AREA │-│ │-│ (One of 4 Pages Below) │-│ │-└─────────────────────────────────────────────────────────────────┘-```--**Features:**-- Dark theme (#0a0a0a bg, #1a1a1a surface)-- Orange accent (#f97316) on active/hover states-- Responsive: Mobile hamburger, desktop horizontal tabs-- Sticky header with refresh button (⌘R)--## Layout & Pages--### Navigation Bar-- Sticky header with tabs and refresh button-- Desktop: horizontal navigation (Monitoring, Agents, Profiles, Settings)-- Mobile: hamburger menu + responsive layout-- Keyboard shortcuts: ⌘1-4 (navigate), ⌘R (refresh)--### 1. **Monitoring Page** (`/monitoring`) - Default--Real-time instance and tab monitoring with memory tracking.--**Visual Layout:**-```-┌─ Chart Area ─────────────────────────────┐-│ ↑ Tabs / Memory (dual Y-axis) │-│ │ ▂▄▆█▊▋▊▉▆▅▃▁ │ ← Solid: tabs, Dashed: memory-│ │ ▁ ▃▅▇ ▆█▁ ▂▄▆█▁▂ │-│ ├─────────────────────────────────────→ │-│ │ 60 min history (polled every 30s) │-└───────────────────────────────────────────┘--┌─ Instances ───────────────────────────────┐-│ ┌─ instance-1 ┐ ┌─ instance-2 ┐ │-│ │ :9868 │ │ :9869 │ │ ← Shows port, tab count, memory-│ │ 5 tabs │ │ 12 tabs │ │-│ │ 524MB │ │ 1382MB │ │-│ └─────────────┘ └─────────────┘ │-│ ┌─ Selected Instance Tabs ──────────────┐ │-│ │ └─ tab_abc123 (google.com) │ │ ← Tab list for selected instance-│ │ └─ tab_def456 (github.com) │ │-│ └───────────────────────────────────────┘ │-└───────────────────────────────────────────┘-```--**Components:**-- **Dual-Axis Chart**- - Left Y-axis: Tab count (solid lines)- - Right Y-axis: Memory in MB (dashed lines)- - History: 60-minute window- - Poll interval: 30 seconds (configurable in Settings)--- **Instance List**- - Grid of running instances- - Shows: port, tab count, memory (e.g., `:9868 · 5 tabs · 524MB`)- - Click to select and view tabs--- **Tab Details**- - List of tabs in selected instance- - Shows tab title, URL, and ID--**Data Flow:**-```-MonitoringPage- ↓- └─ Poll /instances/metrics (every 30s)- └─ Poll /instances/{id}/tabs (per selected instance)- └─ addChartDataPoint() → store → chart re-render-```--### 2. **Agents Page** (`/agents`)--Real-time view of agent activity and events.--**Visual Layout:**--Desktop (sm:):-```-┌─ Sidebar ──────┬─ Activity ─────────┐-│ All │ Filter: │-│ ► Agent-1 │ Navigate │-│ Agent-2 │ Snapshot │-│ Agent-3 │ Actions │-│ │ │-│ [events] │ [activity stream] │-└────────────────┴────────────────────┘-```--Mobile:-```-┌─ Carousel ─────────────────┐-│ All → A1 → A2 → A3 ← → │-└────────────────────────────┘-┌─ Activity ─────────────────┐-│ Filter: All / Navigate / │-│ Snapshot / Actions │-│ [activity stream] │-└────────────────────────────┘-```--**Desktop Layout (detailed):**-```-┌─ Sidebar ──────┬─ Activity Log ──────────┐-│ All │ Filter: All/Navigate/ │-│ ► Agent-1 │ Snapshot/Actions │-│ Agent-2 │ │-│ Agent-3 │ [Events stream via SSE] │-│ │ │-│ [events list] │ [activity lines] │-└────────────────┴─────────────────────────┘-```--**Mobile Layout:**-```-┌─ Carousel (horizontal scroll) ─┐-│ All → Agent-1 → Agent-2 → A-3 │-└────────────────────────────────┘-┌─ Activity Log below ───────────┐-│ [events] │-└────────────────────────────────┘-```--**Data Flow:**-```-App.tsx- ↓- └─ subscribeToEvents() → SSE /api/events- └─ init: list of agents- └─ action: agent performed action- └─ system: instance lifecycle- ↓-AgentsPage receives updates- └─ Filter events- └─ Render agents + activity-```--### 3. **Profiles Page** (`/profiles`)--Manage Chrome profiles and launch instances.--**Visual Layout:**-```-┌─ Profiles Grid (2 cols desktop, 1 col mobile) ─┐-│ ┌─────────────┐ ┌─────────────┐ │-│ │ Chrome │ │ Firefox │ │-│ │ id: prof-1 │ │ id: prof-2 │ │-│ │ [Launch ▼] │ │ [Launch ▼] │ │-│ └─────────────┘ └─────────────┘ │-│ ┌─────────────┐ │-│ │ Edge │ [+ Create Profile] │-│ │ id: prof-3 │ │-│ │ [Launch ▼] │ │-│ └─────────────┘ │-└────────────────────────────────────────────────┘--Modals:-[Launch Dialog] [Details Dialog] [Create Dialog]-├ Port: 9868 ├ Name: Chrome ├ Name: [input]-├ ☐ Headless ├ Created: 2026-03-02 ├ Use When: [input]-├ [Launch] [Cancel] └ [Close] ├ [Create] [Cancel]-```--**Modals:**-1. **Create Profile Dialog**- - Name input- - Use When (optional description)- - Create button--2. **Launch Instance Dialog**- - Profile selection (pre-filled)- - Port number (default 9868)- - Headless toggle (default true)- - Launch button--3. **Profile Details Modal**- - Profile metadata- - Copy buttons for ID- - Close button--**Data Flow:**-```-ProfilesPage- ↓- └─ Fetch /profiles (on mount if empty)- └─ SSE updates (new profiles)- ↓-User clicks "Launch"- ↓- └─ POST /profiles/{id}/launch with { port, headless }- └─ Fetch /instances (updated list)-```--### 4. **Settings Page** (`/settings`)--Configure dashboard behavior.--**Visual Layout:**-```-┌─ Settings Page ────────────────────┐-│ ┌─ Monitoring Settings ──────────┐ │-│ │ ☐ Memory Metrics (experimental)│ │-│ │ Poll Interval: 30s [input] │ │-│ │ │ │-│ │ Server Info: │ │-│ │ Go Runtime v1.26 │ │-│ │ Goroutines: 15 │ │-│ │ Heap: 12.5 MB │ │-│ │ │ │-│ │ [Reset] [Apply ✓] │ │ ← Disabled until changes-│ └────────────────────────────────┘ │-└────────────────────────────────────┘-```--**Settings:**-- **Memory Metrics** toggle (experimental)- - When ON: dashboard polls memory data, chart shows memory lines- - When OFF: skips `/instances/metrics` calls--- **Poll Interval** input- - Default: 30 seconds- - Controls chart update frequency--- **Server Info Display**- - Go version- - Goroutines count- - Heap allocation--**Behavior:**-- All settings stored in localStorage-- Apply/Reset buttons (disabled until changes)-- Uses `JSON.stringify` to detect changes--**Data Flow:**-```-SettingsPage- ↓-User toggles Memory Metrics- ↓-hasChanges = true → Apply button enabled- ↓-Click Apply- ↓-setSettings(local) → localStorage + store- ↓-MonitoringPage reacts → adjusts polling behavior-```--## State Management (Zustand Store)--**useAppStore** manages:-- `instances[]` - running Chrome instances-- `profiles[]` - available profiles-- `agents[]` - connected agents-- `events[]` - agent activity log-- `settings` - dashboard preferences-- `tabsChartData[]` - time-series for chart-- `memoryChartData[]` - memory history-- `serverChartData[]` - Go runtime metrics-- `currentTabs{}` - tabs per instance-- `currentMemory{}` - memory per instance--**Persistence:**-- `settings` persisted to localStorage-- `tabsChartData`, `memoryChartData` kept in memory only-- Chart data limited to last 60 points (~30 min)--## API Endpoints--**Dashboard calls:**-- `GET /health` - server status-- `GET /profiles` - list profiles-- `GET /instances` - list running instances-- `GET /instances/metrics` - memory per instance-- `GET /instances/{id}/tabs` - tabs in instance-- `POST /profiles/{id}/launch` - start instance-- `GET /api/events` - SSE event stream (real-time)--**Environment:**-- Development: proxy via Vite (`vite.config.ts`)-- Production: same origin (served from Go at `/dashboard/`)--## Styling & Theme--**Design System:**-- Dark theme: `#0a0a0a` (bg), `#1a1a1a` (surface)-- Orange accent: `#f97316` (primary actions)-- Text: `#e4e4e7` (primary), `#a1a1a1` (secondary)-- Border: `#2a2a2a` (subtle)--**Tailwind Configuration:**-- Atomic design: buttons, inputs, cards are reusable-- Responsive: `sm:` breakpoint at 640px-- Dark mode optimized (no light theme)-- Custom CSS for NavBar animation, chart styling--**Components Hierarchy:**-```-App- ├─ NavBar (sticky header)- └─ Routes- ├─ MonitoringPage- │ ├─ TabsChart (Recharts)- │ ├─ InstanceListItem (molecule)- │ └─ TabItem (molecule)- ├─ AgentsPage- │ ├─ AgentItem (molecule)- │ └─ ActivityLine (molecule)- ├─ ProfilesPage- │ ├─ ProfileCard (molecule)- │ └─ Modal (atom)- └─ SettingsPage- └─ Toolbar (atom)-```--## Testing--**Unit Tests (69 total):**-- Atoms: Badge, Button, StatusDot (7 tests each)-- Molecules: ProfileCard, TabsChart, InstanceListItem, TabItem (3-16 tests)-- Store: useAppStore (19 tests)--**Test Framework:**-- Vitest (via `bun run test`)-- jsdom environment-- Render + user interaction testing--**Gap:**-- No E2E tests for dashboard ↔ Go integration-- Future: Playwright tests for full workflows--## Performance--**Optimization:**-- Vite + code splitting (assets have hash in filename)-- Chart data limited to 60 points (prevents memory bloat)-- useCallback for event handlers-- Memoization for expensive computations-- SSE for push updates (no polling for events)--**Caching:**-- Assets: `Cache-Control: max-age=31536000, immutable` (1 year)-- HTML: `Cache-Control: no-store` (always fresh)-- Settings: localStorage--## Development Workflow--**Build:**-```bash-cd dashboard-bun install-bun run build-```--**Local Dev:**-```bash-cd dashboard-bun run dev # Runs on :5173, proxies /api to :9867-```--**Test:**-```bash-cd dashboard-bun run test:run-```--**CI/CD:**-- Dashboard workflow triggers on push to `dashboard/` or `.github/workflows/dashboard.yml`-- Lint, type check, test, build all run-- Build artifacts uploaded for release--## Future Enhancements--1. **E2E Tests** - Playwright tests for full workflows-2. **Real-time Collaboration** - Multi-user dashboard-3. **Advanced Filtering** - Tag-based instance filtering-4. **Custom Charts** - User-defined metrics-5. **Dark/Light Theme** - Theme toggle-6. **Notification Center** - Persistent alerts for important eventsdiff --git a/docs/references/endpoints.md b/docs/architecture/endpoints.mdsimilarity index 100%rename from docs/references/endpoints.mdrename to docs/architecture/endpoints.mddiff --git a/docs/architecture/find.md b/docs/architecture/find.mdnew file mode 100644index 00000000..a99bb95e--- /dev/null+++ b/docs/architecture/find.md@@ -0,0 +1,121 @@+# Find Architecture++This page covers the implementation details behind PinchTab's semantic `find` pipeline.++## Overview++The `find` system converts accessibility snapshot nodes into lightweight descriptors, scores them against a natural-language query, and returns the best matching `ref`.++The implementation is designed to stay:++- local+- fast+- dependency-light+- recoverable after page re-renders++## Pipeline++```text+accessibility snapshot+ -> element descriptors+ -> lexical matcher+ -> embedding matcher+ -> combined score+ -> best ref+ -> intent cache / recovery hooks+```++## Element Descriptors++Each accessibility node is converted into a descriptor with:++- `ref`+- `role`+- `name`+- `value`++Those fields are also combined into a composite string used for matching.++## Matchers++PinchTab currently uses a combined matcher built from:++- a lexical matcher+- an embedding matcher based on a hashing embedder++Default weighting is:++```text+0.6 lexical + 0.4 embedding+```++Per-request overrides exist through `lexicalWeight` and `embeddingWeight`.++## Lexical Side++The lexical matcher focuses on exact and near-exact token overlap, including role-aware matching behavior.++Useful properties:++- strong for exact words+- easy to reason about+- good precision on explicit queries like `submit button`++## Embedding Side++The embedding matcher uses a feature-hashing approach rather than an external ML model.++Useful properties:++- catches fuzzy similarity+- handles partial and sub-word overlap better+- has no model download or network dependency++## Combined Matching++The combined matcher runs lexical and embedding scoring concurrently, merges results by element ref, and applies the weighted final score.++It also uses a lower internal threshold before the final merge so that candidates which are only strong on one side are not discarded too early.++## Snapshot Dependency++`find` depends on the same accessibility snapshot/ref-cache infrastructure used by snapshot-driven interaction.++If a cached snapshot is missing, the handler tries to refresh it automatically before giving up.++## Intent Cache And Recovery++After a successful match, PinchTab records:++- the original query+- the matched descriptor+- score/confidence metadata++This allows recovery logic to attempt a semantic re-match if a later action fails because the old ref became stale after a page update.++## Orchestrator Routing++The orchestrator exposes `POST /tabs/{id}/find` and proxies it to the correct running instance. The actual matching implementation remains in the shared handler layer.++## Design Constraints++The current design intentionally avoids:++- external embedding services+- heavyweight model dependencies+- selector-first coupling++That keeps the system portable and fast, but it also means the quality ceiling is bounded by the in-process matcher design and the quality of the accessibility snapshot.++## Performance++Benchmarks on Intel i5-4300U @ 1.90GHz:++| Operation | Elements | Latency | Allocations |+| --- | --- | --- | --- |+| Lexical Find | 16 | ~71 us | 134 allocs |+| HashingEmbedder (single) | 1 | ~11 us | 3 allocs |+| HashingEmbedder (batch) | 16 | ~171 us | 49 allocs |+| Embedding Find | 16 | ~180 us | 98 allocs |+| **Combined Find** | **16** | **~233 us** | **263 allocs** |+| Combined Find | 100 | ~1.5 ms | 1685 allocs |diff --git a/docs/architecture/pinchtab-architecture.md b/docs/architecture/overview.mdsimilarity index 98%rename from docs/architecture/pinchtab-architecture.mdrename to docs/architecture/overview.mdindex 2afaa6b0..cc5a1984 100644--- a/docs/architecture/pinchtab-architecture.md+++ b/docs/architecture/overview.md@@ -2,12 +2,11 @@## Overview-Pinchtab is an HTTP server (Go binary, ~12MB) that wraps Chrome DevTools Protocol (CDP)-to give AI agents browser control via a simple REST API.+Pinchtab is an HTTP server that wraps Chrome DevTools Protocol (CDP) to give AI agents browser control via a simple REST API.The product has two process roles:- **Server** — the default `pinchtab` process that manages profiles, instances, routing, and the dashboard-- **Bridge** — the single-instance runtime used for one managed browser+- **Bridge** — the single-instance `pinchtab bridge` runtime used for one managed browser**Managed mode (default):** the Pinchtab server launches and manages bridge-backed Chrome instances.diff --git a/docs/parallel-tab-execution.md b/docs/architecture/parallel-tab-execution.mdsimilarity index 100%rename from docs/parallel-tab-execution.mdrename to docs/architecture/parallel-tab-execution.mddiff --git a/docs/architecture/scheduler.md b/docs/architecture/scheduler.mdnew file mode 100644index 00000000..b647caf6--- /dev/null+++ b/docs/architecture/scheduler.md@@ -0,0 +1,184 @@+# Scheduler Architecture++This page describes how PinchTab's optional scheduler works internally.++## Scope++The scheduler is an opt-in dispatch layer for queued browser tasks. It sits in front of the existing tab action execution path and adds:++- queue admission limits+- per-agent fairness+- bounded concurrency+- cooperative cancellation+- result retention with TTL++It does not replace the direct action endpoints.++## Runtime Placement++In dashboard mode, the scheduler is created only when `scheduler.enabled` is true. It is registered directly on the main mux and exposes:++- `POST /tasks`+- `GET /tasks`+- `GET /tasks/{id}`+- `POST /tasks/{id}/cancel`++## High-Level Flow++```text+client+ -> POST /tasks+ -> scheduler admission+ -> in-memory task queue+ -> worker dispatch+ -> resolve tab -> instance port+ -> POST /tabs/{tabId}/action on the owning instance+ -> result store+```++## Core Components++### Scheduler++The scheduler owns:++- config+- task queue+- result store+- task lookup for live tasks+- cancellation map+- worker lifecycle++### TaskQueue++The queue is:++- in-memory+- global-limit aware+- per-agent-limit aware+- priority ordered within an agent+- fairness aware across agents++Within an agent queue:++- lower `priority` value wins+- equal priority falls back to FIFO by `CreatedAt`++Across agents:++- the agent with the fewest in-flight tasks is chosen first++### ResultStore++The result store keeps snapshots of tasks and evicts terminal tasks after the configured TTL.++### ManagerResolver++The resolver maps a `tabId` to the owning instance port through `instance.Manager.FindInstanceByTabID`.++This is how the scheduler knows where to forward execution.++## Dispatch Lifecycle++A task moves through these internal states:++```text+queued -> assigned -> running -> done+ -> failed+queued -> cancelled+queued -> rejected+```++Implementation details:++- `assigned` is set just before worker execution starts+- `running` is set immediately before the proxied action request+- `done`, `failed`, and `cancelled` are terminal+- rejected tasks are stored as terminal results even though they never enter active execution++## Admission And Limits++Admission checks include:++- global queue size+- per-agent queue size++Execution checks include:++- max global in-flight count+- max per-agent in-flight count++These are enforced in the queue and worker dispatch path rather than by external infrastructure.++## Cancellation Model++Each running task gets its own `context.WithDeadline(...)`.++The scheduler stores the corresponding cancel function so that:++- `POST /tasks/{id}/cancel` can stop a running task+- shutdown can cancel in-flight work+- deadlines propagate naturally to the proxied request++## Deadline Handling++Two deadline paths exist:++- queued task expiry: a background reaper scans queued tasks every second and marks expired ones as failed+- running task deadline: the per-task context deadline is enforced by the HTTP request to the executor++Queued expiry currently records:++```text+deadline exceeded while queued+```++## Execution Contract++The scheduler does not invent a separate execution protocol. It converts each task into the normal action request body:++```json+{+ "kind": "<action>",+ "ref": "<ref>",+ "...params": "..."+}+```++and forwards it to:++```text+POST /tabs/{tabId}/action+```++That keeps the immediate path and scheduled path aligned.++## Error Model++Common failure sources:++- admission rejection because the queue is full+- tab-to-instance resolution failure+- executor HTTP failure+- browser-side action failure+- deadline expiry++Scheduler task snapshots keep the final `error` string for these cases.++## Result Retention++Terminal task snapshots are stored in memory and evicted after the configured TTL. This makes `GET /tasks/{id}` and `GET /tasks` useful for short-lived inspection, not for long-term audit storage.++## Design Tradeoffs++The current scheduler favors:++- simple in-memory operation+- low dependency count+- reuse of the existing action executor++That means it does not currently provide:++- persistent queue storage+- durable recovery after process restart+- a separate task execution DSLdiff --git a/docs/core-concepts.md b/docs/core-concepts.mdindex 9b7bb926..cc1f075e 100644--- a/docs/core-concepts.md+++ b/docs/core-concepts.md@@ -1,435 +1,312 @@# Core Concepts-PinchTab is built around two process roles and three main runtime entities:-- **Server**-- **Bridge**-- **Instance**-- **Profile**-- **Tab**--**See also:**-- [Instance API Reference](references/instance-api.md) — Complete instance endpoints-- [Tabs API Reference](references/tabs-api.md) — Tab management endpoints-- [Profile API Reference](references/profile-api.md) — Profile management endpoints-----+This document describes the concepts that are implemented today in PinchTab.## Server-The **full PinchTab server** is the main control-plane process. It manages instances, profiles, routing, and the web dashboard.+The **server** is the main PinchTab process.-- Listens on port `9867` (configurable, dashboard + API)-- Routes requests to the appropriate instance-- Manages instance lifecycle (launch, monitor, stop)-- Provides unified HTTP API for all operations-- Does not talk to Chrome directly for normal managed instances; it delegates to bridge runtimes+Start it with:```bash-# Start the full serverpinchtab-# Listening on http://localhost:9867--# Or explicitly+# or explicitlypinchtab server--# Or specify port-PINCHTAB_PORT=9870 pinchtab server-# Listening on http://localhost:9870```+What the server does:++- exposes the main HTTP API and dashboard on port `9867` by default+- manages profiles and instances+- proxies tab-scoped requests to the correct managed instance+- can expose shorthand routes such as `/navigate`, `/snapshot`, and `/action`++Important clarification:++- the server is the public entry point+- for managed instances, the server usually does **not** talk to Chrome directly+- instead, it spawns or routes to a per-instance **bridge** process+## BridgeThe **bridge** is the single-instance runtime.-- Wraps one browser instance-- Exposes the tab/browser HTTP API-- Used for managed child instances spawned by the server-- Can also be started explicitly with `pinchtab bridge`+Start it directly only when you want one standalone browser runtime:```bash-# Explicit bridge modepinchtab bridge```-Most users do not start `bridge` directly. They run the server, and the server launches bridge children as needed.+What the bridge does:----+- owns exactly one Chrome browser process+- exposes browser and tab endpoints such as `/navigate`, `/snapshot`, `/action`, and `/tabs/{id}/...`+- is the process the server launches for each managed instance-## Instance+In normal multi-instance usage, you usually interact with the server, not with bridge processes directly.-A **running Chrome process** with an optional profile, auto-allocated to a unique port (9868-9968 by default).+## Profiles-- One Chrome browser per instance-- Optional profile (see [Profile](#profile) below)-- Can host multiple tabs-- Completely isolated from other instances-- Identified by instance ID: `inst_XXXXXXXX` (hash-based, stable)-- Auto-allocated to unique port in 9868-9968 range-- Lazy Chrome initialization (starts on first request, not at creation)+A **profile** is a Chrome user data directory.-**Key constraint:** One instance = one Chrome process = zero or one profile.+It stores persistent browser state such as:-### Creating Instances+- cookies+- local storage+- cache+- browsing history+- extensions+- saved account state-Instances are managed by the server via the API. Managed instances run as isolated bridge child processes.--```bash-# CLI: Create instance (headless by default)-pinchtab instance launch+Profile facts that match the current implementation:-# CLI: Create headed (visible) instance-pinchtab instance launch --mode headed+- profiles are persistent on disk+- profiles can exist without any running instance+- at most one active managed instance can use a given profile at a time+- profile IDs use the format `prof_XXXXXXXX`+- `GET /profiles` hides temporary auto-generated profiles unless you pass `?all=true`-# CLI: Create with specific port-pinchtab instance launch --mode headed --port 9999+Create a profile with the API:-# Curl: Create instance via API-curl -X POST http://localhost:9867/instances/launch \+```bash+curl -X POST http://localhost:9867/profiles \-H "Content-Type: application/json" \- -d '{"mode": "headed", "port": "9999"}'-+ -d '{+ "name": "work",+ "description": "Main logged-in work profile"+ }'# Response{- "id": "inst_0a89a5bb",- "profileId": "prof_278be873",- "profileName": "Instance-...",- "port": "9868",- "headless": false,- "status": "starting"+ "status": "created",+ "id": "prof_278be873",+ "name": "work"}```-### Multiple Instances--You can run multiple instances simultaneously for isolation and scalability. The orchestrator manages them automatically:--```bash-# Terminal 1: Start server-pinchtab--# Terminal 2: Create multiple instances-for i in 1 2 3; do- pinchtab instance launch --mode headless-done+## Instances-# List all instances-curl http://localhost:9867/instances | jq .+An **instance** is a managed browser runtime.-# Response: 3 independent instances on ports 9868, 9869, 9870-[- {"id": "inst_0a89a5bb", "port": "9868", "status": "running"},- {"id": "inst_1b9a5dcc", "port": "9869", "status": "running"},- {"id": "inst_2c8a5eef", "port": "9870", "status": "running"}-]-```+In practice, one instance means:-Each instance is completely independent — no shared state, no cookie leakage, no resource contention.+- one bridge process+- one Chrome process+- zero or one profile+- one dedicated port+- many tabs----+Instance facts that match the current implementation:-## Profile+- instance IDs use the format `inst_XXXXXXXX`+- ports are auto-allocated from `9868-9968` by default+- instance status is tracked as `starting`, `running`, `stopping`, `stopped`, or `error`+- one profile cannot be attached to multiple active managed instances at the same time-A **browser profile** (Chrome user data directory) containing browser state. Optional per instance.+### Persistent vs temporary instances-- Holds browser state: cookies, local storage, cache, browsing history, extensions-- Only one profile per instance-- Multiple tabs can share the same profile (and its state)-- Identified by profile ID: `prof_XXXXXXXX` (hash-based, stable)-- Useful for: user accounts, login sessions, multi-tenant workflows-- Persistent across instance restarts+There are two common ways to start an instance:-**Key constraint:** Instance without a profile = ephemeral, no persistent state across restarts.+1. with a named profile+2. without a profile ID-### Managing Profiles+If you start an instance with a profile ID, the instance uses that persistent profile.-```bash-# CLI: List all profiles-pinchtab profiles+If you start an instance without a profile ID, PinchTab creates an auto-generated profile named like `instance-...`.+That temporary profile is deleted when the instance stops.-# CLI: Create profile-pinchtab profile create my-profile+So this is the correct mental model:-# Curl: List profiles (excludes temporary auto-generated profiles)-curl http://localhost:9867/profiles | jq .+- instances without an explicit profile are **ephemeral**+- the implementation still creates a temporary profile directory behind the scenes+- that temporary profile is cleanup state, not a reusable long-term profile-# Response-[- {- "id": "278be873",- "name": "my-profile",- "created": "2026-03-01T05:21:38.274Z",- "diskUsage": 5242880,- "source": "created"- }-]-```+### Starting an instance-### Using Profiles with Instances+Preferred endpoint:```bash-# Create instance with specific profilecurl -X POST http://localhost:9867/instances/start \-H "Content-Type: application/json" \- -d '{"profileId": "278be873"}'--# Or via CLI-pinchtab instance launch # Uses temp auto-generated profile+ -d '{+ "profileId": "prof_278be873",+ "mode": "headed"+ }'+# CLI Alternative+pinchtab instance start --profileId prof_278be873 --mode headed+# Response+{+ "id": "inst_0a89a5bb",+ "profileId": "prof_278be873",+ "profileName": "work",+ "port": "9868",+ "headless": false,+ "status": "starting"+}```-### Profile Use Cases+## Tabs-**Separate User Accounts:**-```text-Instance 1 (profile: alice)- ├── Tab 1: [email protected] logged in- └── Tab 2: [email protected] dashboard+A **tab** is a single page inside an instance.-Instance 2 (profile: bob)- ├── Tab 1: [email protected] logged in- └── Tab 2: [email protected] dashboard-```+Tabs belong to an instance, and therefore inherit that instance's profile state.-```bash-# Create profiles for each user-pinchtab profile create alice-pinchtab profile create bob+What a tab gives you:-# Start instances with profiles-curl -X POST http://localhost:9867/instances/start \- -d '{"profileId": "alice-profile-id"}'+- its own URL and page state+- a snapshot of the accessibility tree+- action execution such as click, type, fill, hover, and press+- text extraction, screenshots, PDF export, cookie access, and evaluation-curl -X POST http://localhost:9867/instances/start \- -d '{"profileId": "bob-profile-id"}'+Open a tab in a specific instance:-# Each instance has isolated cookies/auth-```--**Login Once, Use Anywhere:**```bash-# Start instance with persistent profile-curl -X POST http://localhost:9867/instances/start \- -d '{"profileId": "work"}'+INST=inst_0a89a5bb-# Open a login tab and log in-TAB_ID=$(curl -s -X POST http://localhost:9867/instances/inst_xyz/tabs/open \- -H "Content-Type: application/json" \- -d '{"url": "https://pinchtab.com/login"}' | jq -r '.tabId')--curl -X POST http://localhost:9867/tabs/$TAB_ID/action \+curl -X POST http://localhost:9867/instances/$INST/tabs/open \-H "Content-Type: application/json" \- -d '{"kind":"fill","ref":"e3","text":"[email protected]"}'-# ... continue login flow ...--# Later (even after instance restart): Profile is persistent-pinchtab instance launch # Or restart orchestrator-# Cookies intact, still logged in via profile's saved state+ -d '{"url":"https://pinchtab.com"}'+# Response+{+ "tabId": "CDP_TARGET_ID"+}```----+Then use tab-scoped endpoints:-## Tab--A **browser tab** (webpage) within an instance and its profile.+```bash+TAB=CDP_TARGET_ID-- Single webpage with its own DOM, URL, accessibility tree-- Identified by tab ID: `tab_XXXXXXXX` (hash-based, stable)-- Tabs are ephemeral (don't survive instance restart unless using a profile)-- Multiple tabs can be open simultaneously in one instance-- Each tab has stable element references (e0, e1...) for DOM interaction-- Can navigate, take snapshots, execute actions, evaluate JavaScript+curl http://localhost:9867/tabs/$TAB/snapshot-```bash-# Create tab in instance (returns tabId)-curl -X POST http://localhost:9867/instances/inst_0a89a5bb/tabs/open \+curl -X POST http://localhost:9867/tabs/$TAB/action \-H "Content-Type: application/json" \- -d '{"url": "https://pinchtab"}' | jq '.tabId'-# Returns: "tab_abc123"+ -d '{"kind":"click","ref":"e5"}'-# Or via CLI-pinchtab tab open inst_0a89a5bb https://pinchtab.com+curl -X POST http://localhost:9867/tabs/$TAB/close+```-# Get tab info-curl http://localhost:9867/tabs/tab_abc123 | jq .+### Are tabs persistent?-# Navigate tab-curl -X POST http://localhost:9867/tabs/tab_abc123/navigate \- -H "Content-Type: application/json" \- -d '{"url": "https://google.com"}'+Usually, no.-# Take snapshot (DOM structure)-curl http://localhost:9867/tabs/tab_abc123/snapshot | jq .+For managed instances started by the server:-# Interact with tab (click, type, etc.)-curl -X POST http://localhost:9867/tabs/tab_abc123/action \- -H "Content-Type: application/json" \- -d '{"kind": "click", "ref": "e5"}'+- tabs are runtime objects+- tabs disappear when the instance stops+- profiles persist, but open tabs do not-# Close tab-curl -X POST http://localhost:9867/tabs/tab_abc123/close+That means the persistent part is the **profile state**, not the tab list.-# Or via CLI-pinchtab tab close tab_abc123-```+## Element references-**See:** [Tabs API Reference](references/tabs-api.md) for complete operations.-------## Hierarchy--```text-PinchTab Server (HTTP server on port 9867)- │- ├── Instance 1 (inst_0a89a5bb, port 9868, temp profile)- │ ├── Tab 1 (tab_xyz123, https://pinchtab.com)- │ ├── Tab 2 (tab_xyz124, https://google.com)- │ └── Tab 3 (tab_xyz125, https://github.com)- │- ├── Instance 2 (inst_1b9a5dcc, port 9869, profile: work)- │ ├── Tab 1 (tab_abc001, internal dashboard, logged in as alice)- │ └── Tab 2 (tab_abc002, internal docs)- │- └── Instance 3 (inst_2c8a5eef, port 9870, profile: personal)- ├── Tab 1 (tab_def001, gmail, logged in as [email protected])- └── Tab 2 (tab_def002, bank.com)-```+Snapshots return element references such as `e0`, `e1`, `e2`, and so on.----+These refs are useful because they let you interact with elements without writing CSS selectors for common flows.-## Relationships & Constraints+## Relationships-| Relationship | Rule |+The implementation is easiest to understand with these rules:++| Relationship | What is true today ||---|---|-| **Tabs → Instance** | Every tab must exist in exactly one instance |-| **Tabs → Profile** | Every tab inherits the instance's profile (zero or one) |-| **Profile → Instance** | Every profile belongs to exactly one instance |-| **Instance → Profile** | An instance has zero or one profile |-| **Instance → Chrome** | One instance = one Chrome process |+| Server -> Instances | One server can manage many instances |+| Bridge -> Chrome | One bridge owns one Chrome process |+| Instance -> Profile | An instance has zero or one profile |+| Profile -> Instance | A profile can have zero or one active managed instance at a time |+| Instance -> Tabs | An instance can have many tabs |+| Tab -> Instance | Every tab belongs to exactly one instance |+| Tab -> Profile | A tab inherits the instance profile, if one exists |----+Profiles are reusable persistent state. Instances are temporary runtimes that may use a profile.-## Common Workflows+## Shorthand routes vs explicit routes-### Workflow 1: Single Instance, Multiple Tabs+PinchTab exposes two styles of interaction:-```bash-# Terminal 1: Start orchestrator-pinchtab+### Explicit routes-# Terminal 2: Create instance-INST=$(pinchtab instance launch --mode headless)-# Returns: inst_0a89a5bb+These always name the resource you want:-# Create multiple tabs in the same instance-curl -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://pinchtab.com"}'+- `POST /instances/start`+- `POST /instances/{id}/tabs/open`+- `GET /tabs/{id}/snapshot`+- `POST /tabs/{id}/action`-curl -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://google.com"}'+This is the clearest model for multi-instance work.-# List all tabs across all instances-curl http://localhost:9867/tabs | jq .+### Shorthand routes-# Or tabs in specific instance-curl http://localhost:9867/instances/$INST/tabs | jq .-```+These omit the instance and sometimes the tab:-### Workflow 2: Multiple Instances, Separate Profiles+- `POST /navigate`+- `GET /snapshot`+- `POST /action`+- `GET /text`-```bash-# Create persistent profiles for Alice and Bob-pinchtab profile create alice-pinchtab profile create bob+These route to the "current" or first running instance.-# Get profile IDs-ALICE_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="alice") | .id')-BOB_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="bob") | .id')+## Recommended mental model-# Start instance for Alice-INST_ALICE=$(curl -X POST http://localhost:9867/instances/start \- -d '{"profileId":"'$ALICE_ID'"}' | jq -r '.id')+For most users, this is the right sequence:-# Start instance for Bob-INST_BOB=$(curl -X POST http://localhost:9867/instances/start \- -d '{"profileId":"'$BOB_ID'"}' | jq -r '.id')+1. start the server with `pinchtab`+2. create a profile if you need persistence+3. start an instance from that profile+4. open one or more tabs in that instance+5. snapshot a tab+6. act on refs from that snapshot-# Create tabs in both instances with isolated cookies-curl -X POST http://localhost:9867/instances/$INST_ALICE/tabs/open \- -d '{"url":"https://app.pinchtab.com"}'+If you do not need persistence:-curl -X POST http://localhost:9867/instances/$INST_BOB/tabs/open \- -d '{"url":"https://app.pinchtab.com"}'+1. start an instance without `profileId`+2. use it normally+3. stop it when done+4. let PinchTab delete the temporary profile automatically-# Login in each instance separately — profiles keep sessions isolated-```+## Example workflows-### Workflow 3: Ephemeral Instance (No Profile)+### Workflow 1: persistent logged-in browser```bash-# Create instance without persistent profile (temporary auto-generated)-INST=$(pinchtab instance launch)+PROFILE_ID=$(curl -s -X POST http://localhost:9867/profiles \+ -H "Content-Type: application/json" \+ -d '{"name":"work"}' | jq -r '.id')-# Create tab, use it-curl -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://pinchtab.com"}'-# ... work ...+INST=$(curl -s -X POST http://localhost:9867/instances/start \+ -H "Content-Type: application/json" \+ -d "{\"profileId\":\"$PROFILE_ID\",\"mode\":\"headed\"}" | jq -r '.id')-# Stop instance-pinchtab instance stop $INST+TAB=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \+ -H "Content-Type: application/json" \+ -d '{"url":"https://pinchtab.com/login"}' | jq -r '.tabId')-# Tab is gone, all cookies gone — clean slate next time+curl http://localhost:9867/tabs/$TAB/snapshot```-### Workflow 4: Polling for Instance Ready Status+Use this when you want cookies and account state to survive instance restarts.++### Workflow 2: disposable run```bash-# Create instance (returns with status "starting")-INST=$(pinchtab instance launch | jq -r '.id')--# Poll until running (monitor's health check initializes Chrome)-while true; do- STATUS=$(curl http://localhost:9867/instances/$INST | jq -r '.status')- if [ "$STATUS" == "running" ]; then- echo "Instance ready!"- break- fi- echo "Instance status: $STATUS, waiting..."- sleep 0.5-done--# Now safe to create a tab and work through tab endpoints-TAB_ID=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \+INST=$(curl -s -X POST http://localhost:9867/instances/start \-H "Content-Type: application/json" \- -d '{"url":"https://pinchtab.com"}' | jq -r '.tabId')--curl http://localhost:9867/tabs/$TAB_ID/snapshot-```+ -d '{"mode":"headless"}' | jq -r '.id')----+TAB=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \+ -H "Content-Type: application/json" \+ -d '{"url":"https://example.com"}' | jq -r '.tabId')-## Mental Model+curl http://localhost:9867/tabs/$TAB/text-```-What you control │ What it is │ Identified by-─────────────────────────┼──────────────────────────┼─────────────────────-PinchTab Server │ HTTP control plane │ port (9867 default)-Instance │ Chrome process │ inst_XXXXXXXX (hash ID)-Profile (optional) │ Browser state directory │ prof_XXXXXXXX (hash ID)-Tab │ Single webpage │ tab_XXXXXXXX (hash ID)+curl -X POST http://localhost:9867/instances/$INST/stop```-## Summary+Use this when you want a clean, throwaway session.-- **PinchTab Server** is the HTTP control plane that manages everything-- **Instance** is a running Chrome process with optional profile and multiple tabs-- **Profile** is optional persistent browser state (cookies, auth, history)-- **Tab** is the actual webpage you navigate and interact with+## Summary-**Key insights:**-- Instances are launched via API and auto-allocated unique ports (9868-9968)-- Instances are lazy: Chrome initializes on first request, not at creation time-- Profiles are optional but provide persistent state across instance restarts-- Tabs are ephemeral unless using a persistent profile-- Instance + Profile + Tabs = the complete mental model for using PinchTab effectively+The durable object in PinchTab is the **profile**.+The runtime object is the **instance**.+The page object is the **tab**.+The **server** manages them, and the **bridge** executes them.-**Next:** See [Instance API Reference](references/instance-api.md), [Tabs API Reference](references/tabs-api.md), and [Profile API Reference](references/profile-api.md) for complete endpoint documentation.diff --git a/docs/dashboard.md b/docs/dashboard.mdindex f0ab6af9..bac958cf 100644--- a/docs/dashboard.md+++ b/docs/dashboard.md@@ -1,262 +1,220 @@# Dashboard-PinchTab includes a built-in web dashboard for monitoring and managing instances, profiles, and agent activity.+PinchTab includes a built-in web dashboard for monitoring instances, managing profiles, and editing configuration.++The dashboard is part of the full server:-The dashboard is part of the **full server**:- `pinchtab` or `pinchtab server` starts the full server and serves the dashboard-- `pinchtab bridge` does not serve the dashboard; it only exposes the single-instance bridge API+- `pinchtab bridge` does not serve the dashboard-Access the dashboard at **`http://localhost:9867`** (adjust port if needed).+You can open the dashboard at:-Alternatively, use **`http://localhost:9867/dashboard`** (also works for backward compatibility).+- `http://localhost:9867`+- `http://localhost:9867/dashboard`----## Dashboard Overview+## Dashboard overview++The current dashboard exposes three main pages:-The dashboard provides four main screens:+1. **Monitoring**+2. **Profiles**+3. **Settings**-1. **Instances** — View and manage running Chrome instances-2. **Profiles** — Browse and launch saved browser profiles-3. **Profile Details** — Configure and launch a specific profile-4. **Agents Feed** — Monitor agent activity and automation workflows+The UI is a React SPA served by the Go server.----## Instances Screen+## Monitoring page-> **Screenshot placeholder:** Instances view+The Monitoring page is the default view.-### What It Shows+It shows:-- List of all running PinchTab instances-- Port number for each instance-- Instance status (running, stopped, idle)-- Number of tabs in each instance-- Profile name (if any) for each instance+- running and stopped instances+- selected-instance details+- open tabs for the selected instance+- charted monitoring data+- optional memory metrics when enabled in settings-### What You Can Do+What you can do:-- **View details** — Click an instance to see full information-- **Create new instance** — Start a new Chrome process-- **Stop instance** — Shut down a running instance-- **View tabs** — See all tabs open in the instance+- select an instance+- inspect its port, mode, and status+- view its open tabs+- stop a running instance-### Use Cases+Operational data comes from:-- Monitor multiple instances running in parallel-- Check resource usage per instance-- Stop instances when no longer needed-- Debug instance configuration+- SSE updates on `GET /api/events`+- instance lists from `GET /instances`+- tab data from `GET /instances/{id}/tabs`+- optional memory data from `GET /instances/metrics`----## Profiles Screen--> **Screenshot placeholder:** Profiles view+## Profiles page-### What It Shows+The Profiles page manages saved browser profiles.-- Grid of all available browser profiles-- Each profile card displays:- - Profile name- - Associated email/account (if available)- - Last used timestamp- - Current status (running, stopped)- - Quick info (cookies count, stored data size)+It shows:-### What You Can Do+- available profiles+- launch and stop actions+- profile metadata such as name, path, size, source, and account details-- **Launch profile** — Start a new instance with this profile-- **View details** — Click profile card to see configuration details-- **Edit profile** — Modify profile settings (name, metadata)-- **Delete profile** — Remove a profile (with confirmation)-- **Search/filter** — Find profiles by name or account+What you can do:-### Use Cases+- create a new profile+- launch a profile as a managed instance+- stop the running instance for a profile+- edit profile metadata+- delete a profile+- open a profile details modal-- Quickly launch a profile for a specific user account-- Switch between different login contexts-- See which profiles are currently active-- Manage multiple user sessions+The launch flow uses the server APIs behind the scenes:----+```bash+curl -X POST http://localhost:9867/profiles \+ -H "Content-Type: application/json" \+ -d '{"name":"work","useWhen":"Team account workflows"}'+# Response+{+ "status": "created",+ "id": "prof_278be873",+ "name": "work"+}+```-## Profile Details Screen+```bash+curl -X POST http://localhost:9867/instances/start \+ -H "Content-Type: application/json" \+ -d '{"profileId":"prof_278be873","mode":"headed"}'+# CLI Alternative+pinchtab instance start --profileId prof_278be873 --mode headed+# Response+{+ "id": "inst_ea2e747f",+ "profileId": "prof_278be873",+ "profileName": "work",+ "port": "9868",+ "headless": false,+ "status": "starting"+}+```-> **Screenshot placeholder:** Profile details view+----### What It Shows+## Profile details modal-- **Profile name** — Editable identifier-- **Account info** — Associated email, username, or account ID-- **Launch settings**:- - Headless or headed mode- - Port assignment- - Stealth level (light, medium, full)- - Environment variables-- **State info**:- - Created date- - Last modified- - Data size (cookies, storage, cache)- - Number of saved tabs-- **Instances using this profile** — Currently running instances+Profile details are shown in a modal, not as a separate top-level page.-### What You Can Do+The modal currently includes tabs for:-- **Launch** — Start a new instance with this profile-- **Edit** — Modify profile configuration-- **View data** — See stored cookies, local storage, browsing history-- **Clear data** — Reset cookies/cache while keeping profile-- **Export** — Backup profile configuration-- **Delete** — Remove profile entirely+- **Profile**+- **Live**+- **Logs**-### Use Cases+From there you can:-- Configure launch options before starting an instance-- Check what data is stored in a profile-- Clone a profile for a similar use case-- Debug profile-related issues+- view the profile ID and metadata+- edit name and `useWhen`+- inspect live tabs for a running instance+- open a screencast tile for tab previews----## Agents Feed Screen+## Settings page-> **Screenshot placeholder:** Agents feed view+The Settings page combines local dashboard preferences with backend configuration.-### What It Shows+It includes sections for:-- Real-time activity log from all connected agents-- Each entry displays:- - Timestamp- - Agent name/ID- - Action performed (navigated, clicked, extracted text, etc.)- - Associated instance/profile- - Result (success, error, pending)+- Dashboard+- Instance Defaults+- Orchestration+- Security+- Profiles+- Network & Attach+- Browser Runtime+- Timeouts-### What You Can Do+What you can do:-- **Monitor agents** — Watch what automation is happening in real-time-- **Filter by agent** — Show only activity from a specific agent-- **Filter by instance** — Show only activity in a specific instance-- **Search** — Find activities by action, URL, or data-- **View details** — Click an entry to see full request/response-- **Pause/resume** — Control logging verbosity+- change local dashboard preferences such as monitoring and screencast settings+- load backend config from `GET /api/config`+- save backend config through `PUT /api/config`+- see whether a restart is required for server-level changes-### Use Cases+The health payload also surfaces summary info:-- Debug agent automation workflows-- Audit what agents have done-- Monitor for errors or unexpected behavior-- Understand which agents are most active-- Troubleshoot automation issues-------## Navigation--The dashboard header provides tabs to switch between screens:--```text-[Instances] | [Profiles] | [Profile Details] | [Agents]+```bash+curl http://localhost:9867/health | jq .+# Response+{+ "status": "ok",+ "mode": "dashboard",+ "profiles": 3,+ "instances": 1,+ "agents": 0,+ "restartRequired": false+}```-You can also navigate by clicking:-- An instance → shows its details-- A profile → shows its profile details screen-- An agent event → shows relevant instance/profile-----## Status Indicators--### Instance Status-- **Running** (green) — Active Chrome process-- **Idle** (yellow) — Running but no tabs-- **Stopped** (red) — Process not running+## Event stream-### Profile Status-- **Active** (green) — At least one instance using it-- **Dormant** (gray) — No active instances-- **Launching** (blue) — Instance starting+The dashboard uses Server-Sent Events, not WebSockets.-### Agent Status-- **Success** (green) — Action completed-- **Error** (red) — Action failed-- **Pending** (yellow) — In progress-- **Cancelled** (gray) — Aborted+Primary stream endpoint:----+```bash+curl http://localhost:9867/api/events+```-## Keyboard Shortcuts+This stream carries:-| Shortcut | Action |-|---|---|-| `R` | Refresh current screen |-| `Esc` | Go back / Close modal |-| `Ctrl+K` | Search |-| `Ctrl+1` | Instances tab |-| `Ctrl+2` | Profiles tab |-| `Ctrl+3` | Profile Details tab |-| `Ctrl+4` | Agents Feed tab |+- `init`+- `action`+- `system`+- `monitoring`----## Dark Mode--The dashboard automatically uses your system's dark/light preference.+## Build note-Toggle manually:-- Click the theme toggle in the top-right corner (sun/moon icon)-- Preference is saved in browser local storage+If the React dashboard assets are not built into the binary, the server serves a fallback page telling you to build the dashboard bundle.----## Performance & Limits--- **Refresh rate**: Real-time updates (WebSocket-based)-- **History retention**: Last 1000 agent events (older events archived)-- **Scalability**: Optimized for 10+ instances, 100+ profiles+## Troubleshooting-For high-throughput monitoring, consider using the REST API directly:+### Dashboard not loading```bash-# Get all instances-curl http://localhost:9867/instances--# Get all profiles-curl http://localhost:9867/profiles--# Stream agent events-curl http://localhost:9867/events/stream+curl http://localhost:9867/health```------## Troubleshooting--### Dashboard Not Loading+If the server is up, try:-- Check if PinchTab is running: `curl http://localhost:9867/health`-- Check the port: Default is `9867`, adjust if you started with `--port`-- Clear browser cache: `Ctrl+Shift+Delete` (most browsers)+- `http://localhost:9867`+- `http://localhost:9867/dashboard`-### No Instances Showing+### No instances visible-- Make sure at least one instance is running: `pinchtab --port 9867`-- Refresh the page (`R` key)-- Check browser console for errors (`F12`)+Start one:-### Agent Events Not Updating--- Confirm agents are actually running tasks-- Check WebSocket connection: Open DevTools → Network → WS tab-- Try refreshing the page+```bash+curl -X POST http://localhost:9867/instances/start \+ -H "Content-Type: application/json" \+ -d '{"mode":"headless"}'+# CLI Alternative+pinchtab instance start+```----+### No live profile preview-## Next Steps+The profile must have a running instance before the Live tab in the profile details modal can show live tab data.-- [Core Concepts](core-concepts.md) — Understand instances, profiles, tabs-- [Get Started](get-started.md) — Set up your first profile-- [Headless vs Headed](headless-vs-headed.md) — Choose the right modediff --git a/docs/examples/pinchtab-bridge.md b/docs/examples/pinchtab-bridge.mddeleted file mode 100644index c8b3e1cf..00000000--- a/docs/examples/pinchtab-bridge.md+++ /dev/null@@ -1,384 +0,0 @@-# Example: Bridge Smoke Test--This example is a happy-path smoke test for a running `pinchtab bridge` instance on `127.0.0.1:9867`.--It is useful when you want to verify that the single-instance runtime can:-- respond to health checks-- open and list tabs-- navigate and inspect pages-- perform actions-- capture screenshots and PDFs-- read cookies-- use tab locking--For the bridge-mode mental model, see [Expert Guide: Bridge Mode](../guides/expert-bridge-mode.md).--## Prerequisites--Start the bridge:--```bash-pinchtab bridge-```--Set the base URL:--```bash-BASE=http://127.0.0.1:9867-```--The commands below assume `jq` is installed.--## 1. Check Health--```bash-curl -s "$BASE/health" | jq .-```--```bash-# CLI alternative-pinchtab health-```--```jsonc-// Response-{- "status": "ok",- "tabs": 1-}-```--## 2. Navigate To A Page--```bash-curl -s -X POST "$BASE/navigate" \- -H "Content-Type: application/json" \- -d '{"url":"https://github.com/pinchtab/pinchtab"}' | jq .-```--```bash-# CLI alternative-pinchtab nav https://github.com/pinchtab/pinchtab-```--```jsonc-// Response-{- "tabId": "BD78E40ED7400A4B0E73B99415E1B9EA",- "title": "GitHub - pinchtab/pinchtab",- "url": "https://github.com/pinchtab/pinchtab"-}-```--## 3. List Tabs--```bash-curl -s "$BASE/tabs" | jq .-```--```bash-# CLI alternative-pinchtab tabs-```--```jsonc-// Response-{- "tabs": [- {- "id": "BD78E40ED7400A4B0E73B99415E1B9EA",- "title": "GitHub - pinchtab/pinchtab",- "type": "page",- "url": "https://github.com/pinchtab/pinchtab"- }- ]-}-```--## 4. Capture An Interactive Snapshot--```bash-curl -s "$BASE/snapshot?filter=interactive" | jq .-```--```bash-# CLI alternative (compact format)-pinchtab snap -i -c-```--```jsonc-// Response (JSON)-{- "nodes": [- { "ref": "e0", "role": "link", "name": "Skip to content" },- { "ref": "e1", "role": "link", "name": "GitHub Homepage" },- { "ref": "e14", "role": "button", "name": "Search or jump to…" }- ]-}-```--```bash-# CLI compact output-# GitHub - pinchtab/pinchtab | https://github.com/pinchtab/pinchtab | 219 nodes-e0:link "Skip to content"-e1:link "GitHub Homepage"-e14:button "Search or jump to…"-...-```--## 5. Extract Page Text--```bash-curl -s "$BASE/text" | jq .-```--```bash-# CLI alternative-pinchtab text-```--```jsonc-// Response-{- "text": "High-performance browser automation bridge and multi-instance orchestrator...",- "title": "GitHub - pinchtab/pinchtab",- "url": "https://github.com/pinchtab/pinchtab"-}-```--## 6. Click An Element--First get the snapshot to cache refs:--```bash-curl -s "$BASE/snapshot?filter=interactive" > /dev/null-```--Then click:--```bash-curl -s -X POST "$BASE/action" \- -H "Content-Type: application/json" \- -d '{"kind":"click","ref":"e14"}' | jq .-```--```bash-# CLI alternative (run snap first to cache refs)-pinchtab snap -i > /dev/null-pinchtab click e14-```--```jsonc-// Response-{- "success": true,- "result": {- "clicked": true- }-}-```--## 7. Type Into A Search Box--After clicking the search button (e14), a search input appears:--```bash-curl -s "$BASE/snapshot?filter=interactive" | jq '.. | objects | select(.role == "combobox")' | head -10-```--```bash-# CLI alternative-pinchtab snap -i -c | grep combobox-# Output: e221:combobox "Search" val="repo:pinchtab/pinchtab"-```--Type into it:--```bash-curl -s -X POST "$BASE/action" \- -H "Content-Type: application/json" \- -d '{"kind":"type","ref":"e221","text":"browser automation"}' | jq .-```--```bash-# CLI alternative-pinchtab type e221 "browser automation"-```--```jsonc-// Response-{- "success": true,- "result": {- "typed": "browser automation"- }-}-```--## 8. Press A Key--```bash-curl -s -X POST "$BASE/action" \- -H "Content-Type: application/json" \- -d '{"kind":"press","key":"Escape"}' | jq .-```--```bash-# CLI alternative-pinchtab press Escape-```--```jsonc-// Response-{- "success": true,- "result": {- "pressed": "Escape"- }-}-```--## 9. Take A Screenshot--```bash-curl -s "$BASE/screenshot" > smoke.jpg-ls -lh smoke.jpg-```--```bash-# CLI alternative-pinchtab ss -o smoke.jpg-```--```bash-# Output-Saved smoke.jpg (55876 bytes)--rw------- 1 user staff 55K Mar 7 18:20 smoke.jpg-```--## 10. Export A PDF--```bash-curl -s "$BASE/pdf" > smoke.pdf-ls -lh smoke.pdf-```--```bash-# CLI alternative-pinchtab pdf -o smoke.pdf-```--```jsonc-// Output-Saved smoke.pdf (1494657 bytes)--rw------- 1 user staff 1.4M Mar 7 18:51 smoke.pdf-```--## 11. Read Cookies--```bash-TAB=$(curl -s "$BASE/tabs" | jq -r '.tabs[0].id')-curl -s "$BASE/tabs/$TAB/cookies" | jq '.cookies[:2]'-```--```jsonc-// Response-[- {- "domain": ".github.com",- "name": "_gh_sess",- "path": "/",- "secure": true,- "httpOnly": true- }-]-```--> **Note:** No direct CLI alternative for cookies. Use curl or the API.--## 12. Lock And Unlock The Tab--```bash-TAB=$(curl -s "$BASE/tabs" | jq -r '.tabs[0].id')--curl -s -X POST "$BASE/tabs/$TAB/lock" \- -H "Content-Type: application/json" \- -d '{"owner":"smoke-test","ttl":60}' | jq .-```--```jsonc-// Response-{- "locked": true,- "owner": "smoke-test",- "expiresAt": "2026-03-07T18:30:43+01:00"-}-```--```bash-curl -s -X POST "$BASE/tabs/$TAB/unlock" \- -H "Content-Type: application/json" \- -d '{"owner":"smoke-test"}' | jq .-```--```jsonc-// Response-{- "unlocked": true-}-```--> **Note:** No direct CLI alternative for lock/unlock. Use curl or the API.--## 13. Open A Second Tab--```bash-curl -s -X POST "$BASE/tab" \- -H "Content-Type: application/json" \- -d '{"action":"new","url":"https://pinchtab.com"}' | jq .-```--```bash-# CLI alternative-pinchtab nav https://pinchtab.com-```--```jsonc-// Response-{- "tabId": "F266512A8B4FF5E537ADECDCD898BA02",- "title": "PinchTab — Browser Control for AI Agents",- "url": "https://pinchtab.com/"-}-```--## CLI Quick Reference--| Action | CLI Command |-|--------|-------------|-| Health check | `pinchtab health` |-| Navigate | `pinchtab nav <url>` |-| List tabs | `pinchtab tabs` |-| Snapshot | `pinchtab snap -i -c` |-| Extract text | `pinchtab text` |-| Click | `pinchtab click <ref>` |-| Type | `pinchtab type <ref> <text>` |-| Press key | `pinchtab press Enter` |-| Screenshot | `pinchtab ss -o file.jpg` |-| PDF export | `pinchtab pdf -o file.pdf` |--> **Tip:** Run `pinchtab snap` before `click` or `type` to cache element refs.--## What This Example Proves--If the full sequence works, your bridge runtime can:-- start and respond to API requests-- manage multiple tabs-- inspect page structure and text-- execute actions (click, type, press)-- render visual outputs (screenshots, PDFs)-- support locking and basic browser state APIs--If this example fails, check:-- the bridge is running on `127.0.0.1:9867`-- Chrome can be started successfullydiff --git a/docs/examples/pinchtab-server.md b/docs/examples/pinchtab-server.mddeleted file mode 100644index f18fcdbc..00000000--- a/docs/examples/pinchtab-server.md+++ /dev/null@@ -1,358 +0,0 @@-# Example: Server Smoke Test--This example is a happy-path smoke test for a running `pinchtab server` (orchestrator mode) on `127.0.0.1:9867`.--It is useful when you want to verify that the multi-instance orchestrator can:-- respond to health checks-- list and manage profiles-- launch and stop instances-- route requests to instances-- use the `--instance` CLI flag--For the server-mode mental model, see [Multi-Instance Guide](../guides/multi-instance.md).--## Prerequisites--Start the server:--```bash-pinchtab server-# or just: pinchtab (server is the default mode)-```--Set the base URL:--```bash-BASE=http://127.0.0.1:9867-```--The commands below assume `jq` is installed.--## 1. Check Health--```bash-curl -s "$BASE/health" | jq .-```--```bash-# CLI alternative-pinchtab health-```--```jsonc-// Response-{- "status": "ok",- "mode": "dashboard"-}-```--## 2. List Profiles--```bash-curl -s "$BASE/profiles" | jq .-```--```bash-# CLI alternative-pinchtab profiles-```--```jsonc-// Response-[- {- "id": "prof_967ae079",- "name": "default",- "path": "/Users/you/.pinchtab/profiles/default",- "pathExists": true,- "running": false,- "sizeMB": 160.17- }-]-```--## 3. List Instances--```bash-curl -s "$BASE/instances" | jq .-```--```bash-# CLI alternative-pinchtab instances-```--```jsonc-// Response (empty initially)-[]-```--## 4. Launch An Instance--```bash-INST=$(curl -s -X POST "$BASE/instances/launch" \- -H "Content-Type: application/json" \- -d '{"name":"my-profile","mode":"headless"}' \- | jq -r '.id')--echo "$INST"-```--```jsonc-// Response-{- "id": "inst_944a07ad",- "profileId": "prof_910b1739",- "profileName": "my-profile",- "port": "9871",- "headless": true,- "status": "starting",- "startTime": "2026-03-07T19:29:54.066542+01:00",- "attached": false-}-```--> **Note:** The instance will transition from `starting` to `running` within a few seconds.--## 5. Get Instance Details--```bash-curl -s "$BASE/instances/$INST" | jq .-```--```jsonc-// Response-{- "id": "inst_944a07ad",- "profileId": "prof_910b1739",- "profileName": "my-profile",- "port": "9871",- "headless": true,- "status": "running",- "startTime": "2026-03-07T19:29:54.066542+01:00",- "attached": false-}-```--## 6. Navigate On An Instance--Use the orchestrator proxy:--```bash-curl -s -X POST "$BASE/instances/$INST/navigate" \- -H "Content-Type: application/json" \- -d '{"url":"https://github.com/pinchtab/pinchtab"}' | jq .-```--Or connect directly to the instance port:--```bash-PORT=$(curl -s "$BASE/instances/$INST" | jq -r '.port')-curl -s -X POST "http://127.0.0.1:$PORT/navigate" \- -H "Content-Type: application/json" \- -d '{"url":"https://github.com/pinchtab/pinchtab"}' | jq .-```--```bash-# CLI alternative (uses --instance flag)-pinchtab nav --instance $INST https://github.com/pinchtab/pinchtab-```--```jsonc-// Response-{- "tabId": "E291F6815F61C58B0C9EA9129F960744",- "title": "GitHub - pinchtab/pinchtab",- "url": "https://github.com/pinchtab/pinchtab"-}-```--## 7. List Tabs On An Instance--```bash-curl -s "$BASE/instances/$INST/tabs" | jq .-```--```bash-# CLI alternative-pinchtab tabs --instance $INST-```--```jsonc-// Response-{- "tabs": [- {- "id": "E291F6815F61C58B0C9EA9129F960744",- "title": "GitHub - pinchtab/pinchtab",- "type": "page",- "url": "https://github.com/pinchtab/pinchtab"- }- ]-}-```--## 8. Snapshot On An Instance--```bash-curl -s "$BASE/instances/$INST/snapshot?filter=interactive" | jq '.nodes[:5]'-```--```bash-# CLI alternative-pinchtab snap -i -c --instance $INST-```--```bash-# CLI output-# GitHub - pinchtab/pinchtab | https://github.com/pinchtab/pinchtab | 144 nodes-e0:link "Skip to content"-e1:link "GitHub Homepage"-e2:link "pinchtab"-e5:button "Search or jump to…"-...-```--## 9. Click On An Instance--```bash-curl -s "$BASE/instances/$INST/snapshot?filter=interactive" > /dev/null-curl -s -X POST "$BASE/instances/$INST/action" \- -H "Content-Type: application/json" \- -d '{"kind":"click","ref":"e5"}' | jq .-```--```bash-# CLI alternative-pinchtab snap -i --instance $INST > /dev/null-pinchtab click e5 --instance $INST-```--```jsonc-// Response-{- "success": true,- "result": {- "clicked": true- }-}-```--## 10. Screenshot On An Instance--```bash-curl -s "$BASE/instances/$INST/screenshot" > screenshot.jpg-ls -lh screenshot.jpg-```--```bash-# CLI alternative-pinchtab ss -o screenshot.jpg --instance $INST-```--```bash-# Output-Saved screenshot.jpg (97376 bytes)-```--## 11. PDF On An Instance--```bash-curl -s "$BASE/instances/$INST/pdf" > page.pdf-ls -lh page.pdf-```--```bash-# CLI alternative-pinchtab pdf -o page.pdf --instance $INST-```--```bash-# Output-Saved page.pdf (1492879 bytes)-```--## 12. Launch A Second Instance--```bash-INST2=$(curl -s -X POST "$BASE/instances/launch" \- -H "Content-Type: application/json" \- -d '{"name":"another-profile","mode":"headless"}' \- | jq -r '.id')--echo "Instance 2: $INST2"-curl -s "$BASE/instances" | jq '.[].profileName'-```--```jsonc-// Response-"my-profile"-"another-profile"-```--## 13. Stop An Instance--```bash-curl -s -X DELETE "$BASE/instances/$INST" | jq .-```--```jsonc-// Response-{- "stopped": true-}-```--## 14. Attach To External Chrome (Optional)--If you have Chrome running with `--remote-debugging-port=9222`:--```bash-# Get the CDP URL-CDP_URL=$(curl -s http://localhost:9222/json/version | jq -r '.webSocketDebuggerUrl')--# Attach via Pinchtab (requires attach.enabled: true in config)-curl -s -X POST "$BASE/instances/attach" \- -H "Content-Type: application/json" \- -d "{\"cdpUrl\":\"$CDP_URL\"}" | jq .-```--```jsonc-// Response-{- "id": "inst_abc123",- "attached": true,- "cdpUrl": "ws://localhost:9222/devtools/browser/..."-}-```--## CLI Quick Reference (Server Mode)--| Action | CLI Command |-|--------|-------------|-| Health check | `pinchtab health` |-| List profiles | `pinchtab profiles` |-| List instances | `pinchtab instances` |-| Navigate | `pinchtab nav <url> --instance <id>` |-| Snapshot | `pinchtab snap -i -c --instance <id>` |-| Click | `pinchtab click <ref> --instance <id>` |-| Screenshot | `pinchtab ss -o file.jpg --instance <id>` |-| PDF export | `pinchtab pdf -o file.pdf --instance <id>` |--> **Tip:** Use `pinchtab instances` to get instance IDs, then use `--instance <id>` or `-I <id>` with other commands.--## What This Example Proves--If the full sequence works, your server/orchestrator can:-- start and manage multiple Chrome instances-- launch instances with different profiles-- route requests to specific instances-- proxy all bridge endpoints through the orchestrator-- stop instances cleanly-- optionally attach to external Chrome instances--If this example fails, check:-- the server is running on `127.0.0.1:9867`-- Chrome can be started successfully-- for attach: `attach.enabled: true` is set in configdiff --git a/docs/find-endpoint.md b/docs/find-endpoint.mddeleted file mode 100644index 7692370f..00000000--- a/docs/find-endpoint.md+++ /dev/null@@ -1,306 +0,0 @@-# `/find` Endpoint--## Overview--The `/find` endpoint allows AI agents to locate interactive elements on a web page using natural language descriptions instead of brittle CSS selectors or XPaths. It searches the current accessibility snapshot of a tab and returns the best-matching element reference, which can be passed directly to `/action` to interact with the element.--This solves a core problem in browser automation: agents no longer need to know exact selectors ahead of time. They describe *what* they want to interact with, and PinchTab resolves *which* element matches.-------## Endpoint--```-POST /tabs/{tabId}/find-```--The endpoint is available on both the per-instance API and the orchestrator (dashboard) API, where the orchestrator proxies the request to the correct instance.-------## Request Format--### Request Body (JSON)--| Field | Type | Required | Default | Description |-|-------------------|---------|----------|---------|--------------------------------------------------------------------------|-| `query` | string | **Yes** | — | Natural language description of the target element |-| `tabId` | string | No | active | Tab ID to search; defaults to the currently active tab |-| `threshold` | float | No | `0.3` | Minimum similarity score (0–1); results below this are filtered out |-| `topK` | int | No | `3` | Maximum number of matches to return |-| `lexicalWeight` | float | No | `0.6` | Weight for lexical scoring component (should sum to 1.0 with embedding) |-| `embeddingWeight` | float | No | `0.4` | Weight for embedding scoring component (should sum to 1.0 with lexical) |-| `explain` | bool | No | `false` | Include per-match score breakdown for debugging |--### Example Request--```json-{- "query": "search input",- "threshold": 0.3,- "topK": 3-}-```--### Example Request with Debug--```json-{- "query": "login button",- "threshold": 0.2,- "topK": 5,- "explain": true-}-```-------## Response Format--### Response Fields--| Field | Type | Description |-|-----------------|---------|-------------------------------------------------------------------------|-| `best_ref` | string | Reference ID of the highest-scoring element; pass this to `/action` |-| `confidence` | string | Human-readable label: `"high"`, `"medium"`, or `"low"` |-| `score` | float | Similarity score of the best match (0–1) |-| `matches` | array | Top-K scored matches (see Match Object below) |-| `strategy` | string | Matching strategy used (e.g. `"combined:lexical+embedding:hashing"`) |-| `threshold` | float | Threshold that was applied for this request |-| `latency_ms` | int | Time taken to execute the search in milliseconds |-| `element_count` | int | Total number of elements evaluated from the snapshot |--### Match Object--Each entry in the `matches` array contains:--| Field | Type | Description |-|-----------|---------|-----------------------------------------------------|-| `ref` | string | Element reference ID |-| `score` | float | Combined similarity score (0–1) |-| `role` | string | Accessibility role (e.g. `"button"`, `"textbox"`) |-| `name` | string | Accessible name of the element |-| `explain` | object | *(Only when `explain: true`)* Score breakdown |--### Explain Object--When `explain` is enabled, each match includes:--| Field | Type | Description |-|-------------------|---------|--------------------------------------------------|-| `lexical_score` | float | Weighted lexical similarity contribution |-| `embedding_score` | float | Weighted embedding similarity contribution |-| `composite` | string | The element's composite text used for matching |--### Example Response--```json-{- "best_ref": "e7",- "confidence": "high",- "score": 0.91,- "matches": [- { "ref": "e7", "score": 0.91, "role": "textbox", "name": "Search" },- { "ref": "e12", "score": 0.54, "role": "button", "name": "Search Wikipedia" }- ],- "strategy": "combined:lexical+embedding:hashing",- "threshold": 0.3,- "latency_ms": 18,- "element_count": 142-}-```--### Confidence Labels--| Label | Score Range | Meaning |-|----------|--------------|--------------------------------------------------|-| `high` | ≥ 0.80 | Strong match — safe to act on immediately |-| `medium` | 0.60 – 0.79 | Reasonable match — verify before critical actions|-| `low` | < 0.60 | Weak match — consider rephrasing the query |-------### Embedding Matcher--Converts text into fixed-dimension vectors using feature hashing (the "hashing trick"):--- **Word-level features** — whole word hashes for exact overlap-- **Character n-gram features** — 2-to-4 character subsequences capture sub-word similarity-- **Role-aware features** — known UI roles get boosted feature weights-- **Synonym injection** — synonym tokens are added at reduced weight so related terms share vector space-- Vectors are **L2-normalized** and scored via **cosine similarity**-- Zero external dependencies — no ML models, APIs, or vocabulary files required--### Combined Scoring--The final score for each element is a weighted average:--```-final_score = 0.6 × lexical_score + 0.4 × embedding_score-```--Both matchers run **concurrently**. The combined matcher uses a lower internal threshold (50% of the requested threshold) to capture candidates that might only score well on one strategy but pass when combined.--Per-request weight overrides are supported via `lexicalWeight` and `embeddingWeight`.-------## Matching Strategy Details--### Synonym Categories--The built-in synonym table covers 10 UI categories:--| Category | Examples |-|----------------------|--------------------------------------------------------------|-| Authentication | login ↔ sign in ↔ log in ↔ authenticate ↔ log on |-| Account | register ↔ sign up ↔ create account ↔ join |-| Navigation | search ↔ find ↔ lookup; menu ↔ navigation ↔ sidebar |-| Form actions | submit ↔ send ↔ confirm ↔ save; cancel ↔ abort ↔ discard |-| UI elements | button ↔ btn; input ↔ textbox ↔ text field |-| Shopping | cart ↔ basket ↔ bag; checkout ↔ purchase ↔ buy |-| Content | image ↔ picture ↔ photo ↔ icon; title ↔ heading ↔ header |-| Dialogs | modal ↔ dialog ↔ popup ↔ overlay |-| User feedback | notification ↔ alert ↔ toast ↔ banner |-| Common actions | click ↔ press ↔ tap; accept ↔ agree ↔ ok ↔ confirm |--### Element Descriptors--Each element from the accessibility snapshot is converted into a composite text string:--```-{Role}: {Name} [{Value}]-```--For example, a search box might produce: `textbox: Search`.-------## Example Usage--### Find a search input--```bash-curl -X POST http://localhost:9868/tabs/t1/find \- -H "Content-Type: application/json" \- -d '{"query": "search input"}'-```--### Find the login button--```bash-curl -X POST http://localhost:9868/tabs/t1/find \- -H "Content-Type: application/json" \- -d '{"query": "login button"}'-```--### Find with debug scoring--```bash-curl -X POST http://localhost:9868/tabs/t1/find \- -H "Content-Type: application/json" \- -d '{"query": "submit button", "explain": true, "topK": 5}'-```-------## Typical AI Agent Workflow--```-navigate → find → action-```--### Step-by-Step--```jsonc-// Step 1: Navigate to a page-POST /tabs/t1/navigate-{ "url": "https://github.com/login" }--// Step 2: Find the username field-POST /tabs/t1/find-{ "query": "username input" }-// → { "best_ref": "e14", "confidence": "high", "score": 0.85 }--// Step 3: Type into it-POST /tabs/t1/action-{ "ref": "e14", "action": "type", "value": "[email protected]" }--// Step 4: Find the password field-POST /tabs/t1/find-{ "query": "password field" }-// → { "best_ref": "e18", "confidence": "high", "score": 0.82 }--// Step 5: Type password-POST /tabs/t1/action-{ "ref": "e18", "action": "type", "value": "••••••••" }--// Step 6: Find and click the sign-in button-POST /tabs/t1/find-{ "query": "sign in button" }-// → { "best_ref": "e23", "confidence": "high", "score": 0.88 }--POST /tabs/t1/action-{ "ref": "e23", "action": "click" }-```-------## Example Queries--| Query | What it finds |-|-----------------------------|------------------------------------------|-| `"search input"` | Main search text field |-| `"login button"` | Sign-in / log-in button |-| `"submit button"` | Form submit button |-| `"cart icon"` | Shopping cart link or button |-| `"sign up"` | Registration / create account link |-| `"close modal"` | Dialog dismiss button |-| `"top right profile menu"` | User profile button in the header |-| `"accept cookies"` | Cookie consent accept button |--Synonyms are handled automatically — `"sign in"`, `"log in"`, `"login"`, and `"log on"` all resolve to the same element.-------## Performance Characteristics--- **Latency**: typically < 20ms for pages with 100–200 elements-- **Snapshot**: operates on a cached accessibility snapshot (no DOM traversal per query)-- **Auto-fetch**: if no cached snapshot exists, one is fetched automatically via CDP before matching-- **Concurrency**: lexical and embedding matchers run concurrently in separate goroutines-- **Zero external dependencies**: all matching runs in-process using pure Go — no ML model downloads, no API calls-- **Intent caching**: successful matches are stored in an intent cache, enabling the recovery engine to re-find elements if references go stale after page changes-------## Error Handling--| Status | Condition | Response Body |-|--------|------------------------------------------------|---------------------------------------------------|-| `400` | Request body cannot be decoded | `{"error": "decode: ..."}` |-| `400` | `query` field is missing or empty | `{"error": "missing required field 'query'"}` |-| `404` | Tab ID does not exist | `{"error": "..."}` |-| `500` | Chrome not initialized | `{"error": "chrome initialization: ..."}` |-| `500` | No elements in snapshot | `{"error": "no elements found in snapshot ..."}` |-| `500` | Internal matcher error | `{"error": "matcher error: ..."}` |--When `best_ref` is an empty string in a 200 response, no element met the threshold. Lower the threshold or rephrase the query.-------## Notes for Developers--### Integration with PinchTab Architecture--1. **Accessibility Snapshot** — `/find` reads from the same snapshot cache used by `/snapshot`. When a snapshot is not cached, it is auto-fetched via CDP (`getAccessibilityTree`). No separate snapshot call is needed.--2. **Element Descriptors** — each `A11yNode` from the snapshot is converted into an `ElementDescriptor` with `Ref`, `Role`, `Name`, and `Value` fields. These are combined into a composite string (`"role: Name [Value]"`) for matching.--3. **Semantic Matching Pipeline** — the `CombinedMatcher` runs `LexicalMatcher` and `EmbeddingMatcher` concurrently, merges scores by element ref, applies the weighted average, and filters by threshold.--4. **Intent Caching & Recovery** — after a successful match, the query and matched descriptor are stored in an `IntentCache`. If a subsequent `/action` call fails because the ref is stale (e.g. after a page re-render), the recovery engine uses the cached intent to re-run the semantic search and find the element at its new ref.--5. **Orchestrator Proxy** — the dashboard orchestrator exposes `POST /tabs/{id}/find` and proxies the request to the correct browser instance. No code duplication — the same handler runs on both the instance and orchestrator APIs.--6. **No External Dependencies** — the entire matching pipeline (tokenization, stopwords, synonyms, hashing embedder, cosine similarity) is implemented in pure Go with zero external libraries or ML models.diff --git a/docs/get-started.md b/docs/get-started.mdindex 46582e83..15d3862d 100644--- a/docs/get-started.md+++ b/docs/get-started.md@@ -1,19 +1,21 @@# Getting Started-Get PinchTab running in 5 minutes, from zero to browser automation.+Get PinchTab running in a few minutes, from zero to browser automation.----## Installation (Choose One)+## Installation-### Option 1: One-Liner (Recommended)+### Option 1: one-liner++**macOS / Linux**-**macOS / Linux:**```bashcurl -fsSL https://pinchtab.com/install.sh | bash```Then verify:+```bashpinchtab --version```@@ -27,13 +29,6 @@ npm install -g pinchtabpinchtab --version```-**Troubleshooting npm:**-```bash-# If "command not found", add npm to PATH-export PATH="$(npm config get prefix)/bin:$PATH"-# Add to ~/.bashrc or ~/.zshrc to persist-```-### Option 3: Docker**Requires:** Docker@@ -43,600 +38,119 @@ docker run -d -p 9867:9867 pinchtab/pinchtabcurl http://localhost:9867/health```-### Option 4: Build from Source+### Option 4: build from source**Requires:** Go 1.25+, Git, Chrome/Chromium```bashgit clone https://github.com/pinchtab/pinchtab.gitcd pinchtab-./pdev doctor # Verify environment + install hooks/deps+./pdev doctorgo build -o pinchtab ./cmd/pinchtab./pinchtab --version```-**[Full build guide →](architecture/building.md)**+**[Full build guide ->](architecture/building.md)**----## Quick Start (5 Minutes)--The primary usage model is simple:+## Quick start-- install Pinchtab-- run `pinchtab`-- point your agent or automation client at `http://localhost:9867`-- treat Pinchtab as the local browser service+The normal flow is:-That is the default setup for users who want Pinchtab to replace an embedded browser runtime in another tool.+1. start the server+2. start an instance+3. navigate+4. inspect or act-### Step 1: Start the Server+### Step 1: start the server-**Terminal 1:**```bashpinchtab+# Response+🦀 PinchTab port=9867+dashboard ready url=http://localhost:9867```-**Expected output:**-```-🦀 Pinchtab port=9867-dashboard ready url=http://localhost:9867/dashboard-```--The full server is running on `http://127.0.0.1:9867`. Open the dashboard in your browser to see instances and profiles.--PinchTab also has a `pinchtab bridge` mode, but that is the single-instance runtime used behind managed instances. For normal use, start the full server.--### Step 2: Create an Instance--**Terminal 2:**-```bash-# Create a headless instance (background Chrome)-INST=$(pinchtab instance launch --mode headless | jq -r '.id')-echo "Instance created: $INST"--# Wait for Chrome to initialize (~2-5 seconds)-sleep 3-```--### Step 3: Run Your First Command--```bash-# Navigate to a website-TAB_ID=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -H "Content-Type: application/json" \- -d '{"url":"https://pinchtab.com"}' | jq -r '.tabId')--# Get page structure-curl http://localhost:9867/tabs/$TAB_ID/snapshot | jq '.nodes | map({role, name}) | .[0:5]'--# Extract text-curl http://localhost:9867/tabs/$TAB_ID/text | jq '.text'-```--✅ **You're running PinchTab!**-------## Common First Commands--### Get Page Content--```bash-INST=$(pinchtab instance launch | jq -r '.id')-sleep 2--# Navigate-TAB_ID=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://pinchtab.com"}' | jq -r '.id')--# Read the page as text-curl http://localhost:9867/tabs/$TAB_ID/text--# Get interactive elements (snapshot)-curl http://localhost:9867/tabs/$TAB_ID/snapshot | jq '.nodes | map({ref, role, name})'-```--### Take a Screenshot--```bash-# Save screenshot for a specific tab-curl "http://localhost:9867/tabs/$TAB_ID/screenshot" -o page.png-```--### Export as PDF--```bash-# Save PDF-curl "http://localhost:9867/tabs/$TAB_ID/pdf?landscape=true" -o output.pdf-```--### Interact with the Page--```bash-# Get page structure (snapshot)-SNAPSHOT=$(curl http://localhost:9867/tabs/$TAB_ID/snapshot)--# Extract a reference (e.g., first button)-BUTTON_REF=$(echo "$SNAPSHOT" | jq -r '.nodes[] | select(.role=="button") | .ref' | head -1)+The server runs on `http://127.0.0.1:9867`.+You can open the dashboard at `http://127.0.0.1:9867` or `http://127.0.0.1:9867/dashboard`.-# Click the button-curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -H "Content-Type: application/json" \- -d '{"kind":"click","ref":"'$BUTTON_REF'"}'--# Or fill a form input-curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -H "Content-Type: application/json" \- -d '{"kind":"fill","ref":"e3","text":"[email protected]"}'-```--### Multiple Tabs+### Step 2: start your first instance```bash-# Create new tab in instance-curl -X POST http://localhost:9867/instances/$INST/tabs/open \+curl -s -X POST http://127.0.0.1:9867/instances/start \-H "Content-Type: application/json" \- -d '{"url":"https://github.com"}'--# List all tabs-curl http://localhost:9867/tabs--# Operate on specific tab-TAB_ID=$(curl http://localhost:9867/instances/$INST/tabs | jq -r '.[0].id')--curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"click","ref":"e5","tabId":"'$TAB_ID'"}'-```-------## Understanding the Workflow--### Key Concepts--**Server** (port 9867):-- Manages instances and profiles-- Routes requests via `/instances/{id}/*` and `/tabs/{id}/*`-- Serves the dashboard UI-- Spawns bridge runtimes for managed instances--**Instance** (ports 9868-9968):-- Real Chrome browser process-- Has one or more tabs-- Isolated cookies, history, storage-- Each has unique ID: `inst_XXXXXXXX`--**Bridge**:-- The single-instance runtime backing a managed instance-- Thin HTTP wrapper over one browser instance-- Usually spawned by the server automatically--**Tab**:-- Single webpage within instance-- Has state (URL, DOM, focus, content)-- Unique ID: `tab_XXXXXXXX`--### Typical Workflow--```bash-# 1. Create instance (Chrome starts lazily on first request)-INST=$(pinchtab instance launch | jq -r '.id')-sleep 2--# 2. Navigate to a page-TAB_ID=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://pinchtab.com"}' | jq -r '.id')--# 3. Get page structure (see buttons, links, inputs)-curl http://localhost:9867/tabs/$TAB_ID/snapshot--# 4. Interact with page (click, type, etc.)-curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"click","ref":"e5"}'--# 5. Verify changes-curl http://localhost:9867/tabs/$TAB_ID/snapshot--# 6. Capture result-curl "http://localhost:9867/tabs/$TAB_ID/screenshot" -o page.png-curl "http://localhost:9867/tabs/$TAB_ID/pdf" -o report.pdf--# 7. Stop instance (clean up)-curl -X POST http://localhost:9867/instances/$INST/stop+ -d '{"mode":"headless"}' | jq .+# CLI Alternative+pinchtab instance start+# Response+{+ "id": "inst_0a89a5bb",+ "profileId": "prof_278be873",+ "profileName": "instance-1741400000000000000",+ "port": "9868",+ "headless": true,+ "status": "starting"+}```------## Using with curl (HTTP API)--You don't need the CLI. PinchTab is HTTP:+### Step 3: navigate```bash-# Health check-curl http://localhost:9867/health--# Create instance-INST=$(curl -s -X POST http://localhost:9867/instances/launch | jq -r '.id')-sleep 2--# Navigate-curl -X POST http://localhost:9867/instances/$INST/tabs/open \+curl -s -X POST http://127.0.0.1:9867/navigate \-H "Content-Type: application/json" \- -d '{"url":"https://pinchtab.com"}'--# Get snapshot-curl http://localhost:9867/tabs/$TAB_ID/snapshot--# Extract text-curl http://localhost:9867/tabs/$TAB_ID/text--# Stop instance-curl -X POST http://localhost:9867/instances/$INST/stop-```--**Full API reference** → [curl-commands.md](references/curl-commands.md)-**Instance API details** → [instance-api.md](references/instance-api.md)-------## Using with Python--```python-import requests-import json-import time--BASE = "http://localhost:9867"--# 1. Create instance-resp = requests.post(f"{BASE}/instances/launch", json={"mode": "headless"})-inst_id = resp.json()["id"]-print(f"Created instance: {inst_id}")--# Wait for Chrome to initialize-time.sleep(2)--# 2. Create tab by navigating-resp = requests.post(f"{BASE}/instances/{inst_id}/tabs/open", json={- "url": "https://pinchtab.com"-})-tab_id = resp.json()["id"]-print(f"Navigated: {resp.json()}")--# 3. Get snapshot-snapshot = requests.get(f"{BASE}/tabs/{tab_id}/snapshot").json()--# Print interactive elements-for elem in snapshot.get("nodes", []):- if elem.get("role") in ["button", "link"]:- print(f"{elem['ref']}: {elem['role']} - {elem['name']}")--# 4. Click an element-requests.post(f"{BASE}/tabs/{tab_id}/action", json={- "action": "click",- "ref": "e5"-})--# 5. Get text-text = requests.get(f"{BASE}/tabs/{tab_id}/text").json()-print(f"Page text: {text['text'][:200]}...")--# 6. Stop instance-requests.post(f"{BASE}/instances/{inst_id}/stop")-print(f"Stopped instance: {inst_id}")-```-------## Using with Node.js--```javascript-const fetch = require('node-fetch');--const BASE = "http://localhost:9867";--async function main() {- try {- // 1. Create instance- const launchResp = await fetch(`${BASE}/instances/launch`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ mode: "headless" })- });- const launch = await launchResp.json();- const instId = launch.id;- console.log(`Created instance: ${instId}`);-- // Wait for Chrome to initialize- await new Promise(r => setTimeout(r, 2000));-- // 2. Create tab by navigating- const navResp = await fetch(`${BASE}/instances/${instId}/tabs/open`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- url: "https://pinchtab.com"- })- });- const navData = await navResp.json();- const tabId = navData.id;-- // 3. Get snapshot- const snapResp = await fetch(`${BASE}/tabs/${tabId}/snapshot`);- const snap = await snapResp.json();-- // Print interactive elements- snap.nodes- .filter(n => ["button", "link"].includes(n.role))- .forEach(n => console.log(`${n.ref}: ${n.role} - ${n.name}`));-- // 4. Click element- await fetch(`${BASE}/tabs/${tabId}/action`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- action: "click",- ref: "e5"- })- });-- // 5. Get text- const textResp = await fetch(`${BASE}/tabs/${tabId}/text`);- const text = await textResp.json();- console.log(`Page text: ${text.text.substring(0, 200)}...`);-- // 6. Stop instance- await fetch(`${BASE}/instances/${instId}/stop`, {- method: "POST"- });- console.log(`Stopped instance: ${instId}`);-- } catch (error) {- console.error("Error:", error);- }+ -d '{"url":"https://github.com/pinchtab/pinchtab"}' | jq .+# CLI Alternative+pinchtab nav https://github.com/pinchtab/pinchtab+# Response+{+ "tabId": "CDP_TARGET_ID",+ "title": "GitHub - pinchtab/pinchtab",+ "url": "https://github.com/pinchtab/pinchtab"}--main();```------## Configuration--### Server Configuration+### Step 4: inspect the page```bash-# Custom port-PINCHTAB_PORT=9868 pinchtab--# Auth token for remote access-PINCHTAB_TOKEN=my-secret-token pinchtab--# Bind to all interfaces (for remote access)-PINCHTAB_BIND=0.0.0.0 pinchtab--# Custom Chrome binary (used by all instances)-CHROME_BIN=/usr/bin/google-chrome pinchtab-```--### Instance Configuration--Instance-specific options are set when creating instances:--```bash-# Headless (default, fastest)-pinchtab instance launch --mode headless--# Headed (visible window, for debugging)-pinchtab instance launch --mode headed--# Specific port (usually auto-allocated)-pinchtab instance launch --port 9999--# With persistent profile-pinchtab profile create work-PROF_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="work") | .id')-curl -X POST http://localhost:9867/instances/start \- -d '{"profileId":"'$PROF_ID'","mode":"headed"}'-```--**[Full configuration →](references/configuration.md)**-------## Common Scenarios--### Scenario 1: Scrape a Website--```bash-# Create instance-INST=$(pinchtab instance launch | jq -r '.id')-sleep 2--# Navigate-curl -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://pinchtab.com/article"}'--# Extract text-curl http://localhost:9867/tabs/$TAB_ID/text | jq '.text'--# Save to file-curl http://localhost:9867/tabs/$TAB_ID/text | jq -r '.text' > article.txt--# Stop instance-curl -X POST http://localhost:9867/instances/$INST/stop-```--### Scenario 2: Fill and Submit a Form--```bash-# Create instance-INST=$(pinchtab instance launch | jq -r '.id')-sleep 2--# Navigate to form-curl -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://pinchtab.com/contact"}'--# Get form structure-SNAP=$(curl http://localhost:9867/tabs/$TAB_ID/snapshot)--# Fill fields (get refs from snapshot)-curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"fill","ref":"e3","text":"John Doe"}'--curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"fill","ref":"e5","text":"[email protected]"}'--curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"fill","ref":"e7","text":"My message here"}'--# Click submit-curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"click","ref":"e10"}'--# Verify success-curl http://localhost:9867/tabs/$TAB_ID/snapshot | jq '.nodes | length'-```--### Scenario 3: Login + Stay Logged In--```bash-# Create persistent profile-pinchtab profile create mylogin-PROF_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="mylogin") | .id')--# Start instance with profile-INST=$(curl -s -X POST http://localhost:9867/instances/start \- -d '{"profileId":"'$PROF_ID'"}' | jq -r '.id')-sleep 2--# Login-curl -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://pinchtab.com/login"}'--curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"fill","ref":"e3","text":"[email protected]"}'--curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"fill","ref":"e5","text":"password"}'--curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"click","ref":"e7"}'--# Stop instance (profile saved)-curl -X POST http://localhost:9867/instances/$INST/stop--# Later: restart with same profile (already logged in!)-INST=$(curl -s -X POST http://localhost:9867/instances/start \- -d '{"profileId":"'$PROF_ID'"}' | jq -r '.id')-sleep 2--# Navigate to dashboard (cookies preserved)-curl -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://pinchtab.com/dashboard"}'-```--### Scenario 4: Generate PDF Report--```bash-# Create instance-INST=$(pinchtab instance launch | jq -r '.id')-sleep 2--TAB_ID=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://reports.pinchtab.com/monthly"}' | jq -r '.id')-# Export PDF-curl "http://localhost:9867/tabs/$TAB_ID/pdf?landscape=true" -o report.pdf+curl -s "http://127.0.0.1:9867/snapshot?filter=interactive" | jq .+# CLI Alternative+pinchtab snap -i -c+# Response+{+ "nodes": [+ { "ref": "e0", "role": "link", "name": "Skip to content" },+ { "ref": "e14", "role": "button", "name": "Search or jump to…" }+ ]+}```-### Scenario 5: Multi-Tab Workflow--```bash-# Create instance-INST=$(pinchtab instance launch | jq -r '.id')-sleep 2--# Open first tab (source)-curl -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://source.pinchtab.com"}'--# Open second tab (destination)-curl -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://destination.pinchtab.com"}'--# List tabs-TABS=$(curl http://localhost:9867/instances/$INST/tabs)-SOURCE_TAB=$(echo "$TABS" | jq -r '.[0].id')-DEST_TAB=$(echo "$TABS" | jq -r '.[1].id')--# Extract from source tab-DATA=$(curl "http://localhost:9867/tabs/$TAB_ID/text" | jq -r '.text')--# Fill destination tab-curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -H "Content-Type: application/json" \- -d '{"kind":"fill","ref":"e3","text":"'$DATA'","tabId":"'$DEST_TAB'"}'-```+You now have a working PinchTab server, a running browser instance, and a navigated tab.---## Troubleshooting-### "connection refused" / "Cannot connect"--**Problem:** Orchestrator not running+### Connection refused-**Solution:**```bash-# Terminal 1: Start orchestrator-pinchtab--# Terminal 2: Check health (once running)curl http://localhost:9867/health```-### "Instance stuck in 'starting' state"+If that fails, start the server:-**Problem:** Chrome takes time to initialize (8-20 seconds)--**Solution:**```bash-# Poll instance status-INST=$(pinchtab instance launch | jq -r '.id')--# Wait until 'running'-while [ "$(curl -s http://localhost:9867/instances/$INST | jq -r '.status')" != "running" ]; do- sleep 0.5-done--# Now safe to use-curl -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://pinchtab.com"}'+pinchtab```-### "Port already in use"--**Problem:** Port 9867 (or instance port) is taken+### Port already in use-**Solution:**```bash-# Use different server portPINCHTAB_PORT=9868 pinchtab--# Or kill the process using 9867-lsof -i :9867-kill -9 <PID>--# Instance ports auto-allocated from 9868-9968, no manual config needed```-### "Chrome not found"+### Chrome not found-**Problem:** Chrome/Chromium not installed--**Solution:**```bash# macOSbrew install chromium@@ -644,180 +158,14 @@ brew install chromium# Linux (Ubuntu/Debian)sudo apt install chromium-browser-# Or specify custom Chrome+# Custom Chrome binaryCHROME_BIN=/path/to/chrome pinchtab```-### "Empty snapshot / 404 error"--**Problem:** Instance ID is invalid or instance was stopped--**Solution:**-```bash-# List running instances-curl http://localhost:9867/instances--# Use valid instance ID-INST=$(pinchtab instance launch | jq -r '.id')--# Verify it's running-curl http://localhost:9867/instances/$INST-```--### "ref e5 not found"--**Problem:** Page updated or different page loaded--**Solution:**-```bash-# Get fresh snapshot-SNAP=$(curl http://localhost:9867/tabs/$TAB_ID/snapshot)--# Extract new ref from snapshot-NEW_REF=$(echo "$SNAP" | jq -r '.nodes[] | select(.role=="button") | .ref' | head -1)--# Use new ref-curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"click","ref":"'$NEW_REF'"}'-```-------## Common Features--### Extract Text Efficiently--```bash-# Get text content-curl http://localhost:9867/tabs/$TAB_ID/text--# Get snapshot (DOM structure)-curl http://localhost:9867/tabs/$TAB_ID/snapshot--# Filter snapshot to interactive elements-curl http://localhost:9867/tabs/$TAB_ID/snapshot | \- jq '.nodes[] | select(.role | IN("button", "link", "textbox"))'-```--### Interact with Page--```bash-# Click element-curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"click","ref":"e5"}'--# Type text-curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"type","ref":"e3","text":"hello"}'--# Fill input-curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"fill","ref":"e3","text":"value"}'--# Press key-curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"press","key":"Enter"}'--# Focus element-curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"focus","ref":"e5"}'--# Hover element-curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"hover","ref":"e5"}'--# Select dropdown-curl -X POST http://localhost:9867/tabs/$TAB_ID/action \- -d '{"kind":"select","ref":"e8","text":"Option 2"}'-```--### Run JavaScript--```bash-# Evaluate expression-curl -X POST http://localhost:9867/instances/$INST/evaluate \- -H "Content-Type: application/json" \- -d '{"expression":"document.title"}'--# Get page info-curl -X POST http://localhost:9867/instances/$INST/evaluate \- -H "Content-Type: application/json" \- -d '{"expression":"JSON.stringify({title: document.title, url: location.href})"}'-```-------## Performance Tips--### Use Headless for Speed--```bash-# Headless (default, faster)-pinchtab instance launch --mode headless--# Headed (visible window, slower, better for debugging)-pinchtab instance launch --mode headed-```--### Parallel Processing--```bash-# Create multiple instances for concurrent work-for i in 1 2 3 4 5; do- INST=$(pinchtab instance launch | jq -r '.id')- INSTANCES+=("$INST")-done--# Distribute work across instances (round-robin)-for URL in "${URLS[@]}"; do- INST="${INSTANCES[$((INDEX % 5))]}"- curl -X POST "http://localhost:9867/instances/$INST/tabs/open" \- -d '{"url":"'$URL'"}' &- ((INDEX++))-done-wait-```--### Token Efficiency--```bash-# Use text extraction (cheaper than screenshots)-curl http://localhost:9867/tabs/$TAB_ID/text # Lower tokens--# Use snapshot (cheaper than screenshot)-curl http://localhost:9867/tabs/$TAB_ID/snapshot # Lower tokens--# Screenshots are expensive (JPG encoding)-curl "http://localhost:9867/tabs/$TAB_ID/screenshot" # Higher tokens-```-------## Quick Reference--| Task | Command |-|------|---------|-| Start orchestrator | `pinchtab` |-| Health check | `curl http://localhost:9867/health` |-| Create instance | `INST=$(pinchtab instance launch \| jq -r '.id')` |-| Navigate | `curl -X POST http://localhost:9867/instances/$INST/tabs/open -d '{"url":"..."}' ` |-| See structure | `curl http://localhost:9867/tabs/$TAB_ID/snapshot` |-| Get text | `curl http://localhost:9867/tabs/$TAB_ID/text` |-| Click element | `curl -X POST http://localhost:9867/tabs/$TAB_ID/action -d '{"kind":"click","ref":"e5"}'` |-| Type text | `curl -X POST http://localhost:9867/tabs/$TAB_ID/action -d '{"kind":"type","ref":"e3","text":"hello"}'` |-| Screenshot | `curl "http://localhost:9867/tabs/$TAB_ID/screenshot" -o page.png` |-| PDF export | `curl http://localhost:9867/tabs/$TAB_ID/pdf -o out.pdf` |-| List instances | `curl http://localhost:9867/instances` |-| List tabs | `curl http://localhost:9867/instances/$INST/tabs` |-| New tab | `curl -X POST http://localhost:9867/instances/$INST/tabs/open -d '{"url":"..."}'` |-| Stop instance | `curl -X POST http://localhost:9867/instances/$INST/stop` |-----## Getting Help+## Getting help-- **Issues** → [GitHub Issues](https://github.com/pinchtab/pinchtab/issues)-- **Q&A** → [GitHub Discussions](https://github.com/pinchtab/pinchtab/discussions)-- **Docs** → [Full documentation](overview.md)+- [GitHub Issues](https://github.com/pinchtab/pinchtab/issues)+- [GitHub Discussions](https://github.com/pinchtab/pinchtab/discussions)-**Happy automating!** 🦀diff --git a/docs/guides/agent-optimization.md b/docs/guides/agent-optimization.mddeleted file mode 100644index 40d26a50..00000000--- a/docs/guides/agent-optimization.md+++ /dev/null@@ -1,199 +0,0 @@-# Agent Optimization Guide--**Last updated:** Feb 25, 2026-**Tested with:** Claude Haiku, Corriere.it, BBC News--## Executive Summary--Agents using Pinchtab can reduce token usage by **93%** and improve reliability by 100% through:-1. Clear, prescriptive instructions (no experimentation)-2. Waiting 3+ seconds after navigation-3. Using a saved query pattern-------## The Experiment--### Setup-Three scraping tasks across different approaches:-- **Run 1 (web_fetch fallback):** Agent chose simpler HTML extraction-- **Run 2 (exploratory Pinchtab):** Agent discovered Pinchtab, tried multiple filters, adapted to page load delays-- **Run 3 (pattern-driven Pinchtab):** Agent given exact curl command, executed once, reported results--### Results--| Run | Approach | In | Out | **Total** | Notes |-|-----|----------|----|----|----------|-------|-| 1 | web_fetch | 43 | 1,800 | **1,843** | Fallback extraction |-| 2 | Exploratory Pinchtab | 142 | 3,700 | **3,842** | Found pattern through trial |-| 3 | Pattern-driven Pinchtab | 10 | 262 | **272** | ✅ **14x better** |--### Key Discovery: The 3-Second Wait--Early attempts returned only 1 node:-```json-{"count": 1, "nodes": [{"ref": "e0", "role": "RootWebArea"}]}-```--After sleeping 3 seconds:-```-{"count": 2645, "nodes": [...]}-```--**Why?** Chrome's accessibility tree takes time to populate. The DOM renders immediately, but accessibility events lag behind.-------## Reliable Pattern--### For Scraping Headlines/Titles--```bash-curl -X POST http://localhost:9867/navigate \- -H "Content-Type: application/json" \- -d '{"url": "https://pinchtab.com"}' && \-sleep 3 && \-curl http://localhost:9867/snapshot | \-jq '.nodes[] | select(.name | length > 15) | .name' | \-head -30-```--**Why this works:**-1. Navigate + wait ensures full accessibility tree-2. jq filter extracts text nodes only (eliminates UI chrome)-3. `length > 15` filters out buttons, labels, tiny text-4. `head -30` limits output (saves tokens)--### For Interactive Tasks (Click, Type, etc.)--Pattern same as above, but:-1. Take snapshot after navigation-2. Extract refs (e.g., `e5`, `e12`)-3. Act on refs (`click e5`, `type e12 "text"`)-4. Take another snapshot to verify-5. Repeat until done--**Cost:** Higher (full snapshots), but necessary for interaction.-------## Token Cost Deep Dive--### Scraping Cost: Pattern-Driven (Optimal)--```-Input: 10 tokens (simple instructions + curl command)-Output: 262 tokens (30 headlines)-Total: 272 tokens-Per headline: ~9 tokens-```--### Scraping Cost: Exploratory (What agents do without guidance)--```-Input: 142 tokens (task + agent thinking + skill search)-Output: 3,700 tokens (full parsing + multiple attempts + explanation)-Total: 3,842 tokens-Per headline: ~128 tokens-```--**Ratio:** 128 / 9 = **14.2x worse**--### Why the Difference?--| Overhead | Tokens | Reason |-|----------|--------|--------|-| Skill file search | ~50 | Agent looking for docs |-| Failed snapshot filter attempts | ~100 | Trying `.role == "article"`, etc. |-| Full tree parsing | ~2,000 | Extracting all 2,645 nodes |-| Explanation + reasoning | ~1,550 | Agent narrating process |-| **Pattern-driven (no overhead)** | ~272 | Direct execution |-------## System Prompt Template--Use this for agents scraping with Pinchtab:--```-# Pinchtab Scraping Instructions--When extracting headlines from a website:--1. Use EXACTLY this curl pattern (do not deviate):-- curl -X POST http://localhost:9867/navigate \- -H "Content-Type: application/json" \- -d '{"url": "TARGET_URL"}' && \- sleep 3 && \- curl http://localhost:9867/snapshot | \- jq '.nodes[] | select(.name | length > 15) | .name' | \- head -30--2. Replace TARGET_URL with the site URL-3. Report the headlines (limit to 20 unique items)-4. Do NOT try alternative filters, approaches, or explanations--This pattern has been optimized for token efficiency (93% savings).-```-------## Site-Specific Notes--### Corriere.it-- **Nodes:** 2,645-- **Render time:** 3 seconds-- **Filter:** `.name | length > 15`-- **Example headline:** "A 65 anni vende tutto per girare il mondo: «Ho 4 valigie e un sogno, ecco come faccio». Ha già visitato 146 Paesi"--### BBC News-- **Nodes:** 2,300+-- **Render time:** 3 seconds-- **Filter:** `.name | length > 15`-- **Example headline:** "Trump announces emergency declaration for border security"--### Pattern Universality-The 3-second + jq filter pattern works on **any site with a standard HTML DOM**. No site-specific tuning needed.-------## When NOT to Use Pattern-Driven--1. **Interactive workflows** — Need to click, fill forms, verify results (requires full snapshots + refs)-2. **Dynamic content** — Page loads data after initial render (increase wait time to 5-10s)-3. **JavaScript-heavy SPAs** — May need multiple snapshots + waits between state changes--**Use pattern-driven ONLY for:** Read-only headline/title scraping with fast render times.-------## Validation Checklist--Before deploying to production:--- [ ] Agent follows curl pattern exactly (no `web_fetch` fallback)-- [ ] Wait time is 3+ seconds (adjust if needed)-- [ ] jq filter matches target content (headlines vs. all text)-- [ ] `head -N` limits output appropriately-- [ ] Agent reports only relevant results (no parsing explanation)-- [ ] First run validated manually on target site-------## Future Improvements--- [ ] Adaptive wait time detection (poll `/snapshot` until count > threshold)-- [ ] Site-specific render profiles (BBC: 2s, SPA: 8s, etc.)-- [ ] Cache snapshot between multiple extract calls (same navigation, different filters)-- [ ] Fallback to web_fetch if Pinchtab unavailable (graceful degradation)-------## Questions?--- **Token usage still high?** Check your jq filter; overly complex filters parse more nodes-- **Only 1-2 headlines extracted?** Increase `head -N` or lower `.name | length` threshold-- **Timeouts?** Increase sleep time or set `BRIDGE_HEADLESS=true` for faster rendering-- **See "RootWebArea" only?** Wait time too short; increase to 5 seconds minimum-diff --git a/docs/guides/attach-chrome.md b/docs/guides/attach-chrome.mdnew file mode 100644index 00000000..95ef3a66--- /dev/null+++ b/docs/guides/attach-chrome.md@@ -0,0 +1,234 @@+# Attach An Existing Chrome++Use this guide when:++- Chrome already exists outside PinchTab+- you want the PinchTab server to register that browser as an instance+- you already have a browser-level DevTools WebSocket URL++Do not use this guide if your goal is simply:++- start a browser for your agent+- run the normal local PinchTab workflow++For that, use managed instances with `pinchtab` and `POST /instances/start`.++---++## Launch vs attach++The mental model is:++```text+launch = PinchTab starts and owns the browser+attach = PinchTab registers an already running browser+```++With attach:++- Chrome is started somewhere else+- PinchTab receives a `cdpUrl`+- the server registers that browser as an attached instance++---++## What is implemented today++The current codebase implements:++- `POST /instances/attach`+- attach policy in config under `attach`+- attached-instance metadata in `GET /instances`++The attach request body is:++```json+{+ "name": "shared-chrome",+ "cdpUrl": "ws://127.0.0.1:9222/devtools/browser/..."+}+```++There is currently no CLI attach command.++---++## Step 1: enable attach policy++Attach is disabled unless you allow it in config.++Example:++```json+{+ "attach": {+ "enabled": true,+ "allowHosts": ["127.0.0.1", "localhost", "::1"],+ "allowSchemes": ["ws", "wss"]+ }+}+```++What this does:++- enables the attach endpoint+- restricts which hosts are accepted+- restricts which URL schemes are accepted++What this does not do:++- it does not start Chrome+- it does not define a global remote browser+- it does not replace managed instances++---++## Step 2: start Chrome with remote debugging++Example:++```bash+google-chrome --remote-debugging-port=9222+# Or on some systems:+# chromium --remote-debugging-port=9222+```++This makes Chrome expose a browser-level DevTools endpoint.++---++## Step 3: get the browser WebSocket URL++Query Chrome:++```bash+curl -s http://127.0.0.1:9222/json/version | jq .+# Response+{+ "webSocketDebuggerUrl": "ws://127.0.0.1:9222/devtools/browser/abc123"+}+```++The value of `webSocketDebuggerUrl` is the `cdpUrl` you pass to PinchTab.++---++## Step 4: attach it to PinchTab++```bash+curl -X POST http://localhost:9867/instances/attach \+ -H "Content-Type: application/json" \+ -d '{+ "name": "shared-chrome",+ "cdpUrl": "ws://127.0.0.1:9222/devtools/browser/abc123"+ }'+# Response+{+ "id": "inst_0a89a5bb",+ "profileId": "prof_278be873",+ "profileName": "shared-chrome",+ "port": "",+ "headless": false,+ "status": "running",+ "attached": true,+ "cdpUrl": "ws://127.0.0.1:9222/devtools/browser/abc123"+}+```++Notes:++- `name` is optional; if omitted, the server generates one like `attached-...`+- the server validates the URL against `attach.allowHosts` and `attach.allowSchemes`++---++## Step 5: confirm it is registered++```bash+curl -s http://localhost:9867/instances | jq .+# CLI Alternative+pinchtab instances+```++An attached instance appears in the normal instance list with:++- `attached: true`+- `cdpUrl: ...`+- `status: "running"`++---++## Ownership and lifecycle++Attached instances are externally owned.++That means:++- PinchTab did not launch the browser+- PinchTab stores metadata about that browser as an instance+- the external Chrome process remains outside PinchTab lifecycle ownership++In practical terms:++- stopping the attached instance in PinchTab unregisters it from the server+- it does not imply that PinchTab launched or can fully manage the external Chrome process++---++## When attach makes sense++Use attach when:++- Chrome is managed by another system+- Chrome is already running in a separate service or container+- you want the server to know about an externally managed browser+- you want to keep browser ownership outside PinchTab++---++## Security++Attach widens the trust boundary, so keep it locked down.++Recommended rules:++- leave attach disabled unless you need it+- keep `allowHosts` narrow+- keep `allowSchemes` narrow+- set `PINCHTAB_TOKEN` when the server is reachable outside localhost+- only attach to CDP endpoints you trust++Also remember:++- Chrome DevTools gives powerful browser control+- a reachable CDP endpoint should be treated as sensitive infrastructure++If Chrome is remote, prefer a tunnel rather than exposing the debugging port broadly.++---++## Operational model++The intended model is:++```text+agent -> PinchTab server -> attached external Chrome+```++This is an expert path, not the default user path.++The default path remains:++```bash+pinchtab+```++then managed instance launch via:++```bash+curl -X POST http://localhost:9867/instances/start \+ -H "Content-Type: application/json" \+ -d '{"mode":"headless"}'+# CLI Alternative+pinchtab instance start+```\ No newline at end of filediff --git a/docs/guides/cdp-url-shared-chrome.md b/docs/guides/cdp-url-shared-chrome.mddeleted file mode 100644index 5034af60..00000000--- a/docs/guides/cdp-url-shared-chrome.md+++ /dev/null@@ -1,372 +0,0 @@-# Remote Chrome--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.pinchtab.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/guides/common-patterns.md b/docs/guides/common-patterns.mddeleted file mode 100644index 7462bc3d..00000000--- a/docs/guides/common-patterns.md+++ /dev/null@@ -1,689 +0,0 @@-# 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 '{"mode":"headed"}'-```--**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 '{"mode":"headed"}' | jq -r '.id')--echo "Manual testing instance: $INST"-echo "Chrome window is open - interact manually or use API calls"--# Wait for Chrome to initialize-sleep 2--# Optionally navigate to starting URL (via orchestrator proxy)-curl -s -X POST "http://localhost:9867/instances/$INST/tabs/open" \- -H "Content-Type: application/json" \- -d '{"url":"https://app.pinchtab.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 '{"mode":"headless"}'-```--**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 '{"mode":"headless"}' | jq -r '.id')-- INSTANCES+=("$INST")-done--echo "Created 5 parallel test workers"--# Run tests in parallel-TEST_URLS=(- "https://app.pinchtab.com/test1"- "https://app.pinchtab.com/test2"- "https://app.pinchtab.com/test3"- "https://app.pinchtab.com/test4"- "https://app.pinchtab.com/test5"-)--for i in "${!INSTANCES[@]}"; do- INST="${INSTANCES[$i]}"- URL="${TEST_URLS[$i]}"-- # Run test in parallel (via orchestrator proxy)- (- curl -s -X POST "http://localhost:9867/instances/$INST/tabs/open" \- -H "Content-Type: application/json" \- -d "{\"url\":\"$URL\"}" > /dev/null-- # Verify page loaded- TITLE=$(curl -s "http://localhost:9867/tabs/$TAB_ID/snapshot" | jq -r '.title')- echo "Test $i: $TITLE"- ) &-done--wait--# Cleanup-for INST in "${INSTANCES[@]}"; do- 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 '{"mode":"headed"}' | 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 '{"mode":"headless"}' > /dev/null &-done-wait--echo "Setup: 1 headed (debug) + 10 headless (workers)"-```-------## Pattern 2: Load Distribution--### Round-Robin Distribution--Distribute requests evenly across instances via orchestrator:--```bash-#!/bin/bash--# Create 5 instances-INSTANCES=()-for i in {1..5}; do- INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')- INSTANCES+=("$INST")-done--# Wait for Chrome initialization-sleep 3--URLS=(- "https://pinchtab.com/page1"- "https://pinchtab.com/page2"- "https://pinchtab.com/page3"- "https://pinchtab.com/page4"- "https://pinchtab.com/page5"- "https://pinchtab.com/page6"- "https://pinchtab.com/page7"- "https://pinchtab.com/page8"-)--# Distribute evenly via orchestrator proxy-for i in "${!URLS[@]}"; do- URL="${URLS[$i]}"- INST="${INSTANCES[$((i % ${#INSTANCES[@]}))]}"-- curl -s -X POST "http://localhost:9867/instances/$INST/tabs/open" \- -H "Content-Type: application/json" \- -d "{\"url\":\"$URL\"}" &-done--wait-```--**Result:**-Each instance handles roughly equal work (round-robin).--### Weighted Distribution--Send more work to better instances (e.g., faster systems get more requests):--```bash-#!/bin/bash--# Create weighted instance pool-INSTANCES=()--# Add 3 copies of fast instance (handles 3/6 = 50% of work)-for i in {1..3}; do- INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')- INSTANCES+=("$INST")-done--# Add 2 copies of standard instance (handles 2/6 = 33% of work)-for i in {1..2}; do- INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')- INSTANCES+=("$INST")-done--# Add 1 copy of slow instance (handles 1/6 = 17% of work)-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')-INSTANCES+=("$INST")--# Distribute using weighted list-for i in "${!URLS[@]}"; do- URL="${URLS[$i]}"- INST="${INSTANCES[$((i % ${#INSTANCES[@]}))]}"-- curl -s -X POST "http://localhost:9867/instances/$INST/tabs/open" \- -H "Content-Type: application/json" \- -d "{\"url\":\"$URL\"}" &-done--wait-```--**Result:**-Fast instances handle more load, slower instances handle less.--### Queue-Based Distribution--Process a work queue dynamically, keeping a fixed number of concurrent jobs:--```bash-#!/bin/bash--# Create instance pool (3 workers)-INSTANCES=()-for i in {1..3}; do- INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')- INSTANCES+=("$INST")-done--# Work queue (100 URLs)-QUEUE=(- "https://pinchtab.com/1"- "https://pinchtab.com/2"- "https://pinchtab.com/3"- # ... up to ...- "https://pinchtab.com/100"-)--# Process queue with max concurrent jobs (use 'wait -n' for job-level control)-MAX_JOBS=3-CURRENT_JOB=0--# Start initial batch-for i in $(seq 0 $((MAX_JOBS - 1))); do- [ $CURRENT_JOB -lt ${#QUEUE[@]} ] || break-- URL="${QUEUE[$CURRENT_JOB]}"- INST="${INSTANCES[$((CURRENT_JOB % MAX_JOBS))]}"-- (- curl -s -X POST "http://localhost:9867/instances/$INST/tabs/open" \- -H "Content-Type: application/json" \- -d "{\"url\":\"$URL\"}" > /dev/null- echo "Processed: $URL"- ) &-- ((CURRENT_JOB++))-done--# Process remaining queue-while [ $CURRENT_JOB -lt ${#QUEUE[@]} ]; do- URL="${QUEUE[$CURRENT_JOB]}"- INST="${INSTANCES[$((CURRENT_JOB % MAX_JOBS))]}"-- (- curl -s -X POST "http://localhost:9867/instances/$INST/tabs/open" \- -H "Content-Type: application/json" \- -d "{\"url\":\"$URL\"}" > /dev/null- echo "Processed: $URL"- ) &-- # Wait for a background job to complete- wait -n-- ((CURRENT_JOB++))-done--# Wait for remaining jobs-wait--echo "Queue processing complete"-```-------## Pattern 3: State Isolation--### Per-User Profiles--Each user gets their own instance with persistent state:--```bash-#!/bin/bash--# Create persistent profiles for each user-pinchtab profile create user-1-pinchtab profile create user-2-pinchtab profile create user-3--# Get profile IDs-U1_PROF=$(pinchtab profiles | jq -r '.[] | select(.name=="user-1") | .id')-U2_PROF=$(pinchtab profiles | jq -r '.[] | select(.name=="user-2") | .id')-U3_PROF=$(pinchtab profiles | jq -r '.[] | select(.name=="user-3") | .id')--# Create instances with profiles-U1=$(curl -s -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"profileId":"'$U1_PROF'","mode":"headless"}' | jq -r '.id')--U2=$(curl -s -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"profileId":"'$U2_PROF'","mode":"headless"}' | jq -r '.id')--U3=$(curl -s -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"profileId":"'$U3_PROF'","mode":"headless"}' | jq -r '.id')--# Each user has:-# - Separate Chrome process-# - Persistent profile (survives restarts)-# - Separate cookies (login sessions preserved)-# - Separate history, local storage-# - No interference between users--# User 1 navigates (via orchestrator proxy)-curl -s -X POST "http://localhost:9867/instances/$U1/tabs/open" \- -H "Content-Type: application/json" \- -d '{"url":"https://app.pinchtab.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.pinchtab.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.pinchtab.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.pinchtab.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.pinchtab.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.pinchtab.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.pinchtab.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.pinchtab.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://pinchtab.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/architecture/building.md b/docs/guides/contributing.mdsimilarity index 100%rename from docs/architecture/building.mdrename to docs/guides/contributing.mddiff --git a/docs/guides/data-storage.md b/docs/guides/data-storage.mdindex 426c2a01..7726d96d 100644--- a/docs/guides/data-storage.md+++ b/docs/guides/data-storage.md@@ -1,292 +1,191 @@# Data Storage Guide-Pinchtab stores configuration, state, and browser profiles on your local filesystem. This guide explains what files are saved, why, where they're located, and how storage locations changed in recent versions.+PinchTab stores configuration, profiles, session state, and usage logs on local disk. This guide describes what is stored, where it lives by default, and which paths you can change.-## What Files Does Pinchtab Store?+## What PinchTab Stores-| File/Directory | Purpose | Configurable Via |-|----------------|---------|------------------|-| `profiles/<name>/` | Chrome browser profile (cookies, cache, localStorage, etc.) | `profiles.baseDir` + `profiles.defaultProfile` in config |-| `config.json` | Runtime configuration (port, token, headless mode, etc.) | `PINCHTAB_CONFIG` env var |-| `action_logs.json` | Profile action history and analytics | *(not currently configurable)* |-| `*.state.json` | Bridge state files (orchestrator state, etc.) | `server.stateDir` in config |+| Path | Purpose | How To Change It |+| --- | --- | --- |+| `config.json` | Main PinchTab configuration | `PINCHTAB_CONFIG` selects the file |+| `profiles/<profile>/` | Chrome user data for each profile | `profiles.baseDir` |+| `action_logs.json` | Profile activity log used by profile analytics | not currently configurable |+| `sessions.json` | Saved tab/session state for a bridge instance | `server.stateDir` |+| `<profile>/.pinchtab-state/config.json` | Child instance config written by the orchestrator | generated automatically for managed instances |-### Chrome Profile Directory+## Default Storage Location-The largest and most important directory. Contains:-- **Cookies & Session Storage** — Login sessions, auth tokens-- **LocalStorage & IndexedDB** — Web app data-- **Cache** — Images, scripts, and other cached resources-- **Extensions** — If you've installed Chrome extensions via the Bridge API+PinchTab uses the OS config directory:-**Why it exists:** Chrome requires a profile directory to run. Without it, you'd lose all session state between restarts.+| OS | Default Base Directory |+| --- | --- |+| Linux | `~/.config/pinchtab/` or `$XDG_CONFIG_HOME/pinchtab/` |+| macOS | `~/Library/Application Support/pinchtab/` |+| Windows | `%APPDATA%\\pinchtab\\` |-**Size:** Can grow to 100MB+ depending on usage (cache, cookies, etc.).+Typical layout:-### Configuration File+```text+pinchtab/+├── config.json+├── action_logs.json+├── sessions.json+└── profiles/+ └── default/+```++## Legacy Fallback++For backward compatibility, PinchTab still uses `~/.pinchtab/` if:++- that legacy directory already exists+- and the newer OS-native location does not exist yet++That fallback applies to both config lookup and the default base storage directory.++## Profiles++Profiles are the durable browser state PinchTab reuses across launches. A profile directory can contain:++- cookies and login sessions+- local storage and IndexedDB+- cache and history+- Chrome preferences and session files++Configure the profile root with:-`config.json` stores runtime settings:```json{- "server": {- "port": "9867",- "token": "your-secret-token",- "stateDir": "/custom/path/state"- },- "instanceDefaults": {- "mode": "headless"- },"profiles": {- "baseDir": "/custom/path/profiles",+ "baseDir": "/path/to/profiles","defaultProfile": "default"}}```-**Why it exists:** Allows persistent configuration without environment variables.+`profiles.defaultProfile` controls the default profile name used by single-instance flows. In orchestrator mode, managed instances can still launch with other profile names.-### Action Logs+## Config File-`action_logs.json` tracks browser actions for analytics:-- URL visits per profile-- Common hosts accessed-- Action timestamps+The main config file is read from:-**Why it exists:** Provides usage analytics via the `/profiles/analytics` API endpoint.+- the path in `PINCHTAB_CONFIG`, if set+- otherwise `<user-config-dir>/config.json`-### State Files+Example:-Internal bridge state (orchestrator, instance tracking, etc.).+```json+{+ "server": {+ "port": "9867",+ "stateDir": "/var/lib/pinchtab/state"+ },+ "profiles": {+ "baseDir": "/var/lib/pinchtab/profiles",+ "defaultProfile": "default"+ }+}+```-**Why they exist:** Restore browser instances after restart (if `noRestore` is false).+## Session State-## Storage Locations+Bridge session restore data is stored as:-### Current (v1.x+, After XDG Migration)+```text+<server.stateDir>/sessions.json+```-Pinchtab now uses **OS-native application data directories**:+This file is used for tab/session restoration when restore behavior is enabled.-| OS | Default Location |-|----|------------------|-| **Linux** | `~/.config/pinchtab/` (or `$XDG_CONFIG_HOME/pinchtab/`) |-| **macOS** | `~/Library/Application Support/pinchtab/` |-| **Windows** | `%APPDATA%\pinchtab\` (`C:\Users\YourName\AppData\Roaming\pinchtab\`) |+In orchestrator mode, child instances get their own state directory under the profile:-Inside that directory:-```-pinchtab/-├── profiles/ # Browser profiles-│ └── default/-├── config.json # Configuration-├── action_logs.json # Action history-└── *.state.json # Bridge state files+```text+<profile>/.pinchtab-state/```-**Why the change?**-- **Linux Snap/AppArmor compatibility** — Security policies allow standard XDG directories but block arbitrary dotfolders under `$HOME`-- **OS conventions** — Follows platform-specific best practices-- **Better Windows support** — Uses proper `%APPDATA%` instead of a dotfolder+PinchTab writes a child `config.json` there so the launched instance can inherit the correct profile path, state directory, and port.-### Legacy (Pre-XDG Migration)+## Action Logs-Previously, everything lived in `~/.pinchtab/`:-```-~/.pinchtab/-├── chrome-profile/-├── config.json-├── action_logs.json-└── *.state.json-```+PinchTab stores profile activity in:-**Backwards compatibility:** If you have an existing `~/.pinchtab/` directory with data, pinchtab will continue using it automatically (migration logic checks for the old location first).+```text+<user-config-dir>/action_logs.json+```-## Customizing Storage Locations+This powers profile analytics endpoints. It is separate from the per-instance session restore state.-### Via Environment Variables+## Customizing Storage-Only `PINCHTAB_CONFIG` remains for storage-related path selection:+### Choose A Different Config File```bash-# Custom config file locationexport PINCHTAB_CONFIG=/etc/pinchtab/config.jsonpinchtab```-### Via Configuration File+### Choose Different Profile And State Paths-Set custom paths in `config.json`:```json{"server": {- "stateDir": "/var/lib/pinchtab/state"+ "stateDir": "/srv/pinchtab/state"},"profiles": {- "baseDir": "/mnt/data/profiles",+ "baseDir": "/srv/pinchtab/profiles","defaultProfile": "default"}}```-**Priority order:** `PINCHTAB_CONFIG` chooses which config file to load. Storage paths inside that file control the actual directories.--## Migration from Legacy Location+## Container Use-If you're upgrading from an older version that used `~/.pinchtab/`, you have three options:+For Docker or other containers, persist both config and profile data with a mounted volume and point `PINCHTAB_CONFIG` at a file inside that volume.-### Option 1: Automatic (Recommended)+Example layout inside the volume:-Do nothing. Pinchtab will detect the old location and continue using it if:-- `~/.pinchtab/` exists-- The new OS-native location doesn't exist yet--### Option 2: Manual Migration--Move your data to the new location:--**Linux:**-```bash-mkdir -p ~/.config/pinchtab-mv ~/.pinchtab/* ~/.config/pinchtab/-rmdir ~/.pinchtab-```--**macOS:**-```bash-mkdir -p ~/Library/Application\ Support/pinchtab-mv ~/.pinchtab/* ~/Library/Application\ Support/pinchtab/-rmdir ~/.pinchtab-```--**Windows (PowerShell):**-```powershell-mkdir $env:APPDATA\pinchtab-mv ~/.pinchtab/* $env:APPDATA\pinchtab\-rmdir ~/.pinchtab+```text+/data/+├── config.json+├── state/+└── profiles/```-### Option 3: Stay on Legacy Location+Then set:-Set your config file to point to the legacy location:```json{"server": {- "stateDir": "~/.pinchtab"+ "stateDir": "/data/state"},"profiles": {- "baseDir": "~/.pinchtab/profiles",- "defaultProfile": "default"+ "baseDir": "/data/profiles"}}```-## Container Deployments--In Docker/containerized environments:--1. **Mount a volume** for persistence:- ```bash- docker run -v /host/pinchtab-data:/data \- -e PINCHTAB_CONFIG=/data/config.json \- pinchtab/pinchtab- ```--2. **Set `HOME` environment variable** if needed:- ```dockerfile- ENV HOME=/app- ```--3. **Store explicit paths in the mounted config file**.--## Security Considerations+## Security Notes-### Profile Directory Contains Sensitive Data+Profile directories often contain sensitive browser state:-- **Cookies & Sessions** — Can be used to impersonate logged-in users-- **LocalStorage** — May contain auth tokens, API keys-- **History & Cache** — Reveals browsing activity+- cookies+- session tokens+- cached content+- site data-**Recommendations:**-- Set restrictive permissions on profile directories, for example `chmod 700 ~/.config/pinchtab/profiles/default`-- Don't commit profile directories to version control-- Use separate profiles for different security contexts-- Consider encrypting the filesystem or using encrypted volumes+Recommended practice:-### Configuration File--`config.json` may contain:-- **`token`** — Used to authenticate API requests--**Recommendations:**-- Set restrictive permissions: `chmod 600 config.json`-- Use environment variables for tokens in production (don't hardcode in config files)+- keep profile directories out of version control+- restrict permissions on config and profile directories+- use separate profiles for separate security contexts## Cleanup-To completely remove all pinchtab data:--**Linux/macOS:**-```bash-rm -rf ~/.config/pinchtab # New location-rm -rf ~/Library/Application\ Support/pinchtab # macOS-rm -rf ~/.pinchtab # Legacy location (if still exists)-```--**Windows:**-```powershell-rmdir /s $env:APPDATA\pinchtab-```--This will delete:-- All browser profiles and sessions-- Configuration-- State files-- Action logs--**Warning:** You'll lose all saved sessions, cookies, and browser state. Back up your `chrome-profile/` directory if you want to preserve login sessions.--## Troubleshooting--### "Permission denied" on Linux (Snap/AppArmor)--**Symptom:** Chrome fails to start with:-```-Failed to create SingletonLock: Permission denied (13)-```--**Cause:** Using an old pinchtab version that stores profiles in `~/.pinchtab` (blocked by Snap AppArmor).--**Solution:** Upgrade to the latest version (uses `~/.config/pinchtab` by default) or move profile storage under your configured `profiles.baseDir`.--See [Issue #98](https://github.com/pinchtab/pinchtab/issues/98) for details.--### "Config file not found" after upgrade--**Cause:** Upgraded from legacy `~/.pinchtab/` but pinchtab is now looking in the new location.--**Solution:** Copy your config:-```bash-cp ~/.pinchtab/config.json ~/.config/pinchtab/config.json # Linux-```--Or use `PINCHTAB_CONFIG`:-```bash-export PINCHTAB_CONFIG=~/.pinchtab/config.json-```--### Profile directory size is huge--**Cause:** Chrome cache grows over time.--**Solution:** Clear the cache periodically:-```bash-rm -rf ~/.config/pinchtab/profiles/default/Default/Cache-rm -rf ~/.config/pinchtab/profiles/default/Default/Code\ Cache-```+Removing the PinchTab data directory deletes:-Or point `profiles.baseDir` at a temporary directory for short-lived sessions.+- saved profiles+- session restore data+- action logs+- local configuration-## Further Reading+Back up the profile directories first if you need to preserve logged-in browser sessions.-- [Configuration Reference](../references/configuration.md) — Full list of config options-- [CLI Quick Reference](../references/cli-quick-reference.md) — Command-line usage-- [Issue #98](https://github.com/pinchtab/pinchtab/issues/98) — XDG directory migration discussiondiff --git a/docs/guides/docker.md b/docs/guides/docker.mdindex 6c1471cc..a1feaca3 100644--- a/docs/guides/docker.md+++ b/docs/guides/docker.md@@ -1,112 +1,116 @@# Docker Deployment-Pinchtab includes a Docker image with bundled Chromium for easy deployment.+PinchTab can run in Docker with a mounted data volume for config, profiles, and state. The safest way to configure the current implementation is to mount a `config.json` file and point `PINCHTAB_CONFIG` at it.## Quick Start-### Using Docker Compose+Build the image from this repository:```bash-# Clone the repository-git clone https://github.com/pinchtab/pinchtab.git-cd pinchtab+docker build -t pinchtab .+```-# Start with docker-compose-docker-compose up -d+Create a local data directory with config:-# Check logs-docker-compose logs -f+```text+docker-data/+└── config.json+```-# Test-curl http://localhost:9867/health+Example `docker-data/config.json`:++```json+{+ "server": {+ "bind": "0.0.0.0",+ "port": "9867",+ "stateDir": "/data/state"+ },+ "profiles": {+ "baseDir": "/data/profiles",+ "defaultProfile": "default"+ },+ "instanceDefaults": {+ "mode": "headless",+ "noRestore": true+ }+}```-### Using Docker CLI+Run the container:```bash-# Build image-docker build -t pinchtab .--# Run containerdocker run -d \--name pinchtab \-p 9867:9867 \- -v pinchtab-data:/data \+ -v "$PWD/docker-data:/data" \+ -e PINCHTAB_CONFIG=/data/config.json \+ --shm-size=2g \--security-opt seccomp=unconfined \pinchtab+```-# With auth token-docker run -d \- --name pinchtab \- -p 9867:9867 \- -v pinchtab-data:/data \- -e BRIDGE_TOKEN=your-secret-token \- --security-opt seccomp=unconfined \- pinchtab+Check it:++```bash+curl http://localhost:9867/health+curl http://localhost:9867/instances```-## Configuration+## What To Persist-Environment variables:-- `BRIDGE_BIND` - Address to bind to (set to `0.0.0.0` in Docker)-- `BRIDGE_PORT` - HTTP port (default: 9867)-- `BRIDGE_TOKEN` - Auth token (optional)-- `BRIDGE_HEADLESS` - Run Chrome headless (default: true in Docker)-- `BRIDGE_STATE_DIR` - State directory (default: /data)-- `BRIDGE_STEALTH` - Stealth level: `light` (default) or `full`-- `BRIDGE_BLOCK_IMAGES` - Block image loading (default: false)-- `BRIDGE_BLOCK_MEDIA` - Block all media (default: false)-- `BRIDGE_NO_ANIMATIONS` - Disable CSS animations (default: false)-- `CHROME_BINARY` - Set automatically in Docker (`/usr/bin/chromium-browser`)-- `CHROME_FLAGS` - Set automatically in Docker (`--no-sandbox --disable-gpu`)+If you want data to survive container restarts, persist:-## Architecture+- the config file+- the profile directory+- the state directory-The Docker image:-- Uses Alpine Linux for minimal size-- Includes Chromium browser-- Runs as non-root user-- Uses dumb-init for proper signal handling-- Persists state in `/data` volume+Without a mounted volume, profiles and saved session state are ephemeral.-## Profiles & Dashboard Mode+## Runtime Configuration-Docker runs Pinchtab in **bridge mode** — a single headless Chrome instance with one default profile. This is the intended setup for containers.+For current runtime overrides, rely on:-The **profile management** feature (dashboard mode, multiple named Chrome profiles) is designed for **desktop/workstation** use where you might manage multiple browser identities from a GUI. It doesn't apply to Docker deployments:+- `PINCHTAB_CONFIG`+- `PINCHTAB_BIND`+- `PINCHTAB_PORT`+- `PINCHTAB_TOKEN`+- `CHROME_BIN`-- Containers are ephemeral — profiles don't persist unless you mount `/data`-- There's no user desktop or personal Chrome to coexist with-- One container = one browser instance, which is the right model for automation+Everything else should go in `config.json`.-If you need multiple isolated browser instances, run multiple containers rather than using the dashboard's profile system.+In the bundled image, you usually do not need to set `CHROME_BIN` manually unless you are replacing the browser binary.-## Security Notes+## Compose-The container requires `--security-opt seccomp=unconfined` for Chrome to function properly. This is a limitation of running Chrome in containers.+The repository includes a `docker-compose.yml`, but the stable configuration pattern is still:-For production use:-1. Always set `BRIDGE_TOKEN`-2. Use a reverse proxy with TLS-3. Limit container resources-4. Run on isolated networks+1. mount a persistent data directory+2. point `PINCHTAB_CONFIG` at `/data/config.json`+3. keep behavior settings in that file-## Troubleshooting+If you expose PinchTab beyond localhost, set an auth token and put it behind TLS or a trusted reverse proxy.-### Chrome crashes-Increase memory limit:-```yaml-mem_limit: 4g-```+## Resource Notes-### Font issues-The image includes basic fonts. For specific fonts:-```dockerfile-RUN apk add --no-cache ttf-liberation ttf-dejavu-```+Chrome in containers usually needs:++- larger shared memory, such as `--shm-size=2g`+- a relaxed seccomp profile such as `seccomp=unconfined`+- enough RAM for your tab count and workload++For heavier scraping or testing workloads, also consider:++- lowering `instanceDefaults.maxTabs`+- setting block options like `blockImages` in config+- running multiple smaller containers instead of one oversized browser++## Multi-Instance In Containers++You can run orchestrator mode inside one container and start managed instances from the API, but many teams prefer one browser service per container because:++- lifecycle is simpler+- container-level resource limits are clearer+- restart behavior is easier to reason about-### Performance-For better performance:-```yaml-shm_size: '2gb' # Shared memory for Chrome-```\ No newline at end of file+Choose based on whether you want container-level isolation or PinchTab-managed multi-instance orchestration.diff --git a/docs/guides/expert-attach.md b/docs/guides/expert-attach.mddeleted file mode 100644index a904feb0..00000000--- a/docs/guides/expert-attach.md+++ /dev/null@@ -1,155 +0,0 @@-# Expert Guide: Attach--This guide is for advanced setups where Chrome already exists outside Pinchtab and you want the server to register it as an instance.--## What Attach Means--Attach does not launch Chrome.--Instead:-- Chrome is already running somewhere else-- Pinchtab server receives a `cdpUrl`-- Pinchtab registers that browser as an instance-- requests can then be routed through the server--Mental model:--```text-launch = Pinchtab creates the browser-attach = Pinchtab registers an existing browser-```--## When Attach Makes Sense--Use attach when:-- Chrome is managed by another system-- Chrome runs in another container or service-- you need Pinchtab routing around an existing CDP endpoint-- you want the server to treat external Chrome as an instance--## When Attach Does Not Make Sense--Do not use attach if your goal is simply:-- “start a browser for my agent”-- “run Pinchtab locally as my browser service”--In those cases, use managed launch via the full server.--## Enable Attach Policy--Attach is controlled by config policy.--Example:--```json-{- "attach": {- "enabled": true,- "allowHosts": ["127.0.0.1", "localhost", "::1"],- "allowSchemes": ["ws", "wss"]- }-}-```--This does not define a browser.-It only defines which attach requests are allowed.--## Attach Request--Example:--```bash-curl -X POST http://localhost:9867/instances/attach \- -H "Content-Type: application/json" \- -d '{- "name": "shared-chrome",- "cdpUrl": "ws://127.0.0.1:9222/devtools/browser/..."- }'-```--## Getting A CDP URL--If you are attaching to a browser you started yourself, the usual flow is:--```bash-# Start Chrome with remote debugging enabled-google-chrome --remote-debugging-port=9222--# Or on some systems:-# chromium --remote-debugging-port=9222-```--Then ask Chrome for its browser-level websocket endpoint:--```bash-curl http://localhost:9222/json/version-```--Example response:--```json-{- "webSocketDebuggerUrl": "ws://localhost:9222/devtools/browser/abc123"-}-```--That `webSocketDebuggerUrl` is the value you pass as `cdpUrl` in the attach request.--Example:--```bash-curl -X POST http://localhost:9867/instances/attach \- -H "Content-Type: application/json" \- -d '{- "name": "shared-chrome",- "cdpUrl": "ws://localhost:9222/devtools/browser/abc123"- }'-```--## What Pinchtab Owns--By default, attached instances are externally owned:--```text-source = attached-runtime = direct-cdp-ownership = external-```--That means:-- Pinchtab routes to them-- Pinchtab did not launch them-- lifecycle ownership may remain outside Pinchtab--## Security Considerations--Attach should be treated as an expert feature because it widens trust boundaries.--Recommended rules:-- keep `attach.enabled` off by default-- restrict `allowHosts`-- restrict `allowSchemes`-- require `PINCHTAB_TOKEN` when the server is reachable by anything other than localhost-- only attach to CDP endpoints you trust--## Operational Model--```text-agent -> pinchtab server -> attached external Chrome-```--There is no bridge child in the attach path.--## Current Scope--Attach is the right abstraction for:-- external Chrome-- containerized Chrome managed elsewhere-- CDP endpoints outside Pinchtab lifecycle control--It is not the primary user path.-The primary user path remains:--```bash-pinchtab-```diff --git a/docs/guides/expert-bridge-mode.md b/docs/guides/expert-bridge-mode.mddeleted file mode 100644index f969828e..00000000--- a/docs/guides/expert-bridge-mode.md+++ /dev/null@@ -1,115 +0,0 @@-# Expert Guide: Bridge Mode--This guide is for advanced users who want to run `pinchtab bridge` directly.--For most users, the right entrypoint is still:--```bash-pinchtab-```--Use bridge mode only when you explicitly want the single-instance runtime without the full server control plane.--## What Bridge Mode Is--`pinchtab bridge` starts the single-instance HTTP runtime.--It:-- wraps one browser-- exposes the browser/tab API directly-- does not serve the dashboard-- does not manage multiple instances-- does not act as the main control plane--In normal managed mode, the server spawns bridge children for you.--## When To Use It--Bridge mode makes sense when:-- you want one browser runtime only-- you do not need profiles/instance orchestration in the parent process-- you want to debug the single-instance runtime directly-- you want to run the bridge as a standalone worker--## When Not To Use It--Do not use bridge mode as the primary onboarding path if your real goal is:-- “give my agent a local browser service”-- “replace an embedded browser runtime in another tool”-- “manage profiles and instances from one endpoint”--In those cases, use:--```bash-pinchtab-```--## Minimal Example--```bash-pinchtab bridge-```--Then call the single-instance API on the configured port:--```bash-curl -X POST http://localhost:9867/navigate \- -H "Content-Type: application/json" \- -d '{"url":"https://pinchtab.com"}'--curl http://localhost:9867/snapshot?filter=interactive-```--For a broader end-to-end check, see [Example: Bridge Smoke Test](../examples/bridge-smoke-test.md).--## Configuration Model--Bridge mode still uses the same `config.json` and operational env surface:--```bash-PINCHTAB_PORT=9868 pinchtab bridge-PINCHTAB_TOKEN=secret pinchtab bridge-CHROME_BIN=/usr/bin/google-chrome pinchtab bridge-```--Behavior defaults still come from config file sections like:-- `browser`-- `instanceDefaults`-- `security`-- `timeouts`--## Mental Model--```text-pinchtab bridge- -> one runtime- -> one browser- -> many tabs-```--Compared with full server mode:--```text-pinchtab- -> one control plane- -> many instances- -> each managed instance may run through a bridge-```--## Tradeoffs--Benefits:-- fewer product layers visible to you-- direct access to the single-instance API-- useful for debugging and specialized deployments--Costs:-- no instance pool-- no profile/instance dashboard workflow-- no attach/launch control plane-- you are choosing the lower-level runtime, not the main product entrypoint--## Recommended Rule--Use bridge mode when you explicitly want the worker runtime.-Use server mode when you want Pinchtab as a browser service.diff --git a/docs/guides/expert-strategies.md b/docs/guides/expert-strategies.mddeleted file mode 100644index 5775421e..00000000--- a/docs/guides/expert-strategies.md+++ /dev/null@@ -1,188 +0,0 @@-# Expert Guide: Multi-Instance Strategies And Allocation--This guide covers advanced server behavior for users running more than the default simple local setup.--## Two Separate Concepts--Pinchtab has two knobs for advanced multi-instance behavior:--- `multiInstance.strategy`-- `multiInstance.allocationPolicy`--These are different.--Mental model:--```text-strategy = what routing model the server exposes-allocationPolicy = which running instance gets selected-```--## Strategy--Valid strategies on this branch:--- `simple`-- `explicit`-- `simple-autorestart`--### `simple`--`simple` is the default.--It behaves like:-- shorthand routes proxy to the first running instance-- if needed, the strategy may ensure one instance exists-- good default for single-user, single-active-instance workflows--Best fit:-- local development-- “just give me one browser service”-- simplest replacement for an embedded browser runtime--### `explicit`--`explicit` exposes the orchestrator model directly.--It is best when you want to think in terms of:-- profiles-- instances-- tab IDs-- explicit routing--Best fit:-- systems that manage several instances deliberately-- users who want predictable, explicit control over which instance handles work-- environments where shorthand auto-routing is too implicit--### `simple-autorestart`--`simple-autorestart` behaves like `simple`, but actively tries to keep a managed instance alive.--Best fit:-- kiosk-style or always-on setups-- local browser service behavior where one managed instance should come back after a crash-- unattended environments--## Allocation Policy--Valid allocation policies on this branch:--- `fcfs`-- `round_robin`-- `random`--### `fcfs`--First suitable instance wins.--Best fit:-- predictable behavior-- simple deployments-- minimal surprise--### `round_robin`--Requests rotate across eligible instances.--Best fit:-- distributing work across a stable set of running instances-- light balancing without randomness--### `random`--Requests pick a random eligible instance.--Best fit:-- spreading work without a fixed order-- experiments or looser balancing behavior--## Example Config--```json-{- "multiInstance": {- "strategy": "explicit",- "allocationPolicy": "round_robin",- "instancePortStart": 9868,- "instancePortEnd": 9968- }-}-```--## Recommended Usage Patterns--### Primary User Path--For the normal “local browser service” workflow:--```json-{- "multiInstance": {- "strategy": "simple",- "allocationPolicy": "fcfs"- }-}-```--This matches:-- install Pinchtab-- run `pinchtab`-- point the client to `http://localhost:9867`--### Explicit Multi-Instance Control--Use:--```json-{- "multiInstance": {- "strategy": "explicit",- "allocationPolicy": "round_robin"- }-}-```--when you want:-- clear instance boundaries-- explicit instance API usage-- predictable multi-instance orchestration--### Self-Healing Single-Service Setup--Use:--```json-{- "multiInstance": {- "strategy": "simple-autorestart",- "allocationPolicy": "fcfs"- }-}-```--when you want one logical browser service that tries to recover automatically.--## Decision Rule--Use this rule:--```text-simple = easiest default-explicit = most control-simple-autorestart = single-service resilience--fcfs = most predictable-round_robin = balanced rotation-random = loose distribution-```--## Important Boundary--These settings are expert-level because they change control-plane behavior.--They are not required for the primary Pinchtab experience.-Most users should stay on:--- `strategy = simple`-- `allocationPolicy = fcfs`diff --git a/docs/guides/headed-mode-guide.md b/docs/guides/headed-mode-guide.mddeleted file mode 100644index 29142d23..00000000--- a/docs/guides/headed-mode-guide.md+++ /dev/null@@ -1,441 +0,0 @@-# Headed Mode--Most browser automation assumes you're either fully automated or fully manual. Real workflows aren't like that.--Your agent can fill out a 50-field form in seconds, but it can't solve a CAPTCHA. It can navigate to the right page, but it can't approve a bank transfer. It can scrape a dashboard, but first someone needs to log in with 2FA.--That's what headed mode is for.--## The Problem with Headless-Only--Headless browsers are great until they aren't. The moment you hit any of these, you're stuck:--- **Login walls** — OAuth flows, 2FA, SMS codes-- **CAPTCHAs** — reCAPTCHA, hCaptcha, Cloudflare challenges-- **Visual verification** — "does this look right?" before submitting-- **Sensitive actions** — payments, deletions, things you want a human to approve--The usual workaround? Copy cookies from a real browser, hope they don't expire, pray the session doesn't get flagged. Fragile, annoying, doesn't scale.--## How Pinchtab Solves It--Pinchtab's headed mode gives you a real Chrome window that both humans and agents share. Same browser, same session, same cookies. No hacks.--The flow is simple:--1. **Human** opens a profile, logs in, handles 2FA-2. **Agent** takes over via HTTP API — same browser, same session-3. **Human** can watch, intervene, or take back control at any time--The agent doesn't need screenshots to "see" the page. It reads the accessibility tree — the same structure screen readers use. Structured, fast, cheap on tokens.--## Profiles: Persistent Identity--Each Chrome profile is a complete browser identity — cookies, localStorage, saved passwords, extensions, everything. Pinchtab stores them in `~/.pinchtab/profiles/`.--Profiles persist across restarts. Log in once to Gmail on Monday, and your agent can read email on Friday without re-authenticating.--```bash-# List profiles-curl http://localhost:9867/profiles-```--```json-[- {- "id": "a1b2c3d4e5f6",- "name": "Work",- "accountEmail": "[email protected]",- "accountName": "Your Name",- "useWhen": "Work email and social accounts"- }-]-```--Every profile gets a stable 12-character hex ID derived from its name. Use IDs in automation — they're URL-safe and won't break if you have spaces or special characters in profile names.--## Start and Stop with One Call--The orchestrator API makes profile management trivial for agents:--```bash-# List profiles (get profile ID)-curl http://localhost:9867/profiles | jq '.[] | {id, name}'--# Start a profile instance-curl -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"profileId":"a1b2c3d4e5f6"}'-```--**Response:**-```json-{- "id": "inst_work123",- "profileId": "a1b2c3d4e5f6",- "profileName": "Work",- "port": "9868",- "status": "starting",- "headless": false-}-```--The response tells you the instance ID. All your API calls go through the orchestrator proxy:--```bash-INST="inst_work123"--# Navigate (via orchestrator)-curl -X POST http://localhost:9867/instances/$INST/navigate \- -d '{"url": "https://mail.google.com"}'--# Read the inbox-curl "http://localhost:9867/instances/$INST/snapshot"--# Done — shut it down-curl -X POST http://localhost:9867/instances/$INST/stop-```--You can also specify mode (headed/headless):--```bash-# Start profile in headless mode (faster, no display)-curl -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"profileId":"a1b2c3d4e5f6","mode":"headless"}'--# Start profile in headed mode (visible window, debug)-curl -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"profileId":"a1b2c3d4e5f6","mode":"headed"}'-```--## A Real Example: Reading Email--Here's what a full agent workflow looks like. The human already logged into Gmail through the profile once. Now the agent can check email any time:--```bash-# 1. Get profile ID-PROFILE_ID=$(curl -s http://localhost:9867/profiles \- | jq -r '.[] | select(.name=="Work") | .id')--# 2. Start the profile instance-INST=$(curl -s -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"profileId":"'$PROFILE_ID'"}' | jq -r '.id')--# 3. Wait for instance to initialize-sleep 2--# 4. Navigate to Gmail (uses orchestrator proxy)-curl -s -X POST http://localhost:9867/instances/$INST/navigate \- -d '{"url": "https://mail.google.com"}'--# 5. Read the inbox (accessibility tree, not screenshots)-curl -s "http://localhost:9867/instances/$INST/snapshot" | jq '.nodes[] | select(.role == "row") | .name' | head -5-```--**Output:**-```-"unread, GitHub, [org/repo] New pull request #42, 11:44 AM, ..."-"unread, Stripe, Your January invoice is ready, 11:26 AM, ..."-"unread, AWS, Your EC2 instance is running, 11:15 AM, ..."-```--No screenshots. No vision models. No token-heavy page dumps. Just structured data from the accessibility tree — the same way a screen reader would see it.--```bash-# 6. Clean up-curl -X POST http://localhost:9867/instances/$INST/stop-```--## When to Use Headed vs Headless--| Scenario | Mode | Why |-|---|---|---|-| First login to a service | **Headed** | Human handles 2FA/CAPTCHA |-| Daily email check | Either | Session persists, no login needed |-| Scraping public data | **Headless** | No human interaction needed |-| Filling forms with approval | **Headed** | Human reviews before submit |-| CI/CD automation | **Headless** | No display available |-| Debugging agent behavior | **Headed** | Watch what the agent does |--The key insight: you don't have to choose one mode forever. Start headed when you need human involvement, then switch to headless for routine automation. The profile carries the session either way.--## Dashboard & Control Plane--Running `pinchtab` gives you a web UI at `http://localhost:9867` for managing everything:--- Create and import Chrome profiles (persistent)-- Launch instances (headed or headless) with any profile-- Monitor running instances — status, tabs, logs, Chrome initialization-- View all agents connected to each instance-- Stop instances gracefully-- Real-time activity feed of all operations--The dashboard doesn't run Chrome itself. It's a lightweight orchestrator that manages profile instances as separate processes.--### Instances Tab — Monitor Your Running Browsers----The Instances tab shows all running browser instances:-- **Instance ID & Status** — Unique ID and current state (running/stopped)-- **Port** — Which port this instance is listening on-- **Mode** — headed or headless-- **Start Time** — When the instance launched-- **Controls** — DETAILS button for more info, STOP button to shut down--**Web UI:**-```bash-# Start orchestrator and dashboard-pinchtab--# Open in browser-open http://localhost:9867/dashboard-```--**CLI for agents:**-```bash-# List profiles-pinchtab profiles--# List running instances-pinchtab instances--# Start instance with profile-pinchtab instance launch # Temporary profile-PROFILE_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="Work") | .id')-curl -X POST http://localhost:9867/instances/start \- -d '{"profileId":"'$PROFILE_ID'"}'-```--## Multiple Profiles, Multiple Agents--Nothing stops you from running several profiles at once. Different accounts, different purposes:--```bash-# Get profile IDs-WORK_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="Work") | .id')-PERSONAL_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="Personal") | .id')--# Start Work profile instance (headed for debugging)-WORK_INST=$(curl -s -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"profileId":"'$WORK_ID'","mode":"headed"}' | jq -r '.id')--# Start Personal profile instance (headless for automation)-PERSONAL_INST=$(curl -s -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"profileId":"'$PERSONAL_ID'","mode":"headless"}' | jq -r '.id')--# Start temporary instance (no persistent profile)-RESEARCH_INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')-```--Each gets its own port (auto-allocated), its own Chrome process, its own isolated session. The Profiles tab shows them running with their Chrome windows visible:----When you start a profile in headed mode:-- **Left panel** — Profile details (name, size, account info, status)-- **Right panel** — Live Chrome browser window-- **Status badge** — Shows it's running on port 9868-- **STOP button** — Gracefully shut down the instance--The Chrome window is a real browser — you or your agent can interact with it via the API while watching live. Perfect for debugging agent behavior or letting a human take over when needed.--Agents can work across multiple instances simultaneously:--```bash-# Agent A works on Work profile-curl -X POST http://localhost:9867/instances/$WORK_INST/navigate \- -d '{"url":"https://work.slack.com"}'--# Agent B works on Personal profile at the same time-curl -X POST http://localhost:9867/instances/$PERSONAL_INST/navigate \- -d '{"url":"https://twitter.com"}'--# Agent C uses temporary research instance-curl -X POST http://localhost:9867/instances/$RESEARCH_INST/navigate \- -d '{"url":"https://google.com/search?q=..."}'--# All three isolated, no interference-```-------Headed mode isn't about choosing between humans and agents. It's about letting them work together — each doing what they're best at. Humans handle the messy, contextual, trust-requiring parts. Agents handle the repetitive, fast, scale-requiring parts.--## Monitoring Agents Remotely--Here's where it gets interesting. Your agents are running on a server — a Mac Mini under your desk, a VPS, a home lab box. You're on your laptop, maybe on the couch, maybe in a coffee shop. You want to know what your agents are doing right now.--The dashboard gives you that. Open it in your browser and you get a real-time view of every agent, every profile, every action.--### Setting Up Remote Access--By default, PinchTab only listens on `127.0.0.1` — locked to the machine. To access the orchestrator and dashboard from another device on your network, you can set environment variables or bind to a different address.--**Simple setup (local network only):**-```bash-# Bind to all interfaces (only safe on private network!)-BRIDGE_BIND=0.0.0.0 pinchtab-```--**Secure setup (production):**-```bash-# Bind to all interfaces + require auth token-BRIDGE_BIND=0.0.0.0 BRIDGE_TOKEN=your-secret-token pinchtab-```--Now open `http://<server-ip>:9867/dashboard` from your laptop and you'll see the full dashboard.--With a token, every API call requires it:--```bash-curl http://192.168.1.100:9867/profiles \- -H "Authorization: Bearer your-secret-token"-```--Without the token, requests get a `401` error. No exceptions.--**For production:** Consider running behind a reverse proxy (nginx) with HTTPS instead of exposing the orchestrator directly.--### What You See--The dashboard has several views:--**Instances** (default) — all running instances, their status, port, profile, Chrome mode (headed/headless). Click any instance to see:-- Instance metadata (ID, port, profile, status)-- Open tabs in that instance-- Instance logs (Chrome output, errors)-- Quick actions (navigate, take snapshot, stop)--**Profiles** — all profiles (persistent and temporary), their status, account info. Create new profiles, delete old ones, see which instances are using each profile.--**Agents** — every agent (identified by X-Agent-Id header) and which instance they're connected to. The Activity Feed shows a real-time stream of every navigate, snapshot, and action — filterable by type.--**Settings** — Configure orchestrator behavior, instance defaults, port ranges.--### The Activity Feed--The Activity Feed is the heartbeat of your agent fleet. Every action from every agent across every instance streams in real-time.----The Agents view shows:-- **Left panel** — List of connected agents with their status-- **Right panel** — Real-time activity feed filtered by action type-- **Filters** — Toggle between All, Navigate, Snapshot, and Actions-- **Status codes** — HTTP response codes (200, 404, etc.)-- **Timing** — How long each operation took--Example activity stream:--```-16:17:18 anonymous GET /tabs — 0ms — 200-16:17:18 anonymous GET /stealth/status — 2ms — 200-scraper → POST /navigate (inst_def456) — 31ms-scraper → GET /text (inst_def456) — 89ms-```--Filter by type — just navigations, just snapshots, just actions — to focus on what matters.--This works because the orchestrator collects events from all running instances and streams them to the dashboard via Server-Sent Events (SSE). You get one unified view even when agents are spread across multiple instances on different ports.--### Agent Identification--For agents to show up with a name in the dashboard instead of "anonymous", they just need to pass a header:--```bash-# Via orchestrator proxy-curl -X POST http://localhost:9867/instances/$INST/navigate \- -H "X-Agent-Id: mario" \- -H "Content-Type: application/json" \- -d '{"url": "https://pinchtab.com"}'--# Or directly to instance-curl -X POST http://localhost:9868/navigate \- -H "X-Agent-Id: mario" \- -H "Content-Type: application/json" \- -d '{"url": "https://pinchtab.com"}'-```--That's all it takes. The `X-Agent-Id` header tags every request, and the dashboard tracks it automatically. No registration, no config — just a header.--### Watching Live--Click on any running instance in the Instances tab to see a real-time screencast. The dashboard streams JPEG frames from Chrome's DevTools protocol directly to your browser. You see exactly what the agent sees — every page load, every click, every form fill.--This is useful for:--- **Debugging** — why did the agent click the wrong button? Watch it happen.-- **Trust** — your agent is buying something? Watch it fill in the details before it submits.-- **Fun** — there's something oddly satisfying about watching an AI browse the web.--**Note:** Screencast only works for headed instances (with visible Chrome window). Headless instances don't have a visual display to capture.--The screencast is lightweight — you can configure:-- Frames per second (1-15 FPS)-- Quality (10-80% JPEG compression)-- Max width (scale down for bandwidth)--Default settings use minimal bandwidth for remote monitoring.--### A Typical Remote Monitoring Setup--**On your server:**-```bash-# Start orchestrator, open to network, locked with token-BRIDGE_BIND=0.0.0.0 \-BRIDGE_TOKEN=my-secret-token \-pinchtab &--# Your agents start instances and work as usual-# They just pass X-Agent-Id headers so you can identify them-AGENT_ID=mario ./my-agent.sh-```--**On your laptop, phone, or tablet:**--1. Open `http://<server-ip>:9867/dashboard` in browser-2. Enter token when prompted-3. See all instances, profiles, agents in real-time-4. Click into any **headed** instance → see live screencast-5. Switch to Agents view → see real-time activity feed of all operations--No SSH tunnels. No VPN. No complex setup. Just a browser and a token.--**API calls from agents:**-```bash-# Agents identify themselves with X-Agent-Id header-curl -X POST http://orchestrator:9867/instances/$INST/navigate \- -H "X-Agent-Id: mario" \- -H "Content-Type: application/json" \- -d '{"url": "https://pinchtab.com"}'-```--The dashboard automatically tracks which agent is doing what, where, and when.--## Security--Pinchtab binds to `127.0.0.1` by default — only accessible from the machine it's running on. This is intentional. Your agent runs on the same machine, so it just works. Nobody on your network can reach the dashboard or the API.--If you need remote access, set `BRIDGE_BIND=0.0.0.0` and **always** pair it with `BRIDGE_TOKEN`:--```bash-BRIDGE_BIND=0.0.0.0 BRIDGE_TOKEN=my-secret-token pinchtab-```--Without `BRIDGE_TOKEN`, every request is rejected with `401` — including the dashboard UI itself. There's no "public mode". If you open the bind address, you must set a token. This is by design.--For production setups, consider:--- Running behind a reverse proxy (nginx, Caddy) with HTTPS-- Using a strong, random token (`openssl rand -hex 32`)-- Restricting network access with firewall rules--That's the whole point. 🦀diff --git a/docs/guides/identifying-instances.md b/docs/guides/identifying-instances.mdindex 6def03be..799e697b 100644--- a/docs/guides/identifying-instances.md+++ b/docs/guides/identifying-instances.md@@ -1,114 +1,84 @@-# Chrome Instances+# Identifying Instances-Running multiple Chrome instances? Here's how to tell Pinchtab's apart from your regular browser.+When you run PinchTab alongside your normal browser, the easiest way to distinguish its Chrome processes is to combine three signals:-## 1. Rename the Chrome binary (recommended)+- a dedicated Chrome binary name+- recognizable command-line flags+- the PinchTab dashboard and instance metadata-Copy Chrome to a custom name — changes the actual process name in `ps`, Activity Monitor, Task Manager:+## 1. Use A Distinct Chrome Binary Name++If you copy Chrome or Chromium to a custom filename, that filename appears in process listings.```bash-# macOS+# macOS examplecp "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" /usr/local/bin/pinchtab-chrome--# Linux-cp $(which google-chrome) /usr/local/bin/pinchtab-chrome-chmod +x /usr/local/bin/pinchtab-chrome-```--Then point Pinchtab at it:-```bashCHROME_BIN=/usr/local/bin/pinchtab-chrome pinchtab```-Now `ps aux | grep pinchtab-chrome` instantly identifies the Chrome processes. Name it whatever you want — `ai-agent-chrome`, `bot-chrome`, etc.+Now a process listing such as `ps -axo pid,command | rg pinchtab-chrome` gives you a quick way to spot the browser PinchTab launches.-## 2. Add custom Chrome flags (visible in process)+## 2. Add Recognizable Chrome Flags-```bash-CHROME_FLAGS="--user-agent=Custom-Agent/1.0" pinchtab-```+Extra Chrome flags are configured through `browser.extraFlags` in `config.json`:-Custom flags show up in the full process command line:--```bash-ps aux | grep pinchtab-# Shows Chrome processes with custom flags+```json+{+ "browser": {+ "extraFlags": "--user-agent=PinchTab-Automation/1.0 --disable-dev-shm-usage"+ }+}```-Useful for identifying different agent roles:+Those flags appear in the Chrome command line, which makes process inspection easier:```bash-# Scraper agent (with custom flag)-CHROME_FLAGS="--user-agent=Scraper/1.0" pinchtab &--# Monitor agent (different flag)-BRIDGE_PORT=9868 CHROME_FLAGS="--user-agent=Monitor/1.0" pinchtab &+ps -axo pid,command | rg 'PinchTab-Automation|user-data-dir'```-## 3. Separate profile directory (built-in)+Use this when you want to differentiate roles such as “scraper”, “monitor”, or “debug”.-Each Pinchtab profile gets its own directory under `~/.pinchtab/profiles/<name>/` — completely separate from your real Chrome profile.+## 3. Use Profile Paths As An Identifier-Instance Chrome processes show `--user-data-dir=/.../.pinchtab/profiles/...` in their args.+Each managed profile lives under the configured profile base directory. By default that is the OS-specific PinchTab config directory under `profiles/`.-When you create instances via API, they automatically use isolated profiles.+PinchTab-launched Chrome processes include a `--user-data-dir=...` argument that points at that profile location. That is often the fastest way to confirm that a browser process belongs to PinchTab rather than your personal Chrome profile.-## 4. Identify via Dashboard+## 4. Use The Dashboard For The Most Reliable View-The easiest way: Open the dashboard at `http://localhost:9867/dashboard`+Open the dashboard at:-You'll see:-- Instance IDs (`inst_XXXXXXXX`)-- Which profile each instance uses-- Whether it's headed or headless-- When it was started-- Current status+- `http://localhost:9867/`+- or `http://localhost:9867/dashboard`-## Full example+The dashboard and instance APIs show:-```bash-# Start orchestrator with custom Chrome binary-CHROME_BIN=/usr/local/bin/pinchtab-chrome pinchtab-```+- instance IDs+- profile IDs and profile names+- assigned ports+- headless vs headed mode+- current status-Or for agents/instances with custom Chrome flags:+If you need an API-based view instead of the UI:```bash-# Orchestrator-CHROME_BIN=/usr/local/bin/pinchtab-chrome pinchtab &--# Create instances with identifying info-# View in dashboard: http://localhost:9867/dashboard-curl -X POST http://localhost:9867/instances/launch \- -d '{"mode":"headless"}'--# Instance appears in dashboard with its ID, port, profile info+curl http://localhost:9867/instances```-## Docker--Volume-mount your renamed binary and set the env var:--```dockerfile-FROM alpine:latest--COPY pinchtab-chrome /usr/local/bin/pinchtab-chrome-RUN chmod +x /usr/local/bin/pinchtab-chrome+## Practical Combination-ENV CHROME_BIN=/usr/local/bin/pinchtab-chrome+For most setups, this combination is enough:-EXPOSE 9867+1. point PinchTab to a renamed Chrome binary with `CHROME_BIN`+2. add a recognizable `browser.extraFlags` marker in config+3. verify the profile path or instance ID in the dashboard-CMD ["pinchtab"]-```+## Docker-## Tips+The same approach works in containers:-- **[Chrome for Testing](https://googlechromelabs.github.io/chrome-for-testing/)** provides standalone Chrome binaries — no installer, won't conflict with system Chrome. Ideal for automation setups.-- **`chrome-headless-shell`** from the same source is even smaller — headless-only, perfect for server deployments.-- The orchestrator process is always `pinchtab`, so `pkill -f pinchtab` cleanly shuts down all instances.-- Instance IDs (`inst_XXXXXXXX`) are hash-based and stable — great for identifying instances in logs, dashboards, and monitoring.-- Combine approaches (renamed binary + custom flags + dashboard visibility) for maximum clarity in production.-- The dashboard shows all running instances with their profiles, status, and real-time activity — easiest way to identify what's running.+- use `CHROME_BIN` only if you need to override the bundled browser path+- put identifying flags in `browser.extraFlags`+- inspect the instance list from the API or dashboard rather than relying only on process names inside the containerdiff --git a/docs/guides/images/memory-monitoring-dashboard.jpg b/docs/guides/images/memory-monitoring-dashboard.jpgdeleted file mode 100644index ba90ff42..00000000Binary files a/docs/guides/images/memory-monitoring-dashboard.jpg and /dev/null differdiff --git a/docs/guides/memory-monitoring.md b/docs/guides/memory-monitoring.mdindex aa3376f6..d6df5653 100644--- a/docs/guides/memory-monitoring.md+++ b/docs/guides/memory-monitoring.md@@ -1,51 +1,66 @@# Memory Monitoring Guide-Pinchtab monitors Chrome's memory usage at the OS level, providing accurate real-world memory consumption for each browser instance.+PinchTab exposes memory information for the Chrome processes it launches. The current implementation measures browser memory at the process level and reports browser-wide aggregates for each instance.-+## What PinchTab Measures-## Enabling Memory Metrics+PinchTab walks the Chrome process tree for a running instance:-Memory monitoring is **off by default** to minimize overhead.+1. find the main browser PID+2. enumerate child processes+3. sum RSS memory across the browser and its children+4. count renderer processes-To enable:+This gives you real OS-level memory usage for that instance's Chrome process tree.-1. Open the dashboard at `http://localhost:<port>/dashboard`-2. Go to **Settings** → **📈 Monitoring**-3. Toggle **Tab Memory Metrics** on (marked as experimental)-4. Click **Apply Settings**+## Memory Fields-## How Memory is Calculated+| Field | Meaning |+| --- | --- |+| `memoryMB` | Real RSS memory across the browser process tree |+| `jsHeapUsedMB` | Estimated value derived from `memoryMB` |+| `jsHeapTotalMB` | Estimated value derived from `memoryMB` |+| `renderers` | Number of renderer processes in the browser process tree |+| `documents`, `frames`, `nodes`, `listeners` | Legacy compatibility fields; currently not populated with live DOM counts |-Pinchtab uses a **process tree approach** to measure memory:+Important limitation:-1. **Identify the browser process** — Gets the main Chrome PID from chromedp-2. **Walk the process tree** — Finds all child processes (renderers, GPU, utilities)-3. **Sum RSS memory** — Adds up Resident Set Size across all Chrome processes-4. **Filter renderers** — Counts processes with `--type=renderer` for tab count+- `jsHeapUsedMB` and `jsHeapTotalMB` are estimates, not true per-tab DevTools heap measurements+- `GET /tabs/{id}/metrics` returns the owning browser instance's aggregate memory, not isolated per-tab memory-This approach ensures memory is **isolated per instance** — you only see memory for that specific Chrome profile, not other Chrome windows on your system.+## Instance Metrics-### Memory Fields+For a single running browser:-| Field | Description |-|-------|-------------|-| `memoryMB` | Real OS-level memory (RSS) across all Chrome processes |-| `jsHeapUsedMB` | Estimated JS heap (~40% of memoryMB) |-| `jsHeapTotalMB` | Estimated total heap (~50% of memoryMB) |-| `renderers` | Number of renderer processes (≈ tabs) |+```bash+curl http://localhost:9867/metrics+```-> **Note**: JS heap values are estimates based on typical Chrome memory distribution. For exact JS heap metrics, use Chrome DevTools directly.+Example shape:-## API Endpoints+```json+{+ "metrics": {+ "goHeapAllocMB": 12.5,+ "goHeapSysMB": 24.0,+ "goNumGoroutine": 15+ },+ "memory": {+ "memoryMB": 850.5,+ "jsHeapUsedMB": 340.2,+ "jsHeapTotalMB": 425.25,+ "renderers": 11+ }+}+```-### Per-Tab Metrics+## Per-Tab Metrics-```-GET /tabs/{tabId}/metrics+```bash+curl http://localhost:9867/tabs/<tabId>/metrics```-Returns memory metrics (aggregated, since we can't reliably map tabs to PIDs):+Example shape:```json{@@ -60,83 +75,56 @@ Returns memory metrics (aggregated, since we can't reliably map tabs to PIDs):}```-### Instance Metrics+Treat this as “memory for the browser instance that owns this tab”, not “memory for this tab alone”.-```-GET /metrics-```+## All Running Instances-Returns server metrics and browser memory:+In orchestrator mode:-```json-{- "metrics": {- "goHeapAllocMB": 12.5,- "goHeapSysMB": 24.0,- "goNumGoroutine": 15- },- "memory": {- "memoryMB": 850.5,- "jsHeapUsedMB": 340.2,- "jsHeapTotalMB": 425.25,- "renderers": 11- }-}+```bash+curl http://localhost:9867/instances/metrics```-### All Instances (Orchestrator)+This returns one metrics object per running instance, which is the best API for comparing memory across a fleet.-```-GET /instances/metrics-```+## Dashboard Monitoring-Returns memory metrics for all running instances:+The dashboard consumes monitoring snapshots from:-```json-[- {- "instanceId": "inst_abc123",- "profileName": "MyProfile",- "jsHeapUsedMB": 340.2,- "jsHeapTotalMB": 425.25,- "documents": 0,- "frames": 0,- "nodes": 0,- "listeners": 0- }-]+```bash+curl http://localhost:9867/api/events?memory=1```-## Dashboard Visualization+That stream includes:-When enabled, the Monitoring page shows:+- instance list+- tab list+- per-instance metrics when `memory=1`+- server metrics for the PinchTab process itself-- **Chart**: Solid lines for tab counts (left axis), dashed lines for memory in MB (right axis)-- **Instance List**: Shows memory alongside tab count (e.g., `:9869 · 11 tabs · 1382MB`)-- **Real-time updates**: Data polled every 30 seconds, chart retains ~30 minutes of history+The current SSE monitoring loop updates on a short interval, which is suitable for live dashboard views.-## Performance Considerations+## Troubleshooting-- Memory metrics use [gopsutil](https://github.com/shirou/gopsutil) for OS-level process info-- Minimal overhead: just reads `/proc` (Linux) or uses sysctl (macOS)-- No CDP calls required — works reliably even with many tabs-- 5-second grace period for new instances to stabilize before polling+### Memory Shows `0`-## Troubleshooting+Likely causes:++- Chrome has not started yet+- the instance is stopped+- the browser context is not initialized++### Memory Looks Higher Than Expected-**Memory shows 0**+Remember that `memoryMB` includes:-- Chrome may not have started yet (check instance status)-- Browser context not initialized+- the browser process+- renderer processes+- GPU and utility children if present-**Memory seems too high**+This is usually closer to “what the OS sees” than to a narrow JavaScript heap figure.-- Chrome is known to use significant memory-- Each tab runs in a separate renderer process-- Extensions and DevTools add to memory usage+### Numbers Do Not Match Activity Monitor Or Task Manager Exactly-**Memory doesn't match Activity Monitor/Task Manager**+Different tools report different memory definitions. PinchTab currently reports RSS-based totals for the Chrome process tree it owns.-- Pinchtab shows RSS (Resident Set Size) for Chrome processes-- System tools may show different metrics (virtual memory, shared memory)-- Other Chrome windows are excluded — we only count this instance's process treediff --git a/docs/guides/multi-instance.md b/docs/guides/multi-instance.mdindex 32a5e8d9..2aa7aabd 100644--- a/docs/guides/multi-instance.md+++ b/docs/guides/multi-instance.md@@ -1,771 +1,144 @@# Multi-Instance Workflows-Pinchtab's multi-instance architecture enables running multiple isolated Chrome browsers simultaneously, each with their own cookies, history, profiles, and configurations.+PinchTab can run multiple isolated Chrome instances at the same time. Each running instance has its own browser process, port, tabs, and profile-backed state.-## Getting Started+## Mental Model-### 1. Start the Orchestrator+- a profile is stored browser state on disk+- an instance is a running Chrome process+- one profile can have at most one active managed instance at a time+- tabs belong to an instance, and tab IDs should be treated as opaque values returned by the API++## Start The Orchestrator```bashpinchtab```-The orchestrator runs on **port 9867** and manages all instances.+By default the orchestrator listens on `http://localhost:9867`.-### 2. Create Your First Instance+## Start An Instance-Create a headed instance (visible window) for interactive work:+Use the explicit instance API when you want predictable multi-instance behavior:```bash-curl -X POST http://localhost:9867/instances/launch \+curl -X POST http://localhost:9867/instances/start \-H "Content-Type: application/json" \- -d '{"mode":"headed"}'-```--**Response:**-```json+ -d '{"mode":"headed","port":"9999"}'+# CLI Alternative+pinchtab instance start --mode headed --port 9999+# Response{- "id": "inst_a365262a",- "profileId": "prof_7f3d1e8b",- "profileName": "instance-1672531200",- "port": "9868",+ "id": "inst_0a89a5bb",+ "profileId": "prof_278be873",+ "profileName": "instance-1741410000000",+ "port": "9999","headless": false,- "status": "starting",- "startTime": "2026-03-01T06:30:00Z"+ "status": "starting"}```-The instance gets:-- **Auto-allocated port** (9868, 9869, ...) - unique per instance-- **Hash-based ID** (`inst_XXXXXXXX`) - stable and portable-- **Temporary profile** (auto-generated, deleted on stop)-- **Chrome process** - running independently on its port-- **Lazy initialization** - Chrome starts on first request+Notes:-### 3. Navigate and Interact+- `POST /instances/launch` still exists as a compatibility endpoint, but `POST /instances/start` is the clearer primary form.+- If you omit `profileId`, PinchTab creates a managed instance with an auto-generated profile name.+- Starting an instance is only optional in workflows that use shorthand routes with auto-launch behavior, such as the `simple` strategy. In `explicit`, you should assume you need to start one yourself.-Navigate the instance via the orchestrator (recommended):+## Open A Tab In A Specific Instance```bash-curl -X POST http://localhost:9867/instances/inst_a365262a/tabs/open \+curl -X POST http://localhost:9867/instances/inst_0a89a5bb/tabs/open \-H "Content-Type: application/json" \-d '{"url":"https://pinchtab.com"}'-```--**Response:**-```json+# Response{- "id": "tab_19949f62",+ "tabId": "8f9c7d4e1234567890abcdef12345678","url": "https://pinchtab.com",- "title": "Example Domain"+ "title": "PinchTab"}```-Each navigation automatically creates a new tab. Use the `id` (tabId) for subsequent operations on that specific tab.--**Note:** You can also access the instance directly on its port (9868), but using the orchestrator proxy is recommended for consistency.--### 4. Get Page Content--Retrieve page snapshot using the tab ID:+For follow-up operations, keep using the returned `tabId`:```bash-TAB=$(curl -s -X POST http://localhost:9867/instances/inst_a365262a/tabs/open \- -d '{"url":"https://pinchtab.com"}' | jq -r '.id')--curl http://localhost:9867/tabs/$TAB/snapshot+curl "http://localhost:9867/tabs/<tabId>/snapshot"+curl "http://localhost:9867/tabs/<tabId>/text"+curl "http://localhost:9867/tabs/<tabId>/metrics"```-Or get just the text:+## Reuse A Persistent Profile-```bash-curl http://localhost:9867/tabs/$TAB/text-```--### 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 reuse by the next instance. The temporary profile is automatically deleted.-------## Common Workflows--### Parallel Scraping with Multiple Instances--Create 5 headless instances for concurrent scraping:+List existing profiles first:```bash-#!/bin/bash--URLS=(- "https://pinchtab.com/page1"- "https://pinchtab.com/page2"- "https://pinchtab.com/page3"- "https://pinchtab.com/page4"- "https://pinchtab.com/page5"-)--INSTANCES=()--echo "Creating 5 headless instances..."--# Create instances (in parallel for speed)-for i in {1..5}; do- curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' > /tmp/inst_$i.json &-done-wait--# Parse instance IDs-for i in {1..5}; do- ID=$(jq -r '.id' /tmp/inst_$i.json)- INSTANCES+=("$ID")- echo "Created instance $i: $ID"-done--# Wait for instances to initialize (lazy Chrome start)-sleep 2--echo "Navigating all instances concurrently..."--# Navigate all instances and capture tab IDs-TABS=()-for i in "${!INSTANCES[@]}"; do- ID="${INSTANCES[$i]}"- URL="${URLS[$i]}"-- RESPONSE=$(curl -s -X POST "http://localhost:9867/instances/$ID/tabs/open" \- -H "Content-Type: application/json" \- -d "{\"url\":\"$URL\"}")- TAB_ID=$(echo "$RESPONSE" | jq -r '.id')- TABS+=("$TAB_ID")-done--echo "All pages loaded. Getting snapshots..."--# Get snapshots using tab IDs-for i in "${!TABS[@]}"; do- TAB="${TABS[$i]}"-- curl -s "http://localhost:9867/tabs/$TAB/snapshot" > "snapshot-$i.json" &-done-wait--# Cleanup-echo "Stopping instances..."-for ID in "${INSTANCES[@]}"; do- curl -s -X POST "http://localhost:9867/instances/$ID/stop" &-done-wait--echo "Done! Scraped ${#URLS[@]} pages in parallel."+curl http://localhost:9867/profiles```-**Benefits:**-- 5 headless instances = 5x faster scraping than sequential-- No cookie/history interference between sites-- Each instance gets isolated Chrome process and temporary profile-- Ports automatically allocated (9868-9872) and reused on stop-- All API calls go through orchestrator proxy for consistency--### Mixed Headed/Headless Testing--Test web app with multiple instances in different modes:+Then start an instance for a known profile:```bash-echo "Creating mixed instance setup for testing..."--# Headed instance for interactive debugging-WORK=$(curl -s -X POST http://localhost:9867/instances/launch \+curl -X POST http://localhost:9867/instances/start \-H "Content-Type: application/json" \- -d '{"mode":"headed"}' | jq -r '.id')--# Headless instance for automated testing (faster)-TEST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')--# Another headed instance with persistent profile for state preservation-pinchtab profile create testing-profile-PROFILE_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="testing-profile") | .id')--DEBUG=$(curl -s -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"profileId":"'$PROFILE_ID'","mode":"headed"}' | jq -r '.id')--echo "Dev (headed): $WORK (temporary profile, no persistence)"-echo "Test (headless): $TEST (temporary profile, fast)"-echo "Debug (headed): $DEBUG (persistent profile, state saved)"+ -d '{"profileId":"278be873adeb","mode":"headless"}'+# CLI Alternative+pinchtab instance start --profileId 278be873adeb --mode headless```-You now have three independent instances:-- **dev instance** - Visible window, temporary profile (good for quick testing)-- **test instance** - Headless, temporary profile (best for automated tests, no display overhead)-- **debug instance** - Visible window, persistent profile (login state preserved, can reconnect later)--### Load Distribution with Headless Fleet+Because a profile can have only one active managed instance, starting the same profile again while it is already active returns an error instead of creating a duplicate browser.-Run a fleet of headless instances for high-throughput work:+## Monitor Running Instances```bash-#!/bin/bash--FLEET_SIZE=10-INSTANCES=()--echo "Launching fleet of $FLEET_SIZE headless instances..."--# Create instances in parallel-for i in $(seq 1 $FLEET_SIZE); do- curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' > /tmp/inst_$i.json &-done-wait--# Collect instance IDs-for i in $(seq 1 $FLEET_SIZE); do- ID=$(jq -r '.id' /tmp/inst_$i.json)- INSTANCES+=("$ID")-done--echo "Fleet ready: ${#INSTANCES[@]} instances allocated (ports 9868-907$((9868 + FLEET_SIZE - 1)))"--# Wait for Chrome initialization-sleep 3--echo "Processing 100 tasks with round-robin distribution..."--# Distribute work across instances-TASKS=($(seq 1 100))-INSTANCE_INDEX=0--# Process tasks in parallel (10 at a time)-for TASK in "${TASKS[@]}"; do- # Round-robin: assign task to next instance in rotation- ID="${INSTANCES[$((INSTANCE_INDEX % $FLEET_SIZE))]}"-- # Send task to instance via orchestrator proxy- curl -s -X POST "http://localhost:9867/instances/$ID/tabs/open" \- -H "Content-Type: application/json" \- -d "{\"url\":\"https://api.pinchtab.com?task=$TASK\"}" > /dev/null &-- # Keep 10 requests in flight at a time- if (( (INSTANCE_INDEX + 1) % 10 == 0 )); then- wait- fi-- ((INSTANCE_INDEX++))-done--wait--# Cleanup fleet-echo "Cleaning up fleet..."-for ID in "${INSTANCES[@]}"; do- curl -s -X POST "http://localhost:9867/instances/$ID/stop" > /dev/null &-done-wait--echo "Fleet cleaned up"+curl http://localhost:9867/instances+curl http://localhost:9867/instances/inst_0a89a5bb+curl http://localhost:9867/instances/inst_0a89a5bb/tabs+curl http://localhost:9867/instances/metrics```-**Performance:**-- 10 instances = 10x parallelism (10 concurrent navigations)-- Round-robin distribution = balanced load across fleet-- Each instance isolated = no resource contention-- Easy to scale: increase FLEET_SIZE for more throughput+Useful fields:-**Scaling tips:**-- For 100 instances: Allocate 5-10 GB RAM + adjust ulimits-- Monitor: `curl http://localhost:9867/instances | jq 'length'`-- Cleanup: Remove instances when done to free resources+- `id`: stable instance identifier+- `profileId` and `profileName`: the profile backing that instance+- `port`: the instance's HTTP port+- `headless`: whether Chrome was launched headless+- `status`: usually `starting`, `running`, `stopping`, or `stopped`-### Multi-Agent Coordination--Have multiple agents work on different instances with isolated state:+## Stop An Instance```bash-# Create profiles for each agent (optional but recommended)-pinchtab profile create agent-linkedin-pinchtab profile create agent-twitter-pinchtab profile create agent-news--# Get profile IDs-LINKEDIN_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="agent-linkedin") | .id')-TWITTER_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="agent-twitter") | .id')-NEWS_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="agent-news") | .id')--echo "Starting agents..."--# Agent A: LinkedIn scraper with persistent profile-AGENT_A=$(curl -s -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"profileId":"'$LINKEDIN_ID'","mode":"headless"}' | jq -r '.id')--# Agent B: Twitter monitor with persistent profile-AGENT_B=$(curl -s -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"profileId":"'$TWITTER_ID'","mode":"headless"}' | jq -r '.id')--# Agent C: News aggregator with persistent profile-AGENT_C=$(curl -s -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"profileId":"'$NEWS_ID'","mode":"headless"}' | jq -r '.id')--echo "Agents running:"-echo " LinkedIn agent: $AGENT_A"-echo " Twitter agent: $AGENT_B"-echo " News agent: $AGENT_C"--# Each agent has its own isolated browser with persistent state-# They can run concurrently without any interference-```--**Isolation Benefits:**-- Agent A's LinkedIn login state saved to `agent-linkedin` profile-- Agent B's Twitter cookies never touch Agent A's LinkedIn cookies-- Agent C can run in parallel without affecting others-- State persists: agents can reconnect later and resume work-- Clear audit trail: which agent ran on which instance, when-------## 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 uses **lazy initialization**: it starts when first needed, not at instance creation.--```bash-POST /instances/launch → Instance created immediately- ↓ status: "starting" (orchestrator monitor probes /health)- ↓ First /health probe triggers Chrome initialization (8-20 seconds)- ↓ Chrome starts, TabManager initializes- ↓ Monitor's health check succeeds- ↓ status: "running" (instance ready for requests)-→ Ready for navigation requests-```--**Why lazy init?** Reduces memory overhead for ephemeral instances, initialization happens automatically on first request.--**Wait for ready state:**-```bash-# Create instance-INST=$(curl -s -X POST http://localhost:9867/instances/launch | jq -r '.id')--# Poll until running (Chrome will initialize during health checks)-while [ "$(curl -s http://localhost:9867/instances/$INST | jq -r '.status')" != "running" ]; do- sleep 0.5-done--# Now safe to use-curl -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://pinchtab.com"}'-```--### 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 | jq .-```--**Response:**-```json-[- {- "id": "inst_a365262a",- "profileId": "prof_7f3d1e8b",- "profileName": "instance-1672531200",- "port": "9868",- "headless": false,- "status": "running",- "startTime": "2026-03-01T06:30:00Z"- },- {- "id": "inst_b471d93c",- "profileId": "prof_5e2c7f1a",- "profileName": "instance-1672531205",- "port": "9869",- "headless": true,- "status": "running",- "startTime": "2026-03-01T06:30:05Z"- }-]-```--### Get Specific Instance Info--```bash-# Check status of specific instance-curl http://localhost:9867/instances/inst_a365262a | jq .-+curl -X POST http://localhost:9867/instances/inst_0a89a5bb/stop+# CLI Alternative+pinchtab instance stop inst_0a89a5bb# Response{- "id": "inst_a365262a",- "port": "9868",- "headless": false,- "status": "running",- "startTime": "2026-03-01T06:30:00Z",- "profileName": "instance-1672531200"+ "id": "inst_0a89a5bb",+ "status": "stopped"}```-### Instance Health and Tabs+Stopping the instance frees its port. If the profile is persistent, its browser state remains on disk.-```bash-# Check health and tab count for specific instance-curl http://localhost:9867/instances/inst_a365262a/health+## Port Allocation-# Response+If you do not pass a port, PinchTab allocates one from the configured range:++```json{- "status": "ok",- "tabs": 2+ "multiInstance": {+ "instancePortStart": 9868,+ "instancePortEnd": 9968+ }}--# List tabs in instance-curl http://localhost:9867/instances/inst_a365262a/tabs | jq .-```--### Get Instance Logs--```bash-# View logs for debugging-curl http://localhost:9867/instances/inst_a365262a/logs | head -50-```--### Dashboard Web UI--Open http://localhost:9867 in a browser to see:-- Live instance list (real-time updates)-- Instance status, port, mode, uptime-- Profile information per instance-- Tab count per instance-- Quick actions (view logs, stop instance)-------## Best Practices--### 1. Use Persistent Profiles for Important Sessions--```bash-# For agents that need persistent login state-pinchtab profile create linkedin-scraper--PROFILE_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="linkedin-scraper") | .id')--# Start instance with profile-INST=$(curl -s -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"profileId":"'$PROFILE_ID'","mode":"headless"}' | jq -r '.id')--# Login once, reuse session on next run-```--Persistent profiles preserve cookies, history, login state across restarts.--### 2. Use Ephemeral (Temporary) Profiles for Isolation--```bash-# For one-off tasks, temporary profiles auto-delete on stop-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')--# ... do work ...--# Stop instance -> profile automatically deleted-curl -X POST http://localhost:9867/instances/$INST/stop-```--Temporary profiles are auto-generated and deleted, good for clean slates.--### 3. Wait for Instance Ready Before Using--```bash-# Always poll status before first request-INST=$(curl -s -X POST http://localhost:9867/instances/launch | jq -r '.id')--# Wait for Chrome initialization-while [ "$(curl -s http://localhost:9867/instances/$INST | jq -r '.status')" != "running" ]; do- sleep 0.5-done--# Now safe to navigate-curl -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://pinchtab.com"}'-```--Chrome lazy-initializes on first health check (~8-20 seconds).--### 4. Batch Operations for Performance--```bash-# Create 10 instances in parallel (faster than sequential)-for i in {1..10}; do- curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' > /tmp/inst_$i.json &-done-wait--# Extract IDs-for i in {1..10}; do- jq -r '.id' /tmp/inst_$i.json-done-```--Much faster than sequential instance creation.--### 5. Clean Up Stopped Instances--```bash-# List all instances-curl http://localhost:9867/instances | jq '.[] | {id, status}'--# Stop idle instances to free resources-curl http://localhost:9867/instances | jq -r '.[] | select(.status=="running") | .id' | while read ID; do- curl -s -X POST http://localhost:9867/instances/$ID/stop-done-```--Frees ports and RAM for new instances.--### 6. Route All Requests Through Orchestrator--```bash-# DO: Use orchestrator proxy (recommended)-curl -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://pinchtab.com"}'--# AVOID: Direct port access (less consistent)-curl -X POST http://localhost:$PORT/tabs/open \- -d '{"url":"https://pinchtab.com"}'-```--Orchestrator proxy ensures consistent routing and better monitoring.--### 7. Monitor Resource Usage--```bash-# Check instance count-INST_COUNT=$(curl -s http://localhost:9867/instances | jq 'length')-echo "Running instances: $INST_COUNT"--# Estimate RAM (headless ~80MB, headed ~150MB each)-HEADLESS=$(curl -s http://localhost:9867/instances | jq '[.[] | select(.headless==true)] | length')-HEADED=$(curl -s http://localhost:9867/instances | jq '[.[] | select(.headless==false)] | length')-echo "Headless: $HEADLESS (~$((HEADLESS * 80))MB)"-echo "Headed: $HEADED (~$((HEADED * 150))MB)"-```--Keep an eye on resource usage to avoid exhausting system limits.-------## Architecture--```-Orchestrator (port 9867)-├─ Instance manager: lifecycle (create, monitor, stop)-├─ Profile manager: persistent browser state directories-├─ Port allocator: assigns ports 9868-9968-└─ Dashboard UI: monitor instances, create/stop via web--Instance 1 (port 9868, temp profile)-├─ Bridge: HTTP API for this instance only-├─ Chrome: independent browser process (lazy-init)-├─ Profile: temporary, deleted on stop-└─ Tabs: multiple tabs in same browser--Instance 2 (port 9869, profile=work)-├─ Bridge: HTTP API for this instance only-├─ Chrome: independent browser process (lazy-init)-├─ Profile: persistent (work), survives restarts-└─ Tabs: multiple tabs in same browser--Instance 3 (port 9870, profile=linkedin)-├─ Bridge: HTTP API for this instance only-├─ Chrome: independent browser process (lazy-init)-├─ Profile: persistent (linkedin), survives restarts-└─ Tabs: multiple tabs in same browser-```--Each instance is **completely isolated**:-- **Separate port** (9868-9968, auto-allocated)-- **Separate Chrome process** (independent browser, no cross-contamination)-- **Separate profile** (cookies, history, cache all isolated)-- **Separate HTTP API** (Bridge server on instance port)--**Orchestrator forwards requests** from `9867/instances/{id}/*` to the appropriate instance port for clean routing.-------## Troubleshooting--### Instance Not Starting (Status: "error")--```bash-# Check instance error details-curl http://localhost:9867/instances/$INST | jq '.error'--# Get full logs-curl http://localhost:9867/instances/$INST/logs--# Common issues:-# - "Chrome binary not found" → Set CHROME_BIN env var-# - "Port already in use" → Change INSTANCE_PORT_START/END-# - "process exited early" → Check logs for Chrome crash reason-```--### Instance Stuck in "starting"--```bash-# Wait longer (Chrome init takes 8-20 seconds)-sleep 10--# Check status again-curl http://localhost:9867/instances/$INST | jq '.status'--# If still "starting" after 30s, likely Chrome init failed-# Check logs:-curl http://localhost:9867/instances/$INST/logs | tail -20```-### Chrome Window Not Visible (Headed Mode)+When an instance stops, its port becomes available for reuse.-```bash-# On Linux, ensure DISPLAY is set-echo $DISPLAY # Should show :0 or :1, etc.--# If not set, enable X11 forwarding-export DISPLAY=:0--# For SSH access, use X11 forwarding-ssh -X user@server-pinchtab instance launch --mode headed-```--### Port Conflicts--```bash-# Check which ports are in use-lsof -i :9868 # Check specific port-netstat -tlnp | grep 986 # Check range--# If port conflict, change instance port range-export INSTANCE_PORT_START=10000-export INSTANCE_PORT_END=10100-pinchtab--# Or specify port for specific instance-curl -X POST http://localhost:9867/instances/launch \- -d '{"mode":"headless","port":"10000"}'-```--### Chrome Binary Not Found--```bash-# Check if Chrome is installed-which google-chrome-which chromium-which chromium-browser+## When To Use Explicit Multi-Instance APIs-# If not found, install Chrome/Chromium+Prefer explicit instance APIs when:-# Or set explicit path-export CHROME_BIN=/path/to/chrome-pinchtab-```--### Memory Usage Growing--```bash-# Monitor instance count and resource usage-curl http://localhost:9867/instances | jq 'length'--# Estimate RAM per instance-# Headless: ~80 MB each-# Headed: ~150 MB each--# Stop old instances to free memory-curl -X POST http://localhost:9867/instances/$OLD_INST/stop+- multiple browser sessions must stay isolated+- you want separate headed and headless browsers at the same time+- you need stable profile-to-instance ownership rules+- you are building tooling that should never depend on implicit auto-launch-# For limits, set systemd cgroup or Docker memory limit-# docker run --memory=8g pinchtab-```--### Can't Access Instance After Stop/Start--```bash-# Instance IDs are stable, but ports change on restart-# Always use orchestrator proxy:-curl http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://pinchtab.com"}'--# Don't rely on cached port numbers-PORT=$(curl http://localhost:9867/instances/$INST | jq -r '.port')-```diff --git a/docs/guides/raspberry-pi.md b/docs/guides/raspberry-pi.mdindex a701d285..a45d8d23 100644--- a/docs/guides/raspberry-pi.md+++ b/docs/guides/raspberry-pi.md@@ -1,420 +1,194 @@# Raspberry Pi Setup Guide-Pinchtab works great on Raspberry Pi (3, 4, 5, Zero 2 W) for browser automation, web scraping, testing, and headless browsing. This guide covers installation, optimization, and common issues.+PinchTab runs on Raspberry Pi as long as Chromium or Chrome is available. The current implementation does not need Pi-specific feature flags, but it does benefit from conservative defaults because memory is limited.-## Requirements+## Recommended Baseline-- **Raspberry Pi**: Pi 3, 4, 5, or Zero 2 W (ARM64/aarch64)-- **OS**: Raspberry Pi OS (64-bit recommended) or Ubuntu-- **RAM**: 2GB+ recommended (1GB works for headless with low tab counts)-- **Node.js**: 18+ (install via [nvm](https://github.com/nvm-sh/nvm) recommended)-- **Chrome/Chromium**: Required (not bundled with pinchtab)+- Raspberry Pi OS or Ubuntu on ARM64+- 64-bit userspace if possible+- Chromium installed locally+- headless mode by default+- low tab counts on smaller boards-## Installation+## Install Chromium-### Step 1: Install Chrome/Chromium--Pinchtab requires Chrome or Chromium. Install it first:+On Raspberry Pi OS:```bashsudo apt updatesudo apt install -y chromium-browser```-Verify installation:-```bash-which chromium-browser-# Should output: /usr/bin/chromium-browser-```--> **ARM64 Optimization**: Pinchtab automatically detects ARM64/ARM architecture and prioritizes `chromium-browser` for optimal Raspberry Pi compatibility. No manual configuration needed!--### Step 2: Install Node.js--**Option A: Via nvm (recommended)**-```bash-curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash-source ~/.bashrc # or ~/.zshrc-nvm install 22-nvm use 22-```--**Option B: Via apt** (usually outdated, not recommended)-```bash-sudo apt install -y nodejs npm-```--Verify:-```bash-node -v # Should be 18+-npm -v-```--### Step 3: Install Pinchtab--```bash-curl -fsSL https://pinchtab.com/install.sh | bash-```--Or manually via npm:-```bash-npm install -g pinchtab-```--### Step 4: Start Pinchtab+Verify the binary:```bash-pinchtab+which chromium-browser+which chromium```-First startup takes ~5-10 seconds as Chrome initializes. You should see:-```-INFO starting chrome initialization headless=true-INFO chrome initialized successfully-INFO Bridge server listening addr=127.0.0.1:9867-```+If auto-detection misses it, set:-Test it:```bash-curl http://localhost:9867/health+CHROME_BIN=/usr/bin/chromium-browser pinchtab```-## Configuration for Raspberry Pi--### Headless Mode (Default)+## Install PinchTab-By default, pinchtab runs Chrome in headless mode (no GUI), which is perfect for Pi:+Use your normal PinchTab install path for the platform, or build the binary from this repository:```bash-pinchtab # Headless by default+go build -o pinchtab ./cmd/pinchtab```-### Headed Mode (with Desktop)--If you're running Raspberry Pi OS with desktop and want to see the browser:+Then start it:```bash-BRIDGE_HEADLESS=false pinchtab+./pinchtab```-### Memory Optimization+## Pi-Friendly Config-Raspberry Pi has limited RAM. Optimize pinchtab for lower memory usage:+Create a config file and keep most settings there instead of relying on old environment variables.-**Limit max tabs:**-```bash-BRIDGE_MAX_TABS=5 pinchtab-```+Example:-**Disable images (saves bandwidth + memory):**-```bash-BRIDGE_BLOCK_IMAGES=true pinchtab+```json+{+ "browser": {+ "binary": "/usr/bin/chromium-browser",+ "extraFlags": "--disable-gpu --disable-dev-shm-usage"+ },+ "instanceDefaults": {+ "mode": "headless",+ "maxTabs": 5,+ "blockImages": true,+ "blockAds": true+ },+ "profiles": {+ "baseDir": "/home/pi/.config/pinchtab/profiles",+ "defaultProfile": "default"+ }+}```-**Block ads (saves bandwidth):**-```bash-BRIDGE_BLOCK_ADS=true pinchtab-```+Run with it:-**Combined example:**```bash-BRIDGE_MAX_TABS=5 BRIDGE_BLOCK_IMAGES=true BRIDGE_BLOCK_ADS=true pinchtab+PINCHTAB_CONFIG=/home/pi/.config/pinchtab/config.json ./pinchtab```-### Storage Location--On Pi, you might want to use a USB drive or external storage for the Chrome profile:+## Headless Vs Headed-```bash-BRIDGE_PROFILE=/mnt/usb/pinchtab-profile pinchtab-```+For most Raspberry Pi workloads, keep the default:-Or create a persistent config:-```bash-mkdir -p ~/.config/pinchtab-cat > ~/.config/pinchtab/config.json <<EOF+```json{- "port": "9867",- "headless": true,- "maxTabs": 5,- "profileDir": "/mnt/usb/pinchtab-profile"+ "instanceDefaults": {+ "mode": "headless"+ }}-EOF-```--## Performance Tips--### 1. Use Headless Mode--Headless mode uses significantly less RAM than headed:-```bash-# Default is headless=true, but you can be explicit:-BRIDGE_HEADLESS=true pinchtab```-### 2. Reduce Chrome Flags+If you are using a desktop session and want a visible browser, switch to:-Add lighter-weight Chrome flags:-```bash-CHROME_FLAGS="--disable-gpu --disable-software-rasterizer --disable-dev-shm-usage" pinchtab+```json+{+ "instanceDefaults": {+ "mode": "headed"+ }+}```-### 3. Swap Space (for 1GB Pi models)--If you have only 1GB RAM, increase swap:-```bash-sudo dphys-swapfile swapoff-sudo nano /etc/dphys-swapfile-# Change CONF_SWAPSIZE=100 to CONF_SWAPSIZE=1024-sudo dphys-swapfile setup-sudo dphys-swapfile swapon-```+Headed mode costs more RAM and is usually best kept for debugging.-### 4. Overclock (Carefully)+## Storage-For Pi 4/5, mild overclocking can improve performance:-```bash-sudo raspi-config-# Performance Options → Overclock → Moderate-```+If the SD card is small or slow, move profile storage to a larger drive:-⚠️ **Ensure adequate cooling** — use a heatsink or fan.--### 5. Use Lightweight OS--Consider **Raspberry Pi OS Lite** (no desktop) for dedicated automation:-```bash-# Install minimal OS, then:-sudo apt install -y chromium-browser nodejs npm-npm install -g pinchtab+```json+{+ "profiles": {+ "baseDir": "/mnt/usb/pinchtab-profiles",+ "defaultProfile": "default"+ },+ "server": {+ "stateDir": "/mnt/usb/pinchtab-state"+ }+}```-## Running as a Service+This is the current supported way to relocate data. Keep using the nested config keys rather than older flat config files.-Run pinchtab automatically on boot using systemd:+## Running As A Service-### Create service file:-```bash-sudo nano /etc/systemd/system/pinchtab.service-```+Example `systemd` unit:-**Content:**```ini[Unit]-Description=Pinchtab Browser Automation+Description=PinchTab Browser ServiceAfter=network.target[Service]Type=simpleUser=piWorkingDirectory=/home/pi-ExecStart=/home/pi/.nvm/versions/node/v22.13.0/bin/pinchtab+ExecStart=/home/pi/pinchtab+Environment=PINCHTAB_CONFIG=/home/pi/.config/pinchtab/config.json+Environment=CHROME_BIN=/usr/bin/chromium-browserRestart=alwaysRestartSec=10-Environment="BRIDGE_HEADLESS=true"-Environment="BRIDGE_MAX_TABS=5"-Environment="BRIDGE_BLOCK_IMAGES=true"[Install]WantedBy=multi-user.target```-**Note:** Adjust `ExecStart` path to match your Node.js installation:-```bash-which pinchtab # Use this path in ExecStart-```+Then:-### Enable and start:```bashsudo systemctl daemon-reloadsudo systemctl enable pinchtabsudo systemctl start pinchtab-```--### Check status:-```bashsudo systemctl status pinchtab```-### View logs:-```bash-sudo journalctl -u pinchtab -f-```--## Common Issues--### Issue: "Chrome binary not found"--**Cause:** Chromium not installed.--**Solution:**-```bash-sudo apt install -y chromium-browser-```--If chromium is installed but pinchtab can't find it:-```bash-export CHROME_BIN=/usr/bin/chromium-browser-pinchtab-```--Make it permanent:-```bash-echo 'export CHROME_BIN=/usr/bin/chromium-browser' >> ~/.bashrc-source ~/.bashrc-```--### Issue: Chrome crashes or hangs--**Cause:** Out of memory.--**Solutions:**-1. Reduce max tabs: `BRIDGE_MAX_TABS=3 pinchtab`-2. Block images: `BRIDGE_BLOCK_IMAGES=true pinchtab`-3. Increase swap (see Performance Tips)-4. Close other applications--### Issue: "Address already in use"--**Cause:** Port 9867 is occupied.--**Solution:** Use a different port:-```bash-BRIDGE_PORT=9868 pinchtab-```--### Issue: Slow page loads--**Cause:** Limited bandwidth or CPU.--**Solutions:**-1. Block images/ads: `BRIDGE_BLOCK_IMAGES=true BRIDGE_BLOCK_ADS=true pinchtab`-2. Increase navigation timeout:- ```json- {- "navigateSec": 90- }- ```-3. Use wired Ethernet instead of Wi-Fi--### Issue: npm install fails with EACCES--**Cause:** Permission error.+## Performance Tips-**Solution:** Use nvm (recommended) or fix npm permissions:-```bash-# Option 1: Use nvm (best)-curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash-nvm install 22-npm install -g pinchtab--# Option 2: Fix npm permissions-mkdir ~/.npm-global-npm config set prefix '~/.npm-global'-echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc-source ~/.bashrc-npm install -g pinchtab-```+- keep `instanceDefaults.maxTabs` low on 1 GB and 2 GB boards+- prefer headless mode+- block images and ads for scraping-heavy workloads+- move profiles to faster external storage if the SD card is the bottleneck+- add swap carefully if you are hitting OOM conditions often-## Example Use Cases+## Troubleshooting-### Web Scraping Cron Job+### Chrome Binary Not Found-```bash-#!/bin/bash-# scrape-daily.sh--curl -X POST http://localhost:9867/tabs \- -H "Content-Type: application/json" \- -d '{- "url": "https://pinchtab.com",- "actions": [- {"kind": "wait", "selector": ".content"}- ]- }' | jq -r '.snapshot' > /home/pi/data/snapshot-$(date +%Y%m%d).json-```+Set `CHROME_BIN` explicitly:-Schedule with cron:```bash-crontab -e-# Add:-0 2 * * * /home/pi/scrape-daily.sh+CHROME_BIN=/usr/bin/chromium-browser ./pinchtab```-### Home Automation Dashboard--Render a web dashboard on an HDMI screen:-```bash-BRIDGE_HEADLESS=false pinchtab-curl -X POST http://localhost:9867/tabs \- -H "Content-Type: application/json" \- -d '{- "url": "http://homeassistant.local:8123",- "kiosk": true- }'-```--### Automated Testing--Run Playwright/Puppeteer tests against pinchtab:-```javascript-// test.js-const { chromium } = require('playwright');--(async () => {- const browser = await chromium.connectOverCDP('http://localhost:9867');- const page = await browser.newPage();- await page.goto('https://pinchtab.com');- console.log(await page.title());- await browser.close();-})();-```+### Out Of Memory-## Monitoring+Reduce workload in config:-Check pinchtab health and resource usage:--```bash-# Health check-curl http://localhost:9867/health--# Metrics (if enabled)-curl http://localhost:9867/metrics--# System resources-htop # Install: sudo apt install htop+```json+{+ "instanceDefaults": {+ "maxTabs": 3,+ "blockImages": true,+ "mode": "headless"+ }+}```-## Upgrading--```bash-npm update -g pinchtab-pinchtab --version-```+### Port Already In Use-## Uninstallation+Override the server port:```bash-# Remove pinchtab-npm uninstall -g pinchtab--# Remove Chrome profile data-rm -rf ~/.config/pinchtab+PINCHTAB_PORT=9868 ./pinchtab```-## Further Reading--- [Data Storage Guide](data-storage.md) — Where pinchtab stores files-- [Configuration Reference](../references/configuration.md) — All config options-- [API Reference](../references/api-reference.json) — REST API documentation-- [Memory Monitoring](memory-monitoring.md) — Track memory usage--## Community--- **GitHub**: https://github.com/pinchtab/pinchtab-- **Issues**: https://github.com/pinchtab/pinchtab/issues-- **Discussions**: https://github.com/pinchtab/pinchtab/discussions------**Have a cool Raspberry Pi + Pinchtab project?** Share it in GitHub Discussions!diff --git a/docs/headless-vs-headed.md b/docs/headless-vs-headed.mdindex d1c26285..8f99ecf6 100644--- a/docs/headless-vs-headed.md+++ b/docs/headless-vs-headed.md@@ -1,545 +1,247 @@# Headless vs Headed-PinchTab instances can run Chrome in two modes: **Headless** (no visible UI) and **Headed** (visible window). Understanding the tradeoffs helps you choose the right mode for your workflow.+PinchTab instances can run Chrome in two modes:-**Note:** You run a single orchestrator (`pinchtab`), then create instances with different modes via the API.+- **Headless**: no visible browser window+- **Headed**: visible browser window++You usually run one server with `pinchtab`, then start instances in either mode through the API or CLI.----## Headless Mode (Default)+## Headless mode-Chrome runs **without a visible window**. All interactions happen via the API.+Headless is the default mode for managed instances.```bash-# Start orchestrator (once)-pinchtab--# Terminal 2: Create headless instance (default)-pinchtab instance launch--# Or via curl-curl -X POST http://localhost:9867/instances/launch \+curl -X POST http://localhost:9867/instances/start \-H "Content-Type: application/json" \- -d '{"mode": "headless"}'-+ -d '{"mode":"headless"}'+# CLI Alternative+pinchtab instance start# Response{"id": "inst_0a89a5bb",+ "profileId": "prof_278be873",+ "profileName": "instance-1741400000000000000","port": "9868","headless": true,"status": "starting"}```-### Characteristics+### Good fit for-- ✅ **No UI overhead** — No window rendering, faster operations-- ✅ **Scriptable** — Perfect for automation, CI/CD, unattended workflows-- ✅ **Lightweight** — Lower CPU/memory than headed mode-- ✅ **Remote-friendly** — Works over SSH, Docker, cloud servers-- ❌ **Can't see what's happening** — Debugging requires screenshots or logs+- agents and automation+- CI and batch jobs+- containers and remote servers+- higher-throughput workloads-### Use Cases+### Tradeoffs-- **AI agents** — Automated tasks, form filling, data extraction-- **CI/CD pipelines** — Testing, scraping, report generation-- **Cloud servers** — VPS, Lambda, container orchestration-- **Production workflows** — Long-running tasks, batch processing+- no visible browser window+- debugging usually happens through snapshots, screenshots, text extraction, and logs----## Headed Mode+## Headed mode-Chrome runs **with a visible window** that you can see and interact with.+Headed mode launches a visible Chrome window.```bash-# Start orchestrator (once)-pinchtab--# Terminal 2: Create headed instance-pinchtab instance launch --mode headed--# Or via curl-curl -X POST http://localhost:9867/instances/launch \+curl -X POST http://localhost:9867/instances/start \-H "Content-Type: application/json" \- -d '{"mode": "headed"}'-+ -d '{"mode":"headed"}'+# CLI Alternative+pinchtab instance start --mode headed# Response{"id": "inst_1b9a5dcc",+ "profileId": "prof_278be873",+ "profileName": "instance-1741400000000000001","port": "9869","headless": false,"status": "starting"}```-### Characteristics--- ✅ **Visual feedback** — See exactly what's happening in real-time-- ✅ **Debuggable** — Watch the browser, inspect elements, debug flows-- ✅ **Interactive** — You can click, type, scroll in the window manually-- ✅ **Development-friendly** — Great for testing, debugging, prototyping-- ❌ **Slower** — Window rendering adds latency-- ❌ **Requires a display** — Needs X11/Wayland on Linux, native desktop on macOS/Windows-- ❌ **Resource-heavy** — More CPU/memory for rendering--### Use Cases--- **Development & debugging** — Build and test automation scripts-- **Local testing** — Verify workflows before production-- **Live demonstrations** — Show what your automation is doing-- **Interactive debugging** — Watch and modify behavior in real-time-- **Manual collaboration** — A human watches and guides the automation--### Viewing Headed Instances in the Dashboard--The PinchTab lets you monitor both headless and headed instances:+### Good fit for-+- development+- debugging+- local testing+- visual verification+- human-in-the-loop workflows-When you launch a headed instance:-- **Mode field** shows "headed" (vs "headless")-- **Port** indicates which port the instance is listening on-- **Status** shows "Running" with green badge-- **STOP button** allows graceful shutdown+### Tradeoffs-The dashboard automatically detects the mode and displays the appropriate controls. You can see the real Chrome window alongside the dashboard for visual verification.+- requires a display environment+- usually uses more CPU and memory than headless mode----## Side-by-Side Comparison+## Side-by-side comparison| Aspect | Headless | Headed ||---|---|---|-| **Visibility** | ❌ Invisible | ✅ Visible window |-| **Speed** | ✅ Fast | ❌ Slower (2-3x) |-| **Resource usage** | ✅ Light | ❌ Heavy |-| **Debugging** | ❌ Hard | ✅ Easy |-| **Display required** | ❌ No | ✅ Yes (X11/Wayland/native) |-| **Automation** | ✅ Perfect | ⚠️ Can interact manually |-| **CI/CD** | ✅ Ideal | ❌ Not practical |-| **Development** | ⚠️ Possible | ✅ Recommended |+| Visibility | No window | Visible window |+| Debugging | Snapshot- and log-based | Direct visual feedback |+| Display required | No | Yes |+| CI use | Strong fit | Usually poor fit |+| Local development | Fine | Usually easier |+| Resource usage | Lower | Higher |----## When to Use Headless+## Recommended workflows-**Use headless for:**-- Production automation (scripts, agents, workflows)-- CI/CD pipelines (GitHub Actions, GitLab CI, Jenkins)-- Unattended execution (servers, containers, cloud functions)-- High-throughput tasks (scraping 1000s of pages)-- Cost-sensitive environments (minimize CPU/memory)-- Long-running processes (24/7 automation)+## Development workflow-```bash-# Production: Create headless instance-pinchtab instance launch--# Or multiple headless instances for scale-for i in 1 2 3; do- pinchtab instance launch --mode headless-done--# List all instances-curl http://localhost:9867/instances | jq .-```-------## When to Use Headed--**Use headed for:**-- Local development (debugging scripts)-- Testing automation behavior-- Demonstrating workflows to humans-- Prototyping and experimentation-- Interactive debugging (pause and inspect)-- Manual verification before production+Use a visible browser while you are building and validating the flow:```bash-# Development: Create headed instance with profile-pinchtab profile create dev--# Get profile ID-DEV_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="dev") | .id')--# Start headed instance with profilecurl -X POST http://localhost:9867/instances/start \-H "Content-Type: application/json" \- -d '{"profileId":"'$DEV_ID'","mode":"headed"}'--# Or simpler: start without persistent profile-pinchtab instance launch --mode headed-```-------## Display Requirements--Display requirements apply to **headed instances**, not the orchestrator. The orchestrator can run anywhere and create instances in any mode.--### On macOS-- Native window system — headed instances work out of the box-- ```bash- pinchtab # Orchestrator- # Terminal 2:- pinchtab instance launch --mode headed- ```--### On Linux-- Headless instances: Work anywhere (no display needed)-- Headed instances: Require X11 or Wayland display server-- In a Docker container: Forward `DISPLAY` environment variable-- In a headless server: Use headless mode only-- ```bash- # Orchestrator on remote server (SSH)- ssh user@server 'pinchtab &'-- # Create headed instance via X11 forwarding- ssh -X user@server 'pinchtab instance launch --mode headed'- ```--### On Windows-- Native window system — headed instances work out of the box-- ```bash- pinchtab # Orchestrator- # Terminal 2:- pinchtab instance launch --mode headed- ```--### In Docker (Headless - Recommended)-```dockerfile-# Headless works everywhere, no display needed-FROM pinchtab/pinchtab:latest-CMD ["pinchtab"]-```--Run with:-```bash-docker run -d -p 9867:9867 pinchtab/pinchtab--# Create headless instances in the container-curl -X POST http://localhost:9867/instances/launch \- -d '{"mode":"headless"}'+ -d '{"mode":"headed"}'+# CLI Alternative+pinchtab instance start --mode headed```-### In Docker (Headed - Advanced)-```dockerfile-# Headed requires display forwarding-FROM pinchtab/pinchtab:latest-ENV DISPLAY=:0-CMD ["pinchtab"]-```+When you need persistence, create a profile first:-Run with X11 forwarding:```bash-docker run \- -e DISPLAY=$DISPLAY \- -v /tmp/.X11-unix:/tmp/.X11-unix:rw \- -p 9867:9867 \- pinchtab/pinchtab--# Create headed instances (display forwarded to host)-curl -X POST http://localhost:9867/instances/launch \- -d '{"mode":"headed"}'+curl -X POST http://localhost:9867/profiles \+ -H "Content-Type: application/json" \+ -d '{"name":"dev"}'+# Response+{+ "status": "created",+ "id": "prof_278be873",+ "name": "dev"+}```------## Best Practices--### Development Workflow+Then launch the profile in headed mode:```bash-# Terminal 1: Start orchestrator (once)-pinchtab--# Terminal 2: Create headed instance for debugging-DEV=$(pinchtab instance launch --mode headed | jq -r '.id')--# Terminal 3: Build and test your automation-curl -X POST http://localhost:9867/instances/$DEV/navigate \- -d '{"url":"https://pinchtab.com"}'--# Verify behavior in the visible window while you develop-# ... iterate on your script ...--# When stable, test in headless for production-PROD=$(pinchtab instance launch --mode headless)--# Run full test suite against headless instance-# ... verify all tests pass ...--# Clean up-pinchtab instance stop $DEV-pinchtab instance stop $PROD+curl -X POST http://localhost:9867/instances/start \+ -H "Content-Type: application/json" \+ -d '{"profileId":"prof_278be873","mode":"headed"}'+# CLI Alternative+pinchtab instance start --profileId prof_278be873 --mode headed+# Response+{+ "id": "inst_ea2e747f",+ "profileId": "prof_278be873",+ "profileName": "dev",+ "port": "9868",+ "headless": false,+ "status": "starting"+}```-### CI/CD Pipeline--```yaml-# Always headless in CI-test:- script:- # Start orchestrator- - pinchtab &- - sleep 1 # Wait for orchestrator to be ready-- # Create headless instance- - INST=$(curl -X POST http://localhost:9867/instances/launch | jq -r '.id')- - sleep 2 # Wait for instance to initialize-- # Run tests against headless instance- - npm test-- # Cleanup- - curl -X POST http://localhost:9867/instances/$INST/stop- - pkill pinchtab-```+## Production workflow-### Multi-Instance Setup (Scale)+Use headless mode for repeatable unattended work:```bash-# Terminal 1: Start orchestrator (once)-pinchtab--# Terminal 2: Create multiple headless instances for scalefor i in 1 2 3; do- INST=$(pinchtab instance launch --mode headless | jq -r '.id')- echo "Created headless instance: $INST"+ curl -s -X POST http://localhost:9867/instances/start \+ -H "Content-Type: application/json" \+ -d '{"mode":"headless"}' | jq .+done+# CLI Alternative+for i in 1 2 3; do+ pinchtab instance startdone--# List all instances-curl http://localhost:9867/instances | jq .--# Response: 3 independent headless instances-# [-# {"id": "inst_xxx", "port": "9868", "headless": true, "status": "running"},-# {"id": "inst_yyy", "port": "9869", "headless": true, "status": "running"},-# {"id": "inst_zzz", "port": "9870", "headless": true, "status": "running"}-# ]--# Terminal 3: Route requests to instances via orchestrator-# All operations go through: http://localhost:9867/instances/{id}/...-```--### Multi-Instance with Mixed Modes--```bash-# Terminal 1: Start orchestrator-pinchtab--# Create persistent profiles-pinchtab profile create alice-pinchtab profile create bob-pinchtab profile create dev--# Get profile IDs-ALICE_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="alice") | .id')-BOB_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="bob") | .id')-DEV_ID=$(pinchtab profiles | jq -r '.[] | select(.name=="dev") | .id')--# Production: Multiple headless instances-ALICE_INST=$(curl -X POST http://localhost:9867/instances/start \- -d '{"profileId":"'$ALICE_ID'","mode":"headless"}' | jq -r '.id')--BOB_INST=$(curl -X POST http://localhost:9867/instances/start \- -d '{"profileId":"'$BOB_ID'","mode":"headless"}' | jq -r '.id')--# Development: One headed instance for debugging-DEV_INST=$(curl -X POST http://localhost:9867/instances/start \- -d '{"profileId":"'$DEV_ID'","mode":"headed"}' | jq -r '.id')--# Each instance is isolated with its own profile/cookies```-### Dashboard View of Mixed Instances--In the Profiles tab, you'll see all your instances with their live Chrome windows:----The dashboard displays:-- **Left panel** — Profile metadata (name, size, account, status)-- **Right panel** — Live Chrome window when in headed mode-- **Status badge** — Running instance on specific port-- **Port number** — Where this instance is accessible via API--Each instance is completely isolated — different profiles, different cookies, different Chrome processes, different ports.-------## Performance Tips--### For Headless Instances (Already Optimized)-- Headless is the default and already optimized-- Most operations are fast-- For high-throughput: Create multiple headless instances and load-balance--### For Headed Instances (Optimize for Dev)-- Close unused tabs to reduce rendering load-- Use snapshots instead of screenshots when possible (faster)-- Take screenshots sparingly (they're rendered + encoded, slower)-- Minimize window size (less to render)-- For faster debugging: Use headless for bulk work, headed only for visual debugging--### For Scale-- Use headless instances (no display overhead)-- Create multiple instances (one per worker/agent)-- Load-balance via `/instances` list and round-robin routing-- Monitor instance health via `GET /instances/{id}`-----## Monitoring Instance Activity--The PinchTab dashboard includes an Agents tab that shows all activity happening across your instances in real-time:+## Inspecting a headless instance-+You can debug a headless instance through tab APIs.-The activity feed displays:-- **Timestamp** — When the operation occurred-- **Agent/User** — Which client made the request-- **Method** — GET, POST, etc.-- **Endpoint** — Which API endpoint was called-- **Timing** — How long the operation took-- **Status** — HTTP response code (200, 404, 500, etc.)--Use the activity feed to:-- Monitor what your agents are doing in real-time-- Debug failed operations (check status codes)-- Understand performance (see timing metrics)-- Track all API calls across all instances--Filter by operation type (Navigate, Snapshot, Actions, All) to focus on specific actions.-----+List the instance tabs:-## Troubleshooting--### Headed Instance Not Opening a Window--**Root cause:** Display server not available--**On Linux:**```bash-# Check if DISPLAY is set-echo $DISPLAY--# If empty or :0 unavailable, you need X11 or Wayland-# Fallback to headless: Use --mode headless instead-pinchtab instance launch --mode headless+curl http://localhost:9867/instances/inst_0a89a5bb/tabs | jq .+# Response+[+ {+ "id": "CDP_TARGET_ID",+ "instanceId": "inst_0a89a5bb",+ "url": "https://pinchtab.com",+ "title": "PinchTab"+ }+]```-**On macOS/Windows:**-- Verify Chrome/Chromium is installed-- Verify OS has native display server--### Headed Instance Too Slow--**Solution:** Use headless for production, headed only for development+Then inspect the tab:```bash-# Switch from headed to headless-INST=$(pinchtab instance launch --mode headed)-# ... do some debugging ...-pinchtab instance stop $INST--# Create headless for production testing-INST=$(pinchtab instance launch --mode headless)+curl http://localhost:9867/tabs/CDP_TARGET_ID/snapshot | jq .```-### Headless Instance But Need to Debug--**Solution:** Use API operations to see what's happening+```bash+curl http://localhost:9867/tabs/CDP_TARGET_ID/text | jq .+``````bash-# Get page structure (DOM)-curl http://localhost:9867/instances/$INST/snapshot | jq .+curl http://localhost:9867/tabs/CDP_TARGET_ID/screenshot > page.jpg+```-# Extract all text-curl http://localhost:9867/instances/$INST/text+----# Take screenshot-TAB_ID=$(curl -s http://localhost:9867/instances/$INST/tabs | jq -r '.[0].id')-curl "http://localhost:9867/tabs/$TAB_ID/screenshot" > page.png+## Display requirements-# Get page title and URL-curl http://localhost:9867/instances/$INST/tabs | jq '.[] | {title, url}'-```+Headed instances need a display environment.-### Instance Initialization Slow+### macOS-**Symptom:** Instance stuck in "starting" state+Headed mode works with the native desktop session.-**Solution:** Wait for instance to reach "running" state before making requests+### Linux-```bash-# Check instance status-curl http://localhost:9867/instances/$INST | jq '.status'+Headless works anywhere.+Headed mode needs X11 or Wayland.-# Poll until running (first request initializes Chrome: 5-20 seconds)-while [ "$(curl -s http://localhost:9867/instances/$INST | jq -r '.status')" != "running" ]; do- sleep 0.5-done--# Now safe to use-curl -X POST http://localhost:9867/instances/$INST/navigate \- -d '{"url":"https://pinchtab.com"}'+```bash+ssh -X user@server 'pinchtab instance start --mode headed'```-### Can't Connect to Instance+### Windows-**Symptom:** 503 error when trying to navigate/snapshot+Headed mode works with the native desktop session.-**Causes:**-1. Instance still initializing (check status)-2. Chrome crashed (check logs)-3. Port already in use (specify different port)--**Debug:**-```bash-# Get instance status and error details-curl http://localhost:9867/instances/$INST | jq .+### Docker-# Get instance logs-curl http://localhost:9867/instances/$INST/logs+Headless is the normal choice in containers:-# Check if port is available-lsof -i :9868 # Shows what's using the port+```bash+docker run -d -p 9867:9867 pinchtab/pinchtab+curl -X POST http://localhost:9867/instances/start \+ -H "Content-Type: application/json" \+ -d '{"mode":"headless"}'```----## Summary+## Dashboard-- **Headless instances** = Fast, scriptable, production-ready (no display overhead)-- **Headed instances** = Visible, debuggable, development-friendly (requires display)+The dashboard lets you monitor running instances and profiles while you use either mode.-### Key Points-- Start orchestrator once: `pinchtab`-- Create instances with mode via API: `instance launch --mode headless|headed`-- Profiles are optional but preserve state across mode switches-- You can have both headless and headed instances running simultaneously-- Switch modes by stopping one instance and creating another-- If using profiles, login state and cookies persist across mode switches+Useful views:-### Quick Reference-```bash-# Orchestrator (runs once)-pinchtab+- Monitoring: running instances, status, tabs, and optional memory metrics+- Profiles: saved profiles, launch actions, and live details+- Settings: runtime and dashboard preferences-# Create headless instance (production)-pinchtab instance launch --mode headless+----# Create headed instance (development)-pinchtab instance launch --mode headed+## Summary-# Create with persistent profile (state preserved on mode switch)-pinchtab profile create work-curl -X POST http://localhost:9867/instances/start \- -d '{"profileId":"work-id","mode":"headed"}'-```+- Use **headless** for unattended automation and scale.+- Use **headed** for local debugging and human-visible workflows.+- Choose the mode per instance, not per server.-**Next:** See [Instance API Reference](references/instance-api.md) for complete instance management details.diff --git a/docs/index.json b/docs/index.jsonindex b7a2682d..1b2afa40 100644--- a/docs/index.json+++ b/docs/index.json@@ -1,46 +1,32 @@{"main": [- "overview.md",+ "pinchtab.md",+ "showcase.md",+ "get-started.md","core-concepts.md","headless-vs-headed.md",- "dashboard.md",- "get-started.md"- ],- "references": [- "references/api-structure.md",- "references/endpoints.md",- "references/profile-api.md",- "references/instance-api.md",- "references/tabs-api.md",- "references/cli-quick-reference.md",- "references/configuration.md"- ],- "architecture": [- "architecture/pinchtab-architecture.md",- "architecture/overall-system-chart.md",- "architecture/instance-model-charts.md",- "architecture/managed-bridge-vs-managed-direct-cdp.md",- "architecture/chrome-lifecycle-and-orchestration.md",- "architecture/dashboard-ui.md",- "architecture/building.md"+ "dashboard.md"],"guides": [- "guides/expert-bridge-mode.md",- "guides/expert-attach.md",- "guides/expert-strategies.md",- "guides/headed-mode-guide.md",+ "guides/contributing.md",+ "guides/attach-chrome.md",+ "guides/multi-instance.md","guides/identifying-instances.md",- "guides/agent-optimization.md","guides/memory-monitoring.md","guides/data-storage.md",+ "guides/docker.md","guides/raspberry-pi.md"],- "examples": [- "examples/bridge-smoke-test.md"+ "architecture": [+ "architecture/overview.md",+ "architecture/overall-system-chart.md",+ "architecture/instance-model-charts.md",+ "architecture/managed-bridge-vs-managed-direct-cdp.md",+ "architecture/chrome-lifecycle-and-orchestration.md",+ "architecture/find.md",+ "architecture/scheduler.md"],- "proposals": [- "proposals/default-instance.md",- "proposals/performance-optimization.md",- "proposals/ui-enhancements.md"+ "reference": [+ "*"]}diff --git a/docs/media/dashboard-agents-activity.png b/docs/media/dashboard-agents-activity.pngdeleted file mode 100644index d974e670..00000000Binary files a/docs/media/dashboard-agents-activity.png and /dev/null differdiff --git a/docs/media/dashboard-instances-headed.jpeg b/docs/media/dashboard-instances-headed.jpegnew file mode 100644index 00000000..bb690c7cBinary files /dev/null and b/docs/media/dashboard-instances-headed.jpeg differdiff --git a/docs/media/dashboard-instances-headed.png b/docs/media/dashboard-instances-headed.pngdeleted file mode 100644index b98561b8..00000000Binary files a/docs/media/dashboard-instances-headed.png and /dev/null differdiff --git a/docs/media/dashboard-instances.jpeg b/docs/media/dashboard-instances.jpegnew file mode 100644index 00000000..0e63a31eBinary files /dev/null and b/docs/media/dashboard-instances.jpeg differdiff --git a/docs/media/dashboard-profiles-headed-chrome.jpeg b/docs/media/dashboard-profiles-headed-chrome.jpegnew file mode 100644index 00000000..1dfca696Binary files /dev/null and b/docs/media/dashboard-profiles-headed-chrome.jpeg differdiff --git a/docs/media/dashboard-profiles-headed-chrome.png b/docs/media/dashboard-profiles-headed-chrome.pngdeleted file mode 100644index c6e7cc93..00000000Binary files a/docs/media/dashboard-profiles-headed-chrome.png and /dev/null differdiff --git a/docs/media/dashboard-profiles.jpeg b/docs/media/dashboard-profiles.jpegnew file mode 100644index 00000000..d54a8ee1Binary files /dev/null and b/docs/media/dashboard-profiles.jpeg differdiff --git a/docs/media/dashboard-settings.jpeg b/docs/media/dashboard-settings.jpegnew file mode 100644index 00000000..84b2900cBinary files /dev/null and b/docs/media/dashboard-settings.jpeg differdiff --git a/docs/overview.md b/docs/overview.mddeleted file mode 100644index 36724ffd..00000000--- a/docs/overview.md+++ /dev/null@@ -1,113 +0,0 @@-# PinchTab--Welcome to PinchTab — browser control for AI agents, scripts, and automation workflows.--## What is PinchTab?--PinchTab is a **standalone HTTP server** that gives you direct control over Chrome. Any AI agent can use the CLI or HTTP API.--The main concept to understand first is that PinchTab has two runtime roles:--- `pinchtab` or `pinchtab server` — the full control-plane server-- `pinchtab bridge` — the single-instance bridge runtime--The server is the normal entrypoint. It manages profiles, instances, routing, and the dashboard. The bridge runtime is the lightweight single-instance HTTP wrapper used for managed child instances.--That gives you a simple mental model:-- start the **server**-- create or attach **instances**-- operate on **tabs**--## Primary Usage--For most users, Pinchtab is a local browser service:--1. install Pinchtab-2. run `pinchtab`-3. connect your agent or tool to `http://localhost:9867`-4. use Pinchtab instead of embedding a browser runtime directly in the client--In that model:-- `pinchtab server` is the primary target-- `pinchtab bridge` is an internal or advanced runtime detail--**CLI example:**-```bash-# Navigate-pinchtab nav https://pinchtab.com--# Get interactive elements-pinchtab snap -i -c--# Click element by ref-pinchtab click e5-```--**HTTP example (realistic flow):**-```bash-# 1. Create an instance-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"name":"work","mode":"headless"}' | jq -r '.id')--# 2. Open a tab-TAB=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -H "Content-Type: application/json" \- -d '{"url":"https://pinchtab.com"}' | jq -r '.tabId')--# 3. Get page structure-curl -s "http://localhost:9867/tabs/$TAB/snapshot?filter=interactive" | jq--# 4. Click element using the tabId-curl -s -X POST http://localhost:9867/tabs/$TAB/action \- -H "Content-Type: application/json" \- -d '{"kind":"click","ref":"e5"}'-```-------## Characteristics--- **Server-first** — The default process is the control-plane server, not a raw browser wrapper-- **Bridge-backed instances** — Managed instances run as isolated bridge runtimes behind the server-- **Tab-Centric** — Everything revolves around tabs, not URLs-- **Stateful** — Sessions persist between requests. Log in once, stay logged in across restarts-- **Token Inexpensive** — Text extraction at 800 tokens/page (5-13x cheaper than full snapshots)-- **Flexible Modes** — Launch headed or headless browsers, keep persistent profiles, or attach to external Chrome when allowed-- **Monitoring & Control** — Tab locking for multi-agent safety, stealth mode for bot detection bypass-------## Features--- 🌲 **Accessibility Tree** — Structured DOM with stable refs (e0, e1...) for click, type, read. No coordinate guessing.-- 🎯 **Smart Filters** — `?filter=interactive` returns only buttons, links, inputs. Fewer tokens per snapshot.-- 🕵️ **Stealth Mode** — Patches `navigator.webdriver`, spoofs UA, hides automation flags for bot detection bypass.-- 📝 **Text Extraction** — Readability mode (clean) or raw (full HTML). Choose based on workflow.-- 🖱️ **Direct Actions** — Click, type, fill, press, focus, hover, select, scroll by ref or selector.-- ⚡ **JavaScript Execution** — Run arbitrary JS in any tab. Escape hatch for workflow gaps.-- 📸 **Screenshots** — JPEG output with quality control.-- 📄 **PDF Export** — Full pages to PDF with headers, footers, landscape mode.-- 🎭 **Multi-Tab** — Create, switch, close tabs. Work with multiple pages concurrently.--## Expert Guides--If you are moving beyond the primary server-first workflow, use the expert guides:--- [Bridge Mode](guides/expert-bridge-mode.md) — run the single-instance runtime directly-- [Attach](guides/expert-attach.md) — register externally managed Chrome instances-- [Multi-Instance Strategies](guides/expert-strategies.md) — advanced routing and allocation behavior-------## Support & Community--- **GitHub Issues** — https://github.com/pinchtab/pinchtab/issues-- **Discussions** — https://github.com/pinchtab/pinchtab/discussions-- **Twitter/X** — [@pinchtabdev](https://x.com/pinchtabdev)-------## License--[MIT](https://github.com/pinchtab/pinchtab?tab=MIT-1-ov-file#readme)diff --git a/docs/pinchtab.md b/docs/pinchtab.mdnew file mode 100644index 00000000..4fc2dd9c--- /dev/null+++ b/docs/pinchtab.md@@ -0,0 +1,143 @@+# PinchTab++Welcome to PinchTab: browser control for AI agents, scripts, and automation workflows.++## What PinchTab is++PinchTab is a standalone HTTP server that gives you direct control over Chrome through a CLI and HTTP API.++PinchTab has two runtimes:++- `pinchtab` or `pinchtab server`: the full server+- `pinchtab bridge`: the single-instance bridge runtime++The server is the normal entry point. It manages profiles, instances, routing, security policy, and the dashboard.+The bridge is the lightweight per-instance HTTP runtime used behind managed child instances.++The basic model is:++- start the server+- start or attach instances+- operate on tabs++## Main usage patterns++Start `pinchtab` and leave it running:++- use it as a browser for agents+- use it as a local automation endpoint+- attach an existing debug browser when needed++## Minimal working flow++### 1. Start the server++```bash+pinchtab+```++### 2. Start an instance++```bash+curl -X POST http://localhost:9867/instances/start \+ -H "Content-Type: application/json" \+ -d '{"mode":"headless"}'+# CLI Alternative+pinchtab instance start+# Response+{+ "id": "inst_0a89a5bb",+ "profileId": "prof_278be873",+ "profileName": "instance-1741400000000000000",+ "port": "9868",+ "headless": true,+ "status": "starting"+}+```++### 3. Navigate++```bash+curl -s -X POST http://localhost:9867/navigate \+ -H "Content-Type: application/json" \+ -d '{"url":"https://pinchtab.com"}' | jq .+# CLI Alternative+pinchtab nav https://pinchtab.com+# Response+{+ "tabId": "CDP_TARGET_ID",+ "title": "PinchTab",+ "url": "https://pinchtab.com"+}+```++### 4. Inspect interactive elements++```bash+curl -s "http://localhost:9867/snapshot?filter=interactive" | jq .+# CLI Alternative+pinchtab snap -i -c+# Response+{+ "nodes": [+ { "ref": "e0", "role": "link", "name": "Docs" },+ { "ref": "e1", "role": "button", "name": "Get started" }+ ]+}+```++### 5. Click by ref++```bash+curl -s -X POST http://localhost:9867/action \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","ref":"e1"}' | jq .+# CLI Alternative+pinchtab click e1+# Response+{+ "success": true,+ "result": {+ "clicked": true+ }+}+```++## Characteristics++- Server-first: the main process is the control-plane server+- Bridge-backed instances: managed instances run behind isolated bridge runtimes+- Tab-oriented: interaction happens at the tab level+- Stateful: profiles persist cookies and browser state+- Token-efficient: snapshot and text endpoints are cheaper than screenshot-driven workflows+- Flexible: headless, headed, profile-backed, or attached Chrome+- Controlled: health, metrics, auth, and tab locking are built into the system++## Common features++- Accessibility-tree snapshots with `e0`, `e1`, and similar refs+- Text extraction+- Direct actions such as click, type, fill, press, focus, hover, select, and scroll+- Screenshots and PDF export+- Multi-instance orchestration+- External Chrome attach+- Optional JavaScript evaluation++## Expert guides++When you move beyond the default server-first workflow:++- [Bridge](guides/expert-bridge-mode.md)+- [Attach](guides/expert-attach.md)+- [Multi-Instance Strategies](guides/expert-strategies.md)+- [Architecture](architecture/pinchtab-architecture.md)++## Support++- [GitHub Issues](https://github.com/pinchtab/pinchtab/issues)+- [GitHub Discussions](https://github.com/pinchtab/pinchtab/discussions)+- [@pinchtabdev](https://x.com/pinchtabdev)++## License++[MIT](https://github.com/pinchtab/pinchtab?tab=MIT-1-ov-file#readme)diff --git a/docs/proposals/default-instance.md b/docs/proposals/default-instance.mddeleted file mode 100644index bf4ce87f..00000000--- a/docs/proposals/default-instance.md+++ /dev/null@@ -1,608 +0,0 @@-# Default Instance Pattern: Simplified API Design--**Status:** Design Proposal-**Date:** 2026-03-01-**Purpose:** Support simplified single-instance workflows while maintaining full multi-instance capability-**Related Issue:** [#65 - Single instance mode](https://github.com/pinchtab/pinchtab/issues/65)-------## Overview--The **Default Instance Pattern** provides a simplified REST API for users who only need a single browser instance. Instead of managing multiple instances, users can directly interact with a default instance using clean, intuitive endpoints.--### Use Cases--1. **Simple automation** - Single-user browser automation scripts-2. **Testing frameworks** - Integration with test runners (Playwright-compatible)-3. **Quick scraping** - One-off web scraping tasks-4. **CLI tools** - Command-line utilities that need a browser-5. **Educational** - Learning browser automation without complexity-------## API Structure--### Current Multi-Instance API-```-GET /instances/{id}/status-POST /instances/{id}/navigate-POST /tabs/{tabId}/snapshot-GET /tabs/{tabId}/screenshot-```--### Proposed Default Instance API-```-GET /-POST /start-POST /navigate-GET /snapshot-GET /screenshot-```--This is NOT a replacement, but a **convenience layer** that:-- Routes to an internal default instance-- Manages lifecycle automatically-- Provides cleaner URLs for common use cases-------## Endpoints (Default Instance Mode)--### Lifecycle--**GET /**-```bash-curl http://localhost:9867/--Response:-{- "status": "running|stopped",- "instanceId": "inst_default",- "instanceName": "default",- "browser": "chrome",- "chromeBinary": "/path/to/chrome",- "startTime": "2026-03-01T15:12:34Z",- "uptime": 3600-}-```--**POST /start**-```bash-curl -X POST http://localhost:9867/start \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}'--Response:-{- "status": "starting",- "instanceId": "inst_default",- "port": 9868-}-```--**POST /stop**-```bash-curl -X POST http://localhost:9867/stop--Response:-{- "status": "stopped",- "instanceId": "inst_default"-}-```--### Navigation & Tabs--**GET /tabs**-```bash-curl http://localhost:9867/tabs--Response:-[- {- "id": "tab_abc123",- "title": "Example Domain",- "url": "https://pinchtab.com/",- "active": true- }-]-```--**POST /tabs/open**-```bash-curl -X POST http://localhost:9867/tabs/open \- -H "Content-Type: application/json" \- -d '{"url":"https://pinchtab.com"}'--Response:-{- "id": "tab_abc123",- "title": "Example Domain",- "url": "https://pinchtab.com/"-}-```--**DELETE /tabs/{targetId}**-```bash-curl -X DELETE http://localhost:9867/tabs/tab_abc123--Response:-{- "status": "closed",- "id": "tab_abc123"-}-```--### Navigation--**POST /navigate**-```bash-curl -X POST http://localhost:9867/navigate \- -H "Content-Type: application/json" \- -d '{"url":"https://pinchtab.com"}'--Response:-{- "status": "navigated",- "url": "https://pinchtab.com",- "title": "Example Domain"-}-```--### Browser Operations--**GET /snapshot**-```bash-curl http://localhost:9867/snapshot--Response:-{- "nodes": [...],- "tree": "DOM tree in ARIA format"-}-```--**GET /screenshot**-```bash-curl http://localhost:9867/screenshot \- -o page.png-```--**GET /pdf**-```bash-curl http://localhost:9867/pdf?landscape=true \- -o report.pdf-```--**POST /action** (Unified Action Endpoint)-```bash-curl -X POST http://localhost:9867/action \- -H "Content-Type: application/json" \- -d '{- "action": "click",- "ref": "e5"- }'--# Supported actions:-# - click, type, fill, select, press, hover, drag, resize, focus, scroll-# - wait, evaluate, close, highlight-```--### Advanced Operations--**POST /evaluate**-```bash-curl -X POST http://localhost:9867/evaluate \- -H "Content-Type: application/json" \- -d '{"expression":"document.title"}'--Response:-{- "result": "Example Domain"-}-```--**POST /highlight**-```bash-curl -X POST http://localhost:9867/highlight \- -H "Content-Type: application/json" \- -d '{"ref":"e5"}'-```--**GET /text**-```bash-curl http://localhost:9867/text--Response:-{- "text": "Page text content..."-}-```--**POST /screenshot**-```bash-curl -X POST http://localhost:9867/screenshot \- -H "Content-Type: application/json" \- -d '{"selector":".main"}'-```--**GET /download**-```bash-# Trigger file download (returns filename and size info)-curl http://localhost:9867/download--Response:-{- "filename": "document.pdf",- "size": 1024000,- "ready": true-}-```-------## Implementation Strategy--### Phase 1: Route Handling-Add routes that map to default instance:--```go-// In orchestrator/handlers.go or dashboard/cmd_dashboard.go--// Health/status-mux.HandleFunc("GET /", handleDefaultStatus)-mux.HandleFunc("POST /start", handleDefaultStart)-mux.HandleFunc("POST /stop", handleDefaultStop)--// Tabs-mux.HandleFunc("GET /tabs", handleDefaultListTabs)-mux.HandleFunc("POST /tabs/open", handleDefaultOpenTab)-mux.HandleFunc("DELETE /tabs/{targetId}", handleDefaultCloseTab)--// Operations-mux.HandleFunc("POST /navigate", handleDefaultNavigate)-mux.HandleFunc("GET /snapshot", handleDefaultSnapshot)-mux.HandleFunc("GET /screenshot", handleDefaultScreenshot)-mux.HandleFunc("GET /pdf", handleDefaultPDF)-mux.HandleFunc("POST /action", handleDefaultAction)-mux.HandleFunc("GET /text", handleDefaultText)-// ... etc-```--### Phase 2: Default Instance Manager-Create a helper to manage the default instance:--```go-type DefaultInstanceManager struct {- orchestrator *Orchestrator- instanceId string // Always "inst_default"- mu sync.RWMutex-}--func (m *DefaultInstanceManager) Start(mode string) error-func (m *DefaultInstanceManager) Stop() error-func (m *DefaultInstanceManager) Status() InstanceStatus-func (m *DefaultInstanceManager) GetTabId() (string, error) // Returns active tab-func (m *DefaultInstanceManager) EnsureRunning() error-```--### Phase 3: Handler Implementation-Each handler resolves to orchestrator calls:--```go-func handleDefaultSnapshot(w http.ResponseWriter, r *http.Request) {- mgr := getDefaultInstanceManager()- tabId, err := mgr.GetTabId()- if err != nil {- web.Error(w, 503, err)- return- }-- // Route to: GET /tabs/{tabId}/snapshot- o.handleTabSnapshot(w, r, tabId)-}-```--### Phase 4: Backward Compatibility-- Default instance routes coexist with multi-instance routes-- No changes to existing `/instances/{id}/*` routes-- Users can still use full orchestrator API if they want--### Phase 5: Helm/Docker Configuration-Add flag to enable/disable default instance:--```bash-# Docker-docker run -e PINCHTAB_DEFAULT_INSTANCE=1 pinchtab:latest--# CLI-pinchtab --default-instance-```-------## Architecture Diagram--```-Client (simplified API)- ↓-GET /-POST /navigate-GET /snapshot-POST /action- ↓-Default Instance Manager- ↓-Orchestrator (internal routing)- ↓-GET /tabs/{defaultTabId}/snapshot-POST /tabs/{defaultTabId}/action- ↓-Instance Bridge (port 9868)- ↓-Chrome-```-------## Relationship to Issue #65--**Issue #65** likely requests a simpler, more direct API for users who don't need multi-instance complexity.--### How This Design Satisfies It--| Requirement | Solution |-|---|---|-| Single instance mode | Default instance pattern |-| Simplified URLs | No instance ID in path |-| Less configuration | Auto-manages default instance |-| Familiar API | Similar to Playwright/Puppeteer |-| Optional | Can disable, use full API instead |--### Example Workflow (Issue #65)--Before (multi-instance):-```bash-# Create instance-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -d '{"mode":"headless"}' | jq -r '.id')-sleep 2--# Navigate-TAB=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://pinchtab.com"}' | jq -r '.id')--# Snapshot-curl http://localhost:9867/tabs/$TAB/snapshot-```--After (default instance):-```bash-# Start default instance-curl -X POST http://localhost:9867/start--# Navigate-curl -X POST http://localhost:9867/navigate \- -d '{"url":"https://pinchtab.com"}'--# Snapshot-curl http://localhost:9867/snapshot-```--Much simpler! ✨-------## Testing Strategy--### Unit Tests-- `DefaultInstanceManager` lifecycle management-- Route handlers for error conditions-- Tab ID resolution--### Integration Tests-```go-func TestDefaultInstanceWorkflow(t *testing.T) {- // Start default instance- // Navigate- // Snapshot- // Stop- // Verify state-}-```--### Compatibility Tests-- Multi-instance and default instance can coexist-- Switching between modes works-- No cross-contamination-------## Deployment Considerations--### Backward Compatibility-✅ No breaking changes to existing API-✅ Opt-in feature (can be disabled)-✅ Existing orchestrator routes unchanged--### Configuration-```yaml-# config.yaml-default_instance:- enabled: true- auto_start: false # Or true if always-on- mode: headless # Or headed- lazy_chrome: true-```--### Monitoring-- Track default instance usage-- Log lifecycle events-- Metrics: uptime, memory, operations/sec-------## Future Extensions--### Multiple Named Instances-```bash-GET /instances/production-GET /instances/staging-POST /instances/testing/navigate-```--### Session Persistence-```bash-POST /save-session-GET /restore-session-```--### Headless vs Headed-```bash-POST /start?headed=true-```-------## Migration Path--### Step 1 (Now)-- Implement default instance handlers-- Route to existing orchestrator-- Document API--### Step 2 (Next)-- Add Playwright adapter-- Support `@playwright/test`-- Test compatibility--### Step 3 (Future)-- Docker image with default instance-- CLI preset for single-instance mode-- Web UI for default instance-------## Example Usage Patterns--### Shell Script-```bash-#!/bin/bash-curl -X POST http://localhost:9867/start-curl -X POST http://localhost:9867/navigate -d '{"url":"https://pinchtab.com"}'-curl http://localhost:9867/snapshot | jq '.nodes'-curl -X POST http://localhost:9867/stop-```--### Python-```python-import requests--BASE = "http://localhost:9867"--# Start-requests.post(f"{BASE}/start", json={"mode": "headless"})--# Navigate-requests.post(f"{BASE}/navigate", json={"url": "https://pinchtab.com"})--# Snapshot-snap = requests.get(f"{BASE}/snapshot").json()-print(snap["nodes"])--# Stop-requests.post(f"{BASE}/stop")-```--### JavaScript-```javascript-const BASE = "http://localhost:9867";--async function automate() {- // Start- await fetch(`${BASE}/start`, {- method: "POST",- body: JSON.stringify({ mode: "headless" })- });-- // Navigate- await fetch(`${BASE}/navigate`, {- method: "POST",- body: JSON.stringify({ url: "https://pinchtab.com" })- });-- // Snapshot- const snap = await fetch(`${BASE}/snapshot`).then(r => r.json());- console.log(snap.nodes);-- // Stop- await fetch(`${BASE}/stop`, { method: "POST" });-}--automate();-```-------## Success Criteria--- ✅ All default instance endpoints work-- ✅ Routes correctly proxy to orchestrator-- ✅ Multi-instance mode still works-- ✅ Documentation covers both patterns-- ✅ Tests for default instance workflows-- ✅ No performance degradation-- ✅ Users prefer it for single-instance tasks-------## Questions & Decisions--**Q1: Should default instance be always running?**-- **A:** Optional. Can auto-start or lazy-init on first request.--**Q2: What happens to multi-instance during default-instance use?**-- **A:** Fully supported. Can launch other instances independently.--**Q3: Can you switch between default and multi-instance APIs?**-- **A:** Yes. Both work simultaneously on the same server.--**Q4: Is default instance a "first tab only" concept?**-- **A:** Initially yes (for simplicity). Can expand to multi-tab later.--**Q5: How does this relate to profiles?**-- **A:** Default instance uses default profile (or specified profile).-------## Conclusion--The **Default Instance Pattern** provides:--1. **Simplicity** - Clean API for single-instance use cases-2. **Compatibility** - Doesn't break multi-instance system-3. **Flexibility** - Can opt-in or opt-out-4. **Familiarity** - Similar to Playwright/Puppeteer-5. **Migration path** - Route to full orchestrator when needed--This design **satisfies issue #65** as a particular case of the multi-instance/profile system, where the "special case" is using a single default instance without explicit instance management.-------## Implementation Checklist--- [ ] Design review (this doc)-- [ ] Create DefaultInstanceManager-- [ ] Implement lifecycle handlers (/start, /stop, /)-- [ ] Implement tab handlers (/tabs, /tabs/open)-- [ ] Implement operation handlers (/navigate, /snapshot, /action)-- [ ] Integration tests-- [ ] Documentation-- [ ] Example scripts-- [ ] Docker image-- [ ] Release notes-------**Next Step:** Review this design, gather feedback, then implement Phase 1 (route handling).diff --git a/docs/proposals/performance-optimization.md b/docs/proposals/performance-optimization.mddeleted file mode 100644index 14e040b4..00000000--- a/docs/proposals/performance-optimization.md+++ /dev/null@@ -1,287 +0,0 @@-# Optimization & Scaling--## Overview--Pinchtab multi-instance architecture is production-ready. Phase 7 focuses on optimizing performance, establishing baseline metrics, and validating system behavior under high load.--## Goals--- Establish performance baselines (latency, memory, throughput)-- Optimize critical paths (connection pooling, caching, batch operations)-- Validate scalability (100+ concurrent instances)-- Document resource requirements and limits-------## Section 1: Benchmarking & Metrics--### Objectives--Capture baseline performance metrics across single and multi-instance scenarios.--### Tasks--#### 1.1 Request Latency Baseline--- [ ] **Measure endpoint latency (p50, p95, p99)**- - `/navigate` - first request (Chrome init) vs subsequent- - `/snapshot` - element retrieval time- - `/actions` (click, type, etc.) - per action cost- - `/tabs` aggregate - response time with N instances--- [ ] **Tools & Methods**- - Use `ab` (Apache Bench) for load testing- - Use `vegeta` (Go HTTP load testing) for sustained load- - Capture detailed timing with custom harness- - Document environment: CPU, RAM, disk speed--- [ ] **Acceptance Criteria**- - Single instance: `/navigate` < 2s (first request)- - Single instance: `/navigate` < 200ms (subsequent)- - 10 instances: `/tabs` aggregate < 500ms- - All operations p99 < 5s--#### 1.2 Memory per Instance--- [ ] **Measure baseline memory footprint**- - Idle Chrome process (headless)- - Idle Chrome process (headed)- - Memory after 10 navigations- - Memory after 100 navigations- - Memory leak detection over 1 hour--- [ ] **Tools & Methods**- - Use `pmap` or `/proc/[pid]/status` on Linux- - Use `Instruments.app` or `Activity Monitor` on macOS- - Track RSS (resident set size) and VSZ (virtual size)- - Profile heap with `pprof`--- [ ] **Acceptance Criteria**- - Idle instance: < 150 MB RSS- - 10 instances: < 2 GB total RSS- - No memory growth > 5 MB/hour idle- - No memory growth > 20 MB/100 navigations--#### 1.3 Concurrent Instance Limits--- [ ] **Identify breaking points**- - How many instances can run concurrently? (CPU bound? File descriptor bound? Memory?)- - How many concurrent requests per instance?- - Orchestrator overhead as instance count grows--- [ ] **Tools & Methods**- - Create instances in loop, monitor system metrics- - Run concurrent navigation requests across instances- - Use `ulimit` and `/proc/sys/fs/file-max` to check limits- - Profile orchestrator CPU usage--- [ ] **Acceptance Criteria**- - 100 instances should be sustainable with 16GB RAM- - Orchestrator should handle 1000 concurrent requests- - Port allocation should handle allocation/release in < 10ms- - No file descriptor leaks (connections cleaned up properly)-------## Section 2: Optimizations & Improvements--### Objectives--Implement targeted performance improvements based on bottleneck analysis.--### Tasks--#### 2.1 Connection Pooling--- [ ] **HTTP connection reuse**- - Orchestrator to instances: Keep-Alive connections- - Bridge handlers: Connection pools for concurrent requests- - Measure impact on latency (target: 10-20% improvement)--- [ ] **Implementation Strategy**- - Update `proxyToInstance()` to use persistent HTTP client- - Configure http.Client with max idle connections, timeouts- - Consider connection limits per instance--- [ ] **Testing**- - Baseline: 100 sequential requests to single endpoint- - After: 100 sequential requests (measure improvement)- - Concurrent: 50 concurrent requests, measure connection reuse--- [ ] **Acceptance Criteria**- - Connection pool should reduce latency by 10-20%- - No connection leaks (verify with `ss -tna | grep ESTABLISHED`)- - Graceful connection cleanup on instance shutdown--#### 2.2 Cache Improvements--- [ ] **Query result caching**- - Cache `/tabs` aggregate results (5-10s TTL)- - Cache `/instances` listing (2-5s TTL)- - Cache profile data (1-5m TTL)--- [ ] **Implementation Strategy**- - Add simple in-memory cache with sync.RWMutex- - Invalidate cache on instance create/delete/update- - Log cache hits/misses for monitoring--- [ ] **Testing**- - Measure reduction in aggregation time- - Verify cache invalidation on changes- - Test with 50+ instances--- [ ] **Acceptance Criteria**- - `/tabs` response time with cache < 50ms (vs 500ms without)- - Cache eviction doesn't break consistency- - Stale reads acceptable for 5-10s window--#### 2.3 Batch Navigation Support--- [ ] **Bulk navigation endpoint**- - `POST /instances/{id}/batch-navigate` - navigate multiple URLs- - `POST /batch-navigate` - navigate across instances--- [ ] **Implementation Strategy**- - Accept array of URLs- - Return array of tab IDs- - Consider sequential vs parallel (with concurrency limits)--- [ ] **Testing**- - Navigate 50 URLs on single instance- - Measure latency improvement vs sequential calls- - Verify all tabs created correctly--- [ ] **Acceptance Criteria**- - 50-URL batch < 20s (vs 50 * 200ms = 10s sequential + overhead)- - All tabs successfully created- - Error handling for partial failures-------## Section 3: Scaling Tests & Validation--### Objectives--Validate system behavior under realistic production load scenarios.--### Tasks--#### 3.1 Stress Test: 100+ Concurrent Instances--- [ ] **Test scenario**- - Create 100 instances in rapid sequence- - Verify all reach "running" status- - Verify port allocation doesn't fail- - Verify Chrome initialization completes for all--- [ ] **Monitoring**- - Track system metrics: CPU, RAM, file descriptors, disk I/O- - Monitor orchestrator response times- - Log any errors or warnings--- [ ] **Implementation**- - Build test script: Create 100 instances, pause, verify all running- - Run 3x and average results- - Document peak resource usage--- [ ] **Acceptance Criteria**- - All 100 instances successfully created- - No port allocation conflicts- - CPU usage < 80% during test- - RAM usage < 12 GB- - All instances responsive after test--#### 3.2 Multi-Agent Concurrent Load--- [ ] **Test scenario**- - Simulate 5-10 agents, each using 2-3 instances- - Each agent navigates different URLs concurrently- - Run for 5 minutes- - Measure latency, errors, resource usage--- [ ] **Monitoring**- - Track latency distribution (p50, p95, p99)- - Monitor for race conditions or conflicts- - Verify instance isolation (no data leakage)--- [ ] **Implementation**- - Build multi-agent test harness- - Use goroutines to simulate agents- - Log actions and timing--- [ ] **Acceptance Criteria**- - p99 latency < 5s for all operations- - 0 errors from isolation violations- - CPU usage stable (not growing over time)- - No connection leaks--#### 3.3 Resource Limits Testing--- [ ] **Test orchestrator limits**- - What happens at 1000 instances? (Should gracefully degrade or error)- - What happens with port range exhaustion? (Clear error, not crash)- - What happens with memory pressure? (Can't create more instances)--- [ ] **Test instance limits**- - How many tabs per instance? (Chrome limit, usually 500+)- - What happens over 500 tabs? (Error or performance degradation)- - How many concurrent requests per instance?--- [ ] **Implementation**- - Build test for each limit- - Document expected behavior and error messages- - Verify graceful degradation--- [ ] **Acceptance Criteria**- - All limit conditions handled gracefully (no crashes)- - Clear error messages to users- - Documentation of limits- - Possible auto-scaling recommendations-------## Success Metrics--| Metric | Current | Target | Priority |-|--------|---------|--------|----------|-| `/navigate` latency (p99) | TBD | < 5s | High |-| Instance memory (idle) | TBD | < 150MB | High |-| 100 instances creation time | TBD | < 2 min | High |-| Cache hit ratio | N/A | > 80% | Medium |-| Connection reuse efficiency | N/A | > 90% | Medium |-| Error rate under load | TBD | < 0.1% | High |-------## Timeline Estimate--- **Benchmarking (3.1)**: 2-3 hours-- **Connection pooling (2.1)**: 1-2 hours-- **Cache improvements (2.2)**: 1-2 hours-- **Batch navigation (2.3)**: 1-2 hours-- **Stress testing (3.1-3.3)**: 2-3 hours-- **Documentation & analysis**: 1-2 hours--**Total: 9-14 hours**-------## Deliverables--- [ ] `docs/performance-benchmarks.md` - Baseline metrics and analysis-- [ ] `docs/performance-tuning.md` - Optimization recommendations-- [ ] `scripts/benchmark.sh` - Automated benchmarking harness-- [ ] `scripts/stress-test.sh` - 100+ instance stress test-- [ ] `scripts/multi-agent-load.sh` - Concurrent agent simulation-- [ ] Updated `TESTING.md` with performance test procedures-- [ ] Performance dashboard or metrics export (optional)-------## Notes--- Focus on realistic production scenarios, not synthetic micro-benchmarks-- Profile actual bottlenecks before optimizing (avoid premature optimization)-- Document all findings, even if results are "good enough"-- Consider infrastructure costs (more instances = more resource usage)-- Plan for monitoring/observability from the startdiff --git a/docs/proposals/ui-enhancements.md b/docs/proposals/ui-enhancements.mddeleted file mode 100644index 659a53b3..00000000--- a/docs/proposals/ui-enhancements.md+++ /dev/null@@ -1,414 +0,0 @@-# UI Enhancements--## Overview--Focuses on improving the dashboard user experience with real-time monitoring, batch operations, and better instance navigation. Current dashboard provides basic instance listing; Phase 8 adds production-grade observability and control.--## Goals--- Real-time visibility into instance health and resource usage-- Batch operations for efficient multi-instance management-- Improved navigation and search across large instance sets-- Live debugging and diagnostics capability-------## Section 1: Instance Monitoring Screen--### Objectives--Provide comprehensive real-time visibility into instance status, resource consumption, and activity.--### Tasks--#### 1.1 Real-Time Chrome Status--- [ ] **Display per-instance Chrome state**- - Chrome running / not running / initializing- - Process ID- - Window handle (for headed instances)- - Last activity timestamp--- [ ] **Implementation Strategy**- - Add `/instances/{id}/health/chrome` endpoint (returns {status, pid, active_window, last_activity})- - Update dashboard UI to poll every 2-5 seconds- - Show status indicator (green=running, yellow=initializing, red=crashed)- - Display "last activity" as relative time (e.g., "2 mins ago")--- [ ] **UI Components**- - Chrome status badge in instance card- - "Restart Chrome" button for crashed instances- - Process info popup (PID, memory, CPU)--- [ ] **Testing**- - Verify status updates reflect actual state- - Test with crashed Chrome (simulate process kill)- - Verify "Restart Chrome" brings instance back online--- [ ] **Acceptance Criteria**- - Status updates within 5 seconds- - Accurate reflection of Chrome state- - Graceful handling of process crashes- - Clear user feedback--#### 1.2 Memory & CPU Usage per Instance--- [ ] **Display resource consumption**- - RSS (resident set size) in MB- - CPU usage as percentage- - Trend over time (sparkline)- - Resource threshold alerts (warn if > 80% of available)--- [ ] **Implementation Strategy**- - Add `/instances/{id}/health/resources` endpoint (returns {memory_mb, cpu_percent, trend})- - Collect metrics every 10-30 seconds- - Calculate trend from last 10 samples- - Store metrics in circular buffer (last 100 samples)--- [ ] **Metric Collection Methods**- - Linux: Parse `/proc/[pid]/stat` and `/proc/[pid]/status`- - macOS: Use `ps` command or native APIs- - Include Chrome process + all child processes--- [ ] **UI Components**- - Memory gauge (0-1000 MB range, color-coded)- - CPU percentage with trend sparkline- - Alert badge if threshold exceeded- - Click to see detailed metrics over time--- [ ] **Testing**- - Verify metrics accurate compared to system tools (`ps`, `top`)- - Test with idle instance vs active navigation- - Verify trend calculation correct- - Test threshold alerts--- [ ] **Acceptance Criteria**- - Memory readings within ±5 MB of actual- - CPU readings within ±2% of actual- - Metrics updated every 10-30 seconds- - Alerts triggered correctly at thresholds--#### 1.3 Tab Activity Visualization--- [ ] **Display per-instance tab activity**- - Tab list with URL, title- - Last modified time- - Activity sparkline (show tab usage over time)- - Highlight most active tab--- [ ] **Implementation Strategy**- - Extend `/instances/{id}/tabs` to include: `last_modified`, `activity_count`, `last_action`- - Track tab actions (navigate, click, etc.) and timestamps- - Calculate activity trend (e.g., actions/minute)- - Reset counters hourly--- [ ] **UI Components**- - Tab list in instance details panel- - Activity sparkline for each tab- - Hover to see: URL, title, last action, action count- - Color indicate activity level (green=active, gray=idle)--- [ ] **Testing**- - Verify activity tracking accuracy- - Test with multiple concurrent tabs- - Verify sparkline rendering- - Test activity reset on schedule--- [ ] **Acceptance Criteria**- - Activity metrics accurate- - Sparklines render correctly- - Performance impact negligible (< 5% CPU increase)- - Activity data persists across instance lifecycle-------## Section 2: Batch Operations--### Objectives--Enable efficient management of multiple instances with bulk actions.--### Tasks--#### 2.1 Create Multiple Instances at Once--- [ ] **Bulk instance creation UI**- - Input: Count, profile name, headless flag- - e.g., "Create 10 scraping instances (headless)"- - Progress indicator during creation- - Confirmation of all created (IDs, ports, status)--- [ ] **Implementation Strategy**- - New form on "Instances" tab- - Add `/instances/batch-create` endpoint (accepts {count, profile, headless})- - Create instances in sequence (avoid overwhelming system)- - Return array of created instance IDs and ports--- [ ] **UI Components**- - "Create Batch" button- - Modal with count/profile/headless selectors- - Progress bar during creation- - Success confirmation with download CSV option (IDs, ports)--- [ ] **Error Handling**- - Handle port exhaustion (stop at max available)- - Handle instance creation failures (skip, continue with others)- - Provide detailed error messages--- [ ] **Testing**- - Create 5 instances in batch- - Verify all created with correct config- - Test port exhaustion scenario- - Verify error handling--- [ ] **Acceptance Criteria**- - 5 instances created in < 30 seconds- - All instances reachable and responsive- - Clear feedback on success/failure- - CSV export contains all created instances--#### 2.2 Terminate All Instances Button--- [ ] **Bulk shutdown UI**- - "Terminate All" button with confirmation- - Optional: Select subset before terminating- - Progress indicator during shutdown- - Cleanup verification (no orphaned processes)--- [ ] **Implementation Strategy**- - Add `/instances/batch-stop` endpoint (stops all or filtered list)- - Send stop requests in parallel (with concurrency limit)- - Track completion- - Verify ports released--- [ ] **UI Components**- - "Terminate All" button in Instances toolbar- - Confirmation dialog: "Terminate all {N} instances?"- - Progress bar with count (e.g., "Stopped 7/10")- - Success message: "All instances terminated, ports released"--- [ ] **Error Handling**- - Handle instances that fail to stop (provide manual options)- - Log any orphaned processes- - Clear error reporting--- [ ] **Testing**- - Create 5 instances, terminate all- - Verify all stopped- - Verify ports released (can create new instances)- - Test partial failure scenario--- [ ] **Acceptance Criteria**- - All instances stopped in < 30 seconds- - All ports released and available for reuse- - No orphaned Chrome processes- - Clear feedback on results--#### 2.3 Port Range Configuration UI--- [ ] **Configure instance port range**- - Display current range (e.g., 9868-9968)- - Allow modification (validate: start < end, reasonable range)- - Show available ports vs allocated- - Visual indicator of "capacity" (e.g., "48/100 ports allocated")--- [ ] **Implementation Strategy**- - Add `/config/port-range` endpoint (GET/POST)- - GET returns: current_start, current_end, allocated_count, total_count- - POST to change range (with validation)- - Update dashboard to call GET on load--- [ ] **UI Components**- - Settings panel with port range inputs- - Validation error messages- - Visual progress bar: "48 of 100 ports in use"- - Warning: "Some instances may be disconnected if range changed while running"- - "Apply" button (with confirmation if instances running)--- [ ] **Error Handling**- - Reject invalid ranges (start >= end, out of system limits)- - Warn if changing while instances running- - Prevent change if no available capacity for existing instances--- [ ] **Testing**- - Change port range from 9800-9900 to 9900-10000- - Verify new instances use new range- - Test invalid range inputs (rejected)- - Test changing range with instances running (warn user)--- [ ] **Acceptance Criteria**- - Port range configurable from UI- - Validation prevents invalid configurations- - User can see allocated vs available ports- - Changes take effect immediately for new instances-------## Section 3: Better Navigation & UX--### Objectives--Improve usability when managing large numbers of instances.--### Tasks--#### 3.1 Search & Filter Instances--- [ ] **Search and filter capabilities**- - Search by instance ID, profile name, port- - Filter by: status (running/stopped/error), headless (true/false)- - Filter by resource usage (e.g., "memory > 200MB")- - Combine multiple filters--- [ ] **Implementation Strategy**- - Frontend filtering (no backend API change needed initially)- - Add search box to Instances toolbar- - Add filter button with dropdown/checkboxes- - Real-time filtering as user types/selects--- [ ] **UI Components**- - Search input field (with clear button)- - "Filters" dropdown showing active filters- - Filter options: Status, Profile, Headless, Memory, CPU- - Results count: "Showing 12 of 50 instances"- - "Clear filters" button--- [ ] **Testing**- - Search for instance ID (partial match)- - Search for profile name- - Filter by status- - Combine multiple filters- - Verify result count accurate--- [ ] **Acceptance Criteria**- - Search results instant (< 100ms) for 100+ instances- - All filter combinations work- - Results count accurate- - Clear indication of active filters--#### 3.2 Instance Details Modal--- [ ] **Detailed view for single instance**- - Full instance info (ID, profile, port, mode, headless)- - Resource metrics (memory, CPU, trend)- - Chrome status (PID, window handle)- - Tab list with activity metrics- - Action buttons (restart Chrome, restart instance, stop instance)- - Log viewer (last 50 lines of instance logs)--- [ ] **Implementation Strategy**- - Create modal component that opens on instance click- - Combine data from: `/instances/{id}`, `/health/chrome`, `/health/resources`, `/tabs`- - Add `/instances/{id}/logs` endpoint (returns last N log lines)- - Update modal every 5 seconds with fresh data--- [ ] **UI Components**- - Modal with tabs: Overview, Resources, Tabs, Logs- - Responsive design (readable on small screens)- - Copy-to-clipboard for IDs/URLs- - Action buttons with confirmation dialogs--- [ ] **Testing**- - Open detail modal for multiple instances- - Verify all data displayed correctly- - Verify refresh works (data updates)- - Verify actions work (restart, stop)- - Test with many tabs (scroll, performance)--- [ ] **Acceptance Criteria**- - Modal loads in < 1 second- - Data refreshes every 5 seconds- - All instance details visible- - Actions execute correctly- - Performance acceptable with 50+ tabs--#### 3.3 Live Logs Viewer--- [ ] **Real-time log visualization**- - Stream logs from orchestrator and instances- - Filter by log level (info, warning, error, debug)- - Filter by source (orchestrator, instance ID)- - Timestamp on each log- - Autoscroll (can toggle off)- - Search within logs--- [ ] **Implementation Strategy**- - Add `/logs` endpoint with SSE (Server-Sent Events) or WebSocket- - Return stream of {timestamp, level, source, message}- - Client-side filtering (no backend filter needed initially)- - Store last 1000 logs in memory--- [ ] **UI Components**- - New "Logs" tab in main navigation- - Timeline view with scrollable log list- - Filter controls: level, source, search term- - Clear logs button- - Export logs button (download as text)--- [ ] **Testing**- - Verify logs stream in real-time- - Verify filtering works (level, source)- - Test with high log volume (1000+ logs/minute)- - Verify autoscroll works- - Test lag/latency with updates--- [ ] **Acceptance Criteria**- - Logs appear in < 500ms after event- - Filtering instant (no noticeable lag)- - Performance acceptable with 1000+ logs- - Search works on displayed logs- - Clear and export functions work-------## Success Metrics--| Feature | Metric | Target | Priority |-|---------|--------|--------|----------|-| Chrome status | Update latency | < 5s | High |-| Resource metrics | Accuracy | ±5% of actual | High |-| Batch create | Time for 10 instances | < 30s | Medium |-| Search | Response time | < 100ms | Medium |-| Log viewer | Update latency | < 500ms | Low |-------## Timeline Estimate--- **Chrome status (1.1)**: 2-3 hours-- **Resource metrics (1.2)**: 2-3 hours-- **Tab activity (1.3)**: 1-2 hours-- **Batch create (2.1)**: 2-3 hours-- **Terminate all (2.2)**: 1-2 hours-- **Port range config (2.3)**: 1-2 hours-- **Search & filter (3.1)**: 2-3 hours-- **Details modal (3.2)**: 3-4 hours-- **Live logs (3.3)**: 2-3 hours-- **Integration & testing**: 2-3 hours--**Total: 18-28 hours**-------## Deliverables--- [ ] Updated dashboard with monitoring screen-- [ ] Monitoring components: Chrome status, resource metrics, tab activity-- [ ] Batch operations: Create multiple, terminate all-- [ ] Port range configuration UI-- [ ] Search and filter system-- [ ] Instance details modal with logs viewer-- [ ] Updated `dashboard/` frontend files-- [ ] New API endpoints: `/health/*`, `/batch-*`, `/logs`, `/config/*`-- [ ] Updated documentation: Dashboard usage guide-------## Notes--- Prioritize high-visibility metrics (Chrome status, memory usage)-- Use polling initially, upgrade to WebSocket/SSE if performance issues-- Consider mobile responsiveness for remote dashboards-- Log viewer can be phase 8.5 if time-constrained-- Batch operations enable scripting (e.g., "create 100 instances for load test")-- Details modal is foundation for future alerts and anomaly detectiondiff --git a/docs/reference/click.md b/docs/reference/click.mdnew file mode 100644index 00000000..c2bb4d2c--- /dev/null+++ b/docs/reference/click.md@@ -0,0 +1,29 @@+# Click++Click an element by ref from a previous snapshot.++```bash+curl -X POST http://localhost:9867/action \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","ref":"e5"}'+# CLI Alternative+pinchtab click e5+# Response+{+ "success": true,+ "result": {+ "success": true+ }+}+```++Notes:++- element refs come from `/snapshot`+- `--wait-nav` exists on the top-level CLI command++## Related Pages++- [Snapshot](./snapshot.md)+- [Navigate](./navigate.md)+diff --git a/docs/reference/config.md b/docs/reference/config.mdnew file mode 100644index 00000000..c0338831--- /dev/null+++ b/docs/reference/config.md@@ -0,0 +1,294 @@+# Config++`pinchtab config` is the CLI entry point for creating, inspecting, validating, and editing PinchTab's config file.++Use this page as the command and schema reference. Broader deployment patterns can move to a separate guide later.++## Commands++### `pinchtab config init`++Creates a default config file at the standard user config location.++```bash+pinchtab config init+```++Current behavior note:++- `config init` writes to the default config path+- it does not currently switch to a custom `PINCHTAB_CONFIG` target path++### `pinchtab config show`++Shows the effective runtime configuration after applying:++```text+env vars -> config file -> built-in defaults+```++```bash+pinchtab config show+```++### `pinchtab config path`++Prints the config file path PinchTab will read.++```bash+pinchtab config path+```++### `pinchtab config validate`++Validates the current config file.++```bash+pinchtab config validate+```++### `pinchtab config get`++Reads a single dotted-path value from the config file.++```bash+pinchtab config get server.port+pinchtab config get instanceDefaults.mode+pinchtab config get attach.allowHosts+```++### `pinchtab config set`++Sets a single dotted-path value in the config file.++```bash+pinchtab config set server.port 8080+pinchtab config set instanceDefaults.mode headed+pinchtab config set multiInstance.strategy explicit+```++### `pinchtab config patch`++Applies a JSON patch object to the config file.++```bash+pinchtab config patch '{"server":{"port":"8080"}}'+pinchtab config patch '{"instanceDefaults":{"mode":"headed","maxTabs":50}}'+```++## Config Priority++PinchTab loads configuration in this order:++1. environment variables+2. config file+3. built-in defaults++The currently supported operational env vars are:++- `PINCHTAB_CONFIG`+- `PINCHTAB_BIND`+- `PINCHTAB_PORT`+- `PINCHTAB_TOKEN`+- `CHROME_BIN`++Everything else should be configured in `config.json`.++## Config File Location++Default location by OS:++- macOS: `~/Library/Application Support/pinchtab/config.json`+- Linux: `~/.config/pinchtab/config.json` or `$XDG_CONFIG_HOME/pinchtab/config.json`+- Windows: `%APPDATA%\pinchtab\config.json`++Legacy fallback:++- if `~/.pinchtab/config.json` exists and the newer location does not, PinchTab still uses the legacy location++Override the read path with:++```bash+export PINCHTAB_CONFIG=/path/to/config.json+```++## Config Shape++Current nested config shape:++```json+{+ "server": {+ "port": "9867",+ "bind": "127.0.0.1",+ "token": "your-secret-token",+ "stateDir": "/path/to/state"+ },+ "browser": {+ "version": "144.0.7559.133",+ "binary": "/path/to/chrome",+ "extraFlags": "",+ "extensionPaths": []+ },+ "instanceDefaults": {+ "mode": "headless",+ "maxTabs": 20,+ "maxParallelTabs": 0,+ "stealthLevel": "light",+ "tabEvictionPolicy": "reject",+ "blockAds": false,+ "blockImages": false,+ "blockMedia": false,+ "noRestore": false,+ "noAnimations": false+ },+ "security": {+ "allowEvaluate": false,+ "allowMacro": false,+ "allowScreencast": false,+ "allowDownload": false,+ "allowUpload": false+ },+ "profiles": {+ "baseDir": "/path/to/profiles",+ "defaultProfile": "default"+ },+ "multiInstance": {+ "strategy": "simple",+ "allocationPolicy": "fcfs",+ "instancePortStart": 9868,+ "instancePortEnd": 9968+ },+ "attach": {+ "enabled": false,+ "allowHosts": ["127.0.0.1", "localhost", "::1"],+ "allowSchemes": ["ws", "wss"]+ },+ "timeouts": {+ "actionSec": 30,+ "navigateSec": 60,+ "shutdownSec": 10,+ "waitNavMs": 1000+ }+}+```++## Sections++| Section | Purpose |+| --- | --- |+| `server` | HTTP server settings |+| `browser` | Chrome executable and launch wiring |+| `instanceDefaults` | Default behavior for managed instances |+| `security` | Sensitive feature gates |+| `profiles` | Profile storage defaults |+| `multiInstance` | Strategy, allocation, and instance port range |+| `attach` | Policy for attaching to external Chrome targets |+| `timeouts` | Runtime timeouts |++## Common Examples++### Headed Mode++```json+{+ "instanceDefaults": {+ "mode": "headed"+ }+}+```++### Network Bind With Token++```bash+PINCHTAB_BIND=0.0.0.0 PINCHTAB_TOKEN=secret pinchtab+```++### Custom Instance Port Range++```json+{+ "server": {+ "port": "8080"+ },+ "multiInstance": {+ "instancePortStart": 8100,+ "instancePortEnd": 8200+ }+}+```++### Tab Eviction Policy++```json+{+ "instanceDefaults": {+ "maxTabs": 10,+ "tabEvictionPolicy": "close_lru"+ }+}+```++### Attach Policy++```json+{+ "attach": {+ "enabled": true,+ "allowHosts": ["127.0.0.1", "localhost", "chrome.internal"],+ "allowSchemes": ["ws", "wss"]+ }+}+```++This is policy only. The actual `cdpUrl` is provided in the attach request, not in global config.++## Legacy Flat Format++Older flat config is still accepted for backward compatibility:++```json+{+ "port": "9867",+ "headless": true,+ "maxTabs": 20,+ "allowEvaluate": false,+ "timeoutSec": 30,+ "navigateSec": 60+}+```++Use `pinchtab config init` to create a nested config file.++## Validation++`pinchtab config validate` currently checks, among other things:++- valid server port values+- valid `instanceDefaults.mode`+- valid `instanceDefaults.stealthLevel`+- valid `instanceDefaults.tabEvictionPolicy`+- `instanceDefaults.maxTabs >= 1`+- `instanceDefaults.maxParallelTabs >= 0`+- valid `multiInstance.strategy`+- valid `multiInstance.allocationPolicy`+- valid `attach.allowSchemes`+- `multiInstance.instancePortStart <= multiInstance.instancePortEnd`+- non-negative timeout values++Valid enum values:++| Field | Values |+| --- | --- |+| `instanceDefaults.mode` | `headless`, `headed` |+| `instanceDefaults.stealthLevel` | `light`, `medium`, `full` |+| `instanceDefaults.tabEvictionPolicy` | `reject`, `close_oldest`, `close_lru` |+| `multiInstance.strategy` | `simple`, `explicit`, `simple-autorestart` |+| `multiInstance.allocationPolicy` | `fcfs`, `round_robin`, `random` |+| `attach.allowSchemes` | `ws`, `wss` |++## Notes++- `config show` reports effective runtime values, not just raw file contents.+- `config get`, `set`, and `patch` operate on the file config model, not on transient env overrides.+- Most operational behavior now belongs in `config.json`, not in startup env vars.\ No newline at end of filediff --git a/docs/reference/eval.md b/docs/reference/eval.mdnew file mode 100644index 00000000..972e37bd--- /dev/null+++ b/docs/reference/eval.md@@ -0,0 +1,26 @@+# Eval++Run JavaScript in the current tab. This endpoint is disabled unless evaluation is explicitly enabled in config.++```bash+curl -X POST http://localhost:9867/evaluate \+ -H "Content-Type: application/json" \+ -d '{"expression":"document.title"}'+# CLI Alternative+pinchtab eval "document.title"+# Response+{+ "result": "Example Domain"+}+```++Notes:++- requires `security.allowEvaluate: true`+- the tab-scoped variant is `POST /tabs/{id}/evaluate`++## Related Pages++- [Config](./config.md)+- [Tabs](./tabs.md)+diff --git a/docs/reference/fill.md b/docs/reference/fill.mdnew file mode 100644index 00000000..bbffcc09--- /dev/null+++ b/docs/reference/fill.md@@ -0,0 +1,29 @@+# Fill++Set an input value directly without relying on the same event sequence as `type`.++```bash+curl -X POST http://localhost:9867/action \+ -H "Content-Type: application/json" \+ -d '{"kind":"fill","ref":"e8","text":"[email protected]"}'+# CLI Alternative+pinchtab fill e8 "[email protected]"+# Response+{+ "success": true,+ "result": {+ "success": true+ }+}+```++Notes:++- the top-level CLI also accepts a selector form: `pinchtab fill 'input[name=email]' "[email protected]"`+- for the raw HTTP action endpoint, selectors use `selector`, not `ref`++## Related Pages++- [Type](./type.md)+- [Snapshot](./snapshot.md)+diff --git a/docs/reference/find.md b/docs/reference/find.mdnew file mode 100644index 00000000..7bb5fcb1--- /dev/null+++ b/docs/reference/find.md@@ -0,0 +1,156 @@+# Find++`/find` lets PinchTab locate elements by natural-language description instead of CSS selectors or XPath.++It works against the accessibility snapshot for a tab and returns the best matching `ref`, which you can pass to `/action`.++## Endpoints++PinchTab currently exposes two useful forms:++- `POST /find`+- `POST /tabs/{id}/find`++Use `POST /find` when you are talking directly to a bridge-style runtime or shorthand route and want to pass `tabId` in the request body.++Use `POST /tabs/{id}/find` when you already know the tab ID and want the orchestrator to route the request to the correct instance.++## Request Body++| Field | Type | Required | Default | Description |+| --- | --- | --- | --- | --- |+| `query` | string | yes | - | Natural-language description of the target element |+| `tabId` | string | no | active tab | Tab ID when using `POST /find` |+| `threshold` | float | no | `0.3` | Minimum similarity score |+| `topK` | int | no | `3` | Maximum number of matches to return |+| `lexicalWeight` | float | no | matcher default | Override lexical score weight |+| `embeddingWeight` | float | no | matcher default | Override embedding score weight |+| `explain` | bool | no | `false` | Include per-match score breakdown |++## Main Example++```bash+curl -X POST http://localhost:9867/tabs/<tabId>/find \+ -H "Content-Type: application/json" \+ -d '{"query":"login button","threshold":0.3,"topK":3}'+# Response+{+ "best_ref": "e5",+ "confidence": "high",+ "score": 0.85,+ "matches": [+ {+ "ref": "e5",+ "score": 0.85,+ "role": "button",+ "name": "Log in"+ }+ ],+ "strategy": "combined:lexical+embedding:hashing",+ "threshold": 0.3,+ "latency_ms": 2,+ "element_count": 42+}+```++There is no dedicated CLI `find` command at the moment.++## Using `POST /find`++```bash+curl -X POST http://localhost:9867/find \+ -H "Content-Type: application/json" \+ -d '{"tabId":"<tabId>","query":"search input"}'+# Response+{+ "best_ref": "e7",+ "confidence": "high",+ "score": 0.91,+ "matches": [+ {+ "ref": "e7",+ "score": 0.91,+ "role": "textbox",+ "name": "Search"+ }+ ],+ "strategy": "combined:lexical+embedding:hashing",+ "threshold": 0.3,+ "latency_ms": 18,+ "element_count": 142+}+```++If `tabId` is omitted, PinchTab uses the active tab in the current bridge context.++## Response Fields++| Field | Description |+| --- | --- |+| `best_ref` | Highest-scoring element reference to use with `/action` |+| `confidence` | `high`, `medium`, or `low` |+| `score` | Score of the best match |+| `matches` | Top matches above threshold |+| `strategy` | Matching strategy used |+| `threshold` | Threshold used for the request |+| `latency_ms` | Matching time in milliseconds |+| `element_count` | Number of elements evaluated |++When `explain` is enabled, each match may also include:++- `lexical_score`+- `embedding_score`+- `composite`++## Confidence Levels++| Level | Score Range | Meaning |+| --- | --- | --- |+| `high` | `>= 0.80` | Usually safe to act on directly |+| `medium` | `0.60 - 0.79` | Reasonable match, but verify for critical actions |+| `low` | `< 0.60` | Weak match; rephrase the query or lower the threshold carefully |++## Common Flow++The standard pattern is:++```text+navigate -> find -> action+```++Example:++```bash+curl -X POST http://localhost:9867/tabs/<tabId>/find \+ -H "Content-Type: application/json" \+ -d '{"query":"username input"}'+# Response+{+ "best_ref": "e14",+ "confidence": "high",+ "score": 0.85+}+```++Then use the returned ref:++```bash+curl -X POST http://localhost:9867/tabs/<tabId>/action \+ -H "Content-Type: application/json" \+ -d '{"ref":"e14","kind":"type","text":"[email protected]"}'+```++## Operational Notes++- `/find` uses the tab's accessibility snapshot, not raw DOM selectors.+- If there is no cached snapshot, PinchTab tries to refresh it automatically before matching.+- Successful matches are useful inputs to `/action`, `/actions`, and higher-level recovery logic.+- A `200` response can still return an empty `best_ref` if nothing met the threshold.++## Error Cases++| Status | Condition |+| --- | --- |+| `400` | invalid JSON or missing `query` |+| `404` | tab not found |+| `500` | Chrome not initialized, snapshot unavailable, or matcher failure |diff --git a/docs/reference/focus.md b/docs/reference/focus.mdnew file mode 100644index 00000000..1887da0a--- /dev/null+++ b/docs/reference/focus.md@@ -0,0 +1,25 @@+# Focus++Move focus to an element by ref.++```bash+curl -X POST http://localhost:9867/action \+ -H "Content-Type: application/json" \+ -d '{"kind":"focus","ref":"e8"}'+# CLI Alternative+pinchtab focus e8+# Response+{+ "success": true,+ "result": {+ "success": true+ }+}+```++This is useful before keyboard-only flows such as `press Enter` or `type`.++## Related Pages++- [Press](./press.md)+- [Type](./type.md)diff --git a/docs/reference/health.md b/docs/reference/health.mdnew file mode 100644index 00000000..2fe6a8fe--- /dev/null+++ b/docs/reference/health.md@@ -0,0 +1,25 @@+# Health++Check whether the current browser context is available and how many tabs are open.++```bash+curl http://localhost:9867/health+# CLI Alternative+pinchtab health+# Response+{+ "status": "ok",+ "tabs": 1+}+```++Notes:++- this is a shorthand route for the current browser context+- in error cases it returns `503` with `status: "error"`++## Related Pages++- [Tabs](./tabs.md)+- [Navigate](./navigate.md)+diff --git a/docs/reference/hover.md b/docs/reference/hover.mdnew file mode 100644index 00000000..2f7e8006--- /dev/null+++ b/docs/reference/hover.md@@ -0,0 +1,26 @@+# Hover++Move the pointer over an element by ref.++```bash+curl -X POST http://localhost:9867/action \+ -H "Content-Type: application/json" \+ -d '{"kind":"hover","ref":"e5"}'+# CLI Alternative+pinchtab hover e5+# Response+{+ "success": true,+ "result": {+ "success": true+ }+}+```++Use this when menus or tooltips appear only after hover.++## Related Pages++- [Click](./click.md)+- [Snapshot](./snapshot.md)+diff --git a/docs/reference/index.md b/docs/reference/index.mdnew file mode 100644index 00000000..bf5d9db2--- /dev/null+++ b/docs/reference/index.md@@ -0,0 +1,28 @@+# CLI Reference++Reference pages for the current PinchTab CLI and closely related command-facing endpoints.++Note: this index is generated and should be checked against the code when commands change.++- [Click](./click.md)+- [Config](./config.md)+- [Eval](./eval.md)+- [Fill](./fill.md)+- [Find](./find.md)+- [Focus](./focus.md)+- [Health](./health.md)+- [Hover](./hover.md)+- [Instances](./instances.md)+- [Navigate](./navigate.md)+- [PDF](./pdf.md)+- [Press](./press.md)+- [Profiles](./profiles.md)+- [Scheduler And Tasks](./scheduler.md)+- [Screenshot](./screenshot.md)+- [Scroll](./scroll.md)+- [Select](./select.md)+- [Snapshot](./snapshot.md)+- [Strategies](./strategies.md)+- [Tabs](./tabs.md)+- [Text](./text.md)+- [Type](./type.md)diff --git a/docs/reference/instances.md b/docs/reference/instances.mdnew file mode 100644index 00000000..da9b1b49--- /dev/null+++ b/docs/reference/instances.md@@ -0,0 +1,205 @@+# Instances++Instances are running Chrome processes managed by PinchTab. Each managed instance has:++- an instance ID+- a profile+- a port+- a mode (`headless` or `headed`)+- an execution status++One profile can have at most one active managed instance at a time.++## List Instances++```bash+curl http://localhost:9867/instances+# CLI Alternative+pinchtab instances+# Response+[+ {+ "id": "inst_0a89a5bb",+ "profileId": "prof_278be873",+ "profileName": "work",+ "port": "9868",+ "headless": true,+ "status": "running",+ "startTime": "2026-03-01T05:21:38.27432Z"+ }+]+```++`pinchtab instances` is the simplest way to inspect the current fleet from the CLI.++## Start An Instance++```bash+curl -X POST http://localhost:9867/instances/start \+ -H "Content-Type: application/json" \+ -d '{"profileId":"278be873adeb","mode":"headed","port":"9999"}'+# CLI Alternative+pinchtab instance start --profileId 278be873adeb --mode headed --port 9999+# Response+{+ "id": "inst_ea2e747f",+ "profileId": "prof_278be873",+ "profileName": "work",+ "port": "9999",+ "headless": false,+ "status": "starting",+ "startTime": "2026-03-01T05:21:38.27432Z"+}+```++Notes:++- `POST /instances/start` is the primary endpoint.+- `pinchtab instance launch` is a CLI alias for `pinchtab instance start`.+- if `profileId` is omitted, PinchTab creates an auto-generated temporary profile such as `instance-...`+- if `port` is omitted, PinchTab allocates one from the configured instance port range++## Get One Instance++```bash+curl http://localhost:9867/instances/inst_ea2e747f+# Response+{+ "id": "inst_ea2e747f",+ "profileId": "prof_278be873",+ "profileName": "work",+ "port": "9999",+ "headless": false,+ "status": "running",+ "startTime": "2026-03-01T05:21:38.27432Z"+}+```++Common status values:++- `starting`+- `running`+- `stopping`+- `stopped`+- `error`++## Get Instance Logs++```bash+curl http://localhost:9867/instances/inst_ea2e747f/logs+# CLI Alternative+pinchtab instance logs inst_ea2e747f+```++Response is plain text.++## Stop An Instance++```bash+curl -X POST http://localhost:9867/instances/inst_ea2e747f/stop+# CLI Alternative+pinchtab instance stop inst_ea2e747f+# Response+{+ "id": "inst_ea2e747f",+ "status": "stopped"+}+```++Stopping an instance preserves the profile unless it was a temporary auto-generated profile.++## Start By Profile++You can also start an instance from a profile-oriented route:++```bash+curl -X POST http://localhost:9867/profiles/278be873adeb/start \+ -H "Content-Type: application/json" \+ -d '{"headless":false,"port":"9999"}'+# Response+{+ "id": "inst_ea2e747f",+ "profileId": "prof_278be873",+ "profileName": "work",+ "port": "9999",+ "headless": false,+ "status": "starting"+}+```++This route accepts a profile ID or profile name in the path. Its request body uses `headless` rather than `mode`.++## Open A Tab In An Instance++```bash+curl -X POST http://localhost:9867/instances/inst_ea2e747f/tabs/open \+ -H "Content-Type: application/json" \+ -d '{"url":"https://pinchtab.com"}'+# Response+{+ "tabId": "8f9c7d4e1234567890abcdef12345678",+ "url": "https://pinchtab.com",+ "title": "PinchTab"+}+```++There is no dedicated instance-scoped `tab open` CLI command today. The CLI shortcut is:++```bash+pinchtab instance navigate inst_ea2e747f https://pinchtab.com+```++That command opens a tab for the instance and then navigates it.++## List Tabs For One Instance++```bash+curl http://localhost:9867/instances/inst_ea2e747f/tabs+# Response+[+ {+ "id": "8f9c7d4e1234567890abcdef12345678",+ "instanceId": "inst_ea2e747f",+ "url": "https://pinchtab.com",+ "title": "PinchTab"+ }+]+```++## List All Tabs Across Running Instances++```bash+curl http://localhost:9867/instances/tabs+```++This is the fleet-wide tab listing endpoint. It is different from `GET /tabs`, which is shorthand/bridge-style and not a fleet-wide inventory.++## List Metrics Across Instances++```bash+curl http://localhost:9867/instances/metrics+```++Use this when you want per-instance memory metrics across all running instances.++## Attach An Existing Chrome++```bash+curl -X POST http://localhost:9867/instances/attach \+ -H "Content-Type: application/json" \+ -d '{"name":"shared-chrome","cdpUrl":"ws://127.0.0.1:9222/devtools/browser/..."}'+# Response+{+ "id": "inst_0a89a5bb",+ "profileId": "prof_278be873",+ "profileName": "shared-chrome",+ "status": "running",+ "attached": true,+ "cdpUrl": "ws://127.0.0.1:9222/devtools/browser/..."+}+```++Notes:++- there is no CLI attach command+- attach is allowed only when enabled in config under `attach`diff --git a/docs/reference/navigate.md b/docs/reference/navigate.mdnew file mode 100644index 00000000..d01c6d94--- /dev/null+++ b/docs/reference/navigate.md@@ -0,0 +1,28 @@+# Navigate++Open a new tab and navigate it to a URL, or reuse a tab when a tab ID is provided through the API.++```bash+curl -X POST http://localhost:9867/navigate \+ -H "Content-Type: application/json" \+ -d '{"url":"https://example.com"}'+# CLI Alternative+pinchtab nav https://example.com+# Response+{+ "tabId": "8f9c7d4e1234567890abcdef12345678",+ "url": "https://example.com",+ "title": "Example Domain"+}+```++Useful flags:++- CLI: `--new-tab`, `--block-images`, `--block-ads`+- API body: `tabId`, `newTab`, `timeout`, `blockImages`, `blockAds`, `waitFor`, `waitSelector`++## Related Pages++- [Snapshot](./snapshot.md)+- [Tabs](./tabs.md)+diff --git a/docs/reference/pdf.md b/docs/reference/pdf.mdnew file mode 100644index 00000000..1dd765ce--- /dev/null+++ b/docs/reference/pdf.md@@ -0,0 +1,25 @@++Render the current page as a PDF.++```bash+curl "http://localhost:9867/pdf?output=file"+# CLI Alternative+pinchtab pdf -o page.pdf+# Response+{+ "path": "/path/to/state/pdfs/page-20260308-120001.pdf",+ "size": 48210+}+```++Useful flags:++- CLI: `-o`, `--tab`, `--landscape`, `--scale`+- API query: `output=file`, `raw`, `landscape`, `scale`, `paperWidth`, `paperHeight`++## Related Pages++- [Text](./text.md)+- [Screenshot](./screenshot.md)+diff --git a/docs/reference/press.md b/docs/reference/press.mdnew file mode 100644index 00000000..1ae1cf0e--- /dev/null+++ b/docs/reference/press.md@@ -0,0 +1,26 @@+# Press++Send a keyboard key to the current tab.++```bash+curl -X POST http://localhost:9867/action \+ -H "Content-Type: application/json" \+ -d '{"kind":"press","key":"Enter"}'+# CLI Alternative+pinchtab press Enter+# Response+{+ "success": true,+ "result": {+ "success": true+ }+}+```++Common keys include `Enter`, `Tab`, and `Escape`.++## Related Pages++- [Click](./click.md)+- [Focus](./focus.md)+diff --git a/docs/reference/profiles.md b/docs/reference/profiles.mdnew file mode 100644index 00000000..01498bbd--- /dev/null+++ b/docs/reference/profiles.md@@ -0,0 +1,209 @@+# Profiles++Profiles are browser user data directories. They hold cookies, local storage, history, and other durable browser state.++In PinchTab:++- profiles exist even when no instance is running+- one profile can have at most one active managed instance at a time+- profile IDs and names are both useful, but some endpoints require the profile ID specifically++## List Profiles++```bash+curl http://localhost:9867/profiles+# CLI Alternative+pinchtab profiles+# Response+[+ {+ "id": "278be873adeb",+ "name": "work",+ "created": "2026-02-27T20:37:13.599055326Z",+ "diskUsage": 534952089,+ "sizeMB": 510.17,+ "running": false,+ "source": "created",+ "useWhen": "Use for work accounts",+ "description": ""+ }+]+```++Notes:++- `GET /profiles` excludes temporary auto-generated instance profiles by default+- use `GET /profiles?all=true` to include temporary profiles+- `pinchtab profiles` exists, but the HTTP API is the more reliable source of truth for structured output++## Get One Profile++```bash+curl http://localhost:9867/profiles/278be873adeb+# Response+{+ "id": "278be873adeb",+ "name": "work",+ "path": "/path/to/profiles/work",+ "pathExists": true,+ "created": "2026-02-27T20:37:13.599055326Z",+ "diskUsage": 534952089,+ "sizeMB": 510.17,+ "source": "created",+ "chromeProfileName": "Your Chrome",+ "accountEmail": "[email protected]",+ "accountName": "Luigi",+ "hasAccount": true,+ "useWhen": "Use for work accounts",+ "description": ""+}+```++`GET /profiles/{id}` accepts either the profile ID or the profile name.++## Create A Profile++```bash+curl -X POST http://localhost:9867/profiles \+ -H "Content-Type: application/json" \+ -d '{"name":"scraping-profile","description":"Used for scraping","useWhen":"Use for ecommerce scraping"}'+# Response+{+ "status": "created",+ "id": "0f32ae81e4a1",+ "name": "scraping-profile"+}+```++There is no `pinchtab profile create` CLI command today.++## Update A Profile++```bash+curl -X PATCH http://localhost:9867/profiles/278be873adeb \+ -H "Content-Type: application/json" \+ -d '{"description":"Updated description","useWhen":"Updated usage note"}'+# Response+{+ "status": "updated",+ "id": "278be873adeb",+ "name": "work"+}+```++You can also rename the profile:++```bash+curl -X PATCH http://localhost:9867/profiles/278be873adeb \+ -H "Content-Type: application/json" \+ -d '{"name":"work-renamed"}'+```++Important:++- `PATCH /profiles/{id}` requires the profile ID+- using the profile name in that path returns an error+- a rename changes the generated profile ID because IDs are derived from the name++## Delete A Profile++```bash+curl -X DELETE http://localhost:9867/profiles/278be873adeb+# Response+{+ "status": "deleted",+ "id": "278be873adeb",+ "name": "work"+}+```++`DELETE /profiles/{id}` also requires the profile ID.++## Start Or Stop By Profile++Start the active instance for a profile:++```bash+curl -X POST http://localhost:9867/profiles/278be873adeb/start \+ -H "Content-Type: application/json" \+ -d '{"headless":true}'+# Response+{+ "id": "inst_ea2e747f",+ "profileId": "278be873adeb",+ "profileName": "work",+ "port": "9868",+ "headless": true,+ "status": "starting"+}+```++Stop the active instance for a profile:++```bash+curl -X POST http://localhost:9867/profiles/278be873adeb/stop+# Response+{+ "status": "stopped",+ "id": "278be873adeb",+ "name": "work"+}+```++For these orchestrator routes, the path can be a profile ID or profile name.++## Check Whether A Profile Has A Running Instance++```bash+curl http://localhost:9867/profiles/278be873adeb/instance+# Response+{+ "name": "work",+ "running": true,+ "status": "running",+ "port": "9868",+ "id": "inst_ea2e747f"+}+```++## Additional Profile Operations++### Reset A Profile++```bash+curl -X POST http://localhost:9867/profiles/278be873adeb/reset+```++This route requires the profile ID.++### Import A Profile++```bash+curl -X POST http://localhost:9867/profiles/import \+ -H "Content-Type: application/json" \+ -d '{"name":"imported-profile","sourcePath":"/path/to/existing/profile"}'+```++### Get Logs++```bash+curl http://localhost:9867/profiles/278be873adeb/logs+curl 'http://localhost:9867/profiles/work/logs?limit=50'+```++`logs` accepts either the profile ID or the profile name.++### Get Analytics++```bash+curl http://localhost:9867/profiles/278be873adeb/analytics+curl http://localhost:9867/profiles/work/analytics+```++`analytics` also accepts either the profile ID or the profile name.++## Related Pages++- [Instances](./instances.md)+- [Tabs](./tabs.md)+- [Config](./config.md)diff --git a/docs/reference/scheduler.md b/docs/reference/scheduler.mdnew file mode 100644index 00000000..490abff2--- /dev/null+++ b/docs/reference/scheduler.md@@ -0,0 +1,286 @@+# Scheduler And Tasks++The scheduler is an optional in-memory task queue for multi-agent coordination. It accepts tasks over `/tasks`, applies admission and fairness rules, then dispatches work to the same tab action executor used by the immediate browsing routes.++It does not replace the normal direct path. Routes such as `POST /tabs/{id}/action` still work independently.++There is no CLI scheduler command today.++## Enable The Scheduler++The scheduler is off by default. Dashboard mode registers the task routes only when `scheduler.enabled` is true.++```json+{+ "scheduler": {+ "enabled": true+ }+}+```++## Scheduler Config++```json+{+ "scheduler": {+ "enabled": true,+ "strategy": "fair-fifo",+ "maxQueueSize": 1000,+ "maxPerAgent": 100,+ "maxInflight": 20,+ "maxPerAgentInflight": 10,+ "resultTTLSec": 300,+ "workerCount": 4+ }+}+```++| Field | Default | Meaning |+| --- | --- | --- |+| `enabled` | `false` | enables task routes in dashboard mode |+| `strategy` | `fair-fifo` | scheduler strategy label |+| `maxQueueSize` | `1000` | global queued task limit |+| `maxPerAgent` | `100` | queued task limit per agent |+| `maxInflight` | `20` | max concurrently executing tasks overall |+| `maxPerAgentInflight` | `10` | max concurrently executing tasks per agent |+| `resultTTLSec` | `300` | retention time for terminal task snapshots |+| `workerCount` | `4` | number of worker goroutines |++## Task Object++Tasks are scheduler-owned records with these main fields:++| Field | Meaning |+| --- | --- |+| `taskId` | generated task ID |+| `agentId` | submitting agent identifier |+| `action` | action kind to run |+| `tabId` | target tab ID |+| `ref` | optional element ref |+| `params` | optional action-specific request fields |+| `priority` | lower number means higher priority |+| `state` | current task state |+| `deadline` | execution deadline |+| `createdAt` | submission time |+| `startedAt` | first execution timestamp |+| `completedAt` | terminal timestamp |+| `latencyMs` | elapsed time from start to completion |+| `result` | executor response payload |+| `error` | terminal error message |+| `position` | queue position at submission time |++Task IDs are currently generated as `tsk_XXXXXXXX`, but callers should still treat them as opaque IDs.++## Submit A Task++```bash+curl -X POST http://localhost:9867/tasks \+ -H "Content-Type: application/json" \+ -d '{+ "agentId": "agent-crawl-01",+ "action": "click",+ "tabId": "8f9c7d4e1234567890abcdef12345678",+ "ref": "e14",+ "priority": 5,+ "deadline": "2026-03-08T12:05:00Z"+ }'+# Response+{+ "taskId": "tsk_a1b2c3d4",+ "state": "queued",+ "position": 1,+ "createdAt": "2026-03-08T12:00:01Z"+}+```++This endpoint returns `202 Accepted` on successful queue submission.++Request fields:++| Field | Required | Notes |+| --- | --- | --- |+| `agentId` | yes | validated at request time |+| `action` | yes | becomes the executor `kind` |+| `tabId` | practically yes | required by the execution path |+| `ref` | no | top-level element ref for element-targeted actions |+| `params` | no | action-specific fields merged into the executor request body |+| `priority` | no | lower number means higher priority |+| `deadline` | no | RFC3339 timestamp; defaults to `now + 60s` |++Important:++- request validation enforces only `agentId` and `action`+- missing `tabId` is rejected later during execution with `tabId is required for task execution`+- past deadlines are rejected at submission time++## Queue Full Response++If admission fails because the global queue or an agent queue is full, the scheduler returns `429 Too Many Requests`.++```bash+curl -X POST http://localhost:9867/tasks \+ -H "Content-Type: application/json" \+ -d '{"agentId":"agent-crawl-01","action":"click","tabId":"8f9c7d4e1234567890abcdef12345678"}'+# Response+{+ "code": "queue_full",+ "error": "rejected: global queue full",+ "retryable": true,+ "details": {+ "agentId": "agent-crawl-01",+ "queued": 1000,+ "maxQueue": 1000,+ "maxPerAgent": 100+ }+}+```++## List Tasks++`GET /tasks` returns the scheduler's in-memory task snapshots, including queued, running, and recently completed tasks that are still within the TTL window.++```bash+curl http://localhost:9867/tasks+# Response+{+ "tasks": [+ {+ "taskId": "tsk_a1b2c3d4",+ "state": "done",+ "agentId": "agent-crawl-01",+ "action": "click",+ "latencyMs": 842+ }+ ],+ "count": 1+}+```++Supported query filters:++- `agentId`+- `state`++Example:++```bash+curl 'http://localhost:9867/tasks?agentId=agent-crawl-01&state=done,failed'+```++## Get One Task++```bash+curl http://localhost:9867/tasks/tsk_a1b2c3d4+# Response+{+ "taskId": "tsk_a1b2c3d4",+ "agentId": "agent-crawl-01",+ "action": "click",+ "tabId": "8f9c7d4e1234567890abcdef12345678",+ "ref": "e14",+ "priority": 5,+ "state": "done",+ "createdAt": "2026-03-08T12:00:01Z",+ "startedAt": "2026-03-08T12:00:01Z",+ "completedAt": "2026-03-08T12:00:02Z",+ "latencyMs": 842,+ "result": {+ "success": true+ }+}+```++If the task is not found, the scheduler returns:++```json+{+ "code": "not_found",+ "error": "task not found"+}+```++## Cancel A Task++```bash+curl -X POST http://localhost:9867/tasks/tsk_a1b2c3d4/cancel+# Response+{+ "status": "cancelled",+ "taskId": "tsk_a1b2c3d4"+}+```++Behavior:++- queued tasks are removed from the queue+- running tasks have their execution context cancelled+- terminal tasks return `409 Conflict`++## Task States++Implemented states:++- `queued`+- `assigned`+- `running`+- `done`+- `failed`+- `cancelled`+- `rejected`++Terminal states:++- `done`+- `failed`+- `cancelled`+- `rejected`++## How Tasks Execute++The scheduler forwards each task to the normal tab action endpoint:++```text+POST /tabs/{tabId}/action+```++It builds the action body like this:++```json+{+ "kind": "<action>",+ "ref": "<ref>",+ "...params": "..."+}+```++That means:++- `action` becomes `kind`+- top-level `ref` is forwarded when present+- every key in `params` is merged into the top-level action body++Example:++```bash+curl -X POST http://localhost:9867/tasks \+ -H "Content-Type: application/json" \+ -d '{+ "agentId": "my-agent",+ "action": "type",+ "tabId": "8f9c7d4e1234567890abcdef12345678",+ "ref": "e12",+ "params": {+ "text": "Alan Turing"+ }+ }'+```++In practice, task payloads should use the same action fields that the immediate `/tabs/{id}/action` route expects.++## Fairness, Deadlines, And Retention++- within one agent queue, lower `priority` values run first+- equal-priority tasks for the same agent fall back to FIFO order+- across agents, the scheduler prefers the agent with the fewest in-flight tasks+- if a queued task passes its deadline before execution starts, it is marked failed with `deadline exceeded while queued`+- terminal task snapshots are retained in memory for `resultTTLSec`\ No newline at end of filediff --git a/docs/reference/screenshot.md b/docs/reference/screenshot.mdnew file mode 100644index 00000000..8ccb61ec--- /dev/null+++ b/docs/reference/screenshot.md@@ -0,0 +1,27 @@+# Screenshot++Capture the current page as an image.++```bash+curl "http://localhost:9867/screenshot?output=file"+# CLI Alternative+pinchtab ss -o page.jpg+# Response+{+ "path": "/path/to/state/screenshots/screenshot-20260308-120001.jpg",+ "size": 34567,+ "format": "jpeg",+ "timestamp": "20260308-120001"+}+```++Useful flags:++- CLI: `-o`, `-q`, `--tab`+- API query: `quality`, `raw`, `output=file`, `tabId`++## Related Pages++- [Snapshot](./snapshot.md)+- [PDF](./pdf.md)+diff --git a/docs/reference/scroll.md b/docs/reference/scroll.mdnew file mode 100644index 00000000..e043859b--- /dev/null+++ b/docs/reference/scroll.md@@ -0,0 +1,29 @@+# Scroll++Scroll the current tab by direction or pixel amount.++```bash+curl -X POST http://localhost:9867/action \+ -H "Content-Type: application/json" \+ -d '{"kind":"scroll","direction":"down"}'+# CLI Alternative+pinchtab scroll down+# Response+{+ "success": true,+ "result": {+ "success": true+ }+}+```++Notes:++- the top-level CLI also accepts a pixel value such as `pinchtab scroll 800`+- the raw API can also use `scrollY`++## Related Pages++- [Snapshot](./snapshot.md)+- [Text](./text.md)+diff --git a/docs/reference/select.md b/docs/reference/select.mdnew file mode 100644index 00000000..e0b8da90--- /dev/null+++ b/docs/reference/select.md@@ -0,0 +1,26 @@+# Select++Choose a value in a select element by ref.++```bash+curl -X POST http://localhost:9867/action \+ -H "Content-Type: application/json" \+ -d '{"kind":"select","ref":"e12","value":"it"}'+# CLI Alternative+pinchtab select e12 it+# Response+{+ "success": true,+ "result": {+ "success": true+ }+}+```++The `value` should match the option value expected by the page.++## Related Pages++- [Snapshot](./snapshot.md)+- [Focus](./focus.md)+diff --git a/docs/reference/snapshot.md b/docs/reference/snapshot.mdnew file mode 100644index 00000000..98831222--- /dev/null+++ b/docs/reference/snapshot.md@@ -0,0 +1,33 @@+# Snapshot++Get an accessibility snapshot of the current page, including element refs that can be reused by action commands.++```bash+curl "http://localhost:9867/snapshot?filter=interactive"+# CLI Alternative+pinchtab snap -i+# Response+{+ "url": "https://example.com",+ "title": "Example Domain",+ "nodes": [+ {+ "ref": "e5",+ "role": "link",+ "name": "More information..."+ }+ ],+ "count": 1+}+```++Useful flags:++- CLI: `-i`, `-c`, `-d`, `--selector`, `--max-tokens`, `--depth`+- API query: `filter`, `format`, `diff`, `selector`, `maxTokens`, `depth`++## Related Pages++- [Click](./click.md)+- [Tabs](./tabs.md)+diff --git a/docs/reference/strategies.md b/docs/reference/strategies.mdnew file mode 100644index 00000000..a753cb6f--- /dev/null+++ b/docs/reference/strategies.md@@ -0,0 +1,175 @@+# Strategies And Allocation++PinchTab has two separate multi-instance controls:++- `multiInstance.strategy`+- `multiInstance.allocationPolicy`++They solve different problems:++```text+strategy = what routes PinchTab exposes and how shorthand requests behave+allocationPolicy = which running instance gets picked when PinchTab must choose one+```++## Strategy++Valid strategies in the current implementation:++- `simple`+- `explicit`+- `simple-autorestart`++### `simple`++`simple` is the default.++Behavior:++- registers the full orchestrator API+- keeps shorthand routes such as `/snapshot`, `/text`, `/navigate`, and `/tabs`+- if a shorthand request arrives and no instance is running, PinchTab auto-launches one managed instance and waits for it to become healthy++Best fit:++- local development+- single-user automation+- “just make the browser service available” setups++### `explicit`++`explicit` also exposes the orchestrator API and shorthand routes, but it does not auto-launch on shorthand requests.++Behavior:++- you start instances explicitly with `/instances/start`, `/instances/launch`, or `/profiles/{id}/start`+- shorthand routes proxy to the first running instance only if one already exists+- if nothing is running, shorthand routes return an error instead of launching a browser for you++Best fit:++- controlled multi-instance environments+- agents that should name instances deliberately+- deployments where hidden auto-launch would be surprising++### `simple-autorestart`++`simple-autorestart` behaves like a managed single-instance service with recovery.++Behavior:++- launches one managed instance when the strategy starts+- exposes the same shorthand routes as `simple`+- watches that managed instance and tries to restart it after unexpected exits+- exposes `GET /autorestart/status` for restart state++Best fit:++- kiosk or appliance-style setups+- unattended local services+- environments where one browser should come back after a crash++## Allocation Policy++Valid policies in the current implementation:++- `fcfs`+- `round_robin`+- `random`++Allocation policy matters only when PinchTab has multiple eligible running instances and needs to choose one. If your request already targets `/instances/{id}/...`, no allocation policy is involved for that request.++### `fcfs`++First running candidate wins.++Best fit:++- predictable behavior+- simplest operational model+- “always use the earliest running instance” workflows++### `round_robin`++Candidates are selected in rotation.++Best fit:++- light balancing across a stable pool+- repeated shorthand-style traffic where you want even distribution over time++### `random`++PinchTab picks a random eligible candidate.++Best fit:++- looser balancing+- experiments where deterministic ordering is not important++## Example Config++```json+{+ "multiInstance": {+ "strategy": "explicit",+ "allocationPolicy": "round_robin",+ "instancePortStart": 9868,+ "instancePortEnd": 9968+ }+}+```++## Recommended Defaults++### Simple Local Service++```json+{+ "multiInstance": {+ "strategy": "simple",+ "allocationPolicy": "fcfs"+ }+}+```++Use this when you want shorthand routes to feel like a single local browser service.++### Explicit Orchestration++```json+{+ "multiInstance": {+ "strategy": "explicit",+ "allocationPolicy": "round_robin"+ }+}+```++Use this when your client is instance-aware and you want to control lifecycle directly.++### Self-Healing Single Service++```json+{+ "multiInstance": {+ "strategy": "simple-autorestart",+ "allocationPolicy": "fcfs"+ }+}+```++Use this when one managed browser should stay available and recover after crashes.++## Decision Rule++```text+simple = easiest default, auto-launches on shorthand traffic+explicit = most control, no shorthand auto-launch+simple-autorestart = one managed browser with crash recovery++fcfs = deterministic+round_robin = balanced rotation+random = loose distribution+```+diff --git a/docs/reference/tabs.md b/docs/reference/tabs.mdnew file mode 100644index 00000000..cf7c53cd--- /dev/null+++ b/docs/reference/tabs.md@@ -0,0 +1,239 @@+# Tabs++Tabs are the main execution surface for browsing, extracting, and interacting with pages.++Use tab-scoped routes once you already have a tab ID. Use instance-scoped routes when you need to create a new tab in a specific instance.++Tab IDs should be treated as opaque values returned by the API. Do not construct them yourself or assume one stable format across all routes.++## Shorthand Browser Commands++Top-level browser commands such as `nav`, `snap`, `text`, `click`, `type`, `fill`, `pdf`, `ss`, `eval`, and `health` now have their own quick reference pages.++Use those pages when you want the shorthand route plus the matching CLI command:++- [Health](./health.md)+- [Navigate](./navigate.md)+- [Snapshot](./snapshot.md)+- [Text](./text.md)+- [Click](./click.md)+- [Type](./type.md)+- [Fill](./fill.md)+- [Screenshot](./screenshot.md)+- [PDF](./pdf.md)+- [Eval](./eval.md)+- [Press](./press.md)+- [Hover](./hover.md)+- [Scroll](./scroll.md)+- [Select](./select.md)+- [Focus](./focus.md)++## Open A Tab In A Specific Instance++```bash+curl -X POST http://localhost:9867/instances/inst_ea2e747f/tabs/open \+ -H "Content-Type: application/json" \+ -d '{"url":"https://pinchtab.com"}'+# Response+{+ "tabId": "8f9c7d4e1234567890abcdef12345678",+ "url": "https://pinchtab.com",+ "title": "PinchTab"+}+```++There is no dedicated instance-scoped `tab open` CLI command today.++If you want a CLI shortcut that opens a tab and navigates it, use:++```bash+pinchtab instance navigate inst_ea2e747f https://pinchtab.com+```++## List Tabs++### Shorthand Or Bridge List++```bash+curl http://localhost:9867/tabs+# CLI Alternative+pinchtab tabs+# Response+{+ "tabs": [+ {+ "id": "8f9c7d4e1234567890abcdef12345678",+ "url": "https://pinchtab.com",+ "title": "PinchTab",+ "type": "page"+ }+ ]+}+```++Notes:++- `GET /tabs` is not a fleet-wide orchestrator inventory+- in bridge mode or shorthand mode it lists tabs from the active browser context+- `pinchtab tabs` follows that shorthand behavior++### One Instance++```bash+curl http://localhost:9867/instances/inst_ea2e747f/tabs+# Response+[+ {+ "id": "8f9c7d4e1234567890abcdef12345678",+ "instanceId": "inst_ea2e747f",+ "url": "https://pinchtab.com",+ "title": "PinchTab"+ }+]+```++### All Running Instances++```bash+curl http://localhost:9867/instances/tabs+```++Use `GET /instances/tabs` when you need the fleet-wide view.++## Navigate An Existing Tab++```bash+curl -X POST http://localhost:9867/tabs/<tabId>/navigate \+ -H "Content-Type: application/json" \+ -d '{"url":"https://example.com"}'+# CLI Alternative+pinchtab tab navigate <tabId> https://example.com+# Response+{+ "tabId": "8f9c7d4e1234567890abcdef12345678",+ "url": "https://example.com",+ "title": "Example Domain"+}+```++## Snapshot++```bash+curl "http://localhost:9867/tabs/<tabId>/snapshot?interactive=true&compact=true"+# CLI Alternative+pinchtab tab snapshot <tabId> -i -c+```++Use this to retrieve the accessibility snapshot and element refs for the page.++## Text++```bash+curl "http://localhost:9867/tabs/<tabId>/text?raw=true"+# CLI Alternative+pinchtab tab text <tabId> --raw+```++## Find++```bash+curl -X POST http://localhost:9867/tabs/<tabId>/find \+ -H "Content-Type: application/json" \+ -d '{"query":"login button"}'+# Response+{+ "best_ref": "e5",+ "confidence": "high",+ "score": 0.85+}+```++There is no dedicated CLI `find` command today.++## Action++```bash+curl -X POST http://localhost:9867/tabs/<tabId>/action \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","ref":"e5"}'+# CLI Alternative+pinchtab tab click <tabId> e5+```++Other CLI-backed tab operations include:++- `pinchtab tab type <tabId> <ref> <text>`+- `pinchtab tab fill <tabId> <ref> <text>`+- `pinchtab tab press <tabId> <key>`+- `pinchtab tab hover <tabId> <ref>`+- `pinchtab tab scroll <tabId> <direction|pixels>`+- `pinchtab tab select <tabId> <ref> <value>`+- `pinchtab tab focus <tabId> <ref>`++## Screenshot++```bash+curl "http://localhost:9867/tabs/<tabId>/screenshot?raw=true" > out.png+# CLI Alternative+pinchtab tab screenshot <tabId> -o out.png+```+++```bash+curl "http://localhost:9867/tabs/<tabId>/pdf?raw=true" > page.pdf+# CLI Alternative+pinchtab tab pdf <tabId> -o page.pdf+```++## Cookies++```bash+curl http://localhost:9867/tabs/<tabId>/cookies+# CLI Alternative+pinchtab tab cookies <tabId>+```++## Metrics++```bash+curl http://localhost:9867/tabs/<tabId>/metrics+```++This returns aggregate browser metrics for the tab's owning instance, not isolated per-tab memory.++## Lock And Unlock++```bash+curl -X POST http://localhost:9867/tabs/<tabId>/lock \+ -H "Content-Type: application/json" \+ -d '{"owner":"my-agent","ttl":60}'+# CLI Alternative+pinchtab tab lock <tabId> --owner my-agent --ttl 60+```++```bash+curl -X POST http://localhost:9867/tabs/<tabId>/unlock \+ -H "Content-Type: application/json" \+ -d '{"owner":"my-agent"}'+# CLI Alternative+pinchtab tab unlock <tabId> --owner my-agent+```++## Close A Tab++```bash+curl -X POST http://localhost:9867/tabs/<tabId>/close+# CLI Alternative+pinchtab tab close <tabId>+# Response+{+ "status": "closed"+}+```++## Important Limits++- there is no documented `GET /tabs/{id}` resource endpoint in the current server routes+- `pinchtab tab info <tabId>` exists in the CLI, but it depends on a route that is not part of the current documented HTTP surface+- `GET /tabs` and `GET /instances/tabs` serve different purposes and should not be treated as interchangeablediff --git a/docs/reference/text.md b/docs/reference/text.mdnew file mode 100644index 00000000..8917e7c7--- /dev/null+++ b/docs/reference/text.md@@ -0,0 +1,27 @@+# Text++Extract readable text from the current page. Use raw mode when you want `innerText` instead of readability-style extraction.++```bash+curl "http://localhost:9867/text?mode=raw"+# CLI Alternative+pinchtab text --raw+# Response+{+ "url": "https://example.com",+ "title": "Example Domain",+ "text": "Example Domain\nThis domain is for use in illustrative examples in documents.",+ "truncated": false+}+```++Useful flags:++- CLI: `--raw`+- API query: `mode=raw`, `maxChars`, `format=text`++## Related Pages++- [Snapshot](./snapshot.md)+- [PDF](./pdf.md)+diff --git a/docs/reference/type.md b/docs/reference/type.mdnew file mode 100644index 00000000..b9f8d24a--- /dev/null+++ b/docs/reference/type.md@@ -0,0 +1,29 @@+# Type++Type text into an element, sending key events as the text is entered.++```bash+curl -X POST http://localhost:9867/action \+ -H "Content-Type: application/json" \+ -d '{"kind":"type","ref":"e8","text":"Ada Lovelace"}'+# CLI Alternative+pinchtab type e8 "Ada Lovelace"+# Response+{+ "success": true,+ "result": {+ "success": true+ }+}+```++Notes:++- use `fill` when you want to set the value more directly+- top-level `type` expects a ref, not a CSS selector++## Related Pages++- [Fill](./fill.md)+- [Snapshot](./snapshot.md)+diff --git a/docs/references/api-structure.md b/docs/references/api-structure.mddeleted file mode 100644index 3e78df01..00000000--- a/docs/references/api-structure.md+++ /dev/null@@ -1,427 +0,0 @@-# API Structure--## Overview--### Resource Hierarchy--```-Profile- ↓ (create instance with profile)-Instance (orchestrator resource)- ↓ (create tab in instance)-Tab (primary resource - where all work happens)- ├─ Navigate- ├─ Snapshot- ├─ Action / Actions- ├─ Text- ├─ Evaluate- ├─ Screenshot- ├─ Cookies- ├─ Lock / Unlock- └─ Close-```-------## Complete Endpoint List--### Profile Management-| Method | Path | Payload | Response | Purpose |-|--------|------|---------|----------|---------|-| GET | `/profiles` | - | `[{id, name, createdAt, usedAt}]` | List profiles |-| POST | `/profiles` | `{name}` | `{id, name, createdAt}` | Create profile |-| GET | `/profiles/{id}` | - | `{id, name, createdAt, usedAt}` | Get profile info |-| DELETE | `/profiles/{id}` | - | `{id, deleted: true}` | Delete profile |--### Instance Management-| Method | Path | Payload | Response | Purpose |-|--------|------|---------|----------|---------|-| GET | `/instances` | - | `[{id, profileId, port, mode, status, startTime}]` | List instances |-| GET | `/instances/{id}` | - | `{id, profileId, port, mode, status, startTime}` | Get instance status (read-only) |-| POST | `/instances/start` | `{profileId?, mode?, port?}` | `{id, profileId, port, mode, status}` | Start instance |-| POST | `/instances/{id}/start` | - | `{status: "chrome_ready"}` or `{id, profileId, port, mode, status}` | Start browser for existing instance |-| POST | `/instances/{id}/stop` | - | `{id, stopped: true}` | Stop instance |-| GET | `/instances/{id}/logs` | - | `text` | Get instance logs |--### Tab Management (NEW)-| Method | Path | Payload | Response | Purpose |-|--------|------|---------|----------|---------|-| POST | `/tabs/new` | `{instanceId, url?}` | `{id, instanceId, url?, status}` | Create tab |-| GET | `/tabs` | - | `[{id, instanceId, url, title, type}]` | List all tabs |-| GET | `/tabs?instanceId={id}` | - | `[{id, instanceId, url, title}]` | List instance tabs |-| GET | `/tabs/{id}` | - | `{id, instanceId, url, title, type, status}` | Get tab info |-| POST | `/tabs/{id}/close` | - | `{id, closed: true}` | Close tab |--### Tab Operations (NEW - Replaces /instances/{id}/...)-| Method | Path | Query/Body | Response | Purpose |-|--------|------|-----------|----------|---------|-| **Navigate** |-| POST | `/tabs/{id}/navigate` | `{url, timeout?, blockImages?, blockAds?}` | `{url, status, title}` | Navigate to URL |-| **Snapshot** |-| GET | `/tabs/{id}/snapshot` | `?interactive&compact&depth=3&maxTokens=2000` | `{elements: [], tree: ...}` | Page structure |-| **Action** |-| POST | `/tabs/{id}/action` | `{kind, ref?, text?, key?, value?, ...}` | `{kind, result?, error?}` | Single action |-| POST | `/tabs/{id}/actions` | `{actions: [{kind, ...}, ...]}` | `{results: [...]}` | Multiple actions |-| **Text & Evaluation** |-| GET | `/tabs/{id}/text` | `?raw` | `{text: "...", elements: [...]}` | Extract text |-| POST | `/tabs/{id}/evaluate` | `{expression, await?}` | `{result: any, type: string}` | Run JS |-| **Media** |-| GET | `/tabs/{id}/screenshot` | `?format=png&quality=80` | `binary (PNG/JPEG)` | Screenshot |-| GET | `/tabs/{id}/pdf` | `?landscape&margins=0.5&scale=1.0&pages=1-3` | `binary (PDF)` | PDF export |-| **Cookies** |-| GET | `/tabs/{id}/cookies` | - | `[{name, value, domain, ...}]` | Get cookies |-| POST | `/tabs/{id}/cookies` | `{action: "set"|"delete", cookies: [...]}` | `{set: [...], deleted: [...]}` | Manage cookies |-| **Locking** |-| POST | `/tabs/{id}/lock` | `{owner: string, ttl: number}` | `{locked: true, owner, expiresAt}` | Lock tab |-| POST | `/tabs/{id}/unlock` | `{owner: string}` | `{unlocked: true}` | Unlock tab |-| GET | `/tabs/{id}/locks` | - | `{locked: bool, owner?, expiresAt?}` | Check lock |-| **Fingerprinting** |-| POST | `/tabs/{id}/fingerprint/rotate` | - | `{rotated: true, userAgent, ...}` | Rotate fingerprint |-| GET | `/tabs/{id}/fingerprint/status` | - | `{stealth: "light"|"full", ua, ...}` | Get fingerprint |-------## Comparison: Old vs New--### Example 1: Click Element--**OLD (instance-scoped):**-```bash-curl -X POST http://localhost:9867/instances/inst_abc123/action \- -d '{"kind": "click", "ref": "e5"}'-```-- Requires instance ID-- Path has 3 segments--**NEW (tab-scoped):**-```bash-curl -X POST http://localhost:9867/tabs/tab_xyz789/action \- -d '{"kind": "click", "ref": "e5"}'-```-- Requires tab ID (which identifies instance)-- Path has 2 segments-- Cleaner for multi-tab workflows-------### Example 2: Navigate to URL--**OLD:**-```bash-curl -X POST http://localhost:9867/instances/inst_abc123/navigate \- -d '{"url": "https://pinchtab.com"}'-```--**NEW:**-```bash-curl -X POST http://localhost:9867/tabs/tab_xyz789/navigate \- -d '{"url": "https://pinchtab.com"}'-```-------### Example 3: Create Tab--**OLD:**-```bash-curl -X POST http://localhost:9867/instances/inst_abc123/tabs/open \- -d '{}'-# Response: {id: "tab_xyz", ...}-```--**NEW:**-```bash-curl -X POST http://localhost:9867/tabs/new \- -d '{"instanceId": "inst_abc123"}'-# Response: {id: "tab_xyz", ...}-```-------### Example 4: List tabs--**OLD:**-```bash-curl http://localhost:9867/instances/inst_abc123/tabs-# Returns just tabs from that instance-```--**NEW:**-```bash-# All tabs (across instances)-curl http://localhost:9867/tabs--# Specific instance-curl http://localhost:9867/tabs?instanceId=inst_abc123-```-------## Query Parameters vs Body--### Query Parameters (GET)-```bash-# Snapshot with options-curl 'http://localhost:9867/tabs/tab_xyz/snapshot?interactive&compact&depth=2&maxTokens=2000'--# Screenshot with format-curl 'http://localhost:9867/tabs/tab_xyz/screenshot?format=jpeg&quality=85'--# List with filter-curl 'http://localhost:9867/tabs?instanceId=inst_abc123'-```--### Body (POST)-```bash-# Navigate with options-curl -X POST http://localhost:9867/tabs/tab_xyz/navigate \- -d '{- "url": "https://pinchtab.com",- "timeout": 30,- "blockImages": true,- "blockAds": false- }'--# Action (already body-based)-curl -X POST http://localhost:9867/tabs/tab_xyz/action \- -d '{- "kind": "click",- "ref": "e5",- "timeout": 5- }'-```-------## HTTP Status Codes--| Code | Meaning | Example |-|------|---------|---------|-| **200** | Success (GET/action) | Snapshot returned, action completed |-| **201** | Created | Tab created, instance started |-| **204** | No content | Close successful |-| **400** | Bad request | Invalid action kind, malformed JSON |-| **404** | Not found | Tab ID doesn't exist, instance stopped |-| **409** | Conflict | Tab locked by another agent, port in use |-| **500** | Server error | Chrome crashed, internal error |-| **503** | Unavailable | Chrome not initialized, instance starting |-------## Response Format--### Success Response-```json-{- "kind": "action",- "result": {- "text": "Element text",- "visible": true,- "rect": {...}- }-}-```--### Error Response-```json-{- "error": "tab not found",- "code": "ERR_TAB_NOT_FOUND",- "statusCode": 404-}-```--### Snapshot Response-```json-{- "elements": [- {- "ref": "e1",- "tag": "button",- "text": "Click me",- "interactive": true,- "rect": {"x": 100, "y": 50, "w": 80, "h": 30}- }- ],- "tree": {...},- "meta": {"count": 45, "interactive": 12}-}-```-------## CLI Command Mapping--### Profile Management-```bash-# List-pinchtab profiles--# Create-pinchtab profile create my-profile--# Delete-pinchtab profile delete my-profile-```--### Instance Management-```bash-# List-pinchtab instances--# Start-pinchtab instance start --profile my-profile --mode headed --port 9868--# Stop-pinchtab instance stop inst_abc123--# Logs-pinchtab instance logs inst_abc123-```--### Tab Management-```bash-# List all tabs-pinchtab tabs--# List instance tabs-pinchtab --instance inst_abc123 tabs--# Create tab-pinchtab --instance inst_abc123 tab new https://pinchtab.com-# → tab_xyz789--# Close tab-pinchtab --tab tab_xyz789 close-```--### Tab Operations-```bash-# Navigate-pinchtab --tab tab_xyz789 nav https://pinchtab.com--# Snapshot-pinchtab --tab tab_xyz789 snap -i -c--# Click-pinchtab --tab tab_xyz789 click e5--# Get text-pinchtab --tab tab_xyz789 text--# Run action-cat << 'EOF' | pinchtab --tab tab_xyz789 action-{- "kind": "actions",- "actions": [- {"kind": "click", "ref": "e1"},- {"kind": "type", "ref": "e2", "text": "search"},- {"kind": "press", "key": "Enter"}- ]-}-EOF--# Lock tab (exclusive access)-pinchtab --tab tab_xyz789 lock --owner my-agent --ttl 60--# Unlock-pinchtab --tab tab_xyz789 unlock --owner my-agent-```-------## Full Workflow Example--### Setup-```bash-# 1. Create profile-PROF=$(pinchtab profile create my-app | jq -r .id)--# 2. Start instance-INST=$(pinchtab instance start --profile my-app --mode headed | jq -r .id)--# 3. Create tab-TAB=$(pinchtab --instance $INST tab new | jq -r .id)-```--### Work-```bash-# 4. Navigate-pinchtab --tab $TAB nav https://pinchtab.com--# 5. Get page structure-pinchtab --tab $TAB snap -i -c | jq .--# 6. Interact-pinchtab --tab $TAB click e5-pinchtab --tab $TAB type e12 "search text"-pinchtab --tab $TAB press Enter--# 7. Check result-pinchtab --tab $TAB snap -d | jq .--# 8. Extract data-pinchtab --tab $TAB text-```--### Cleanup-```bash-# 9. Close tab (optional, instance cleanup closes all)-pinchtab --tab $TAB close--# 10. Stop instance-pinchtab instance stop $INST-```-------## Data Flow--### Request Path-```-CLI Command- ↓-HTTP Request (curl or SDK)- ↓-Orchestrator Server (9867)- ↓-Tab Resolver (tab ID → instance ID)- ↓-Route to Instance (HTTP call to 9868+)- ↓-Bridge Server- ↓-Chrome (DevTools Protocol)-```--### Response Path-```-Chrome responds- ↓-Bridge returns JSON- ↓-Instance Server returns JSON- ↓-Orchestrator aggregates/proxies- ↓-CLI/SDK receives JSON-```-------## Deprecation Timeline--### Phase 1 (Now - v1.0)-- New tab endpoints available-- Old instance endpoints still work-- Deprecation headers on old endpoints--### Phase 2 (v1.1)-- CLI prefers `--tab` over `--instance`-- Documentation focuses on new API-- Users migrated gradually--### Phase 3 (v2.0)-- Old instance endpoints removed-- Only tab-centric APIdiff --git a/docs/references/configuration.md b/docs/references/configuration.mddeleted file mode 100644index ef2a6b06..00000000--- a/docs/references/configuration.md+++ /dev/null@@ -1,299 +0,0 @@-# Configuration--Complete reference for PinchTab configuration. Supports environment variables, config files (JSON), and CLI commands.--PinchTab has two instance ownership models:-- `launch`: PinchTab starts and manages Chrome-- `attach`: PinchTab connects to an externally managed Chrome instance--The config file defines defaults and policy for those models. It does not define a global instance-specific CDP target.--## Configuration Priority--Values are loaded in this order (highest priority first):--1. **Environment variables**-2. **Config file** — `~/.config/pinchtab/config.json` (or `~/.pinchtab/config.json` legacy)-3. **Built-in defaults**--Only a small operational env surface remains:-- `PINCHTAB_CONFIG`-- `PINCHTAB_BIND`-- `PINCHTAB_PORT`-- `PINCHTAB_TOKEN`-- `CHROME_BIN`--Everything else should be configured in `config.json`.--## Config File--### Location--Default location varies by OS:-- **macOS:** `~/Library/Application Support/pinchtab/config.json`-- **Linux:** `~/.config/pinchtab/config.json` (or `$XDG_CONFIG_HOME/pinchtab/config.json`)-- **Windows:** `%APPDATA%\pinchtab\config.json`--For backward compatibility, `~/.pinchtab/config.json` is used if it exists and the new location doesn't.--Override with `PINCHTAB_CONFIG=/path/to/config.json`.--### Format--```json-{- "server": {- "port": "9867",- "bind": "127.0.0.1",- "token": "your-secret-token",- "stateDir": "/path/to/state"- },- "browser": {- "version": "144.0.7559.133",- "binary": "/path/to/chrome",- "extraFlags": "",- "extensionPaths": []- },- "instanceDefaults": {- "mode": "headless",- "maxTabs": 20,- "stealthLevel": "light",- "tabEvictionPolicy": "reject",- "blockAds": false,- "blockImages": false,- "blockMedia": false,- "noRestore": false,- "noAnimations": false- },- "security": {- "allowEvaluate": false,- "allowMacro": false,- "allowScreencast": false,- "allowDownload": false,- "allowUpload": false- },- "profiles": {- "baseDir": "/path/to/profiles",- "defaultProfile": "default"- },- "multiInstance": {- "strategy": "simple",- "allocationPolicy": "fcfs",- "instancePortStart": 9868,- "instancePortEnd": 9968- },- "attach": {- "enabled": false,- "allowHosts": ["127.0.0.1", "localhost", "::1"],- "allowSchemes": ["ws", "wss"]- },- "timeouts": {- "actionSec": 30,- "navigateSec": 60,- "shutdownSec": 10,- "waitNavMs": 1000- }-}-```--### Section Semantics--- `server`: PinchTab HTTP server settings.-- `browser`: Chrome executable/runtime wiring used when PinchTab launches Chrome.-- `instanceDefaults`: Default launch-time behavior for managed instances.-- `security`: Feature gates for sensitive endpoints.-- `profiles`: Shared profile storage model for both single-instance and multi-instance flows.-- `multiInstance`: Orchestration strategy and instance port allocation.-- `attach`: Policy for whether attach is allowed and which remote CDP targets are acceptable.-- `timeouts`: PinchTab runtime timeouts.--### Legacy Flat Format--Older flat format is still supported for backward compatibility:--```json-{- "port": "9867",- "headless": true,- "maxTabs": 20,- "allowEvaluate": false,- "timeoutSec": 30,- "navigateSec": 60-}-```--Run `pinchtab config init` to generate a new config with the nested format.--## Environment Variables--Environment variables always take precedence over config file values.--### Operational Env Vars--| Variable | Default | Description |-|----------|---------|-------------|-| `PINCHTAB_PORT` | `9867` | HTTP server port |-| `PINCHTAB_BIND` | `127.0.0.1` | Bind address |-| `PINCHTAB_TOKEN` | (none) | API authentication token |-| `PINCHTAB_CONFIG` | (OS config dir)/config.json | Config file path |-| `CHROME_BIN` | (auto) | Chrome binary path |--All behavior settings such as display mode, feature gates, profile defaults, attach policy, timeouts, and multi-instance strategy live in `config.json`.--## CLI Commands--### `pinchtab config init`--Create a default config file:--```bash-pinchtab config init-```--### `pinchtab config show`--Show current effective configuration:--```bash-pinchtab config show-```--### `pinchtab config path`--Show config file path:--```bash-pinchtab config path-```--### `pinchtab config validate`--Validate config file:--```bash-pinchtab config validate-```--Checks for:-- Valid port numbers (1-65535)-- Valid enum values (strategy, stealthLevel, tabEvictionPolicy, etc.)-- Valid attach schemes (`ws`, `wss`)-- Valid timeout values (non-negative)-- Valid instance port range (`start <= end`)--## Examples--### Basic Setup--```bash-pinchtab-```--Runs on `localhost:9867`, headless, no authentication.--### With Authentication--```bash-PINCHTAB_TOKEN=my-secret-token pinchtab-```--Or in config file:--```json-{- "server": {- "token": "my-secret-token"- }-}-```--### Network Accessible--```bash-PINCHTAB_BIND=0.0.0.0 PINCHTAB_TOKEN=secret pinchtab-```--Always use a token when binding to `0.0.0.0`.--### Headed Mode for Debugging--```json-{- "instanceDefaults": {- "mode": "headed"- }-}-```--### Attach Policy--Enable attach mode only if you want PinchTab to accept attach requests to externally managed Chrome instances.--```json-{- "attach": {- "enabled": true,- "allowHosts": ["127.0.0.1", "localhost", "chrome.internal"],- "allowSchemes": ["ws", "wss"]- }-}-```--This is policy only. The actual `cdpUrl` belongs to the attach request, not global config.--### Custom Ports--```bash-PINCHTAB_PORT=8080 pinchtab server-```--Or in config file:--```json-{- "server": {- "port": "8080"- },- "multiInstance": {- "instancePortStart": 8100,- "instancePortEnd": 8200- }-}-```--### Tab Eviction Policy--When max tabs is reached:-- `reject` — return error-- `close_oldest` — close oldest tab by creation time-- `close_lru` — close least recently used tab--```json-{- "instanceDefaults": {- "maxTabs": 10,- "tabEvictionPolicy": "close_lru"- }-}-```--## Validation--All enum fields are validated on load:--| Field | Valid Values |-|-------|--------------|-| `instanceDefaults.mode` | `headless`, `headed` |-| `instanceDefaults.stealthLevel` | `light`, `medium`, `full` |-| `instanceDefaults.tabEvictionPolicy` | `reject`, `close_oldest`, `close_lru` |-| `multiInstance.strategy` | `simple`, `explicit`, `simple-autorestart` |-| `multiInstance.allocationPolicy` | `fcfs`, `round_robin`, `random` |-| `attach.allowSchemes` | `ws`, `wss` |--Run `pinchtab config validate` to check your config file.--## Related Documentation--- [API Reference](endpoints.md)-- [CLI Reference](cli-quick-reference.md)-- [Instance API](instance-api.md)diff --git a/docs/references/find-api.md b/docs/references/find-api.mddeleted file mode 100644index 5673251d..00000000--- a/docs/references/find-api.md+++ /dev/null@@ -1,125 +0,0 @@-# Semantic Find API (`/find`)--Find UI elements by natural language description using semantic matching.--## Endpoint--```-POST /find-POST /find?tab={tabId}-```--## Request Body--| Field | Type | Default | Description |-|-------|------|---------|-------------|-| `query` | string | *required* | Natural language description of the target element |-| `threshold` | float | `0.3` | Minimum score threshold (0.0–1.0) |-| `topK` | int | `3` | Maximum matches to return |--### Example Request--```bash-curl -s -X POST http://localhost:9868/find \- -H "Content-Type: application/json" \- -d '{"query": "submit button", "threshold": 0.3, "topK": 3}'-```--## Response--```json-{- "best_ref": "e5",- "score": 0.85,- "confidence": "high",- "strategy": "combined:lexical+embedding:hashing",- "element_count": 42,- "threshold": 0.3,- "latency_ms": 2,- "matches": [- { "ref": "e5", "score": 0.85, "role": "button", "name": "Submit" },- { "ref": "e12", "score": 0.42, "role": "button", "name": "Reset Form" }- ]-}-```--### Response Fields--| Field | Type | Description |-|-------|------|-------------|-| `best_ref` | string | Ref of the highest-scoring element (use with `/action`) |-| `score` | float | Best match score (0.0–1.0) |-| `confidence` | string | `"high"` (≥0.8), `"medium"` (≥0.6), or `"low"` |-| `strategy` | string | Matching strategy used |-| `element_count` | int | Total elements evaluated on the page |-| `threshold` | float | Echo of the threshold used |-| `latency_ms` | int | Processing time in milliseconds |-| `matches` | array | Top-K matches above threshold, sorted by score desc |--## Matching Strategy--PinchTab uses a **combined matcher** that fuses two scoring methods:--### 1. Lexical Matching (60% weight)--Jaccard-based token overlap with:-- **Stopword removal** — "the", "a", "is" are ignored-- **Token frequency weighting** — rare tokens score higher-- **Role keyword boost** — matches on "button", "textbox", "link" etc. get a 0.15 bonus--### 2. Embedding Matching (40% weight)--Feature-hashing embedder (128-dim vectors) with:-- **Word unigrams** — exact word overlap-- **Character n-grams** (2–4) — sub-word similarity (e.g., "btn" ↔ "button")-- **Role-aware features** — extra dimensions for UI role keywords-- **Cosine similarity** — normalized vector comparison--### Combined Score--```-final_score = 0.6 × lexical_score + 0.4 × embedding_score-```--## Usage with /action--Chain `/find` → `/action` for natural language element interaction:--```bash-# 1. Find the element-REF=$(curl -s -X POST http://localhost:9868/find \- -d '{"query": "login button"}' | jq -r '.best_ref')--# 2. Act on it-curl -s -X POST http://localhost:9868/action \- -d "{\"ref\": \"$REF\", \"action\": \"click\"}"-```--## Confidence Levels--| Level | Score Range | Guidance |-|-------|------------|----------|-| `high` | ≥ 0.80 | Safe to act automatically |-| `medium` | 0.60 – 0.79 | Likely correct, may want confirmation |-| `low` | < 0.60 | Multiple candidates possible, re-query advised |--## Error Responses--| Code | Condition |-|------|-----------|-| `400` | Missing `query` field |-| `404` | Tab not found |-| `500` | No accessibility snapshot available (call `/text` first) |--## Performance--Benchmarks on Intel i5-4300U @ 1.90GHz:--| Operation | Elements | Latency | Allocations |-|-----------|----------|---------|-------------|-| Lexical Find | 16 | ~71 µs | 134 allocs |-| HashingEmbedder (single) | 1 | ~11 µs | 3 allocs |-| HashingEmbedder (batch) | 16 | ~171 µs | 49 allocs |-| Embedding Find | 16 | ~180 µs | 98 allocs |-| **Combined Find** | **16** | **~233 µs** | **263 allocs** |-| Combined Find | 100 | ~1.5 ms | 1685 allocs |diff --git a/docs/references/instance-api.md b/docs/references/instance-api.mddeleted file mode 100644index e2e961d0..00000000--- a/docs/references/instance-api.md+++ /dev/null@@ -1,684 +0,0 @@-# Instance API Reference--Instances are running Chrome browser processes managed by PinchTab. Each instance is associated with a profile (browser user data directory) and has its own independent browser state.--## Quick Start--### List Running Instances-```bash-# CLI-pinchtab instances--# Curl-curl http://localhost:9867/instances | jq .--# Response-[- {- "id": "inst_0a89a5bb",- "profileId": "prof_278be873",- "profileName": "Pinchtab org",- "port": "9868",- "headless": true,- "status": "running",- "startTime": "2026-03-01T05:21:38.27432Z"- }-]-```--### Start an Instance-```bash-# CLI (all parameters optional)-pinchtab instance start--# CLI with profile-pinchtab instance start --profileId 278be873adeb--# CLI with mode and port-pinchtab instance start --mode headed --port 9999--# Curl-curl -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"profileId": "278be873adeb", "mode": "headed", "port": 9999}'--# Response-{- "id": "inst_ea2e747f",- "profileId": "prof_278be873",- "profileName": "Pinchtab org",- "port": "9868",- "headless": false,- "status": "starting"-}-```--### Get Instance Logs-```bash-# CLI-pinchtab instance logs inst_ea2e747f-pinchtab instance logs --id inst_ea2e747f--# Curl-curl http://localhost:9867/instances/inst_ea2e747f/logs-```--### Stop an Instance-```bash-# CLI-pinchtab instance stop inst_ea2e747f-pinchtab instance stop --id inst_ea2e747f--# Curl-curl -X POST http://localhost:9867/instances/inst_ea2e747f/stop--# Response-{- "id": "inst_ea2e747f",- "status": "stopped"-}-```-------## Complete API Reference--### 1. List Instances--**Endpoint:** `GET /instances`--**CLI:**-```bash-pinchtab instances-```--**Curl:**-```bash-curl http://localhost:9867/instances | jq .-```--**Response:** Array of Instance objects-```json-[- {- "id": "inst_0a89a5bb",- "profileId": "prof_278be873",- "profileName": "Pinchtab org",- "port": "9868",- "headless": true,- "status": "running",- "startTime": "2026-03-01T05:21:38.27432Z"- }-]-```--**Instance Status Values:**-- `starting` — Instance process spawning, Chrome initializing-- `running` — Instance healthy and ready to accept commands-- `error` — Instance failed to start-- `stopping` — Instance is shutting down-------### 2. Start Instance--**Endpoint:** `POST /instances/start`--**CLI:**-```bash-# All parameters optional - uses defaults-pinchtab instance start--# With specific profile-pinchtab instance start --profileId 278be873adeb--# With mode and port-pinchtab instance start --profileId abc123 --mode headed --port 9999--# Combine flags-pinchtab instance start --mode headed --port 9998-```--**Curl:**-```bash-# Minimal (all defaults)-curl -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{}'--# With profile ID-curl -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{- "profileId": "278be873adeb",- "mode": "headed",- "port": "9999"- }'-```--**Request Body (all optional):**-```json-{- "profileId": "278be873adeb",- "mode": "headed",- "port": "9999"-}-```--**Parameters:**-- `profileId` (string, optional) — Profile ID or name. If omitted, creates temporary instance-- `mode` (string, optional, default: "headless") — "headed" or "headless"-- `port` (string, optional) — Port number. If omitted, auto-allocated from available ports--**Response:** Instance object-```json-{- "id": "inst_ea2e747f",- "profileId": "prof_278be873",- "profileName": "Pinchtab org",- "port": "9868",- "headless": false,- "status": "starting",- "startTime": "2026-03-01T05:21:38.27432Z"-}-```--**Defaults:**-- `profileId` — If omitted, auto-generates temporary profile name-- `mode` — Defaults to "headless" if not specified-- `port` — Auto-allocated if not specified (finds first available port)-------### 3. Get Instance Logs--**Endpoint:** `GET /instances/{id}/logs`--**CLI:**-```bash-# Positional argument-pinchtab instance logs inst_ea2e747f--# With --id flag-pinchtab instance logs --id inst_ea2e747f-```--**Curl:**-```bash-curl http://localhost:9867/instances/inst_ea2e747f/logs-```--**Response:** Text (plain text log output)-```-2026-03-01 05:21:38 INFO starting instance process id=inst_ea2e747f profile=Pinchtab org port=9868-2026-03-01 05:21:40 INFO instance ready id=inst_ea2e747f-```--**Notes:**-- Returns raw text output (not JSON)-- Includes timestamps and log levels-- Useful for debugging instance startup issues-------### 4. Stop Instance--**Endpoint:** `POST /instances/{id}/stop`--**CLI:**-```bash-# Positional argument-pinchtab instance stop inst_ea2e747f--# With --id flag-pinchtab instance stop --id inst_ea2e747f-```--**Curl:**-```bash-curl -X POST http://localhost:9867/instances/inst_ea2e747f/stop-```--**Response:**-```json-{- "id": "inst_ea2e747f",- "status": "stopped"-}-```--**Notes:**-- Gracefully shuts down Chrome process-- Returns immediately (shutdown happens in background)-- Instance moved to stopped state-- Profile is preserved (not deleted)-------## Complete Workflow Examples--### Example 1: Simple Start and Stop--```bash-#!/bin/bash--# Start headless instance (auto-allocated port, temporary profile)-INST=$(curl -s -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r .id)--echo "Started instance: $INST"--# Wait a moment for instance to be ready-sleep 2--# Get logs-echo "Instance logs:"-curl -s http://localhost:9867/instances/$INST/logs | head -5--# Stop instance-curl -s -X POST http://localhost:9867/instances/$INST/stop | jq .--echo "Stopped instance: $INST"-```--### Example 2: Start with Specific Profile--```bash-#!/bin/bash--# Get first available profile ID-PROF=$(curl -s http://localhost:9867/profiles | jq -r '.[0].id')-echo "Using profile: $PROF"--# Start instance with that profile in headed mode-INST=$(curl -s -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d "{- \"profileId\": \"$PROF\",- \"mode\": \"headed\",- \"port\": \"9999\"- }" | jq -r .id)--echo "Started instance: $INST on port 9999"--# List running instances-echo -e "\nRunning instances:"-curl -s http://localhost:9867/instances | jq '.[] | {id, port, mode: (if .headless then "headless" else "headed" end)}'--# Stop when done-curl -s -X POST http://localhost:9867/instances/$INST/stop-```--### Example 3: CLI-Based Workflow--```bash-#!/bin/bash--# Start instance-echo "Starting instance..."-INST=$(pinchtab instance start --mode headed --port 9998 | jq -r .id)-echo "Instance: $INST"--# Wait for ready-sleep 3--# View logs-echo -e "\nInstance logs:"-pinchtab instance logs $INST | tail -5--# List instances-echo -e "\nRunning instances:"-pinchtab instances | jq '.[] | {id, port}'--# Stop-echo -e "\nStopping..."-pinchtab instance stop $INST-```--### Example 4: Multiple Instances--```bash-#!/bin/bash--declare -a INSTANCES--# Start 3 instances with different profiles-PROFILES=$(curl -s http://localhost:9867/profiles | jq -r '.[0:3] | .[] | .id')--i=0-for prof in $PROFILES; do- PORT=$((9868 + i))- INST=$(curl -s -X POST http://localhost:9867/instances/start \- -H "Content-Type: application/json" \- -d "{\"profileId\":\"$prof\",\"port\":\"$PORT\"}" | jq -r .id)- INSTANCES+=($INST)- echo "Started: $INST on port $PORT"- i=$((i + 1))-done--# Wait and verify-sleep 2-echo -e "\nRunning instances:"-curl -s http://localhost:9867/instances | jq length | xargs echo "Count:"--# Stop all-echo -e "\nStopping all instances..."-for inst in "${INSTANCES[@]}"; do- curl -s -X POST http://localhost:9867/instances/$inst/stop > /dev/null- echo "Stopped: $inst"-done-```-------## CLI Examples--### Quick Start with CLI--```bash-# List instances-pinchtab instances--# Start headless instance-pinchtab instance start--# Start headed instance on specific port-pinchtab instance start --mode headed --port 9999--# Start with profile-pinchtab instance start --profileId 278be873adeb--# Get logs (both syntaxes work)-pinchtab instance logs inst_0a89a5bb-pinchtab instance logs --id inst_0a89a5bb--# Stop instance (both syntaxes work)-pinchtab instance stop inst_0a89a5bb-pinchtab instance stop --id inst_0a89a5bb-```--### Script Example--```bash-#!/bin/bash-# Simple instance management script--case "$1" in- "start")- pinchtab instance start --mode $2 --port $3- ;;- "logs")- pinchtab instance logs $2- ;;- "stop")- pinchtab instance stop $2- ;;- "list")- pinchtab instances- ;;- *)- echo "Usage: $0 {start|logs|stop|list} [args]"- ;;-esac-```-------## Integration Examples--### With Bash--```bash-# Start instance and capture ID-INST=$(curl -s -X POST http://localhost:9867/instances/start \- -d '{}' | jq -r .id)--# Use instance-PORT=$(curl -s http://localhost:9867/instances | jq -r ".[] | select(.id == \"$INST\") | .port")-echo "Instance $INST running on port $PORT"--# Cleanup-curl -s -X POST http://localhost:9867/instances/$INST/stop-```--### With Python--```python-import requests-import json--BASE = "http://localhost:9867"--# Start instance-resp = requests.post(f"{BASE}/instances/start", json={- "profileId": "278be873adeb",- "mode": "headed",- "port": "9999"-})-inst = resp.json()-print(f"Started: {inst['id']} on port {inst['port']}")--# List instances-instances = requests.get(f"{BASE}/instances").json()-print(f"Total running: {len(instances)}")--# Get logs-logs = requests.get(f"{BASE}/instances/{inst['id']}/logs").text-print("Recent logs:", logs[:200])--# Stop instance-resp = requests.post(f"{BASE}/instances/{inst['id']}/stop")-print(f"Stopped: {resp.json()}")-```--### With JavaScript/Node.js--```javascript-const BASE = "http://localhost:9867";--async function manageInstances() {- // Start instance- const startResp = await fetch(`${BASE}/instances/start`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- profileId: "278be873adeb",- mode: "headed",- port: "9999"- })- });- const inst = await startResp.json();- console.log(`Started: ${inst.id} on port ${inst.port}`);-- // List instances- const listResp = await fetch(`${BASE}/instances`);- const instances = await listResp.json();- console.log(`Total running: ${instances.length}`);-- // Get logs- const logsResp = await fetch(`${BASE}/instances/${inst.id}/logs`);- const logs = await logsResp.text();- console.log("Recent logs:", logs.substring(0, 200));-- // Stop instance- const stopResp = await fetch(`${BASE}/instances/${inst.id}/stop`, {- method: "POST"- });- const stopped = await stopResp.json();- console.log(`Stopped: ${stopped.id}`);-}--manageInstances().catch(console.error);-```-------## Error Handling--### Profile Not Found (404)--```bash-curl -X POST http://localhost:9867/instances/start \- -d '{"profileId":"nonexistent"}'--# Response (400 Bad Request)-{- "error": "profile \"nonexistent\" not found",- "statusCode": 404-}-```--### Port Already in Use (409)--```bash-curl -X POST http://localhost:9867/instances/start \- -d '{"port":"9867"}'--# Response (409 Conflict)-{- "error": "port 9867 already in use",- "statusCode": 409-}-```--### Instance Not Found (404)--```bash-curl http://localhost:9867/instances/nonexistent/logs--# Response (404 Not Found)-{- "error": "instance not found",- "statusCode": 404-}-```--### Invalid JSON (400)--```bash-curl -X POST http://localhost:9867/instances/start \- -d 'invalid json'--# Response (400 Bad Request)-{- "error": "invalid JSON",- "statusCode": 400-}-```-------## Best Practices--### Port Management--```bash-# Let PinchTab auto-allocate ports (recommended)-pinchtab instance start--# Or manually specify if you need a specific port-pinchtab instance start --port 9999-```--### Profile Selection--```bash-# Start with specific profile to preserve state-pinchtab instance start --profileId 278be873adeb--# Or use temporary profile (good for isolated testing)-pinchtab instance start-```--### Cleanup--```bash-# Always stop instances when done-pinchtab instance stop $INSTANCE_ID--# Check for orphaned instances-pinchtab instances | jq length-```--### Monitoring--```bash-# Check instance status-pinchtab instances | jq '.[] | {id, port, status}'--# View recent logs-pinchtab instance logs $INSTANCE_ID | tail -20-```-------## Instance Lifecycle--```-START (POST /instances/start)- ↓-[status: "starting"] — Chrome initializing, health checks running- ↓-[status: "running"] — Ready to accept commands- ↓-STOP (POST /instances/{id}/stop)- ↓-[status: "stopping"] — Graceful shutdown- ↓-Instance removed from list, profile preserved-```-------## Status Codes--| Code | Meaning | Example |-|------|---------|---------|-| **200** | Success (GET) | List retrieved, logs retrieved |-| **201** | Created | Instance started successfully |-| **400** | Bad request | Invalid JSON, missing required field |-| **404** | Not found | Instance/profile not found |-| **409** | Conflict | Port already in use, launch error |-| **500** | Server error | Internal error |-------## Summary Table--| Operation | Method | Endpoint | CLI |-|-----------|--------|----------|-----|-| List | GET | `/instances` | `pinchtab instances` |-| Start | POST | `/instances/start` | `pinchtab instance start [opts]` |-| Logs | GET | `/instances/{id}/logs` | `pinchtab instance logs <id>` |-| Stop | POST | `/instances/{id}/stop` | `pinchtab instance stop <id>` |-------## FAQ--**Q: What's the difference between headless and headed mode?**-A: Headless runs without a GUI window (good for servers), headed shows the browser window (good for debugging).--**Q: Can I run multiple instances simultaneously?**-A: Yes, each gets its own port and Chrome process.--**Q: What happens to my profile when I stop an instance?**-A: Profile is preserved. Stop just closes the browser. You can start the same instance again.--**Q: How do I choose between temporary and named profiles?**-A: Use named profiles when you need to preserve state (logins, settings). Use temporary when testing.--**Q: Can I change the port after starting?**-A: No, port is assigned on start. Stop and restart with a new port if needed.--**Q: How do I know when an instance is ready?**-A: Status transitions from "starting" to "running" when healthy.-------## Related Documentation--- **Profile API** (docs/references/profile-api.md) — Manage browser profiles-- **Tab API** (docs/references/tab-api.md — coming soon) — Control tabs within instances-- **CLI Design** (docs/references/cli-design.md) — CLI command patternsdiff --git a/docs/references/profile-api.md b/docs/references/profile-api.mddeleted file mode 100644index 8746390f..00000000--- a/docs/references/profile-api.md+++ /dev/null@@ -1,838 +0,0 @@-# Profile API Reference--Profiles are browser user data directories. Each profile is an isolated Chrome user data directory where you can log into different accounts, save preferences, and maintain browser state.--## Quick Start--### List Profiles-```bash-# CLI-pinchtab profiles--# Curl-curl http://localhost:9867/profiles | jq .--# Response-[- {- "id": "278be873adeb",- "name": "Pinchtab org",- "created": "2026-02-27T20:37:13.599055326Z",- "diskUsage": 534952089,- "source": "created",- "useWhen": "For gmail related to giago org"- }-]-```--### Create Profile-```bash-# CLI (ready to implement)-pinchtab profile create my-profile--# Curl-curl -X POST http://localhost:9867/profiles \- -H "Content-Type: application/json" \- -d '{- "name": "my-profile",- "description": "For web scraping",- "useWhen": "When extracting data from e-commerce"- }'--# Response-{- "status": "created",- "name": "my-profile"-}-```--### Delete Profile-```bash-# CLI (ready to implement)-pinchtab profile delete my-profile--# Curl-curl -X DELETE http://localhost:9867/profiles/my-profile--# Response-{- "status": "deleted",- "id": "my-profile",- "name": "my-profile"-}-```-------## Complete API Reference--### 1. List Profiles--**Endpoint:** `GET /profiles`--**CLI:**-```bash-pinchtab profiles-```--**Curl:**-```bash-# List all profiles except temporary ones-curl http://localhost:9867/profiles--# Include temporary (auto-generated) profiles-curl 'http://localhost:9867/profiles?all=true'-```--**Response:** Array of ProfileInfo objects-```json-[- {- "id": "278be873adeb",- "name": "Pinchtab org",- "created": "2026-02-27T20:37:13.599055326Z",- "diskUsage": 534952089,- "source": "created",- "running": false,- "accountEmail": "[email protected]",- "accountName": "Luigi Agosti",- "chromeProfileName": "Your Chrome",- "hasAccount": true,- "useWhen": "For gmail related to giago org",- "description": ""- }-]-```--**Query Parameters:**-- `all` (boolean, optional, default: false) — Include temporary profiles created by instances-------### 2. Get Single Profile--**Endpoint:** `GET /profiles/{id}`--**Parameters:**-- `id` (string, path) — Profile ID (hash like `278be873adeb`) or name (like `my-profile`)--**Curl:**-```bash-# By ID-curl http://localhost:9867/profiles/278be873adeb--# By name (spaces are URL-encoded)-curl 'http://localhost:9867/profiles/Pinchtab%20org'-```--**Response:** Single ProfileInfo object-```json-{- "id": "278be873adeb",- "name": "Pinchtab org",- "created": "2026-02-27T20:37:13.599055326Z",- "diskUsage": 534952089,- "source": "created",- "running": false,- "accountEmail": "[email protected]",- "accountName": "Luigi Agosti",- "chromeProfileName": "Your Chrome",- "hasAccount": true,- "useWhen": "For gmail related to giago org",- "description": ""-}-```-------### 3. Create Profile--**Endpoint:** `POST /profiles`--**Parameters:** JSON body--**Curl:**-```bash-# Minimal (name only)-curl -X POST http://localhost:9867/profiles \- -H "Content-Type: application/json" \- -d '{"name": "my-profile"}'--# Full (with metadata)-curl -X POST http://localhost:9867/profiles \- -H "Content-Type: application/json" \- -d '{- "name": "scraping-profile",- "description": "Used for production web scraping",- "useWhen": "When extracting data from e-commerce sites"- }'-```--**Request Body:**-```json-{- "name": "my-profile",- "description": "Optional description",- "useWhen": "Helps agents pick the right profile"-}-```--**Response:**-```json-{- "status": "created",- "name": "my-profile"-}-```--**Validation:**-- `name` is required and must be unique-- Special characters and spaces are allowed in names-- If name already exists, returns 400 error-------### 4. Update Profile--**Endpoint:** `PATCH /profiles/{id}`--**Parameters:**-- `id` (string, path) — Profile ID (e.g. `prof_abc123`). Name is not accepted.-- `name` (string, body, optional) — New name for the profile (rename)-- `description` (string, body, optional) — Profile description-- `useWhen` (string, body, optional) — Use case guidance for agents--**Curl:**-```bash-# Update metadata-curl -X PATCH http://localhost:9867/profiles/prof_abc123 \- -H "Content-Type: application/json" \- -d '{- "description": "Updated description",- "useWhen": "Updated use case"- }'--# Rename a profile-curl -X PATCH http://localhost:9867/profiles/prof_abc123 \- -H "Content-Type: application/json" \- -d '{"name": "new-name"}'-```--**Request Body:**-```json-{- "name": "new-profile-name",- "description": "New description for the profile",- "useWhen": "New use case guidance"-}-```--**Response:**-```json-{- "status": "updated",- "id": "prof_def456",- "name": "new-profile-name"-}-```--**Notes:**-- Only provided fields are updated-- Can omit any field to update only the others-- **Must use profile ID, not name** — returns 404 if name is used-- Renaming updates both the profile name and generates a new ID-- Returns 409 Conflict if the new name already exists-------### 5. Delete Profile--**Endpoint:** `DELETE /profiles/{id}`--**Parameters:**-- `id` (string, path) — Profile ID (e.g. `prof_abc123`). Name is not accepted.--**CLI:**-```bash-pinchtab profile delete prof_abc123-```--**Curl:**-```bash-curl -X DELETE http://localhost:9867/profiles/prof_abc123-```--**Response:**-```json-{- "status": "deleted",- "id": "prof_abc123",- "name": "my-profile"-}-```--**Notes:**-- **Must use profile ID, not name** — returns 404 if name is used-- Recursively deletes entire profile directory-- Returns 404 if profile not found-- Deletion is permanent and cannot be undone-------### 6. Reset Profile--**Endpoint:** `POST /profiles/{id}/reset`--**Parameters:**-- `id` (string, path) — Profile ID (e.g. `prof_abc123`). Name is not accepted.--**Curl:**-```bash-curl -X POST http://localhost:9867/profiles/prof_abc123/reset-```--**Response:**-```json-{- "status": "reset",- "id": "prof_abc123",- "name": "my-profile"-}-```--**What Gets Cleared:**-- Sessions-- Session Storage-- Cache-- Code Cache-- GPUCache-- Service Worker-- Cookies-- Cookies-journal-- History-- Visited Links--**Notes:**-- Profile directory structure remains-- User can re-login after reset-- Useful before sharing profile or starting fresh-------### 7. Get Profile Logs--**Endpoint:** `GET /profiles/{id}/logs`--**Parameters:**-- `id` (string, path) — Profile ID or name-- `limit` (int, query, optional, default: 100) — Max number of log entries--**Curl:**-```bash-# Last 50 actions-curl 'http://localhost:9867/profiles/my-profile/logs?limit=50'--# All logs-curl 'http://localhost:9867/profiles/my-profile/logs?limit=1000'-```--**Response:** Array of ActionRecord objects-```json-[- {- "timestamp": "2026-03-01T05:12:45Z",- "action": "navigate",- "url": "https://pinchtab.com"- },- {- "timestamp": "2026-03-01T05:12:50Z",- "action": "click",- "selector": "e5"- },- {- "timestamp": "2026-03-01T05:12:55Z",- "action": "type",- "text": "search query"- }-]-```--**Actions Include:**-- navigate, click, type, press, fill, hover, scroll, select, focus-- screenshot, snapshot, pdf, evaluate-- And more (see ActivityTracker)-------### 8. Get Profile Analytics--**Endpoint:** `GET /profiles/{id}/analytics`--**Parameters:**-- `id` (string, path) — Profile ID or name--**Curl:**-```bash-curl http://localhost:9867/profiles/my-profile/analytics-```--**Response:** AnalyticsReport object-```json-{- "totalActions": 256,- "averageActionDuration": 2.5,- "topActions": {- "navigate": 128,- "click": 98,- "type": 30- },- "lastUsed": "2026-03-01T05:12:50Z",- "commonHosts": [- "pinchtab.com",- "google.com",- "github.com"- ],- "last24h": {- "actions": 50,- "uniqueHosts": 5- }-}-```--**Insights Provided:**-- Total action count-- Average action duration-- Top 5 most used actions-- Last used timestamp-- Common hosts visited-- 24h activity summary-------### 9. Import Profile--**Endpoint:** `POST /profiles/import`--**Parameters:** JSON body--**Curl:**-```bash-curl -X POST http://localhost:9867/profiles/import \- -H "Content-Type: application/json" \- -d '{- "name": "imported-chrome",- "sourcePath": "/Users/you/Library/Application Support/Google/Chrome/Default",- "description": "Imported from my Chrome browser",- "useWhen": "For existing Chrome accounts"- }'-```--**Request Body:**-```json-{- "name": "chrome-work",- "sourcePath": "/path/to/chrome/profile",- "description": "Optional description",- "useWhen": "Optional use case"-}-```--**Response:**-```json-{- "status": "imported",- "name": "chrome-work"-}-```--**Common Source Paths:**--**macOS:**-```-/Users/<username>/Library/Application Support/Google/Chrome/Default-/Users/<username>/Library/Application Support/Google/Chrome/Profile 1-```--**Linux:**-```-~/.config/google-chrome/Default-~/.config/google-chrome/Profile 1-~/.config/chromium/Default-```--**Windows:**-```-C:\Users\<username>\AppData\Local\Google\Chrome\User Data\Default-C:\Users\<username>\AppData\Local\Chromium\User Data\Default-```--**Validation:**-- Source directory must contain `Default/` subdirectory or `Preferences` file-- Profile name must be unique-- Source must be readable-------## Complete Workflow Examples--### Example 1: Create and Use Profile--```bash-# 1. Create profile-PROF=$(curl -s -X POST http://localhost:9867/profiles \- -H "Content-Type: application/json" \- -d '{"name":"my-work"}' | jq -r .name)--echo "Created profile: $PROF"--# 2. Get profile info-curl -s http://localhost:9867/profiles/$PROF | jq .--# 3. Update profile metadata-curl -s -X PATCH http://localhost:9867/profiles/$PROF \- -H "Content-Type: application/json" \- -d '{"description":"Work account profile"}'--# 4. View profile logs (after use)-curl -s http://localhost:9867/profiles/$PROF/logs | jq length--# 5. Reset before archiving-curl -s -X POST http://localhost:9867/profiles/$PROF/reset--# 6. View final analytics-curl -s http://localhost:9867/profiles/$PROF/analytics | jq .totalActions-```--### Example 2: Import Chrome Profile--```bash-# Find your Chrome profile path-CHROME_PATH="/Users/luigi/Library/Application Support/Google/Chrome/Default"--# Import it-curl -X POST http://localhost:9867/profiles/import \- -H "Content-Type: application/json" \- -d "{- \"name\": \"imported-work\",- \"sourcePath\": \"$CHROME_PATH\",- \"description\": \"Imported from my Chrome\",- \"useWhen\": \"Production accounts\"- }"--# Verify-curl -s http://localhost:9867/profiles/imported-work | jq '{id, name, source}'-```--### Example 3: Manage Multiple Profiles--```bash-#!/bin/bash-# Create profiles for different use cases--for profile in "testing" "staging" "production"; do- echo "Creating profile: $profile"- curl -s -X POST http://localhost:9867/profiles \- -H "Content-Type: application/json" \- -d "{- \"name\": \"$profile\",- \"useWhen\": \"$profile environment\"- }"-done--# List all-echo -e "\nAll profiles:"-curl -s http://localhost:9867/profiles | jq '.[] | {name, useWhen}'--# Get stats for each-echo -e "\nProfile statistics:"-for profile in "testing" "staging" "production"; do- echo -n "$profile: "- curl -s http://localhost:9867/profiles/$profile/analytics | jq .totalActions-done-```--### Example 4: Cleanup Script--```bash-#!/bin/bash-# List temporary profiles and delete them--echo "Temporary profiles:"-TEMP_PROFILES=$(curl -s 'http://localhost:9867/profiles?all=true' | \- jq -r '.[] | select(.temporary == true) | .name')--if [ -z "$TEMP_PROFILES" ]; then- echo "No temporary profiles found"- exit 0-fi--echo "$TEMP_PROFILES"--read -p "Delete these profiles? (y/N) " -n 1 -r-echo-if [[ $REPLY =~ ^[Yy]$ ]]; then- for prof in $TEMP_PROFILES; do- echo "Deleting: $prof"- curl -s -X DELETE http://localhost:9867/profiles/$prof- done-fi-```-------## Error Handling--### Common Errors--**Profile Not Found (404):**-```bash-curl http://localhost:9867/profiles/nonexistent--# Response-{- "error": "profile \"nonexistent\" not found",- "code": "ERR_PROFILE_NOT_FOUND",- "statusCode": 404-}-```--**Profile Already Exists (400):**-```bash-curl -X POST http://localhost:9867/profiles \- -d '{"name":"existing-profile"}'--# Response-{- "error": "profile \"existing-profile\" already exists",- "statusCode": 400-}-```--**Invalid Source Path (400):**-```bash-curl -X POST http://localhost:9867/profiles/import \- -d '{"name":"imp","sourcePath":"/invalid/path"}'--# Response-{- "error": "source path invalid: stat /invalid/path: no such file or directory",- "statusCode": 400-}-```--**Missing Required Field (400):**-```bash-curl -X POST http://localhost:9867/profiles \- -d '{}'--# Response-{- "error": "name required",- "statusCode": 400-}-```-------## Best Practices--### Profile Naming--✅ **Good:**-- `work-email`-- `github-scraper`-- `testing-v2`-- `production-accounts`--❌ **Avoid:**-- Names that are too generic: `test`, `temp`, `profile`-- Very long names (>50 chars)-- Special characters that need URL encoding (use hyphens instead of spaces)--### Using Descriptions and UseWhen--```bash-# Include metadata for team collaboration-curl -X POST http://localhost:9867/profiles \- -d '{- "name": "github-automation",- "description": "For automated GitHub operations",- "useWhen": "When scheduled workflows need to access GitHub repos"- }'-```--This helps:-- Document profile purpose-- Assist AI agents in selecting right profile-- Make maintenance easier--### Profile Isolation--Each profile is completely isolated:-- Separate cookies and sessions-- Independent browser cache-- Isolated browser storage-- No data sharing between profiles--Use different profiles for:-- Different accounts-- Different environments (dev/staging/prod)-- Different projects-- Security isolation--### Cleanup Strategy--```bash-# Reset before switching accounts-curl -X POST http://localhost:9867/profiles/my-profile/reset--# Delete old profiles periodically-curl -X DELETE http://localhost:9867/profiles/old-profile-```-------## Integration Examples--### With Bash--```bash-# Create profile, get ID, use it-PROF_ID=$(curl -s -X POST http://localhost:9867/profiles \- -d '{"name":"test"}' | jq -r .name)--# Use the profile in instance-INST=$(curl -s -X POST http://localhost:9867/instances/start \- -d "{\"profile\":\"$PROF_ID\",\"mode\":\"headed\"}" | jq -r .id)--# Cleanup-curl -s -X DELETE http://localhost:9867/profiles/$PROF_ID-```--### With Python--```python-import requests-import json--BASE = "http://localhost:9867"--# List profiles-profiles = requests.get(f"{BASE}/profiles").json()-print(f"Found {len(profiles)} profiles")--# Create profile-resp = requests.post(f"{BASE}/profiles", json={- "name": "python-test",- "description": "Created from Python"-})-print(f"Created: {resp.json()}")--# Update profile-requests.patch(f"{BASE}/profiles/python-test", json={- "useWhen": "Python integration testing"-})--# Get analytics-analytics = requests.get(f"{BASE}/profiles/python-test/analytics").json()-print(f"Total actions: {analytics.get('totalActions', 0)}")--# Delete profile-requests.delete(f"{BASE}/profiles/python-test")-```--### With JavaScript/Node.js--```javascript-const BASE = "http://localhost:9867";--// List profiles-async function listProfiles() {- const resp = await fetch(`${BASE}/profiles`);- return resp.json();-}--// Create profile-async function createProfile(name) {- const resp = await fetch(`${BASE}/profiles`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name })- });- return resp.json();-}--// Delete profile-async function deleteProfile(id) {- const resp = await fetch(`${BASE}/profiles/${id}`, {- method: "DELETE"- });- return resp.json();-}--// Usage-(async () => {- const prof = await createProfile("js-test");- console.log("Created:", prof);-- const profiles = await listProfiles();- console.log(`Total profiles: ${profiles.length}`);-- await deleteProfile("js-test");- console.log("Deleted");-})();-```-------## Status Codes--| Code | Meaning | Example |-|------|---------|---------|-| **200** | Success (GET, PATCH, POST reset) | Profile retrieved, metadata updated |-| **201** | Created | Profile created (for POST /profiles) |-| **204** | No content | Profile deleted successfully |-| **400** | Bad request | Invalid JSON, missing name, duplicate profile |-| **404** | Not found | Profile doesn't exist |-| **500** | Server error | Internal error |-------## FAQ--**Q: Can I rename a profile?**-A: Yes, use `PATCH /profiles/{id}` with `{"name": "new-name"}` in the request body. You must use the profile ID (e.g. `prof_abc123`), not the profile name.--**Q: Can I move profiles to different machines?**-A: Yes, use POST /profiles/import with the profile directory from another machine.--**Q: How much disk space does a profile use?**-A: Varies, but typically 100MB-1GB per profile. Check `diskUsage` in profile info.--**Q: Can I share profiles between users?**-A: Not recommended. Create separate profiles for isolation and security.--**Q: What happens when I reset a profile?**-A: Cache, cookies, history, and sessions are cleared. You stay logged out.--**Q: Can I recover a deleted profile?**-A: No, deletion is permanent. Always backup important profiles first.--**Q: How do I export a profile?**-A: Copy the profile directory from `~/.pinchtab/profiles/<name>/`.-------## Summary Table--| Operation | Method | Endpoint | Requires |-|-----------|--------|----------|----------|-| List | GET | `/profiles` | None |-| Get | GET | `/profiles/{id}` | ID or name |-| Create | POST | `/profiles` | Name |-| Update | PATCH | `/profiles/{id}` | **ID only** |-| Delete | DELETE | `/profiles/{id}` | **ID only** |-| Reset | POST | `/profiles/{id}/reset` | **ID only** |-| Logs | GET | `/profiles/{id}/logs` | ID or name |-| Analytics | GET | `/profiles/{id}/analytics` | ID or name |-| Import | POST | `/profiles/import` | Name + source path |diff --git a/docs/references/tabs-api.md b/docs/references/tabs-api.mddeleted file mode 100644index dc4df310..00000000--- a/docs/references/tabs-api.md+++ /dev/null@@ -1,914 +0,0 @@-# Tabs API Reference--Tabs are individual browser windows/pages within an instance. Each tab has its own URL, content, and state. Tabs are the primary resource for browser operations in PinchTab.--## Quick Start--### List All Tabs-```bash-# CLI-pinchtab tabs--# Curl-curl http://localhost:9867/tabs | jq .--# Response-[- {- "id": "tab_abc123",- "instanceId": "inst_xyz",- "url": "https://pinchtab.com",- "title": "Example Domain",- "status": "ready"- }-]-```--### Open a New Tab-```bash-# CLI (create new tab in instance)-pinchtab tab open inst_xyz https://pinchtab.com--# Curl-curl -X POST http://localhost:9867/instances/{id}/tabs/open \- -H "Content-Type: application/json" \- -d '{"url": "https://pinchtab.com"}'--# Response-{- "tabId": "tab_abc123",- "url": "https://pinchtab.com",- "title": "Example Domain"-}-```--### Get Tab Info-```bash-# CLI-pinchtab tab info tab_abc123--# Curl-curl http://localhost:9867/tabs/tab_abc123--# Response-{- "id": "tab_abc123",- "instanceId": "inst_xyz",- "url": "https://pinchtab.com",- "title": "Example Domain",- "status": "ready"-}-```--### Close Tab-```bash-# CLI-pinchtab tab close tab_abc123--# Curl-curl -X POST http://localhost:9867/tabs/tab_abc123/close--# Response-{- "id": "tab_abc123",- "status": "closed"-}-```-------## Tab ID Format--Tab IDs use a hash-based format: `tab_XXXXXXXX` (12 characters total).--```-tab_abc12345-└─┬─┘└──┬───┘- │ └── 8-character hash (derived from internal Chrome target ID)- └──────── Prefix identifying resource type-```--### Why Hash IDs?--1. **Security**: Raw Chrome DevTools Protocol (CDP) target IDs are never exposed. This prevents:- - Guessing/brute-forcing tab identifiers- - Cross-instance tab access in multi-instance setups- - Information leakage about Chrome internals--2. **Consistency**: All PinchTab resources use the same format:- - Profiles: `prof_XXXXXXXX`- - Instances: `inst_XXXXXXXX`- - Tabs: `tab_XXXXXXXX`--3. **Stability**: Hash IDs remain stable for the tab's lifetime--### Important--- Only hash-format IDs are accepted by the API-- Raw CDP target IDs (32-character hex strings) are **rejected with 404**-- Tab IDs are scoped to the instance that created them-------## Complete API Reference--### 1. Open Tab--**Endpoint:** `POST /instances/{id}/tabs/open`--**CLI:**-```bash-# Create tab in instance with URL-pinchtab tab open inst_xyz https://pinchtab.com--# Create tab without initial URL-pinchtab tab open inst_xyz-```--**Curl:**-```bash-# Minimal (instanceId only, no URL)-curl -X POST http://localhost:9867/instances/{id}/tabs/open \- -H "Content-Type: application/json" \- -d '{}'--# With URL-curl -X POST http://localhost:9867/instances/{id}/tabs/open \- -H "Content-Type: application/json" \- -d '{"url": "https://pinchtab.com"}'-```--**Request Body:**-```json-{- "url": "https://pinchtab.com"-}-```--**Parameters:**-- `url` (string, optional) — URL to navigate to after opening tab--**Response:** Tab object-```json-{- "tabId": "tab_abc123",- "url": "https://pinchtab.com",- "title": "Example Domain"-}-```--**Defaults:**-- If `url` not provided, tab opens with blank page-- Status is "ready" immediately after creation-------### 2. List All Tabs--**Endpoint:** `GET /tabs`--**CLI:**-```bash-pinchtab tabs-```--**Curl:**-```bash-# List all tabs across all instances-curl http://localhost:9867/tabs | jq .--# Filter by instance-curl 'http://localhost:9867/tabs?instanceId=inst_xyz' | jq .-```--**Query Parameters:**-- `instanceId` (string, optional) — Filter tabs to specific instance--**Response:** Array of Tab objects-```json-[- {- "id": "tab_abc123",- "instanceId": "inst_xyz",- "url": "https://pinchtab.com",- "title": "Example Domain",- "status": "ready",- "createdAt": "2026-03-01T05:25:30Z"- },- {- "id": "tab_def456",- "instanceId": "inst_xyz",- "url": "https://google.com",- "title": "Google",- "status": "ready",- "createdAt": "2026-03-01T05:26:00Z"- }-]-```--**Tab Status Values:**-- `ready` — Tab is loaded and ready to accept commands-- `loading` — Tab is navigating to URL-- `error` — Tab failed to load-------### 3. Get Tab Info--**Endpoint:** `GET /tabs/{id}`--**CLI:**-```bash-pinchtab tab info tab_abc123-```--**Curl:**-```bash-curl http://localhost:9867/tabs/tab_abc123 | jq .-```--**Response:** Single Tab object-```json-{- "id": "tab_abc123",- "instanceId": "inst_xyz",- "url": "https://pinchtab.com",- "title": "Example Domain",- "status": "ready",- "createdAt": "2026-03-01T05:25:30Z"-}-```--**Notes:**-- Returns 404 if tab not found-- Provides full tab state information-------### 4. Close Tab--**Endpoint:** `POST /tabs/{id}/close`--**CLI:**-```bash-pinchtab tab close tab_abc123-```--**Curl:**-```bash-curl -X POST http://localhost:9867/tabs/tab_abc123/close-```--**Response:**-```json-{- "id": "tab_abc123",- "status": "closed"-}-```--**Notes:**-- Gracefully closes tab-- Tab removed from instance-- Returns 404 if tab already closed/not found-------## Complete Workflow Examples--### Example 1: Multi-Tab Workflow--```bash-#!/bin/bash--# Start instance-INST=$(pinchtab instance start --mode headed | jq -r .id)-echo "Instance: $INST"--# Open first tab-TAB1=$(pinchtab tab open $INST https://pinchtab.com | jq -r .id)-echo "Tab 1: $TAB1"--# Open second tab-TAB2=$(pinchtab tab open $INST https://google.com | jq -r .id)-echo "Tab 2: $TAB2"--# List all tabs in instance-echo -e "\nTabs in instance:"-curl -s "http://localhost:9867/tabs?instanceId=$INST" | jq '.[] | {id, url}'--# Get info on tab 1-echo -e "\nTab 1 info:"-pinchtab tab info $TAB1--# Close tab 1-echo -e "\nClosing tab 1..."-pinchtab tab close $TAB1--# Verify closed-echo "Remaining tabs:"-curl -s "http://localhost:9867/tabs?instanceId=$INST" | jq 'length' | xargs echo "Count:"--# Cleanup-pinchtab instance stop $INST-```--### Example 2: Batch Tab Operations--```bash-#!/bin/bash--INST=$1-URLS=(- "https://pinchtab.com"- "https://google.com"- "https://github.com"- "https://stackoverflow.com"-)--echo "Opening $((${#URLS[@]})) tabs in instance $INST..."--TABS=()-for url in "${URLS[@]}"; do- TAB=$(curl -s -X POST "http://localhost:9867/instances/$INST/tabs/open" \- -d "{\"url\":\"$url\"}" | jq -r .tabId)- TABS+=($TAB)- echo "Opened: $TAB"-done--# Wait for loading-sleep 3--# Show all tabs-echo -e "\nAll tabs:"-curl -s "http://localhost:9867/tabs?instanceId=$INST" | jq '.[] | {id, title}'--# Close all-echo -e "\nClosing all tabs..."-for tab in "${TABS[@]}"; do- curl -s -X POST http://localhost:9867/tabs/$tab/close > /dev/null- echo "Closed: $tab"-done-```--### Example 3: Sequential Tab Navigation--```bash-#!/bin/bash--# Start instance with specific profile-PROF="my-profile"-INST=$(curl -s -X POST http://localhost:9867/instances/start \- -d "{\"profileId\":\"$PROF\"}" | jq -r .id)--echo "Started: $INST"--# Create single tab (will be used for all navigation)-TAB=$(pinchtab tab open $INST | jq -r .id)-echo "Tab: $TAB"--# Navigate through multiple sites-SITES=("pinchtab.com" "google.com" "github.com")--for site in "${SITES[@]}"; do- echo "Navigating to $site..."- curl -s -X POST http://localhost:9867/tabs/$TAB/navigate \- -d "{\"url\":\"https://$site\"}" > /dev/null- sleep 2-done--# Cleanup-pinchtab tab close $TAB-pinchtab instance stop $INST-```-------## CLI Examples--### Quick Start with CLI--```bash-# List instances first-pinchtab instances--# Open tab in instance-pinchtab tab open inst_abc123 https://pinchtab.com--# List all tabs-pinchtab tabs--# List tabs in specific instance-pinchtab tabs inst_abc123--# Get tab info-pinchtab tab info tab_xyz789--# Close tab-pinchtab tab close tab_xyz789--# Open multiple tabs-for url in pinchtab.com google.com github.com; do- pinchtab tab open inst_abc123 https://$url-done-```-------## Integration Examples--### With Bash--```bash-# Get instance, create tabs, list them-INST=$(pinchtab instance start --mode headed | jq -r .id)--TAB1=$(curl -s -X POST "http://localhost:9867/instances/$INST/tabs/open" \- -d "{\"url\":\"https://pinchtab.com\"}" | jq -r .tabId)--TAB2=$(curl -s -X POST "http://localhost:9867/instances/$INST/tabs/open" \- -d "{\"url\":\"https://google.com\"}" | jq -r .tabId)--# List tabs-curl -s http://localhost:9867/tabs | jq '.[] | {id, url}'-```--### With Python--```python-import requests-import json--BASE = "http://localhost:9867"--# Start instance-inst_resp = requests.post(f"{BASE}/instances/start", json={"mode": "headed"})-inst_id = inst_resp.json()["id"]-print(f"Instance: {inst_id}")--# Open tabs-for url in ["https://pinchtab.com", "https://google.com"]:- resp = requests.post(f"{BASE}/instances/{inst_id}/tabs/open",- json={"url": url})- tab = resp.json()- print(f"Tab: {tab['tabId']} → {url}")--# List tabs-tabs = requests.get(f"{BASE}/tabs").json()-print(f"\nTotal tabs: {len(tabs)}")-for tab in tabs:- print(f" {tab['id']}: {tab['url']}")--# Close first tab-first_tab = tabs[0]["id"]-requests.post(f"{BASE}/tabs/{first_tab}/close")-print(f"\nClosed: {first_tab}")-```--### With JavaScript/Node.js--```javascript-const BASE = "http://localhost:9867";--async function tabWorkflow() {- // Start instance- const instResp = await fetch(`${BASE}/instances/start`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ mode: "headed" })- });- const inst = await instResp.json();- console.log(`Instance: ${inst.id}`);-- // Open tabs- const urls = ["https://pinchtab.com", "https://google.com"];- const tabs = [];-- for (const url of urls) {- const resp = await fetch(`${BASE}/instances/${inst.id}/tabs/open`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ url })- });- const tab = await resp.json();- tabs.push(tab);- console.log(`Tab: ${tab.tabId} → ${url}`);- }-- // List all tabs- const listResp = await fetch(`${BASE}/tabs`);- const allTabs = await listResp.json();- console.log(`\nTotal tabs: ${allTabs.length}`);-- // Close first tab- const closeResp = await fetch(`${BASE}/tabs/${tabs[0].id}/close`, {- method: "POST"- });- console.log(`Closed: ${tabs[0].id}`);-}--tabWorkflow().catch(console.error);-```-------## Error Handling--### Instance Not Found (404)--```bash-curl -X POST http://localhost:9867/instances/{id}/tabs/open \- -d '{"url":"https://pinchtab.com"}'--# Response (404)-{- "error": "instance not found",- "statusCode": 404-}-```--### Tab Not Found (404)--```bash-curl http://localhost:9867/tabs/nonexistent--# Response (404)-{- "error": "tab not found",- "statusCode": 404-}-```--### Invalid JSON (400)--```bash-curl -X POST http://localhost:9867/instances/{id}/tabs/open -d 'invalid'--# Response (400)-{- "error": "invalid JSON",- "statusCode": 400-}-```-------## Best Practices--### Tab Lifecycle--```bash-# 1. Open tab-TAB=$(pinchtab tab open $INST | jq -r .id)--# 2. Do work (navigate, interact, etc.)-pinchtab tab navigate $TAB https://pinchtab.com--# 3. Get results-pinchtab tab snapshot $TAB--# 4. Close tab-pinchtab tab close $TAB-```--### Resource Management--```bash-# Always close tabs when done-for tab_id in $(pinchtab tabs | jq -r '.[].id'); do- pinchtab tab close $tab_id-done--# Stop instances-pinchtab instance stop $INSTANCE_ID-```--### Error Handling--```bash-# Check if tab exists before operating-if ! pinchtab tab info $TAB_ID > /dev/null 2>&1; then- echo "Tab not found: $TAB_ID"- exit 1-fi--# Handle navigation errors-if ! curl -s -X POST http://localhost:9867/tabs/$TAB_ID/navigate \- -d "{\"url\":\"$url\"}" | jq -e .error > /dev/null; then- echo "Navigation failed"-fi-```-------## Status Codes--| Code | Meaning | Example |-|------|---------|---------|-| **200** | Success (GET) | Tab info retrieved |-| **201** | Created | Tab opened |-| **204** | No content | Tab closed |-| **400** | Bad request | Invalid JSON, missing instanceId |-| **404** | Not found | Tab/instance not found |-| **500** | Server error | Internal error |-------## Tab Lifecycle Diagram--```-OPEN (POST /instances/{id}/tabs/open)- ↓-[status: "ready"] → Ready for commands- ↓-Can navigate, interact, snapshot, etc.- ↓-CLOSE (POST /tabs/{id}/close)- ↓-[status: "closed"] → Tab removed-```-------## Summary Table--| Operation | Method | Endpoint | CLI |-|-----------|--------|----------|-----|-| Open | POST | `/instances/{id}/tabs/open` | `pinchtab tab open <inst> [url]` |-| List All | GET | `/tabs` | `pinchtab tabs` |-| Get Info | GET | `/tabs/{id}` | `pinchtab tab info <id>` |-| Close | POST | `/tabs/{id}/close` | `pinchtab tab close <id>` |-------## FAQ--**Q: How many tabs can I open in an instance?**-A: Technically unlimited, limited only by system resources (memory).--**Q: What happens when I navigate to a new URL in a tab?**-A: URL loads in the same tab. Use a new tab if you want to keep the old page.--**Q: Can I close all tabs at once?**-A: No, close individually. You can script it with a loop.--**Q: What happens to tabs when I stop an instance?**-A: All tabs are closed automatically when instance stops.--**Q: How do I know when a tab is ready after opening?**-A: Check status via GET /tabs/{id} or GET /tabs?instanceId=...--**Q: Can I reopen a closed tab?**-A: No, create a new tab instead.------------## Tab Operations (Phase 4)--Once you have a tab ID, you can perform full browser control operations on it.--### Navigate Tab--**Endpoint:** `POST /tabs/{id}/navigate`--**CLI:**-```bash-pinchtab tab navigate <tab-id> https://pinchtab.com-pinchtab tab navigate <tab-id> https://pinchtab.com --timeout 30-```--**Curl:**-```bash-curl -X POST http://localhost:9867/tabs/tab_abc/navigate \- -d '{"url":"https://pinchtab.com","timeout":30,"blockImages":true}'-```--### Get Snapshot--**Endpoint:** `GET /tabs/{id}/snapshot`--**CLI:**-```bash-pinchtab tab snapshot <tab-id>-pinchtab tab snapshot <tab-id> --interactive --compact-pinchtab tab snapshot <tab-id> -i -c-```--**Curl:**-```bash-curl 'http://localhost:9867/tabs/tab_abc/snapshot?interactive=true&compact=true'-```--### Take Screenshot--**Endpoint:** `GET /tabs/{id}/screenshot`--**CLI:**-```bash-pinchtab tab screenshot <tab-id> -o screenshot.png-pinchtab tab screenshot <tab-id> -o out.jpg -q 85-```--**Curl:**-```bash-curl http://localhost:9867/tabs/tab_abc/screenshot > screenshot.png-```--### Execute Action--**Endpoint:** `POST /tabs/{id}/action`--**CLI:**-```bash-# Click element-pinchtab tab click <tab-id> e5--# Type text-pinchtab tab type <tab-id> e12 "hello world"--# Press key-pinchtab tab press <tab-id> Enter--# Fill input-pinchtab tab fill <tab-id> e12 "value"--# Hover element-pinchtab tab hover <tab-id> e5--# Scroll-pinchtab tab scroll <tab-id> down--# Select dropdown-pinchtab tab select <tab-id> e3 "option2"--# Focus element-pinchtab tab focus <tab-id> e5-```--**Curl:**-```bash-curl -X POST http://localhost:9867/tabs/tab_abc/action \- -d '{"kind":"click","ref":"e5"}'-```--### Execute Multiple Actions--**Endpoint:** `POST /tabs/{id}/actions`--**CLI:**-```bash-# Piped JSON-cat actions.json | pinchtab tab actions <tab-id>--# Inline JSON-pinchtab tab actions <tab-id> --json '[{"kind":"click","ref":"e5"},...]'-```--**Curl:**-```bash-curl -X POST http://localhost:9867/tabs/tab_abc/actions \- -d '{- "actions": [- {"kind":"click","ref":"e5"},- {"kind":"type","ref":"e12","text":"search"},- {"kind":"press","key":"Enter"}- ]- }'-```--### Get Page Text--**Endpoint:** `GET /tabs/{id}/text`--**CLI:**-```bash-pinchtab tab text <tab-id>-pinchtab tab text <tab-id> --raw-```--**Curl:**-```bash-curl http://localhost:9867/tabs/tab_abc/text-```--### Evaluate JavaScript--**Endpoint:** `POST /tabs/{id}/evaluate`--**CLI:**-```bash-pinchtab tab eval <tab-id> "document.title"-pinchtab tab eval <tab-id> "document.querySelectorAll('a').length"-```--**Curl:**-```bash-curl -X POST http://localhost:9867/tabs/tab_abc/evaluate \- -d '{"expression":"document.title"}'-```--### Export to PDF--**Endpoint:** `GET /tabs/{id}/pdf`--**CLI:**-```bash-pinchtab tab pdf <tab-id> -o output.pdf-pinchtab tab pdf <tab-id> -o out.pdf --landscape-```--**Curl:**-```bash-curl 'http://localhost:9867/tabs/tab_abc/pdf?landscape=true' > output.pdf-```--### Manage Cookies--**Endpoint:** `GET /tabs/{id}/cookies` and `POST /tabs/{id}/cookies`--**CLI:**-```bash-pinchtab tab cookies <tab-id> # Get cookies-```--**Curl:**-```bash-curl http://localhost:9867/tabs/tab_abc/cookies-```--### Lock Tab--**Endpoint:** `POST /tabs/{id}/lock`--**CLI:**-```bash-pinchtab tab lock <tab-id> --owner my-agent --ttl 60-```--**Curl:**-```bash-curl -X POST http://localhost:9867/tabs/tab_abc/lock \- -d '{"owner":"my-agent","ttl":60}'-```--### Unlock Tab--**Endpoint:** `POST /tabs/{id}/unlock`--**CLI:**-```bash-pinchtab tab unlock <tab-id> --owner my-agent-```-------## Complete Tab Operation Example--```bash-#!/bin/bash--# Start instance-INST=$(pinchtab instance start --mode headed)-echo "Instance: $INST"--# Create tab-TAB=$(pinchtab tab new $INST | jq -r .id)-echo "Tab: $TAB"--# Navigate-pinchtab tab navigate $TAB https://pinchtab.com-sleep 2--# Get snapshot-pinchtab tab snapshot $TAB -i -c | jq .--# Click element-pinchtab tab click $TAB e5-sleep 1--# Get result-pinchtab tab snapshot $TAB -d--# Extract text-pinchtab tab text $TAB | jq .text--# Take screenshot-pinchtab tab screenshot $TAB -o result.png--# Export PDF-pinchtab tab pdf $TAB -o result.pdf--# Cleanup-pinchtab tab close $TAB-pinchtab instance stop $INST-```-------## Related Documentation--- **Instance API** (docs/references/instance-api.md) — Manage instances-- **Profile API** (docs/references/profile-api.md) — Manage profiles-- **CLI Design** (docs/references/cli-design.md) — CLI command patternsdiff --git a/docs/scheduler-api.md b/docs/scheduler-api.mddeleted file mode 100644index 339e2bc4..00000000--- a/docs/scheduler-api.md+++ /dev/null@@ -1,576 +0,0 @@-# Task Scheduler API--## Overview--The Task Scheduler is an optional queueing layer that accepts browser automation tasks from multiple AI agents, queues them with priority-based fairness, and dispatches them to the existing executor for browser action execution.--This solves a core problem in multi-agent browser automation: when several agents target the same browser, their requests can collide. The scheduler serializes access, enforces per-agent fairness, and provides priority ordering -- all without changing the existing immediate execution path.--**It does not replace anything.** The immediate browsing path (`POST /tabs/{id}/action`) is untouched. The scheduler only activates when explicitly enabled via config and agents use the `/tasks` API.-------## Endpoints--| Method | Path | Status | Description |-|--------|------|--------|-------------|-| `POST /tasks` | Submit a new task | `202` | Task accepted and queued |-| `GET /tasks/{id}` | Get task status | `200` | Returns full task snapshot |-| `POST /tasks/{id}/cancel` | Cancel a task | `200` | Task cancelled |-| `GET /tasks` | List tasks | `200` | Filterable task list |--All endpoints are available on the dashboard (orchestrator) API.-------## Submit a Task--```-POST /tasks-```--### Request Body (JSON)--| Field | Type | Required | Default | Description |-|------------|--------|----------|---------|-------------|-| `agentId` | string | **Yes** | -- | Unique identifier for the submitting agent |-| `action` | string | **Yes** | -- | Action kind to execute (see Action Kinds below) |-| `tabId` | string | No | -- | Target tab ID (hashed `tab_XXXXXXXX` format) |-| `ref` | string | No | -- | Element reference from `/find` or `/snapshot` |-| `params` | object | No | `{}` | Action-specific parameters (see Params below) |-| `priority` | int | No | `0` | Lower number = higher priority; 0 is default |-| `deadline` | string | No | now+60s | RFC 3339 timestamp; task expires if not started by this time |--### Example Request--```json-{- "agentId": "agent-crawl-01",- "action": "click",- "tabId": "tab_a1b2c3d4",- "ref": "e14",- "priority": 5,- "deadline": "2026-03-07T12:05:00Z"-}-```--### Response (202)--```json-{- "taskId": "tsk_a1b2c3d4",- "state": "queued",- "position": 1,- "createdAt": "2026-03-07T12:00:01Z"-}-```--### Response (429 -- Queue Full)--```json-{- "code": "queue_full",- "error": "rejected: global queue full",- "retryable": true,- "details": {- "agentId": "agent-crawl-01",- "queued": 1000,- "maxQueue": 1000,- "maxPerAgent": 100- }-}-```-------## Get Task Status--```-GET /tasks/{id}-```--Returns the full task snapshot including result if completed.--### Response (200)--```json-{- "taskId": "tsk_a1b2c3d4",- "state": "done",- "agentId": "agent-crawl-01",- "action": "click",- "tabId": "tab_a1b2c3d4",- "ref": "e14",- "priority": 5,- "createdAt": "2026-03-07T12:00:01Z",- "startedAt": "2026-03-07T12:00:01Z",- "completedAt": "2026-03-07T12:00:02Z",- "latencyMs": 842,- "result": { "success": true }-}-```--### Response (404)--```json-{- "code": "not_found",- "error": "task not found"-}-```-------## Cancel a Task--```-POST /tasks/{id}/cancel-```--Cancels a queued or running task. Queued tasks are removed from the queue immediately. Running tasks have their context cancelled, which propagates to the executor.--### Response (200)--```json-{- "status": "cancelled",- "taskId": "tsk_a1b2c3d4"-}-```--### Response (409 -- Already Terminal)--```json-{- "code": "conflict",- "error": "task \"tsk_a1b2c3d4\" already in terminal state \"done\""-}-```-------## List Tasks--```-GET /tasks-```--Returns all tasks in the result store. Supports optional query-string filters.--### Query Parameters--| Parameter | Type | Description |-|-----------|--------|-------------|-| `agentId` | string | Filter by agent ID |-| `state` | string | Filter by state (comma-separated: `queued,done,failed`) |--### Example--```-GET /tasks?agentId=agent-crawl-01&state=done,failed-```--### Response (200)--```json-{- "tasks": [- {- "taskId": "tsk_a1b2c3d4",- "state": "done",- "agentId": "agent-crawl-01",- "action": "click",- "latencyMs": 842- }- ],- "count": 1-}-```-------## Action Kinds--The `action` field maps to the same action kinds supported by `POST /tabs/{id}/action`. The scheduler internally translates `action` to `kind` and spreads `params` as top-level fields in the proxied request body.--| Action | Required Params | Optional Params | Description |-|--------------|-----------------|-----------------|-------------|-| `click` | `selector` or `nodeId` | `waitNav` | Click an element |-| `type` | `text`, `selector` or `nodeId` | -- | Type text character by character |-| `fill` | `text`, `selector` or `nodeId` | -- | Set input value directly (faster than type) |-| `press` | `key` | -- | Dispatch a keyboard key (e.g. `"Enter"`, `"Tab"`, `"Backspace"`) |-| `focus` | `selector` or `nodeId` | -- | Focus an element |-| `hover` | `selector` or `nodeId` | -- | Hover over an element |-| `select` | `value` or `text`, `selector` or `nodeId` | -- | Select a dropdown option |-| `scroll` | -- | `scrollX`, `scrollY`, `nodeId` | Scroll the page (default: 800px down) |-| `humanClick` | `selector` or `nodeId` | -- | Human-like click with realistic mouse movement |-| `humanType` | `text`, `selector` or `nodeId` | -- | Human-like typing with variable delays |--### Params Object--Action-specific parameters are passed in the `params` object. These are spread as top-level fields in the request body sent to the executor.--```json-{- "agentId": "my-agent",- "action": "type",- "tabId": "tab_a1b2c3d4",- "params": {- "selector": "input[name='search']",- "text": "Alan Turing"- }-}-```--This becomes the following request to the bridge:--```json-{- "kind": "type",- "selector": "input[name='search']",- "text": "Alan Turing"-}-```-------## Task States--```-queued --> assigned --> running --> done- \--> failed- \--> cancelled- \--> rejected (queue full)-```--| State | Description |-|-------------|-------------|-| `queued` | Waiting in the priority queue |-| `assigned` | Picked up by a worker, about to execute |-| `running` | Currently executing on the browser instance |-| `done` | Completed successfully |-| `failed` | Execution failed (error in `error` field) |-| `cancelled` | Cancelled by the user or by scheduler shutdown |-| `rejected` | Rejected at admission (queue full) |--Terminal states: `done`, `failed`, `cancelled`, `rejected`. Once terminal, a task cannot transition further.-------## Configuration--The scheduler is **disabled by default**. Enable it in the PinchTab config file (`~/.pinchtab/config.json` or `%APPDATA%\pinchtab\config.json`):--```json-{- "scheduler": {- "enabled": true- }-}-```--The scheduler config lives inside the main PinchTab config file alongside other sections (`server`, `browser`, `security`, etc.). No separate config file is needed.--### Full Configuration--```json-{- "scheduler": {- "enabled": true,- "strategy": "fair-fifo",- "maxQueueSize": 1000,- "maxPerAgent": 100,- "maxInflight": 20,- "maxPerAgentInflight": 10,- "resultTTLSec": 300,- "workerCount": 4- }-}-```--| Field | Type | Default | Description |-|---------------------|------|------------|-------------|-| `enabled` | bool | `false` | Master switch for the scheduler |-| `strategy` | str | `fair-fifo`| Scheduling strategy |-| `maxQueueSize` | int | `1000` | Maximum tasks in the global queue |-| `maxPerAgent` | int | `100` | Maximum queued tasks per agent |-| `maxInflight` | int | `20` | Maximum concurrently executing tasks |-| `maxPerAgentInflight`| int | `10` | Maximum concurrent tasks per agent |-| `resultTTLSec` | int | `300` | Seconds to retain completed task results |-| `workerCount` | int | `4` | Number of dispatch worker goroutines |-------## Architecture--```-Agent --> POST /tasks --> Admission (queue limits) --> TaskQueue --> Worker pool --> HTTP proxy --> TabExecutor --> Browser (CDP)- |-Agent <-- GET /tasks/{id} <-- ResultStore (TTL) <----------------------------------------------------done/failed result-```--### Key Design Decisions--- **Fair dispatch** -- per-agent sub-queues with round-robin selection; the agent with fewest in-flight tasks is served first-- **Priority ordering** -- within an agent's queue, lower priority number = higher priority, then FIFO for equal priorities-- **Cooperative cancellation** -- each task gets its own `context.WithCancel()` propagated to the HTTP executor-- **Deadline enforcement** -- background reaper runs every 1s and expires queued tasks past their deadline-- **TTL eviction** -- completed results auto-evict after configurable TTL (default 5 min)-- **Existing executor untouched** -- scheduler dispatches via HTTP proxy to the instance bridge, same path as immediate actions-------## Typical AI Agent Workflow--```-navigate --> submit task --> poll result-```--### Step-by-Step--```jsonc-// Step 1: Navigate to a page-POST /tabs/tab_a1b2c3d4/navigate-{ "url": "https://en.wikipedia.org/wiki/Main_Page" }--// Step 2: Submit a scroll task-POST /tasks-{- "agentId": "wiki-reader",- "action": "scroll",- "tabId": "tab_a1b2c3d4",- "params": { "scrollY": 400 },- "priority": 5-}-// --> { "taskId": "tsk_e7f8a9b0", "state": "queued", "position": 1 }--// Step 3: Poll for completion-GET /tasks/tsk_e7f8a9b0-// --> { "state": "done", "latencyMs": 142 }--// Step 4: Submit a click task-POST /tasks-{- "agentId": "wiki-reader",- "action": "click",- "tabId": "tab_a1b2c3d4",- "params": { "selector": "a.mw-redirect" },- "priority": 5-}-// --> { "taskId": "tsk_c2d3e4f5", "state": "queued" }--// Step 5: Poll for completion-GET /tasks/tsk_c2d3e4f5-// --> { "state": "done", "latencyMs": 312 }-```--### Using with `/find`--The scheduler works well with the `/find` endpoint. Use `/find` to locate elements by natural language, then pass the `ref` to a scheduled task:--```jsonc-// Find the search box-POST /tabs/tab_a1b2c3d4/find-{ "query": "search input" }-// --> { "best_ref": "e7", "confidence": "high", "score": 0.91 }--// Submit a type task using the ref-POST /tasks-{- "agentId": "wiki-reader",- "action": "type",- "tabId": "tab_a1b2c3d4",- "ref": "e7",- "params": { "text": "Alan Turing" }-}-```-------## Multi-Agent Fairness--When multiple agents submit tasks for the same browser, the scheduler ensures fair access:--```jsonc-// Agent A submits 3 tasks-POST /tasks { "agentId": "agent-a", "action": "scroll", ... }-POST /tasks { "agentId": "agent-a", "action": "click", ... }-POST /tasks { "agentId": "agent-a", "action": "scroll", ... }--// Agent B submits 1 task-POST /tasks { "agentId": "agent-b", "action": "type", ... }-```--The scheduler round-robin dequeues across agents, favoring the agent with fewer in-flight tasks. Agent B's single task won't be starved behind Agent A's three tasks.-------## Error Handling--| Status | Condition | Response Body |-|--------|-----------|---------------|-| `202` | Task accepted | `{"taskId": "...", "state": "queued"}` |-| `400` | Missing `agentId` or `action` | `{"error": "invalid task: agentId is required"}` |-| `400` | Invalid deadline format | `{"error": "invalid deadline format: ..."}` |-| `400` | Deadline in the past | `{"error": "deadline is in the past"}` |-| `404` | Task ID not found | `{"code": "not_found", "error": "task not found"}` |-| `409` | Cancel on terminal task | `{"code": "conflict", "error": "...already in terminal state..."}` |-| `429` | Queue is full | `{"code": "queue_full", "retryable": true, ...}` |-------## Performance Characteristics--- **Throughput**: worker pool dispatches up to `workerCount` (default 4) tasks concurrently-- **Latency overhead**: queue + dispatch adds < 5ms over direct execution-- **Deadline reaper**: runs every 1 second, expires stale queued tasks-- **Result TTL**: completed results are evicted after 5 minutes (configurable)-- **No external dependencies**: pure Go, no message brokers or databases required-- **Memory**: all state is in-memory; tasks are garbage collected after TTL expiry-------## Manual Integration Test Results--**Run at:** 2026-03-08 01:05:38-**Server:** `http://localhost:9867`-**Instance:** `inst_39b1eef5` (port 9868)--### Websites Tested--| Website | Actions Tested |-|---------|---------------|-| Wikipedia (en.wikipedia.org) | scroll, click, hover, focus, type, press |-| Hacker News (news.ycombinator.com) | click, scroll, press (back navigation) |-| GitHub (github.com/explore) | scroll, click, type, press |-| httpbin.org (forms/post) | fill (text fields), click (radio, checkbox, submit) |-| DuckDuckGo (duckduckgo.com) | humanClick, humanType, press, scroll |--### Action Kinds Exercised--`scroll`, `click`, `hover`, `focus`, `type`, `fill`, `press`, `humanClick`, `humanType`--### Results--| # | Test | Status | Detail |-|---|------|--------|--------|-| 1 | Server is alive | PASS | |-| 2 | Scheduler is enabled | PASS | |-| 3 | Tab discovered | PASS | |-| 4 | Navigate to Wikipedia Main Page | PASS | |-| 5 | Submit: scroll Wikipedia 400px | PASS | |-| 6 | Scroll completed | PASS | state=done |-| 7 | Submit: click In the news anchor | PASS | |-| 8 | Click completed | FAIL | state= (timeout -- element not found by selector) |-| 9 | Submit: hover first paragraph | PASS | |-| 10 | Hover completed | PASS | state=done |-| 11 | Submit: focus search box | PASS | |-| 12 | Focus completed | PASS | state=done |-| 13 | Submit: type 'Alan Turing' | PASS | |-| 14 | Type completed | PASS | state=done |-| 15 | Submit: press Enter | PASS | |-| 16 | Press completed | PASS | state=done |-| 17 | Submit: scroll article (default 800px) | PASS | |-| 18 | Article scroll completed | PASS | state=done |-| 19 | Navigate to Hacker News | PASS | |-| 20 | Submit: click first HN story | PASS | |-| 21 | Click story completed | PASS | state=failed (external link navigation) |-| 22 | Submit: scroll story 600px | PASS | |-| 23 | Story scroll completed | PASS | state=done |-| 24 | Submit: press Backspace (back) | PASS | |-| 25 | Back navigation completed | PASS | state=done |-| 26 | Navigate to GitHub Explore | PASS | |-| 27 | Submit: scroll GitHub Explore | PASS | |-| 28 | Explore scroll completed | PASS | state=done |-| 29 | Submit: click GitHub search button | PASS | |-| 30 | Search button click completed | PASS | state=done |-| 31 | Submit: type 'golang scheduler' | PASS | |-| 32 | Search type completed | PASS | state=done |-| 33 | Submit: press Enter | PASS | |-| 34 | Search submit completed | PASS | state=done |-| 35 | Navigate to httpbin.org forms | PASS | |-| 36 | Submit: fill customer name | PASS | |-| 37 | Fill name completed | PASS | state=done |-| 38 | Submit: fill telephone | PASS | |-| 39 | Fill phone completed | PASS | state=done |-| 40 | Submit: fill email | PASS | |-| 41 | Fill email completed | PASS | state=done |-| 42 | Submit: click medium radio | PASS | |-| 43 | Radio click completed | PASS | state=done |-| 44 | Submit: click cheese checkbox | PASS | |-| 45 | Checkbox click completed | PASS | state=done |-| 46 | Submit: click submit button | PASS | |-| 47 | Form submit completed | PASS | state=failed (page navigated away) |-| 48 | Navigate to Wikipedia CS article | PASS | |-| 49 | reader-1 scroll queued | PASS | |-| 50 | reader-2 scroll queued | PASS | |-| 51 | reader-1 hover queued | PASS | |-| 52 | reader-2 click queued | PASS | |-| 53 | All 4 multi-agent tasks completed | PASS | |-| 54 | Navigate to Sorting Algorithm article | PASS | |-| 55 | Low-priority (99) queued | PASS | |-| 56 | Mid-priority (50) queued | PASS | |-| 57 | High-priority (1) queued | PASS | |-| 58 | All priority tasks completed | PASS | |-| 59 | Task submitted for cancel | PASS | |-| 60 | Cancel returns 200 | FAIL | task executed before cancel reached it |-| 61 | Task state is cancelled | FAIL | state=done (race: task completed before cancel) |-| 62 | Re-cancel returns 409 | PASS | |-| 63 | GET unknown task returns 404 | PASS | |-| 64 | Missing agentId returns 400 | PASS | |-| 65 | Missing action returns 400 | PASS | |-| 66 | Bad deadline returns 400 | PASS | |-| 67 | Past deadline returns 400 | PASS | |-| 68 | Task with future deadline accepted | PASS | |-| 69 | Deadline task completed | PASS | state=done |-| 70 | GET /tasks returns 200 | PASS | |-| 71 | Response has count | PASS | count=30 |-| 72 | Filter by agentId=wiki-reader | PASS | count=7 |-| 73 | Filter by state=cancelled | PASS | count=0 |-| 74 | Filter by agentId=form-agent | PASS | count=6 |-| 75 | Navigate to DuckDuckGo | PASS | |-| 76 | Submit: humanClick search input | PASS | |-| 77 | humanClick completed | PASS | state=done |-| 78 | Submit: humanType search query | PASS | |-| 79 | humanType completed | PASS | state=done |-| 80 | Submit: press Enter | PASS | |-| 81 | Search submitted | PASS | state=done |-| 82 | Submit: scroll results | PASS | |-| 83 | Results scroll completed | PASS | state=done |--**Total: 80 passed, 3 failed / 83 tests**--### Failure Analysis--| # | Test | Cause |-|---|------|-------|-| 8 | Click In the news anchor | The CSS selector `#In_the_news` targets an anchor element that may not exist on all Wikipedia page layouts; timeout waiting for completion |-| 60-61 | Cancel returns 200 / Task state is cancelled | Race condition: the scheduler's worker pool (4 workers) dispatched and completed the task before the cancel request arrived. This is expected behavior -- with a fast local executor and low queue depth, tasks execute nearly instantly. The cancel logic itself is correct (verified by test 62: re-cancel returns 409) |-------## Notes for Developers--### Integration with PinchTab Architecture--1. **Config loading** -- `SchedulerFileConfig` is part of the main `FileConfig` struct in `internal/config/config.go`. The scheduler section is read from the same config file as all other PinchTab settings. No separate config file is needed; just add `"scheduler": {"enabled": true}` to the existing config.--2. **Dashboard wiring** -- in `cmd/pinchtab/cmd_dashboard.go`, the scheduler is conditionally created when `cfg.Scheduler.Enabled == true`. Routes are registered on the shared `http.ServeMux` and the scheduler lifecycle is tied to the server's start/stop.--3. **Instance resolution** -- the scheduler resolves tab IDs to instance ports using `ManagerResolver` (in `resolver.go`), which wraps `instance.Manager.FindInstanceByTabID()`. This is the same resolution the orchestrator uses for immediate actions.--4. **Execution path** -- `executeTask()` builds a request body with `kind` (from `action`) and spreads `params` as top-level fields, then POSTs to `http://localhost:{port}/tabs/{tabId}/action` on the bridge instance. This is identical to the immediate action path.--5. **Existing paths untouched** -- `POST /tabs/{id}/action`, `POST /tabs/{id}/navigate`, and all other existing endpoints continue to work exactly as before. The scheduler is purely additive.--### Source Files--| File | Purpose |-|------|---------|-| `internal/scheduler/task.go` | Task struct, state machine, validation, ID generation |-| `internal/scheduler/queue.go` | Priority queue with per-agent sub-queues and fair round-robin |-| `internal/scheduler/results.go` | TTL-based in-memory result store with background eviction |-| `internal/scheduler/scheduler.go` | Core dispatch engine: worker pool, deadline reaper, HTTP proxy execution |-| `internal/scheduler/handlers.go` | HTTP handlers: submit, get, cancel, list |-| `internal/scheduler/resolver.go` | Adapter bridging `instance.Manager` to `InstanceResolver` interface |-| `internal/scheduler/clock.go` | Testable clock for deterministic unit tests |diff --git a/docs/showcase.md b/docs/showcase.mdindex b7b3a138..11cd8e67 100644--- a/docs/showcase.md+++ b/docs/showcase.md@@ -1,719 +1,234 @@-# API Workflows+# Showcase-Learn the correct way to use PinchTab's API through practical, step-by-step examples.+## Browser for your agents-## Core Concepts: Orchestrator → Instance → Tab+Start the server and one instance first:-PinchTab uses a three-level hierarchy:--```-Orchestrator (port 9867)- ↓-Instance (port 9868+) ← Creates/manages Chrome process- ↓-Tab ← Individual webpage within instance-```--### Why This Design?--- **Multiple instances** enable isolation (separate cookies, history, profiles)-- **Multiple tabs per instance** allow parallel work within same session-- **Orchestrator manages everything** via consistent routing (`/instances/{id}/...`)-- **Complete isolation** — Each instance has its own Chrome process, no resource contention-- **Supports multi-agent workflows** — Agents can coordinate via orchestrator--### Key Principles--1. **Create instance first** (once per workflow or reused)-2. **Create tabs within instance** (multiple tabs per instance)-3. **Use instance-scoped endpoints** (`/instances/{id}/...`)-4. **Stop instance when done** (cleanup, free resources)-------## The Complete Workflow Pattern--Every PinchTab workflow follows this pattern:--```-1. Create instance → Get instId- ↓-2. Create tab (navigate) → Get tabId- ↓-3. Interact with tab (snapshot, click, type, eval)- ↓-4. Verify results (snapshot again, screenshot)- ↓-5. Stop instance (cleanup)+```bash+pinchtab```------## Workflow 1: Text Extraction (Simplest)--**Goal:** Get readable text from a webpage.--### Step-by-Step--**Step 1: Create instance**```bash-curl -X POST http://localhost:9867/instances/launch \+curl -s -X POST http://127.0.0.1:9867/instances/start \-H "Content-Type: application/json" \- -d '{"mode":"headless"}'-```--**Response:**-```json+ -d '{"mode":"headless"}' | jq .+# CLI Alternative+pinchtab instance start+# Response{- "id": "inst_abc123",+ "id": "inst_0a89a5bb",+ "profileId": "prof_278be873",+ "profileName": "instance-1741400000000000000","port": "9868",+ "headless": true,"status": "starting"}```-**Step 2: Wait for Chrome to initialize**-```bash-sleep 2-```--**Step 3: Create tab and navigate to URL (returns tabId)**-```bash-TAB=$(curl -s -X POST http://localhost:9867/instances/inst_abc123/tabs/open \- -H "Content-Type: application/json" \- -d '{"url":"https://pinchtab.com"}' | jq -r '.id')--echo "Tab created: $TAB"-```+Starting an instance may be optional, depending on strategy/config.-**Response contains:**-```json-{- "id": "tab_def456",- "title": "Example Domain",- "url": "https://pinchtab.com/"-}-```+### Navigate-**Step 4: Extract text (use tabId)**```bash-curl "http://localhost:9867/tabs/$TAB/text"-```--**Response:**-```json+curl -s -X POST http://127.0.0.1:9867/navigate \+ -H "Content-Type: application/json" \+ -d '{"url":"https://github.com/pinchtab/pinchtab"}' | jq .+# CLI Alternative+pinchtab nav https://github.com/pinchtab/pinchtab+# Response{- "text": "Example Domain\nThis domain is for use in examples...",- "length": 234+ "tabId": "CDP_TARGET_ID",+ "title": "GitHub - pinchtab/pinchtab",+ "url": "https://github.com/pinchtab/pinchtab"}```-**Complete script:**-```bash-#!/bin/bash-URL="https://pinchtab.com"--# Step 1: Create instance-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')--echo "Created instance: $INST"--# Step 2: Wait for Chrome initialization-sleep 2--# Step 3: Create tab by navigating-TAB=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -H "Content-Type: application/json" \- -d "{\"url\":\"$URL\"}" | jq -r '.id')--echo "Created tab: $TAB"--# Step 4: Get text-echo "Extracting text from $URL..."-curl -s "http://localhost:9867/tabs/$TAB/text" | jq '.text'--# Step 5: Cleanup-curl -s -X POST "http://localhost:9867/instances/$INST/stop"-echo "Stopped instance: $INST"-```-----+### Snapshot-## Workflow 2: Snapshot + Click (Interaction)--**Goal:** See page structure, click an element, verify the change.--### Step-by-Step--**Step 1: Create instance and navigate to get tabId**-```bash-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')--sleep 2--TAB=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -H "Content-Type: application/json" \- -d '{"url":"https://pinchtab.com/interactive"}' | jq -r '.id')--echo "Instance: $INST, Tab: $TAB"-```--**Step 2: Get snapshot (see interactive elements)**```bash-curl "http://localhost:9867/tabs/$TAB/snapshot"-```--**Response:**-```json+curl -s "http://127.0.0.1:9867/snapshot?filter=interactive" | jq .+# CLI Alternative+pinchtab snap -i -c+# Response{"nodes": [- {- "ref": "e0",- "role": "heading",- "name": "Interactive Page"- },- {- "ref": "e5",- "role": "button",- "name": "Click Me!"- },- {- "ref": "e8",- "role": "link",- "name": "Learn More"- }+ { "ref": "e0", "role": "link", "name": "Skip to content" },+ { "ref": "e1", "role": "link", "name": "GitHub Homepage" },+ { "ref": "e14", "role": "button", "name": "Search or jump to…" }]}```-**Step 3: Click element**-```bash-curl -X POST http://localhost:9867/tabs/$TAB/action \- -H "Content-Type: application/json" \- -d '{"action":"click","ref":"e5"}'-```--**Step 4: Verify result**-```bash-curl "http://localhost:9867/tabs/$TAB/snapshot" | jq '.nodes'-```+### Extract Text-**Complete script:**```bash-#!/bin/bash-URL="https://pinchtab.com/interactive"--# Step 1: Create instance-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')--echo "Instance: $INST"--# Step 2: Wait and navigate to create tab-sleep 2-TAB=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -H "Content-Type: application/json" \- -d "{\"url\":\"$URL\"}" | jq -r '.id')--echo "Tab: $TAB"--# Step 3: Get interactive elements-echo "Getting interactive elements..."-SNAPSHOT=$(curl -s "http://localhost:9867/tabs/$TAB/snapshot")-echo "$SNAPSHOT" | jq '.nodes[] | select(.role | IN("button", "link")) | {ref, name}'--# Step 4: Click button-echo "Clicking button e5..."-curl -s -X POST http://localhost:9867/tabs/$TAB/action \- -H "Content-Type: application/json" \- -d '{"action":"click","ref":"e5"}'--# Step 5: Wait for action and verify-sleep 1-echo "Verifying result..."-curl -s "http://localhost:9867/tabs/$TAB/snapshot" | jq '.nodes[] | {ref, role, name}' | head -10--# Step 6: Cleanup-curl -s -X POST "http://localhost:9867/instances/$INST/stop"-echo "Stopped instance: $INST"+curl -s http://127.0.0.1:9867/text | jq .+# CLI Alternative+pinchtab text+# Response+{+ "text": "High-performance browser automation bridge and multi-instance orchestrator...",+ "title": "GitHub - pinchtab/pinchtab",+ "url": "https://github.com/pinchtab/pinchtab"+}```------## Workflow 3: Form Filling+### Click By Ref-**Goal:** Fill a form and submit it.--### Step-by-Step--**Step 1: Create instance and navigate to form**```bash-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')--sleep 2--TAB=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \+curl -s -X POST http://127.0.0.1:9867/action \-H "Content-Type: application/json" \- -d '{"url":"https://pinchtab.com/login"}' | jq -r '.id')--echo "Instance: $INST, Tab: $TAB"-```--**Step 2: Get form fields**-```bash-curl -s "http://localhost:9867/tabs/$TAB/snapshot" | jq '.nodes[] | select(.role | IN("textbox", "button"))'-```--**Output:**-```json-{- "ref": "e3",- "role": "textbox",- "name": "Email"-}+ -d '{"kind":"click","ref":"e14"}' | jq .+# CLI Alternative+pinchtab click e14+# Response{- "ref": "e5",- "role": "textbox",- "name": "Password"-}-{- "ref": "e7",- "role": "button",- "name": "Sign In"+ "success": true,+ "result": {+ "clicked": true+ }}```-**Step 3: Fill email field**-```bash-curl -X POST http://localhost:9867/tabs/$TAB/action \- -H "Content-Type: application/json" \- -d '{"action":"fill","ref":"e3","text":"[email protected]"}'-```+### Screenshot-**Step 4: Fill password field**```bash-curl -X POST http://localhost:9867/tabs/$TAB/action \- -H "Content-Type: application/json" \- -d '{"action":"fill","ref":"e5","text":"mypassword"}'+curl -s http://127.0.0.1:9867/screenshot > smoke.jpg+ls -lh smoke.jpg+# CLI Alternative+pinchtab ss -o smoke.jpg+# Response+Saved smoke.jpg (55876 bytes)```-**Step 5: Click submit**-```bash-curl -X POST http://localhost:9867/tabs/$TAB/action \- -H "Content-Type: application/json" \- -d '{"action":"click","ref":"e7"}'-```+### Export a PDF-**Step 6: Verify success (check page)**```bash-curl -s "http://localhost:9867/tabs/$TAB/text" | jq '.text'+curl -s http://127.0.0.1:9867/pdf > smoke.pdf+ls -lh smoke.pdf+# CLI Alternative+pinchtab pdf -o smoke.pdf+# Response+Saved smoke.pdf (1494657 bytes)```-**Complete script:**-```bash-#!/bin/bash--# Step 1: Create instance-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')--echo "Instance: $INST"--# Step 2: Wait and navigate (capture tabId)-sleep 2-TAB=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -H "Content-Type: application/json" \- -d '{"url":"https://pinchtab.com/login"}' | jq -r '.id')--echo "Tab: $TAB"--# Step 3: Get form fields-echo "Getting form fields..."-curl -s "http://localhost:9867/tabs/$TAB/snapshot" | \- jq '.nodes[] | select(.role | IN("textbox", "button")) | {ref, name}'--# Step 4: Fill email-curl -s -X POST http://localhost:9867/tabs/$TAB/action \- -H "Content-Type: application/json" \- -d '{"action":"fill","ref":"e3","text":"[email protected]"}'--# Step 5: Fill password-curl -s -X POST http://localhost:9867/tabs/$TAB/action \- -H "Content-Type: application/json" \- -d '{"action":"fill","ref":"e5","text":"mypassword"}'+## Automation tool for the web-# Step 6: Click submit-echo "Submitting form..."-curl -s -X POST http://localhost:9867/tabs/$TAB/action \- -H "Content-Type: application/json" \- -d '{"action":"click","ref":"e7"}'+Use PinchTab as a scriptable browser endpoint for repeatable web tasks.-# Step 7: Wait for page load-sleep 2--# Step 8: Check result-echo "Login result:"-curl -s "http://localhost:9867/tabs/$TAB/text" | jq '.text' | head -5--# Step 9: Cleanup-curl -s -X POST "http://localhost:9867/instances/$INST/stop"-echo "Stopped instance: $INST"-```+### Fill a form field------## Workflow 4: Multi-Tab Coordination--**Goal:** Work with multiple tabs simultaneously within one instance.--### Step-by-Step--**Step 1: Create instance**```bash-INST=$(curl -s -X POST http://localhost:9867/instances/launch \+curl -s -X POST http://127.0.0.1:9867/action \-H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')--sleep 2-```--**Step 2: Create first tab**-```bash-TAB1=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -H "Content-Type: application/json" \- -d '{"url":"https://github.com"}' | jq -r '.id')--echo "Tab 1: $TAB1"-```--**Step 3: Create second tab**-```bash-TAB2=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -H "Content-Type: application/json" \- -d '{"url":"https://stackoverflow.com"}' | jq -r '.id')--echo "Tab 2: $TAB2"-```--**Step 4: List all tabs in instance**-```bash-curl -s "http://localhost:9867/instances/$INST/tabs" | jq '.[] | {id, title, url}'+ -d '{"kind":"fill","ref":"e3","text":"[email protected]"}' | jq .+# CLI Alternative+pinchtab fill e3 "[email protected]"+# Response+{+ "success": true,+ "result": {+ "filled": "[email protected]"+ }+}```-**Step 5: Get snapshot from each tab**-```bash-# Get content from Tab 1-curl -s "http://localhost:9867/tabs/$TAB1/snapshot" | jq '.nodes | length'--# Get content from Tab 2-curl -s "http://localhost:9867/tabs/$TAB2/snapshot" | jq '.nodes | length'-```+### Press a key-**Step 6: Interact with tabs**```bash-# Click on element in Tab 1-curl -s -X POST http://localhost:9867/tabs/$TAB1/action \- -H "Content-Type: application/json" \- -d '{"action":"click","ref":"e5"}'--# Click on element in Tab 2-curl -s -X POST http://localhost:9867/tabs/$TAB2/action \+curl -s -X POST http://127.0.0.1:9867/action \-H "Content-Type: application/json" \- -d '{"action":"click","ref":"e3"}'--# Take screenshot of Tab 1-curl "http://localhost:9867/tabs/$TAB1/screenshot" -o screenshot1.png-```--**Complete script:**-```bash-#!/bin/bash--# Step 1: Create instance-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')--echo "Instance: $INST"--# Step 2: Wait for initialization-sleep 2--# Step 3: Create tabs-echo "Creating tabs..."-TAB1=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -H "Content-Type: application/json" \- -d '{"url":"https://github.com"}' | jq -r '.id')--TAB2=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -H "Content-Type: application/json" \- -d '{"url":"https://stackoverflow.com"}' | jq -r '.id')--echo "Tab 1: $TAB1"-echo "Tab 2: $TAB2"--# Step 4: List tabs-echo "Tabs in instance:"-curl -s "http://localhost:9867/instances/$INST/tabs" | jq '.[] | {id, title, url}'--# Step 5: Get content from Tab 1-echo "Content from Tab 1:"-curl -s "http://localhost:9867/tabs/$TAB1/text" | jq '.text' | head -3--# Step 6: Get snapshots from both tabs-echo "Getting snapshots..."-echo "Tab 1 nodes: $(curl -s "http://localhost:9867/tabs/$TAB1/snapshot" | jq '.nodes | length')"-echo "Tab 2 nodes: $(curl -s "http://localhost:9867/tabs/$TAB2/snapshot" | jq '.nodes | length')"--# Step 7: Interact with elements in each tab-echo "Clicking element in Tab 1..."-curl -s -X POST http://localhost:9867/tabs/$TAB1/action \- -H "Content-Type: application/json" \- -d '{"action":"click","ref":"e5"}'--echo "Clicking element in Tab 2..."-curl -s -X POST http://localhost:9867/tabs/$TAB2/action \- -H "Content-Type: application/json" \- -d '{"action":"click","ref":"e3"}'--# Step 8: Take screenshots of each tab-echo "Taking screenshots..."-curl "http://localhost:9867/tabs/$TAB1/screenshot" -o /tmp/tab1.png-curl "http://localhost:9867/tabs/$TAB2/screenshot" -o /tmp/tab2.png--# Step 9: Cleanup-curl -s -X POST "http://localhost:9867/instances/$INST/stop"-echo "Stopped instance: $INST"+ -d '{"kind":"press","key":"Enter"}' | jq .+# CLI Alternative+pinchtab press Enter+# Response+{+ "success": true,+ "result": {+ "pressed": "Enter"+ }+}```------## Workflow 5: PDF Export--**Goal:** Generate a PDF from a webpage.--### Step-by-Step--**Step 1: Create instance and navigate to create tab**-```bash-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')--sleep 2--TAB=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -H "Content-Type: application/json" \- -d '{"url":"https://pinchtab.com/report"}' | jq -r '.id')--echo "Instance: $INST, Tab: $TAB"-```+### Generate artifacts-**Step 2: Generate PDF (use tabId)**```bash-curl "http://localhost:9867/tabs/$TAB/pdf?landscape=true" \- -o report.pdf+curl -s http://127.0.0.1:9867/pdf > report.pdf+ls -lh report.pdf+# CLI Alternative+pinchtab pdf -o report.pdf+# Response+Saved report.pdf (1494657 bytes)```-**Complete script:**```bash-#!/bin/bash--# Step 1: Create instance-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')--echo "Instance: $INST"--# Step 2: Wait for initialization-sleep 2--# Step 3: Navigate to report page-echo "Navigating to report page..."-TAB=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \- -H "Content-Type: application/json" \- -d '{"url":"https://pinchtab.com/report"}' | jq -r '.id')--echo "Tab: $TAB"--# Step 4: Generate PDF with options-echo "Generating PDF..."-curl -s "http://localhost:9867/tabs/$TAB/pdf?landscape=true&displayHeaderFooter=true" \- -o report.pdf--echo "PDF saved: report.pdf"--# Step 5: Take screenshot for preview-echo "Taking preview screenshot..."-curl -s "http://localhost:9867/tabs/$TAB/screenshot" -o /tmp/report_preview.png--# Step 6: Cleanup-curl -s -X POST "http://localhost:9867/instances/$INST/stop"-echo "Stopped instance: $INST"+curl -s http://127.0.0.1:9867/screenshot > page.jpg+ls -lh page.jpg+# CLI Alternative+pinchtab ss -o page.jpg+# Response+Saved page.jpg (55876 bytes)```----+This fits:-## Common Mistakes & Solutions+- browser-driven scripts+- content extraction and reporting+- visual checks and artifacts+- automation tools that need a local browser endpoint-### ❌ Mistake 1: Forgetting to create instance first+## Human-agent development surface-```bash-# WRONG - instance doesn't exist yet-curl "http://localhost:9867/instances/$INST/snapshot"+When Chrome is already running in remote-debugging mode, PinchTab can attach to it and expose it through the same API.-# CORRECT - create instance, wait, then use-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')-sleep 2-curl "http://localhost:9867/instances/$INST/snapshot"-```--### ❌ Mistake 2: Not waiting for Chrome initialization+### 1. Start Chrome with remote debugging```bash-# WRONG - instance starts but Chrome isn't ready yet-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')--curl -X POST http://localhost:9867/instances/$INST/tabs/open \- -d '{"url":"https://pinchtab.com"}' # Likely timeout or error--# CORRECT - wait for Chrome-sleep 2+google-chrome --remote-debugging-port=9222+# Or on some systems:+# chromium --remote-debugging-port=9222```-### ❌ Mistake 3: Not extracting instance ID from response+### 2. Read the browser CDP URL```bash-# WRONG - trying to use JSON object as instance ID-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}')--# CORRECT - extract with jq-INST=$(curl -s -X POST http://localhost:9867/instances/launch \- -H "Content-Type: application/json" \- -d '{"mode":"headless"}' | jq -r '.id')+curl -s http://127.0.0.1:9222/json/version | jq .+# Response+{+ "webSocketDebuggerUrl": "ws://127.0.0.1:9222/devtools/browser/abc123"+}```-### ❌ Mistake 4: Using refs from old snapshots+### 3. Attach that browser to PinchTab```bash-# WRONG - page changed, e5 no longer a button-curl "http://localhost:9867/tabs/$TAB/snapshot" > snapshot1.json-# ... do something ...-curl -X POST http://localhost:9867/tabs/$TAB/action \- -H "Content-Type: application/json" \- -d '{"action":"click","ref":"e5"}'+CDP_URL=$(curl -s http://127.0.0.1:9222/json/version | jq -r '.webSocketDebuggerUrl')-# CORRECT - get fresh snapshot before clicking-curl "http://localhost:9867/tabs/$TAB/snapshot" > snapshot2.json-# Read refs from snapshot2.json-curl -X POST http://localhost:9867/tabs/$TAB/action \+curl -s -X POST http://127.0.0.1:9867/instances/attach \-H "Content-Type: application/json" \- -d '{"action":"click","ref":"e7"}'-```--### ❌ Mistake 5: Forgetting to stop instances--```bash-# WRONG - instances accumulate, wasting resources-INST1=$(curl -s -X POST http://localhost:9867/instances/launch ...)-INST2=$(curl -s -X POST http://localhost:9867/instances/launch ...)-# ... do work, then exit script ...-# Instances still running!--# CORRECT - stop when done-curl -X POST http://localhost:9867/instances/$INST1/stop-curl -X POST http://localhost:9867/instances/$INST2/stop-```-------## Key Takeaways--1. **Create instance first** — Every workflow starts with creating an instance-2. **Wait for Chrome** — Sleep 2 seconds to allow lazy initialization-3. **Extract instance ID** — Use jq: `jq -r '.id'`-4. **Use tab-scoped paths for tab work** — Prefer `/tabs/{id}/...` for navigate/snapshot/screenshot/pdf-5. **Get fresh snapshots** — Refs change when page updates; get new snapshot-6. **Stop instances** — Clean up when done to free resources-7. **Chain operations** — Create instance → Navigate → Snapshot → Click → Snapshot → Stop-------## Quick Reference: When to Use Each Endpoint--| Goal | Endpoint | Notes |-|------|----------|-------|-| Create instance | `POST /instances/launch` | Returns instance ID |-| Navigate | `POST /tabs/{id}/navigate` | Navigates a specific tab |-| See page structure | `GET /tabs/{id}/snapshot` | Returns DOM nodes + refs |-| Click/type/press | `POST /tabs/{id}/action` | Use ref from snapshot |-| Extract text | `GET /tabs/{id}/text` | Returns readable text |-| Run JavaScript | `POST /tabs/{id}/evaluate` | Returns JSON result |-| Screenshot | `GET /tabs/{id}/screenshot` | Returns JPEG image |-| PDF export | `GET /tabs/{id}/pdf` | Returns PDF file |-| List tabs | `GET /instances/{id}/tabs` | All tabs in instance |-| New tab | `POST /instances/{id}/tabs/open` | Open URL in new tab |-| Stop instance | `POST /instances/{id}/stop` | Cleanup, free resources |-------## Debugging Tips--### Check if instance is running-```bash-curl http://localhost:9867/instances/$INST | jq '.status'-```--### Get instance logs-```bash-curl http://localhost:9867/instances/$INST/logs-```--### List all running instances-```bash-curl http://localhost:9867/instances | jq '.[] | {id, status, port}'-```--### Get current page URL and title-```bash-curl -s "http://localhost:9867/instances/$INST/snapshot" | jq '{url, title}'+ -d "{\"name\":\"dev-chrome\",\"cdpUrl\":\"$CDP_URL\"}" | jq .+# Response+{+ "id": "inst_abc12345",+ "profileId": "prof_def67890",+ "profileName": "dev-chrome",+ "attached": true,+ "cdpUrl": "ws://127.0.0.1:9222/devtools/browser/abc123",+ "status": "running"+}```-### See all interactive elements-```bash-curl -s "http://localhost:9867/instances/$INST/snapshot" | \- jq '.nodes[] | select(.role | IN("button", "link", "textbox")) | {ref, name}'-```+### 4. Inspect it through PinchTab-### Wait for instance to be ready```bash-while [ "$(curl -s http://localhost:9867/instances/$INST | jq -r '.status')" != "running" ]; do- sleep 0.5-done-echo "Instance ready!"+curl -s http://127.0.0.1:9867/instances | jq .+# CLI Alternative+pinchtab instances```-----------## For More Information+This is useful when:-- **Instance API:** See [`references/instance-api.md`](references/instance-api.md) for complete endpoint details-- **Tabs API:** See [`references/tabs-api.md`](references/tabs-api.md) for tab management-- **curl Examples:** See [`curl-commands.md`](references/curl-commands.md) for more API examples-- **Core Concepts:** See [`core-concepts.md`](core-concepts.md) to understand instances, profiles, and tabs+- you are developing in a real browser session+- you want an agent to inspect the page you already have open+- you do not want PinchTab to launch a separate managed browser+- you want one local API for both managed and attached browser work