All files / web/src/lib/tasks phi-explore-generate.ts

0% Statements 0/213
0% Branches 0/1
0% Functions 0/1
0% Lines 0/213

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214                                                                                                                                                                                                                                                                                                                                                                                                                                           
import {
  PHI_EXPLORE_SUBJECTS,
  PHI_EXPLORE_PROMPT_PREFIX,
  PHI_EXPLORE_THEME_MODIFIERS,
} from '@/components/toys/number-line/constants/phiExploreData'
import { createTask } from '../task-manager'
import { getImageProvider } from '../image-providers'
import { generateAndStoreImage } from '../image-generation'
import { imageExists } from '../image-storage'
import type { PhiExploreGenerateEvent } from './events'
import { recordImageGenUsage } from '../ai-usage/helpers'
import { AiFeature } from '../ai-usage/features'

export { IMAGE_PROVIDERS } from '../image-providers'

export interface PhiExploreGenerateInput {
  provider: 'gemini' | 'openai'
  model: string
  targets: Array<{ subjectId: string; theme?: 'light' | 'dark' }>
  forceRegenerate?: boolean
  _userId?: string
}

export interface PhiExploreGenerateOutput {
  generated: number
  skipped: number
  failed: number
  results: Array<{
    subjectId: string
    theme?: 'light' | 'dark'
    status: 'generated' | 'skipped' | 'failed'
    error?: string
  }>
}

/**
 * Start a phi explore image generation background task.
 *
 * Generates golden-ratio subject illustrations using the specified AI provider.
 * Reports per-image progress via task events.
 */
export async function startPhiExploreGeneration(input: PhiExploreGenerateInput): Promise<string> {
  return createTask<PhiExploreGenerateInput, PhiExploreGenerateOutput, PhiExploreGenerateEvent>(
    'phi-explore-generate',
    input,
    async (handle, config) => {
      const provider = getImageProvider(config.provider)
      if (!provider) {
        handle.fail(`Unknown image provider: ${config.provider}`)
        return
      }

      if (!provider.isAvailable()) {
        const { envKey, envKeyAlt } = provider.meta
        const keys = envKeyAlt ? `${envKey} or ${envKeyAlt}` : envKey
        handle.fail(
          `No API key configured for ${provider.meta.name}. Set ${keys} in your environment.`
        )
        return
      }

      // Build lookup for subject data
      const subjectMap = new Map(PHI_EXPLORE_SUBJECTS.map((s) => [s.id, s]))

      // Determine work items
      const results: PhiExploreGenerateOutput['results'] = []
      let generated = 0
      let skipped = 0
      let failed = 0
      let consecutiveErrors = 0
      const MAX_CONSECUTIVE_ERRORS = 3

      const total = config.targets.length

      handle.setProgress(0, `Starting generation of ${total} phi explore images`)

      for (let i = 0; i < config.targets.length; i++) {
        if (handle.isCancelled()) break

        const target = config.targets[i]
        const subject = subjectMap.get(target.subjectId)
        if (!subject) {
          results.push({
            subjectId: target.subjectId,
            theme: target.theme,
            status: 'failed',
            error: `Unknown subject: ${target.subjectId}`,
          })
          failed++
          continue
        }

        const themeSuffix = target.theme ? `-${target.theme}` : ''
        const filename = `${target.subjectId}${themeSuffix}.png`
        const storageTarget = {
          type: 'static' as const,
          relativePath: `images/constants/phi-explore/${filename}`,
        }

        // Skip if already exists and not force-regenerating
        if (!config.forceRegenerate && imageExists(storageTarget)) {
          results.push({
            subjectId: target.subjectId,
            theme: target.theme,
            status: 'skipped',
          })
          skipped++
          const progress = Math.round(((i + 1) / total) * 100)
          handle.setProgress(
            progress,
            `Skipped ${subject.name}${target.theme ? ` (${target.theme})` : ''} (already exists)`
          )
          continue
        }

        handle.emit({
          type: 'image_started',
          subjectId: target.subjectId,
          model: config.model,
          provider: config.provider,
          ...(target.theme && { theme: target.theme }),
        })

        handle.emit({
          type: 'batch_progress',
          completed: generated + skipped + failed,
          total,
          currentSubject: subject.name,
          ...(target.theme && { theme: target.theme }),
        })

        // Build the full prompt
        const themeModifier = target.theme ? ` ${PHI_EXPLORE_THEME_MODIFIERS[target.theme]}` : ''
        const fullPrompt = `${PHI_EXPLORE_PROMPT_PREFIX} ${subject.prompt}${themeModifier}`

        try {
          const result = await generateAndStoreImage({
            provider: config.provider,
            model: config.model,
            prompt: fullPrompt,
            storageTarget,
          })

          const sizeBytes = result.sizeBytes ?? 0

          generated++
          consecutiveErrors = 0
          if (config._userId) {
            recordImageGenUsage(config.provider, config.model, {
              userId: config._userId,
              feature: AiFeature.IMAGE_PHI_EXPLORE,
              backgroundTaskId: handle.id,
            })
          }

          handle.emit({
            type: 'image_complete',
            subjectId: target.subjectId,
            filePath: result.publicUrl,
            sizeBytes,
            ...(target.theme && { theme: target.theme }),
          })

          results.push({
            subjectId: target.subjectId,
            theme: target.theme,
            status: 'generated',
          })
        } catch (err) {
          failed++
          consecutiveErrors++
          const errorMsg = err instanceof Error ? err.message : String(err)

          handle.emit({
            type: 'image_error',
            subjectId: target.subjectId,
            error: errorMsg,
            ...(target.theme && { theme: target.theme }),
          })

          results.push({
            subjectId: target.subjectId,
            theme: target.theme,
            status: 'failed',
            error: errorMsg,
          })

          if (consecutiveErrors >= MAX_CONSECUTIVE_ERRORS) {
            handle.fail(
              `Generation aborted after ${MAX_CONSECUTIVE_ERRORS} consecutive failures: ${errorMsg}`
            )
            return
          }
        }

        const progress = Math.round(((i + 1) / total) * 100)
        handle.setProgress(
          progress,
          `${generated + skipped + failed}/${total} — ${generated} generated, ${skipped} skipped, ${failed} failed`
        )
      }

      handle.emit({
        type: 'batch_complete',
        generated,
        skipped,
        failed,
      })

      handle.complete({ generated, skipped, failed, results })
    }
  )
}