All files / web/src/lib/tasks flowchart-generate.ts

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

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 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             
import { eq } from 'drizzle-orm'
import type { z } from 'zod'
import { db, schema } from '@/db'
import {
  GeneratedFlowchartSchema,
  getGenerationSystemPrompt,
  getSubtractionExample,
  transformLLMDefinitionToInternal,
} from '@/lib/flowchart-workshop/llm-schemas'
import { validateTestCasesWithCoverage } from '@/lib/flowchart-workshop/test-case-validator'
import { createTaskLLM } from '@/lib/llm'
import { createUsageRecordingMiddleware } from '@/lib/ai-usage/llm-middleware'
import { createTask } from '../task-manager'
import type { FlowchartGenerateEvent } from './events'

type GeneratedFlowchart = z.infer<typeof GeneratedFlowchartSchema>

/**
 * Input for the flowchart generate task
 */
export interface FlowchartGenerateInput {
  sessionId: string
  topicDescription: string
  userId: string
  debug?: boolean
}

/**
 * Output from the flowchart generate task
 */
export interface FlowchartGenerateOutput {
  definition: unknown
  mermaidContent: string
  title: string
  description: string
  emoji: string
  difficulty: string
  notes: string[]
  usage?: { promptTokens: number; completionTokens: number; reasoningTokens?: number }
  validationPassed: boolean
  coveragePercent: number
  versionNumber: number
}

/**
 * Start a flowchart generation background task.
 *
 * Extracts LLM generation logic from the legacy SSE route. The task handler:
 * 1. Streams LLM reasoning and output via transient events (no DB writes per token)
 * 2. Saves the result to the workshop session draft
 * 3. Creates a version history entry
 * 4. Runs test-case validation
 */
