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

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

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 336 337 338 339 340 341 342 343 344 345 346 347 348                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import { eq } from 'drizzle-orm'
import type { z } from 'zod'
import { db, schema } from '@/db'
import {
  getRefinementSystemPrompt,
  RefinementResultSchema,
  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 { FlowchartRefineEvent } from './events'

type RefinementResult = z.infer<typeof RefinementResultSchema>

/**
 * Input for the flowchart refine task
 */
export interface FlowchartRefineInput {
  sessionId: string
  refinementRequest: string
  userId: string
}

/**
 * Output from the flowchart refine task
 */
export interface FlowchartRefineOutput {
  definition: unknown
  mermaidContent: string
  emoji: string
  changesSummary: string
  notes: string[]
  usage?: { promptTokens: number; completionTokens: number; reasoningTokens?: number }
  validationPassed: boolean
  coveragePercent: number
  versionNumber: number
}

/**
 * Start a flowchart refinement background task.
 *
 * Extracts LLM refinement logic from the legacy SSE route. The task handler:
 * 1. Streams LLM reasoning and output via transient events
 * 2. Updates the workshop session draft
 * 3. Creates a version history entry
 * 4. Runs test-case validation
 */
export async function startFlowchartRefinement(input: FlowchartRefineInput): Promise<string> {
  return createTask<FlowchartRefineInput, FlowchartRefineOutput, FlowchartRefineEvent>(
    'flowchart-refine',
    input,
    async (handle, config) => {
      const { sessionId, refinementRequest, userId } = 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
      }

      // Check we have a draft to refine
      if (!session.draftDefinitionJson || !session.draftMermaidContent) {
        handle.fail('No draft to refine - generate first')
        return
      }

      // Parse refinement history
      let refinementHistory: string[] = []
      if (session.refinementHistory) {
        try {
          refinementHistory = JSON.parse(session.refinementHistory)
        } catch {
          // Ignore
        }
      }

      // Store task ID on session
      await db
        .update(schema.workshopSessions)
        .set({
          currentTaskId: handle.id,
          updatedAt: new Date(),
        })
        .where(eq(schema.workshopSessions.id, sessionId))

      handle.emit({
        type: 'refine_started',
        sessionId,
        refinementRequest,
      })

      handle.emit({
        type: 'refine_progress',
        stage: 'preparing',
        message: 'Preparing refinement...',
      })

      // Build the prompt
      const systemPrompt = getRefinementSystemPrompt()

      const historyContext =
        refinementHistory.length > 0
          ? `\n\n## Previous Refinements\n${refinementHistory.map((r, i) => `${i + 1}. ${r}`).join('\n')}`
          : ''

      const userPrompt = `Here is the current flowchart to refine:

## Current Definition (JSON)
\`\`\`json
${session.draftDefinitionJson}
\`\`\`

## Current Mermaid Content
\`\`\`mermaid
${session.draftMermaidContent}
\`\`\`

## Current Emoji
${session.draftEmoji || '📊'}

## Topic/Context
${session.topicDescription || 'Not specified'}

${historyContext}

## Refinement Request
${refinementRequest}

Please modify the flowchart according to this request. Return the complete updated definition and mermaid content. If the topic changed significantly and the current emoji no longer fits, provide an updated emoji; otherwise set updatedEmoji to null to keep the current one.`

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

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

      try {
        // 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:refine',
            backgroundTaskId: handle.id,
          })
        )

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

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

        for await (const event of llmStream) {
          if (handle.isCancelled()) {
            console.log(`[flowchart-refine] 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, 'Refining flowchart...')
              break

            case 'error':
              console.error('[flowchart-refine] 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-refine] 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({
            currentTaskId: null,
            updatedAt: new Date(),
          })
          .where(eq(schema.workshopSessions.id, sessionId))
        return
      }

      if (llmError) {
        // Clear task ID but don't change state — keep previous draft
        await db
          .update(schema.workshopSessions)
          .set({
            currentTaskId: null,
            updatedAt: new Date(),
          })
          .where(eq(schema.workshopSessions.id, sessionId))

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

      if (!finalResult) {
        await db
          .update(schema.workshopSessions)
          .set({
            currentTaskId: 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 changes...')
      handle.emit({
        type: 'refine_progress',
        stage: 'validating',
        message: 'Validating changes...',
      })

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

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

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

      // Add to refinement history
      refinementHistory.push(refinementRequest)

      // Determine the emoji (use updated if provided, otherwise keep current)
      const newEmoji = finalResult.updatedEmoji || session.draftEmoji || '📊'

      // 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.updatedMermaidContent,
        title: session.draftTitle,
        description: session.draftDescription,
        emoji: newEmoji,
        difficulty: session.draftDifficulty,
        notes: JSON.stringify(finalResult.notes),
        source: 'refine',
        sourceRequest: refinementRequest,
        validationPassed: validationReport.passed,
        coveragePercent: validationReport.coverage.coveragePercent,
      })

      // Update session with refined content
      await db
        .update(schema.workshopSessions)
        .set({
          state: 'refining',
          draftDefinitionJson: JSON.stringify(internalDefinition),
          draftMermaidContent: finalResult.updatedMermaidContent,
          draftEmoji: newEmoji,
          draftNotes: JSON.stringify(finalResult.notes),
          refinementHistory: JSON.stringify(refinementHistory),
          currentVersionNumber: newVersion,
          currentTaskId: null,
          updatedAt: new Date(),
        })
        .where(eq(schema.workshopSessions.id, sessionId))

      const output: FlowchartRefineOutput = {
        definition: internalDefinition,
        mermaidContent: finalResult.updatedMermaidContent,
        emoji: newEmoji,
        changesSummary: finalResult.changesSummary,
        notes: finalResult.notes,
        usage: usage ?? undefined,
        validationPassed: validationReport.passed,
        coveragePercent: validationReport.coverage.coveragePercent,
        versionNumber: newVersion,
      }

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

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