---
title: "Part 4: generate strips"
description: "Define the generation queue, hold credits while a strip draws and charge or refund them, run it from a page, and label the result as AI-generated."
canonical_url: "https://nuxt-backend.dev/docs/start/tutorial/generate"
---
# Part 4: generate strips

> Define the generation queue, hold credits while a strip draws and charge or refund them, run it from a page, and label the result as AI-generated.

Version: nuxt-backend 0.6.x · Tab: Start · Kind: tutorial · Status: stable

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.

Turn an idea and a photo into three panels. A strip takes several model calls and about a minute, so it runs as a job in a queue, paid with credits.

<table>
<thead>
  <tr>
    <th>
      Part
    </th>
    
    <th>
      You add
    </th>
    
    <th>
      Accounts
    </th>
    
    <th>
      Time
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      4. Generate strips
    </td>
    
    <td>
      A generation queue with a head start for Studio, a job that writes and draws a strip, its page, and the AI-generated label
    </td>
    
    <td>
      The AI gateway from Part 3
    </td>
    
    <td>
      25 min
    </td>
  </tr>
</tbody>
</table>

## Before you start

You need the app from [Part 3](https://nuxt-backend.dev/docs/start/tutorial/uploads), with a route to the models and credits in the workspace. The AI gateway bills each call at its real cost. A spending limit on it caps the total ([AI gateway](https://nuxt-backend.dev/docs/services/ai-gateway)).

A strip is too long for one request: a model writes three captions, then an image model draws each panel. A job queue runs it for you. The job waits its turn in a fair line, and Studio's strips get a head start. The queue keeps each model under its rate limit, so a busy hour slows strips down instead of failing them. The job's 30 credits are held while it waits, charged when it starts, and refunded if it fails.

<steps level="3">

### Define the generation queue

`defineJobQueue` declares the queue once. Each job runs on Convex's Workflow component, so a deploy or a restart picks it up after its last finished step:

```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,
  perOwner: 1,
  tiers: {
    priority: { feature: 'priority_queue', headStart: 10 * MINUTE },
    standard: {},
  },
  models: {
    'google/gemini-2.5-flash-image': { perMinute: 10 },
  },
})

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

- `perOwner: 1` lets each workspace draw one strip at a time, so one person cannot fill the line.
- `tiers` gives a workspace whose plan has `priority_queue`, the Studio plan from Part 2, a ten-minute head start.
- `models` sets where the image model's limit starts. The queue halves it on a `429` and grows it back on success.
- The exports are the functions behind `useJob()` and the admin console's Queue tab.

Turn on content credentials in `backend/ai.ts`. Under the EU AI Act, generated images must be marked as such from 2 August 2026, and apps already on the market have until 2 December 2026. With `provenance`, each image a job step stores carries a signed C2PA manifest and the IPTC "trained algorithmic media" source type. [Disclose AI-generated content](https://nuxt-backend.dev/docs/ship/compliance/ai-transparency) covers what the law asks, and is not legal advice:

```ts [backend/ai.ts]
export const ai = setupAi(components, {
  billing,
  rateLimiter,
  moderation: { model: 'meta-llama/llama-guard-4-12b' },
  provenance: { name: 'Panels' },
  spendLimit: { usdPerDay: 5 },
})
```

### Write the job

A job is a handler that orders steps, and steps that call the models. Add them to `backend/strips.ts`, with these imports:

```ts [backend/strips.ts]
import { generateText, type LanguageModel } from 'ai'
// …
import { jobs } from './jobs'
// …
const PANELS = 3

const DRAW_COST = 30
// …
export const draw = jobs.define({
  meter: 'credits',
  cost: DRAW_COST,
  args: { stripId: v.id('strips') },
  handler: async (job, { stripId }) => {
    const captions = await job.run(internal.strips.writeCaptions, { stripId })
    for (const [index, caption] of captions.entries()) {
      const last = index === captions.length - 1
      await job.run(internal.strips.drawPanel, { stripId, caption, index, last })
      await job.progress({ done: index + 1, total: captions.length, label: caption })
    }
  },
})

export async function captionsFor(model: LanguageModel, idea: string): Promise<string[]> {
  const { text } = await generateText({
    model,
    prompt: `Write ${PANELS} short captions, one per line, for a comic strip about: ${idea}`,
  })
  const captions = text.split('\n').map(line => line.trim()).filter(Boolean).slice(0, PANELS)
  if (captions.length === 0) throw new Error('The model wrote no captions')
  return captions
}

export async function panelFor(model: LanguageModel, caption: string, photo: string | null) {
  const { files } = await generateText({
    model,
    messages: [{
      role: 'user',
      content: [
        { type: 'text', text: `Draw one comic panel in ink and flat colour: ${caption}` },
        ...(photo ? [{ type: 'file' as const, mediaType: 'image', data: new URL(photo) }] : []),
      ],
    }],
  })
  const image = files.find(file => file.mediaType.startsWith('image/'))
  if (!image) throw new Error('The model returned no image')
  return image
}

export const writeCaptions = jobs.step({
  model: 'openai/gpt-5-mini',
  args: { stripId: v.id('strips') },
  handler: async (ctx, { stripId }) => {
    const strip: Doc<'strips'> = await ctx.runQuery(internal.strips.read, { id: stripId })
    return captionsFor(ctx.model(), strip.idea)
  },
})

export const drawPanel = jobs.step({
  model: 'google/gemini-2.5-flash-image',
  args: { stripId: v.id('strips'), caption: v.string(), index: v.number(), last: v.boolean() },
  handler: async (ctx, { stripId, caption, index, last }) => {
    const strip: Doc<'strips'> = await ctx.runQuery(internal.strips.read, { id: stripId })
    const photo = strip.photoId ? await storage.fileUrl(ctx, strip.photoId) : null
    const image = await panelFor(ctx.model(), caption, photo)
    const imageId = await ctx.storeImage(image, { inputs: [stripId] })
    await ctx.runMutation(internal.strips.savePanel, { stripId, jobId: ctx.job.id, imageId, caption, index, last })
  },
})

export const read = internalQuery({
  args: { id: v.id('strips') },
  handler: async (ctx, { id }) => {
    const strip = await ctx.db.get('strips', id)
    if (!strip) throw new Error('The strip is gone')
    return strip
  },
})
// …
export const savePanel = internalMutation({
  args: { stripId: v.id('strips'), jobId: v.string(), imageId: v.string(), caption: v.string(), index: v.number(), last: v.boolean() },
  handler: async (ctx, { stripId, jobId, imageId, caption, index, last }) => {
    const strip = await ctx.db.get('strips', stripId)
    if (strip?.jobId !== jobId || strip.status !== 'queued' || index < strip.panels.length) {
      await storage.release(ctx, imageId)
      return
    }
    if (index > strip.panels.length) throw new Error(`Panel ${index} came before panel ${strip.panels.length}`)
    await ctx.db.patch('strips', stripId, { panels: [...strip.panels, { imageId, caption }], status: last ? 'ready' : 'queued' })
    // …
  },
})
```

- `jobs.define` holds `cost` credits from the `credits` meter, `DRAW_COST`, which the page shows too. Whatever the handler throws ends the job as failed, and the hold is refunded: a model that writes no caption leaves nothing to draw, so `captionsFor` throws. The handler only orders the steps: reads and model calls happen inside them, so a replay after a restart makes the same calls in the same order.
- `jobs.step` takes a turn from its model's limit before it runs, and `ctx.model()` returns that model through your AI gateway. When the model answers `429` or times out, `job.run` waits and runs the step again.
- `captionsFor` and `panelFor` are plain functions, so the demo's own job in Part 6 asks the models the same way.
- The photo is in the package's storage, and `storage.fileUrl` is the app's own read of it: it reads any file, so call it only where your code has already decided who may see the strip.
- `ctx.storeImage(image, { inputs })` saves the generated file with its content credentials in the package's storage, as the workspace's file, the job's owner. It counts against the workspace's quota, and an export or an erasure finds it. It records the strip it came from on the job's provenance ([Label AI-generated content](https://nuxt-backend.dev/docs/build/ai/provenance#label-a-result)).
- `savePanel` puts each panel in its place, by `index`. A step can run twice, after a restart or a retry of its own, so a panel already in its place keeps it and the second image goes back with `storage.release`: one panel, and one announcement. An image also goes back when the strip was deleted while it drew, or let go of this job (`retry`, below).
- The last panel makes the strip ready, however many captions the model wrote. [Part 5](https://nuxt-backend.dev/docs/start/tutorial/notify-and-share) fills the gap with the announcement.

Now `get` can return the panels with their images' URLs, and what drawing the strip costs, for its button. Replace the `return strip` you wrote in Part 1, and add the helpers below it:

```ts [backend/strips.ts]
if (strip?.workspaceId !== ctx.workspace.id || strip.hidden) return null
    return { ...strip, panels: await withUrls(ctx, strip.panels), cost: await costOf(ctx, strip) }
  },
})