export async function startFlowchartGeneration(input: FlowchartGenerateInput): Promise<string> {
  return createTask<FlowchartGenerateInput, FlowchartGenerateOutput, FlowchartGenerateEvent>(
    'flowchart-generate',
    input,
    async (handle, config) => {
      const { sessionId, topicDescription, userId, debug } = config

      // Verify session exists and belongs to user
      const session = await db.query.workshopSessions.findFirst({
        where: eq(schema.workshopSessions.id, sessionId),
      })

      if (!session) {
        handle.fail('Session not found')
        return
      }

      if (session.userId !== userId) {
        handle.fail('Not authorized')
        return
      }

      // Update session state to generating and store task ID
      await db
        .update(schema.workshopSessions)
        .set({
          state: 'generating',
          topicDescription,
          currentTaskId: handle.id,
          updatedAt: new Date(),
        })
        .where(eq(schema.workshopSessions.id, sessionId))

      handle.emit({
        type: 'generate_started',
        sessionId,
        topicDescription,
      })

      handle.emit({
        type: 'generate_progress',
        stage: 'preparing',
        message: 'Preparing flowchart generation...',
      })

      // Build the prompt
      const systemPrompt = getGenerationSystemPrompt()
      const examplePrompt = getSubtractionExample()

      const userPrompt = `Create an interactive math flowchart for teaching the following topic:

**Topic**: ${topicDescription}

Create a complete, working flowchart with:
1. A JSON definition with all nodes, variables, and validation
2. Mermaid content with visual formatting and phases
3. At least one example problem in the problemInput.examples array

The flowchart should be engaging for students, with clear phases, checkpoints for important calculations, and encouraging visual elements.

Return the result as a JSON object matching the GeneratedFlowchartSchema.`

      const fullPrompt = `${systemPrompt}\n\n${examplePrompt}\n\n---\n\n${userPrompt}`

      let llmError: { message: string; code?: string } | null = null
      let finalResult: GeneratedFlowchart | null = null
      let usage: {
        promptTokens: number
        completionTokens: number
        reasoningTokens?: number
      } | null = null

      try {
        if (debug) {
          console.log(`[flowchart-generate] Creating LLM stream`, {
            promptLength: fullPrompt.length,
          })
        }

        // Create task-aware LLM client that handles streaming events
        // Middleware automatically:
        // - Emits transient reasoning/output_delta events to Socket.IO
        // - Persists reasoning/output snapshots every 3s for page-reload recovery
        const taskLLM = createTaskLLM(
          handle,
          createUsageRecordingMiddleware({
            userId,
            feature: 'flowchart:generate',
            backgroundTaskId: handle.id,
          })
        )

        const llmStream = taskLLM.stream({
          provider: 'openai',
          model: 'gpt-5.2',
          prompt: fullPrompt,
          schema: GeneratedFlowchartSchema,
          reasoning: {
            effort: 'medium',
            summary: 'auto',
          },
          timeoutMs: 300_000,
          debug: true,
        })

        handle.setProgress(10, 'AI is thinking...')

        for await (const event of llmStream) {
          if (handle.isCancelled()) {
            console.log(`[flowchart-generate] Task cancelled, breaking LLM loop`)
            break
          }

          // Middleware handles reasoning, output_delta, and snapshots automatically
          switch (event.type) {
            case 'started':
              handle.setProgress(15, 'AI is thinking...')
              break

            case 'output_delta':
              // Just update progress - middleware handles event emission
              handle.setProgress(50, 'Generating flowchart...')
              break

            case 'error':
              console.error('[flowchart-generate] LLM error:', event.message, event.code)
              llmError = { message: event.message, code: event.code }
              break

            case 'complete':
              finalResult = event.data
              usage = event.usage
              break
          }
        }
      } catch (error) {
        console.error('[flowchart-generate] Stream processing error:', error)
        llmError = {
          message: error instanceof Error ? error.message : 'Unknown error',
        }
      }

      // Handle cancelled task
      if (handle.isCancelled()) {
        await db
          .update(schema.workshopSessions)
          .set({
            state: session.draftDefinitionJson ? 'refining' : 'initial',
            currentTaskId: null,
            currentReasoningText: null,
            updatedAt: new Date(),
          })
          .where(eq(schema.workshopSessions.id, sessionId))
        return
      }

      if (llmError) {
        // LLM failed — reset session to initial, clear reasoning
        await db
          .update(schema.workshopSessions)
          .set({
            state: 'initial',
            draftNotes: JSON.stringify([`Generation failed: ${llmError.message}`]),
            currentReasoningText: null,
            currentTaskId: null,
            updatedAt: new Date(),
          })
          .where(eq(schema.workshopSessions.id, sessionId))

        handle.emit({
          type: 'generate_error',
          message: llmError.message,
          code: llmError.code,
        })
        handle.fail(llmError.message)
        return
      }

      if (!finalResult) {
        await db
          .update(schema.workshopSessions)
          .set({
            state: 'initial',
            currentTaskId: null,
            currentReasoningText: null,
            updatedAt: new Date(),
          })
          .where(eq(schema.workshopSessions.id, sessionId))

        handle.fail('LLM returned no result')
        return
      }

      // LLM succeeded — validate and save
      handle.setProgress(80, 'Validating result...')
      handle.emit({
        type: 'generate_progress',
        stage: 'validating',
        message: 'Validating result...',
      })

      // Transform LLM output (array-based) to internal format (record-based)
      const internalDefinition = transformLLMDefinitionToInternal(finalResult.definition)

      // Run test case validation with coverage analysis
      const validationReport = await validateTestCasesWithCoverage(
        internalDefinition,
        finalResult.mermaidContent
      )

      handle.emit({
        type: 'generate_validation',
        passed: validationReport.passed,
        failedCount: validationReport.summary.failed + validationReport.summary.errors,
        totalCount: validationReport.summary.total,
        coveragePercent: validationReport.coverage.coveragePercent,
      })

      // Increment version number and save to history
      const currentVersion = session.currentVersionNumber ?? 0
      const newVersion = currentVersion + 1

      await db.insert(schema.flowchartVersionHistory).values({
        sessionId,
        versionNumber: newVersion,
        definitionJson: JSON.stringify(internalDefinition),
        mermaidContent: finalResult.mermaidContent,
        title: finalResult.title,
        description: finalResult.description,
        emoji: finalResult.emoji,
        difficulty: finalResult.difficulty,
        notes: JSON.stringify(finalResult.notes),
        source: 'generate',
        sourceRequest: topicDescription,
        validationPassed: validationReport.passed,
        coveragePercent: validationReport.coverage.coveragePercent,
      })

      // Update session with generated content
      await db
        .update(schema.workshopSessions)
        .set({
          state: 'refining',
          draftDefinitionJson: JSON.stringify(internalDefinition),
          draftMermaidContent: finalResult.mermaidContent,
          draftTitle: finalResult.title,
          draftDescription: finalResult.description,
          draftDifficulty: finalResult.difficulty,
          draftEmoji: finalResult.emoji,
          draftNotes: JSON.stringify(finalResult.notes),
          currentReasoningText: null,
          currentTaskId: null,
          currentVersionNumber: newVersion,
          updatedAt: new Date(),
        })
        .where(eq(schema.workshopSessions.id, sessionId))

      const output: FlowchartGenerateOutput = {
        definition: internalDefinition,
        mermaidContent: finalResult.mermaidContent,
        title: finalResult.title,
        description: finalResult.description,
        emoji: finalResult.emoji,
        difficulty: finalResult.difficulty,
        notes: finalResult.notes,
        usage: usage ?? undefined,
        validationPassed: validationReport.passed,
        coveragePercent: validationReport.coverage.coveragePercent,
        versionNumber: newVersion,
      }

      handle.emit({
        type: 'generate_complete',
        ...output,
      })

      handle.setProgress(100, 'Flowchart generated!')
      handle.complete(output)
    }
  )
}