> ## Documentation Index
> Fetch the complete documentation index at: https://docs.webrun.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Tasks

> Understanding browser tasks and their lifecycle

## What is a Task?

A **task** is a single objective for the AI agent to complete within a browser session. Each task is described in natural language and executed autonomously by the agent.

Examples of tasks:

* "Search Google for Anthropic and return the first result"
* "Find the price of the wireless keyboard on this page"
* "Fill out this form with the provided data and submit it"
* "Navigate through the checkout flow and screenshot the payment page"
* "Download the invoice from the billing portal and upload it to Google Drive"

***

## Task Lifecycle

Tasks progress through several states from initiation to completion:

```
┌─────────┐     ┌───────────┐     ┌─────────────────┐
│ Started │────►│  Running  │────►│ task_completed  │
└─────────┘     └───────────┘     └─────────────────┘
                     │
                     ├───────────► guardrail_trigger
                     │
                     └───────────► failed
```

### Task States

| State               | Description                          | What Happens                      |
| ------------------- | ------------------------------------ | --------------------------------- |
| `started`           | Task has been accepted and queued    | Agent prepares to execute         |
| `running`           | Agent is actively executing the task | Browser actions occurring         |
| `task_completed`    | Task finished successfully           | Result available in response      |
| `guardrail_trigger` | Agent needs human input to proceed   | Task paused, awaiting response    |
| `failed`            | Task encountered an error            | Session may continue or terminate |

***

## Task Patterns

There are two ways to execute tasks:

### Pattern 1: Single Task (`run-task`)

For one-off tasks where you don't need to maintain browser state. The session auto-terminates after completion.

```bash theme={null}
POST /start/run-task

{
  "prompt": "Go to google.com and search for Anthropic"
}
```

### Pattern 2: Multi-Task Session

For workflows requiring sequential tasks within the same browser context (e.g., login → navigate → extract). The session persists across tasks, preserving cookies, authentication, and page state.

```bash theme={null}
# 1. Create session with initial task
POST /start/start-session

{
  "task": {
    "prompt": "Log into the dashboard",
    "startingUrl": "https://example.com/login"
  }
}

# 2. Send follow-up tasks to the session
POST /start/send-message

{
  "sessionId": "sess_abc123",
  "message": {
    "actionType": "newTask",
    "newState": "start",
    "prompt": "Navigate to billing settings"
  }
}
```

| Aspect                | Single Task            | Multi-Task Session                    |
| --------------------- | ---------------------- | ------------------------------------- |
| **Session lifecycle** | Auto-closes after task | Persists until terminated             |
| **Use case**          | Isolated, simple tasks | Multi-step workflows                  |
| **State sharing**     | None                   | Cookies, auth, page context preserved |

<Tip>
  For multi-task sessions, set `terminateOnCompletion: true` on your final task to avoid idle session charges.
</Tip>

***

## Task Properties

### Task Identification

Each task gets a unique `taskId` when created. Use this ID to:

* Poll for task status (REST API)
* Track specific tasks in multi-task workflows
* Retrieve task results

### Task Parameters

| Parameter               | Type      | Default  | Description                                                                                                                             |
| ----------------------- | --------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `prompt`                | string    | required | Natural language task description                                                                                                       |
| `maxDuration`           | number    | 300000   | Max time for this task in ms                                                                                                            |
| `maxInputTokens`        | number    | 100000   | Max input tokens                                                                                                                        |
| `maxOutputTokens`       | number    | 100000   | Max output tokens                                                                                                                       |
| `startingUrl`           | string    | null     | Starting URL (optional)                                                                                                                 |
| `terminateOnCompletion` | boolean   | false    | Auto-terminate session after this task                                                                                                  |
| `secrets`               | array     | `[]`     | Credentials for website authentication ([details](/usage-guides/secrets))                                                               |
| `files`                 | string\[] | `[]`     | File IDs to attach for upload tasks ([details](/environments/file-uploads))                                                             |
| `environmentId`         | string    | null     | Environment ID to attach to the session ([details](/environments/overview)). This is a top-level parameter, not nested inside the task. |

***

## Example: Complete Task Flow

Here's a practical example of sending a task and receiving the result:

**Request:**

```bash theme={null}
POST /start/run-task
Content-Type: application/json

{
  "prompt": "Go to news.ycombinator.com and return the titles of the top 3 posts",
  "maxDuration": 60000
}
```

**Response:**

```json theme={null}
{
  "success": true,
  "sessionId": "sess_7f8a9b2c",
  "taskId": "task_3e4f5a6b",
  "type": "task_completed",
  "data": {
    "message": "Here are the top 3 posts:\n1. Show HN: I built a new programming language\n2. The future of web browsers\n3. Why SQLite is so popular",
    "files": [],
    "network": [
      {
        "id": "hn001",
        "taskId": "task_3e4f5a6b",
        "urls": [
          {
            "url": "https://news.ycombinator.com/",
            "timestamp": 1771138379087.646
          }
        ]
      }
    ]
  },
  "usage": {
    "prompt_tokens": 8200,
    "completion_tokens": 1500,
    "total_tokens": 9700,
    "completion_time": 15.2,
    "cost": 0.0072
  }
}
```

***

## Task Results

When a task completes successfully, you receive a structured result:

