---
title: "Turn a long generation into a job"
description: "End to end: move a six-panel comic-strip renderer out of one long action and into a job, with credits held while it waits, a place in line, a progress bar that survives a reload, labeled results and a cancel button."
canonical_url: "https://nuxt-backend.dev/docs/build/ai/jobs/long-generation"
---
# Turn a long generation into a job

> End to end: move a six-panel comic-strip renderer out of one long action and into a job, with credits held while it waits, a place in line, a progress bar that survives a reload, labeled results and a cancel button.

Version: nuxt-backend 0.6.x · Tab: Build · Kind: recipe · Status: experimental

Every page: [llms.txt](https://nuxt-backend.dev/llms.txt) · Skill for coding agents: [nuxt-backend](https://nuxt-backend.dev/.well-known/skills/nuxt-backend/SKILL.md)

Commands use npm; use your project's package manager.

- **You get:** a strip renderer that queues fairly, survives reloads and deploys, shows its place in line and its progress, labels what it made, and costs nothing when it fails.
- **Powered by:** an image model through the gateway, Convex file storage, and the job queue's Workflow and rate limiter components.
- **The package adds:** `defineJobQueue`, the credit hold, `useJob`, content credentials on every panel, and the AI-generated label.

This recipe moves Panels' strip renderer from one long action into a job. A signed-in member types an idea, and the app draws a six-panel comic strip, one image model call per panel. As one action, it ran for minutes: a closed tab lost the progress, a throttled model failed the whole strip, and a busy hour failed many at once. As a job, the strip waits its turn and shows its place in line. Then it draws panel by panel, with a progress bar that survives a reload, and it costs nothing if it fails.

## The files

<code-tree default-value="backend/strips.ts">

```ts [backend/schema.ts]
import { defineSchema, defineTable } from 'convex/server'
import { v } from 'convex/values'

export default defineSchema({
  strips: defineTable({
    workspaceId: v.string(),
    idea: v.string(),
    jobId: v.optional(v.string()),
  }),
  panels: defineTable({
    stripId: v.id('strips'),
    panel: v.number(),
    storageId: v.string(),
  }).index('by_strip_and_panel', ['stripId', 'panel']),
})
```

```ts [backend/jobs.ts]
import { defineJobQueue } from 'nuxt-backend/ai'
import { MINUTE } from 'nuxt-backend/rate-limit'
import { components } from './_generated/api'
import { ai } from './ai'

export const jobs = defineJobQueue(components, {
  ai,
  concurrency: 3,
  tiers: {
    priority: { feature: 'priority_queue', headStart: 4 * MINUTE },
    standard: {},
  },
  models: {
    'google/gemini-3.1-flash-image-preview': { perMinute: 6, min: 1, max: 30 },
  },
})

export const { getJob, cancelJob, getQueue, listJobs, setQueue, retryJob, discardJob, runQueue, billJob } = jobs.api
```

```ts [backend/strips.ts]
import { generateText } from 'ai'
import { backendError } from 'nuxt-backend/functions'
import { v } from 'convex/values'
import { internal } from './_generated/api'
import { internalMutation, internalQuery } from './_generated/server'
import { workspace } from './functions'
import { jobs } from './jobs'
import { storage } from './storage'

const PANELS = 6

export const create = workspace.mutation({
  args: { idea: v.string() },
  handler: async (ctx, { idea }) => {
    if (idea.length > 300) throw backendError('invalid_input', { field: 'idea', message: 'Up to 300 characters.' })
    const stripId = await ctx.db.insert('strips', { workspaceId: ctx.workspace.id, idea })
    const { jobId } = await jobs.enqueue(ctx, internal.strips.render, { stripId, idea })
    await ctx.db.patch('strips', stripId, { jobId })
    return stripId
  },
})

export const render = jobs.define({
  meter: 'credits',
  cost: PANELS * 5,
  args: { stripId: v.id('strips'), idea: v.string() },
  handler: async (job, { stripId, idea }) => {
    for (let panel = 1; panel <= PANELS; panel++) {
      await job.run(internal.strips.drawPanel, { stripId, idea, panel })
      await job.progress({ done: panel, total: PANELS, label: `Panel ${panel}` })
    }
  },
})

export const drawPanel = jobs.step({
  model: 'google/gemini-3.1-flash-image-preview',
  args: { stripId: v.id('strips'), idea: v.string(), panel: v.number() },
  handler: async (ctx, { stripId, idea, panel }) => {
    const previous = await ctx.runQuery(internal.strips.panelCount, { stripId })
    const { files } = await generateText({
      model: ctx.model(),
      prompt: [
        `Panel ${panel} of ${PANELS} of a comic strip about: ${idea}.`,
        `Panels drawn so far: ${previous}. Keep the characters consistent.`,
        'Flat colors, bold ink outlines, no text in the image.',
      ].join('\n'),
    })
    const image = files.find(file => file.mediaType.startsWith('image/'))
    if (!image) throw backendError('unavailable', { reason: 'provider_refused' })
    const storageId = await ctx.storeImage(image, { inputs: [stripId] })
    await ctx.runMutation(internal.strips.savePanel, { stripId, panel, storageId })
  },
})

export const panelCount = internalQuery({
  args: { stripId: v.id('strips') },
  handler: async (ctx, { stripId }) => {
    const rows = await ctx.db.query('panels')
      .withIndex('by_strip_and_panel', q => q.eq('stripId', stripId))
      .take(PANELS)
    return rows.length
  },
})

// A retried step draws its panel again: replace it, never add a second.
export const savePanel = internalMutation({
  args: { stripId: v.id('strips'), panel: v.number(), storageId: v.string() },
  handler: async (ctx, { stripId, panel, storageId }) => {
    const row = await ctx.db.query('panels')
      .withIndex('by_strip_and_panel', q => q.eq('stripId', stripId).eq('panel', panel))
      .unique()
    if (row) {
      await storage.release(ctx, row.storageId)
      await ctx.db.patch('panels', row._id, { storageId })
    }
    else {
      await ctx.db.insert('panels', { stripId, panel, storageId })
    }
  },
})

export const get = workspace.query({
  args: { id: v.id('strips') },
  handler: async (ctx, { id }) => {
    const strip = await ctx.db.get('strips', id)
    if (!strip || strip.workspaceId !== ctx.workspace.id) return null
    const rows = await ctx.db.query('panels')
      .withIndex('by_strip_and_panel', q => q.eq('stripId', id))
      .take(PANELS)
    const panels = await Promise.all(rows.map(async row => ({ ...row, url: await storage.fileUrl(ctx, row.storageId) })))
    return { ...strip, panels }
  },
})
```

```vue [app/pages/strips/new.vue]
<script setup lang="ts">
import { api } from '#backend/api'

definePageMeta({ auth: true })

const idea = ref('')
const credits = useCredits({ meter: 'credits' })
const create = useMutation(api.strips.create)
const error = ref<string>()

async function start() {
  error.value = undefined
  try {
    const stripId = await create({ idea: idea.value })
    await navigateTo(`/strips/${stripId}`)
  }
  catch (caught) {
    error.value = getBackendError(caught)?.message
  }
}
</script>

<template>
  <p>{{ credits.balance.value ?? '…' }} credits. A strip costs 30.</p>
  <textarea v-model="idea" maxlength="300" placeholder="A fox who wants to fly" />
  <button @click="start">
    Draw the strip
  </button>
  <p v-if="error" role="alert">
    {{ error }}
  </p>
</template>
```

```vue [app/pages/strips/[id].vue]
<script setup lang="ts">
import { api } from '#backend/api'

definePageMeta({ auth: true })

const route = useRoute()
const strip = useQuery(api.strips.get, () => ({ id: route.params.id as string }))
const job = useJob(() => strip.value?.jobId)
const minutes = computed(() => Math.max(1, Math.round((job.estimatedWait.value ?? 0) / 60_000)))
</script>

<template>
  <h1>{{ strip?.idea }}</h1>
  <p v-if="job.status.value === 'queued'" aria-live="polite">
    Number {{ job.position.value ?? '100+' }} in line, about {{ minutes }} min
  </p>
  <p v-else-if="job.status.value === 'running'" aria-live="polite">
    Drawing {{ job.progress.value?.label ?? 'the first panel' }}
    <progress :value="job.progress.value?.done ?? 0" :max="job.progress.value?.total ?? 6" />
  </p>
  <p v-else-if="job.status.value === 'failed'" role="alert">
    {{ job.error.value?.message }} Your credits are back.
  </p>
  <button v-if="job.status.value === 'queued' || job.status.value === 'running'" @click="job.cancel()">
    Cancel
  </button>
  <figure v-for="panel in strip?.panels" :key="panel._id">
    <img :src="panel.url ?? undefined" :alt="`Panel ${panel.panel} of ${strip?.idea}`">
    <AiLabel />
  </figure>
</template>
```

</code-tree>

## How it fits together

### The mutation puts the strip in line

`create` saves the strip, then `jobs.enqueue` puts its job in line and holds 30 credits. Both happen in one transaction: a refusal such as `insufficient_credits` rolls the strip back too, so no strip ever waits without its credits. The page reads the refusal's message and shows it under the button. See [Start a job](https://nuxt-backend.dev/docs/build/ai/jobs#start-a-job).

### The job draws one panel per step

`render` is the job: six calls to `job.run`, each one panel. Each step is saved as it finishes, so a deploy in the middle of a strip picks it up at the next panel. `drawPanel` asks the image model for the next panel, stores it with its content credentials through `ctx.storeImage`, and saves it. A throttled call waits and runs again, so `savePanel` replaces a panel, and deletes the file it replaces, rather than adding a second one. See [Keep models under their limits](https://nuxt-backend.dev/docs/build/ai/jobs/model-limits).

### The page follows the job

`useJob` reads the job live: its place in line while it waits, then the label and count each `job.progress` reported. The panels come from your own `panels` table through `get`, so they appear one by one as they are saved. A reload, or the same page on another device, shows the same state. See [Follow it in the page](https://nuxt-backend.dev/docs/build/ai/jobs#follow-it-in-the-page).

### Every panel says what made it

Each stored panel carries a C2PA content-credentials manifest and the IPTC source type for AI-generated media, and `<AiLabel>` puts the visible label under it. See [Label AI-generated content](https://nuxt-backend.dev/docs/build/ai/provenance).

### The credits follow the outcome

The 30 credits leave the balance when the strip joins the line. They are charged when it starts, and refunded if it fails. Canceled before it starts, the hold is released. Canceled while it runs, the strip keeps the panels it has and stays charged. What the job cost you in model calls reaches Polar's Cost Insights when it ends. See [Charge for a queued job](https://nuxt-backend.dev/docs/build/ai/jobs/credits).

### Pro strips start sooner

`priority` gives a job a four-minute head start when the workspace's plan has the `priority_queue` feature. Add the feature to the plans that include it in `backend/billing.catalog.ts`, and run `npx nuxt-backend billing sync`. A tier can also run more strips at once per workspace, keep slots for paid plans, and cap what a free workspace draws per day: see [Give plans priority in the queue](https://nuxt-backend.dev/docs/build/ai/jobs/priority).

## Try it locally

1. With `npx nuxt-backend dev` running and a model route set up ([Develop and test](https://nuxt-backend.dev/docs/build/ai/models#develop-and-test)), sign in and buy a credit pack with the sandbox's test card.
2. Open `/strips/new`, type an idea and submit. The balance drops by 30, and the strip page shows the job running, panel by panel.
3. Start three more strips from three other accounts. With `concurrency: 3`, the fourth waits and shows its place in line.
4. Cancel a strip while it runs. It stops after the panel it is drawing, keeps its panels, and stays charged. Cancel one that still waits, and its 30 credits come back at once.
5. As an administrator, open `/admin?tab=queue` and pause the queue. A new strip waits until you resume it.

## Before launch

- [ ] `npx nuxt-backend billing sync --env production` pushed the `credits` meter, the packs and the `priority_queue` feature.
- [ ] A model route is ready on production, and the gateway has a spending cap: see [Cap what the gateway spends](https://nuxt-backend.dev/docs/build/ai/models#cap-what-the-gateway-spends).
- [ ] `models` lists each model your steps call, with a starting rate under your provider's limit.
- [ ] The price covers what a strip costs you: compare it with Polar's Costs dashboard after a few test strips.
- [ ] Generated panels are labeled where people see them, as the EU AI Act asks ([Disclose AI-generated content](https://nuxt-backend.dev/docs/ship/compliance/ai-transparency)).
- [ ] You know where the Queue tab is, its dead letters, and the `pause_ai` switch.

[Production checklist](https://nuxt-backend.dev/docs/ship/checklist) has the rest of the list.

## Related

- [Run generation jobs](https://nuxt-backend.dev/docs/build/ai/jobs): every option of the queue and of a job.
- [Meter an AI action](https://nuxt-backend.dev/docs/build/ai/metered-actions#a-complete-feature): the same feature for a generation that fits in one streamed call.
- [Operate the queue](https://nuxt-backend.dev/docs/build/ai/jobs/operate): pause, concurrency, model limits and dead letters in production.
- [Label AI-generated content](https://nuxt-backend.dev/docs/build/ai/provenance): the credentials and the label on every panel.
- [Your data](https://nuxt-backend.dev/docs/build/data/your-data): the schema the strips and panels live in.


## Sitemap

See the full [sitemap](https://nuxt-backend.dev/sitemap.md) for all pages.
