All files / src extension.ts

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

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 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import * as fs from 'node:fs'
import * as path from 'node:path'
import { defineExtension, useCommand, useIsDarkTheme, watchEffect } from 'reactive-vscode'
import { window, workspace } from 'vscode'
import { message } from './configs'
import { startServer, stopServer } from './server'
import { loginWorkflowService, registerLoginCommands } from './services/login-workflow-service'
import { TemplateDownloadService } from './services/template-download-service'
import { initializeUserInfoService, userInfoService } from './services/user-info-service'
import { WorkspaceAnalysisService } from './services/workspace-analysis-service'
import { logger } from './utils/logger-adapter'
import { ensureDalidevMCPConfig, ensurePlaywrightMCPConfig, hasPlaywrightMCPConfig } from './utils/mcp-config'
// 存储文件 - 使用workspaceRoot而不是tmpdir
function getTimeTrackingFile(workspaceRoot: string): string {
  const dataDir = path.join(workspaceRoot, '.dalidev')
  if (!fs.existsSync(dataDir)) {
    fs.mkdirSync(dataDir, { recursive: true })
  }
  return path.join(dataDir, 'dalidev-ai-editor-tracking.json')
}
 
interface FileStats {
  lines: number
  characters: number
  size: number
}
 
interface CodeStats {
  beforeStats?: Record<string, FileStats>
  afterStats?: Record<string, FileStats>
}
 
interface TimeTrackingRecord {
  sessionId: string
  startTime?: number
  endTime?: number
  duration?: number
  metadata?: {
    prompt?: string
    files?: string[]
    workspaceRoot?: string
    codeStats?: CodeStats
  }
  status: 'started' | 'completed'
  codeGenerated?: {
    totalLinesAdded: number
    totalLinesRemoved: number
    totalCharactersAdded: number
    totalCharactersRemoved: number
    filesCreated: number
    filesModified: number
    filesDeleted: number
  }
}
 
interface TimeTrackingData {
  sessions: Record<string, TimeTrackingRecord>
  lastUpdated: number
}
 
