File size: 10,927 Bytes
b1df986
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import fs from 'fs'
import path from 'path'
import { performance } from 'node:perf_hooks'
import { createLogger } from '../../../../shared/logging/logger'
import { cleanManimCode } from '../../../../utils/manim-code-cleaner'
import { executeManimCommand, type ManimExecuteOptions } from '../../../../utils/manim-executor'
import { ensureJobNotCancelled } from '../../../job/job-cancel'
import { isJobCancelled } from '../../../job/job-cancel-store'
import { JobCancelledError } from '../../../../shared/errors/errors'
import { resolveJobTimeoutMs } from '../../../../utils/job-timeout'
import { resolveRenderCacheWorkspace } from '../../../../utils/render-cache-workspace'
import { workspaceRenderOutputDirectory } from '../../../workspace-output-directory'
import {
  createRenderFailureEvent,
  extractCodeSnippet,
  inferErrorMessage,
  inferErrorType,
  isRenderFailureFeatureEnabled,
  sanitizeFullCode,
  sanitizeStderrPreview,
  sanitizeStdoutPreview
} from '../../../../operations/render-failures'
import type { GenerationResult } from './analysis-step'
import type { CustomApiConfig, PromptOverrides, VideoConfig } from '../../../../types'
import type { RenderResult } from './render-step-types'
import { executeRenderWithRetry } from './render-with-retry'

const logger = createLogger('RenderImageStep')

function writeImagesIntoWorkspace(workspaceDirectory: string | undefined, jobId: string, sourceImagePaths: string[], versionDirectory?: string): string[] | undefined {
  if (!workspaceDirectory || sourceImagePaths.length === 0) {
    return undefined
  }

  const workspaceOutputDir = workspaceRenderOutputDirectory(workspaceDirectory, jobId, versionDirectory)
  fs.mkdirSync(workspaceOutputDir, { recursive: true })

  return sourceImagePaths.map((sourcePath, index) => {
    const suffix = path.extname(sourcePath) || '.png'
    const workspaceImagePath = path.join(workspaceOutputDir, `image-${String(index + 1).padStart(3, '0')}${suffix}`)
    fs.copyFileSync(sourcePath, workspaceImagePath)
    return workspaceImagePath
  })
}

interface ImageCodeBlock {
  index: number
  code: string
}

interface ImageRenderAttempt {
  success: boolean
  stderr: string
  stdout: string
  peakMemoryMB: number
  imageUrls: string[]
  outputPaths: string[]
  exitCode?: number
  failedCode?: string
}

