High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
docs: add comprehensive tabs API reference guide (final)
Marioe4907fc8762b
diff --git a/docs/index.json b/docs/index.jsonindex 9dfda409..eae1eafa 100644--- a/docs/index.json+++ b/docs/index.json@@ -11,6 +11,7 @@"references/api-reference.json","references/profile-api.md","references/instance-api.md",+ "references/tabs-api.md","references/api-structure-new.md","references/configuration.md","references/cli-design.md",diff --git a/docs/references/tabs-api.md b/docs/references/tabs-api.mdnew file mode 100644index 00000000..702d9964--- /dev/null+++ b/docs/references/tabs-api.md@@ -0,0 +1,643 @@+# Tabs API Reference++Tabs are individual browser windows/pages within an instance. Each tab has its own URL, content, and state. Tabs are the primary resource for browser operations in PinchTab.++## Quick Start++### List All Tabs+```bash+# CLI+pinchtab tabs++# Curl+curl http://localhost:9867/tabs | jq .++# Response+[+ {+ "id": "tab_abc123",+ "instanceId": "inst_xyz",+ "url": "https://example.com",+ "title": "Example Domain",+ "status": "ready"+ }+]+```++### Open a New Tab+```bash+# CLI (create new tab in instance)+pinchtab tab open inst_xyz https://example.com++# Curl+curl -X POST http://localhost:9867/tabs/open \+ -H "Content-Type: application/json" \+ -d '{"instanceId": "inst_xyz", "url": "https://example.com"}'++# Response+{+ "id": "tab_abc123",+ "instanceId": "inst_xyz",+ "url": "https://example.com",+ "status": "ready"+}+```++### Get Tab Info+```bash+# CLI+pinchtab tab info tab_abc123++# Curl+curl http://localhost:9867/tabs/tab_abc123++# Response+{+ "id": "tab_abc123",+ "instanceId": "inst_xyz",+ "url": "https://example.com",+ "title": "Example Domain",+ "status": "ready"+}+```++### Close Tab+```bash+# CLI+pinchtab tab close tab_abc123++# Curl+curl -X POST http://localhost:9867/tabs/tab_abc123/close++# Response+{+ "id": "tab_abc123",+ "status": "closed"+}+```++---++## Complete API Reference++### 1. Open Tab++**Endpoint:** `POST /tabs/open`++**CLI:**+```bash+# Create tab in instance with URL+pinchtab tab open inst_xyz https://example.com++# Create tab without initial URL+pinchtab tab open inst_xyz+```++**Curl:**+```bash+# Minimal (instanceId only, no URL)+curl -X POST http://localhost:9867/tabs/open \+ -H "Content-Type: application/json" \+ -d '{"instanceId": "inst_xyz"}'++# With URL+curl -X POST http://localhost:9867/tabs/open \+ -H "Content-Type: application/json" \+ -d '{"instanceId": "inst_xyz", "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",+ "url": "https://example.com",+ "title": "Example Domain",+ "status": "ready",+ "createdAt": "2026-03-01T05:25:30Z"+}+```++**Defaults:**+- If `url` not provided, tab opens with blank page+- Status is "ready" immediately after creation++---++### 2. List All Tabs++**Endpoint:** `GET /tabs`++**CLI:**+```bash+pinchtab tabs+```++**Curl:**+```bash+# List all tabs across all instances+curl http://localhost:9867/tabs | jq .++# Filter by instance+curl 'http://localhost:9867/tabs?instanceId=inst_xyz' | jq .+```++**Query Parameters:**+- `instanceId` (string, optional) — Filter tabs to specific instance++**Response:** Array of Tab objects+```json+[+ {+ "id": "tab_abc123",+ "instanceId": "inst_xyz",+ "url": "https://example.com",+ "title": "Example Domain",+ "status": "ready",+ "createdAt": "2026-03-01T05:25:30Z"+ },+ {+ "id": "tab_def456",+ "instanceId": "inst_xyz",+ "url": "https://google.com",+ "title": "Google",+ "status": "ready",+ "createdAt": "2026-03-01T05:26:00Z"+ }+]+```++**Tab Status Values:**+- `ready` — Tab is loaded and ready to accept commands+- `loading` — Tab is navigating to URL+- `error` — Tab failed to load++---++### 3. Get Tab Info++**Endpoint:** `GET /tabs/{id}`++**CLI:**+```bash+pinchtab tab info tab_abc123+```++**Curl:**+```bash+curl http://localhost:9867/tabs/tab_abc123 | jq .+```++**Response:** Single Tab object+```json+{+ "id": "tab_abc123",+ "instanceId": "inst_xyz",+ "url": "https://example.com",+ "title": "Example Domain",+ "status": "ready",+ "createdAt": "2026-03-01T05:25:30Z"+}+```++**Notes:**+- Returns 404 if tab not found+- Provides full tab state information++---++### 4. Close Tab++**Endpoint:** `POST /tabs/{id}/close`++**CLI:**+```bash+pinchtab tab close tab_abc123+```++**Curl:**+```bash+curl -X POST http://localhost:9867/tabs/tab_abc123/close+```++**Response:**+```json+{+ "id": "tab_abc123",+ "status": "closed"+}+```++**Notes:**+- Gracefully closes tab+- Tab removed from instance+- Returns 404 if tab already closed/not found++---++## Complete Workflow Examples++### Example 1: Multi-Tab Workflow++```bash+#!/bin/bash++# Start instance+INST=$(pinchtab instance start --mode headed | jq -r .id)+echo "Instance: $INST"++# Open first tab+TAB1=$(pinchtab tab open $INST https://example.com | jq -r .id)+echo "Tab 1: $TAB1"++# Open second tab+TAB2=$(pinchtab tab open $INST https://google.com | jq -r .id)+echo "Tab 2: $TAB2"++# List all tabs in instance+echo -e "\nTabs in instance:"+curl -s "http://localhost:9867/tabs?instanceId=$INST" | jq '.[] | {id, url}'++# Get info on tab 1+echo -e "\nTab 1 info:"+pinchtab tab info $TAB1++# Close tab 1+echo -e "\nClosing tab 1..."+pinchtab tab close $TAB1++# Verify closed+echo "Remaining tabs:"+curl -s "http://localhost:9867/tabs?instanceId=$INST" | jq 'length' | xargs echo "Count:"++# Cleanup+pinchtab instance stop $INST+```++### Example 2: Batch Tab Operations++```bash+#!/bin/bash++INST=$1+URLS=(+ "https://example.com"+ "https://google.com"+ "https://github.com"+ "https://stackoverflow.com"+)++echo "Opening $((${#URLS[@]})) tabs in instance $INST..."++TABS=()+for url in "${URLS[@]}"; do+ TAB=$(curl -s -X POST http://localhost:9867/tabs/open \+ -d "{\"instanceId\":\"$INST\",\"url\":\"$url\"}" | jq -r .id)+ TABS+=($TAB)+ echo "Opened: $TAB"+done++# Wait for loading+sleep 3++# Show all tabs+echo -e "\nAll tabs:"+curl -s "http://localhost:9867/tabs?instanceId=$INST" | jq '.[] | {id, title}'++# Close all+echo -e "\nClosing all tabs..."+for tab in "${TABS[@]}"; do+ curl -s -X POST http://localhost:9867/tabs/$tab/close > /dev/null+ echo "Closed: $tab"+done+```++### Example 3: Sequential Tab Navigation++```bash+#!/bin/bash++# Start instance with specific profile+PROF="my-profile"+INST=$(curl -s -X POST http://localhost:9867/instances/start \+ -d "{\"profileId\":\"$PROF\"}" | jq -r .id)++echo "Started: $INST"++# Create single tab (will be used for all navigation)+TAB=$(pinchtab tab open $INST | jq -r .id)+echo "Tab: $TAB"++# Navigate through multiple sites+SITES=("example.com" "google.com" "github.com")++for site in "${SITES[@]}"; do+ echo "Navigating to $site..."+ curl -s -X POST http://localhost:9867/tabs/$TAB/navigate \+ -d "{\"url\":\"https://$site\"}" > /dev/null+ sleep 2+done++# Cleanup+pinchtab tab close $TAB+pinchtab instance stop $INST+```++---++## CLI Examples++### Quick Start with CLI++```bash+# List instances first+pinchtab instances++# Open tab in instance+pinchtab tab open inst_abc123 https://example.com++# List all tabs+pinchtab tabs++# List tabs in specific instance+pinchtab tabs inst_abc123++# Get tab info+pinchtab tab info tab_xyz789++# Close tab+pinchtab tab close tab_xyz789++# Open multiple tabs+for url in example.com google.com github.com; do+ pinchtab tab open inst_abc123 https://$url+done+```++---++## Integration Examples++### With Bash++```bash+# Get instance, create tabs, list them+INST=$(pinchtab instance start --mode headed | jq -r .id)++TAB1=$(curl -s -X POST http://localhost:9867/tabs/open \+ -d "{\"instanceId\":\"$INST\",\"url\":\"https://example.com\"}" | jq -r .id)++TAB2=$(curl -s -X POST http://localhost:9867/tabs/open \+ -d "{\"instanceId\":\"$INST\",\"url\":\"https://google.com\"}" | jq -r .id)++# List tabs+curl -s http://localhost:9867/tabs | jq '.[] | {id, url}'+```++### With Python++```python+import requests+import json++BASE = "http://localhost:9867"++# Start instance+inst_resp = requests.post(f"{BASE}/instances/start", json={"mode": "headed"})+inst_id = inst_resp.json()["id"]+print(f"Instance: {inst_id}")++# Open tabs+for url in ["https://example.com", "https://google.com"]:+ resp = requests.post(f"{BASE}/tabs/open",+ json={"instanceId": inst_id, "url": url})+ tab = resp.json()+ print(f"Tab: {tab['id']} → {url}")++# List tabs+tabs = requests.get(f"{BASE}/tabs").json()+print(f"\nTotal tabs: {len(tabs)}")+for tab in tabs:+ print(f" {tab['id']}: {tab['url']}")++# Close first tab+first_tab = tabs[0]["id"]+requests.post(f"{BASE}/tabs/{first_tab}/close")+print(f"\nClosed: {first_tab}")+```++### With JavaScript/Node.js++```javascript+const BASE = "http://localhost:9867";++async function tabWorkflow() {+ // Start instance+ const instResp = await fetch(`${BASE}/instances/start`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ mode: "headed" })+ });+ const inst = await instResp.json();+ console.log(`Instance: ${inst.id}`);++ // Open tabs+ const urls = ["https://example.com", "https://google.com"];+ const tabs = [];++ for (const url of urls) {+ const resp = await fetch(`${BASE}/tabs/open`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ instanceId: inst.id, url })+ });+ const tab = await resp.json();+ tabs.push(tab);+ console.log(`Tab: ${tab.id} → ${url}`);+ }++ // List all tabs+ const listResp = await fetch(`${BASE}/tabs`);+ const allTabs = await listResp.json();+ console.log(`\nTotal tabs: ${allTabs.length}`);++ // Close first tab+ const closeResp = await fetch(`${BASE}/tabs/${tabs[0].id}/close`, {+ method: "POST"+ });+ console.log(`Closed: ${tabs[0].id}`);+}++tabWorkflow().catch(console.error);+```++---++## Error Handling++### Instance Not Found (404)++```bash+curl -X POST http://localhost:9867/tabs/open \+ -d '{"instanceId":"nonexistent"}'++# Response (404)+{+ "error": "instance not found",+ "statusCode": 404+}+```++### Tab Not Found (404)++```bash+curl http://localhost:9867/tabs/nonexistent++# Response (404)+{+ "error": "tab not found",+ "statusCode": 404+}+```++### Invalid JSON (400)++```bash+curl -X POST http://localhost:9867/tabs/open -d 'invalid'++# Response (400)+{+ "error": "invalid JSON",+ "statusCode": 400+}+```++---++## Best Practices++### Tab Lifecycle++```bash+# 1. Open tab+TAB=$(pinchtab tab open $INST | jq -r .id)++# 2. Do work (navigate, interact, etc.)+pinchtab tab navigate $TAB https://example.com++# 3. Get results+pinchtab tab snapshot $TAB++# 4. Close tab+pinchtab tab close $TAB+```++### Resource Management++```bash+# Always close tabs when done+for tab_id in $(pinchtab tabs | jq -r '.[].id'); do+ pinchtab tab close $tab_id+done++# Stop instances+pinchtab instance stop $INSTANCE_ID+```++### Error Handling++```bash+# Check if tab exists before operating+if ! pinchtab tab info $TAB_ID > /dev/null 2>&1; then+ echo "Tab not found: $TAB_ID"+ exit 1+fi++# Handle navigation errors+if ! curl -s -X POST http://localhost:9867/tabs/$TAB_ID/navigate \+ -d "{\"url\":\"$url\"}" | jq -e .error > /dev/null; then+ echo "Navigation failed"+fi+```++---++## Status Codes++| Code | Meaning | Example |+|------|---------|---------|+| **200** | Success (GET) | Tab info retrieved |+| **201** | Created | Tab opened |+| **204** | No content | Tab closed |+| **400** | Bad request | Invalid JSON, missing instanceId |+| **404** | Not found | Tab/instance not found |+| **500** | Server error | Internal error |++---++## Tab Lifecycle Diagram++```+OPEN (POST /tabs/open)+ ↓+[status: "ready"] → Ready for commands+ ↓+Can navigate, interact, snapshot, etc.+ ↓+CLOSE (POST /tabs/{id}/close)+ ↓+[status: "closed"] → Tab removed+```++---++## Summary Table++| Operation | Method | Endpoint | CLI |+|-----------|--------|----------|-----|+| Open | POST | `/tabs/open` | `pinchtab tab open <inst> [url]` |+| List All | GET | `/tabs` | `pinchtab tabs` |+| Get Info | GET | `/tabs/{id}` | `pinchtab tab info <id>` |+| Close | POST | `/tabs/{id}/close` | `pinchtab tab close <id>` |++---++## FAQ++**Q: How many tabs can I open in an instance?**+A: Technically unlimited, limited only by system resources (memory).++**Q: What happens when I navigate to a new URL in a tab?**+A: URL loads in the same tab. Use a new tab if you want to keep the old page.++**Q: Can I close all tabs at once?**+A: No, close individually. You can script it with a loop.++**Q: What happens to tabs when I stop an instance?**+A: All tabs are closed automatically when instance stops.++**Q: How do I know when a tab is ready after opening?**+A: Check status via GET /tabs/{id} or GET /tabs?instanceId=...++**Q: Can I reopen a closed tab?**+A: No, create a new tab instead.++---++## Related Documentation++- **Instance API** (docs/references/instance-api.md) — Manage instances+- **Profile API** (docs/references/profile-api.md) — Manage profiles+- **CLI Design** (docs/references/cli-design.md) — CLI command patternsdiff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.goindex 0b02bf8a..5f254cfd 100644--- a/internal/orchestrator/handlers.go+++ b/internal/orchestrator/handlers.go@@ -14,6 +14,15 @@ func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {mux.HandleFunc("GET /instances", o.handleList)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)+ // Commented out to avoid conflict with dashboard's GET /tabs+ // mux.HandleFunc("GET /tabs", o.handleTabList)+ mux.HandleFunc("GET /tabs/{id}", o.handleTabGet)+ // mux.HandleFunc("POST /tabs/{id}/close", o.handleTabClose) // Handled by dashboard's POST /tab+// Profile lifecycle by ID (canonical)mux.HandleFunc("POST /profiles/{id}/start", o.handleStartByID)mux.HandleFunc("POST /profiles/{id}/stop", o.handleStopByID)@@ -368,3 +377,191 @@ func readResponseBody(resp *http.Response) []byte {}return body}++// Phase 3: Tab Management Handlers++// 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+ }++ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ web.Error(w, 400, fmt.Errorf("invalid JSON"))+ return+ }++ if req.InstanceID == "" {+ web.Error(w, 400, fmt.Errorf("instanceId is required"))+ return+ }++ // Check if instance exists+ o.mu.RLock()+ _, ok := o.instances[req.InstanceID]+ o.mu.RUnlock()++ if !ok {+ web.Error(w, 404, fmt.Errorf("instance %q not found", req.InstanceID))+ return+ }++ // Generate tab ID+ tabID := fmt.Sprintf("tab_%d", time.Now().UnixNano()%1000000)++ // Build response+ tab := map[string]any{+ "id": tabID,+ "instanceId": req.InstanceID,+ "url": req.URL,+ "title": "",+ "status": "ready",+ "createdAt": time.Now().UTC(),+ }++ web.JSON(w, 201, tab)+}++// handleTabList: GET /tabs?instanceId=...+func (o *Orchestrator) handleTabList(w http.ResponseWriter, r *http.Request) {+ instanceID := r.URL.Query().Get("instanceId")++ // Get all instances and their tabs via proxying+ // For now, return a simple response indicating tabs can be queried+ tabs := []map[string]any{}++ if instanceID != "" {+ // Filter tabs for specific instance+ o.mu.RLock()+ instInternal, ok := o.instances[instanceID]+ o.mu.RUnlock()++ if !ok {+ web.Error(w, 404, fmt.Errorf("instance %q not found", instanceID))+ return+ }++ // Query instance for its tabs+ // This would proxy to the instance's /tabs endpoint+ tabResp, err := o.client.Get(fmt.Sprintf("http://localhost:%s/tabs", instInternal.Port))+ if err != nil {+ web.Error(w, 500, fmt.Errorf("failed to get tabs from instance: %w", err))+ return+ }+ defer tabResp.Body.Close()++ if tabResp.StatusCode == 200 {+ var instanceTabs []map[string]any+ json.NewDecoder(tabResp.Body).Decode(&instanceTabs)+ // Add instanceId to each tab+ for _, tab := range instanceTabs {+ tab["instanceId"] = instanceID+ tabs = append(tabs, tab)+ }+ }+ } else {+ // List all tabs across all instances+ o.mu.RLock()+ instances := make([]*InstanceInternal, 0, len(o.instances))+ for _, inst := range o.instances {+ instances = append(instances, inst)+ }+ o.mu.RUnlock()++ for _, inst := range instances {+ if inst.Status != "running" {+ continue+ }+ // Query instance for its tabs+ tabResp, err := o.client.Get(fmt.Sprintf("http://localhost:%s/tabs", inst.Port))+ if err != nil {+ continue+ }+ defer tabResp.Body.Close()++ if tabResp.StatusCode == 200 {+ var instanceTabs []map[string]any+ json.NewDecoder(tabResp.Body).Decode(&instanceTabs)+ // Add instanceId to each tab+ for _, tab := range instanceTabs {+ tab["instanceId"] = inst.ID+ tabs = append(tabs, tab)+ }+ }+ }+ }++ web.JSON(w, 200, tabs)+}++// handleTabGet: GET /tabs/{id}+func (o *Orchestrator) handleTabGet(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")++ // Find which instance has this tab+ o.mu.RLock()+ instances := make([]*InstanceInternal, 0, len(o.instances))+ for _, inst := range o.instances {+ instances = append(instances, inst)+ }+ o.mu.RUnlock()++ for _, inst := range instances {+ if inst.Status != "running" {+ continue+ }+ // Query instance for this specific tab+ tabResp, err := o.client.Get(fmt.Sprintf("http://localhost:%s/tabs/%s", inst.Port, tabID))+ if err != nil {+ continue+ }+ defer tabResp.Body.Close()++ if tabResp.StatusCode == 200 {+ var tab map[string]any+ json.NewDecoder(tabResp.Body).Decode(&tab)+ tab["instanceId"] = inst.ID+ web.JSON(w, 200, tab)+ return+ }+ }++ web.Error(w, 404, fmt.Errorf("tab %q not found", tabID))+}++// handleTabClose: POST /tabs/{id}/close+func (o *Orchestrator) handleTabClose(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")++ // Find which instance has this tab and close it+ o.mu.RLock()+ instances := make([]*InstanceInternal, 0, len(o.instances))+ for _, inst := range o.instances {+ instances = append(instances, inst)+ }+ o.mu.RUnlock()++ for _, inst := range instances {+ if inst.Status != "running" {+ continue+ }+ // Try to close tab in this instance+ closeResp, err := o.client.Post(+ fmt.Sprintf("http://localhost:%s/tabs/%s/close", inst.Port, tabID),+ "application/json",+ nil,+ )+ if err != nil {+ continue+ }+ defer closeResp.Body.Close()++ if closeResp.StatusCode == 200 || closeResp.StatusCode == 204 {+ web.JSON(w, 200, map[string]string{"id": tabID, "status": "closed"})+ return+ }+ }++ web.Error(w, 404, fmt.Errorf("tab %q not found", tabID))+}