High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor: endpoints consolidation
Luigi Agosti74d9cabea80c
diff --git a/TODO.md b/TODO.mddeleted file mode 100644index ddc29f73..00000000--- a/TODO.md+++ /dev/null@@ -1,479 +0,0 @@-# PinchTab API Refactoring TODO--## Overview--Refactor from deeply nested instance-centric API to flatter, resource-centric API focused on **tabs** as the primary resource.--**Current (nested):** `POST /instances/{id}/navigate` + `POST /instances/{id}/tab` + `POST /instances/{id}/action`-**New (flat):** `POST /navigate {tabId, url}` + `POST /tabs/new {instanceId}` + `POST /action {tabId, ...}`-------## New API Structure--### Phase 1: Profile Management (Already ~complete)-```-GET /profiles List profiles-POST /profiles Create profile-GET /profiles/{id} Get profile-DELETE /profiles/{id} Delete profile-```--### Phase 2: Instance Management (Simplify current)-```-GET /instances List running instances-POST /instances/start Start instance with profile- {profile: "name", mode: "headed|headless", port: optional}- → {id: "inst_xyz", profileId, port, mode, status}--POST /instances/{id}/stop Stop instance-GET /instances/{id}/logs View instance logs-```--### Phase 3: Tab Management (NEW - Main focus)-```-POST /tabs/new Create new tab in instance- {instanceId: "inst_xyz", url: optional}- → {id: "tab_abc", instanceId, url, status}--GET /tabs List all tabs (across all instances)-GET /tabs?instanceId=... List tabs in specific instance-GET /tabs/{id} Get tab info-POST /tabs/{id}/close Close tab-```--### Phase 4: Tab Operations (Flatten from /instances/{id}/...)-```-POST /tabs/{id}/navigate Navigate tab- {url, timeout, blockImages, blockAds}--GET /tabs/{id}/snapshot Get page structure- ?interactive, ?compact, ?depth, ?maxTokens--GET /tabs/{id}/screenshot Screenshot- ?format=png|jpeg, ?quality=80--POST /tabs/{id}/action Single action- {kind: "click"|"type"|"press"|"fill"|"hover"|"scroll"|"select"|"focus", ...}--POST /tabs/{id}/actions Multiple actions- {actions: [{kind, ...}, ...]}--GET /tabs/{id}/text Extract visible text-POST /tabs/{id}/evaluate Run JavaScript- {expression, await}--GET /tabs/{id}/pdf Export as PDF- ?landscape, ?margins, ?scale, ?pages--POST /tabs/{id}/cookies Get/set cookies-GET /tabs/{id}/cookies--POST /tabs/{id}/lock Lock tab (exclusive access)- {owner: "agent-name", ttl: 60}--POST /tabs/{id}/unlock Unlock tab- {owner: "agent-name"}--GET /tabs/{id}/locks Check lock status-POST /tabs/{id}/fingerprint/rotate Rotate fingerprint-```-------## Current Endpoints (To Deprecate/Refactor)--### Instance-scoped endpoints (Remove after migration)-```-❌ POST /instances/{id}/navigate → POST /tabs/{id}/navigate-❌ GET /instances/{id}/snapshot → GET /tabs/{id}/snapshot-❌ GET /instances/{id}/screenshot → GET /tabs/{id}/screenshot-❌ POST /instances/{id}/action → POST /tabs/{id}/action-❌ POST /instances/{id}/actions → POST /tabs/{id}/actions-❌ GET /instances/{id}/text → GET /tabs/{id}/text-❌ POST /instances/{id}/evaluate → POST /tabs/{id}/evaluate-✅ PDF endpoint migrated to `GET/POST /tabs/{id}/pdf`-❌ POST /instances/{id}/tab → POST /tabs/new {instanceId}-❌ GET /instances/{id}/tabs → GET /tabs?instanceId={id}-❌ POST /instances/{id}/tab/lock → POST /tabs/{id}/lock-❌ POST /instances/{id}/tab/unlock → POST /tabs/{id}/unlock-❌ GET /instances/{id}/cookies → GET /tabs/{id}/cookies-❌ POST /instances/{id}/cookies → POST /tabs/{id}/cookies-❌ GET /instances/{id}/download → GET /tabs/{id}/download (future)-❌ POST /instances/{id}/upload → POST /tabs/{id}/upload (future)-❌ POST /instances/{id}/ensure-chrome (Keep for health check, but hidden)-```--### Old instance launch endpoint-```-❌ POST /instances/launch {name, headless, port}- → POST /instances/start {profile, mode, port}-```-------## Implementation Checklist--### Phase 1: Add New Tab-focused Endpoints-- [ ] Create `POST /tabs/new {instanceId, url}` handler- - Calls bridge.CreateTab(url)- - Returns tab info with ID- - Stores mapping of tabId → (instanceId, tabHandle)--- [ ] Create `GET /tabs` handler (list all)- - Queries all instances for their tabs- - Returns flattened list with tabId, instanceId, url, title--- [ ] Create `GET /tabs?instanceId=...` handler- - Filters to specific instance- - Reuses GetTabs logic--- [ ] Create `GET /tabs/{id}` handler- - Returns single tab info--- [ ] Create tab operation handlers (refactored from instance handlers)- - `/tabs/{id}/navigate` → Extract from `/instances/{id}/navigate`- - `/tabs/{id}/snapshot` → Extract from `/instances/{id}/snapshot`- - `/tabs/{id}/screenshot` → Extract from `/instances/{id}/screenshot`- - `/tabs/{id}/action` → Extract from `/instances/{id}/action`- - `/tabs/{id}/actions` → Extract from `/instances/{id}/actions`- - `/tabs/{id}/text` → Extract from `/instances/{id}/text`- - `/tabs/{id}/evaluate` → Extract from `/instances/{id}/evaluate`- - `/tabs/{id}/pdf` (implemented)- - `/tabs/{id}/cookies` (GET/POST) → Extract from `/instances/{id}/cookies`- - `/tabs/{id}/lock` → Extract from `/instances/{id}/tab/lock`- - `/tabs/{id}/unlock` → Extract from `/instances/{id}/tab/unlock`--### Phase 2: Add Tab ID Resolution Layer-- [ ] Create `TabResolver` interface- - Method: `ResolveTab(tabId) → (instanceId, tabHandle, error)`- - Method: `ResolveInstance(tabId) → (instanceId, error)`--- [ ] Add to orchestrator- - Maps tabId → instanceId globally- - Routes tab operations to correct instance--- [ ] Update Bridge interface- - Add method: `TabByID(tabId) → (tab.Info, error)`--### Phase 3: Refactor Handler Logic-- [ ] Extract common logic from instance handlers- - TabResolver lookup- - Parameter passing to instance- - Response formatting--- [ ] Create tab-specific handler package- - `handlers/tabs/navigate.go`- - `handlers/tabs/snapshot.go`- - `handlers/tabs/action.go`- - etc.--- [ ] Update Handlers struct- - Add `TabResolver` field- - Keep Bridge for backward compat (bridge mode)--### Phase 4: Deprecate Old Endpoints-- [ ] Add deprecation warnings to old endpoints- - Log "DEPRECATED: Use /tabs/... instead"- - Return 307 Temporary Redirect or 308 Permanent Redirect--- [ ] Keep old endpoints working- - Translate to new handlers internally- - `POST /instances/{id}/navigate` → calls `/tabs/{id}/navigate` internally--- [ ] Document migration path- - Example: old curl → new curl--### Phase 5: Update CLI Commands-- [ ] Update CLI to use new endpoints- - `pinchtab nav <url>` → stays same (auto-detects tab)- - `pinchtab --instance <id> nav <url>` → `pinchtab --tab <id> nav <url>`- - `pinchtab snap` → `pinchtab --tab <id> snap`--- [ ] Add `--tab` flag support- - Alternative to `--instance`- - Auto-detects instance from tab--- [ ] Update docs/cli-*.md- - Reflect new structure--### Phase 6: Update Documentation-- [ ] Update API reference (docs/references/api-reference.json)- - Add all new endpoints- - Mark old endpoints as deprecated--- [ ] Update architecture docs- - Explain tab-centric design- - Show tabId routing--- [ ] Update get-started guide- - Profile → Instance → Tab workflow--- [ ] Update examples- - Curl examples with new endpoints- - CLI examples-------## Endpoint Mapping (Migration Guide)--### Example: Click Element--**Old (instance-centric):**-```bash-curl -X POST http://localhost:9867/instances/inst_abc123/action \- -H "Content-Type: application/json" \- -d '{"kind": "click", "ref": "e5"}'-```--**New (tab-centric):**-```bash-# First, get tab ID-TAB=$(curl -s http://localhost:9867/tabs?instanceId=inst_abc123 | jq -r '.[0].id')--# Then operate on tab-curl -X POST http://localhost:9867/tabs/$TAB/action \- -H "Content-Type: application/json" \- -d '{"kind": "click", "ref": "e5"}'-```--Or just:-```bash-curl -X POST http://localhost:9867/tabs/tab_xyz789/action \- -H "Content-Type: application/json" \- -d '{"kind": "click", "ref": "e5"}'-```--**CLI (both work):**-```bash-# Old-pinchtab --instance inst_abc123 click e5--# New (cleaner - direct tab reference)-pinchtab --tab tab_xyz789 click e5--# Or still support old way internally-pinchtab --instance inst_abc123 click e5 # Auto-detects default tab-```-------## Example: Full Workflow--### New (Flat, Tab-centric)--**Step 1: Create profile**-```bash-curl -X POST http://localhost:9867/profiles \- -d '{"name": "my-profile"}'-# → {id: "prof_123", name: "my-profile"}-```--**Step 2: Start instance**-```bash-curl -X POST http://localhost:9867/instances/start \- -d '{"profile": "my-profile", "mode": "headed", "port": 9868}'-# → {id: "inst_abc", profileId: "prof_123", port: 9868, status: "running"}-```--**Step 3: Create tab**-```bash-curl -X POST http://localhost:9867/tabs/new \- -d '{"instanceId": "inst_abc"}'-# → {id: "tab_xyz", instanceId: "inst_abc", status: "ready"}-```--**Step 4: Navigate (direct to tab)**-```bash-curl -X POST http://localhost:9867/tabs/tab_xyz/navigate \- -d '{"url": "https://example.com"}'-```--**Step 5: Get page structure**-```bash-curl -s http://localhost:9867/tabs/tab_xyz/snapshot?interactive=true | jq .-```--**Step 6: Click element**-```bash-curl -X POST http://localhost:9867/tabs/tab_xyz/action \- -d '{"kind": "click", "ref": "e5"}'-```--**Step 7: Extract text**-```bash-curl -s http://localhost:9867/tabs/tab_xyz/text | jq .-```--**Step 8: Close tab**-```bash-curl -X POST http://localhost:9867/tabs/tab_xyz/close-```--**Step 9: Stop instance**-```bash-curl -X POST http://localhost:9867/instances/inst_abc/stop-```-------## Benefits of New Structure--| Aspect | Old (Nested) | New (Flat) |-|--------|--------------|-----------|-| **Focus** | Instance-centric | Tab-centric |-| **Main resource** | Instance ID | Tab ID |-| **URL depth** | 3-4 levels | 2 levels |-| **Parameter passing** | Via path segments | Via body/query |-| **Scaling** | Hard (more nesting) | Easy (flat) |-| **Tab switching** | Change instance | Change tab |-| **Multi-tab workflows** | Complex (one instance) | Simple (many tabs) |-| **CLI complexity** | `--instance --tab` flags | Just `--tab` flag |-| **HTTP cacheability** | Low (deep paths) | Higher (flat paths) |-------## Code Structure Changes--### Current-```-handlers/- handlers.go (bridge-only, ~30 handlers)- - HandleNavigate- - HandleSnapshot- - HandleAction- - HandleTab- - HandleTabs- - etc.--orchestrator/- handlers.go (~40 endpoints routed to instances)- - handleLaunchByName- - handleStopByInstanceID- - handleNavigate (proxies to /instances/{id}/navigate)- - etc.-```--### New-```-handlers/- handlers.go (bridge-only, ~30 handlers) [UNCHANGED]- tabs/- resolver.go (tab ID → instance mapping)- navigate.go (POST /tabs/{id}/navigate)- snapshot.go (GET /tabs/{id}/snapshot)- action.go (POST /tabs/{id}/action)- actions.go (POST /tabs/{id}/actions)- text.go (GET /tabs/{id}/text)- evaluate.go (POST /tabs/{id}/evaluate)- pdf.go (GET /tabs/{id}/pdf)- screenshot.go (GET /tabs/{id}/screenshot)- cookies.go (GET/POST /tabs/{id}/cookies)- lock.go (POST /tabs/{id}/lock)- unlock.go (POST /tabs/{id}/unlock)--orchestrator/- handlers.go (refactored)- - handleListTabs- - handleNewTab- - handleCloseTab- - [Proxy to handlers/tabs/]-- tabs/- handler.go (routes to handlers/tabs/*)- resolver.go (tab ID lookup)-```-------## Migration Path--### For Users-1. **No breaking changes initially** — Old endpoints still work-2. **Gradual migration** — Update to new endpoints at own pace-3. **CLI stays compatible** — `pinchtab --instance` still works--### For Maintainers-1. **Phase 1-3** — Add new endpoints alongside old-2. **Phase 4** — Mark old as deprecated (deprecation headers)-3. **Phase 5-6** — Update CLI & docs to prefer new-4. **Maintenance window** — After N months, remove old endpoints-------## Testing Strategy--### Unit Tests-- [ ] Tab resolver tests- - Resolve valid tabId → instanceId- - Handle invalid tabId- - Handle cross-instance tab access--- [ ] Tab operation tests- - Navigate to URL- - Get snapshot- - Execute actions- - Lock/unlock--### Integration Tests-- [ ] Full workflow (profile → instance → tab → actions)-- [ ] Multi-tab scenario-- [ ] Tab lifecycle (create, use, close)-- [ ] Cross-instance tab access (should fail appropriately)--### Backward compat tests-- [ ] Old endpoints still work-- [ ] Old endpoints return deprecation headers-- [ ] CLI with `--instance` flag still works-------## Effort Estimation--| Phase | Task | Effort | Days |-|-------|------|--------|------|-| 1 | Add new tab endpoints | Medium | 2-3 |-| 2 | Tab resolver layer | Medium | 1-2 |-| 3 | Refactor handlers | Medium | 2-3 |-| 4 | Deprecation + compat | Small | 1 |-| 5 | Update CLI | Medium | 1-2 |-| 6 | Update docs | Small | 1 |-| | **Tests & QA** | Medium | 2-3 |-| | **TOTAL** | | ~11-17 days |-------## Success Criteria--- [x] All new endpoints documented and in API reference-- [x] CLI commands work with `--tab` flag-- [x] Old endpoints still work (deprecated)-- [x] Documentation updated-- [x] Examples updated-- [x] All tests passing-- [x] No breaking changes for users-------## Related Files to Update--1. **Endpoint docs**- - [ ] docs/references/api-reference.json (add 15+ new endpoints)- - [ ] docs/references/cli-design.md (update patterns)- - [ ] docs/references/cli-implementation.md (update code examples)- - [ ] docs/references/cli-quick-reference.md (update curl examples)--2. **Code**- - [ ] internal/handlers/handlers.go (add tab operation handlers to bridge)- - [ ] internal/orchestrator/handlers.go (add tab endpoints + routing)- - [ ] cmd/pinchtab/cmd_cli.go (add --tab support)- - [ ] internal/bridge/bridge.go (add TabByID method if needed)--3. **Tests**- - [ ] internal/handlers/*_test.go (add tab tests)- - [ ] internal/orchestrator/*_test.go (add tab routing tests)- - [ ] tests/integration/*_test.go (add workflow tests)--4. **Architecture docs**- - [ ] docs/architecture/architecture-overview.md (explain tab-centric model)- - [ ] docs/core-concepts.md (update concepts with tabs as primary resource)diff --git a/cmd/pinchtab/cmd_cli.go b/cmd/pinchtab/cmd_cli.goindex 327cea61..8a310715 100644--- a/cmd/pinchtab/cmd_cli.go+++ b/cmd/pinchtab/cmd_cli.go@@ -949,11 +949,22 @@ func cliInstanceNavigate(client *http.Client, base, token string, args []string)}instID := args[0]- url := args[1]+ targetURL := args[1]- body := map[string]any{"url": url}- // doPost auto-prints JSON response- doPost(client, base, token, fmt.Sprintf("/instances/%s/navigate", instID), body)+ // Instance navigate now works via tab-scoped navigation:+ // open a tab on the instance, then navigate that tab.+ openResp := doPost(client, base, token, fmt.Sprintf("/instances/%s/tabs/open", instID), map[string]any{+ "url": "about:blank",+ })+ tabID, _ := openResp["tabId"].(string)+ if tabID == "" {+ fatal("failed to open tab for instance %s", instID)+ }++ // doPost auto-prints JSON response.+ doPost(client, base, token, fmt.Sprintf("/tabs/%s/navigate", tabID), map[string]any{+ "url": targetURL,+ })}func cliInstanceLogs(client *http.Client, base, token string, args []string) {diff --git a/cmd/pinchtab/cmd_cli_test.go b/cmd/pinchtab/cmd_cli_test.goindex 133824bf..e6356838 100644--- a/cmd/pinchtab/cmd_cli_test.go+++ b/cmd/pinchtab/cmd_cli_test.go@@ -116,6 +116,28 @@ func TestCLINavigateWithBlockAds(t *testing.T) {}}+func TestCLIInstanceNavigateUsesTabRoute(t *testing.T) {+ m := newMockServer()+ m.response = `{"tabId":"tab-abc"}`+ defer m.close()+ client := m.server.Client()++ cliInstanceNavigate(client, m.base(), "", []string{"inst-123", "https://example.com"})++ if m.lastMethod != "POST" {+ t.Errorf("expected POST, got %s", m.lastMethod)+ }+ if m.lastPath != "/tabs/tab-abc/navigate" {+ t.Errorf("expected tab-scoped navigate path, got %s", m.lastPath)+ }++ var body map[string]any+ _ = json.Unmarshal([]byte(m.lastBody), &body)+ if body["url"] != "https://example.com" {+ t.Errorf("expected navigate URL in body, got %v", body["url"])+ }+}+// --- snapshot tests ---func TestCLISnapshot(t *testing.T) {diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.goindex 69974772..82ac52f1 100644--- a/cmd/pinchtab/cmd_dashboard.go+++ b/cmd/pinchtab/cmd_dashboard.go@@ -68,7 +68,6 @@ func runDashboard(cfg *config.RuntimeConfig) {proxyEndpoints := []string{"GET /snapshot", "GET /screenshot", "GET /text",- "GET /tabs/{tabId}/pdf", "POST /tabs/{tabId}/pdf","POST /navigate", "POST /action", "POST /actions", "POST /evaluate","POST /tab", "POST /tab/lock", "POST /tab/unlock","GET /cookies", "POST /cookies",diff --git a/docs/core-concepts.md b/docs/core-concepts.mdindex 1908c5a9..e36f9ee5 100644--- a/docs/core-concepts.md+++ b/docs/core-concepts.md@@ -211,9 +211,9 @@ A **browser tab** (webpage) within an instance and its profile.```bash# Create tab in instance (returns tabId)-curl -X POST http://localhost:9867/tabs/open \+curl -X POST http://localhost:9867/instances/inst_0a89a5bb/tabs/open \-H "Content-Type: application/json" \- -d '{"instanceId": "inst_0a89a5bb", "url": "https://example.com"}' | jq '.id'+ -d '{"url": "https://example.com"}' | jq '.tabId'# Returns: "tab_abc123"# Or via CLI@@ -290,11 +290,11 @@ INST=$(pinchtab instance launch --mode headless)# Returns: inst_0a89a5bb# Create multiple tabs in the same instance-curl -X POST http://localhost:9867/tabs/open \- -d '{"instanceId":"'$INST'","url":"https://example.com"}'+curl -X POST http://localhost:9867/instances/$INST/tabs/open \+ -d '{"url":"https://example.com"}'-curl -X POST http://localhost:9867/tabs/open \- -d '{"instanceId":"'$INST'","url":"https://google.com"}'+curl -X POST http://localhost:9867/instances/$INST/tabs/open \+ -d '{"url":"https://google.com"}'# List all tabs across all instancescurl http://localhost:9867/tabs | jq .@@ -323,11 +323,11 @@ INST_BOB=$(curl -X POST http://localhost:9867/instances/start \-d '{"profileId":"'$BOB_ID'"}' | jq -r '.id')# Create tabs in both instances with isolated cookies-curl -X POST http://localhost:9867/tabs/open \- -d '{"instanceId":"'$INST_ALICE'","url":"https://app.example.com"}'+curl -X POST http://localhost:9867/instances/$INST_ALICE/tabs/open \+ -d '{"url":"https://app.example.com"}'-curl -X POST http://localhost:9867/tabs/open \- -d '{"instanceId":"'$INST_BOB'","url":"https://app.example.com"}'+curl -X POST http://localhost:9867/instances/$INST_BOB/tabs/open \+ -d '{"url":"https://app.example.com"}'# Login in each instance separately — profiles keep sessions isolated```@@ -339,8 +339,8 @@ curl -X POST http://localhost:9867/tabs/open \INST=$(pinchtab instance launch)# Create tab, use it-curl -X POST http://localhost:9867/tabs/open \- -d '{"instanceId":"'$INST'","url":"https://example.com"}'+curl -X POST http://localhost:9867/instances/$INST/tabs/open \+ -d '{"url":"https://example.com"}'# ... work ...# Stop instancediff --git a/docs/examples/API_DOCUMENTATION_EXAMPLES.md b/docs/examples/API_DOCUMENTATION_EXAMPLES.mddeleted file mode 100644index a35949df..00000000--- a/docs/examples/API_DOCUMENTATION_EXAMPLES.md+++ /dev/null@@ -1,345 +0,0 @@-# API Documentation Examples--This document shows what documented endpoints look like with structured comments.--## Example 1: Navigate to URL (POST /navigate)--### Description-Navigate a tab to a URL or create a new tab and navigate--### Request--**Endpoint:** `POST /navigate`--**Body Parameters:**-- `tabId` (string, optional) — Tab ID to navigate in. If omitted, creates new tab-- `url` (string, required) — URL to navigate to-- `newTab` (bool, optional, default: false) — Force create new tab-- `waitTitle` (float64, optional, default: 0) — Wait for title change (ms)-- `timeout` (float64, optional, default: 30000) — Timeout for navigation (ms)--### Response--**Success (200):**-```json-{- "tabId": "tab-abc123",- "url": "https://example.com",- "title": "Example Domain"-}-```--**Error (400):**-```json-{- "error": "invalid_url",- "message": "URL is required"-}-```--### Examples--**CLI:**-```bash-pinchtab nav https://example.com-```--**cURL — Create new tab:**-```bash-curl -X POST http://localhost:9867/navigate \- -H "Content-Type: application/json" \- -d '{"url":"https://example.com"}'-```--**cURL — Navigate existing tab:**-```bash-curl -X POST http://localhost:9867/navigate \- -H "Content-Type: application/json" \- -d '{"tabId":"abc123","url":"https://google.com"}'-```-------## Example 2: Get Page Snapshot (GET /snapshot)--### Description-Returns the accessibility tree of a tab with clickable elements, form fields, and text content--### Request--**Endpoint:** `GET /snapshot`--**Query Parameters:**-- `tabId` (string, required) — Tab ID-- `filter` (string, optional, default: "all") — Filter type:- - `"all"` — All elements- - `"interactive"` — Only clickable/inputs-- `interactive` (bool, optional) — Alias for filter=interactive-- `compact` (bool, optional, default: false) — Compact output (shorter ref names)-- `depth` (int, optional, default: -1) — Max nesting depth (full tree)-- `text` (bool, optional, default: true) — Include text content-- `format` (string, optional, default: "json") — Output format: "json" or "yaml"-- `diff` (bool, optional, default: false) — Include diff with previous snapshot--### Response--**Success (200):**-```json-{- "title": "Example Domain",- "url": "https://example.com",- "elements": [- {- "ref": "e0",- "role": "heading",- "name": "Example Domain",- "tag": "h1"- },- {- "ref": "e1",- "role": "paragraph",- "name": "This domain is for use in examples...",- "tag": "p"- },- {- "ref": "e5",- "role": "link",- "name": "More information",- "tag": "a",- "href": "https://www.iana.org/domains/example"- }- ]-}-```--### Examples--**CLI — Interactive only:**-```bash-pinchtab snap -i -c-```--**cURL — All elements:**-```bash-curl "http://localhost:9867/snapshot?tabId=abc123"-```--**cURL — Interactive elements only:**-```bash-curl "http://localhost:9867/snapshot?tabId=abc123&filter=interactive"-```--**cURL — Compact format:**-```bash-curl "http://localhost:9867/snapshot?tabId=abc123&filter=interactive&compact=true"-```--**Python:**-```python-import requests--response = requests.get(- "http://localhost:9867/snapshot",- params={"tabId": "abc123", "filter": "interactive"}-)-tree = response.json()-for el in tree["elements"]:- print(f"{el['ref']}: {el['name']}")-```-------## Example 3: Perform Action (POST /action)--### Description-Interact with page elements: click, type text, fill inputs, press keys, hover, focus, scroll, select--### Request--**Endpoint:** `POST /action`--**Body Parameters:**-- `tabId` (string, required) — Tab ID-- `kind` (string, required) — Action type:- - `"click"` — Click element- - `"type"` — Type text (appends to existing)- - `"fill"` — Fill input (replaces existing)- - `"press"` — Press key- - `"hover"` — Hover over element- - `"focus"` — Focus element- - `"scroll"` — Scroll- - `"select"` — Select option-- `ref` (string, required) — Element reference from snapshot (e.g., "e5")-- `text` (string, optional) — Text to type or fill (for "type"/"fill")-- `value` (string, optional) — Value for "select" action-- `key` (string, optional) — Key to press (for "press" action, e.g., "Enter", "Tab")-- `x` (int, optional) — X coordinate for "scroll"-- `y` (int, optional) — Y coordinate for "scroll"--### Response--**Success (200):**-```json-{- "success": true-}-```--**Error (404):**-```json-{- "error": "element_not_found",- "ref": "e5"-}-```--### Examples--**CLI — Click button:**-```bash-pinchtab click e5-```--**CLI — Type into input:**-```bash-pinchtab type e3 "[email protected]"-```--**CLI — Fill form field:**-```bash-pinchtab fill e3 "John Doe"-```--**cURL — Click:**-```bash-curl -X POST http://localhost:9867/action \- -H "Content-Type: application/json" \- -d '{"tabId":"abc123","kind":"click","ref":"e5"}'-```--**cURL — Type into input:**-```bash-curl -X POST http://localhost:9867/action \- -H "Content-Type: application/json" \- -d '{"tabId":"abc123","kind":"type","ref":"e3","text":"[email protected]"}'-```--**cURL — Fill form (replaces existing text):**-```bash-curl -X POST http://localhost:9867/action \- -H "Content-Type: application/json" \- -d '{"tabId":"abc123","kind":"fill","ref":"e3","text":"John Doe"}'-```--**cURL — Press Enter key:**-```bash-curl -X POST http://localhost:9867/action \- -H "Content-Type: application/json" \- -d '{"tabId":"abc123","kind":"press","ref":"e7","key":"Enter"}'-```--**cURL — Click multiple actions in sequence:**-```bash-# 1. Click login button-curl -X POST http://localhost:9867/action \- -H "Content-Type: application/json" \- -d '{"tabId":"abc123","kind":"click","ref":"e10"}'--# 2. Fill email-curl -X POST http://localhost:9867/action \- -H "Content-Type: application/json" \- -d '{"tabId":"abc123","kind":"fill","ref":"e3","text":"[email protected]"}'--# 3. Fill password-curl -X POST http://localhost:9867/action \- -H "Content-Type: application/json" \- -d '{"tabId":"abc123","kind":"fill","ref":"e5","text":"password123"}'--# 4. Submit form-curl -X POST http://localhost:9867/action \- -H "Content-Type: application/json" \- -d '{"tabId":"abc123","kind":"press","ref":"e7","key":"Enter"}'-```-------## Complete Workflow Example--### Automated Login + Screenshot--**CLI:**-```bash-# 1. Navigate to login page-pinchtab nav https://example.com/login--# 2. Get page structure-pinchtab snap -i -c--# 3. Fill email-pinchtab fill e3 "[email protected]"--# 4. Fill password-pinchtab fill e5 "password123"--# 5. Click submit-pinchtab click e7--# 6. Wait a moment-sleep 2--# 7. Take screenshot-pinchtab screenshot -o login-success.jpg-```--**Python:**-```python-import requests-import json-import time--BASE = "http://localhost:9867"--# 1. Navigate-r = requests.post(f"{BASE}/navigate", json={"url": "https://example.com/login"})-tab_id = r.json()["tabId"]-print(f"Navigated to login page: {tab_id}")--# 2. Get page structure-r = requests.get(f"{BASE}/snapshot", params={"tabId": tab_id, "filter": "interactive"})-elements = r.json()["elements"]-for el in elements:- if "email" in el.get("name", "").lower():- email_ref = el["ref"]- if "password" in el.get("name", "").lower():- password_ref = el["ref"]- if "submit" in el.get("name", "").lower() or "login" in el.get("name", "").lower():- submit_ref = el["ref"]--# 3. Fill email-requests.post(f"{BASE}/action", json={"tabId": tab_id, "kind": "fill", "ref": email_ref, "text": "[email protected]"})--# 4. Fill password-requests.post(f"{BASE}/action", json={"tabId": tab_id, "kind": "fill", "ref": password_ref, "text": "password123"})--# 5. Submit-requests.post(f"{BASE}/action", json={"tabId": tab_id, "kind": "click", "ref": submit_ref})--# 6. Wait for page to load-time.sleep(2)--# 7. Take screenshot-r = requests.get(f"{BASE}/screenshot", params={"tabId": tab_id})-with open("login-success.jpg", "wb") as f:- f.write(r.content)-print("Screenshot saved")-```-------## Notes--- All examples use `http://localhost:9867` as the base URL-- In production, use your actual server address-- Tab IDs are returned from `/navigate` or other tab operations-- Refs come from `/snapshot` responses-- CLI commands require the pinchtab server to be runningdiff --git a/docs/extras/STRUCTURE.txt b/docs/extras/STRUCTURE.txtdeleted file mode 100644index 8878b60f..00000000--- a/docs/extras/STRUCTURE.txt+++ /dev/null@@ -1,161 +0,0 @@-PINCHTAB BENCHMARK DOCUMENTATION STRUCTURE-═════════════════════════════════════════════════════════════════-- BENCHMARK-SUMMARY.md- ↓- (Quick reference for all three methods)- ↓- ┌───────────┬────────────┬─────────────┐- ↓ ↓ ↓ ↓- SNAPSHOT web_fetch PINCHTAB (CLEAN SLATE)- (service) (service) (agent + service)- ↓ ↓ ↓- snapshot-test webfetch-test pinchtab-clean-slate- -results.zip -results.zip -results.zip- ↓- browser-extraction- -spectrum.md- (all three compared)--═════════════════════════════════════════════════════════════════--KEY SCENARIOS:--1. LONG-LIVED AGENT (conversation)- └─→ Service tokens dominate- └─→ Use browser-extraction-spectrum.md- └─→ Snapshot: 64K tokens- └─→ web_fetch: 6.8K tokens- └─→ Pinchtab: 900 tokens--2. FRESH AGENT PER TASK (distributed, high-volume)- └─→ Agent overhead + service tokens- └─→ Use pinchtab-clean-slate.md ← PINCHTAB WINS HERE- └─→ Snapshot: 65K tokens (agent + service)- └─→ web_fetch: 7.3K tokens (agent + service)- └─→ Pinchtab: 1.4K tokens (agent + service) = 47x lighter--═════════════════════════════════════════════════════════════════--ENTRY POINTS:--1. QUICK ANSWER? → BENCHMARK-SUMMARY.md (2-min read)--2. LONG-LIVED AGENT? → browser-extraction-spectrum.md--3. DISTRIBUTED AGENT? → pinchtab-clean-slate.md ← NEW--4. DEEP DIVES? → Pick method:- - default-isolated-browser.md (snapshot)- - web-fetch-lightweight.md (text)- - pinchtab-clean-slate.md (distributed)--5. IMPLEMENT? → pinchtab-architecture.md + docker.md--═════════════════════════════════════════════════════════════════--LINKED DOCUMENTS:--BENCHMARK-SUMMARY.md (4.1 KB) - TOP HUB-├─ Two scenarios: long-lived vs. fresh agent-├─ Links to all method analyses + zip files-└─ "98% lighter" headline for pinchtab.com--default-isolated-browser.md (5.5 KB) - SNAPSHOT DEEP DIVE-├─ Topic: Full DOM + accessibility tree-├─ Service tokens: 11K-95K-├─ Links to: snapshot-test-results.zip-└─ Links to: browser-extraction-spectrum.md--web-fetch-lightweight.md (9.5 KB) - TEXT DEEP DIVE-├─ Topic: Readability parser extraction-├─ Service tokens: 3K-12K-├─ Links to: webfetch-test-results.zip-└─ Links to: browser-extraction-spectrum.md--pinchtab-clean-slate.md (7.8 KB) - PINCHTAB FRESH AGENT-├─ Topic: Fresh agent spawn + Pinchtab call-├─ Total tokens: 1.4K (agent + service)-├─ Scenario: Distributed, high-volume tasks-├─ Links to: pinchtab-clean-slate-results.zip-└─ ADVANTAGE: 47x lighter than snapshot in this scenario--browser-extraction-spectrum.md (8.4 KB) - COMPLETE COMPARISON-├─ Covers: All three methods + decision tree-├─ Assumes: Long-lived agent (service tokens only)-├─ References: Both test zip files-└─ Best for: Comprehensive understanding--TEST DATA (Raw numbers, reproducible):--snapshot-test-results.zip (4.4 KB)-├─ BBC: 45 KB → 11.2K tokens-├─ Corriere: 380 KB → 95K tokens-├─ Daily Mail: 350 KB → 87.5K tokens-└─ Method: OpenClaw /snapshot depth=2--webfetch-test-results.zip (3.6 KB)-├─ BBC: 18.8 KB → 4.7K tokens-├─ Corriere: 13.1 KB → 3.3K tokens-├─ Daily Mail: 50 KB → 12.5K tokens-└─ Method: web_fetch /Readability--pinchtab-clean-slate-results.zip (3.9 KB) ← NEW-├─ Agent overhead: 500 tokens-├─ BBC: 3-4 KB → 900 tokens (service)-├─ Corriere: 2-3 KB → 700 tokens (service)-├─ Daily Mail: 4-5 KB → 1150 tokens (service)-└─ Method: Fresh agent + Pinchtab /snapshot--═════════════════════════════════════════════════════════════════--COST COMPARISON MATRICES:--LONG-LIVED AGENT (service tokens only):-┌─────────────┬──────────┬────────┬─────────────┐-│ Method │ Tokens │ Cost │ vs Pinchtab │-├─────────────┼──────────┼────────┼─────────────┤-│ Snapshot │ 64,583 │ $0.19 │ 71.7x │-│ web_fetch │ 6,825 │ $0.02 │ 7.6x │-│ Pinchtab │ 900 │ $0.003 │ 1x (WIN) │-└─────────────┴──────────┴────────┴─────────────┘--FRESH AGENT (agent + service):-┌─────────────┬──────────┬────────┬─────────────┐-│ Method │ Tokens │ Cost │ vs Pinchtab │-├─────────────┼──────────┼────────┼─────────────┤-│ Snapshot │ 65,083 │ $0.19 │ 46x │-│ web_fetch │ 7,325 │ $0.02 │ 5.2x │-│ Pinchtab │ 1,417 │ $0.004 │ 1x (WIN) │-└─────────────┴──────────┴────────┴─────────────┘--MONTHLY (1,000 tasks/day):-┌─────────────┬──────────┬─────────┐-│ Method │ Monthly │ Savings │-├─────────────┼──────────┼─────────┤-│ Snapshot │ $5.85 │ — │-│ web_fetch │ $0.66 │ $5.19 │-│ Pinchtab │ $0.12 │ $5.73 │-└─────────────┴──────────┴─────────┘--═════════════════════════════════════════════════════════════════--FOR pinchtab.com COPY:--SCENARIO 1: "98% lighter than snapshots"-→ Use: snapshot-test-results.zip-→ Quote: "64,583 tokens vs. 900 tokens service"--SCENARIO 2: "47x lighter in distributed workflows"-→ Use: pinchtab-clean-slate-results.zip-→ Quote: "1,417 total tokens (agent + Pinchtab) vs. 65,083 (snapshot)"--SCENARIO 3: "Real Chrome rendering at web_fetch price"-→ Use: browser-extraction-spectrum.md comparison-→ Quote: "Renders JavaScript, 5.7x lighter than web_fetch"--═════════════════════════════════════════════════════════════════--Test date: February 26-27, 2026-OpenClaw version: 2026.2.23-Update: February 27, 2026 - Added clean slate scenariodiff --git a/docs/extras/benckmark-summary.md b/docs/extras/benckmark-summary.mddeleted file mode 100644index 21f73687..00000000--- a/docs/extras/benckmark-summary.md+++ /dev/null@@ -1,141 +0,0 @@-# Benchmark Summary: All Methods Compared--## Quick Reference--Three extraction methods tested on **BBC.com**, **Corriere.it**, **Daily Mail.co.uk**:--### Results at a Glance--#### Long-Lived Agent (Service Tokens Only)-| Method | Avg Size | Avg Tokens | Best For |-|--------|----------|-----------|----------|-| **Snapshot** | 258 KB | 64,583 | Interactive workflows, forms |-| **web_fetch** | 27 KB | 6,825 | Text extraction, blogs, news |-| **Pinchtab** | ~2 KB | 900 | Scale + real Chrome rendering |--#### Fresh Agent per Task (Agent + Service)-| Method | Agent OH | Service | Total |-|--------|----------|---------|-------|-| **Snapshot** | 500 | 64,583 | 65,083 |-| **web_fetch** | 500 | 6,825 | 7,325 |-| **Pinchtab** | 500 | 920 | **1,417** |--*Fresh agent scenario shows Pinchtab's 47x advantage when spawning new agents per task.*-------## The Three Analyses--### 1. 🖥️ Default Isolated Browser (Snapshot)-**Document:** `default-isolated-browser.md`-**Test Data:** `snapshot-test-results.zip`--- Full semantic snapshot with DOM + accessibility tree-- High-fidelity for UI agents, expensive for text extraction-- **11K-95K tokens** depending on site complexity--[📄 Read snapshot analysis](./default-isolated-browser.md) | [📦 Raw data](./snapshot-test-results.zip)-------### 2. 📝 web_fetch (Text-Only)-**Document:** `web-fetch-lightweight.md`-**Test Data:** `webfetch-test-results.zip`--- Readability parser removes 70-90% boilerplate-- Perfect for articles, blogs, content extraction-- **3.3K-12.5K tokens** with minimal structure--[📄 Read web_fetch analysis](./web-fetch-lightweight.md) | [📦 Raw data](./webfetch-test-results.zip)-------### 3. ⚡ Pinchtab (Ultra-Light)-**Document:** `pinchtab-clean-slate.md`-**Test Data:** `pinchtab-clean-slate-results.zip` (metadata + calculations)--- Real Chrome rendering + text optimization-- Clean slate scenario: fresh agent + Pinchtab call-- **~1,400 tokens** per task (including agent overhead)--**Methodology Note:** Snapshot and web_fetch tested empirically. Pinchtab calculated from documented behavior and production measurements. See `pinchtab-clean-slate.md` → "Validation Method" section.--[📄 Read Pinchtab clean slate analysis](./pinchtab-clean-slate.md) | [📦 Raw data](./pinchtab-clean-slate-results.zip)--**Also see:** `browser-extraction-spectrum.md` for complete method comparison-------## The Comparison--**Start here:** [`browser-extraction-spectrum.md`](./browser-extraction-spectrum.md)--This single document covers:-- Complete feature matrix (all three methods)-- Performance analysis at scale (1K-10K pages/day)-- Decision tree (when to use each)-- Real-world scenarios + architecture patterns-- Use case recommendations-------## Test Sites & Methodology--**Sites tested:**-- `BBC.com` — Portal layout, low content density (45 KB snapshot, 18.8 KB text)-- `Corriere.it` — News hub, very high density (380 KB snapshot, 13.1 KB text)-- `Daily Mail.co.uk` — News + features (350 KB snapshot, 50 KB text)--**Methodology:**-1. Snapshot: Full depth=2 semantic DOM extraction-2. web_fetch: Readability parser (markdown mode)-3. Pinchtab: Real Chrome + text optimization (estimated)--**Tokens calculated:**-- Snapshot: 4 chars (text) + 2 chars (JSON) = 1 token-- web_fetch: 4 chars (text) = 1 token-- Pinchtab: 4 chars (text) = 1 token-------## Key Takeaways--1. **Snapshot is heavy but powerful** — Full DOM + refs for clicking, 9-29x heavier-2. **web_fetch is the sweet spot for text** — Built-in, 82% lighter, handles news/articles-3. **Pinchtab owns the scale game** — 90% token savings vs. snapshot, real Chrome rendering-4. **Token efficiency compounds** — At 10K pages/day, method choice has significant impact-------## File Organization--```-~/dev/pinchtab/docs/-├── README.md (navigation hub)-├── BENCHMARK-SUMMARY.md (this file)-├── browser-extraction-spectrum.md (complete comparison)-├── default-isolated-browser.md (snapshot deep dive)-├── web-fetch-lightweight.md (web_fetch deep dive)-├── pinchtab-clean-slate.md (Pinchtab + agent overhead)-├── snapshot-test-results.zip (raw snapshot data)-├── webfetch-test-results.zip (raw web_fetch data)-├── pinchtab-clean-slate-results.zip (raw Pinchtab + agent data)-└── [other architecture docs...]-```-------## For pinchtab.com Copy--**The headline:** "98% lighter than OpenClaw snapshots. Real Chrome. Agent-optimized."--**The proof:**-- Snapshot: 64,583 tokens (snapshot-test-results.zip)-- web_fetch: 6,825 tokens (webfetch-test-results.zip)-- **Pinchtab: 1,200 tokens** ← 5.7x lighter than web_fetch-------**Test Date:** February 26, 2026-**OpenClaw Version:** 2026.2.23-**Updated:** February 27, 2026diff --git a/docs/extras/browser-extraction-spectrum.md b/docs/extras/browser-extraction-spectrum.mddeleted file mode 100644index 10d1a4bd..00000000--- a/docs/extras/browser-extraction-spectrum.md+++ /dev/null@@ -1,257 +0,0 @@-# Browser Content Extraction: Complete Spectrum--## Three Extremes Mapped--This document unifies the analysis across all three extraction methods, showing the **spectrum from heavyweight (Snapshot) → lightweight (web_fetch) → ultra-lightweight (Pinchtab)**.-------## The Spectrum--```-HEAVYWEIGHT SNAPSHOT LIGHTWEIGHT WEB_FETCH ULTRA-LIGHTWEIGHT PINCHTAB-|════════════════════════════════════════════════════════════════════════════════════|-|-| Full DOM + accessibility Text extraction via Readability Text via real Chrome-| tree, interactive refs, parser, removes boilerplate, + CSS selectors-| element coordinates minimal structure-|-| 64K tokens avg 6.8K tokens avg 1.2K tokens avg-|-|════════════════════════════════════════════════════════════════════════════════════|-```-------## Quick Comparison Table--| Aspect | Snapshot | web_fetch | Pinchtab |-|--------|----------|-----------|----------|-| **Avg Size** | 258 KB | 27 KB | ~2 KB (est) |-| **Avg Tokens** | 64,583 | 6,825 | 1,200 |-| **Interactive** | ✅ Yes | ❌ No | ❌ No |-| **Structure Info** | ✅ Yes | ❌ No | ⚠️ Limited |-| **Rendering** | ✅ Yes | ❌ No | ✅ Yes |-| **JavaScript** | ✅ Renders | ❌ No | ✅ Renders |-| **Speed** | ~500ms | ~200ms | ~800ms |-| **Setup** | Built-in | Built-in | Binary required |-------## Data By Site--### BBC (Portal Layout, Low Content Density)--| Method | Size | Tokens | Articles |-|--------|------|--------|----------|-| Snapshot | 45 KB | 11,250 | 17 |-| web_fetch | 18.8 KB | 4,700 | 15 |-| Pinchtab | ~2 KB (est) | 400 | 8-10 |-| **Savings (web vs snap)** | **58%** | **58%** | — |-| **Savings (pin vs snap)** | **96%** | **96%** | — |--### Corriere (News Hub, Very High Density)--| Method | Size | Tokens | Articles |-|--------|------|--------|----------|-| Snapshot | 380 KB | 95,000 | 100+ |-| web_fetch | 13.1 KB | 3,275 | 18 |-| Pinchtab | ~2 KB (est) | 400 | 8-10 |-| **Savings (web vs snap)** | **97%** | **97%** | — |-| **Savings (pin vs snap)** | **99.5%** | **99.5%** | — |--### Daily Mail (News + Clickbait, Very High Density)--| Method | Size | Tokens | Articles |-|--------|------|--------|----------|-| Snapshot | 350 KB | 87,500 | 150+ |-| web_fetch | 50 KB | 12,500 | 20 |-| Pinchtab | ~2 KB (est) | 400 | 8-10 |-| **Savings (web vs snap)** | **86%** | **86%** | — |-| **Savings (pin vs snap)** | **99.4%** | **99.4%** | — |-------## Decision Tree--### I need to interact/click/fill forms--```- ↓ YES- Use Snapshot- (only option with DOM refs)-```--### I need text content only--```- ↓- How much scale?- ├─ <1K pages/day → Use web_fetch- │ (built-in, simple, good enough)- │- └─ ≥1K pages/day → Use Pinchtab- (90% token savings)-```--### I need real JavaScript rendering--```- ↓ YES- Does page need interaction?- ├─ YES → Use Snapshot- └─ NO → Use Pinchtab- (real Chrome, text-optimized)-```--### I'm building an agent workflow--```- ↓- What's primary constraint?- ├─ Interactivity → Snapshot- ├─ Cost/scale → Pinchtab- └─ Speed/simplicity → web_fetch-```-------## Real-World Scenarios--### Scenario A: News Aggregator Bot (Fast + Efficient)--**Requirements:**-- Crawl 10-20 news sites daily-- Extract headlines, summaries-- No interaction needed-- Token efficiency matters--**Recommendation:** **web_fetch**-- Why: Fast, built-in, 97% lighter than snapshot-- Tradeoff: Can't handle JS-heavy sites--**Alternative:** Pinchtab if you hit JS-heavy sites (add real Chrome)-------### Scenario B: Research AI Agent (Accuracy + Scale)--**Requirements:**-- Read 1,000+ pages/day-- Extract accurate data-- Real Chrome rendering needed (JS heavy)-- Minimize token usage--**Recommendation:** **Pinchtab**-- Why: Real Chrome rendering + 90% token savings-- Tradeoff: Requires binary, no form filling--**Alternative:** web_fetch if no JS rendering needed-------### Scenario C: Web Scraping UI Agent (Interactive)--**Requirements:**-- Navigate forms, fill inputs-- Click buttons, interact with page-- Extract after interaction-- Single-page workflows (low volume)--**Recommendation:** **Snapshot**-- Why: Only option with form support + interaction-- Tradeoff: Higher token usage but feature-complete--**No alternative:** You need the full DOM.-------## Architecture Patterns--### Pattern 1: Hybrid (Best of All)--```-Input URL- ├─ Is it a form/interactive page? YES → Use Snapshot- ├─ Needs JS rendering? YES → Use Pinchtab- └─ Text-only? YES → Use web_fetch-Output: Optimal tokens + capability-```--**Pro:** Perfect choice per page-**Con:** Adds routing logic, complexity-------### Pattern 2: Pinchtab-First (Enterprise)--```-Input URL- └─ All pages → Pinchtab- └─ If selector fails → fall back to snapshot-Output: Fast, cheap, handles JS-```--**Pro:** Simple, token-efficient, real Chrome-**Con:** Requires Pinchtab setup, no form filling-------### Pattern 3: web_fetch-Default (Startup)--```-Input URL- ├─ Extract via web_fetch- └─ If fails (JS/auth) → Snapshot-Output: Cheap default, escalate when needed-```--**Pro:** Built-in, no dependencies-**Con:** Falls back to expensive snapshot on complex sites-------## The Pinchtab Pitch--For teams extracting **1K+ pages/day**:--- **Snapshot:** ~64K tokens per page-- **Pinchtab:** ~1.2K tokens per page-- **Reduction:** **98% token savings**--Plus: Real Chrome rendering (JS support), better text quality, agent-optimized.--**Efficiency matters:** At scale (50+ pages/day), token reduction compounds significantly.-------## Test Data Sources--**Full analyses:**-1. [default-isolated-browser.md](./default-isolated-browser.md) — Snapshot deep dive-2. [web-fetch-lightweight.md](./web-fetch-lightweight.md) — web_fetch details-3. [snapshot-test-results.zip](./snapshot-test-results.zip) — Raw test data--**Sites tested:**-- BBC (portal, low density)-- Corriere (news hub, high density)-- Daily Mail (news + clickbait, very high density)--**Test date:** February 26, 2026-**OpenClaw version:** 2026.2.23-------## FAQ--**Q: Can Pinchtab do everything Snapshot does?**-A: No. Snapshot has form support + element refs for clicking. Pinchtab is text-optimized. Use Snapshot for interactive workflows.--**Q: Should I always use Pinchtab over web_fetch?**-A: Only if you need real Chrome rendering (JS) or at scale (1K+ pages/day). web_fetch is simpler for text-only, no-JS sites.--**Q: Can web_fetch handle authentication?**-A: No, it fetches raw HTML. Use Snapshot or Pinchtab if cookies/auth required.--**Q: Does Pinchtab work with Anthropic's API?**-A: Yes. It's just HTTP. Use it to reduce token usage before sending to Claude.diff --git a/docs/extras/chrome-processes.md b/docs/extras/chrome-processes.mddeleted file mode 100644index 8bc28d25..00000000--- a/docs/extras/chrome-processes.md+++ /dev/null@@ -1,92 +0,0 @@-# Chrome Processes & Activity Monitor--Pinchtab launches its own Chrome instance. This doc explains how to identify Pinchtab's Chrome processes vs your personal Chrome, and what to do if things go wrong.--## How Pinchtab Uses Chrome--When Pinchtab starts, it spawns a Chrome process tree:--| Process | Role |-|---------|------|-| **Google Chrome** | Main browser process (parent) |-| **Google Chrome Helper** (gpu) | GPU rendering |-| **Google Chrome Helper** (network) | Network requests |-| **Google Chrome Helper** (storage) | Cookies, localStorage, etc. |-| **Google Chrome Helper (Renderer)** | One per tab/extension |--A typical Pinchtab instance creates **6-10 processes** depending on the number of open tabs.--## Identifying Pinchtab's Chrome--Pinchtab's Chrome is launched with a custom `--user-data-dir` flag pointing to the Pinchtab profile directory. Your personal Chrome uses `~/Library/Application Support/Google/Chrome` instead.--### From the terminal--```bash-# List Pinchtab's Chrome processes-ps ax | grep "user-data-dir=.*pinchtab" | grep -v grep--# List your personal Chrome processes (no --user-data-dir flag)-ps ax | grep "Google Chrome" | grep -v "user-data-dir" | grep -v grep-```--### From Activity Monitor--1. Open **Activity Monitor** (Spotlight → "Activity Monitor")-2. Search for **"Google Chrome"** in the search bar-3. Select a Chrome process → click the **ⓘ** (info) button in the toolbar-4. Go to the **Open Files and Ports** tab-5. Look for paths containing your Pinchtab state directory:- - **Pinchtab Chrome**: references like `~/.pinchtab/chrome-profile/` or your custom `BRIDGE_STATE_DIR`- - **Your Chrome**: references like `~/Library/Application Support/Google/Chrome/`--Alternatively, double-click any Chrome process → **Sample** or **Open Files** to inspect it.--### Quick check: is it headless?--Pinchtab's Chrome (in headless mode) won't appear in the Dock or have a visible window. If you see Chrome in Activity Monitor but not in the Dock, it's likely Pinchtab's.--## Normal Behavior--- Pinchtab Chrome processes appear when Pinchtab is running and disappear on graceful shutdown (SIGTERM/SIGINT)-- More tabs = more Renderer processes-- Memory usage: ~100-300MB base + ~50-150MB per tab depending on page complexity--## Orphaned Processes--If Pinchtab is force-killed (`kill -9`) or crashes, Chrome processes may be left behind. These are **orphaned processes** — they consume memory but do nothing useful.--### Automatic cleanup--Pinchtab automatically detects and kills orphaned Chrome processes on startup. You'll see this in the logs:--```-WARN killed orphaned Chrome processes count=8 profileDir=/path/to/profile-```--### Manual cleanup--If you need to clean up manually:--```bash-# Find orphaned Pinchtab Chrome processes-ps ax | grep "user-data-dir=.*pinchtab" | grep -v grep--# Kill them (graceful)-ps ax | grep "user-data-dir=.*pinchtab" | grep -v grep | awk '{print $1}' | xargs kill--# Or kill by specific profile path-pkill -f "user-data-dir=/Users/you/.pinchtab/chrome-profile"-```--In Activity Monitor, you can right-click any orphaned process → **Quit** (or **Force Quit**).--### How to tell if Chrome is orphaned--- Pinchtab is not running (`curl localhost:9867/health` fails)-- But Chrome processes with `--user-data-dir=<pinchtab-path>` still exist-- These are safe to kill--## Docker--Inside Docker containers, Chrome runs as `chromium-browser` under the `pinchtab` user. The container handles process lifecycle — when the container stops, all processes inside are cleaned up automatically. Orphan issues only apply to native (non-Docker) installations.diff --git a/docs/extras/default-isolated-browser.md b/docs/extras/default-isolated-browser.mddeleted file mode 100644index 18c44969..00000000--- a/docs/extras/default-isolated-browser.md+++ /dev/null@@ -1,184 +0,0 @@-# Default Isolated Browser: Token Efficiency Analysis--## Overview--This document benchmarks OpenClaw's **default isolated browser** (`profile="openclaw"`) against alternative methods (web_fetch, Pinchtab) for web content extraction. The goal: prove that Pinchtab reduces token overhead vs. semantic snapshots.--**Executive Summary:**-- Default snapshots: **~11K-95K tokens** (high structural overhead)-- Pinchtab /text: **~800-1,000 tokens** (optimized for agents)-- web_fetch text: **~2,000-3,000 tokens** (text-only fallback)-- **Savings: 90% token reduction** using Pinchtab vs. full snapshot-------## Test Results--### Methodology--For each site (BBC, Corriere, Daily Mail):-1. Used `browser snapshot` with `profile="openclaw"` and `depth=2`-2. Extracted first 20 article/news titles from response-3. Counted total response size in KB-4. Estimated tokens:- - Text content: **4 characters ≈ 1 token**- - JSON structure: **2 characters ≈ 1 token**--### Data--| Site | Snapshot Size | Est. Tokens | Articles Found | Density |-|------|---------------|------------|-----------------|---------|-| **BBC** | 45 KB | ~11,250 | 17 | Low (mostly nav) |-| **Corriere** | 380 KB | ~95,000 | 100+ | Very High |-| **Daily Mail** | 350 KB | ~87,500 | 150+ | Very High |-| **Average** | **258 KB** | **~64,583** | **~89** | **High** |--**Full test results:** [snapshot-test-results.zip](#)-------## Comparative Analysis--### Method 1: Full Semantic Snapshot (Default)--**What it captures:**-- Complete DOM structure (every tag, attribute)-- Accessibility tree (roles, labels, aria attributes)-- Element positioning, visibility, computed styles-- Interactive element metadata (buttons, links, forms)-- Element references for agent reasoning--**Pros:**-- ✅ Complete structural information-- ✅ Accessibility-first design-- ✅ Element references for clicking/interaction-- ✅ No external dependencies--**Cons:**-- ❌ 20-30% JSON structural overhead-- ❌ High token burn for news aggregators (100+ articles)-- ❌ Noisy for agents (lots of chrome/nav elements)-------### Method 2: web_fetch (Text-Only)--**What it captures:**-- Extracted text via Readability parser-- Markdown formatting-- No DOM, no accessibility tree--**Token usage:**-- BBC: ~4,700 tokens-- Corriere: ~3,275 tokens-- Daily Mail: ~12,500 tokens-- **Total: ~20,475 tokens per 3-page batch** (~82% lighter vs. snapshot)--**Pros:**-- ✅ Fast (no rendering)-- ✅ Lightweight-- ✅ 82% token reduction--**Cons:**-- ❌ No interactivity (can't click elements)-- ❌ Loses structure (no sections/hierarchy)-- ❌ Can't extract form fields or interactive widgets-------### Method 3: Pinchtab /text (Optimized)--**What it captures:**-- Text extraction optimized for agents-- Optional: CSS selector-based filtering-- Real Chrome rendering (not Readability parser)--**Token usage (estimated):**-- ~800-1,200 tokens per page-- **Total: ~2,400-3,600 tokens per 3-page batch** (~90% lighter vs. snapshot)--**Pros:**-- ✅ 90% token reduction-- ✅ Real Chrome rendering (handles JavaScript)-- ✅ Selector-based filtering (get specific content)-- ✅ Direct HTTP API (no browser overhead)--**Cons:**-- ❌ Requires running Pinchtab binary-- ❌ No accessibility tree (text-optimized)-------## Token Efficiency Comparison--### Per-Page Tokens--| Method | Tokens | Relative Efficiency |-|--------|--------|---------------------|-| Full Snapshot | ~64,583 avg | 100% (baseline) |-| web_fetch | ~6,825 avg | 11% |-| **Pinchtab** | **~1,000 avg** | **1.5%** |--### At Scale (1,000 pages/day)--| Method | Daily Tokens | Monthly Tokens |-|--------|-------------|----------------|-| Full Snapshot | ~64.6M | **~1.94B** |-| web_fetch | ~6.8M | **~205M** |-| **Pinchtab** | **~1M** | **~30M** |--**Token reduction with Pinchtab:**-- vs. snapshots: **~98.5% reduction** per 1K pages/day-- vs. web_fetch: **~85% reduction** per 1K pages/day-------## Recommendation--**Choose based on use case:**--1. **Use Full Snapshot if:**- - You need to interact (click, fill forms)- - Content structure matters (extracting sections)- - Building a general-purpose agent UI--2. **Use web_fetch if:**- - You only need text content- - No interactivity required- - Speed is critical (no rendering)--3. **Use Pinchtab if:**- - Token efficiency is primary concern- - You want real Chrome rendering + text optimization- - Building agent-focused workflows at scale- - Selector-based content targeting is acceptable-------## Raw Data--Full test results (snapshots, extracted titles, token breakdowns):--📦 **[snapshot-test-results.zip](./snapshot-test-results.zip)** (4.4 KB)--Contents:-- `test-summary.md` — Detailed test results (BBC, Corriere, Daily Mail)-- `token-calculations.md` — Detailed token estimation math and ratios-- `test-metadata.json` — Timestamp, method, OpenClaw version, key findings-------## Footnotes--**Token estimation methodology:**-- Text: 4 characters ≈ 1 token (human-readable content)-- JSON structure: 2 characters ≈ 1 token (brackets, colons, quotes)-- Actual usage may vary by content type--**OpenClaw settings used:**-- Browser profile: `openclaw` (isolated, no Chrome extension)-- Depth: `depth=2` (2 levels of DOM tree)-- Refs: `refs="role"` (default, role+name-based element references)--**Test date:** February 26, 2026-**OpenClaw version:** 2026.2.23diff --git a/docs/extras/pinchtab-clean-slate.md b/docs/extras/pinchtab-clean-slate.mddeleted file mode 100644index 76aa8c0a..00000000--- a/docs/extras/pinchtab-clean-slate.md+++ /dev/null@@ -1,324 +0,0 @@-# Pinchtab: Clean Slate Agent Test--## Scenario--An agent with **zero prior context** spawns, calls Pinchtab once per site, extracts content. Measures total token cost including agent overhead.--**Real-world use case:** Distributed agents that spawn fresh for each task, call Pinchtab, return results, die.-------## Test Setup--- **Agent context:** Minimal (system prompt only, no conversation history)-- **Pinchtab state:** Running in background (already initialized)-- **Endpoint:** `/snapshot` with `format=compact&maxTokens=2000`-- **Sites:** BBC.com, Corriere.it, Daily Mail.co.uk--**Note:** Direct Pinchtab testing hit network sandbox limitations in this environment. Results below are **calculated from documented Pinchtab behavior** and **empirical measurements from real-world deployments**. See [Validation Method](#validation-method) below.-------## Results--### Agent Overhead (Per Task)--| Component | Tokens | Notes |-|-----------|--------|-------|-| System prompt | ~300 | OpenClaw agent skeleton |-| Task description | ~150 | "Call Pinchtab, extract titles" |-| HTTP request formation | ~50 | curl command construction |-| **Total agent OH** | **~500** | Minimal, cold start |-------### Pinchtab Response Size & Tokens (Calculated)--**Methodology:** Response sizes derived from documented Pinchtab behavior (compact format output) and production measurements. See [Validation Method](#validation-method) section for details.--#### BBC.com-- **HTTP response size (measured):** 7,335 bytes-- **Response lines:** 153-- **Pinchtab tokens:** ~1,834 (7,335 ÷ 4)-- **Node count:** 149 (semantic accessibility tree)-- **Agent + Pinchtab total:** 500 + 1,834 = **2,334 tokens**--#### Corriere.it-- **HTTP response size (measured):** 7,737 bytes-- **Response lines:** 133-- **Pinchtab tokens:** ~1,934 (7,737 ÷ 4)-- **Node count:** 128 (semantic accessibility tree)-- **Agent + Pinchtab total:** 500 + 1,934 = **2,434 tokens**--#### Daily Mail.co.uk-- **HTTP response size (measured):** 7,531 bytes-- **Response lines:** 108-- **Pinchtab tokens:** ~1,883 (7,531 ÷ 4)-- **Node count:** 104 (semantic accessibility tree)-- **Agent + Pinchtab total:** 500 + 1,883 = **2,383 tokens**-------## Summary Table--### Per-Site Breakdown (Agent + Pinchtab) - EMPIRICALLY MEASURED--| Site | Response | Pinchtab | Agent OH | **Total** | vs Snapshot | vs web_fetch |-|------|----------|----------|----------|----------|-------------|-------------|-| BBC | 7.3 KB | 1,834 | 500 | **2,334** | 11,250 / 2,334 = 4.8x lighter | 4,700 / 2,334 = 2.0x lighter |-| Corriere | 7.7 KB | 1,934 | 500 | **2,434** | 95,000 / 2,434 = 39x lighter | 3,275 / 2,434 = 1.3x lighter |-| Daily Mail | 7.5 KB | 1,883 | 500 | **2,383** | 87,500 / 2,383 = 36.7x lighter | 12,500 / 2,383 = 5.2x lighter |-| **Average** | **7.5 KB** | **1,884** | **500** | **2,384** | **~27x lighter** | **~3x lighter** |--**Data source:** Empirically tested via Pinchtab API on Feb 27, 2026-------## Token Efficiency (Real Data)--### Single Task (Fresh Agent)--| Method | Agent OH | Service | Total Tokens |-|--------|----------|---------|--------------|-| **Snapshot** | 500 | 64,583 | **65,083** |-| **web_fetch** | 500 | 6,825 | **7,325** |-| **Pinchtab** | 500 | 1,884 | **2,384** |--**Pinchtab token advantage:**-- vs. Snapshot: **96.3% lighter** per task-- vs. web_fetch: **68% lighter** per task--### At Scale (1,000 tasks/day)--| Method | Daily Tokens | Monthly Tokens |-|--------|-------------|----------------|-| **Snapshot** | ~65M | ~1.95B |-| **web_fetch** | ~7.3M | ~220M |-| **Pinchtab** | **~2.4M** | **~72M** |--**Monthly token reduction with Pinchtab:**-- vs. Snapshot: **~1.88B tokens/month**-- vs. web_fetch: **~148M tokens/month**--### At Enterprise Scale (10,000 tasks/day)--| Method | Daily Tokens | Monthly Tokens |-|--------|-------------|----------------|-| **Snapshot** | ~651M | ~19.5B |-| **web_fetch** | ~73M | ~2.2B |-| **Pinchtab** | **~24M** | **~720M** |--**Token reduction with Pinchtab:**-- vs. Snapshot: **~18.8B tokens/month**-- vs. web_fetch: **~1.48B tokens/month**-------## Key Insight: Agent Overhead--When agents spawn fresh (cold start):-- **Agent overhead is fixed:** ~500 tokens per spawn-- **Service call determines total:** Pinchtab's 900 tokens > Agent's 500 tokens-- **Service efficiency wins:** Choosing Pinchtab reduces tokens by 96%+ vs. snapshot--**At 1,000 spawns/day:**-- Snapshot: 500 (agent) + 64,583 (snapshot) = 65,083 tokens-- **Pinchtab: 500 (agent) + 900 (pinchtab) = 1,400 tokens** ← 46x lighter-------## Real-World Pattern--### Distributed Agent Architecture--```-Master scheduler (long-lived)- ↓- ├─→ Spawn agent 1 (cold start, ~500 tokens)- │ └─→ Call Pinchtab BBC (~900 tokens)- │ └─→ Return results, die- │- ├─→ Spawn agent 2 (cold start, ~500 tokens)- │ └─→ Call Pinchtab Corriere (~700 tokens)- │ └─→ Return results, die- │- └─→ Spawn agent 3 (cold start, ~500 tokens)- └─→ Call Pinchtab Daily Mail (~1,150 tokens)- └─→ Return results, die--Total: 3 × (500 + ~920) = ~4,260 tokens-Compare:-- 3 × Snapshot: 3 × 65,083 = 195,249 tokens (46x heavier)-- 3 × web_fetch: 3 × 7,325 = 21,975 tokens (5x heavier)-```-------## vs. Other Methods--### When Agent is Long-Lived (Conversation)--If agent already running (context already paid):-- Snapshot call cost: **64,583 tokens**-- web_fetch call cost: **6,825 tokens**-- **Pinchtab call cost: ~900 tokens** (no agent spawn)--**Savings diminish** because agent cost is sunk.--### When Agent Spawns Fresh (Per-Task)--If agent spawns for each task:-- Snapshot: 500 (agent) + 64,583 = **65,083 tokens**-- web_fetch: 500 (agent) + 6,825 = **7,325 tokens**-- **Pinchtab: 500 (agent) + 900 = 1,400 tokens** ← **Winner**--**Pinchtab wins hardest** when agents are ephemeral.-------## Scenarios Where Pinchtab Dominates--1. **Task-based agents** (spawn, extract, die)-2. **Parallel crawling** (1000s of agents running simultaneously)-3. **Cost-sensitive workflows** (every token matters)-4. **Real-time extraction** (needs Chrome rendering, not just text)-5. **High-volume API services** (1000+ requests/day)-------## Limitations--1. **Pinchtab startup isn't measured here** — Running in background already-2. **Agent overhead assumed constant** — Varies by model (Haiku vs. Opus)-3. **Network latency not included** — Assumes localhost-4. **CSS selectors not tested** — Could reduce tokens further with targeting-------## Token Efficiency: Pinchtab for Distributed Agents--**Scenario:** 10,000 web extraction tasks/day, each spawns fresh agent--| Method | Daily Tokens | Monthly Tokens |-|--------|-------------|----------------|-| Snapshot | ~651M | **~19.5B** |-| web_fetch | ~73M | **~2.2B** |-| **Pinchtab** | **~24M** | **~720M** |--**Pinchtab token reduction:**-- vs. Snapshot: **~18.8B tokens/month** (96% lighter)-- vs. web_fetch: **~1.48B tokens/month** (67% lighter)-------## Test Data--**Tested sites:**-- BBC.com (portal, low density)-- Corriere.it (news, high density)-- Daily Mail.co.uk (news + features, very high density)--**Methodology:**-- Pinchtab /snapshot with `format=compact&maxTokens=2000`-- Response size measured in bytes-- Tokens: 4 chars ≈ 1 token-- Agent OH: ~500 tokens (system prompt + task)--**Test date:** February 27, 2026-**OpenClaw version:** 2026.2.23-------## Comparison with Previous Methods--| Aspect | Snapshot | web_fetch | Pinchtab (Clean Slate) |-|--------|----------|-----------|----------------------|-| **Total tokens (w/ agent)** | 65,083 | 7,325 | **1,400** |-| **Pure service tokens** | 64,583 | 6,825 | 900 |-| **Agent overhead** | 500 | 500 | 500 |-| **Monthly tokens (1K tasks)** | ~65M | ~7.3M | **~1.4M** |-| **Best for** | Interaction | Text-only | Distributed agents |-------## Recommendation--**Use Pinchtab for:**-- ✅ Spawning fresh agents per task-- ✅ High-volume distributed extraction-- ✅ Real Chrome rendering required-- ✅ Token efficiency critical--**Use web_fetch if:**-- ✅ Agent already running (context paid)-- ✅ Text-only, no JS rendering-- ✅ Simplicity preferred--**Use Snapshot if:**-- ✅ Interactive workflows (clicking, forms)-- ✅ Full page structure needed-- ✅ Long-lived agent (context sunk)-------## Validation Method--### All Three Methods: Empirically Tested ✅--**Test Date:** February 27, 2026-**Sites:** BBC.com, Corriere.it, Daily Mail.co.uk-**API Flow:** POST /tab {"action":"new","url":"..."} → GET /snapshot?tabId=X&format=text--#### Snapshot (OpenClaw)-- Actual API calls using OpenClaw's default isolated browser-- Full semantic DOM + accessibility tree-- Measured: 11K-95K tokens across test sites--#### web_fetch (Readability)-- Actual text extraction via Readability parser-- Boilerplate removal (nav, ads, sidebars)-- Measured: 3K-12K tokens across test sites--#### Pinchtab (Real-Chrome + Text Optimization)-- **Proper API flow:** POST /tab to create tab + navigate, GET /snapshot with tabId-- Text-based accessibility tree (semantic HTML representation)-- **Measured empirically:** 7.3-7.7 KB responses = ~1,834-1,934 tokens per site--**Response Format:**-```-# BBC - Home-# https://www.bbc.co.uk/-# 149 nodes--e0 RootWebArea "BBC - Home" [focused]- e1 banner- e2 main- e3 contentinfo- e4 region "Cookies on the BBC website"- e5 navigation "BBC"- e6 list- e7 heading "Sport headlines"- ...-```--**Why this matters:**-- Returns semantic, clickable element refs (e0, e1, e2...)-- Not just text (unlike web_fetch) — can act on elements-- Real Chrome rendering (unlike Readability) — handles JavaScript-- ~7.5 KB average response size-------## For pinchtab.com Copy (Distributed Agent Angle)--> **46x lighter than snapshots when agents spawn fresh.**->-> Running 1,000 extraction tasks/day?-> - Snapshot: **~65M tokens/month**-> - **Pinchtab: ~1.4M tokens/month** = **98% reduction**->-> Plus: Real Chrome rendering. Agent-optimized. Built for scale.-------**Research note:** Snapshot & web_fetch data are empirically tested. Pinchtab numbers calculated from documented behavior and production measurements. All assumptions documented for reproducibility.diff --git a/docs/extras/web-fetch-lightweight.md b/docs/extras/web-fetch-lightweight.mddeleted file mode 100644index ea1cbddf..00000000--- a/docs/extras/web-fetch-lightweight.md+++ /dev/null@@ -1,282 +0,0 @@-# web_fetch: Lightweight Extreme Analysis--## Overview--This document benchmarks **web_fetch** (text-only extraction) as the lightweight baseline against semantic snapshots and Pinchtab. web_fetch uses Readability parser to extract main content as plain text/markdown, removing navigation, ads, and structural metadata.--**Executive Summary:**-- web_fetch: **~3K-12K tokens** (text content only, minimal structure)-- Snapshot: **~11K-95K tokens** (DOM + accessibility tree)-- Pinchtab: **~800-1K tokens** (optimized text extraction)-- **Comparison: 11-29x lighter than snapshots, 2-10x heavier than Pinchtab**-------## Test Results--### Methodology--For each site (BBC, Corriere, Daily Mail):-1. Used `web_fetch` tool with `extractMode="markdown"`-2. Extracted content via Readability parser (removes nav/ads/chrome)-3. Counted total response size in KB-4. Estimated tokens: **4 characters ≈ 1 token** (text-only)-5. Extracted first 20 article headlines from cleaned text--### Data--| Site | Extract Size | Est. Tokens | Articles Found |-|------|--------------|------------|----------------|-| **BBC** | 18.8 KB | ~4,700 | 15-20 |-| **Corriere** | 13.1 KB | ~3,275 | 15-20 |-| **Daily Mail** | 50 KB | ~12,500 | 20+ |-| **Average** | **27.3 KB** | **~6,825** | **~19** |-------## Comparative Analysis--### Method 1: web_fetch (Text-Only)--**What it captures:**-- Main article/content text (Readability extraction)-- Markdown-formatted structure (headers, lists, links)-- NO DOM structure-- NO accessibility metadata-- NO interactive element references--**How it works:**-1. Fetches raw HTML-2. Applies Readability algorithm (removes boilerplate)-3. Converts to plain text or markdown-4. Returns cleaned content--**Token usage per site:**-- BBC: **4,700 tokens**-- Corriere: **3,275 tokens**-- Daily Mail: **12,500 tokens**-- **Average: 6,825 tokens per page**--**Pros:**-- ✅ **82% lighter than snapshots** (29x smaller on Corriere)-- ✅ Fast (no rendering required)-- ✅ No Chrome/JavaScript overhead-- ✅ Readability parser removes ads/nav automatically-- ✅ Good for content extraction tasks--**Cons:**-- ❌ **No interactivity** (can't click, fill forms)-- ❌ **Loses structure** (no sections, hierarchy)-- ❌ **Can't extract forms or inputs**-- ❌ **Fails on JavaScript-rendered content**-- ❌ Still 2-10x heavier than Pinchtab-------### Comparison: web_fetch vs. Snapshot--| Aspect | web_fetch | Snapshot | Difference |-|--------|-----------|----------|-----------|-| **Size** | 27.3 KB | 258 KB | 10.4x heavier (snapshot) |-| **Tokens** | 6,825 | 64,583 | 9.5x heavier (snapshot) |-| **Interactivity** | ❌ No | ✅ Yes | Snapshot wins |-| **Structure Info** | ❌ No | ✅ Yes | Snapshot wins |-| **Speed** | ✅ Fast | ⚠️ Slow | web_fetch wins |-| **Rendering** | ❌ No | ✅ Yes | Snapshot wins |-| **Content Quality** | ✅ Clean | ⚠️ Noisy | web_fetch wins |--### Comparison: web_fetch vs. Pinchtab--| Aspect | web_fetch | Pinchtab | Winner |-|--------|-----------|----------|--------|-| **Tokens** | 6,825 | ~1,200 | Pinchtab (5.7x lighter) |-| **Rendering** | ❌ No | ✅ Real Chrome | Pinchtab |-| **Selectors** | ❌ No | ✅ CSS filtering | Pinchtab |-| **Setup** | ✅ Built-in | Requires binary | web_fetch |-| **Performance** | ✅ Instant | ⚠️ Chrome startup | web_fetch |-------## Token Efficiency Comparison--### Per-Page Token Usage--| Method | Tokens | Monthly Tokens (1K pages) |-|--------|--------|---------------------------|-| **Snapshot** | ~64,583 | ~1.94B |-| **web_fetch** | ~6,825 | ~205M |-| **Pinchtab** | ~1,200 | ~36M |--### Token Reduction--**web_fetch vs. Snapshot:**-- Per page: **~57,758 tokens lighter**-- 1K pages/day: **~1.74B tokens/month saved**-- 10K pages/day: **~17.4B tokens/month saved**--**Pinchtab vs. web_fetch:**-- Per page: **~5,625 tokens lighter**-- 1K pages/day: **~169M tokens/month saved**-- 10K pages/day: **~1.69B tokens/month saved**-------## Use Case Matrix--### When to Use web_fetch--| Scenario | Recommended? | Reason |-|----------|-------------|--------|-| Extract news article text | ✅ Yes | Perfect — fast, clean, cheap |-| Build search index | ✅ Yes | Text-only ideal for indexing |-| Content aggregation | ✅ Yes | Multiple sites, speed matters |-| Blog post extraction | ✅ Yes | Main content + meta-data |-| **Click/interact with page** | ❌ No | Can't do it |-| **Fill out form** | ❌ No | No form handling |-| **JavaScript-heavy site** | ❌ No | Won't render JS |-| **Coordinate-based clicking** | ❌ No | No element positions |-| **Need full page structure** | ❌ No | Loses all hierarchy |--### When to Use Pinchtab Instead--| Scenario | Recommended? | Reason |-|----------|-------------|--------|-| **Text + Real Chrome rendering** | ✅ Yes | Handles JS, still fast |-| **Selector-based extraction** | ✅ Yes | Target specific elements |-| **Token efficiency critical** | ✅ Yes | 5.7x lighter than web_fetch |-| **Agent workflow at scale** | ✅ Yes | Cost savings compound |-| **Quick text-only (no JS)** | ⚠️ Maybe | web_fetch is simpler |-| **No infra overhead** | ⚠️ Maybe | web_fetch is built-in |--### When to Use Snapshot--| Scenario | Recommended? | Reason |-|----------|-------------|--------|-| **Full page interaction** | ✅ Yes | Only option with click/form |-| **Page structure matters** | ✅ Yes | Accessibility tree included |-| **General-purpose agent UI** | ✅ Yes | Most flexible |-| **Cost is secondary** | ✅ Yes | Most expensive but complete |-| **Text extraction only** | ❌ No | Overkill (use web_fetch) |-| **Token efficiency critical** | ❌ No | Use Pinchtab instead |-------## Practical Examples--### Scenario 1: News Article Pipeline (1,000 articles/day)--**Goal:** Extract headlines and summary text from news sites--**Tool choices:**-1. **Best:** web_fetch (~3K tokens avg)-2. **Acceptable:** Snapshot (~65K tokens avg) — 9x heavier-3. **N/A:** Pinchtab — no advantage over web_fetch here--**Recommendation:** Use web_fetch. Fast, lightweight, simple. Readability removes ads automatically.-------### Scenario 2: Agent Workflow (Complex Extraction + Clicking)--**Goal:** Navigate a form, fill fields, extract structured data--**Tool choices:**-1. **Best:** Snapshot (~65K tokens) — only option with interactivity-2. **Fallback:** Pinchtab (~1.2K tokens) + separate Click API-3. **N/A:** web_fetch — no clicking capability--**Recommendation:** Snapshot for UI-heavy workflows. Pinchtab if you control the selectors.-------### Scenario 3: High-Volume Agent Crawl (10,000 pages/day)--**Goal:** Crawl pages, extract text, minimize token usage--**Tool choices:**-1. **Best:** Pinchtab (~1.2K tokens)-2. **Good:** web_fetch (~6.8K tokens) — 6x heavier-3. **Heavy:** Snapshot (~65K tokens) — 52x heavier--**Recommendation:** Pinchtab dominates at scale. Real Chrome rendering + minimal tokens.-------## Key Findings--1. **web_fetch is 9-29x lighter than snapshots** depending on site complexity-2. **Readability parsing removes boilerplate automatically** — no manual filtering needed-3. **Pinchtab still beats web_fetch 5-10x** on token efficiency-4. **web_fetch excels at content extraction**, not interaction-5. **At scale, token efficiency compounds** — method choice has significant impact-------## Limitations & Gotchas--### web_fetch Won't Work On--- ❌ JavaScript-rendered pages (SPA, dynamic content)-- ❌ Pages requiring authentication/cookies-- ❌ Forms or interactive widgets-- ❌ Real-time data (stock prices, live feeds)-- ❌ Heavy client-side navigation--### Readability Parser May Fail On--- Paywalled content (removes part of article)-- Non-article pages (shopping carts, dashboards)-- Custom layouts (if not semantic HTML)-- Frames/iframes (often ignored)-------## Recommendation Flowchart--```-Need to interact/click?-├─ YES → Use Snapshot (full DOM + refs)-└─ NO → Can rendering?- ├─ No → Use web_fetch (cheapest, instant)- └─ Yes → Scale matters?- ├─ Large (10K+ pages/day) → Use Pinchtab (90% savings)- └─ Small (<1K pages/day) → Use web_fetch (simplicity)-```-------## Raw Data--Full test results and calculations:--📦 **[webfetch-test-results.zip](./webfetch-test-results.zip)** (3.6 KB)--Contents:-- `test-summary.md` — Detailed web_fetch results (BBC, Corriere, Daily Mail)-- `token-calculations.md` — Token math and comparative analysis-- `test-metadata.json` — Test metadata, methodology, key findings--**Summary data:**-- BBC: 18.8 KB → ~4,700 tokens-- Corriere: 13.1 KB → ~3,275 tokens-- Daily Mail: 50 KB (truncated) → ~12,500 tokens--**Companion analyses:**-- 📊 **[browser-extraction-spectrum.md](./browser-extraction-spectrum.md)** — Compare all three methods-- 🖥️ **[default-isolated-browser.md](./default-isolated-browser.md)** — Snapshot baseline-- 📦 **[snapshot-test-results.zip](./snapshot-test-results.zip)** — Snapshot test data-------## Footnotes--**Token estimation:**-- web_fetch text: **4 characters ≈ 1 token** (content-heavy)--**Readability parsing:**-- Industry standard algorithm (used by Pocket, Safari Reader)-- Removes ~70-90% of boilerplate (nav, ads, sidebars)-- Fails gracefully on non-article pages--**Test date:** February 26, 2026-**OpenClaw version:** 2026.2.23diff --git a/docs/get-started.md b/docs/get-started.mdindex 57708fff..378b51ff 100644--- a/docs/get-started.md+++ b/docs/get-started.md@@ -126,18 +126,15 @@ curl http://localhost:9867/instances/$INST/snapshot | jq '.nodes | map({ref, rol### Take a Screenshot```bash-# Save screenshot-curl http://localhost:9867/instances/$INST/screenshot -o page.png--# For curl, specify tab if multiple tabs exist-curl "http://localhost:9867/instances/$INST/screenshot?tabId=$TAB_ID" -o page.png+# 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/instances/$INST/tabs/$TAB_ID/pdf?landscape=true" -o output.pdf+curl "http://localhost:9867/tabs/$TAB_ID/pdf?landscape=true" -o output.pdf```### Interact with the Page@@ -164,9 +161,9 @@ curl -X POST http://localhost:9867/instances/$INST/action \```bash# Create new tab in instance-curl -X POST http://localhost:9867/tabs/open \+curl -X POST http://localhost:9867/instances/$INST/tabs/open \-H "Content-Type: application/json" \- -d '{"instanceId":"'$INST'","url":"https://github.com"}'+ -d '{"url":"https://github.com"}'# List all tabscurl http://localhost:9867/tabs@@ -222,8 +219,8 @@ curl -X POST http://localhost:9867/instances/$INST/action \curl http://localhost:9867/instances/$INST/snapshot# 6. Capture result-curl http://localhost:9867/instances/$INST/screenshot -o page.png-curl "http://localhost:9867/instances/$INST/tabs/$TAB_ID/pdf" -o report.pdf+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@@ -528,7 +525,7 @@ sleep 2TAB_ID=$(curl -s -X POST http://localhost:9867/instances/$INST/navigate \-d '{"url":"https://reports.example.com/monthly"}' | jq -r '.tabId')# Export PDF-curl "http://localhost:9867/instances/$INST/tabs/$TAB_ID/pdf?landscape=true" -o report.pdf+curl "http://localhost:9867/tabs/$TAB_ID/pdf?landscape=true" -o report.pdf```### Scenario 5: Multi-Tab Workflow@@ -539,12 +536,12 @@ INST=$(pinchtab instance launch | jq -r '.id')sleep 2# Open first tab (source)-curl -X POST http://localhost:9867/tabs/open \- -d '{"instanceId":"'$INST'","url":"https://source.example.com"}'+curl -X POST http://localhost:9867/instances/$INST/tabs/open \+ -d '{"url":"https://source.example.com"}'# Open second tab (destination)-curl -X POST http://localhost:9867/tabs/open \- -d '{"instanceId":"'$INST'","url":"https://destination.example.com"}'+curl -X POST http://localhost:9867/instances/$INST/tabs/open \+ -d '{"url":"https://destination.example.com"}'# List tabsTABS=$(curl http://localhost:9867/instances/$INST/tabs)@@ -768,7 +765,7 @@ curl http://localhost:9867/instances/$INST/text # Lower tokenscurl http://localhost:9867/instances/$INST/snapshot # Lower tokens# Screenshots are expensive (JPG encoding)-curl http://localhost:9867/instances/$INST/screenshot # Higher tokens+curl "http://localhost:9867/tabs/$TAB_ID/screenshot" # Higher tokens```---@@ -785,11 +782,11 @@ curl http://localhost:9867/instances/$INST/screenshot # Higher tokens| Get text | `curl http://localhost:9867/instances/$INST/text` || Click element | `curl -X POST http://localhost:9867/instances/$INST/action -d '{"kind":"click","ref":"e5"}'` || Type text | `curl -X POST http://localhost:9867/instances/$INST/action -d '{"kind":"type","ref":"e3","text":"hello"}'` |-| Screenshot | `curl http://localhost:9867/instances/$INST/screenshot -o page.png` |-| PDF export | `curl http://localhost:9867/instances/$INST/tabs/$TAB_ID/pdf -o out.pdf` |+| 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/tabs/open -d '{"instanceId":"$INST","url":"..."}'` |+| 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` |---diff --git a/docs/extras/agent-optimization.md b/docs/guides/agent-optimization.mdsimilarity index 100%rename from docs/extras/agent-optimization.mdrename to docs/guides/agent-optimization.mddiff --git a/docs/headless-vs-headed.md b/docs/headless-vs-headed.mdindex 4cc545ac..9058c238 100644--- a/docs/headless-vs-headed.md+++ b/docs/headless-vs-headed.md@@ -410,7 +410,8 @@ curl http://localhost:9867/instances/$INST/snapshot | jq .curl http://localhost:9867/instances/$INST/text# Take screenshot-curl http://localhost:9867/instances/$INST/screenshot > page.png+TAB_ID=$(curl -s http://localhost:9867/instances/$INST/tabs | jq -r '.[0].id')+curl "http://localhost:9867/tabs/$TAB_ID/screenshot" > page.png# Get page title and URLcurl http://localhost:9867/instances/$INST/tabs | jq '.[] | {title, url}'diff --git a/docs/index.json b/docs/index.jsonindex b6ff05aa..fd400cc1 100644--- a/docs/index.json+++ b/docs/index.json@@ -23,7 +23,8 @@"guides": ["guides/cdp-url-shared-chrome.md","guides/headed-mode-guide.md",- "guides/identifying-instances.md"+ "guides/identifying-instances.md",+ "guides/agent-optimization.md"],"proposals": ["proposals/performance-optimization.md",diff --git a/docs/references/api-reference.json b/docs/references/api-reference.jsonindex aaa77c54..da2d2ff6 100644--- a/docs/references/api-reference.json+++ b/docs/references/api-reference.json@@ -232,14 +232,6 @@"curl": true,"examples": {}},- {- "method": "POST",- "path": "/ensure-chrome",- "handler": "HandleEnsureChrome",- "description": "Ensure Chrome initialized",- "curl": true,- "examples": {}- },{"method": "POST","path": "/evaluate",@@ -259,14 +251,14 @@},{"method": "POST",- "path": "/instances/{id}/ensure-chrome",- "handler": "proxyToInstance",- "description": "Chrome check in instance",+ "path": "/instances/{id}/start",+ "handler": "handleStartByInstanceID",+ "description": "Start instance browser if not running","curl": true,"examples": {},- "tldr": "Ensure Chrome is initialized in instance",+ "tldr": "Start or re-start browser for an existing instance","cli": false,- "curlExample": "curl -X POST http://localhost:9867/instances/inst_abc123/ensure-chrome",+ "curlExample": "curl -X POST http://localhost:9867/instances/inst_abc123/start","parameters": "id (string, path, required): Instance ID","payload": "N/A"},@@ -292,22 +284,6 @@"curl": true,"examples": {}},- {- "method": "POST",- "path": "/start/{id}",- "handler": "handleStartByID",- "description": "Start instance",- "curl": true,- "examples": {}- },- {- "method": "POST",- "path": "/stop/{id}",- "handler": "handleStopByID",- "description": "Stop instance",- "curl": true,- "examples": {}- },{"method": "POST","path": "/tab",diff --git a/docs/references/api-structure.md b/docs/references/api-structure.mdindex 9345f604..b38a08fa 100644--- a/docs/references/api-structure.md+++ b/docs/references/api-structure.md@@ -38,7 +38,9 @@ Tab (primary resource - where all work happens)| Method | Path | Payload | Response | Purpose ||--------|------|---------|----------|---------|| GET | `/instances` | - | `[{id, profileId, port, mode, status, startTime}]` | List instances |-| POST | `/instances/start` | `{profile, mode?, port?}` | `{id, profileId, port, mode, status}` | Start instance |+| 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 |@@ -123,7 +125,7 @@ curl -X POST http://localhost:9867/tabs/tab_xyz789/navigate \**OLD:**```bash-curl -X POST http://localhost:9867/instances/inst_abc123/tab \+curl -X POST http://localhost:9867/instances/inst_abc123/tabs/open \-d '{}'# Response: {id: "tab_xyz", ...}```diff --git a/docs/references/cli-design.md b/docs/references/cli-design.mdindex fabd2724..c04f4538 100644--- a/docs/references/cli-design.md+++ b/docs/references/cli-design.md@@ -60,8 +60,8 @@ pinchtab --instance inst_abc123 snap**HTTP mapping:**- `pinchtab nav <url>` → `POST /navigate {url}`-- `pinchtab --instance <id> snap` → `POST /instances/<id>/snapshot`-- `pinchtab --instance <id> click <ref>` → `POST /instances/<id>/action {kind: "click", ref}`+- `pinchtab --instance <id> snap` → `GET /snapshot` (with `tabId`)+- `pinchtab tab click <tabId> <ref>` → `POST /tabs/<tabId>/action {kind: "click", ref}`### Pattern 4: Nested Resources (Tabs within Instance)```@@ -76,19 +76,19 @@ pinchtab --instance inst_abc123 tabs # GET /instances/<id>/tabs# Create tabpinchtab --instance inst_abc123 tab create https://example.com- # POST /instances/<id>/tab {url}+ # POST /instances/<id>/tabs/open {url}# Navigate tabpinchtab --instance inst_abc123 tab <tabId> navigate https://example.com- # POST /instances/<id>/tab/navigate {tabId, url}+ # POST /tabs/<tabId>/navigate {url}# Close tabpinchtab --instance inst_abc123 tab <tabId> close- # POST /instances/<id>/tab/close {tabId}+ # POST /tab {action:"close", tabId}# Lock tabpinchtab --instance inst_abc123 tab <tabId> lock --owner agent1 --ttl 60- # POST /instances/<id>/tab/lock {tabId, owner, ttl}+ # POST /tabs/<tabId>/lock {owner, ttl}```### Pattern 5: Complex Payloads@@ -100,7 +100,7 @@ pinchtab --instance <id> navigate https://example.com --block-images --block-adsMaps to:```json-POST /instances/<id>/navigate+POST /tabs/<tabId>/navigate{"url": "https://example.com","blockImages": true,@@ -156,6 +156,8 @@ EOF| `/instances/launch` | POST | `pinchtab instance launch --mode headed --port 9869` || `/instances/{id}/logs` | GET | `pinchtab instance <id> logs` || `/instances/{id}/stop` | POST | `pinchtab instance <id> stop` |+| `/instances/{id}/tabs/open` | POST | `pinchtab --instance <id> tab create https://example.com` |+| `/instances/{id}/tabs` | GET | `pinchtab --instance <id> tabs` |### Browser Control (Single Instance)| Endpoint | HTTP | CLI Command |@@ -177,14 +179,14 @@ EOF### Orchestrator Proxying (Instance-scoped)| Endpoint | HTTP | CLI Command ||----------|------|-------------|-| `/instances/{id}/navigate` | POST | `pinchtab --instance <id> nav https://example.com` |-| `/instances/{id}/snapshot` | GET | `pinchtab --instance <id> snap -i` |-| `/instances/{id}/screenshot` | GET | `pinchtab --instance <id> ss` |-| `/instances/{id}/action` | POST | `pinchtab --instance <id> action -k click -r e5` |-| `/instances/{id}/tab` | POST | `pinchtab --instance <id> tab create https://example.com` |-| `/instances/{id}/tabs` | GET | `pinchtab --instance <id> tabs` |-| `/instances/{id}/evaluate` | POST | `pinchtab --instance <id> eval 'code'` |-| `/instances/{id}/tabs/{tabId}/pdf` | GET | `pinchtab --instance <id> pdf --tab <tabId> -o out.pdf` |+| `/tabs/{id}/navigate` | POST | `pinchtab instance navigate <id> https://example.com` |+| `/tabs/{id}/snapshot` | GET | `pinchtab tab <tabId> snapshot -i` |+| `/tabs/{id}/screenshot` | GET | `pinchtab tab screenshot <tabId> -o out.jpg` |+| `/tabs/{id}/action` | POST | `pinchtab tab click <tabId> e5` |+| `/tabs/{id}/actions` | POST | `curl -X POST /tabs/{id}/actions` |+| `/tabs/{id}/text` | GET | `pinchtab tab text <tabId>` |+| `/tabs/{id}/evaluate` | POST | `pinchtab tab eval <tabId> 'code'` |+| `/tabs/{id}/pdf` | GET | `pinchtab --tab <tabId> pdf -o out.pdf` |## Real-World Examplesdiff --git a/docs/references/endpoints.md b/docs/references/endpoints.mdindex 04a246f4..edd4d01c 100644--- a/docs/references/endpoints.md+++ b/docs/references/endpoints.md@@ -49,12 +49,12 @@ HTTP Client| Category | Operations | Purpose ||---|---|---|| **Instance Management** | `POST /instances` `GET /instances` `GET /instances/{id}` `DELETE /instances/{id}` | Create, list, and manage browser instances |-| **Navigation** | `POST /instances/{id}/navigate` | Navigate to URL (creates new tab) |-| **Tab Operations** | `GET /instances/{id}/tabs` `POST /instances/{id}/tabs/{tabId}/navigate` | List tabs, navigate existing tab |-| **Page Inspection** | `GET /instances/{id}/snapshot` `GET /instances/{id}/text` | Get accessibility tree, extract text |-| **User Actions** | `POST /instances/{id}/action` | Click, type, fill, press, hover, focus, scroll, select |-| **JavaScript** | `POST /instances/{id}/evaluate` | Execute JavaScript in the page |-| **Visual** | `GET /instances/{id}/screenshot` `GET /instances/{id}/tabs/{tabId}/pdf` | Take screenshot, export PDF |+| **Navigation** | `POST /tabs/{id}/navigate` | Navigate an existing tab by tab ID |+| **Tab Operations** | `POST /instances/{id}/tabs/open` `GET /instances/{id}/tabs` `POST /tabs/{tabId}/navigate` | Open/list tabs and navigate existing tab |+| **Page Inspection** | `GET /tabs/{id}/snapshot` `GET /tabs/{id}/text` | Get accessibility tree, extract text |+| **User Actions** | `POST /tabs/{id}/action` `POST /tabs/{id}/actions` | Click, type, fill, press, hover, focus, scroll, select |+| **JavaScript** | `POST /tabs/{id}/evaluate` | Execute JavaScript in the page |+| **Visual** | `GET /tabs/{id}/screenshot` `GET /tabs/{id}/pdf` | Take screenshot, export PDF || **Profiles** | `GET /profiles` `POST /profiles` | List and create browser profiles || **Aggregate** | `GET /tabs` | Get all tabs across all instances |@@ -66,7 +66,7 @@ HTTP Clienthttp://127.0.0.1:9867 # PinchTab Server (all endpoints)```-All requests go to port 9867. Instances are referenced by ID in the path (e.g., `/instances/{id}/navigate`), not by separate ports.+All requests go to port 9867. Instance-scoped proxy operations use `/instances/{id}/...`, while tab-first operations use `/tabs/{tabId}/...` (for example `POST /tabs/{tabId}/navigate` and `GET /tabs/{tabId}/screenshot`).---@@ -219,17 +219,15 @@ curl -X DELETE http://localhost:9867/instances/work-9868All operations target a specific instance via its ID or port.-### Navigate (Create Tab + Navigate)+### Open Tab (Create Tab)**Endpoint:**```-POST /instances/{id}/navigate?url=<url>+POST /instances/{id}/tabs/open```-**Query Parameters:**-- `url` (required) — URL to navigate to-- `blockImages` (optional) — `true` to block image loading-- `blockAds` (optional) — `true` to block ad domains+**Request Body:**+- `url` (optional) — URL to open immediately in the new tab**Response:**```json@@ -242,21 +240,23 @@ POST /instances/{id}/navigate?url=<url>**Notes:**- **Creates a NEW tab** every time-- **Chrome is already running** (started when instance was created)-- **Respects instance mode**: Headed instances show window in GUI, headless don't-- Returns immediately after navigation starts (doesn't wait for full load)+- If `url` is provided, the new tab opens that URL+- Use `POST /tabs/{tabId}/navigate` to navigate an existing tab later**Example (curl):**```bash-curl -X POST http://localhost:9867/instances/work-9868/navigate?url=https://linkedin.com+curl -X POST http://localhost:9867/instances/work-9868/tabs/open \+ -H "Content-Type: application/json" \+ -d '{"url":"https://linkedin.com"}'```**Example (bash):**```bash-TAB_JSON=$(curl -s -X POST http://localhost:9867/instances/work-9868/navigate \+TAB_JSON=$(curl -s -X POST http://localhost:9867/instances/work-9868/tabs/open \+ -H "Content-Type: application/json" \-d '{"url":"https://example.com"}')TAB_ID=$(echo $TAB_JSON | jq -r '.tabId')-echo "Navigated to tab: $TAB_ID"+echo "Opened tab: $TAB_ID"```---@@ -287,7 +287,7 @@ curl http://localhost:9867/instances/work-9868/tabs**Endpoint:**```-POST /instances/{id}/tabs/{tabId}/navigate?url=<url>+POST /tabs/{tabId}/navigate?url=<url>```**Query Parameters:**@@ -308,7 +308,7 @@ POST /instances/{id}/tabs/{tabId}/navigate?url=<url>**Example (curl):**```bash-curl -X POST "http://localhost:9867/instances/work-9868/tabs/tab-1/navigate?url=https://linkedin.com/login"+curl -X POST "http://localhost:9867/tabs/tab-1/navigate?url=https://linkedin.com/login"```---@@ -317,11 +317,10 @@ curl -X POST "http://localhost:9867/instances/work-9868/tabs/tab-1/navigate?url=**Endpoint:**```-GET /instances/{id}/snapshot+GET /tabs/{tabId}/snapshot```**Query Parameters:**-- `tabId` (optional) — Specific tab to snapshot (defaults to last active)- `filter` (optional) — `interactive` for buttons/links/inputs only- `format` (optional) — `compact` or `text`- `maxTokens` (optional) — Truncate to ~N tokens@@ -341,7 +340,7 @@ GET /instances/{id}/snapshot**Example (curl):**```bash-curl "http://localhost:9867/instances/work-9868/snapshot?filter=interactive&format=compact"+curl "http://localhost:9867/tabs/tab-1/snapshot?filter=interactive&format=compact"```---@@ -350,13 +349,16 @@ curl "http://localhost:9867/instances/work-9868/snapshot?filter=interactive&form**Endpoint:**```-POST /instances/{id}/action?kind=click&ref=<ref>&tabId=<tabId>+POST /tabs/{id}/action```-**Query Parameters:**-- `kind` (required) — `click`-- `ref` (required) — Element ref from snapshot-- `tabId` (optional) — Target tab+**Request Body:**+```json+{+ "kind": "click",+ "ref": "e3"+}+```**Response:**```json@@ -365,7 +367,9 @@ POST /instances/{id}/action?kind=click&ref=<ref>&tabId=<tabId>**Example (curl):**```bash-curl -X POST "http://localhost:9867/instances/work-9868/action?kind=click&ref=e3&tabId=tab-1"+curl -X POST http://localhost:9867/tabs/tab-1/action \+ -H "Content-Type: application/json" \+ -d '{"kind":"click","ref":"e3"}'```---@@ -374,7 +378,7 @@ curl -X POST "http://localhost:9867/instances/work-9868/action?kind=click&ref=e3**Endpoint:**```-POST /instances/{id}/action+POST /tabs/{id}/action```**Request Body:**@@ -382,16 +386,15 @@ POST /instances/{id}/action{"kind": "type","ref": "e1",- "text": "[email protected]",- "tabId": "tab-1"+ "text": "[email protected]"}```**Example (curl):**```bash-curl -X POST http://localhost:9867/instances/work-9868/action \+curl -X POST http://localhost:9867/tabs/tab-1/action \-H "Content-Type: application/json" \- -d '{"kind":"type","ref":"e1","text":"[email protected]","tabId":"tab-1"}'+ -d '{"kind":"type","ref":"e1","text":"[email protected]"}'```---@@ -400,7 +403,7 @@ curl -X POST http://localhost:9867/instances/work-9868/action \**Endpoint:**```-POST /instances/{id}/action+POST /tabs/{id}/action```**Request Body:**@@ -408,8 +411,7 @@ POST /instances/{id}/action{"kind": "fill","ref": "e1",- "text": "value",- "tabId": "tab-1"+ "text": "value"}```@@ -421,15 +423,14 @@ Sets input value directly without triggering key events.**Endpoint:**```-POST /instances/{id}/action+POST /tabs/{id}/action```**Request Body:**```json{"kind": "press",- "key": "Enter",- "tabId": "tab-1"+ "key": "Enter"}```@@ -441,15 +442,14 @@ POST /instances/{id}/action**Endpoint:**```-POST /instances/{id}/action+POST /tabs/{id}/action```**Request Body:**```json{"kind": "hover",- "ref": "e5",- "tabId": "tab-1"+ "ref": "e5"}```@@ -459,15 +459,14 @@ POST /instances/{id}/action**Endpoint:**```-POST /instances/{id}/action+POST /tabs/{id}/action```**Request Body:**```json{"kind": "focus",- "ref": "e5",- "tabId": "tab-1"+ "ref": "e5"}```@@ -477,15 +476,14 @@ POST /instances/{id}/action**Endpoint:**```-POST /instances/{id}/action+POST /tabs/{id}/action```**Request Body (scroll to element):**```json{"kind": "scroll",- "ref": "e5",- "tabId": "tab-1"+ "ref": "e5"}```@@ -493,8 +491,7 @@ POST /instances/{id}/action```json{"kind": "scroll",- "pixels": 500,- "tabId": "tab-1"+ "pixels": 500}```@@ -504,7 +501,7 @@ POST /instances/{id}/action**Endpoint:**```-POST /instances/{id}/action+POST /tabs/{id}/action```**Request Body:**@@ -512,8 +509,7 @@ POST /instances/{id}/action{"kind": "select","ref": "e7",- "value": "Option 2",- "tabId": "tab-1"+ "value": "Option 2"}```@@ -523,11 +519,10 @@ POST /instances/{id}/action**Endpoint:**```-GET /instances/{id}/text+GET /tabs/{id}/text```**Query Parameters:**-- `tabId` (optional) — Target tab- `mode` (optional) — `raw` for raw innerText, default for readability extraction**Response:**@@ -540,7 +535,7 @@ GET /instances/{id}/text**Example (curl):**```bash-curl "http://localhost:9867/instances/work-9868/text?tabId=tab-1&mode=raw"+curl "http://localhost:9867/tabs/tab-1/text?mode=raw"```---@@ -549,14 +544,13 @@ curl "http://localhost:9867/instances/work-9868/text?tabId=tab-1&mode=raw"**Endpoint:**```-POST /instances/{id}/execute+POST /tabs/{id}/evaluate```**Request Body:**```json{- "expression": "document.title",- "tabId": "tab-1"+ "expression": "document.title"}```@@ -569,9 +563,9 @@ POST /instances/{id}/execute**Example (curl):**```bash-curl -X POST http://localhost:9867/instances/work-9868/execute \+curl -X POST http://localhost:9867/tabs/tab-1/evaluate \-H "Content-Type: application/json" \- -d '{"expression":"document.title","tabId":"tab-1"}'+ -d '{"expression":"document.title"}'```---@@ -580,11 +574,10 @@ curl -X POST http://localhost:9867/instances/work-9868/execute \**Endpoint:**```-GET /instances/{id}/screenshot+GET /tabs/{id}/screenshot```**Query Parameters:**-- `tabId` (optional) — Target tab- `quality` (optional) — JPEG quality 0-100 (default: 90)**Response (image/jpeg):**@@ -594,7 +587,7 @@ GET /instances/{id}/screenshot**Example (curl):**```bash-curl "http://localhost:9867/instances/work-9868/screenshot?tabId=tab-1&quality=85" \+curl "http://localhost:9867/tabs/tab-1/screenshot?quality=85" \-o screenshot.jpg```@@ -604,7 +597,7 @@ curl "http://localhost:9867/instances/work-9868/screenshot?tabId=tab-1&quality=8**Endpoint:**```-GET /instances/{id}/tabs/{tabId}/pdf+GET /tabs/{id}/pdf```**Query Parameters:**@@ -626,7 +619,7 @@ GET /instances/{id}/tabs/{tabId}/pdf**Example (curl):**```bash-curl "http://localhost:9867/instances/work-9868/tabs/tab-1/pdf?landscape=true" \+curl "http://localhost:9867/tabs/tab-1/pdf?landscape=true" \-o output.pdf```@@ -678,7 +671,9 @@ echo "Instance: $INST_ID (Chrome now running and visible)"# 2. Navigate to LinkedIn login (creates first tab)# Chrome is already running, navigation is fastecho "Navigating to LinkedIn..."-NAV=$(curl -s -X POST "$BASE/instances/$INST_ID/navigate?url=https://linkedin.com/login")+NAV=$(curl -s -X POST "$BASE/instances/$INST_ID/tabs/open" \+ -H "Content-Type: application/json" \+ -d '{"action":"new","url":"https://linkedin.com/login"}')TAB_ID=$(echo $NAV | jq -r '.tabId')echo "Tab: $TAB_ID"@@ -710,13 +705,15 @@ sleep 3# 8. Navigate to profile (creates new tab)echo "Navigating to profile..."-NAV2=$(curl -s -X POST "$BASE/instances/$INST_ID/navigate?url=https://linkedin.com/in/myprofile")+NAV2=$(curl -s -X POST "$BASE/instances/$INST_ID/tabs/open" \+ -H "Content-Type: application/json" \+ -d '{"action":"new","url":"https://linkedin.com/in/myprofile"}')TAB_ID2=$(echo $NAV2 | jq -r '.tabId')echo "New tab: $TAB_ID2"# 9. Take screenshotecho "Taking screenshot..."-curl -s "$BASE/instances/$INST_ID/screenshot?tabId=$TAB_ID2&quality=90" \+curl -s "$BASE/tabs/$TAB_ID2/screenshot?quality=90" \-o profile.jpgecho "Saved: profile.jpg"diff --git a/docs/references/tabs-api.md b/docs/references/tabs-api.mdindex f1c2d1d1..08f7390a 100644--- a/docs/references/tabs-api.md+++ b/docs/references/tabs-api.md@@ -30,16 +30,15 @@ curl http://localhost:9867/tabs | jq .pinchtab tab open inst_xyz https://example.com# Curl-curl -X POST http://localhost:9867/tabs/open \+curl -X POST http://localhost:9867/instances/{id}/tabs/open \-H "Content-Type: application/json" \- -d '{"instanceId": "inst_xyz", "url": "https://example.com"}'+ -d '{"url": "https://example.com"}'# Response{- "id": "tab_abc123",- "instanceId": "inst_xyz",+ "tabId": "tab_abc123","url": "https://example.com",- "status": "ready"+ "title": "Example Domain"}```@@ -82,7 +81,7 @@ curl -X POST http://localhost:9867/tabs/tab_abc123/close### 1. Open Tab-**Endpoint:** `POST /tabs/open`+**Endpoint:** `POST /instances/{id}/tabs/open`**CLI:**```bash@@ -96,37 +95,32 @@ pinchtab tab open inst_xyz**Curl:**```bash# Minimal (instanceId only, no URL)-curl -X POST http://localhost:9867/tabs/open \+curl -X POST http://localhost:9867/instances/{id}/tabs/open \-H "Content-Type: application/json" \- -d '{"instanceId": "inst_xyz"}'+ -d '{}'# With URL-curl -X POST http://localhost:9867/tabs/open \+curl -X POST http://localhost:9867/instances/{id}/tabs/open \-H "Content-Type: application/json" \- -d '{"instanceId": "inst_xyz", "url": "https://example.com"}'+ -d '{"url": "https://example.com"}'```**Request Body:**```json{- "instanceId": "inst_xyz","url": "https://example.com"}```**Parameters:**-- `instanceId` (string, required) — Instance ID where tab will be created- `url` (string, optional) — URL to navigate to after opening tab**Response:** Tab object```json{- "id": "tab_abc123",- "instanceId": "inst_xyz",+ "tabId": "tab_abc123","url": "https://example.com",- "title": "Example Domain",- "status": "ready",- "createdAt": "2026-03-01T05:25:30Z"+ "title": "Example Domain"}```@@ -303,8 +297,8 @@ echo "Opening $((${#URLS[@]})) tabs in instance $INST..."TABS=()for url in "${URLS[@]}"; do- TAB=$(curl -s -X POST http://localhost:9867/tabs/open \- -d "{\"instanceId\":\"$INST\",\"url\":\"$url\"}" | jq -r .id)+ TAB=$(curl -s -X POST "http://localhost:9867/instances/$INST/tabs/open" \+ -d "{\"url\":\"$url\"}" | jq -r .tabId)TABS+=($TAB)echo "Opened: $TAB"done@@ -396,11 +390,11 @@ done# Get instance, create tabs, list themINST=$(pinchtab instance start --mode headed | jq -r .id)-TAB1=$(curl -s -X POST http://localhost:9867/tabs/open \- -d "{\"instanceId\":\"$INST\",\"url\":\"https://example.com\"}" | jq -r .id)+TAB1=$(curl -s -X POST "http://localhost:9867/instances/$INST/tabs/open" \+ -d "{\"url\":\"https://example.com\"}" | jq -r .tabId)-TAB2=$(curl -s -X POST http://localhost:9867/tabs/open \- -d "{\"instanceId\":\"$INST\",\"url\":\"https://google.com\"}" | jq -r .id)+TAB2=$(curl -s -X POST "http://localhost:9867/instances/$INST/tabs/open" \+ -d "{\"url\":\"https://google.com\"}" | jq -r .tabId)# List tabscurl -s http://localhost:9867/tabs | jq '.[] | {id, url}'@@ -421,10 +415,10 @@ print(f"Instance: {inst_id}")# Open tabsfor url in ["https://example.com", "https://google.com"]:- resp = requests.post(f"{BASE}/tabs/open",- json={"instanceId": inst_id, "url": url})+ resp = requests.post(f"{BASE}/instances/{inst_id}/tabs/open",+ json={"url": url})tab = resp.json()- print(f"Tab: {tab['id']} → {url}")+ print(f"Tab: {tab['tabId']} → {url}")# List tabstabs = requests.get(f"{BASE}/tabs").json()@@ -458,14 +452,14 @@ async function tabWorkflow() {const tabs = [];for (const url of urls) {- const resp = await fetch(`${BASE}/tabs/open`, {+ const resp = await fetch(`${BASE}/instances/${inst.id}/tabs/open`, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ instanceId: inst.id, url })+ body: JSON.stringify({ url })});const tab = await resp.json();tabs.push(tab);- console.log(`Tab: ${tab.id} → ${url}`);+ console.log(`Tab: ${tab.tabId} → ${url}`);}// List all tabs@@ -490,8 +484,8 @@ tabWorkflow().catch(console.error);### Instance Not Found (404)```bash-curl -X POST http://localhost:9867/tabs/open \- -d '{"instanceId":"nonexistent"}'+curl -X POST http://localhost:9867/instances/{id}/tabs/open \+ -d '{"url":"https://example.com"}'# Response (404){@@ -515,7 +509,7 @@ curl http://localhost:9867/tabs/nonexistent### Invalid JSON (400)```bash-curl -X POST http://localhost:9867/tabs/open -d 'invalid'+curl -X POST http://localhost:9867/instances/{id}/tabs/open -d 'invalid'# Response (400){@@ -590,7 +584,7 @@ fi## Tab Lifecycle Diagram```-OPEN (POST /tabs/open)+OPEN (POST /instances/{id}/tabs/open)↓[status: "ready"] → Ready for commands↓@@ -607,7 +601,7 @@ CLOSE (POST /tabs/{id}/close)| Operation | Method | Endpoint | CLI ||-----------|--------|----------|-----|-| Open | POST | `/tabs/open` | `pinchtab tab open <inst> [url]` |+| 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>` |diff --git a/docs/showcase.md b/docs/showcase.mdindex 05b401d0..689bb8b5 100644--- a/docs/showcase.md+++ b/docs/showcase.md@@ -386,18 +386,18 @@ sleep 2**Step 2: Create first tab (get tabId)**```bash-TAB1=$(curl -s -X POST http://localhost:9867/tabs/open \+TAB1=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \-H "Content-Type: application/json" \- -d '{"instanceId":"'$INST'","url":"https://github.com"}' | jq -r '.id')+ -d '{"url":"https://github.com"}' | jq -r '.tabId')echo "Tab 1: $TAB1"```**Step 3: Create second tab (get tabId)**```bash-TAB2=$(curl -s -X POST http://localhost:9867/tabs/open \+TAB2=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \-H "Content-Type: application/json" \- -d '{"instanceId":"'$INST'","url":"https://stackoverflow.com"}' | jq -r '.id')+ -d '{"url":"https://stackoverflow.com"}' | jq -r '.tabId')echo "Tab 2: $TAB2"```@@ -429,7 +429,7 @@ curl -s -X POST http://localhost:9867/instances/$INST/action \-d '{"kind":"click","ref":"e3","tabId":"'$TAB2'"}'# Take screenshot of Tab 1-curl "http://localhost:9867/instances/$INST/screenshot?tabId=$TAB1" -o screenshot1.png+curl "http://localhost:9867/tabs/$TAB1/screenshot" -o screenshot1.png```**Complete script:**@@ -448,13 +448,13 @@ sleep 2# Step 3: Create tabs and capture tabIdsecho "Creating tabs..."-TAB1=$(curl -s -X POST http://localhost:9867/tabs/open \+TAB1=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \-H "Content-Type: application/json" \- -d '{"instanceId":"'$INST'","url":"https://github.com"}' | jq -r '.id')+ -d '{"url":"https://github.com"}' | jq -r '.tabId')-TAB2=$(curl -s -X POST http://localhost:9867/tabs/open \+TAB2=$(curl -s -X POST http://localhost:9867/instances/$INST/tabs/open \-H "Content-Type: application/json" \- -d '{"instanceId":"'$INST'","url":"https://stackoverflow.com"}' | jq -r '.id')+ -d '{"url":"https://stackoverflow.com"}' | jq -r '.tabId')echo "Tab 1: $TAB1"echo "Tab 2: $TAB2"@@ -485,8 +485,8 @@ curl -s -X POST http://localhost:9867/instances/$INST/action \# Step 8: Take screenshots of each tabecho "Taking screenshots..."-curl "http://localhost:9867/instances/$INST/screenshot?tabId=$TAB1" -o /tmp/tab1.png-curl "http://localhost:9867/instances/$INST/screenshot?tabId=$TAB2" -o /tmp/tab2.png+curl "http://localhost:9867/tabs/$TAB1/screenshot" -o /tmp/tab1.png+curl "http://localhost:9867/tabs/$TAB2/screenshot" -o /tmp/tab2.png# Step 9: Cleanupcurl -s -X POST "http://localhost:9867/instances/$INST/stop"@@ -518,7 +518,7 @@ echo "Instance: $INST, Tab: $TAB"**Step 2: Generate PDF (use tabId)**```bash-curl "http://localhost:9867/instances/$INST/tabs/$TAB/pdf?landscape=true" \+curl "http://localhost:9867/tabs/$TAB/pdf?landscape=true" \-o report.pdf```@@ -546,14 +546,14 @@ echo "Tab: $TAB"# Step 4: Generate PDF with options using tabIdecho "Generating PDF..."-curl -s "http://localhost:9867/instances/$INST/tabs/$TAB/pdf?landscape=true&displayHeaderFooter=true" \+curl -s "http://localhost:9867/tabs/$TAB/pdf?landscape=true&displayHeaderFooter=true" \-o report.pdfecho "PDF saved: report.pdf"# Step 5: Take screenshot for preview using tabIdecho "Taking preview screenshot..."-curl -s "http://localhost:9867/instances/$INST/screenshot?tabId=$TAB" -o /tmp/report_preview.png+curl -s "http://localhost:9867/tabs/$TAB/screenshot" -o /tmp/report_preview.png# Step 6: Cleanupcurl -s -X POST "http://localhost:9867/instances/$INST/stop"@@ -644,7 +644,7 @@ curl -X POST http://localhost:9867/instances/$INST2/stop1. **Create instance first** — Every workflow starts with creating an instance2. **Wait for Chrome** — Sleep 2 seconds to allow lazy initialization3. **Extract instance ID** — Use jq: `jq -r '.id'`-4. **Use instance-scoped paths** — All operations use `/instances/{id}/...`+4. **Use tab-scoped paths for tab work** — Prefer `/tabs/{id}/...` for navigate/snapshot/screenshot/pdf5. **Get fresh snapshots** — Refs change when page updates; get new snapshot6. **Stop instances** — Clean up when done to free resources7. **Chain operations** — Create instance → Navigate → Snapshot → Click → Snapshot → Stop@@ -656,15 +656,15 @@ curl -X POST http://localhost:9867/instances/$INST2/stop| Goal | Endpoint | Notes ||------|----------|-------|| Create instance | `POST /instances/launch` | Returns instance ID |-| Navigate | `POST /instances/{id}/navigate` | Creates/uses first tab |-| See page structure | `GET /instances/{id}/snapshot` | Returns DOM nodes + refs |-| Click/type/press | `POST /instances/{id}/action` | Use ref from snapshot |-| Extract text | `GET /instances/{id}/text` | Returns readable text |-| Run JavaScript | `POST /instances/{id}/evaluate` | Returns JSON result |-| Screenshot | `GET /instances/{id}/screenshot` | Returns PNG image |-| PDF export | `GET /instances/{id}/tabs/{tabId}/pdf` | Returns PDF file |+| 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 /tabs/open` | Open URL in new tab |+| New tab | `POST /instances/{id}/tabs/open` | Open URL in new tab || Stop instance | `POST /instances/{id}/stop` | Cleanup, free resources |---diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex a55c907e..60a0ad1e 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -1,9 +1,11 @@package handlersimport (+ "bytes""context""encoding/json""fmt"+ "io""net/http""time"@@ -133,6 +135,41 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {web.JSON(w, 200, map[string]any{"success": true, "result": result})}+// HandleTabAction performs a single action on a tab identified by path ID.+//+// @Endpoint POST /tabs/{id}/action+func (h *Handlers) HandleTabAction(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ var req bridge.ActionRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ web.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }+ if req.TabID != "" && req.TabID != tabID {+ web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))+ return+ }+ req.TabID = tabID++ payload, err := json.Marshal(req)+ if err != nil {+ web.Error(w, 500, fmt.Errorf("encode: %w", err))+ return+ }++ wrapped := r.Clone(r.Context())+ wrapped.Body = io.NopCloser(bytes.NewReader(payload))+ wrapped.ContentLength = int64(len(payload))+ wrapped.Header = r.Header.Clone()+ wrapped.Header.Set("Content-Type", "application/json")+ h.HandleAction(w, wrapped)+}+type actionsRequest struct {TabID string `json:"tabId"`Actions []bridge.ActionRequest `json:"actions"`@@ -167,6 +204,41 @@ func (h *Handlers) HandleActions(w http.ResponseWriter, r *http.Request) {h.handleActionsBatch(w, r, req)}+// HandleTabActions performs multiple actions on a tab identified by path ID.+//+// @Endpoint POST /tabs/{id}/actions+func (h *Handlers) HandleTabActions(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ var req actionsRequest+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ web.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }+ if req.TabID != "" && req.TabID != tabID {+ web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))+ return+ }+ req.TabID = tabID++ payload, err := json.Marshal(req)+ if err != nil {+ web.Error(w, 500, fmt.Errorf("encode: %w", err))+ return+ }++ wrapped := r.Clone(r.Context())+ wrapped.Body = io.NopCloser(bytes.NewReader(payload))+ wrapped.ContentLength = int64(len(payload))+ wrapped.Header = r.Header.Clone()+ wrapped.Header.Set("Content-Type", "application/json")+ h.HandleActions(w, wrapped)+}+// handleActionsBatch processes a batch of actions (used by both single and batch endpoints)func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, req actionsRequest) {diff --git a/internal/handlers/cookies.go b/internal/handlers/cookies.goindex c210693d..f333addc 100644--- a/internal/handlers/cookies.go+++ b/internal/handlers/cookies.go@@ -1,9 +1,12 @@package handlersimport (+ "bytes""context""encoding/json"+ "errors""fmt"+ "io""net/http""strings""time"@@ -77,6 +80,27 @@ func (h *Handlers) HandleGetCookies(w http.ResponseWriter, r *http.Request) {})}+// HandleTabGetCookies gets cookies for a tab identified by path ID.+//+// @Endpoint GET /tabs/{id}/cookies+func (h *Handlers) HandleTabGetCookies(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ q := r.URL.Query()+ q.Set("tabId", tabID)++ req := r.Clone(r.Context())+ u := *r.URL+ u.RawQuery = q.Encode()+ req.URL = &u++ h.HandleGetCookies(w, req)+}+type cookieRequest struct {TabID string `json:"tabId"`URL string `json:"url"`@@ -168,3 +192,40 @@ func (h *Handlers) HandleSetCookies(w http.ResponseWriter, r *http.Request) {"total": len(req.Cookies),})}++// HandleTabSetCookies sets cookies for a tab identified by path ID.+//+// @Endpoint POST /tabs/{id}/cookies+func (h *Handlers) HandleTabSetCookies(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ reqBody := cookieRequest{}+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))+ if err := dec.Decode(&reqBody); err != nil && !errors.Is(err, io.EOF) {+ web.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ if reqBody.TabID != "" && reqBody.TabID != tabID {+ web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))+ return+ }+ reqBody.TabID = tabID++ payload, err := json.Marshal(reqBody)+ if err != nil {+ web.Error(w, 500, fmt.Errorf("encode: %w", err))+ return+ }++ req := r.Clone(r.Context())+ req.Body = io.NopCloser(bytes.NewReader(payload))+ req.ContentLength = int64(len(payload))+ req.Header = r.Header.Clone()+ req.Header.Set("Content-Type", "application/json")+ h.HandleSetCookies(w, req)+}diff --git a/internal/handlers/download.go b/internal/handlers/download.goindex b56174e1..c95b160b 100644--- a/internal/handlers/download.go+++ b/internal/handlers/download.go@@ -159,3 +159,28 @@ func (h *Handlers) HandleDownload(w http.ResponseWriter, r *http.Request) {"url": dlURL,})}++// HandleTabDownload fetches a URL using the browser session for a tab identified by path ID.+//+// @Endpoint GET /tabs/{id}/download+func (h *Handlers) HandleTabDownload(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }+ if _, _, err := h.Bridge.TabContext(tabID); err != nil {+ web.Error(w, 404, err)+ return+ }++ q := r.URL.Query()+ q.Set("tabId", tabID)++ req := r.Clone(r.Context())+ u := *r.URL+ u.RawQuery = q.Encode()+ req.URL = &u++ h.HandleDownload(w, req)+}diff --git a/internal/handlers/handler_actions_test.go b/internal/handlers/handler_actions_test.goindex 8b17b9d1..7fa478ee 100644--- a/internal/handlers/handler_actions_test.go+++ b/internal/handlers/handler_actions_test.go@@ -29,6 +29,10 @@ func (m *failMockBridge) EnsureChrome(cfg *config.RuntimeConfig) error {return nil}+func (m *failMockBridge) AvailableActions() []string {+ return []string{bridge.ActionClick, bridge.ActionType}+}+func TestHandleActions_EmptyArray(t *testing.T) {h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)req := httptest.NewRequest("POST", "/actions", bytes.NewReader([]byte(`{"actions": []}`)))@@ -50,6 +54,41 @@ func TestHandleActions_EmptyArray(t *testing.T) {}}+func TestHandleTabAction_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs//action", bytes.NewReader([]byte(`{"kind":"click"}`)))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ h.HandleTabAction(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabAction_TabIDMismatch(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs/tab_abc/action", bytes.NewReader([]byte(`{"tabId":"tab_other","kind":"click"}`)))+ req.SetPathValue("id", "tab_abc")+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ h.HandleTabAction(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabAction_NoTab(t *testing.T) {+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs/tab_abc/action", bytes.NewReader([]byte(`{"kind":"click"}`)))+ req.SetPathValue("id", "tab_abc")+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ h.HandleTabAction(w, req)+ if w.Code != 404 {+ t.Errorf("expected 404, got %d", w.Code)+ }+}+func TestHandleActions_NoTabError(t *testing.T) {h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)@@ -70,6 +109,41 @@ func TestHandleActions_NoTabError(t *testing.T) {}}+func TestHandleTabActions_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs//actions", bytes.NewReader([]byte(`{"actions":[{"kind":"click"}]}`)))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ h.HandleTabActions(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabActions_TabIDMismatch(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs/tab_abc/actions", bytes.NewReader([]byte(`{"tabId":"tab_other","actions":[{"kind":"click"}]}`)))+ req.SetPathValue("id", "tab_abc")+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ h.HandleTabActions(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabActions_NoTab(t *testing.T) {+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs/tab_abc/actions", bytes.NewReader([]byte(`{"actions":[{"kind":"click"}]}`)))+ req.SetPathValue("id", "tab_abc")+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ h.HandleTabActions(w, req)+ if w.Code != 404 {+ t.Errorf("expected 404, got %d", w.Code)+ }+}+func TestHandleGetCookies_NoTab(t *testing.T) {h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)diff --git a/internal/handlers/handler_cookies_test.go b/internal/handlers/handler_cookies_test.goindex d5246e66..417e42e5 100644--- a/internal/handlers/handler_cookies_test.go+++ b/internal/handlers/handler_cookies_test.go@@ -52,3 +52,48 @@ func TestHandleGetCookies_NameFilter(t *testing.T) {t.Error("expected error in response")}}++func TestHandleTabGetCookies_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs//cookies", nil)+ w := httptest.NewRecorder()+ h.HandleTabGetCookies(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabGetCookies_NoTab(t *testing.T) {+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs/tab_abc/cookies", nil)+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabGetCookies(w, req)+ if w.Code != 404 {+ t.Errorf("expected 404, got %d", w.Code)+ }+}++func TestHandleTabSetCookies_TabIDMismatch(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ body := `{"tabId":"tab_other","url":"https://example.com","cookies":[{"name":"a","value":"b"}]}`+ req := httptest.NewRequest("POST", "/tabs/tab_abc/cookies", bytes.NewReader([]byte(body)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabSetCookies(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabSetCookies_NoTab(t *testing.T) {+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ body := `{"url":"https://example.com","cookies":[{"name":"a","value":"b"}]}`+ req := httptest.NewRequest("POST", "/tabs/tab_abc/cookies", bytes.NewReader([]byte(body)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabSetCookies(w, req)+ if w.Code != 404 {+ t.Errorf("expected 404, got %d", w.Code)+ }+}diff --git a/internal/handlers/handler_download_test.go b/internal/handlers/handler_download_test.goindex 3a6b6f61..4234266d 100644--- a/internal/handlers/handler_download_test.go+++ b/internal/handlers/handler_download_test.go@@ -27,3 +27,24 @@ func TestHandleDownload_EmptyURL(t *testing.T) {t.Errorf("expected 400 for empty URL, got %d", w.Code)}}++func TestHandleTabDownload_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs//download?url=https://example.com", nil)+ w := httptest.NewRecorder()+ h.HandleTabDownload(w, req)+ if w.Code != http.StatusBadRequest {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabDownload_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs/tab_abc/download?url=https://example.com", nil)+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabDownload(w, req)+ if w.Code != http.StatusNotFound {+ t.Errorf("expected 404, got %d", w.Code)+ }+}diff --git a/internal/handlers/handler_media_test.go b/internal/handlers/handler_media_test.goindex b37b663e..d094bb5c 100644--- a/internal/handlers/handler_media_test.go+++ b/internal/handlers/handler_media_test.go@@ -29,6 +29,27 @@ func TestHandleScreenshot_InvalidQuality(t *testing.T) {}}+func TestHandleTabScreenshot_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs//screenshot", nil)+ w := httptest.NewRecorder()+ h.HandleTabScreenshot(w, req)+ if w.Code != http.StatusBadRequest {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabScreenshot_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs/tab_abc/screenshot", nil)+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabScreenshot(w, req)+ if w.Code != http.StatusNotFound {+ t.Errorf("expected 404, got %d", w.Code)+ }+}+func TestHandleText_NoTab(t *testing.T) {h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)req := httptest.NewRequest("GET", "/text", nil)@@ -58,3 +79,24 @@ func TestHandleText_RawMode(t *testing.T) {t.Errorf("expected 404, got %d", w.Code)}}++func TestHandleTabText_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs//text", nil)+ w := httptest.NewRecorder()+ h.HandleTabText(w, req)+ if w.Code != http.StatusBadRequest {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabText_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs/tab_abc/text", nil)+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabText(w, req)+ if w.Code != http.StatusNotFound {+ t.Errorf("expected 404, got %d", w.Code)+ }+}diff --git a/internal/handlers/handler_snapshot_test.go b/internal/handlers/handler_snapshot_test.goindex 35e98e7c..ab63d053 100644--- a/internal/handlers/handler_snapshot_test.go+++ b/internal/handlers/handler_snapshot_test.go@@ -48,3 +48,24 @@ func TestHandleSnapshot_PathTraversal(t *testing.T) {t.Error("expected error for path traversal")}}++func TestHandleTabSnapshot_MissingTabID(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs//snapshot", nil)+ w := httptest.NewRecorder()+ h.HandleTabSnapshot(w, req)+ if w.Code != http.StatusBadRequest {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabSnapshot_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("GET", "/tabs/tab_123/snapshot", nil)+ req.SetPathValue("id", "tab_123")+ w := httptest.NewRecorder()+ h.HandleTabSnapshot(w, req)+ if w.Code != http.StatusNotFound {+ t.Errorf("expected 404, got %d", w.Code)+ }+}diff --git a/internal/handlers/handler_upload_test.go b/internal/handlers/handler_upload_test.goindex 1051b3da..45ab533e 100644--- a/internal/handlers/handler_upload_test.go+++ b/internal/handlers/handler_upload_test.go@@ -43,3 +43,26 @@ func TestHandleUpload_NonexistentPath(t *testing.T) {t.Errorf("expected 400 for nonexistent path, got %d", w.Code)}}++func TestHandleTabUpload_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs//upload", bytes.NewReader([]byte(`{"selector":"input[type=file]"}`)))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ h.HandleTabUpload(w, req)+ if w.Code != http.StatusBadRequest {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabUpload_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs/tab_abc/upload", bytes.NewReader([]byte(`{"files":["aGVsbG8="]}`)))+ req.SetPathValue("id", "tab_abc")+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ h.HandleTabUpload(w, req)+ if w.Code != http.StatusNotFound {+ t.Errorf("expected 404, got %d", w.Code)+ }+}diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.goindex 6984746f..d8f76ff2 100644--- a/internal/handlers/handlers.go+++ b/internal/handlers/handlers.go@@ -39,6 +39,13 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {mux.HandleFunc("GET /health", h.HandleHealth)mux.HandleFunc("POST /ensure-chrome", h.HandleEnsureChrome)mux.HandleFunc("GET /tabs", h.HandleTabs)+ mux.HandleFunc("POST /tabs/{id}/navigate", h.HandleTabNavigate)+ mux.HandleFunc("GET /tabs/{id}/snapshot", h.HandleTabSnapshot)+ mux.HandleFunc("GET /tabs/{id}/screenshot", h.HandleTabScreenshot)+ mux.HandleFunc("POST /tabs/{id}/action", h.HandleTabAction)+ mux.HandleFunc("POST /tabs/{id}/actions", h.HandleTabActions)+ mux.HandleFunc("GET /tabs/{id}/text", h.HandleTabText)+ mux.HandleFunc("POST /tabs/{id}/evaluate", h.HandleTabEvaluate)mux.HandleFunc("GET /snapshot", h.HandleSnapshot)mux.HandleFunc("GET /screenshot", h.HandleScreenshot)mux.HandleFunc("GET /tabs/{id}/pdf", h.HandleTabPDF)@@ -51,10 +58,16 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {mux.HandleFunc("POST /tab", h.HandleTab)mux.HandleFunc("POST /tab/lock", h.HandleTabLock)mux.HandleFunc("POST /tab/unlock", h.HandleTabUnlock)+ mux.HandleFunc("POST /tabs/{id}/lock", h.HandleTabLockByID)+ mux.HandleFunc("POST /tabs/{id}/unlock", h.HandleTabUnlockByID)+ mux.HandleFunc("GET /tabs/{id}/cookies", h.HandleTabGetCookies)+ mux.HandleFunc("POST /tabs/{id}/cookies", h.HandleTabSetCookies)mux.HandleFunc("GET /cookies", h.HandleGetCookies)mux.HandleFunc("POST /cookies", h.HandleSetCookies)mux.HandleFunc("GET /stealth/status", h.HandleStealthStatus)mux.HandleFunc("POST /fingerprint/rotate", h.HandleFingerprintRotate)+ mux.HandleFunc("GET /tabs/{id}/download", h.HandleTabDownload)+ mux.HandleFunc("POST /tabs/{id}/upload", h.HandleTabUpload)mux.HandleFunc("GET /download", h.HandleDownload)mux.HandleFunc("POST /upload", h.HandleUpload)mux.HandleFunc("GET /screencast", h.HandleScreencast)diff --git a/internal/handlers/handlers_extra_test.go b/internal/handlers/handlers_extra_test.goindex 80a837c5..67b033f7 100644--- a/internal/handlers/handlers_extra_test.go+++ b/internal/handlers/handlers_extra_test.go@@ -32,6 +32,27 @@ func TestHandleNavigate_InvalidJSON(t *testing.T) {}}+func TestHandleTabNavigate_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs//navigate", bytes.NewReader([]byte(`{"url":"https://example.com"}`)))+ w := httptest.NewRecorder()+ h.HandleTabNavigate(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabNavigate_TabIDMismatch(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs/tab_abc/navigate", bytes.NewReader([]byte(`{"tabId":"tab_other","url":"https://example.com"}`)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabNavigate(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}+func TestHandleEvaluate_InvalidJSON(t *testing.T) {h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)req := httptest.NewRequest("POST", "/evaluate", bytes.NewReader([]byte(`not json`)))@@ -42,6 +63,38 @@ func TestHandleEvaluate_InvalidJSON(t *testing.T) {}}+func TestHandleTabEvaluate_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs//evaluate", bytes.NewReader([]byte(`{"expression":"1+1"}`)))+ w := httptest.NewRecorder()+ h.HandleTabEvaluate(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabEvaluate_TabIDMismatch(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs/tab_abc/evaluate", bytes.NewReader([]byte(`{"tabId":"tab_other","expression":"1+1"}`)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabEvaluate(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabEvaluate_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs/tab_abc/evaluate", bytes.NewReader([]byte(`{"expression":"1+1"}`)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabEvaluate(w, req)+ if w.Code != 404 {+ t.Errorf("expected 404, got %d", w.Code)+ }+}+func TestHandleTab_InvalidJSON(t *testing.T) {h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(`not json`)))diff --git a/internal/handlers/lock_handler_test.go b/internal/handlers/lock_handler_test.goindex 67c8ea22..413e14a2 100644--- a/internal/handlers/lock_handler_test.go+++ b/internal/handlers/lock_handler_test.go@@ -79,3 +79,60 @@ func TestHandleTabLockValidation(t *testing.T) {t.Fatalf("expected 400, got %d", w.Code)}}++func TestHandleTabLockByID(t *testing.T) {+ b := bridge.New(context.Background(), context.Background(), nil)+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)++ body, _ := json.Marshal(map[string]any{"owner": "agent-a", "timeoutSec": 10})+ w := httptest.NewRecorder()+ r, _ := http.NewRequest("POST", "/tabs/t1/lock", bytes.NewReader(body))+ r.SetPathValue("id", "t1")+ h.HandleTabLockByID(w, r)+ if w.Code != 200 {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleTabLockByID_Mismatch(t *testing.T) {+ b := bridge.New(context.Background(), context.Background(), nil)+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)++ body, _ := json.Marshal(map[string]any{"tabId": "other", "owner": "agent-a"})+ w := httptest.NewRecorder()+ r, _ := http.NewRequest("POST", "/tabs/t1/lock", bytes.NewReader(body))+ r.SetPathValue("id", "t1")+ h.HandleTabLockByID(w, r)+ if w.Code != 400 {+ t.Fatalf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabUnlockByID(t *testing.T) {+ b := bridge.New(context.Background(), context.Background(), nil)+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)+ _ = b.Lock("t1", "agent-a", 10*time.Minute)++ body, _ := json.Marshal(map[string]any{"owner": "agent-a"})+ w := httptest.NewRecorder()+ r, _ := http.NewRequest("POST", "/tabs/t1/unlock", bytes.NewReader(body))+ r.SetPathValue("id", "t1")+ h.HandleTabUnlockByID(w, r)+ if w.Code != 200 {+ t.Fatalf("expected 200, got %d", w.Code)+ }+}++func TestHandleTabUnlockByID_Mismatch(t *testing.T) {+ b := bridge.New(context.Background(), context.Background(), nil)+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)++ body, _ := json.Marshal(map[string]any{"tabId": "other", "owner": "agent-a"})+ w := httptest.NewRecorder()+ r, _ := http.NewRequest("POST", "/tabs/t1/unlock", bytes.NewReader(body))+ r.SetPathValue("id", "t1")+ h.HandleTabUnlockByID(w, r)+ if w.Code != 400 {+ t.Fatalf("expected 400, got %d", w.Code)+ }+}diff --git a/internal/handlers/lock_shutdown.go b/internal/handlers/lock_shutdown.goindex 686b506e..b49d6427 100644--- a/internal/handlers/lock_shutdown.go+++ b/internal/handlers/lock_shutdown.go@@ -1,8 +1,11 @@package handlersimport (+ "bytes""encoding/json"+ "errors""fmt"+ "io""log/slog""net/http""time"@@ -66,6 +69,92 @@ func (h *Handlers) HandleTabUnlock(w http.ResponseWriter, r *http.Request) {web.JSON(w, 200, map[string]any{"unlocked": true})}+// HandleTabLockByID locks a tab identified by path ID.+//+// @Endpoint POST /tabs/{id}/lock+func (h *Handlers) HandleTabLockByID(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ body := map[string]any{}+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))+ if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {+ web.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ if rawTabID, ok := body["tabId"]; ok {+ if provided, ok := rawTabID.(string); !ok || provided == "" {+ web.Error(w, 400, fmt.Errorf("invalid tabId"))+ return+ } else if provided != tabID {+ web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))+ return+ }+ }++ body["tabId"] = tabID++ payload, err := json.Marshal(body)+ if err != nil {+ web.Error(w, 500, fmt.Errorf("encode: %w", err))+ return+ }++ req := r.Clone(r.Context())+ req.Body = io.NopCloser(bytes.NewReader(payload))+ req.ContentLength = int64(len(payload))+ req.Header = r.Header.Clone()+ req.Header.Set("Content-Type", "application/json")+ h.HandleTabLock(w, req)+}++// HandleTabUnlockByID unlocks a tab identified by path ID.+//+// @Endpoint POST /tabs/{id}/unlock+func (h *Handlers) HandleTabUnlockByID(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ body := map[string]any{}+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))+ if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {+ web.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ if rawTabID, ok := body["tabId"]; ok {+ if provided, ok := rawTabID.(string); !ok || provided == "" {+ web.Error(w, 400, fmt.Errorf("invalid tabId"))+ return+ } else if provided != tabID {+ web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))+ return+ }+ }++ body["tabId"] = tabID++ payload, err := json.Marshal(body)+ if err != nil {+ web.Error(w, 500, fmt.Errorf("encode: %w", err))+ return+ }++ req := r.Clone(r.Context())+ req.Body = io.NopCloser(bytes.NewReader(payload))+ req.ContentLength = int64(len(payload))+ req.Header = r.Header.Clone()+ req.Header.Set("Content-Type", "application/json")+ h.HandleTabUnlock(w, req)+}+func (h *Handlers) HandleShutdown(shutdownFn func()) func(http.ResponseWriter, *http.Request) {return func(w http.ResponseWriter, r *http.Request) {slog.Info("shutdown requested via API")diff --git a/internal/handlers/media.go b/internal/handlers/media.goindex 363e1c1e..f712ab4f 100644--- a/internal/handlers/media.go+++ b/internal/handlers/media.go@@ -126,6 +126,27 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {})}+// HandleTabScreenshot returns screenshot bytes for a tab identified by path ID.+//+// @Endpoint GET /tabs/{id}/screenshot+func (h *Handlers) HandleTabScreenshot(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ q := r.URL.Query()+ q.Set("tabId", tabID)++ req := r.Clone(r.Context())+ u := *r.URL+ u.RawQuery = q.Encode()+ req.URL = &u++ h.HandleScreenshot(w, req)+}+func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {// Ensure Chrome is initializedif err := h.ensureChrome(); err != nil {@@ -384,3 +405,24 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {"text": text,})}++// HandleTabText extracts text for a tab identified by path ID.+//+// @Endpoint GET /tabs/{id}/text+func (h *Handlers) HandleTabText(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ q := r.URL.Query()+ q.Set("tabId", tabID)++ req := r.Clone(r.Context())+ u := *r.URL+ u.RawQuery = q.Encode()+ req.URL = &u++ h.HandleText(w, req)+}diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.goindex 04e2a561..26345323 100644--- a/internal/handlers/navigation.go+++ b/internal/handlers/navigation.go@@ -1,9 +1,12 @@package handlersimport (+ "bytes""context""encoding/json"+ "errors""fmt"+ "io""net/http""net/url""strings"@@ -198,7 +201,54 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {_ = chromedp.Run(tCtx, chromedp.Location(&url))title := bridge.WaitForTitle(tCtx, titleWait)- web.JSON(w, 200, map[string]any{"url": url, "title": title})+ web.JSON(w, 200, map[string]any{"tabId": resolvedTabID, "url": url, "title": title})+}++// HandleTabNavigate navigates an existing tab identified by path ID.+//+// @Endpoint POST /tabs/{id}/navigate+func (h *Handlers) HandleTabNavigate(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ body := map[string]any{}+ if r.Body != nil {+ err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&body)+ if err != nil && !errors.Is(err, io.EOF) {+ web.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }+ }++ if rawTabID, ok := body["tabId"]; ok {+ if provided, ok := rawTabID.(string); !ok || provided == "" {+ web.Error(w, 400, fmt.Errorf("invalid tabId"))+ return+ } else if provided != tabID {+ web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))+ return+ }+ }++ // Path tab ID is canonical for this endpoint and always navigates existing tab.+ body["tabId"] = tabID+ body["newTab"] = false++ payload, err := json.Marshal(body)+ if err != nil {+ web.Error(w, 500, fmt.Errorf("encode: %w", err))+ return+ }++ req := r.Clone(r.Context())+ req.Body = io.NopCloser(bytes.NewReader(payload))+ req.ContentLength = int64(len(payload))+ req.Header = r.Header.Clone()+ req.Header.Set("Content-Type", "application/json")+ h.HandleNavigate(w, req)}func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {@@ -234,6 +284,49 @@ func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {web.JSON(w, 200, map[string]any{"result": result})}+// HandleTabEvaluate runs JavaScript in a tab identified by path ID.+//+// @Endpoint POST /tabs/{id}/evaluate+func (h *Handlers) HandleTabEvaluate(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ body := map[string]any{}+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))+ if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {+ web.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ if rawTabID, ok := body["tabId"]; ok {+ if provided, ok := rawTabID.(string); !ok || provided == "" {+ web.Error(w, 400, fmt.Errorf("invalid tabId"))+ return+ } else if provided != tabID {+ web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))+ return+ }+ }++ body["tabId"] = tabID++ payload, err := json.Marshal(body)+ if err != nil {+ web.Error(w, 500, fmt.Errorf("encode: %w", err))+ return+ }++ req := r.Clone(r.Context())+ req.Body = io.NopCloser(bytes.NewReader(payload))+ req.ContentLength = int64(len(payload))+ req.Header = r.Header.Clone()+ req.Header.Set("Content-Type", "application/json")+ h.HandleEvaluate(w, req)+}+const (tabActionNew = "new"tabActionClose = "close"diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.goindex 2c7f027f..1ab5f9de 100644--- a/internal/handlers/snapshot.go+++ b/internal/handlers/snapshot.go@@ -361,3 +361,24 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {web.JSON(w, 200, resp)}}++// HandleTabSnapshot returns snapshot for a tab identified by path ID.+//+// @Endpoint GET /tabs/{id}/snapshot+func (h *Handlers) HandleTabSnapshot(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ q := r.URL.Query()+ q.Set("tabId", tabID)++ req := r.Clone(r.Context())+ u := *r.URL+ u.RawQuery = q.Encode()+ req.URL = &u++ h.HandleSnapshot(w, req)+}diff --git a/internal/handlers/upload.go b/internal/handlers/upload.goindex a84f93a8..9b8726f0 100644--- a/internal/handlers/upload.go+++ b/internal/handlers/upload.go@@ -118,6 +118,27 @@ func (h *Handlers) HandleUpload(w http.ResponseWriter, r *http.Request) {})}+// HandleTabUpload uploads files for a tab identified by path ID.+//+// @Endpoint POST /tabs/{id}/upload+func (h *Handlers) HandleTabUpload(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ q := r.URL.Query()+ q.Set("tabId", tabID)++ req := r.Clone(r.Context())+ u := *r.URL+ u.RawQuery = q.Encode()+ req.URL = &u++ h.HandleUpload(w, req)+}+// resolveSelector finds a DOM node by CSS selector and returns its NodeID.func resolveSelector(ctx context.Context, selector string) (cdp.NodeID, error) {// Use Runtime.evaluate to get the remote object, then request the node.diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.goindex 7ccd46cd..6a0efc02 100644--- a/internal/orchestrator/handlers.go+++ b/internal/orchestrator/handlers.go@@ -1,8 +1,10 @@package orchestratorimport (+ "bytes""encoding/json""fmt"+ "io""net""net/http""net/url"@@ -12,61 +14,39 @@ import ()func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {- // Core routes- mux.HandleFunc("GET /instances", o.handleList)- mux.HandleFunc("GET /instances/{id}", o.handleGetInstance)- mux.HandleFunc("GET /instances/tabs", o.handleAllTabs)-- // Phase 3: Tab Management (new API)- // Note: GET /tabs and POST /tab handlers are in dashboard.go- // These orchestrator handlers are used when no instances are running or for aggregation- mux.HandleFunc("POST /tabs/open", o.handleTabOpen)-- // Profile lifecycle by ID (canonical)mux.HandleFunc("POST /profiles/{id}/start", o.handleStartByID)mux.HandleFunc("POST /profiles/{id}/stop", o.handleStopByID)mux.HandleFunc("GET /profiles/{id}/instance", o.handleProfileInstance)- // Short aliases for agents- mux.HandleFunc("POST /start/{id}", o.handleStartByID)- mux.HandleFunc("POST /stop/{id}", o.handleStopByID)-- // Phase 2: Instance Management (new API)+ mux.HandleFunc("GET /instances", o.handleList)+ mux.HandleFunc("GET /instances/{id}", o.handleGetInstance)+ mux.HandleFunc("GET /instances/tabs", o.handleAllTabs)mux.HandleFunc("POST /instances/start", o.handleStartInstance)-- // Dashboard / backward compatmux.HandleFunc("POST /instances/launch", o.handleLaunchByName)+ mux.HandleFunc("POST /instances/{id}/start", o.handleStartByInstanceID)mux.HandleFunc("POST /instances/{id}/stop", o.handleStopByInstanceID)mux.HandleFunc("GET /instances/{id}/logs", o.handleLogsByID)- mux.HandleFunc("GET /instances/{id}/proxy/screencast", o.handleProxyScreencast)-- // Instance proxy routes - forward to specific instance port- // Browser operations- mux.HandleFunc("POST /instances/{id}/navigate", o.proxyToInstance)- mux.HandleFunc("GET /instances/{id}/snapshot", o.proxyToInstance)- mux.HandleFunc("POST /instances/{id}/action", o.proxyToInstance)- mux.HandleFunc("POST /instances/{id}/actions", o.proxyToInstance)- mux.HandleFunc("GET /instances/{id}/screenshot", o.proxyToInstance)- mux.HandleFunc("GET /instances/{id}/tabs/{tabId}/pdf", o.proxyToInstance)- mux.HandleFunc("POST /instances/{id}/tabs/{tabId}/pdf", o.proxyToInstance)- mux.HandleFunc("GET /instances/{id}/text", o.proxyToInstance)- mux.HandleFunc("POST /instances/{id}/evaluate", o.proxyToInstance)mux.HandleFunc("GET /instances/{id}/tabs", o.proxyToInstance)-- // Chrome management- mux.HandleFunc("POST /instances/{id}/ensure-chrome", o.proxyToInstance)-- // Tab management+ mux.HandleFunc("GET /instances/{id}/proxy/screencast", o.handleProxyScreencast)+ mux.HandleFunc("POST /instances/{id}/tabs/open", o.handleInstanceTabOpen)mux.HandleFunc("POST /instances/{id}/tab", o.proxyToInstance)- mux.HandleFunc("POST /instances/{id}/tab/lock", o.proxyToInstance)- mux.HandleFunc("POST /instances/{id}/tab/unlock", o.proxyToInstance)-- // Other operations- mux.HandleFunc("GET /instances/{id}/cookies", o.proxyToInstance)- mux.HandleFunc("POST /instances/{id}/cookies", o.proxyToInstance)- mux.HandleFunc("GET /instances/{id}/download", o.proxyToInstance)- mux.HandleFunc("POST /instances/{id}/upload", o.proxyToInstance)mux.HandleFunc("GET /instances/{id}/screencast", o.proxyToInstance)++ mux.HandleFunc("POST /tabs/{id}/navigate", o.handleTabNavigate)+ mux.HandleFunc("GET /tabs/{id}/snapshot", o.handleTabSnapshot)+ mux.HandleFunc("GET /tabs/{id}/screenshot", o.handleTabScreenshot)+ mux.HandleFunc("POST /tabs/{id}/action", o.handleTabAction)+ mux.HandleFunc("POST /tabs/{id}/actions", o.handleTabActions)+ mux.HandleFunc("GET /tabs/{id}/text", o.handleTabText)+ mux.HandleFunc("POST /tabs/{id}/evaluate", o.handleTabEvaluate)+ mux.HandleFunc("GET /tabs/{id}/pdf", o.handleTabPDF)+ mux.HandleFunc("POST /tabs/{id}/pdf", o.handleTabPDF)+ mux.HandleFunc("GET /tabs/{id}/download", o.handleTabDownload)+ mux.HandleFunc("POST /tabs/{id}/upload", o.handleTabUpload)+ mux.HandleFunc("POST /tabs/{id}/lock", o.handleTabLock)+ mux.HandleFunc("POST /tabs/{id}/unlock", o.handleTabUnlock)+ mux.HandleFunc("GET /tabs/{id}/cookies", o.handleTabGetCookies)+ mux.HandleFunc("POST /tabs/{id}/cookies", o.handleTabSetCookies)}func (o *Orchestrator) handleList(w http.ResponseWriter, r *http.Request) {@@ -77,27 +57,34 @@ func (o *Orchestrator) handleGetInstance(w http.ResponseWriter, r *http.Request)id := r.PathValue("id")o.mu.RLock()inst, ok := o.instances[id]- o.mu.RUnlock()-if !ok {+ o.mu.RUnlock()web.Error(w, 404, fmt.Errorf("instance %q not found", id))return}- web.JSON(w, 200, inst.Instance)+ copyInst := inst.Instance+ active := instanceIsActive(inst)+ o.mu.RUnlock()++ if active && copyInst.Status == "stopped" {+ copyInst.Status = "running"+ }+ if !active &&+ (copyInst.Status == "starting" || copyInst.Status == "running" || copyInst.Status == "stopping") {+ copyInst.Status = "stopped"+ }++ web.JSON(w, 200, copyInst)}-// resolveProfileID resolves a path value to a profile name.-// Accepts both a 12-char hex profile ID or a profile name directly.func (o *Orchestrator) resolveProfileName(idOrName string) (string, error) {if o.profiles == nil {return "", fmt.Errorf("profile manager not configured")}- // Try as ID firstif name, err := o.profiles.FindByID(idOrName); err == nil {return name, nil}- // Try as name (for backward compat routes like /profiles/{name}/stop)if o.profiles.Exists(idOrName) {return idOrName, nil}@@ -117,7 +104,6 @@ func (o *Orchestrator) handleStartByID(w http.ResponseWriter, r *http.Request) {Headless bool `json:"headless"`}_ = json.NewDecoder(r.Body).Decode(&req)- // Port is optional - if not provided, Launch() will auto-allocateinst, err := o.Launch(name, req.Port, req.Headless)if err != nil {@@ -143,13 +129,12 @@ func (o *Orchestrator) handleStopByID(w http.ResponseWriter, r *http.Request) {func (o *Orchestrator) handleLaunchByName(w http.ResponseWriter, r *http.Request) {var req struct {- ProfileId string `json:"profileId,omitempty"` // Optional: Profile ID- Name string `json:"name,omitempty"` // Optional: Profile name (fallback if profileId is empty)- Mode string `json:"mode"` // "headed" or "headless" (default: headless)+ ProfileId string `json:"profileId,omitempty"`+ Name string `json:"name,omitempty"`+ Mode string `json:"mode"`Port string `json:"port,omitempty"`}- // Decode body if present (empty body is allowed)if r.ContentLength > 0 {if err := json.NewDecoder(r.Body).Decode(&req); err != nil {web.Error(w, 400, fmt.Errorf("invalid JSON"))@@ -157,13 +142,10 @@ func (o *Orchestrator) handleLaunchByName(w http.ResponseWriter, r *http.Request}}- // Default: headless=true unless mode="headed"headless := req.Mode != "headed"- // Determine profile name: use provided profileId, name, or generate temporary namevar name stringif req.ProfileId != "" {- // Look up profile by ID to get its nameprofs, err := o.profiles.List()if err != nil {web.Error(w, 500, fmt.Errorf("failed to list profiles: %w", err))@@ -182,14 +164,11 @@ func (o *Orchestrator) handleLaunchByName(w http.ResponseWriter, r *http.Requestreturn}} else if req.Name != "" {- // Use provided profile name directly (for cases where dashboard sends name as fallback)name = req.Name} else {- // Generate unique temporary instance name (internal use only)name = fmt.Sprintf("instance-%d", time.Now().UnixNano())}- // Port is optional - if not provided, Launch() will auto-allocateinst, err := o.Launch(name, req.Port, headless)if err != nil {web.Error(w, 409, err)@@ -207,6 +186,40 @@ func (o *Orchestrator) handleStopByInstanceID(w http.ResponseWriter, r *http.Reqweb.JSON(w, 200, map[string]string{"status": "stopped", "id": id})}+func (o *Orchestrator) handleStartByInstanceID(w http.ResponseWriter, r *http.Request) {+ id := r.PathValue("id")++ o.mu.RLock()+ inst, ok := o.instances[id]+ if !ok {+ o.mu.RUnlock()+ web.Error(w, 404, fmt.Errorf("instance %q not found", id))+ return+ }+ active := instanceIsActive(inst)+ port := inst.Port+ profileName := inst.ProfileName+ headless := inst.Headless+ o.mu.RUnlock()++ if active {+ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", port),+ Path: "/ensure-chrome",+ }+ o.proxyToURL(w, r, targetURL)+ return+ }++ started, err := o.Launch(profileName, port, headless)+ if err != nil {+ web.Error(w, 409, err)+ return+ }+ web.JSON(w, 201, started)+}+func (o *Orchestrator) handleLogsByID(w http.ResponseWriter, r *http.Request) {id := r.PathValue("id")logs, err := o.Logs(id)@@ -218,17 +231,13 @@ func (o *Orchestrator) handleLogsByID(w http.ResponseWriter, r *http.Request) {_, _ = w.Write([]byte(logs))}-// handleStartInstance: Phase 2 API endpoint for starting instances-// POST /instances/start {profileId?, mode?, port?}-// All parameters are optionalfunc (o *Orchestrator) handleStartInstance(w http.ResponseWriter, r *http.Request) {var req struct {- ProfileID string `json:"profileId,omitempty"` // Optional: Profile ID or name- Mode string `json:"mode,omitempty"` // Optional: "headed" or "headless"- Port string `json:"port,omitempty"` // Optional: port number+ ProfileID string `json:"profileId,omitempty"`+ Mode string `json:"mode,omitempty"`+ Port string `json:"port,omitempty"`}- // Decode body if present (empty body is allowed)if r.ContentLength > 0 {if err := json.NewDecoder(r.Body).Decode(&req); err != nil {web.Error(w, 400, fmt.Errorf("invalid JSON"))@@ -236,27 +245,21 @@ func (o *Orchestrator) handleStartInstance(w http.ResponseWriter, r *http.Reques}}- // Resolve profileId to profile name- // If profileId not provided, auto-generate instance with default profile or first availablevar profileName stringvar err errorif req.ProfileID != "" {- // User provided profileId (or name) - resolve itprofileName, err = o.resolveProfileName(req.ProfileID)if err != nil {web.Error(w, 404, fmt.Errorf("profile %q not found", req.ProfileID))return}} else {- // No profileId provided - use auto-generated name (creates temporary profile)profileName = fmt.Sprintf("instance-%d", time.Now().UnixNano())}- // Parse mode: "headed" or "headless" (default: headless)headless := req.Mode != "headed"- // Port is optional - Launch() will auto-allocate if not providedinst, err := o.Launch(profileName, req.Port, headless)if err != nil {web.Error(w, 409, err)@@ -320,8 +323,6 @@ func (o *Orchestrator) handleProxyScreencast(w http.ResponseWriter, r *http.Requweb.JSON(w, 200, map[string]string{"wsUrl": targetURL})}-// proxyToInstance forwards requests to a specific instance port-// This allows clients to call /instances/{id}/navigate instead of knowing the instance portfunc (o *Orchestrator) proxyToInstance(w http.ResponseWriter, r *http.Request) {id := r.PathValue("id")@@ -339,45 +340,38 @@ func (o *Orchestrator) proxyToInstance(w http.ResponseWriter, r *http.Request) {return}- // Build target URL by replacing /instances/{id} with the instance port path- // Request: POST /instances/work-9868/navigate?url=...- // Target: POST http://localhost:9868/navigate?url=...targetPath := r.URL.Path- // Remove /instances/{id} prefix (19 + len(id) characters)if len(targetPath) > len("/instances/"+id) {targetPath = targetPath[len("/instances/"+id):]} else {targetPath = ""}- // Build target URL using url.URL struct for explicit component control- // This prevents SSRF by ensuring we only proxy to localhosttargetURL := &url.URL{Scheme: "http",Host: net.JoinHostPort("localhost", inst.Port),Path: targetPath,RawQuery: r.URL.RawQuery,}+ o.proxyToURL(w, r, targetURL)+}- // Verify the constructed URL is valid+func (o *Orchestrator) proxyToURL(w http.ResponseWriter, r *http.Request, targetURL *url.URL) {if targetURL.Hostname() != "localhost" {web.Error(w, 400, fmt.Errorf("invalid proxy target: only localhost allowed"))return}- // Create proxy request with safe, validated URLproxyReq, err := http.NewRequest(r.Method, targetURL.String(), r.Body)if err != nil {web.Error(w, 500, fmt.Errorf("failed to create proxy request: %w", err))return}- // Copy headers from original request (except Host and hop-by-hop headers)for key, values := range r.Header {switch key {case "Host", "Connection", "Keep-Alive", "Proxy-Authenticate","Proxy-Authorization", "Te", "Trailers", "Transfer-Encoding", "Upgrade":- // Skip hop-by-hop headersdefault:for _, value := range values {proxyReq.Header.Add(key, value)@@ -385,7 +379,6 @@ func (o *Orchestrator) proxyToInstance(w http.ResponseWriter, r *http.Request) {}}- // Use orchestrator's HTTP clientresp, err := o.client.Do(proxyReq)if err != nil {web.Error(w, 502, fmt.Errorf("failed to proxy to instance: %w", err))@@ -393,19 +386,40 @@ func (o *Orchestrator) proxyToInstance(w http.ResponseWriter, r *http.Request) {}defer func() { _ = resp.Body.Close() }()- // Copy response headersfor key, values := range resp.Header {for _, value := range values {w.Header().Add(key, value)}}- // Copy response status and bodyw.WriteHeader(resp.StatusCode)_, _ = w.Write(readResponseBody(resp))}-// readResponseBody reads the full response body+func (o *Orchestrator) findRunningInstanceByTabID(tabID string) (*InstanceInternal, error) {+ o.mu.RLock()+ instances := make([]*InstanceInternal, 0, len(o.instances))+ for _, inst := range o.instances {+ if inst.Status == "running" && instanceIsActive(inst) {+ instances = append(instances, inst)+ }+ }+ o.mu.RUnlock()++ for _, inst := range instances {+ tabs, err := o.fetchTabs(inst.URL)+ if err != nil {+ continue+ }+ for _, tab := range tabs {+ if tab.ID == tabID || o.idMgr.TabIDFromCDPTarget(tab.ID) == tabID {+ return inst, nil+ }+ }+ }+ return nil, fmt.Errorf("tab %q not found", tabID)+}+func readResponseBody(resp *http.Response) []byte {if resp.Body == nil {return []byte{}@@ -424,49 +438,359 @@ func readResponseBody(resp *http.Response) []byte {return body}-// Phase 3: Tab Management Handlers+func (o *Orchestrator) handleTabNavigate(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }-// handleTabOpen: POST /tabs/open {instanceId, url?}-func (o *Orchestrator) handleTabOpen(w http.ResponseWriter, r *http.Request) {- var req struct {- InstanceID string `json:"instanceId"` // Required: instance ID- URL string `json:"url,omitempty"` // Optional: URL to open+ inst, err := o.findRunningInstanceByTabID(tabID)+ if err != nil {+ web.Error(w, 404, err)+ return+ }++ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: "/tabs/" + tabID + "/navigate",+ RawQuery: r.URL.RawQuery,+ }+ o.proxyToURL(w, r, targetURL)+}++func (o *Orchestrator) handleTabSnapshot(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ inst, err := o.findRunningInstanceByTabID(tabID)+ if err != nil {+ web.Error(w, 404, err)+ return+ }++ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: "/tabs/" + tabID + "/snapshot",+ RawQuery: r.URL.RawQuery,+ }+ o.proxyToURL(w, r, targetURL)+}++func (o *Orchestrator) handleTabScreenshot(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ inst, err := o.findRunningInstanceByTabID(tabID)+ if err != nil {+ web.Error(w, 404, err)+ return+ }++ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: "/tabs/" + tabID + "/screenshot",+ RawQuery: r.URL.RawQuery,+ }+ o.proxyToURL(w, r, targetURL)+}++func (o *Orchestrator) handleTabAction(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ inst, err := o.findRunningInstanceByTabID(tabID)+ if err != nil {+ web.Error(w, 404, err)+ return+ }++ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: "/tabs/" + tabID + "/action",+ RawQuery: r.URL.RawQuery,+ }+ o.proxyToURL(w, r, targetURL)+}++func (o *Orchestrator) handleTabActions(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ inst, err := o.findRunningInstanceByTabID(tabID)+ if err != nil {+ web.Error(w, 404, err)+ return+ }++ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: "/tabs/" + tabID + "/actions",+ RawQuery: r.URL.RawQuery,}+ o.proxyToURL(w, r, targetURL)+}- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- web.Error(w, 400, fmt.Errorf("invalid JSON"))+func (o *Orchestrator) handleTabText(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ inst, err := o.findRunningInstanceByTabID(tabID)+ if err != nil {+ web.Error(w, 404, err)return}- if req.InstanceID == "" {- web.Error(w, 400, fmt.Errorf("instanceId is required"))+ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: "/tabs/" + tabID + "/text",+ RawQuery: r.URL.RawQuery,+ }+ o.proxyToURL(w, r, targetURL)+}++func (o *Orchestrator) handleTabEvaluate(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))return}- // Check if instance exists+ inst, err := o.findRunningInstanceByTabID(tabID)+ if err != nil {+ web.Error(w, 404, err)+ return+ }++ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: "/tabs/" + tabID + "/evaluate",+ RawQuery: r.URL.RawQuery,+ }+ o.proxyToURL(w, r, targetURL)+}++func (o *Orchestrator) handleTabPDF(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ inst, err := o.findRunningInstanceByTabID(tabID)+ if err != nil {+ web.Error(w, 404, err)+ return+ }++ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: "/tabs/" + tabID + "/pdf",+ RawQuery: r.URL.RawQuery,+ }+ o.proxyToURL(w, r, targetURL)+}++func (o *Orchestrator) handleTabDownload(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ inst, err := o.findRunningInstanceByTabID(tabID)+ if err != nil {+ web.Error(w, 404, err)+ return+ }++ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: "/tabs/" + tabID + "/download",+ RawQuery: r.URL.RawQuery,+ }+ o.proxyToURL(w, r, targetURL)+}++func (o *Orchestrator) handleTabUpload(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ inst, err := o.findRunningInstanceByTabID(tabID)+ if err != nil {+ web.Error(w, 404, err)+ return+ }++ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: "/tabs/" + tabID + "/upload",+ RawQuery: r.URL.RawQuery,+ }+ o.proxyToURL(w, r, targetURL)+}++func (o *Orchestrator) handleTabLock(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ inst, err := o.findRunningInstanceByTabID(tabID)+ if err != nil {+ web.Error(w, 404, err)+ return+ }++ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: "/tabs/" + tabID + "/lock",+ RawQuery: r.URL.RawQuery,+ }+ o.proxyToURL(w, r, targetURL)+}++func (o *Orchestrator) handleTabUnlock(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ inst, err := o.findRunningInstanceByTabID(tabID)+ if err != nil {+ web.Error(w, 404, err)+ return+ }++ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: "/tabs/" + tabID + "/unlock",+ RawQuery: r.URL.RawQuery,+ }+ o.proxyToURL(w, r, targetURL)+}++func (o *Orchestrator) handleTabGetCookies(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ inst, err := o.findRunningInstanceByTabID(tabID)+ if err != nil {+ web.Error(w, 404, err)+ return+ }++ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: "/tabs/" + tabID + "/cookies",+ RawQuery: r.URL.RawQuery,+ }+ o.proxyToURL(w, r, targetURL)+}++func (o *Orchestrator) handleTabSetCookies(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ inst, err := o.findRunningInstanceByTabID(tabID)+ if err != nil {+ web.Error(w, 404, err)+ return+ }++ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: "/tabs/" + tabID + "/cookies",+ RawQuery: r.URL.RawQuery,+ }+ o.proxyToURL(w, r, targetURL)+}++func (o *Orchestrator) handleInstanceTabOpen(w http.ResponseWriter, r *http.Request) {+ id := r.PathValue("id")+o.mu.RLock()- _, ok := o.instances[req.InstanceID]+ inst, ok := o.instances[id]o.mu.RUnlock()-if !ok {- web.Error(w, 404, fmt.Errorf("instance %q not found", req.InstanceID))+ web.Error(w, 404, fmt.Errorf("instance %q not found", id))+ return+ }+ if inst.Status != "running" {+ web.Error(w, 503, fmt.Errorf("instance %q is not running (status: %s)", id, inst.Status))return}- // Generate tab ID- tabID := fmt.Sprintf("tab_%d", time.Now().UnixNano()%1000000)+ var req struct {+ URL string `json:"url,omitempty"`+ }+ if r.ContentLength > 0 {+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ web.Error(w, 400, fmt.Errorf("invalid JSON"))+ return+ }+ }- // Build response- tab := map[string]any{- "id": tabID,- "instanceId": req.InstanceID,- "url": req.URL,- "title": "",- "status": "ready",- "createdAt": time.Now().UTC(),+ payload, err := json.Marshal(map[string]any{+ "action": "new",+ "url": req.URL,+ })+ if err != nil {+ web.Error(w, 500, fmt.Errorf("failed to build tab open request: %w", err))+ return}- web.JSON(w, 201, tab)-}+ proxyReq := r.Clone(r.Context())+ proxyReq.Body = io.NopCloser(bytes.NewReader(payload))+ proxyReq.ContentLength = int64(len(payload))+ proxyReq.Header = r.Header.Clone()+ proxyReq.Header.Set("Content-Type", "application/json")-// handleTabList: GET /tabs?instanceId=...+ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: "/tab",+ RawQuery: r.URL.RawQuery,+ }+ o.proxyToURL(w, proxyReq, targetURL)+}diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.goindex 071ff305..a9deb209 100644--- a/internal/orchestrator/orchestrator.go+++ b/internal/orchestrator/orchestrator.go@@ -20,7 +20,7 @@ import ()type Orchestrator struct {- instances map[string]*InstanceInternal // keyed by instance ID+ instances map[string]*InstanceInternalbaseDir stringbinary stringprofiles *profiles.ProfileManager@@ -81,7 +81,7 @@ func NewOrchestratorWithRunner(baseDir string, runner HostRunner) *Orchestrator// Why so high?// - First request to an instance triggers lazy Chrome initialization (8-20+ seconds)// - Navigation can take up to 60s (NavigateTimeout in bridge config)- // - Proxied requests (e.g., POST /instances/{id}/navigate) must wait for:+ // - Proxied requests (e.g., POST /tabs/{tabId}/navigate) must wait for:// 1. Instance /health handler to initialize Chrome (via ensureChrome())// 2. Tab operations to complete (navigate, snapshot, actions, etc.)// - Short timeout (<5s) would break first-request scenarios@@ -98,7 +98,6 @@ func (o *Orchestrator) SetProfileManager(pm *profiles.ProfileManager) {o.profiles = pm}-// SetPortRange configures the port allocation rangefunc (o *Orchestrator) SetPortRange(start, end int) {o.portAllocator = NewPortAllocator(start, end)}@@ -123,7 +122,6 @@ func installStableBinary(src, dst string) error {func (o *Orchestrator) Launch(name, port string, headless bool) (*bridge.Instance, error) {o.mu.Lock()- // Auto-allocate port if not specifiedif port == "" || port == "0" {o.mu.Unlock()allocatedPort, err := o.portAllocator.AllocatePort()@@ -149,7 +147,6 @@ func (o *Orchestrator) Launch(name, port string, headless bool) (*bridge.Instancreturn nil, fmt.Errorf("port %s is already in use on this machine", port)}- // Generate hash-based IDsprofileID := o.idMgr.ProfileID(name)instanceID := o.idMgr.InstanceID(profileID, name)@@ -217,9 +214,6 @@ func (o *Orchestrator) Launch(name, port string, headless bool) (*bridge.Instancgo o.monitor(inst)- // Note: Chrome initialization happens lazily on first handler request- // This avoids race conditions during instance startup-return &inst.Instance, nil}@@ -320,25 +314,19 @@ func (o *Orchestrator) markStopped(id string) {return}- // Release the port back to the allocatorportStr := inst.Portif portInt, err := strconv.Atoi(portStr); err == nil {o.portAllocator.ReleasePort(portInt)slog.Debug("released port", "id", id, "port", portStr)}- // Delete instance from map (remove it entirely, not just mark stopped)profileName := inst.ProfileNamedelete(o.instances, id)o.mu.Unlock()- // Log the removalslog.Info("instance stopped and removed", "id", id, "profile", profileName)- // Delete temporary/ephemeral profiles (auto-generated for instances)- // These are created with names like "instance-1709275909123456789"if strings.HasPrefix(profileName, "instance-") {- // Delete profile directoryprofilePath := filepath.Join(o.baseDir, profileName)if err := os.RemoveAll(profilePath); err != nil {slog.Warn("failed to delete temporary profile directory", "name", profileName, "err", err)@@ -346,7 +334,6 @@ func (o *Orchestrator) markStopped(id string) {slog.Info("deleted temporary profile", "name", profileName)}- // Also delete profile metadata via profile managerif o.profiles != nil {if err := o.profiles.Delete(profileName); err != nil {slog.Warn("failed to delete profile metadata", "name", profileName, "err", err)diff --git a/internal/orchestrator/orchestrator_test.go b/internal/orchestrator/orchestrator_test.goindex 33b37a63..aec00266 100644--- a/internal/orchestrator/orchestrator_test.go+++ b/internal/orchestrator/orchestrator_test.go@@ -7,7 +7,6 @@ import ()func TestOrchestrator_Launch_Lifecycle(t *testing.T) {- // Mock processAlive to always return true for our fake PIDsold := processAliveFuncprocessAliveFunc = func(pid int) bool { return pid > 0 }defer func() { processAliveFunc = old }()@@ -15,7 +14,6 @@ func TestOrchestrator_Launch_Lifecycle(t *testing.T) {runner := &mockRunner{portAvail: true}o := NewOrchestratorWithRunner(t.TempDir(), runner)- // 1. Initial Launchinst, err := o.Launch("profile1", "9001", true)if err != nil {t.Fatalf("First launch failed: %v", err)@@ -24,13 +22,11 @@ func TestOrchestrator_Launch_Lifecycle(t *testing.T) {t.Errorf("expected status starting, got %s", inst.Status)}- // 2. Duplicate Profile Check_, err = o.Launch("profile1", "9002", true)if err == nil {t.Error("expected error when launching duplicate profile")}- // 3. Port Conflict Check (Runner reports port unavailable)runner.portAvail = false_, err = o.Launch("profile2", "9001", true)if err == nil {@@ -39,7 +35,6 @@ func TestOrchestrator_Launch_Lifecycle(t *testing.T) {}func TestOrchestrator_ListAndStop(t *testing.T) {- // Mock processAlive to return true then false to simulate exitalive := trueold := processAliveFuncprocessAliveFunc = func(pid int) bool { return alive }@@ -50,19 +45,16 @@ func TestOrchestrator_ListAndStop(t *testing.T) {inst, _ := o.Launch("p1", "9001", true)- // Verify instance is in list before stopif len(o.List()) != 1 {t.Fatalf("expected 1 instance, got %d", len(o.List()))}- // Simulate stopalive = falseerr := o.Stop(inst.ID)if err != nil {t.Fatalf("Stop failed: %v", err)}- // Verify instance is removed from list after stopinstances := o.List()if len(instances) != 0 {t.Errorf("expected 0 instances after stop, got %d", len(instances))@@ -91,7 +83,6 @@ func TestOrchestrator_StopProfile(t *testing.T) {}o.mu.Unlock()- // Make it "exit" immediately on stopprocessAliveFunc = func(pid int) bool { return false }err := o.StopProfile("p1")@@ -99,7 +90,6 @@ func TestOrchestrator_StopProfile(t *testing.T) {t.Fatalf("StopProfile failed: %v", err)}- // Verify instance is removed from list after stopinstances := o.List()if len(instances) != 0 {t.Errorf("expected 0 instances after stop, got %d", len(instances))diff --git a/internal/orchestrator/ports.go b/internal/orchestrator/ports.goindex 0cd23871..3bb84b52 100644--- a/internal/orchestrator/ports.go+++ b/internal/orchestrator/ports.go@@ -7,20 +7,17 @@ import ("sync")-// PortAllocator manages allocation of ports for instances within a configured rangetype PortAllocator struct {mu sync.Mutexstart intend int- allocated map[int]bool // tracks which ports are allocated+ allocated map[int]boolnextCandidate int}-// NewPortAllocator creates a new port allocator for the given rangefunc NewPortAllocator(start, end int) *PortAllocator {if start < 1 || end < 1 || start > end {slog.Error("invalid port range", "start", start, "end", end)- // Default to a safe range if invalidstart = 9868end = 9968}@@ -33,8 +30,6 @@ func NewPortAllocator(start, end int) *PortAllocator {}}-// AllocatePort finds and allocates the next available port in the range-// Returns error if no ports are availablefunc (pa *PortAllocator) AllocatePort() (int, error) {pa.mu.Lock()defer pa.mu.Unlock()@@ -45,7 +40,6 @@ func (pa *PortAllocator) AllocatePort() (int, error) {for attempts < maxAttempts {candidate := pa.nextCandidate- // Wrap around to start if we've reached the endif candidate > pa.end {pa.nextCandidate = pa.startcandidate = pa.start@@ -53,13 +47,11 @@ func (pa *PortAllocator) AllocatePort() (int, error) {pa.nextCandidate = candidate + 1- // Skip if already allocatedif pa.allocated[candidate] {attempts++continue}- // Check if port is available (not in use by other processes)if isPortAvailableInt(candidate) {pa.allocated[candidate] = trueslog.Debug("allocated port", "port", candidate)@@ -72,7 +64,6 @@ func (pa *PortAllocator) AllocatePort() (int, error) {return 0, fmt.Errorf("no available ports in range %d-%d", pa.start, pa.end)}-// ReleasePort marks a port as no longer allocatedfunc (pa *PortAllocator) ReleasePort(port int) {pa.mu.Lock()defer pa.mu.Unlock()@@ -81,7 +72,6 @@ func (pa *PortAllocator) ReleasePort(port int) {slog.Debug("released port", "port", port)}-// IsAllocated returns whether a port is currently allocatedfunc (pa *PortAllocator) IsAllocated(port int) bool {pa.mu.Lock()defer pa.mu.Unlock()@@ -89,7 +79,6 @@ func (pa *PortAllocator) IsAllocated(port int) bool {return pa.allocated[port]}-// AllocatedPorts returns a copy of all allocated port numbersfunc (pa *PortAllocator) AllocatedPorts() []int {pa.mu.Lock()defer pa.mu.Unlock()@@ -101,7 +90,6 @@ func (pa *PortAllocator) AllocatedPorts() []int {return ports}-// isPortAvailableInt checks if a port (as int) is available for bindingfunc isPortAvailableInt(port int) bool {addr := fmt.Sprintf("127.0.0.1:%d", port)listener, err := net.Listen("tcp", addr)diff --git a/internal/orchestrator/process_test.go b/internal/orchestrator/process_test.goindex 2dd5acea..58404df8 100644--- a/internal/orchestrator/process_test.go+++ b/internal/orchestrator/process_test.go@@ -44,7 +44,6 @@ func TestLaunch_Mocked(t *testing.T) {if !runner.runCalled {t.Error("expected runner.Run to be called")}- // Check that ID has the correct hash-based format (inst_XXXXXXXX)if !idutil.IsValidID(inst.ID, "inst") {t.Errorf("expected ID format inst_XXXXXXXX, got %s", inst.ID)}diff --git a/internal/orchestrator/process_unix.go b/internal/orchestrator/process_unix.goindex 881fc1c8..bf244fef 100644--- a/internal/orchestrator/process_unix.go+++ b/internal/orchestrator/process_unix.go@@ -7,23 +7,18 @@ import ("syscall")-// setProcGroup puts the child process in its own process group.func setProcGroup(cmd *exec.Cmd) {cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}}-// killProcessGroup sends a signal to the entire process group.func killProcessGroup(pid int, sig syscall.Signal) error {return syscall.Kill(-pid, sig)}-// processAlive checks if a process is still running.func processAlive(pid int) bool {return syscall.Kill(pid, syscall.Signal(0)) == nil}-// sigTERM is the termination signal.const sigTERM = syscall.SIGTERM-// sigKILL is the kill signal.const sigKILL = syscall.SIGKILLdiff --git a/internal/orchestrator/process_windows.go b/internal/orchestrator/process_windows.goindex 58fda780..d95896c6 100644--- a/internal/orchestrator/process_windows.go+++ b/internal/orchestrator/process_windows.go@@ -8,10 +8,8 @@ import ("syscall")-// setProcGroup is a no-op on Windows (no process groups via Setpgid).func setProcGroup(cmd *exec.Cmd) {}-// killProcessGroup kills the process on Windows (no group kill support).func killProcessGroup(pid int, _ syscall.Signal) error {p, err := os.FindProcess(pid)if err != nil {@@ -20,7 +18,6 @@ func killProcessGroup(pid int, _ syscall.Signal) error {return p.Kill()}-// processAlive checks if a process is still running on Windows.func processAlive(pid int) bool {p, err := os.FindProcess(pid)if err != nil {@@ -31,8 +28,6 @@ func processAlive(pid int) bool {return err == nil}-// sigTERM on Windows maps to a regular kill.const sigTERM = syscall.Signal(0xf)-// sigKILL on Windows maps to a regular kill.const sigKILL = syscall.Signal(0x9)diff --git a/internal/profiles/copydir.go b/internal/profiles/copydir.goindex d35e8a2d..82b93dd3 100644--- a/internal/profiles/copydir.go+++ b/internal/profiles/copydir.go@@ -8,7 +8,6 @@ import ("path/filepath")-// copyDir recursively copies src to dst, preserving permissions.func copyDir(src, dst string) error {return filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {if err != nil {diff --git a/internal/profiles/handlers.go b/internal/profiles/handlers.goindex dd2d2d80..7735f8bc 100644--- a/internal/profiles/handlers.go+++ b/internal/profiles/handlers.go@@ -10,20 +10,18 @@ import ()func (pm *ProfileManager) RegisterHandlers(mux *http.ServeMux) {- // Standard CRUD endpointsmux.HandleFunc("GET /profiles", pm.handleList)- mux.HandleFunc("POST /profiles", pm.handleCreate) // RESTful: POST /profiles instead of /profiles/create- mux.HandleFunc("POST /profiles/create", pm.handleCreate) // Backward compat- mux.HandleFunc("GET /profiles/{id}", pm.handleGetByID) // Get single profile by ID or name+ mux.HandleFunc("POST /profiles", pm.handleCreate)+ mux.HandleFunc("POST /profiles/create", pm.handleCreate)+ mux.HandleFunc("GET /profiles/{id}", pm.handleGetByID)- // Advanced endpoints (specific paths, no conflict with {id})mux.HandleFunc("POST /profiles/import", pm.handleImport)mux.HandleFunc("PATCH /profiles/meta", pm.handleUpdateMeta)- mux.HandleFunc("POST /profiles/{id}/reset", pm.handleResetByIDOrName) // Reset profile- mux.HandleFunc("GET /profiles/{id}/logs", pm.handleLogsByIDOrName) // Get logs- mux.HandleFunc("GET /profiles/{id}/analytics", pm.handleAnalyticsByIDOrName) // Get analytics- mux.HandleFunc("DELETE /profiles/{id}", pm.handleDeleteByID) // Delete profile- mux.HandleFunc("PATCH /profiles/{id}", pm.handleUpdateByIDOrName) // Update profile metadata+ mux.HandleFunc("POST /profiles/{id}/reset", pm.handleResetByIDOrName)+ mux.HandleFunc("GET /profiles/{id}/logs", pm.handleLogsByIDOrName)+ mux.HandleFunc("GET /profiles/{id}/analytics", pm.handleAnalyticsByIDOrName)+ mux.HandleFunc("DELETE /profiles/{id}", pm.handleDeleteByID)+ mux.HandleFunc("PATCH /profiles/{id}", pm.handleUpdateByIDOrName)}func (pm *ProfileManager) handleList(w http.ResponseWriter, r *http.Request) {@@ -33,13 +31,11 @@ func (pm *ProfileManager) handleList(w http.ResponseWriter, r *http.Request) {return}- // Filter out temporary profiles by default (unless requested with ?all=true)showAll := r.URL.Query().Get("all") == "true"if !showAll {filtered := []map[string]any{}for _, p := range profiles {if !p.Temporary {- // Convert to map for JSON responsesizeMB := float64(p.DiskUsage) / (1024 * 1024)filtered = append(filtered, map[string]any{"id": p.ID,@@ -93,7 +89,6 @@ func (pm *ProfileManager) handleCreate(w http.ResponseWriter, r *http.Request) {return}- // Generate and return the profile IDgeneratedID := profileID(req.Name)web.JSON(w, 200, map[string]any{"status": "created",@@ -160,8 +155,6 @@ func (pm *ProfileManager) handleUpdateMeta(w http.ResponseWriter, r *http.Requesweb.JSON(w, 200, map[string]string{"status": "updated", "name": req.Name})}-// New RESTful handlers-func (pm *ProfileManager) handleGetByID(w http.ResponseWriter, r *http.Request) {id := r.PathValue("id")@@ -174,7 +167,6 @@ func (pm *ProfileManager) handleGetByID(w http.ResponseWriter, r *http.Request)var foundProfile map[string]anyfor _, p := range profiles {- // Match by ID or name (backward-compatible)if p.ID != id && p.Name != id {continue}@@ -208,10 +200,8 @@ func (pm *ProfileManager) handleGetByID(w http.ResponseWriter, r *http.Request)func (pm *ProfileManager) handleDeleteByID(w http.ResponseWriter, r *http.Request) {id := r.PathValue("id")- // Find profile name by IDname, err := pm.FindByID(id)if err != nil {- // Try as name directly (backward compat)name = idif !pm.Exists(name) {web.Error(w, 404, fmt.Errorf("profile %q not found", id))@@ -227,22 +217,17 @@ func (pm *ProfileManager) handleDeleteByID(w http.ResponseWriter, r *http.Requesweb.JSON(w, 200, map[string]any{"status": "deleted", "id": id, "name": name})}-// Helper to find profile name by ID or use as name directlyfunc (pm *ProfileManager) resolveIDOrName(idOrName string) (string, error) {- // Try as ID firstname, err := pm.FindByID(idOrName)if err == nil {return name, nil}- // Try as name directlyif pm.Exists(idOrName) {return idOrName, nil}return "", fmt.Errorf("profile %q not found (not a valid ID or name)", idOrName)}-// Consolidated handlers that work with both ID and name-func (pm *ProfileManager) handleUpdateByIDOrName(w http.ResponseWriter, r *http.Request) {idOrName := r.PathValue("id")name, err := pm.resolveIDOrName(idOrName)diff --git a/internal/profiles/identity_test.go b/internal/profiles/identity_test.goindex 84ff5dab..c50f6647 100644--- a/internal/profiles/identity_test.go+++ b/internal/profiles/identity_test.go@@ -9,13 +9,11 @@ import (func TestReadChromeProfileIdentity(t *testing.T) {tmpDir := t.TempDir()- // 1. Test empty profilename, email, accName, hasAcc := readChromeProfileIdentity(tmpDir)if name != "" || email != "" || accName != "" || hasAcc != false {t.Errorf("expected empty results for empty dir, got %q, %q, %q, %v", name, email, accName, hasAcc)}- // 2. Test with Local State onlylocalStateDir := tmpDirlocalStatePath := filepath.Join(localStateDir, "Local State")localStateContent := `{@@ -40,7 +38,6 @@ func TestReadChromeProfileIdentity(t *testing.T) {t.Errorf("Local State parsing failed: got %q, %q, %q, %v", name, email, accName, hasAcc)}- // 3. Test with Preferences (should override/supplement)prefsDir := filepath.Join(tmpDir, "Default")if err := os.MkdirAll(prefsDir, 0755); err != nil {t.Fatal(err)@@ -60,7 +57,6 @@ func TestReadChromeProfileIdentity(t *testing.T) {}name, email, accName, hasAcc = readChromeProfileIdentity(tmpDir)- // email and accName should come from Preferences if availableif name != "Work Profile" || email != "[email protected]" || accName != "Pref User" || !hasAcc {t.Errorf("Preferences parsing/override failed: got %q, %q, %q, %v", name, email, accName, hasAcc)}diff --git a/internal/profiles/profiles.go b/internal/profiles/profiles.goindex 2f54f6ec..037d8712 100644--- a/internal/profiles/profiles.go+++ b/internal/profiles/profiles.go@@ -17,14 +17,10 @@ import (var idMgr = idutil.NewManager()-// profileID generates a stable hash-based ID from profile name-// Returns format: prof_XXXXXXXXfunc profileID(name string) string {return idMgr.ProfileID(name)}-// validateProfileName checks for path traversal and other unsafe patterns-// Prevents directory traversal attacks (../, ..\, /, \)func validateProfileName(name string) error {if name == "" {return fmt.Errorf("profile name cannot be empty")@@ -142,10 +138,8 @@ func (pm *ProfileManager) List() ([]bridge.ProfileInfo, error) {continue}- // Mark as temporary if it's an auto-generated instance profileisTemporary := strings.HasPrefix(info.Name, "instance-")- // Check if path existspathExists := trueif _, err := os.Stat(info.Path); err != nil {pathExists = false@@ -245,7 +239,6 @@ func (pm *ProfileManager) Import(name, sourcePath string) error {}}- // Validate source path exists and is a directorysrcInfo, err := os.Stat(sourcePath)if err != nil {return fmt.Errorf("source path invalid: %w", err)diff --git a/internal/profiles/profiles_test.go b/internal/profiles/profiles_test.goindex 18337c81..b5a0b66f 100644--- a/internal/profiles/profiles_test.go+++ b/internal/profiles/profiles_test.go@@ -22,13 +22,11 @@ func TestProfileManagerCreateAndList(t *testing.T) {t.Fatal(err)}- // Verify profile directory exists on diskprofileDir := filepath.Join(dir, profileID("test-profile"))if _, err := os.Stat(profileDir); err != nil {t.Fatalf("profile directory not created: %s", profileDir)}- // Verify Default subdirectory exists (required for Chrome)defaultDir := filepath.Join(profileDir, "Default")if _, err := os.Stat(defaultDir); err != nil {t.Fatalf("Default directory not created: %s", defaultDir)@@ -329,7 +327,6 @@ func TestProfileMetaReadWrite(t *testing.T) {dir := t.TempDir()pm := NewProfileManager(dir)- // Create profile with metadatameta := ProfileMeta{UseWhen: "I need to access work email",Description: "Work profile for corporate tasks",@@ -338,7 +335,6 @@ func TestProfileMetaReadWrite(t *testing.T) {t.Fatal(err)}- // Read back the metadatareadMeta := readProfileMeta(filepath.Join(dir, profileID("work-profile")))if readMeta.UseWhen != "I need to access work email" {t.Errorf("expected useWhen 'I need to access work email', got %q", readMeta.UseWhen)@@ -353,10 +349,8 @@ func TestProfileUpdateMeta(t *testing.T) {mux := http.NewServeMux()pm.RegisterHandlers(mux)- // Create profile_ = pm.Create("updatable")- // Update metadata via PATCHbody := `{"name":"updatable","useWhen":"Updated use case","description":"Updated description"}`req := httptest.NewRequest("PATCH", "/profiles/meta", strings.NewReader(body))req.Header.Set("Content-Type", "application/json")@@ -373,7 +367,6 @@ func TestProfileCreateWithUseWhen(t *testing.T) {mux := http.NewServeMux()pm.RegisterHandlers(mux)- // Create profile with useWhenbody := `{"name":"test-usewhen","useWhen":"For testing purposes"}`req := httptest.NewRequest("POST", "/profiles/create", strings.NewReader(body))req.Header.Set("Content-Type", "application/json")@@ -384,7 +377,6 @@ func TestProfileCreateWithUseWhen(t *testing.T) {t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())}- // Verify profile list includes useWhenprofiles, err := pm.List()if err != nil {t.Fatal(err)@@ -400,11 +392,9 @@ func TestProfileCreateWithUseWhen(t *testing.T) {func TestProfileListIncludesUseWhen(t *testing.T) {pm := NewProfileManager(t.TempDir())- // Create profile with metadatameta := ProfileMeta{UseWhen: "Personal browsing"}_ = pm.CreateWithMeta("personal", meta)- // List profiles and check useWhen is includedprofiles, err := pm.List()if err != nil {t.Fatal(err)diff --git a/internal/uameta/uameta_test.go b/internal/uameta/uameta_test.goindex c59227ef..3b457826 100644--- a/internal/uameta/uameta_test.go+++ b/internal/uameta/uameta_test.go@@ -5,12 +5,10 @@ import ()func TestBuild_Empty(t *testing.T) {- // Empty chromeVersion should return nilif Build("", "") != nil {t.Fatal("expected nil for empty chrome version")}- // Empty user agent but with chromeVersion should generate default and return non-nilp := Build("", "144.0.0.0")if p == nil {t.Fatal("expected non-nil for empty user agent with chromeVersion")@@ -29,7 +27,6 @@ func TestBuild_Versions(t *testing.T) {if meta == nil {t.Fatal("expected metadata")}- // Check major version extractionfor _, b := range meta.Brands {if b.Brand == "Google Chrome" && b.Version != "144" {t.Errorf("expected major version 144, got %s", b.Version)diff --git a/internal/web/web.go b/internal/web/web.goindex b3925b73..50f834b1 100644--- a/internal/web/web.go+++ b/internal/web/web.go@@ -28,8 +28,6 @@ func CancelOnClientDone(reqCtx context.Context, cancel context.CancelFunc) {cancel()}-// StatusWriter wraps ResponseWriter to capture the status code.-// It preserves Hijacker and Flusher interfaces for WebSocket/SSE support.type StatusWriter struct {http.ResponseWriterCode intdiff --git a/tests/integration/main_test.go b/tests/integration/main_test.goindex 174cbc6f..ca279628 100644--- a/tests/integration/main_test.go+++ b/tests/integration/main_test.go@@ -281,15 +281,34 @@ func closeCurrentTab(t *testing.T) {currentTabID = ""}+// navigateInstance creates a fresh tab on the given instance and navigates it.+func navigateInstance(t *testing.T, instID, url string) (int, []byte, string) {+ t.Helper()++ openCode, openBody := httpPostWithRetry(t, fmt.Sprintf("/instances/%s/tabs/open", instID), map[string]any{+ "url": "about:blank",+ }, 2)+ if openCode != 200 {+ return openCode, openBody, ""+ }++ tabID := jsonField(t, openBody, "tabId")+ if tabID == "" {+ return 500, []byte(`{"error":"missing tabId from open tab response"}`), ""+ }++ path := fmt.Sprintf("/tabs/%s/navigate", tabID)+ code, body := httpPostWithRetry(t, path, map[string]any{"url": url}, 2)+ return code, body, tabID+}+// waitForInstanceReady waits for an instance to be ready for navigation// Uses a simple navigate to about:blank to check readinessfunc waitForInstanceReady(t *testing.T, instID string) {t.Helper()deadline := time.Now().Add(15 * time.Second)for time.Now().Before(deadline) {- code, _ := httpPost(t, fmt.Sprintf("/instances/%s/navigate", instID), map[string]any{- "url": "about:blank",- })+ code, _, _ := navigateInstance(t, instID, "about:blank")if code == 200 {t.Logf("instance %s is ready", instID)return@@ -335,21 +354,41 @@ func launchTestInstance(base string) error {// Wait for instance to be ready (can take 2-5 seconds for Chrome to start)deadline := time.Now().Add(30 * time.Second)for time.Now().Before(deadline) {- // Try a simple navigate to check if instance is ready- navResp, err := http.Post(- base+"/instances/"+id+"/navigate",+ // Open a tab first, then navigate it to check if instance is ready.+ openResp, err := http.Post(+ base+"/instances/"+id+"/tabs/open","application/json",strings.NewReader(`{"url":"about:blank"}`),)if err == nil {- if navResp.StatusCode == 200 {- _ = navResp.Body.Close()- fmt.Fprintf(os.Stderr, "TestMain: instance %s is ready\n", id)- return nil+ var tabID string+ if openResp.StatusCode == 200 {+ openBody, _ := io.ReadAll(openResp.Body)+ var open map[string]any+ if err := json.Unmarshal(openBody, &open); err == nil {+ if idValue, ok := open["tabId"].(string); ok {+ tabID = idValue+ }+ }+ }+ _ = openResp.Body.Close()+ if tabID != "" {+ navResp, err := http.Post(+ base+"/tabs/"+tabID+"/navigate",+ "application/json",+ strings.NewReader(`{"url":"about:blank"}`),+ )+ if err == nil {+ if navResp.StatusCode == 200 {+ _ = navResp.Body.Close()+ fmt.Fprintf(os.Stderr, "TestMain: instance %s is ready\n", id)+ return nil+ }+ navBody, _ := io.ReadAll(navResp.Body)+ _ = navResp.Body.Close()+ fmt.Fprintf(os.Stderr, "TestMain: instance not ready yet (%d): %s\n", navResp.StatusCode, string(navBody))+ }}- navBody, _ := io.ReadAll(navResp.Body)- _ = navResp.Body.Close()- fmt.Fprintf(os.Stderr, "TestMain: instance not ready yet (%d): %s\n", navResp.StatusCode, string(navBody))}time.Sleep(500 * time.Millisecond)}diff --git a/tests/integration/orchestrator_test.go b/tests/integration/orchestrator_test.goindex b07c2940..6158ce0a 100644--- a/tests/integration/orchestrator_test.go+++ b/tests/integration/orchestrator_test.go@@ -109,16 +109,11 @@ func TestOrchestrator_HashBasedIDs(t *testing.T) {time.Sleep(2 * time.Second)// Navigate to create tab- navPayload := map[string]any{- "url": "https://example.com",- }-- navStatus, navBody := httpPost(t, fmt.Sprintf("/instances/%s/navigate", instID), navPayload)+ navStatus, navBody, tabID := navigateInstance(t, instID, "https://example.com")if navStatus != 200 {t.Fatalf("navigate failed: %d: %s", navStatus, string(navBody))}- tabID := jsonField(t, navBody, "tabId")if !strings.HasPrefix(tabID, "tab_") || len(tabID) != 12 {t.Fatalf("invalid tab ID format: %s", tabID)}@@ -244,20 +239,16 @@ func TestOrchestrator_InstanceIsolation(t *testing.T) {time.Sleep(2 * time.Second)// Navigate on instance 1- nav1Payload := map[string]any{"url": "https://example.com"}- status, body := httpPost(t, fmt.Sprintf("/instances/%s/navigate", instIDs[0]), nav1Payload)+ status, navBody, tabID1 := navigateInstance(t, instIDs[0], "https://example.com")if status != 200 {- t.Fatalf("navigate instance 1 failed: %d", status)+ t.Fatalf("navigate instance 1 failed: %d: %s", status, string(navBody))}- tabID1 := jsonField(t, body, "tabId")// Navigate on instance 2- nav2Payload := map[string]any{"url": "https://github.com"}- status, body = httpPost(t, fmt.Sprintf("/instances/%s/navigate", instIDs[1]), nav2Payload)+ status, navBody, tabID2 := navigateInstance(t, instIDs[1], "https://github.com")if status != 200 {- t.Fatalf("navigate instance 2 failed: %d", status)+ t.Fatalf("navigate instance 2 failed: %d: %s", status, string(navBody))}- tabID2 := jsonField(t, body, "tabId")// Verify tab IDs are different (isolation)if tabID1 == tabID2 {@@ -334,19 +325,17 @@ func TestOrchestrator_ProxyRouting(t *testing.T) {time.Sleep(2 * time.Second)// Test navigation via orchestrator proxy- navPayload := map[string]any{"url": "https://example.com"}- status, body = httpPost(t, fmt.Sprintf("/instances/%s/navigate", instID), navPayload)+ status, body, tabID := navigateInstance(t, instID, "https://example.com")if status != 200 {t.Fatalf("proxy navigate failed: %d: %s", status, string(body))}- tabID := jsonField(t, body, "tabId")if !strings.HasPrefix(tabID, "tab_") {t.Fatalf("invalid tab ID from proxy: %s", tabID)}// Test snapshot via orchestrator proxy- status, body = httpGet(t, fmt.Sprintf("/instances/%s/snapshot", instID))+ status, body = httpGet(t, fmt.Sprintf("/tabs/%s/snapshot", tabID))if status != 200 {t.Fatalf("proxy snapshot failed: %d", status)}@@ -356,6 +345,105 @@ func TestOrchestrator_ProxyRouting(t *testing.T) {if err := json.Unmarshal(body, &snapshot); err != nil {t.Fatalf("parse snapshot failed: %v", err)}++ // Test action via orchestrator tab route+ status, body = httpPost(t, fmt.Sprintf("/tabs/%s/action", tabID), map[string]any{+ "kind": "press",+ "key": "Escape",+ })+ if status != 200 {+ t.Fatalf("proxy action failed: %d: %s", status, string(body))+ }++ // Test lock/unlock via orchestrator tab routes+ status, body = httpPost(t, fmt.Sprintf("/tabs/%s/lock", tabID), map[string]any{+ "owner": "orchestrator-test",+ "timeoutSec": 10,+ })+ if status != 200 {+ t.Fatalf("proxy lock failed: %d: %s", status, string(body))+ }+ status, body = httpPost(t, fmt.Sprintf("/tabs/%s/unlock", tabID), map[string]any{+ "owner": "orchestrator-test",+ })+ if status != 200 {+ t.Fatalf("proxy unlock failed: %d: %s", status, string(body))+ }++ // Test actions batch via orchestrator tab route+ status, body = httpPost(t, fmt.Sprintf("/tabs/%s/actions", tabID), map[string]any{+ "actions": []map[string]any{+ {"kind": "press", "key": "Escape"},+ },+ })+ if status != 200 {+ t.Fatalf("proxy actions failed: %d: %s", status, string(body))+ }++ // Test text via orchestrator tab route+ status, body = httpGet(t, fmt.Sprintf("/tabs/%s/text?mode=raw", tabID))+ if status != 200 {+ t.Fatalf("proxy text failed: %d: %s", status, string(body))+ }+ if !strings.Contains(string(body), "Example Domain") {+ t.Logf("proxy text response does not contain expected title content")+ }++ // Test evaluate via orchestrator tab route+ status, body = httpPost(t, fmt.Sprintf("/tabs/%s/evaluate", tabID), map[string]any{+ "expression": "document.title",+ })+ if status != 200 {+ t.Fatalf("proxy evaluate failed: %d: %s", status, string(body))+ }++ // Test cookies via orchestrator tab route+ status, body = httpGet(t, fmt.Sprintf("/tabs/%s/cookies?url=https://example.com", tabID))+ if status != 200 {+ t.Fatalf("proxy get cookies failed: %d: %s", status, string(body))+ }+ status, body = httpPost(t, fmt.Sprintf("/tabs/%s/cookies", tabID), map[string]any{+ "url": "https://example.com",+ "cookies": []map[string]any{+ {"name": "orch_test_cookie", "value": "1"},+ },+ })+ if status != 200 {+ t.Fatalf("proxy set cookies failed: %d: %s", status, string(body))+ }++ // Test pdf via orchestrator tab route+ status, body = httpGet(t, fmt.Sprintf("/tabs/%s/pdf?raw=true", tabID))+ if status != 200 {+ t.Fatalf("proxy pdf failed: %d: %s", status, string(body))+ }+ if len(body) < 4 || string(body[:4]) != "%PDF" {+ t.Fatalf("proxy pdf response is not a PDF (size=%d)", len(body))+ }++ // Test download via orchestrator tab route (missing URL should be 400 from bridge handler)+ status, body = httpGet(t, fmt.Sprintf("/tabs/%s/download", tabID))+ if status != 400 {+ t.Fatalf("proxy download failed: expected 400, got %d: %s", status, string(body))+ }++ // Test upload via orchestrator tab route (missing files/paths should be 400 from bridge handler)+ status, body = httpPost(t, fmt.Sprintf("/tabs/%s/upload", tabID), map[string]any{+ "selector": "input[type=file]",+ })+ if status != 400 {+ t.Fatalf("proxy upload failed: expected 400, got %d: %s", status, string(body))+ }++ // Test screenshot via orchestrator tab route+ status, body = httpGet(t, fmt.Sprintf("/tabs/%s/screenshot?raw=true", tabID))+ if status != 200 {+ t.Skipf("proxy screenshot returned %d (headless display limitation), skipping", status)+ }+ // JPEG starts with FF D8+ if len(body) < 2 || body[0] != 0xFF || body[1] != 0xD8 {+ t.Skipf("proxy screenshot response is not JPEG (size=%d), skipping", len(body))+ }}// TestOrchestrator_FirstRequestLazyChrome tests proxy request with lazy Chrome initialization@@ -411,13 +499,11 @@ func TestOrchestrator_FirstRequestLazyChrome(t *testing.T) {}// Now make the actual proxy request - Chrome is already initialized- navPayload := map[string]any{"url": "https://example.com"}- status, body = httpPost(t, fmt.Sprintf("/instances/%s/navigate", instID), navPayload)+ status, body, tabID := navigateInstance(t, instID, "https://example.com")if status != 200 {t.Fatalf("navigate failed: %d: %s", status, string(body))}- tabID := jsonField(t, body, "tabId")if !strings.HasPrefix(tabID, "tab_") {t.Fatalf("invalid tab ID: %s", tabID)}@@ -456,8 +542,10 @@ func TestOrchestrator_AggregateTabsEndpoint(t *testing.T) {// Navigate on each instancefor _, instID := range instIDs {- navPayload := map[string]any{"url": "https://example.com"}- httpPost(t, fmt.Sprintf("/instances/%s/navigate", instID), navPayload)+ httpStatus, navBody, _ := navigateInstance(t, instID, "https://example.com")+ if httpStatus != 200 {+ t.Fatalf("navigate failed for %s: %d: %s", instID, httpStatus, string(navBody))+ }}// Get aggregate tabsdiff --git a/tests/integration/security_proxy_test.go b/tests/integration/security_proxy_test.goindex 4e8fb8a3..ac553335 100644--- a/tests/integration/security_proxy_test.go+++ b/tests/integration/security_proxy_test.go@@ -34,9 +34,7 @@ func TestProxy_LocalhostOnly(t *testing.T) {// (actual SSRF prevention is done at handler level through url.URL struct)// Verify instance can be accessed via proxy- code, _ := httpPost(t, fmt.Sprintf("/instances/%s/navigate", instID), map[string]any{- "url": "https://example.com",- })+ code, _, _ := navigateInstance(t, instID, "https://example.com")if code != 200 {t.Errorf("expected 200 for valid localhost proxy, got %d", code)@@ -64,9 +62,7 @@ func TestProxy_URLValidation(t *testing.T) {waitForInstanceReady(t, instID)// Test with valid URL in path- code, respBody := httpPost(t, fmt.Sprintf("/instances/%s/navigate", instID), map[string]any{- "url": "https://example.com/path?query=value",- })+ code, respBody, _ := navigateInstance(t, instID, "https://example.com/path?query=value")if code != 200 {t.Logf("navigate with query params got %d: %s", code, string(respBody))@@ -114,18 +110,14 @@ func TestProxy_InstanceIsolation(t *testing.T) {waitForInstanceReady(t, instIDs[1])// Navigate in first instance- code1, body1 := httpPost(t, fmt.Sprintf("/instances/%s/navigate", instIDs[0]), map[string]any{- "url": "https://example.com/page1",- })+ code1, body1, _ := navigateInstance(t, instIDs[0], "https://example.com/page1")if code1 != 200 {t.Errorf("navigate in inst1 failed: %d: %s", code1, string(body1))}// Navigate in second instance- code2, body2 := httpPost(t, fmt.Sprintf("/instances/%s/navigate", instIDs[1]), map[string]any{- "url": "https://example.com/page2",- })+ code2, body2, _ := navigateInstance(t, instIDs[1], "https://example.com/page2")if code2 != 200 {t.Errorf("navigate in inst2 failed: %d: %s", code2, string(body2))@@ -170,9 +162,7 @@ func TestProxy_SchemeValidation(t *testing.T) {waitForInstanceReady(t, instID)// Navigate should work (verifies internal http scheme is used)- code, respBody := httpPost(t, fmt.Sprintf("/instances/%s/navigate", instID), map[string]any{- "url": "https://example.com",- })+ code, respBody, _ := navigateInstance(t, instID, "https://example.com")if code != 200 {t.Errorf("navigate failed (scheme validation): %d: %s", code, string(respBody))diff --git a/tests/manual/core.md b/tests/manual/core.mdindex cc837b5e..35119018 100644--- a/tests/manual/core.md+++ b/tests/manual/core.md@@ -188,8 +188,8 @@ Navigate to the test page first: `POST /navigate {"url":"file://<repo>/tests/ass| SEC3 | Profile name with "\" | `POST /profiles {"name":"test\\profile"}` | 400, path separators not allowed || SEC4 | Profile name empty | `POST /profiles {"name":""}` | 400, name required || SEC5 | Valid profile names | `POST /profiles {"name":"valid-profile"}` | 201, profile created |-| SEC6 | SSRF prevention | Proxy to non-localhost (e.g., example.com via /instances/{id}/navigate) | 400, localhost required or fails safely |-| SEC7 | Proxy safe URL | Proxy normal navigate via /instances/{id}/navigate | 200, works as expected |+| SEC6 | SSRF prevention | Proxy to non-localhost (e.g., example.com via /tabs/{tabId}/navigate) | 400, localhost required or fails safely |+| SEC7 | Proxy safe URL | Proxy normal navigate via /tabs/{tabId}/navigate | 200, works as expected |### 1.14 CLI Subcommandsdiff --git a/tests/manual/dashboard.md b/tests/manual/dashboard.mdindex e55cc100..b4f25087 100644--- a/tests/manual/dashboard.md+++ b/tests/manual/dashboard.md@@ -58,8 +58,8 @@ All tests use `__test_profile__` — cleaned up at end.| DO11 | Profile instance after stop | `GET /profiles/__test_profile__/instance` | 200, running=false | ✅ || DO12 | Launch duplicate port | Launch two profiles on same port | 409, conflict | ✅ || DO13 | Stop by profile name | `POST /profiles/__test_profile__/stop` (when running) | 200, stopped | ✅ |-| DO14 | Start by profile ID | `POST /start/{profileId}` | 201, auto-allocated port | ✅ |-| DO15 | Stop by profile ID | `POST /stop/{profileId}` | 200, stopped | ✅ |+| DO14 | Start by profile ID | `POST /profiles/{profileId}/start` | 201, auto-allocated port | ✅ |+| DO15 | Stop by profile ID | `POST /profiles/{profileId}/stop` | 200, stopped | ✅ |---@@ -173,13 +173,6 @@ Verify every registered route returns a non-404 status (may return 400/503 for m| RE25a | `/profiles/{id}/instance` | GET | 200 (instance status) | ✅ || RE25b | `/profiles/{unknownId}/start` | POST | 404 | ✅ |-### Short aliases (agent convenience)--| # | Route | Method | Expected | Auto |-|---|-------|--------|----------|------|-| RE25c | `/start/{id}` | POST | 201 (same as /profiles/{id}/start) | ✅ |-| RE25d | `/stop/{id}` | POST | 200 (same as /profiles/{id}/stop) | ✅ |-### Proxy endpoints (503 when no instance running)| # | Route | Method | Expected (no instance) | Auto |diff --git a/tests/manual/orchestrator.md b/tests/manual/orchestrator.mdindex 71744a5e..bb972236 100644--- a/tests/manual/orchestrator.md+++ b/tests/manual/orchestrator.md@@ -25,7 +25,10 @@3. Within 5 seconds, a Chrome window should appear on screen.4. Navigate the instance:```bash- curl -X POST http://localhost:9867/instances/{id}/navigate \+ TAB_ID=$(curl -s -X POST http://localhost:9867/instances/{id}/tabs/open \+ -H "Content-Type: application/json" \+ -d '{"action":"new","url":"about:blank"}' | jq -r '.tabId')+ curl -X POST http://localhost:9867/tabs/$TAB_ID/navigate \-H "Content-Type: application/json" \-d '{"url":"https://example.com"}'```@@ -453,7 +456,10 @@2. Navigate on each via orchestrator proxy:```bashfor i in 0 1 2; do- curl -X POST http://localhost:9867/instances/${IDS[$i]}/navigate \+ TAB_ID=$(curl -s -X POST http://localhost:9867/instances/${IDS[$i]}/tabs/open \+ -H "Content-Type: application/json" \+ -d '{"action":"new","url":"about:blank"}' | jq -r '.tabId')+ curl -X POST http://localhost:9867/tabs/$TAB_ID/navigate \-H "Content-Type: application/json" \-d '{"url":"https://example.com"}' | jq '.tabId'done@@ -479,25 +485,28 @@-H "Content-Type: application/json" \-d '{"name":"snap-test","headless":true}' | jq -r '.id')- curl -X POST http://localhost:9867/instances/$ID/navigate \+ TAB_ID=$(curl -s -X POST http://localhost:9867/instances/$ID/tabs/open \+ -H "Content-Type: application/json" \+ -d '{"action":"new","url":"about:blank"}' | jq -r '.tabId')+ curl -X POST http://localhost:9867/tabs/$TAB_ID/navigate \-H "Content-Type: application/json" \-d '{"url":"https://example.com"}' > /dev/null```2. Request snapshot via orchestrator:```bash- curl http://localhost:9867/instances/$ID/snapshot | jq '.nodes | length'+ curl http://localhost:9867/tabs/$TAB_ID/snapshot | jq '.nodes | length'```3. Request screenshot via orchestrator:```bash- curl http://localhost:9867/instances/$ID/screenshot > /tmp/test.png- file /tmp/test.png+ curl http://localhost:9867/tabs/$TAB_ID/screenshot > /tmp/test.jpg+ file /tmp/test.jpg```4. Verify both succeed and return expected formats.-**Criteria:** ✓ Snapshot JSON valid | ✓ Screenshot is PNG | ✓ Both proxied correctly+**Criteria:** ✓ Snapshot JSON valid | ✓ Screenshot is JPEG | ✓ Both proxied correctly---@@ -583,7 +592,10 @@2. Navigate via proxy (should work):```bash- curl -X POST http://localhost:9867/instances/{id}/navigate \+ TAB_ID=$(curl -s -X POST http://localhost:9867/instances/{id}/tabs/open \+ -H "Content-Type: application/json" \+ -d '{"action":"new","url":"about:blank"}' | jq -r '.tabId')+ curl -X POST http://localhost:9867/tabs/$TAB_ID/navigate \-H "Content-Type: application/json" \-d '{"url":"https://example.com"}'```