async function costOf(ctx: QueryCtx, strip: Doc<'strips'>): Promise<number | null> {
  if (!isDemo() || strip.ideaId === undefined) return DRAW_COST
  return (await cannedPanels(ctx, strip.ideaId)) ? 0 : null
}
// …
async function withUrls(ctx: QueryCtx, panels: Doc<'strips'>['panels']) {
  return await Promise.all(panels.map(async panel => ({ ...panel, url: await storage.fileUrl(ctx, panel.imageId) })))
}
```

`costOf` is `DRAW_COST` for every strip but a canned idea on the demo, which [Part 6](https://nuxt-backend.dev/docs/start/tutorial/deploy) copies for free once its panels are drawn: `0` then, and `null`, no button, before.

### Start the job from a mutation

`jobs.enqueue` puts the job in line from a mutation of yours. Before it does, it checks what every metered call checks: a signed-in member, the `pause_ai` switch off, room in the `ai` rate limit and enough credits. A refusal rolls the whole mutation back:

```ts [backend/strips.ts]
export const generate = workspace.mutation({
  args: { id: v.id('strips') },
  handler: async (ctx, { id }) => {
    const strip = ownStrip(await ctx.db.get('strips', id), ctx.workspace.id)
    if (strip.status !== 'draft') throw backendError('invalid_input', { field: 'id', reason: 'already_generated' })
    if (isDemo() && strip.ideaId !== undefined) {
      const canned = await cannedPanels(ctx, strip.ideaId)
      if (!canned) throw backendError('not_ready', { reason: 'idea_not_drawn' })
      await ctx.db.patch('strips', id, { panels: canned, cached: true, status: 'ready' })
      // …
      return
    }
    const { jobId } = await jobs.enqueue(ctx, internal.strips.draw, { stripId: id })
    await ctx.db.patch('strips', id, { jobId, status: 'queued' })
  },
})
```

On the public demo, a strip started from a canned idea copies the panels the demo drew once: no job, no model call and no credits, and no photo either, since the panels are the copy's. Until [Part 6](https://nuxt-backend.dev/docs/start/tutorial/deploy) draws them, the idea is refused with `not_ready` and the reason `idea_not_drawn`, so a canned idea never starts a paid job on the demo. Everywhere else, a canned idea goes through the queue like any other.

A job that fails or is canceled leaves its strip `queued`, so give the strip a way back to a draft. The package already refunded a failed job's credits, and gave a canceled job's hold back; `retry` reads how the job ended through `getJob`, and drops what it drew before it stopped:

```ts [backend/strips.ts]
export const retry = workspace.mutation({
  args: { id: v.id('strips') },
  handler: async (ctx, { id }) => {
    const strip = ownStrip(await ctx.db.get('strips', id), ctx.workspace.id)
    if (strip.status !== 'queued' || !strip.jobId) throw backendError('invalid_input', { field: 'id', reason: 'not_stopped' })
    const job = await ctx.runQuery(api.jobs.getJob, { jobId: strip.jobId })
    if (job && job.status !== 'failed' && job.status !== 'canceled') throw backendError('invalid_input', { field: 'id', reason: 'not_stopped' })
    for (const panel of strip.panels) await storage.release(ctx, panel.imageId)
    await ctx.db.patch('strips', id, { status: 'draft', panels: [], jobId: undefined })
  },
})
```

A job `getJob` no longer finds stopped long ago: the queue deletes a finished job after 30 days. While the job still waits or runs, or once it is done, there is nothing to retry: `invalid_input`, reason `not_stopped`. A panel the stopped job saves late finds the strip let go of it, and goes back to storage.

### Run it from the page

`useJob` reads one job, live: its place in line, its progress, its result or why it failed. Put the drawing in a component of its own:

```vue [app/components/StripDrawing.vue]
<script setup lang="ts">
import { api } from '#backend/api'
import type { Doc } from '#backend/dataModel'

