Optional product examples

Five-Credit Image Generation Workflow

Trace the starter's complete asynchronous paid task through authentication, entitlements, idempotent credits, durable work, private storage, and failure compensation.

Verified against starter commit e632762.

Image generation is the starter's minimal reference for a production-shaped paid workflow. The local provider returns a generated SVG rather than calling a commercial model; the important part is the chain around it. One accepted request costs exactly five pooled organization credits.

Run one successful image task

First complete Quick Start through the local Core setup. If another dev runner is open, stop it with Ctrl-C, then run:

pnpm starter core demo

This runs doctor first, seeds only after a successful preflight, and starts web plus the durable worker with ENABLE_DEMO_FEATURES=true, ENABLE_IMAGE_GENERATION_MOCK=true, and IMAGE_GENERATION_MOCK_FAILURES=0. It disables the local captcha and outgoing email, Slack, and Stripe for those processes. It leaves environment files unchanged, uses the local mock adapter, and does not require an AI provider account or paid subscription.

  1. Sign in at localhost:3000/login with demo@example.test / DemoPass123!, or the existing fixture password. A custom DEV_SEED_PASSWORD applies when the account is first created; reseeding does not rotate it.
  2. Open Account → Credits in the seeded workspace. Expect one 1,000-credit demo grant, potentially plus the separate 10-credit signup grant. Wait for startup grants to settle and record the current balance; repeat seeding does not grant another 1,000 or reset prior spending.
  3. Open the image page, keep its org parameter, enter My first Sushi SaaS image task, and select Generate image once.
  4. Wait for Image ready. You may briefly see queued/running states. The SVG contains the label Image generation mock and your prompt on a blue/purple background. It is a mock response, not an AI-generated illustration.
  5. Refresh the same task URL. Confirm the same task ID and result return without another charge. In Account → Credits, find one Image generation −5 entry; with no unrelated activity, the balance is the recorded baseline minus five. Account → Files contains generated-<task ID>.svg.

The object remains in the private Garage bucket. The task API supplies a signed URL valid for 15 minutes; reopening the saved task page renews access. Anyone holding that signed URL has temporary access, so do not treat it as a permanent public asset URL. Generate another image deliberately starts a new paid task and spends another five credits.

Troubleshoot the local walkthrough

SymptomNext step
Setup or doctor failsKeep Docker running; inspect the named port, database, Redis, migration, or storage check. Fix that check before restarting the demo.
Login failsUse the seeded account’s original password. Repeating seed does not rotate an existing password; it never requires a real inbox.
Image page returns 404Use pnpm starter core demo, then reload. Production always disables this mock page/API/service.
Task stays queuedKeep the demo terminal open and inspect [worker] logs. pnpm dev alone starts only web.
Task retries or image is missingRun pnpm starter core doctor and inspect worker/storage errors. Restore the dependency and refresh the existing task URL instead of submitting a replacement.
Signed image URL expiresReload the saved task page to obtain a new signed URL.
Balance differs from an example totalCompare the single task debit with its baseline. Signup bonuses and other tasks have separate ledger entries.
Credit or monthly quota limit appearsKeep the seeded workspace selected and inspect its ledger/usage. Free allows this example, with the default ten-task monthly limit; reseeding is not a quota or balance reset.

The recoverable chain

  1. The API checks origin, rate limit and authentication; the service resolves replays before applying new-operation entitlements.
  2. (user_uuid, type, idempotency_key) identifies one task. A SHA-256 request fingerprint rejects reusing that key with another prompt.
  3. task_image:<task uuid> identifies the five-credit spend. Concurrent request replays return the existing logical debit instead of spending again.
  4. Quota reservation, the five-credit debit, the task and task_image_generation:<task uuid> dispatch commit in one transaction. Queue failure rolls the debit back.
  5. The worker calls the provider with the stable task UUID, writes a deterministic private Garage/S3 object, verifies it, activates its file row, and marks the task succeeded.
  6. GET /api/tasks/[uuid] resolves the organization-scoped file and creates a short-lived signed URL. Bucket credentials and object keys never enter the public task contract.

The task state machine is:

Accepted tasks return as queued. Maintenance repairs legacy charged intents after five minutes without requiring browser replay; unpaid drafts are never charged by maintenance.

queued → running → succeeded
           ↘ refunding → failed

Provider attempts stop after five; the job has eight attempts, leaving three attempts for compensation if the database is temporarily unavailable. A terminal provider failure moves the task to refunding, appends the deterministic ledger refund, and only then records failed. Replaying a refunding or terminal task never runs the provider or refund twice.

For a deliberate retry/refund drill, stop demo mode and run ordinary pnpm starter core dev with both demo flags enabled and IMAGE_GENERATION_MOCK_FAILURES=5 in the web and worker environment. pnpm starter core demo always forces zero provider failures, so it is not the failure-test command. Five failed provider attempts are separated by queue backoff; do not expect an immediate refund. The real-database suite proves one spend and one refund after five failures; Playwright proves request replay, exact five-credit balance change, worker execution, Garage storage, and signed download.

Adapt the example for production

Implement the real adapter in src/services/ai/image.ts, honoring the supplied idempotency key and abort signal. Keep provider credentials and SDK types inside that adapter, and preserve task, credit, job, storage, and public error contracts.

Replacing the adapter alone does not enable production generation. The page, API route, and task service each check isImageGenerationMockEnabled(), which is always false in production. Replace those demo admission checks with an explicit production feature configuration, and keep same-origin, authentication, entitlement, quota, and credit checks at their existing boundaries.

The current GeneratedImage type also permits only image/svg+xml, the svg extension, and provider mock. Define and validate the real provider's allowed output types, extensions, provider identity, and matching file metadata before accepting its bytes. Test the production admission path as well as retries, private output delivery, and compensation.

Ready to launch means: duplicate HTTP requests spend once, provider retries use one external identity, private output is tenant-scoped, a crash after upload repairs the task link, terminal failure refunds once, and operators can recover a buried compensation job.

Related: Organization Credit Ledger, Private Storage Uploads, Durable Jobs and Readiness, and Testing and CI Contracts.