All files / src/server/routes ai-edit.ts

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

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                                                                                                                                                                                                                                                         
import type express from 'express'
import type multer from 'multer'
import * as fs from 'node:fs'
import * as path from 'node:path'
import * as vscode from 'vscode'
import { TemplateDownloadService } from '../../services/template-download-service'
import { dispatchAgentCall } from '../../utils/dispatch-agent-call'
import { logger } from '../../utils/logger-adapter'
 
let templateDownloadService: TemplateDownloadService | null = null
interface TemplateInfo {
  templateId: string
  templateName: string
  templateUrl: string
  formData: Record<string, any>
  packages: string[]
}
 
interface FileMapInfo {
  [placeholder: string]: {
    fileName: string
    fileType: string
  }
}
 
export function registerAIEditRoutes(app: express.Express, upload: multer.Multer) {
  // AI编辑路由 - 简化版本
  app.post('/ai-edit', upload.any(), async (req: any, res: any) => {
    try {
      const { prompt, templateInfo: _templateInfo, fileMapInfo: _fileMapInfo } = req.body as {
        prompt: string
        templateInfo: string
        fileMapInfo?: string
      }
      const templateInfo = JSON.parse(_templateInfo) as TemplateInfo
      const fileMapInfo = _fileMapInfo ? JSON.parse(_fileMapInfo) as FileMapInfo : null
      const uploadedFiles = req.files as Express.Multer.File[]
 
      if (!prompt) {
        res.status(400).json({ success: false, error: '缺少必要参数: prompt' })
        return
      }
 
      const workspaceFolder = vscode.workspace.workspaceFolders?.[0]
      const workspaceRoot = workspaceFolder?.uri.fsPath
      if (!workspaceRoot) {
        res.status(400).json({ success: false, error: '未找到工作区' })
        return
      }
 
      // 处理上传的文件
      const uploadedImagePaths: string[] = []
      if (uploadedFiles && uploadedFiles.length > 0 && fileMapInfo) {
        // 创建资源目录
        const assetsDir = path.join(workspaceRoot, '.dalidev', 'images')
        if (!fs.existsSync(assetsDir)) {
          fs.mkdirSync(assetsDir, { recursive: true })
        }
 
        for (const file of uploadedFiles) {
          // 提取占位符名称(去掉 'file_' 前缀)
          const placeholder = file.fieldname.replace('file_', '')
          const fileInfo = fileMapInfo[placeholder]
 
          if (fileInfo) {
            // 生成唯一的文件名,避免冲突
            const timestamp = Date.now()
            const ext = path.extname(fileInfo.fileName)
            const baseName = path.basename(fileInfo.fileName, ext)
            const uniqueFileName = `${baseName}_${timestamp}${ext}`
            const filePath = path.join(assetsDir, uniqueFileName)
 
            // 保存文件到工作区
            fs.writeFileSync(filePath, file.buffer)
            uploadedImagePaths.push(filePath)
 
            logger.info(`上传文件已保存: ${filePath}`)
          }
        }
      }
 
      if (!templateDownloadService) {
        templateDownloadService = new TemplateDownloadService(workspaceRoot)
      }
 
      // 处理模板请求,下载模板
      const data = await templateDownloadService.downloadTemplate(templateInfo.templateUrl, templateInfo.templateId, templateInfo.templateName)
 
      // 构建包含图片信息的prompt
      let finalPrompt = await templateDownloadService.processTemplateRequest([data])
 
      finalPrompt = `
      用户需求:${prompt}
      模板信息:${finalPrompt}
      `
 
      if (uploadedImagePaths.length > 0) {
        const imagePromptPart = `
 
以下是用户上传的图片文件,请在生成代码时参考这些图片:
${uploadedImagePaths.map((imagePath, index) => `${index + 1}. [dalidev-img]${imagePath}`).join('\n')}
 
请根据这些图片内容来理解用户的需求,并在代码中体现相关的设计或功能。`
 
        finalPrompt += imagePromptPart
      }
 
      const fileContextPath = `${data.localPath}/index.vue`
      dispatchAgentCall({ prompt: finalPrompt, fileContextPath })
 
      res.json({
        success: true,
        message: '已接收AI编辑请求,正在处理',
        workspaceRoot,
        uploadedFiles: uploadedImagePaths.length,
        uploadedImagePaths: uploadedImagePaths.map(p => path.relative(workspaceRoot, p)),
      })
    }
    catch (error) {
      logger.error('处理AI编辑请求失败:', error)
      res.status(500).json({ success: false, error: error instanceof Error ? error.message : String(error) })
    }
  })
}