function parseImageCodeBlocks(code: string): ImageCodeBlock[] {
  const blocks: ImageCodeBlock[] = []
  const blockRegex = /###\s*YON_IMAGE_(\d+)_START\s*###([\s\S]*?)###\s*YON_IMAGE_\1_END\s*###/g

  let match: RegExpExecArray | null
  while ((match = blockRegex.exec(code)) !== null) {
    const index = parseInt(match[1], 10)
    const blockCode = match[2].trim()
    if (!Number.isFinite(index) || !blockCode) {
      continue
    }
    blocks.push({ index, code: blockCode })
  }

  if (blocks.length === 0) {
    throw new Error('No YON_IMAGE code blocks were found')
  }

  const remaining = code
    .replace(/###\s*YON_IMAGE_(\d+)_START\s*###[\s\S]*?###\s*YON_IMAGE_\1_END\s*###/g, '')
    .trim()
  if (remaining.length > 0) {
    throw new Error('Image mode only accepts code inside YON_IMAGE blocks')
  }

  blocks.sort((a, b) => a.index - b.index)
  return blocks
}

function clearPreviousImages(outputDir: string, jobId: string): void {
  const prefix = `${jobId}-`
  if (!fs.existsSync(outputDir)) {
    return
  }

  for (const entry of fs.readdirSync(outputDir)) {
    if (entry.startsWith(prefix) && entry.endsWith('.png')) {
      fs.rmSync(path.join(outputDir, entry), { force: true })
    }
  }
}

function resolveModel(customApiConfig?: unknown): string | undefined {
  const model = (customApiConfig as Partial<CustomApiConfig> | undefined)?.model
  const normalized = typeof model === 'string' ? model.trim() : ''
  return normalized || undefined
}

async function renderImageBlocks(
  jobId: string,
  quality: string,
  code: string,
  frameRate: number,
  timeoutMs: number,
  renderCacheKey: string,
  outputDir: string
): Promise<ImageRenderAttempt> {
  try {
    await ensureJobNotCancelled(jobId)

    logger.info('Image parse stage started', { jobId, stage: 'image-parse' })
    const blocks = parseImageCodeBlocks(code)
    logger.info('Image parse stage completed', { jobId, stage: 'image-parse', blockCount: blocks.length })

    clearPreviousImages(outputDir, jobId)

    const imageUrls: string[] = []
    let peakMemoryMB = 0

    for (const block of blocks) {
      await ensureJobNotCancelled(jobId)

      const stageName = `image-render-${block.index}`
      logger.info('Image render stage started', { jobId, stage: stageName, blockIndex: block.index })

      const blockWorkspace = resolveRenderCacheWorkspace(renderCacheKey, 'image', jobId, block.index)
      const blockDir = blockWorkspace.tempDir
      const mediaDir = blockWorkspace.mediaDir
      const codeFile = blockWorkspace.codeFile

      const cleaned = cleanManimCode(block.code)
      fs.writeFileSync(codeFile, cleaned.code, 'utf-8')

      const options: ManimExecuteOptions = {
        jobId,
        quality,
        frameRate,
        format: 'png',
        isCancelled: () => isJobCancelled(jobId),
        tempDir: blockDir,
        mediaDir,
        timeoutMs
      }

      const renderResult = await executeManimCommand(codeFile, options)
      peakMemoryMB = Math.max(peakMemoryMB, renderResult.peakMemoryMB)
      if (!renderResult.success) {
        return {
          success: false,
          stderr: `Image ${block.index} render failed: ${renderResult.stderr || 'Manim render failed'}`,
          stdout: renderResult.stdout || '',
          peakMemoryMB,
          imageUrls: [],
          outputPaths: [],
          exitCode: renderResult.exitCode,
          failedCode: cleaned.code
        }
      }

      const imagePath = renderResult.outputPath
      if (!imagePath) {
        return {
          success: false,
          stderr: `Image ${block.index} render completed but no PNG output was found`,
          stdout: '',
          peakMemoryMB,
          imageUrls: [],
          outputPaths: [],
          failedCode: cleaned.code
        }
      }

      const outputFilename = `${jobId}-${block.index}.png`
      const outputPath = path.join(outputDir, outputFilename)
      fs.copyFileSync(imagePath, outputPath)
      imageUrls.push(`/images/${outputFilename}`)

      logger.info('Image render stage completed', { jobId, stage: stageName, outputFilename })
    }

    return {
      success: true,
      stderr: '',
      stdout: '',
      peakMemoryMB,
      imageUrls,
      outputPaths: blocks.map((block) => path.join(outputDir, `${jobId}-${block.index}.png`))
    }
  } catch (error) {
    if (error instanceof JobCancelledError) {
      throw error
    }

    return {
      success: false,
      stderr: error instanceof Error ? error.message : String(error),
      stdout: '',
      peakMemoryMB: 0,
      imageUrls: [],
      outputPaths: []
    }
  }
}

export async function renderImages(
  jobId: string,
  concept: string,
  quality: string,
  codeResult: GenerationResult,
  timings?: Record<string, number>,
  videoConfig?: VideoConfig,
  customApiConfig?: unknown,
  promptOverrides?: PromptOverrides,
  onStageUpdate?: () => Promise<void>,
  clientId?: string,
  workspaceDirectory?: string,
  renderCacheKey?: string,
  workspaceOutputDirectory?: string
): Promise<RenderResult> {
  const { code, usedAI, generationType, sceneDesign } = codeResult
  const frameRate = videoConfig?.frameRate || 60
  const timeoutMs = resolveJobTimeoutMs(videoConfig)

  const stableRenderCacheKey = renderCacheKey || workspaceDirectory || `job-${jobId}`
  const outputDir = path.join(process.cwd(), 'public', 'images')

  const logRenderFailure = async (args: {
    attempt: number
    code: string
    codeSnippet?: string
    stderr: string
    stdout: string
    peakMemoryMB: number
    exitCode?: number
    promptRole: string
  }): Promise<void> => {
    if (!isRenderFailureFeatureEnabled()) {
      return
    }

    try {
      await createRenderFailureEvent({
        job_id: jobId,
        attempt: args.attempt,
        output_mode: 'image',
        error_type: inferErrorType(args.stderr),
        error_message: inferErrorMessage(args.stderr),
        stderr_preview: sanitizeStderrPreview(args.stderr),
        stdout_preview: sanitizeStdoutPreview(args.stdout),
        code_snippet: extractCodeSnippet(args.codeSnippet || args.code),
        full_code: sanitizeFullCode(args.code),
        peak_memory_mb: args.peakMemoryMB,
        exit_code: args.exitCode,
        recovered: false,
        model: resolveModel(customApiConfig),
        prompt_version: process.env.PROMPT_VERSION?.trim() || null,
        prompt_role: args.promptRole,
        client_id: clientId || null,
        concept: concept || null
      })
    } catch (error) {
      console.error('[RenderImageStep] Failed to record render failure:', error)
    }
  }

  fs.mkdirSync(outputDir, { recursive: true })
  await ensureJobNotCancelled(jobId)

  if (onStageUpdate) {
    await onStageUpdate()
  }

  let finalImageUrls: string[] = []
  let finalImageOutputPaths: string[] = []
  let peakMemoryMB = 0

  const renderWithCode = async (candidateCode: string): Promise<{
    success: boolean
    stderr: string
    stdout: string
    peakMemoryMB: number
    exitCode?: number
    codeSnippet?: string
  }> => {
    const renderStart = performance.now()
    const attempt = await renderImageBlocks(jobId, quality, candidateCode, frameRate, timeoutMs, stableRenderCacheKey, outputDir)
    if (timings) timings.render = (timings.render || 0) + (performance.now() - renderStart)
    peakMemoryMB = Math.max(peakMemoryMB, attempt.peakMemoryMB)
    if (attempt.success) {
      finalImageUrls = attempt.imageUrls
      finalImageOutputPaths = attempt.outputPaths
    }
    return {
      success: attempt.success,
      stderr: attempt.stderr,
      stdout: attempt.stdout,
      peakMemoryMB: attempt.peakMemoryMB,
      exitCode: attempt.exitCode,
      codeSnippet: attempt.failedCode
    }
  }

  const { finalCode } = await executeRenderWithRetry({
    problemPlan: codeResult.problemPlan,
    referenceImages: codeResult.referenceImages,
    concept,
    outputMode: 'image',
    sceneDesign,
    promptOverrides,
    customApiConfig,
    initialCode: code,
    usedAI,
    timings,
    renderCode: renderWithCode,
    logRenderFailure,
    ensureJobNotCancelled: async () => ensureJobNotCancelled(jobId)
  })

  await ensureJobNotCancelled(jobId)

  const workspaceImagePaths = writeImagesIntoWorkspace(workspaceDirectory, jobId, finalImageOutputPaths, workspaceOutputDirectory)

  return {
    jobId,
    concept,
    outputMode: 'image',
    code: finalCode,
    codeLanguage: 'manim-python',
    usedAI,
    generationType,
    quality,
    imageUrls: finalImageUrls,
    imageCount: finalImageUrls.length,
    workspaceImagePaths,
    renderPeakMemoryMB: peakMemoryMB || undefined
  }
}