```json theme={null}
{
  "success": true,
  "sessionId": "a1b2c3d4e5f6",
  "taskId": "x9y8z7w6v5u4",
  "type": "task_completed",
  "data": {
    "message": "Successfully completed the search",
    "files": [
      {
        "source": "https://example.com/report.zip",
        "downloadUrl": "https://blobs.webrun.ai/files/report.zip",
        "filename": "report.zip",
        "timestamp": 1771138379108
      }
    ],
    "network": [
      {
        "id": "tevo9",
        "taskId": "x9y8z7w6v5u4",
        "urls": [
          {
            "url": "https://example.com/api/data",
            "timestamp": 1771138379087.646
          }
        ]
      }
    ]
  },
  "usage": {
    "prompt_tokens": 12450,
    "completion_tokens": 3200,
    "total_tokens": 15650,
    "completion_time": 23.5,
    "cost": 0.0124
  },
  "completedAt": "2024-01-15T10:30:00Z"
}
```

### Result Fields

| Field                      | Description                                                         |
| -------------------------- | ------------------------------------------------------------------- |
| `data.message`             | Natural language result from the agent                              |
| `data.files`               | Array of files downloaded during task execution (optional)          |
| `data.files[].source`      | Original URL the file was downloaded from                           |
| `data.files[].downloadUrl` | WebRun-hosted URL to download the file                              |
| `data.files[].filename`    | Name of the downloaded file                                         |
| `data.files[].timestamp`   | Unix timestamp (ms) when the file was downloaded                    |
| `data.network`             | Array of network requests captured during task execution (optional) |
| `data.network[].id`        | Unique identifier for the network entry                             |
| `data.network[].taskId`    | Task that generated the network activity                            |
| `data.network[].urls`      | Array of URLs requested with timestamps                             |
| `usage.prompt_tokens`      | Input tokens used                                                   |
| `usage.completion_tokens`  | Output tokens generated                                             |
| `usage.total_tokens`       | Sum of input and output tokens                                      |
| `usage.completion_time`    | Time taken to complete task (seconds)                               |
| `usage.cost`               | Total cost in USD                                                   |
| `completedAt`              | ISO 8601 timestamp                                                  |

***

## Task Execution

### Sequential Execution

Within a single session, tasks run sequentially:

```
Session: sess_abc
├── Task 1 (running) → completes
├── Task 2 (queued) → starts → completes
└── Task 3 (queued) → starts → completes
```

You cannot run multiple tasks in parallel within the same session. For concurrent execution, use multiple sessions.

### Task Duration

Most tasks complete in 10-40 seconds. The API waits up to 50 seconds before returning a `pollUrl` for longer tasks.

**Typical completion times:**

* Simple search/navigation: 10-20 seconds
* Form filling: 20-40 seconds
* Complex multi-step: 60-120 seconds

### Task Dependencies

Tasks can build on previous state within a session. Use the `send-message` endpoint to add tasks to an existing session:

```bash theme={null}
POST /start/send-message
Content-Type: application/json

{
  "sessionId": "sess_abc123",
  "message": {
    "actionType": "newTask",
    "newState": "start",
    "prompt": "Go to my account settings and extract my email address",
    "terminateOnCompletion": true
  }
}
```

This is useful for multi-step workflows where each task depends on the previous one:

1. **Task 1:** Log into the website → session now authenticated
2. **Task 2:** Navigate to settings → page context preserved
3. **Task 3:** Extract data → has access to authenticated page

***

## Writing Effective Task Descriptions

### Be Specific

❌ "Find products"
✅ "Search Amazon for wireless keyboards under \$50 and return the top 3 results with prices"

### Include Context

❌ "Click the button"
✅ "Click the blue 'Add to Cart' button next to the first product"

### Specify Output Format

❌ "Get the data"
✅ "Extract the product name, price, and rating as a JSON object"

### Break Down Complex Tasks

❌ "Research this company and create a report"
✅

1. "Search Google for \[company name] and find their website"
2. "Navigate to their About page and extract the company description"
3. "Find their contact information and return it in structured format"

***

## Task Constraints

### Maximum Duration

Tasks can have a `maxDuration` limit specifying the maximum execution time (default and max: 5 minutes). Session inactivity timeout is separate and fixed at 5 minutes.

### Token Limits

Tasks are constrained by `maxInputTokens` and `maxOutputTokens`. If limits are exceeded:

* Input limit: Task fails with error
* Output limit: Agent's response is truncated

### Domain Restrictions

Use [automation policies](/concepts/policies) with domain rules to control which websites the agent can visit. When a domain is blocked by policy, the agent will:

* Refuse to navigate to those domains
* Trigger a guardrail if configured to do so
* Skip links to those domains in search results

***

## Common Task Patterns

### Research & Extraction

"Search for \[topic] and return \[specific data]"

### Navigation & Screenshot

"Go to \[URL] and take a screenshot of \[element]"

### Form Filling

"Fill out the form with: Name=\[value], Email=\[value], then submit"

### Verification

"Check if \[condition] is true on \[page]"

### File Downloads & Uploads

"Download the CSV report from \[site A] and upload it to \[site B]"

### Conditional Actions

"If \[condition], then \[action], otherwise \[alternative action]"

***

## Related

<CardGroup cols={2}>
  <Card title="Sending Tasks" icon="paper-plane" href="/usage-guides/multi-task-workflows">
    How to create and send tasks
  </Card>

  <Card title="Task Polling" icon="rotate" href="/api-reference/endpoints">
    Poll for task results
  </Card>

  <Card title="Guardrails" icon="shield-halved" href="/concepts/guardrails">
    When tasks need human input
  </Card>

  <Card title="Structured Output" icon="table" href="/usage-guides/structured-output">
    Get structured data from tasks
  </Card>

  <Card title="Environments" icon="box" href="/environments/overview">
    Persist browser data and files across sessions
  </Card>

  <Card title="File Uploads" icon="file-arrow-up" href="/environments/file-uploads">
    Upload files for the agent to use in sessions
  </Card>
</CardGroup>
