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

# Get Task Status

> Check the current status of a specific task to see if it's in progress, completed, or what status it has. This is a lightweight endpoint perfect for polling task progress.

This endpoint allows you to check the current status of a task without retrieving the full task object. It's optimized for frequent polling and returns only essential status information including progress percentage, completion state, and any errors.

## Authentication

**Required** - You need a BLACKBOX API Key to use this API.

Follow these steps to get your API key:

1. **Click on your Profile Image** in the top right corner at [cloud.blackbox.ai](https://cloud.blackbox.ai)
2. **Click on "BLACKBOX API Token"** from the dropdown menu
3. **Copy the existing token** or **click "Generate"** if you don't have one yet

Your API key will be in the format: `bb_xxxxxxxxxxxxxxxxxxxxxx`

## Headers

<ParamField header="Authorization" type="string" required>
  API Key of the form `Bearer <api_key>`.

  Example: `Bearer bb_b41b647ffbfed27f61656049d3eaeef3d903cc503345d9eb80080d98bc0`
</ParamField>

## Path Parameters

<ParamField path="taskId" type="string" required>
  The unique identifier of the task you want to check the status for.

  Example: `9qQe2F8Z_nXx9-eJA0BD6`
</ParamField>

## Response Fields

<ResponseField name="taskId" type="string">
  Task identifier.
</ResponseField>

<ResponseField name="status" type="string">
  Current status of the task.

  Possible values:

  * `pending` - Task is queued and waiting to start
  * `processing` - Task is currently being executed
  * `saving` - Task is saving changes
  * `completed` - Task finished successfully
  * `error` - Task failed with an error
  * `stopped` - Task was manually stopped by user
  * `timeout` - Task exceeded maximum duration
</ResponseField>

<ResponseField name="progress" type="number">
  Progress percentage (0-100).
</ResponseField>

<ResponseField name="inProgress" type="boolean">
  Whether task is currently running (pending/processing/saving).
</ResponseField>

<ResponseField name="isDone" type="boolean">
  Whether task has finished (completed/error/stopped/timeout).
</ResponseField>

<ResponseField name="error" type="string | null">
  Error message if task failed, null otherwise.
</ResponseField>

<ResponseField name="createdAt" type="string">
  ISO 8601 timestamp when task was created.
</ResponseField>

<ResponseField name="updatedAt" type="string">
  ISO 8601 timestamp of last update.
</ResponseField>

<ResponseField name="completedAt" type="string | null">
  ISO 8601 timestamp when task completed, null if still running.
</ResponseField>

<ResponseField name="duration" type="string | null">
  Task duration in seconds (e.g., "900s") if completed, null otherwise.
</ResponseField>

<RequestExample>
  ```bash cURL theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  curl 'https://cloud.blackbox.ai/api/tasks/9qQe2F8Z_nXx9-eJA0BD6/status' \
    -H 'Authorization: Bearer YOUR_API_KEY' \
    -H 'Accept: application/json'
  ```

  ```javascript Node.js theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  const API_KEY = "YOUR_API_KEY";
  const TASK_ID = "9qQe2F8Z_nXx9-eJA0BD6";
  const API_URL = `https://cloud.blackbox.ai/api/tasks/${TASK_ID}/status`;

  const response = await fetch(API_URL, {
      method: "GET",
      headers: {
          Authorization: `Bearer ${API_KEY}`,
          Accept: "application/json",
      },
  });

  const status = await response.json();
  console.log(`Task ${status.taskId}: ${status.status} (${status.progress}%)`);
  ```

  ```python Python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  import requests

  API_KEY = "YOUR_API_KEY"
  TASK_ID = "9qQe2F8Z_nXx9-eJA0BD6"
  API_URL = f"https://cloud.blackbox.ai/api/tasks/{TASK_ID}/status"

  headers = {
      "Authorization": f"Bearer {API_KEY}",
      "Accept": "application/json"
  }

  response = requests.get(API_URL, headers=headers)
  status = response.json()
  print(f"Task {status['taskId']}: {status['status']} ({status['progress']}%)")
  ```

  ```go Go theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  package main

  import (
      "encoding/json"
      "fmt"
      "io"
      "net/http"
  )

  func main() {
      apiKey := "YOUR_API_KEY"
      taskId := "9qQe2F8Z_nXx9-eJA0BD6"
      url := fmt.Sprintf("https://cloud.blackbox.ai/api/tasks/%s/status", taskId)

      req, _ := http.NewRequest("GET", url, nil)
      req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", apiKey))
      req.Header.Add("Accept", "application/json")

      client := &http.Client{}
      resp, err := client.Do(req)
      if err != nil {
          panic(err)
      }
      defer resp.Body.Close()

      body, _ := io.ReadAll(resp.Body)
      
      var status map[string]interface{}
      json.Unmarshal(body, &status)
      
      fmt.Printf("Task %s: %s (%.0f%%)\n", 
          status["taskId"], 
          status["status"], 
          status["progress"])
  }
  ```
</RequestExample>

<ResponseExample>
  ```json Task In Progress theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  {
    "taskId": "9qQe2F8Z_nXx9-eJA0BD6",
    "status": "processing",
    "progress": 45,
    "inProgress": true,
    "isDone": false,
    "error": null,
    "createdAt": "2024-01-15T10:00:00.000Z",
    "updatedAt": "2024-01-15T10:05:00.000Z",
    "completedAt": null,
    "duration": null
  }
  ```

  ```json Task Completed theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  {
    "taskId": "9qQe2F8Z_nXx9-eJA0BD6",
    "status": "completed",
    "progress": 100,
    "inProgress": false,
    "isDone": true,
    "error": null,
    "createdAt": "2024-01-15T10:00:00.000Z",
    "updatedAt": "2024-01-15T10:15:00.000Z",
    "completedAt": "2024-01-15T10:15:00.000Z",
    "duration": "900s"
  }
  ```

  ```json Task Failed theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  {
    "taskId": "9qQe2F8Z_nXx9-eJA0BD6",
    "status": "error",
    "progress": 60,
    "inProgress": false,
    "isDone": true,
    "error": "Failed to execute command: npm install",
    "createdAt": "2024-01-15T10:00:00.000Z",
    "updatedAt": "2024-01-15T10:10:00.000Z",
    "completedAt": "2024-01-15T10:10:00.000Z",
    "duration": "600s"
  }
  ```

  ```json Error - Task Not Found theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  {
    "error": "Task not found"
  }
  ```

  ```json Error - Unauthorized theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
  {
    "error": "Unauthorized"
  }
  ```
</ResponseExample>

## Use Cases

### Polling for Task Completion

Poll task status until completion with simple logic:

```javascript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
async function waitForTaskCompletion(taskId, apiKey) {
  const API_URL = `https://cloud.blackbox.ai/api/tasks/${taskId}/status`;
  
  while (true) {
    const response = await fetch(API_URL, {
      headers: {
        Authorization: `Bearer ${apiKey}`
      }
    });
    const status = await response.json();
    
    console.log(`Task ${taskId}: ${status.status} (${status.progress}%)`);
    
    if (status.isDone) {
      if (status.status === 'completed') {
        console.log(`Task completed in ${status.duration}`);
        return status;
      } else {
        throw new Error(`Task failed: ${status.error}`);
      }
    }
    
    // Wait 2 seconds before next poll
    await new Promise(resolve => setTimeout(resolve, 2000));
  }
}

// Usage
const API_KEY = "YOUR_API_KEY";
try {
  const result = await waitForTaskCompletion('9qQe2F8Z_nXx9-eJA0BD6', API_KEY);
  console.log('Task completed successfully!');
} catch (error) {
  console.error('Task failed:', error.message);
}
```

### Polling with Exponential Backoff

Implement exponential backoff to reduce server load:

```javascript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
async function pollTaskStatus(
  taskId,
  apiKey,
  maxAttempts = 100,
  initialDelay = 1000
) {
  const API_URL = `https://cloud.blackbox.ai/api/tasks/${taskId}/status`;
  let attempts = 0;
  let delay = initialDelay;
  
  while (attempts < maxAttempts) {
    try {
      const response = await fetch(API_URL, {
        headers: {
          Authorization: `Bearer ${apiKey}`
        }
      });
      const status = await response.json();
      
      console.log(`Attempt ${attempts + 1}: ${status.status} (${status.progress}%)`);
      
      if (status.isDone) {
        return status;
      }
      
      // Exponential backoff: double delay each time, max 30 seconds
      await new Promise(resolve => setTimeout(resolve, delay));
      delay = Math.min(delay * 2, 30000);
      attempts++;
      
    } catch (error) {
      console.error('Polling error:', error);
      await new Promise(resolve => setTimeout(resolve, delay));
      attempts++;
    }
  }
  
  throw new Error('Max polling attempts reached');
}
```

### Python Polling Example

```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import requests
import time

def wait_for_task_completion(task_id: str, api_key: str = None):
    """Poll task status until completion"""
    url = f'https://cloud.blackbox.ai/api/tasks/{task_id}/status'
    headers = {}
    if api_key:
        headers['Authorization'] = f'Bearer {api_key}'
    
    while True:
        response = requests.get(url, headers=headers)
        status = response.json()
        
        print(f"Task {task_id}: {status['status']} ({status['progress']}%)")
        
        if status['isDone']:
            if status['status'] == 'completed':
                print(f"Task completed in {status['duration']}")
                return status
            else:
                raise Exception(f"Task failed: {status['error']}")
        
        # Wait 2 seconds before next poll
        time.sleep(2)

# Usage
try:
    result = wait_for_task_completion('9qQe2F8Z_nXx9-eJA0BD6')
    print('Task completed successfully!')
except Exception as e:
    print(f'Task failed: {e}')
```

### Monitoring Multiple Tasks

Monitor multiple tasks simultaneously:

```javascript theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
async function monitorTasks(taskIds, apiKey) {
  const statuses = new Map();
  
  const checkTask = async (taskId) => {
    const response = await fetch(
      `https://cloud.blackbox.ai/api/tasks/${taskId}/status`,
      {
        headers: {
          Authorization: `Bearer ${apiKey}`
        }
      }
    );
    return response.json();
  };
  
  while (taskIds.length > 0) {
    const results = await Promise.all(
      taskIds.map(id => checkTask(id))
    );
    
    results.forEach((status, index) => {
      const taskId = taskIds[index];
      console.log(`${taskId}: ${status.status} (${status.progress}%)`);
      
      if (status.isDone) {
        statuses.set(taskId, status);
        taskIds.splice(index, 1);
      }
    });
    
    if (taskIds.length > 0) {
      await new Promise(resolve => setTimeout(resolve, 3000));
    }
  }
  
  return statuses;
}

// Usage
const API_KEY = "YOUR_API_KEY";
const taskIds = ['task1', 'task2', 'task3'];
const results = await monitorTasks(taskIds, API_KEY);
console.log('All tasks completed:', results);
```

## Polling Best Practices

1. **Use Exponential Backoff**: Start with short intervals (1-2 seconds) and increase gradually to reduce server load
2. **Set Maximum Attempts**: Prevent infinite loops by setting a maximum number of polling attempts
3. **Handle Network Errors**: Implement retry logic for failed requests
4. **Consider Webhooks**: For production applications, webhooks are more efficient than polling
5. **Check `isDone` Flag**: Use the `isDone` boolean for simple completion checks instead of checking multiple status values
6. **Respect Rate Limits**: Avoid polling too frequently; 2-5 second intervals are generally appropriate

## Status Values Reference

| Status       | Description                         | inProgress | isDone |
| ------------ | ----------------------------------- | ---------- | ------ |
| `pending`    | Task is queued and waiting to start | true       | false  |
| `processing` | Task is currently being executed    | true       | false  |
| `saving`     | Task is saving changes              | true       | false  |
| `completed`  | Task finished successfully          | false      | true   |
| `error`      | Task failed with an error           | false      | true   |
| `stopped`    | Task was manually stopped by user   | false      | true   |
| `timeout`    | Task exceeded maximum duration      | false      | true   |

## Error Codes

| Status Code | Error                 | Description                                             |
| ----------- | --------------------- | ------------------------------------------------------- |
| 200         | Success               | Task status retrieved successfully                      |
| 401         | Unauthorized          | Invalid or missing API key                              |
| 404         | Not Found             | Task not found or user does not have access to the task |
| 500         | Internal Server Error | Database error occurred while fetching task status      |
