# Edge-Hosted Browser Rendering Integration

Secrooq Compute provides integration with the **Edge-Hosted Browser Rendering API**. This allows long-running autonomous AI agents to utilize managed, stateless, or persistent headless Chrome instances running on the global edge network.

---

## Architecture: Edge-Hosted Browser Rendering vs. in-VM vision API

Secrooq provides two ways to automate browsers:

1. **In-VM Vision API (Default / Backward Compatible)**
   - Runs a full desktop GUI inside your dedicated hardware-isolated Firecracker MicroVM container (Chromium + Xvfb + `xdotool`).
   - Best for stateful desktop sessions, applications requiring a window manager, running local extensions, or where you need real-time VNC access to a visual desktop display.
   - Operated via `/screenshot`, `/click`, `/type`, `/scroll`, and `/drag` vision endpoints.

2. **Edge-Hosted Browser Rendering (Recommended for heavy web scraping / automation)**
   - Spawns cloud-managed headless browsers managed directly on the global edge network.
   - **Higher Performance & Concurrency**: Spawns in milliseconds, utilizing edge-level scaling.
   - **Puppeteer-native**: Ideal for complex interactions (navigating DOM, selector-based waits, scraping, script evaluations).
   - Keeps sessions alive for up to 30 minutes of idle time.

---

## API Reference

All Browser Run endpoints are mounted under `/computers/:id/browser/*` (also backward compatible with legacy `/computers/:id/browser/*`).

### 1. Create a Browser Session
Starts a new headless browser session and returns a connection payload.

* **Endpoint**: `POST /computers/:id/browser/sessions`
* **Response**:
  ```json
  {
    "sessionId": "bs_87acdf91",
    "webSocketDebuggerUrl": "wss://chrome.edge.secrooq.internal/...",
    "webSocketUrl": "wss://chrome.edge.secrooq.internal/..."
  }
  ```

---

### 1.5 Extract DOM Content
Extracts structured elements (HTML, Markdown, Plain Text, and Title) from the session's active page.

* **Endpoint**: `GET /computers/:id/browser/sessions/:sessionId/dom`
* **Rate Limit**: 30 requests per minute per session.
* **Response**:
  ```json
  {
    "html": "<html><body><h1>Example Domain</h1><p>This is a test.</p></body></html>",
    "markdown": "# Example Domain\n\nThis is a test.",
    "textContent": "Example Domain\n\nThis is a test.",
    "title": "Example Domain"
  }
  ```

---

### 2. Navigate to a URL
Commands the session's active page to navigate to a target website.

* **Endpoint**: `POST /computers/:id/browser/sessions/:sessionId/navigate`
* **Body**:
  ```json
  {
    "url": "https://example.com"
  }
  ```
* **Response**:
  ```json
  {
    "success": true,
    "message": "Successfully navigated to https://example.com"
  }
  ```

### 3. Take Page Screenshot
Capture the current visual state of the browser. Supports capturing the visible screen or the entire page height.

* **Endpoint**: `GET /computers/:id/browser/sessions/:sessionId/screenshot`
* **Query Parameters**:
  - `fullPage` (boolean, optional): Set to `true` to capture a full-page scroll screenshot.
* **Response**: Binary PNG stream (`Content-Type: image/png`).

### 4. Click Elements
Click a specific HTML selector or specific coordinates on the active page.

* **Endpoint**: `POST /computers/:id/browser/sessions/:sessionId/click`
* **Body** (Selector-based):
  ```json
  {
    "selector": "button.submit"
  }
  ```
* **Body** (Coordinate-based):
  ```json
  {
    "x": 250,
    "y": 480
  }
  ```
* **Response**:
  ```json
  {
    "success": true
  }
  ```

### 5. Type Text
Types text string using the keyboard simulator on the currently focused element.

* **Endpoint**: `POST /computers/:id/browser/sessions/:sessionId/type`
* **Body**:
  ```json
  {
    "text": "Autonomous Agent"
  }
  ```
* **Response**:
  ```json
  {
    "success": true
  }
  ```

### 6. Evaluate Javascript Script
Evaluates code in the context of the active page and returns the serialized JSON result.

* **Endpoint**: `POST /computers/:id/browser/sessions/:sessionId/evaluate`
* **Body**:
  ```json
  {
    "script": "document.title"
  }
  ```
* **Response**:
  ```json
  {
    "result": "Example Domain"
  }
  ```

### 7. Close Session
Immediately terminates the browser instance and closes the session.

* **Endpoint**: `DELETE /computers/:id/browser/sessions/:sessionId`
* **Response**:
  ```json
  {
    "success": true,
    "message": "Browser session successfully closed."
  }
  ```

---

## Concurrency Rate Limits
To ensure platform stability and prevent resource abuse, Secrooq enforces a strict limit of **5 concurrent active browser sessions per computer**. 
* Attempting to create a 6th session will result in a `429 Too Many Requests` response.

---

## Error & Expiry Handling (404 Responses)
If a browser session is terminated (either via explicit `DELETE`, auto-expiration, or remote edge closure), any subsequent page action endpoint request will:
1. Automatically transition the session status to `closed` in the database.
2. Return a `404 Not Found` response:
   ```json
   {
     "error": "Not Found",
     "message": "Browser session has been closed or is unavailable."
   }
   ```

---

## Session Cleanup Lifecycle
Secrooq executes automated maintenance processes to manage active edge browser connections:
1. **Idle Expiry (30 Minutes)**: Any session with no API activity for **30 minutes** is automatically disconnected and closed.
2. **Hard Limit (1 Hour)**: To prevent runaway processes, all active sessions are force-closed after **1 hour** from initial creation.
3. **Database Purge (30 Days)**: Closed session history metadata is automatically deleted from the relational database after **30 days** to keep telemetry logs lean.