type Panel = Doc<'strips'>['panels'][number] & { url: string | null }
const props = defineProps<{ strip: Omit<Doc<'strips'>, 'panels'> & { panels: Panel[], cost: number | null } }>()
const generate = useMutation(api.strips.generate)
const retry = useMutation(api.strips.retry)
const job = useJob(() => props.strip.jobId)
const pricing = useBackendPagePath('pricing')
const { errorMessage } = useLabels('errors')
const refusal = ref<string | null>(null)
const stopped = computed(() => job.status.value === 'failed' || job.status.value === 'canceled')

async function start() {
  refusal.value = null
  try {
    await generate({ id: props.strip._id })
  }
  catch (error) {
    const failure = getBackendError(error)
    if (failure?.code === 'insufficient_credits' && pricing.value) await navigateTo(pricing.value)
    else refusal.value = errorMessage(error)
  }
}

async function again() {
  refusal.value = null
  try {
    await retry({ id: props.strip._id })
  }
  catch (error) {
    refusal.value = errorMessage(error)
  }
}
</script>

<template>
  <section aria-labelledby="drawing-heading">
    <h2 id="drawing-heading">
      Panels
    </h2>

    <template v-if="strip.status === 'draft'">
      <button
        v-if="strip.cost === 0"
        type="button"
        class="primary"
        @click="start"
      >
        Copy this strip for free
      </button>
      <button
        v-else-if="strip.cost !== null"
        type="button"
        class="primary"
        @click="start"
      >
        Draw this strip for {{ strip.cost }} credits
      </button>
      <p v-else>
        This idea is not drawn on the demo yet. Start from another one.
      </p>
      <Gate feature="priority_queue">
        <p>Studio: your strip starts first.</p>
        <template #fallback>
          <p v-if="pricing">
            Busy? <NuxtLink :to="pricing">Studio</NuxtLink> strips start first.
          </p>
        </template>
      </Gate>
      <p
        v-if="refusal"
        role="alert"
      >
        {{ refusal }}
      </p>
    </template>

    <p v-else-if="job.status.value === 'queued'">
      Number {{ job.position.value ?? '100+' }} in line
    </p>
    <template v-else-if="job.status.value === 'running'">
      <progress
        :value="job.progress.value?.done"
        :max="job.progress.value?.total"
      />
      <p>{{ job.progress.value?.label }}</p>
      <button
        type="button"
        @click="job.cancel()"
      >
        Cancel
      </button>
    </template>
    <template v-else-if="strip.status === 'queued' && stopped">
      <p
        v-if="job.status.value === 'failed'"
        role="alert"
      >
        {{ job.error.value?.message }} Your credits were refunded.
      </p>
      <p v-else>
        You canceled this strip. Credits held while it waited went back; a strip canceled while drawing keeps its charge.
      </p>
      <button
        type="button"
        @click="again"
      >
        Try again
      </button>
      <p
        v-if="refusal"
        role="alert"
      >
        {{ refusal }}
      </p>
    </template>

    <figure
      v-for="panel in strip.panels"
      :key="panel.imageId"
    >
      <img
        v-if="panel.url"
        :src="panel.url"
        :alt="panel.caption"
        width="480"
      >
      <figcaption>{{ panel.caption }}</figcaption>
    </figure>
    <AiLabel v-if="strip.panels.length" />
  </section>
