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

# Task lifecycle

> Statuses every Viggle API job moves through, how often to poll, watching renders live, cancelling renders, failures and refunds.

Every generation in the Viggle API is a job. The `POST` returns an ID right away, usually with `status: "queued"` (a scene task may already be `processing`); the work happens in the background. You read the job back until it reaches a terminal status, then download the result.

## Statuses

| Status | Meaning | Terminal |
| - | - | - |
| `queued` | Accepted and waiting for capacity | No |
| `processing` | Generating | No |
| `ready` | Finished. The output URLs are set | Yes |
| `failed` | Stopped with an `error` object. Credits are refunded | Yes |
| `cancelled` | Stopped before finishing. Credits are refunded | Yes |

```mermaid theme={null}
stateDiagram-v2
  [*] --> queued
  queued --> processing
  processing --> ready
  queued --> failed
  processing --> failed
  queued --> cancelled
  processing --> cancelled
```

Which jobs can reach `cancelled`:

* Video Remix renders, when you cancel them with `DELETE /v1/renders/{render_id}`.
* Viggle H3, Viggle Remake, upscale and scene jobs, only if Viggle stops them. You can't cancel these yourself.
* Images, characters and motions never show `cancelled`.

Characters and motions can also report `pending`: created, not yet queued. Treat it like `queued`.

Treat any status you don't recognise as still in progress, and stop only on `ready`, `failed` or `cancelled`.

## Poll for the result

Read the job every 3–5 seconds while it is `queued` or `processing`.

| Job | Read it with | Progress fields |
| - | - | - |
| Viggle H3, Viggle Remake | `GET /v1/videos/{video_id}` | `queue_position` and `estimated_wait_seconds`. `progress` stays null until `ready`, then reads 100 |
| Upscale | `GET /v1/videos/{video_id}` | None. `progress` stays null until `ready`, then reads 100 |
| Video Remix | `GET /v1/videos/{video_id}` | `progress` (0 until reported) and `stage` (`analyzing`, `rendering`, `finishing`) |
| Viggle Image | `GET /v1/images/{image_id}` | `progress` (share of images done) |
| Scene task | `GET /v1/scenes/{task_id}` | `queuePosition` while queued |
| Character, motion | `GET /v1/characters/{id}`, `GET /v1/motions/{id}` | `vsplat.status` and `glb.status` for the 3D part |

```bash cURL theme={null}
#!/usr/bin/env bash
# Usage: ./wait.sh https://apis.viggle.ai/v1/videos/vid_7d3f0b8e-2c41-4f6a-9b1e-5a2c8d4e6f10
set -euo pipefail

while true; do
  job=$(curl -sS "$1" -H "Authorization: Bearer $VIGGLE_API_KEY")
  status=$(echo "$job" | jq -r '.status // "error"')
  case "$status" in
    ready) echo "$job"; exit 0 ;;
    failed|cancelled|error) echo "$job" >&2; exit 1 ;;
  esac
  sleep 4
done
```

```javascript Node.js theme={null}
const headers = { Authorization: `Bearer ${process.env.VIGGLE_API_KEY}` };

export async function waitFor(url, { intervalMs = 4000, timeoutMs = 3 * 60 * 60_000 } = {}) {
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    const response = await fetch(url, { headers });
    const job = await response.json();
    if (!response.ok) throw new Error(`HTTP ${response.status}: ${JSON.stringify(job.error)}`);
    if (job.status === "ready") return job;
    if (job.status === "failed" || job.status === "cancelled") {
      throw new Error(`${job.status}: ${job.error?.code} ${job.error?.message}`);
    }
    await new Promise((resolve) => setTimeout(resolve, intervalMs));
  }
  throw new Error(`Timed out waiting for ${url}`);
}

const video = await waitFor("https://apis.viggle.ai/v1/videos/vid_7d3f0b8e-2c41-4f6a-9b1e-5a2c8d4e6f10");
console.log(video.video_url);
```

```python Python theme={null}
import os
import time

import requests

HEADERS = {"Authorization": f"Bearer {os.environ['VIGGLE_API_KEY']}"}


def wait_for(url, interval=4, timeout=3 * 60 * 60):
    deadline = time.time() + timeout
    while time.time() < deadline:
        response = requests.get(url, headers=HEADERS)
        job = response.json()
        if not response.ok:
            raise RuntimeError(f"HTTP {response.status_code}: {job.get('error')}")
        if job["status"] == "ready":
            return job
        if job["status"] in ("failed", "cancelled"):
            error = job.get("error") or {}
            raise RuntimeError(f"{job['status']}: {error.get('code')} {error.get('message')}")
        time.sleep(interval)
    raise TimeoutError(f"Timed out waiting for {url}")


video = wait_for("https://apis.viggle.ai/v1/videos/vid_7d3f0b8e-2c41-4f6a-9b1e-5a2c8d4e6f10")
print(video["video_url"])
```