export default defineExtension(async (ctx) => {
  logger.info('Extension Activated')
 
  // 将扩展上下文设置为全局变量,供服务器使用
  ;(globalThis as any).__dalidevExtensionContext = ctx
 
  // 初始化用户信息服务
  try {
    await initializeUserInfoService(ctx)
    logger.info('用户信息服务初始化完成')
  }
  catch (error) {
    logger.error('用户信息服务初始化失败', error)
  }
 
  // 注册登录相关命令
  try {
    registerLoginCommands()
    logger.info('登录工作流命令注册完成')
  }
  catch (error) {
    logger.error('登录工作流命令注册失败', error)
  }
 
  // 初始化模板下载服务
  let templateDownloadService: TemplateDownloadService
  try {
    templateDownloadService = new TemplateDownloadService(workspace.workspaceFolders?.[0]?.uri.fsPath)
    logger.info('Template download service initialized')
  }
  catch (error) {
    logger.error('Failed to initialize template download service:', error)
  }
 
  // 初始化工作区分析服务
  let workspaceAnalysisService: WorkspaceAnalysisService
  try {
    workspaceAnalysisService = new WorkspaceAnalysisService(ctx)
    logger.info('Workspace analysis service initialized')
  }
  catch (error) {
    logger.error('Failed to initialize workspace analysis service:', error)
  }
 
  // 启动服务器
  let serverStarted = false
 
  // 自动启动服务器
  startServer().then(() => {
    serverStarted = true
  }).catch((error) => {
    logger.error('Failed to auto-start server:', error)
  })
 
  // 自动配置 Playwright MCP 工具
  try {
    ensurePlaywrightMCPConfig()
    ensureDalidevMCPConfig()
    logger.info('MCP configuration check completed')
  }
  catch (error) {
    logger.error('Failed to ensure MCP configuration:', error)
  }
 
  // 获取当前工作区根目录
  function getCurrentWorkspaceRoot(): string | undefined {
    return workspace.workspaceFolders?.[0]?.uri.fsPath
  }
 
  // 注册命令
  useCommand('dalidev-vscode-server.helloWorld', () => {
    window.showInformationMessage(message.value)
  })
 
  // 启动服务器命令
  useCommand('dalidev-vscode-server.startServer', async () => {
    if (serverStarted) {
      window.showInformationMessage('dalidev server is already running')
      return
    }
 
    try {
      await startServer()
      serverStarted = true
    }
    catch (error) {
      logger.error('Failed to start server:', error)
    }
  })
 
  // 停止服务器命令
  useCommand('dalidev-vscode-server.stopServer', async () => {
    if (!serverStarted) {
      window.showInformationMessage('dalidev server is not running')
      return
    }
 
    try {
      await stopServer()
      serverStarted = false
    }
    catch (error) {
      logger.error('Failed to stop server:', error)
    }
  })
 
  // 清理模板缓存命令
  useCommand('dalidev-vscode-server.clearTemplateCache', async () => {
    try {
      if (templateDownloadService) {
        // 这里可以添加清理缓存的方法
        window.showInformationMessage('Template cache cleared successfully')
        logger.info('Template cache cleared')
      }
      else {
        window.showErrorMessage('Template download service not available')
      }
    }
    catch (error) {
      logger.error('Failed to clear template cache:', error)
      window.showErrorMessage('Failed to clear template cache')
    }
  })
 
  // 分析工作区命令
  useCommand('dalidev-vscode-server.analyzeWorkspace', async () => {
    try {
      if (!workspaceAnalysisService) {
        window.showErrorMessage('Workspace analysis service not available')
        return
      }
 
      window.showInformationMessage('开始分析工作区...')
      const result = await workspaceAnalysisService.analyzeWorkspace()
 
      // 显示分析结果摘要
      const message = `工作区分析完成!\n\n${result.summary.substring(0, 200)}${result.summary.length > 200 ? '...' : ''}`
      window.showInformationMessage(message)
 
      logger.info('Workspace analysis completed')
    }
    catch (error) {
      logger.error('Failed to analyze workspace:', error)
      window.showErrorMessage(`工作区分析失败: ${error instanceof Error ? error.message : String(error)}`)
    }
  })
 
  // 清理工作区分析缓存命令
  useCommand('dalidev-vscode-server.clearWorkspaceCache', async () => {
    try {
      if (!workspaceAnalysisService) {
        window.showErrorMessage('Workspace analysis service not available')
        return
      }
 
      await workspaceAnalysisService.clearCache()
      window.showInformationMessage('Workspace analysis cache cleared successfully')
      logger.info('Workspace analysis cache cleared')
    }
    catch (error) {
      logger.error('Failed to clear workspace analysis cache:', error)
      window.showErrorMessage('Failed to clear workspace analysis cache')
    }
  })
 
  // 查看工作区分析缓存统计命令
  useCommand('dalidev-vscode-server.workspaceCacheStats', async () => {
    try {
      if (!workspaceAnalysisService) {
        window.showErrorMessage('Workspace analysis service not available')
        return
      }
 
      const stats = workspaceAnalysisService.getCacheStats()
      const message = `工作区分析缓存统计:\n- 缓存条目数: ${stats.count}\n- 缓存键: ${stats.keys.join(', ')}`
      window.showInformationMessage(message)
    }
    catch (error) {
      logger.error('Failed to get workspace cache stats:', error)
      window.showErrorMessage('Failed to get workspace cache stats')
    }
  })
 
  // 测试后端连接命令
  useCommand('dalidev-vscode-server.testBackendConnection', async () => {
    try {
      if (!workspaceAnalysisService) {
        window.showErrorMessage('Workspace analysis service not available')
        return
      }
 
      window.showInformationMessage('正在测试后端连接...')
      const isConnected = await workspaceAnalysisService.testBackendConnection()
 
      if (isConnected) {
        window.showInformationMessage('后端连接测试成功!')
      }
      else {
        window.showWarningMessage('后端连接测试失败,请检查:\n1. 后端服务是否启动\n2. 端口配置是否正确\n3. 网络连接是否正常')
      }
    }
    catch (error) {
      logger.error('Failed to test backend connection:', error)
      window.showErrorMessage(`连接测试失败: ${error instanceof Error ? error.message : String(error)}`)
    }
  })
 
  // 配置 Playwright MCP 工具命令
  useCommand('dalidev-vscode-server.setupPlaywrightMCP', async () => {
    try {
      window.showInformationMessage('正在配置 Playwright MCP 工具...')
 
      const success = ensurePlaywrightMCPConfig()
 
      if (success) {
        const hasConfig = hasPlaywrightMCPConfig()
        const message = hasConfig
          ? 'Playwright MCP 工具配置成功!请重启 AI 编辑器使配置生效。'
          : 'Playwright MCP 工具配置失败,请检查日志。'
 
        if (hasConfig) {
          window.showInformationMessage(message)
        }
        else {
          window.showErrorMessage(message)
        }
      }
      else {
        window.showErrorMessage('Playwright MCP 工具配置失败')
      }
    }
    catch (error) {
      logger.error('Failed to setup Playwright MCP:', error)
      window.showErrorMessage(`配置 Playwright MCP 工具失败: ${error instanceof Error ? error.message : String(error)}`)
    }
  })
 
  // 查看时间追踪数据命令
  useCommand('dalidev-vscode-server.viewTimeTracking', async () => {
    try {
      const workspaceRoot = getCurrentWorkspaceRoot()
      if (!workspaceRoot) {
        window.showWarningMessage('未找到工作区根目录')
        return
      }
 
      const timeTrackingFile = getTimeTrackingFile(workspaceRoot)
      if (fs.existsSync(timeTrackingFile)) {
        const content = fs.readFileSync(timeTrackingFile, 'utf-8')
        const data: TimeTrackingData = JSON.parse(content)
 
        const sessionCount = Object.keys(data.sessions).length
        const completedSessions = Object.values(data.sessions).filter(s => s.status === 'completed')
        const completedCount = completedSessions.length
 
        // 计算总代码统计
        let totalLinesAdded = 0
        let totalLinesRemoved = 0
        let totalCharactersAdded = 0
        let totalFilesCreated = 0
        let totalFilesModified = 0
        let totalSessionTime = 0
 
        completedSessions.forEach((session) => {
          if (session.codeGenerated) {
            totalLinesAdded += session.codeGenerated.totalLinesAdded || 0
            totalLinesRemoved += session.codeGenerated.totalLinesRemoved || 0
            totalCharactersAdded += session.codeGenerated.totalCharactersAdded || 0
            totalFilesCreated += session.codeGenerated.filesCreated || 0
            totalFilesModified += session.codeGenerated.filesModified || 0
          }
          if (session.duration) {
            totalSessionTime += session.duration
          }
        })
 
        const avgSessionTime = completedCount > 0 ? totalSessionTime / completedCount : 0
        const netLines = totalLinesAdded - totalLinesRemoved
 
        // 显示简短摘要
        window.showInformationMessage(
          `AI编辑器统计: ${completedCount}个会话, 生成${netLines}行代码, 平均用时${(avgSessionTime / 1000).toFixed(1)}秒`,
        )
 
        // 在输出面板显示详细统计
        const outputChannel = window.createOutputChannel('DaliDev 代码统计')
        outputChannel.clear()
        outputChannel.appendLine('📊 DaliDev AI编辑器代码生成统计报告')
        outputChannel.appendLine('='.repeat(50))
        outputChannel.appendLine(`📅 生成时间: ${new Date().toLocaleString()}`)
        outputChannel.appendLine(`📁 数据文件: ${timeTrackingFile}`)
        outputChannel.appendLine('')
 
        outputChannel.appendLine('📈 会话统计:')
        outputChannel.appendLine(`  总会话数: ${sessionCount}`)
        outputChannel.appendLine(`  已完成会话: ${completedCount}`)
        outputChannel.appendLine(`  平均会话时长: ${(avgSessionTime / 1000).toFixed(2)}秒`)
        outputChannel.appendLine(`  总工作时间: ${(totalSessionTime / 1000 / 60).toFixed(1)}分钟`)
        outputChannel.appendLine('')
 
        outputChannel.appendLine('💻 代码生成统计:')
        outputChannel.appendLine(`  新建文件: ${totalFilesCreated}个`)
        outputChannel.appendLine(`  修改文件: ${totalFilesModified}个`)
        outputChannel.appendLine(`  新增代码行: ${totalLinesAdded}行`)
        outputChannel.appendLine(`  删除代码行: ${totalLinesRemoved}行`)
        outputChannel.appendLine(`  净增代码行: ${netLines > 0 ? '+' : ''}${netLines}行`)
        outputChannel.appendLine(`  新增字符数: ${totalCharactersAdded.toLocaleString()}`)
        outputChannel.appendLine('')
 
        if (completedCount > 0) {
          outputChannel.appendLine('📋 最近会话详情:')
          const recentSessions = completedSessions
            .sort((a, b) => (b.endTime || 0) - (a.endTime || 0))
            .slice(0, 5)
 
          recentSessions.forEach((session, index) => {
            const startTime = session.startTime ? new Date(session.startTime).toLocaleString() : 'N/A'
            const duration = session.duration ? `${(session.duration / 1000).toFixed(1)}秒` : 'N/A'
            const prompt = session.metadata?.prompt || '无描述'
            const linesAdded = session.codeGenerated?.totalLinesAdded || 0
            const filesChanged = (session.codeGenerated?.filesCreated || 0) + (session.codeGenerated?.filesModified || 0)
 
            outputChannel.appendLine(`  ${index + 1}. ${session.sessionId}`)
            outputChannel.appendLine(`     时间: ${startTime}`)
            outputChannel.appendLine(`     时长: ${duration}`)
            outputChannel.appendLine(`     任务: ${prompt.substring(0, 50)}${prompt.length > 50 ? '...' : ''}`)
            outputChannel.appendLine(`     成果: +${linesAdded}行代码, ${filesChanged}个文件`)
            outputChannel.appendLine('')
          })
        }
 
        outputChannel.show()
 
        logger.info('时间追踪和代码统计:', {
          totalSessions: sessionCount,
          completedSessions: completedCount,
          totalLinesAdded,
          totalLinesRemoved,
          netLines,
          totalCharactersAdded,
          totalFilesCreated,
          totalFilesModified,
          avgSessionTimeSeconds: avgSessionTime / 1000,
          lastUpdated: new Date(data.lastUpdated).toISOString(),
        })
      }
      else {
        window.showInformationMessage('暂无时间追踪数据')
      }
    }
    catch (error) {
      logger.error('查看时间追踪数据失败:', error)
      window.showErrorMessage('查看时间追踪数据失败')
    }
  })
 
  // 监听主题变化
  const isDark = useIsDarkTheme()
  watchEffect(() => {
    logger.info(`Theme changed: ${isDark.value ? 'dark' : 'light'}`)
  })
 
  // 扩展停用时的清理
  return () => {
    logger.info('Extension Deactivated')
 
    // 清理全局变量
    delete (globalThis as any).__dalidevExtensionContext
 
    if (serverStarted) {
      stopServer().catch((error) => {
        logger.error('Failed to stop server during deactivation:', error)
      })
    }
  }
})