</template>
```

The button says what drawing costs, from `get`: `DRAW_COST` credits, or nothing for the demo's copy of a canned idea. A failed or canceled job shows why, and **Try again** calls `retry`, which makes the strip a draft to draw once more. `useLabels('errors')` words a refusal, Panels' own reasons included ([Part 6](https://nuxt-backend.dev/docs/start/tutorial/deploy) adds their labels). Each panel shows the URL `get` read for it. Add the component to the strip's page, under the photo:

```vue [app/pages/strips/[id].vue]
<StripPhoto
      :strip-id="strip._id"
      :photo-id="strip.photoId"
    />
    <!-- … -->
    <StripDrawing :strip="strip" />
    <!-- … -->
    <ReportStrip :strip-id="strip._id" />
```

**You should see** "Number 1 in line" for a moment, then a progress bar with each caption, then three panels with the "AI-generated" label under them. The header's balance drops by 30 when the job starts.

</steps>

## Check your work

- Start a strip with fewer than 30 credits. The page sends you to `/pricing`, and no strip is queued.
- Cancel a strip while it is still in line. The hold is released, and the balance does not change. A strip that already started stays charged. Either way, **Try again** makes it a draft again.
- Open the admin console's Queue tab. It shows the line, the running job, and a dead-letter view to retry or discard failed jobs.

## What you used

- `defineJobQueue` with `perOwner`, `tiers` and `models`, `jobs.define`, `jobs.step` and `jobs.enqueue` ([Run generation jobs](https://nuxt-backend.dev/docs/build/ai/jobs)).
- Credits held, charged and refunded ([Charge for a queued job](https://nuxt-backend.dev/docs/build/ai/jobs/credits)), and the Studio head start ([Give plans priority in the queue](https://nuxt-backend.dev/docs/build/ai/jobs/priority)).
- `useJob` ([Run generation jobs](https://nuxt-backend.dev/docs/build/ai/jobs)).
- `storage.fileUrl` and `ctx.storeImage` ([Show images](https://nuxt-backend.dev/docs/build/data/files/images), [Label AI-generated content](https://nuxt-backend.dev/docs/build/ai/provenance#label-a-result)).
- `<Gate feature>` ([Show parts of a page to the right people](https://nuxt-backend.dev/docs/build/ui/gate)).
- `setupAi({ provenance })` and `<AiLabel>` ([Label AI-generated content](https://nuxt-backend.dev/docs/build/ai/provenance)).

## Next

[Part 5: notify and share](https://nuxt-backend.dev/docs/start/tutorial/notify-and-share) tells people when their strip is ready, and lets them share it.


## Sitemap

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