Download as soon as a job is `ready`. Every result is deleted 24 hours after the job finishes; the job record stays readable, with null URLs. See [Limits and retention](https://docs.viggle.ai/v1/concepts/limits-and-retention.md).

## Watch a render live

Video Remix renders also stream their lifecycle over Server-Sent Events at `GET /v1/renders/{render_id}/events`. Every other job is poll-only.

```bash theme={null}
curl -N https://apis.viggle.ai/v1/renders/render_job_3f9a2c71b5e04d18/events \
  -H "Authorization: Bearer $VIGGLE_API_KEY"
```

* The first event is `snapshot`, with the render's current state.
* A status change arrives as an event named after the new status (`processing`, `ready`, `failed`, `cancelled`). Other changes arrive as `progress`.
* A `heartbeat` event arrives every 12 seconds.
* The stream closes after a terminal status.

The stream keeps no history. If the connection drops, reconnect and treat the new `snapshot` as the current state; `Last-Event-ID` is not used. You can always fall back to `GET /v1/videos/{render_id}`. See [Watch a render](https://docs.viggle.ai/v1/api-reference/renders/watch-a-render.md).

## Cancel a render

`DELETE /v1/renders/{render_id}` cancels a render that is still `queued` or `processing` and releases its credit reservation. It answers `200` with the render object. A render that has already finished is returned unchanged. This is the only cancel operation in the API.

```bash theme={null}
curl -X DELETE https://apis.viggle.ai/v1/renders/render_job_3f9a2c71b5e04d18 \
  -H "Authorization: Bearer $VIGGLE_API_KEY"
```

See [Cancel a render](https://docs.viggle.ai/v1/api-reference/renders/cancel-a-render.md).

## When a job fails

A `200` from a status endpoint can describe a failed job. Its `error` field uses the same shape as HTTP errors:

```json theme={null}
{
  "id": "vid_7d3f0b8e-2c41-4f6a-9b1e-5a2c8d4e6f10",
  "status": "failed",
  "error": {
    "code": "TASK_FAILED",
    "message": "The h3 video task failed.",
    "retryable": true,
    "request_id": "4f1c2a9e7b3d4e5f8a6b0c1d2e3f4a5b",
    "details": {},
    "remediation": { "action": "retry", "retry_after_ms": null }
  }
}
```

* `code` tells you what happened. Program against it, not against `message`.
* `retryable` is `true` for temporary failures: `PROCESSING_FAILED`, `INTERNAL_ERROR`, `SERVICE_BUSY`, `ALL_WORKERS_BUSY`, `WORKER_STOPPED` and `TASK_FAILED`. Submit the same request again.
* `remediation.action` is `retry` when the job is retryable and `none` otherwise. For `none`, change the input first: for example, `CONTENT_POLICY_VIOLATION` fails again with the same prompt or media, and `INSUFFICIENT_CREDITS` needs more credits.

For a 3D character or motion, the failure is on the 3D part: read `vsplat.error` or `glb.error`. The top-level `error` stays `null`. [Errors](https://docs.viggle.ai/v1/production/errors.md) lists every code.

## Refunds

You never pay for a job that doesn't finish. A `failed` or `cancelled` job has its whole reservation released automatically; there is nothing to claim. A retry is a new job with its own reservation, so a failed attempt is never charged twice. See [Pricing](https://docs.viggle.ai/v1/pricing.md#reservation-and-settlement).

## Retry a submit safely

If a `POST` times out before you get an ID, you can't tell whether the job was created.

* Video Remix: send an `Idempotency-Key` header (1–255 characters) on `POST /v1/renders`. Repeating the request with the same key and body within 24 hours returns the original render instead of a new one. The same key with a different body answers `409 IDEMPOTENCY_KEY_REUSED`. Keys are scoped to your API key, and the JSON form of the endpoint requires one.
* Characters and motions: for `type=vsplat` characters, `type=glb` motions and motions from text, a `task_id` you choose must be unique. Reusing one answers `409 ID_ALREADY_EXISTS`, so you know the first attempt went through. It does not return the original asset. `render` and `all` assets ignore `task_id`, so a retry creates a new asset.
* Everything else has no idempotency key. Before resubmitting, check `GET /v1/videos` or your logs (with `X-Request-Id`) for the job.

## Next steps

> [card] [Errors](https://docs.viggle.ai/v1/production/errors.md)
>
> Every code and what to do about it.

> [card] [Limits and retention](https://docs.viggle.ai/v1/concepts/limits-and-retention.md)
>
> How long results, URLs and job records last.

> [card] [How V1 works](https://docs.viggle.ai/v1/concepts/how-v1-works.md)
>
> Which endpoint reads back which ID.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.