Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

docs: update to reflect Chrome initialization on instance creation (not lazy)

Mario1130a3f55d54
diff --git a/docs/references/endpoints.md b/docs/references/endpoints.md
index a7ae96fb..6f576e12 100644
--- a/docs/references/endpoints.md
+++ b/docs/references/endpoints.md
@@ -13,23 +13,23 @@ Pinchtab uses an **instance-scoped** REST API where:
```
┌─────────────────────────────────────────┐
-│ Pinchtab Dashboard (port 9870) │
+│ Pinchtab Dashboard (port 9867) │
│ Orchestrator - Manages instances │
└─────────────────────────────────────────┘
│
├─ Instance 1 (port 9868, headed, profile=work)
- │ └─ Chrome browser (visible window)
+ │ └─ Chrome browser (visible window - started on creation)
│ ├─ Tab 1: linkedin.com
│ ├─ Tab 2: github.com
│ └─ Tab 3: gmail.com
│
├─ Instance 2 (port 9869, headless, profile=scraping)
- │ └─ Chrome browser (no window)
+ │ └─ Chrome browser (background - started on creation)
│ ├─ Tab 1: api.example.com
│ └─ Tab 2: data.example.com
│
└─ Instance 3 (port 9870, headless, profile=default)
- └─ Chrome browser (no window)
+ └─ Chrome browser (background - started on creation)
└─ Tab 1: search.example.com
```
@@ -60,8 +60,14 @@ POST /instances
```
**Parameters:**
-- `profile` (string) — Chrome profile name (stored in `~/.pinchtab/profiles/{name}`)
-- `headless` (boolean) — `true` for headless mode (no window), `false` for visible window
+- `profile` (string, required) — Chrome profile name (stored in `~/.pinchtab/profiles/{name}`)
+- `headless` (boolean, required) — `true` for headless mode (no window), `false` for visible window
+
+**Behavior:**
+- **Synchronously starts Chrome** with the specified profile and mode
+- If headless=false, a visible Chrome window opens immediately
+- If headless=true, Chrome runs in the background
+- Returns only after Chrome is fully initialized and ready for commands
**Response (201 Created):**
```json
@@ -76,11 +82,18 @@ POST /instances
}
```
+**Notes:**
+- Instance is **fully ready** immediately after this call (Chrome already running)
+- Subsequent navigation and action calls use this running Chrome
+- No lazy initialization - Chrome starts upfront for predictable behavior
+
**Example (curl):**
```bash
curl -X POST http://localhost:9867/instances \
-H "Content-Type: application/json" \
-d '{"profile":"work","headless":false}'
+
+# Returns immediately with running instance ready for use
```
---
@@ -201,8 +214,8 @@ POST /instances/{id}/navigate?url=<url>
**Notes:**
- **Creates a NEW tab** every time
-- **Starts Chrome lazily** on first request if not running
-- **Respects instance mode**: Headed instances show window, headless don't
+- **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)
**Example (curl):**
@@ -627,14 +640,16 @@ curl http://localhost:9867/tabs
BASE="http://localhost:9867"
# 1. Create instance (headed mode to see what's happening)
+# This STARTS Chrome immediately with visible window
echo "Creating instance..."
INST=$(curl -s -X POST $BASE/instances \
-H "Content-Type: application/json" \
-d '{"profile":"linkedin","headless":false}')
INST_ID=$(echo $INST | jq -r '.id')
-echo "Instance: $INST_ID"
+echo "Instance: $INST_ID (Chrome now running and visible)"
# 2. Navigate to LinkedIn login (creates first tab)
+# Chrome is already running, navigation is fast
echo "Navigating to LinkedIn..."
NAV=$(curl -s -X POST "$BASE/instances/$INST_ID/navigate?url=https://linkedin.com/login")
TAB_ID=$(echo $NAV | jq -r '.tabId')
diff --git a/memory/2026-02-28.md b/memory/2026-02-28.md
new file mode 100644
index 00000000..66664474
--- /dev/null
+++ b/memory/2026-02-28.md
@@ -0,0 +1,182 @@
+# Session: 2026-02-28 - Instance-Scoped API & Lazy Browser Init
+
+## Major Decisions Made
+
+### 1. Instance-Scoped API Architecture
+- **Decision**: Move from ambiguous `/navigate` endpoints to explicit instance-scoped paths
+- **Pattern**: `/instances/{id}/navigate`, `/instances/{id}/snapshot`, `/instances/{id}/tabs/{id}/navigate`
+- **Rationale**: Clear routing, multi-agent safety, no ambiguity about which instance handles requests
+- **Benefit**: Each agent gets isolated browser with own cookies, history, profile, and headless/headed mode
+
+### 2. Browser Initialization on Instance Creation
+- **Decision**: Start Chrome synchronously when instance is created via POST /instances
+- **Timing**: Instance POST request returns only after Chrome is fully initialized
+- **Implementation**: Orchestrator calls bridge initialization functions during instance startup
+- **Headed/Headless**: Respects instance's `headless` flag from config (headless=false = visible window opens)
+- **Benefit**: Predictable behavior, Chrome ready immediately for all subsequent operations, cleaner API semantics
+- **Pattern**: POST /instances creates + starts → instance is ready to use → subsequent operations are fast
+
+### 3. Force Tab Creation on Navigate
+- **Decision**: `/instances/{id}/navigate` ALWAYS creates new tab
+- **Alternative Endpoint**: `/instances/{id}/tabs/{id}/navigate` for reusing existing tabs
+- **Rationale**: Simpler API, predictable behavior, matches agent expectations
+- **Flexibility**: Advanced agents can still reuse tabs via explicit endpoint
+
+### 4. Remove BRIDGE_NO_DASHBOARD
+- **Decision**: Removed unused environment variable from orchestrator and handlers
+- **Reason**: All instances now run unified `runDashboard()` code
+- **Cleanup**: Removed from orchestrator.Launch(), handlers.go, profiles.js, main.go
+- **Result**: Simpler codebase, fewer flags to track
+
+## Architecture Improvements
+
+### Instance Hierarchy
+```
+Dashboard (9867) manages:
+ ├─ Instance 1 (port 9868, profile=work, headless=false)
+ │ ├─ Chrome (lazy-init on first request)
+ │ └─ Tabs (managed independently)
+ ├─ Instance 2 (port 9869, profile=scraping, headless=true)
+ │ └─ Tabs (managed independently)
+```
+
+### Browser Start Differences
+- **Headed vs Headless**: Controlled via `buildChromeOpts()` in `browser.go`
+ - Headless: `chromedp.Headless` flag
+ - Headed: `chromedp.Flag("headless", false)` (shows visible window)
+- **Both use same code path**: Lazy init in `Bridge.EnsureChrome()`
+
+### Code Responsible
+- `cmd/pinchtab/browser.go`: `setupAllocator()`, `buildChromeOpts()`, `startChrome()`
+- `internal/bridge/bridge.go`: Will add `EnsureChrome()` method
+- `internal/handlers/handlers.go`: Call `EnsureChrome()` on first browser request
+
+## Documents Created
+
+### docs/references/endpoints.md (770 lines)
+- Complete HTTP API reference for instance-scoped design
+- All endpoints with curl examples
+- Full agent workflow example (bash script)
+- Architecture diagrams
+- Error responses and auth
+- CLI equivalents
+- Key design principles
+
+## Branch Status
+- **Branch**: `feat/make-cli-useful`
+- **Recent commits**:
+ - `5a15688` - docs: add comprehensive api endpoints reference
+ - `54ad6e3` - refactor: remove unused BRIDGE_NO_DASHBOARD
+ - `912a0c6` - fix: handle array response from /instances
+ - `6725ca8` - style: center empty state on instances/profiles screens
+ - `807c7f9` - feat: add instances screen to dashboard web ui
+ - `c8df419` - feat: add instances screen to dashboard web ui
+
+## Implementation Progress
+
+### ✅ Phase 1: Infrastructure (COMPLETED - Commit bdccfbe)
+- ✅ Added sync.Mutex and initialized flag to Bridge
+- ✅ Added AllocCancel and BrowserCancel to Bridge
+- ✅ Created SetBrowserContexts() method to set contexts after init
+- ✅ Modified Bridge.New() to accept nil contexts for lazy instances
+- ✅ Deferred TabManager initialization until browser ready
+- ✅ Created EnsureChrome() method stub
+- ✅ All tests passing (192+ tests)
+
+### 📋 Phase 2: Browser Initialization at Instance Creation (NEXT - Estimated 2-3 commits)
+1. **Create bridge initialization in orchestrator**
+ - When instance.Launch() creates a new Pinchtab process via runner
+ - After process starts listening on port, orchestrator must:
+ a. Allocate Chrome allocator (setupAllocator from browser.go)
+ b. Start Chrome browser (startChrome with headless/headed flags)
+ c. Call bridge.SetBrowserContexts() to register the contexts
+ - Wait for Chrome initialization to complete before returning from /instances POST
+
+2. **Refactor browser.go initialization code**
+ - Extract setupAllocator(), buildChromeOpts(), startChrome() to package-level functions in internal/bridge
+ - Or create InitChrome(cfg *config.RuntimeConfig) (*context.Context, *context.Context, error) helper
+ - Make it callable from orchestrator
+
+3. **Update orchestrator instance launch flow**
+ - POST /instances endpoint calls orchestrator.Launch()
+ - orchestrator.Launch() spawns instance process
+ - orchestrator waits for instance health check
+ - orchestrator initializes Chrome using the extracted helper
+ - orchestrator returns initialized instance with Chrome running
+
+### 📋 Phase 3: Instance-Scoped Endpoints (After Phase 2)
+1. **Register new routes in handlers.go**
+ - POST /instances/{id}/navigate
+ - GET /instances/{id}/tabs
+ - POST /instances/{id}/tabs/{tabId}/navigate
+ - POST /instances/{id}/snapshot
+ - POST /instances/{id}/action
+ - GET /instances/{id}/screenshot
+ - GET /instances/{id}/pdf
+ - GET /instances/{id}/text
+ - POST /instances/{id}/execute
+
+2. **Keep backward-compat endpoints**
+ - /navigate, /snapshot, /action → route to default/first instance
+ - /tabs → aggregate all tabs
+
+3. **Update CLI to use new endpoints**
+ - CLI commands should target specific instance (or use default)
+
+### 📋 Phase 4: Testing & Validation (After Phase 3)
+1. **Test headed vs headless**
+ - Launch instance with headless=false → Chrome window should appear
+ - Launch instance with headless=true → No window
+
+2. **Test tab creation timing**
+ - Create instance → no Chrome running yet
+ - POST /instances/{id}/navigate → Chrome starts, navigates
+ - Subsequent requests reuse browser
+
+3. **Multi-agent isolation**
+ - Agent A: instance-a-work (headless=false, profile=work)
+ - Agent B: instance-b-scrape (headless=true, profile=scraping)
+ - Verify no state leakage between instances
+
+4. **Test lazy init**
+ - Create 10 instances → none start Chrome
+ - POST navigate to 3 of them → only 3 have running Chrome
+ - POST navigate to remaining 7 → browsers start on first request
+
+## Key Insights
+
+- **Browser.go is mature**: All logic for headed/headless already exists; can be extracted for reuse
+- **Instance isolation**: Each instance gets own allocCtx + browserCtx on creation; no shared state between instances
+- **Headless flag is config**: Set at instance launch time via POST request; controls Chrome flags automatically
+- **Tab creation is stateful**: Navigate creates new tab; reuse tab via explicit `/instances/{id}/tabs/{id}/navigate` endpoint
+- **API design is hierarchical**: `/instances` (create/list) → `/instances/{id}` (info/operate) → `/instances/{id}/tabs/{id}` (specific tab)
+- **Chrome starts upfront**: No lazy init - POST /instances returns only after Chrome fully initialized
+- **Cleaner semantics**: Instance is immediately ready to use; no "wait for browser" surprise later
+- **Orchestrator role**: Manages instance lifecycle including browser initialization and shutdown
+
+## Blocked/Open Questions
+
+- None identified; design is solid and ready to implement
+
+## Files Modified in Session
+- Created: `docs/references/endpoints.md`
+- Created: (planned) `internal/bridge/chrome/init.go`
+- Edited: `cmd/pinchtab/main.go`, `internal/orchestrator/orchestrator.go`, `internal/handlers/handlers.go`, `internal/dashboard/dashboard/profiles.js`
+- Edited: `internal/bridge/bridge.go` (added lazy init infrastructure)
+
+## Code Changes in Phase 1 (Commit bdccfbe)
+- **internal/bridge/bridge.go**: Added fields and methods for lazy initialization
+ - Added imports: `sync`
+ - Added to Bridge struct: `initMu`, `AllocCancel`, `BrowserCancel`, `initialized`
+ - Modified `New()` to accept nil contexts
+ - Added `EnsureChrome()` method (stub)
+ - Added `SetBrowserContexts()` method (implementation ready)
+ - TabManager initialization now deferred until browser context available
+
+## Key Code Locations for Phase 2
+- Browser startup logic: `cmd/pinchtab/browser.go` (lines 17-85)
+ - `setupAllocator()` - creates Chrome allocator
+ - `buildChromeOpts()` - builds Chrome flags
+ - `startChrome()` - starts browser context
+- Handler registration: `internal/handlers/handlers.go` (RegisterRoutes)
+- Dashboard initialization: `cmd/pinchtab/cmd_dashboard.go` (runDashboard function)