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 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 | import type express from 'express' import * as fs from 'node:fs' import * as path from 'node:path' import { trackCodeAdoption, trackCodeGeneration, trackError, trackPluginSession } from '@dalidev/core' import * as vscode from 'vscode' import { logger } from '../../utils/logger-adapter' import { IGNORE_FILE_PATTERNS } from '../core/constants' import { sendSSEMessage } from '../state/sse' import { getTaskById, updateTaskProgress } from '../state/tasks' // 采纳率跟踪相关接口 interface FileSnapshot { path: string content: string lines: number characters: number lastModified: number } interface AdoptionTrackingSession { sessionId: string workspaceRoot: string endTime: number observationEndTime: number // 观察期结束时间(任务结束后3分钟) originalFiles: Map<string, FileSnapshot> // 任务开始时的文件快照 taskCompletionFiles: Map<string, FileSnapshot> // 任务完成时的文件快照 finalFiles?: Map<string, FileSnapshot> // 观察期结束时的文件快照 adoptionRate?: number // 最终计算的采纳率 adoptionStatus: 'observing' | 'completed' | 'interrupted' watcher?: vscode.FileSystemWatcher } interface AdoptionAnalysisResult { sessionId: string adoptionRate: number totalChanges: number revertedChanges: number keptChanges: number // 新增精确计算相关字段 preciseAdoptionRate: number simpleAdoptionRate: number avgRevertPercentage: number totalRevertPercentage: number analysisDetails: { fileAnalysis: Array<{ path: string wasReverted: boolean revertPercentage: number }> } } interface FileWatcherSession { sessionId: string startTime: number endTime?: number watcher?: vscode.FileSystemWatcher metadata?: { prompt?: string workspaceRoot?: string taskTodos?: any[] } fileChanges: { created: string[] modified: string[] deleted: string[] } currentFileStats: Map<string, { lines: number, characters: number, size: number }> initialStats: Map<string, any> originalFiles: Map<string, FileSnapshot> // 添加原始文件快照存储 } const fileWatcherSessions = new Map<string, FileWatcherSession>() // 采纳率跟踪会话存储 const adoptionTrackingSessions = new Map<string, AdoptionTrackingSession>() // 检查是否应该忽略文件 function shouldIgnoreFile(filePath: string): boolean { // 确保路径以 / 开始,以便与IGNORE_FILE_PATTERNS中的正则表达式匹配 const normalizedPath = filePath.startsWith('/') ? filePath : `/${filePath}` // 还要检查原始相对路径,因为某些模式可能针对相对路径 const isIgnored = IGNORE_FILE_PATTERNS.some(pattern => pattern.test(normalizedPath) || pattern.test(filePath), ) // 额外检查一些常见的应该被忽略的目录和文件 const shouldIgnorePatterns = [ /^node_modules\//, /^\.git\//, /\.git$/, /^dist\//, /^build\//, /^\.next\//, /^\.nuxt\//, /^\.cache\//, /^\.tmp\//, /^\.temp\//, /^\.vscode\//, /^\.idea\//, /^coverage\//, /\.log$/, /\.tmp$/, /\.swp$/, /~$/, /\.DS_Store$/, /Thumbs\.db$/, ] const additionalIgnore = shouldIgnorePatterns.some(pattern => pattern.test(filePath)) return isIgnored || additionalIgnore } // 计算文件差异统计 function calculateFileDiff( originalContent: string | null, currentContent: string, ): { linesAdded: number, linesRemoved: number, linesModified: number } { if (!originalContent) { // 新创建的文件,所有行都是新增的 return { linesAdded: currentContent.split('\n').length, linesRemoved: 0, linesModified: 0, } } const originalLines = originalContent.split('\n') const currentLines = currentContent.split('\n') // 简化的差异算法 - 可以后续优化为更精确的 LCS 算法 let linesAdded = 0 let linesRemoved = 0 let linesModified = 0 const minLines = Math.min(originalLines.length, currentLines.length) // 比较共同长度部分 for (let i = 0; i < minLines; i++) { if (originalLines[i] !== currentLines[i]) { linesModified++ } } // 计算新增或删除的行 if (currentLines.length > originalLines.length) { linesAdded = currentLines.length - originalLines.length } else if (originalLines.length > currentLines.length) { linesRemoved = originalLines.length - currentLines.length } return { linesAdded, linesRemoved, linesModified } } // 获取文件的原始内容(任务开始时的快照) function getOriginalFileContent(filePath: string, workspaceRoot: string, originalFiles: Map<string, FileSnapshot>): string | null { // 首先从原始快照中查找 const originalSnapshot = originalFiles.get(filePath) if (originalSnapshot) { logger.info(` ✅ 从原始快照获取内容: ${filePath} (${originalSnapshot.content.length}字符)`) return originalSnapshot.content } // 如果没有原始快照,尝试读取当前文件(可能在任务开始前就存在) try { const fullPath = path.isAbsolute(filePath) ? filePath : path.join(workspaceRoot, filePath) if (fs.existsSync(fullPath)) { const content = fs.readFileSync(fullPath, 'utf-8') logger.info(` ⚠️ 从当前文件系统获取内容: ${filePath} (${content.length}字符)`) return content } logger.warn(` ❌ 文件不存在: ${fullPath}`) } catch (error) { logger.warn(` ❌ 无法读取原始文件内容: ${filePath}`, error) } logger.warn(` ❌ 无法获取原始内容: ${filePath}`) return null } // 精确计算代码生成统计 async function calculateAccurateCodeStats( session: FileWatcherSession, workspaceRoot: string, ): Promise<{ totalLinesAdded: number totalLinesRemoved: number totalLinesModified: number totalCharactersAdded: number totalCharactersRemoved: number filesCreated: number filesModified: number filesDeleted: number fileDetails: Array<{ path: string type: 'created' | 'modified' | 'deleted' linesAdded: number linesRemoved: number linesModified: number charactersAdded: number charactersRemoved: number }> }> { // 使用会话中保存的原始文件快照,而不是重新创建 const originalFiles = session.originalFiles const stats = { totalLinesAdded: 0, totalLinesRemoved: 0, totalLinesModified: 0, totalCharactersAdded: 0, totalCharactersRemoved: 0, filesCreated: session.fileChanges.created.length, filesModified: session.fileChanges.modified.length, filesDeleted: session.fileChanges.deleted.length, fileDetails: [] as Array<{ path: string type: 'created' | 'modified' | 'deleted' linesAdded: number linesRemoved: number linesModified: number charactersAdded: number charactersRemoved: number }>, } // 处理创建的文件 for (const filePath of session.fileChanges.created) { const currentStats = session.currentFileStats.get(filePath) if (currentStats) { const currentContent = fs.readFileSync( path.isAbsolute(filePath) ? filePath : path.join(workspaceRoot, filePath), 'utf-8', ) const diff = calculateFileDiff(null, currentContent) stats.totalLinesAdded += diff.linesAdded stats.totalCharactersAdded += currentStats.characters stats.fileDetails.push({ path: filePath, type: 'created', linesAdded: diff.linesAdded, linesRemoved: 0, linesModified: 0, charactersAdded: currentStats.characters, charactersRemoved: 0, }) logger.info(`✅ 精确统计 - 创建文件: ${filePath} (+${diff.linesAdded}行, +${currentStats.characters}字符)`) } } // 处理修改的文件 for (const filePath of session.fileChanges.modified) { const currentStats = session.currentFileStats.get(filePath) if (currentStats) { try { const currentContent = fs.readFileSync( path.isAbsolute(filePath) ? filePath : path.join(workspaceRoot, filePath), 'utf-8', ) const originalContent = getOriginalFileContent(filePath, workspaceRoot, originalFiles) // 添加调试日志 logger.info(`🔍 文件差异分析: ${filePath}`) logger.info(` 原始文件快照存在: ${originalFiles.has(filePath)}`) logger.info(` 原始内容长度: ${originalContent?.length || 0}`) logger.info(` 当前内容长度: ${currentContent.length}`) const diff = calculateFileDiff(originalContent, currentContent) logger.info(` 计算结果: +${diff.linesAdded}行, -${diff.linesRemoved}行, ~${diff.linesModified}行修改`) // 计算字符差异 const originalCharCount = originalContent?.length || 0 const charactersAdded = Math.max(0, currentStats.characters - originalCharCount) const charactersRemoved = Math.max(0, originalCharCount - currentStats.characters) stats.totalLinesAdded += diff.linesAdded stats.totalLinesRemoved += diff.linesRemoved stats.totalLinesModified += diff.linesModified stats.totalCharactersAdded += charactersAdded stats.totalCharactersRemoved += charactersRemoved stats.fileDetails.push({ path: filePath, type: 'modified', linesAdded: diff.linesAdded, linesRemoved: diff.linesRemoved, linesModified: diff.linesModified, charactersAdded, charactersRemoved, }) logger.info(`✅ 精确统计 - 修改文件: ${filePath} (+${diff.linesAdded}行, -${diff.linesRemoved}行, ~${diff.linesModified}行修改)`) } catch (error) { logger.warn(`计算文件差异失败: ${filePath}`, error) } } } // 处理删除的文件 for (const filePath of session.fileChanges.deleted) { const originalContent = getOriginalFileContent(filePath, workspaceRoot, originalFiles) if (originalContent) { const originalLines = originalContent.split('\n').length const originalChars = originalContent.length stats.totalLinesRemoved += originalLines stats.totalCharactersRemoved += originalChars stats.fileDetails.push({ path: filePath, type: 'deleted', linesAdded: 0, linesRemoved: originalLines, linesModified: 0, charactersAdded: 0, charactersRemoved: originalChars, }) logger.info(`✅ 精确统计 - 删除文件: ${filePath} (-${originalLines}行, -${originalChars}字符)`) } } logger.info(`📊 精确代码统计汇总: +${stats.totalLinesAdded}行, -${stats.totalLinesRemoved}行, ~${stats.totalLinesModified}行修改`) return stats } // 扫描工作区源码文件 function scanWorkspaceSourceFiles(workspaceRoot: string): string[] { const sourceFiles: string[] = [] const sourceExtensions = ['.ts', '.tsx', '.js', '.jsx', '.vue', '.py', '.java', '.go', '.rs', '.c', '.cpp', '.h', '.hpp'] function scanDirectory(dirPath: string, relativePath = ''): void { try { const items = fs.readdirSync(dirPath, { withFileTypes: true }) for (const item of items) { const itemPath = path.join(dirPath, item.name) const relativeItemPath = relativePath ? path.join(relativePath, item.name) : item.name // 检查是否应该忽略 if (shouldIgnoreFile(relativeItemPath)) { continue } if (item.isDirectory()) { // 递归扫描子目录,但限制深度 if (relativePath.split(path.sep).length < 10) { scanDirectory(itemPath, relativeItemPath) } } else if (item.isFile()) { // 检查是否为源码文件 const ext = path.extname(item.name) if (sourceExtensions.includes(ext)) { sourceFiles.push(relativeItemPath) } } } } catch (error) { logger.warn(`扫描目录失败: ${dirPath}`, error) } } scanDirectory(workspaceRoot) return sourceFiles } // 创建文件快照 function createFileSnapshot(filePath: string, workspaceRoot: string): FileSnapshot | null { try { const fullPath = path.isAbsolute(filePath) ? filePath : path.join(workspaceRoot, filePath) if (!fs.existsSync(fullPath)) { logger.debug(`文件不存在,无法创建快照: ${fullPath}`) return null } const content = fs.readFileSync(fullPath, 'utf-8') const stats = fs.statSync(fullPath) const snapshot = { path: filePath, content, lines: content.split('\n').length, characters: content.length, lastModified: stats.mtime.getTime(), } logger.debug(`成功创建文件快照: ${filePath} (${snapshot.lines}行, ${snapshot.characters}字符)`) return snapshot } catch (error) { logger.warn(`创建文件快照失败: ${filePath}`, error) return null } } // 计算文件采纳率 /** * 计算文件的代码采纳率 * 通过对比原始文件、任务完成时文件和观察期结束时文件的内容差异, * 来判断AI生成的代码是否被用户保留或还原 * * @param original - 任务开始前的原始文件快照 * @param taskCompletion - 任务完成时的文件快照(包含AI生成的代码) * @param final - 观察期结束时的最终文件快照 * @returns 返回包含是否被还原和还原百分比的对象 */ function calculateFileAdoptionRate( original: FileSnapshot | null, taskCompletion: FileSnapshot | null, final: FileSnapshot | null, ): { wasReverted: boolean, revertPercentage: number } { // 情况1: 如果任务完成时没有文件快照,或者任务完成时内容与原始内容相同 // 说明AI没有对此文件进行修改,返回0%还原率(即100%采纳率) if (!taskCompletion || (original && original.content === taskCompletion.content)) { return { wasReverted: false, revertPercentage: 0 } } // 情况2: 如果观察期结束时文件不存在(被删除) // 认为用户完全还原了AI的修改,返回100%还原率 if (!final) { return { wasReverted: true, revertPercentage: 100 } } // 情况3: 如果最终文件内容与原始文件内容完全相同 // 说明用户将AI的所有修改都还原了,返回100%还原率 if (original && original.content === final.content) { return { wasReverted: true, revertPercentage: 100 } } // 情况4: 如果最终文件内容与任务完成时内容完全相同 // 说明用户完全保留了AI的修改,返回0%还原率(即100%采纳率) if (taskCompletion.content === final.content) { return { wasReverted: false, revertPercentage: 0 } } // 情况5: 部分还原的情况,需要计算具体的还原百分比 // 使用内容长度差异作为简化的计算方法(实际场景可能需要更复杂的diff算法) // 获取各个阶段的文件内容长度 const originalLength = original?.content.length || 0 // 原始文件长度 const taskCompletionLength = taskCompletion.content.length // 任务完成时文件长度 const finalLength = final.content.length // 最终文件长度 // 计算AI修改带来的内容变化量(相对于原始文件) const changeFromOriginal = taskCompletionLength - originalLength // 计算最终文件相对于原始文件的变化量 const finalChangeFromOriginal = finalLength - originalLength // 如果AI没有带来实际的内容变化,返回0%还原率 if (changeFromOriginal === 0) { return { wasReverted: false, revertPercentage: 0 } } // 计算还原百分比 // 公式:(AI带来的变化量 - 最终保留的变化量) / AI带来的变化量 * 100 // 这个值表示有多少比例的AI修改被用户还原了 const revertPercentage = Math.max(0, Math.min(100, ((changeFromOriginal - finalChangeFromOriginal) / changeFromOriginal) * 100)) return { // 如果还原百分比超过50%,认为文件被主要还原了 wasReverted: revertPercentage > 50, // 返回四舍五入后的还原百分比 revertPercentage: Math.round(revertPercentage), } } // 启动采纳率跟踪 async function startAdoptionTracking( sessionId: string, workspaceRoot: string, fileChanges: { created: string[], modified: string[], deleted: string[] }, taskCompletionFiles: Map<string, FileSnapshot>, originalFiles: Map<string, FileSnapshot>, ): Promise<void> { const endTime = Date.now() const observationEndTime = endTime + 3 * 60 * 1000 // 3分钟后 // 不再重新扫描文件,使用传入的快照 logger.info(`启动采纳率跟踪: ${sessionId}`) logger.info(` - 工作区路径: ${workspaceRoot}`) logger.info(` - 文件变更统计: 创建 ${fileChanges.created.length} 个,修改 ${fileChanges.modified.length} 个,删除 ${fileChanges.deleted.length} 个`) logger.info(` - 原始文件快照: ${originalFiles.size} 个`) logger.info(` - 任务完成文件快照: ${taskCompletionFiles.size} 个`) logger.info(` - 任务完成文件列表: ${Array.from(taskCompletionFiles.keys()).join(', ')}`) // 创建文件监听器来观察后续变化 const workspaceFolder = vscode.workspace.workspaceFolders?.[0] if (!workspaceFolder) { throw new Error('未找到工作区文件夹') } const watchPatterns = [ 'src/**/*', 'components/**/*', 'pages/**/*', 'views/**/*', '*.ts', '*.tsx', '*.js', '*.jsx', '*.vue', '*.json', ] const includePattern = `{${watchPatterns.join(',')}}` const pattern = new vscode.RelativePattern(workspaceFolder, includePattern) const watcher = vscode.workspace.createFileSystemWatcher(pattern) const adoptionSession: AdoptionTrackingSession = { sessionId, workspaceRoot, endTime, observationEndTime, originalFiles, taskCompletionFiles, adoptionStatus: 'observing', watcher, } adoptionTrackingSessions.set(sessionId, adoptionSession) // 设置3分钟后的分析定时器 setTimeout(async () => { await finishAdoptionTracking(sessionId) }, 3 * 60 * 1000) logger.info(`启动采纳率跟踪: ${sessionId}, 观察期到 ${new Date(observationEndTime).toLocaleString()}`) } // 完成采纳率跟踪 async function finishAdoptionTracking(sessionId: string): Promise<void> { const adoptionSession = adoptionTrackingSessions.get(sessionId) if (!adoptionSession) { logger.warn(`采纳率跟踪会话不存在: ${sessionId}`) return } logger.info(`采纳率跟踪会话概要: ${sessionId}`) logger.info(` - 会话状态: ${adoptionSession.adoptionStatus}`) logger.info(` - 工作区路径: ${adoptionSession.workspaceRoot}`) logger.info(` - 原始文件数量: ${adoptionSession.originalFiles.size}`) logger.info(` - 任务完成文件数量: ${adoptionSession.taskCompletionFiles.size}`) logger.info(` - 任务完成文件列表: ${Array.from(adoptionSession.taskCompletionFiles.keys()).join(', ')}`) if (adoptionSession.adoptionStatus !== 'observing') { logger.info(`采纳率跟踪会话已结束: ${sessionId}`, adoptionSession.adoptionStatus) return } // 创建最终文件快照 const finalFiles = new Map<string, FileSnapshot>() for (const [filePath] of adoptionSession.taskCompletionFiles) { const snapshot = createFileSnapshot(filePath, adoptionSession.workspaceRoot) if (snapshot) { finalFiles.set(filePath, snapshot) } } adoptionSession.finalFiles = finalFiles adoptionSession.adoptionStatus = 'completed' // 清理监听器 if (adoptionSession.watcher) { adoptionSession.watcher.dispose() } // 分析采纳率 try { const analysisResult = analyzeAdoptionRate(adoptionSession) adoptionSession.adoptionRate = analysisResult.preciseAdoptionRate // 使用精确采纳率 logger.info(`采纳率分析完成: ${sessionId}`) logger.info(` - 精确采纳率: ${analysisResult.preciseAdoptionRate}% (基于还原百分比计算)`) logger.info(` - 简单采纳率: ${analysisResult.simpleAdoptionRate}% (基于文件数量计算)`) logger.info(` - 平均还原百分比: ${analysisResult.avgRevertPercentage.toFixed(2)}%`) logger.info(` - 文件统计: 总变更${analysisResult.totalChanges}, 保留${analysisResult.keptChanges}, 还原${analysisResult.revertedChanges}`) trackCodeAdoption({ sessionId, workspaceRoot: adoptionSession.workspaceRoot, totalChanges: analysisResult.totalChanges, revertedChanges: analysisResult.revertedChanges, keptChanges: analysisResult.keptChanges, adoptionRate: analysisResult.preciseAdoptionRate, // 使用精确采纳率 simpleAdoptionRate: analysisResult.simpleAdoptionRate, avgRevertPercentage: analysisResult.avgRevertPercentage, totalRevertPercentage: analysisResult.totalRevertPercentage, }) // 保存采纳率结果到文件 await saveAdoptionResult(analysisResult) } catch (error) { logger.error('采纳率分析失败:', error) } // 可选择性保留会话一段时间用于查询,或立即删除 setTimeout(() => { adoptionTrackingSessions.delete(sessionId) logger.info(`采纳率跟踪会话已清理: ${sessionId}`) }, 60 * 1000) // 1分钟后清理 } // 保存采纳率结果 async function saveAdoptionResult(result: AdoptionAnalysisResult): Promise<void> { try { const workspaceFolder = vscode.workspace.workspaceFolders?.[0] if (!workspaceFolder) return const adoptionResultsDir = path.join(workspaceFolder.uri.fsPath, '.dalidev', 'adoption-results') if (!fs.existsSync(adoptionResultsDir)) { fs.mkdirSync(adoptionResultsDir, { recursive: true }) } const timestamp = new Date().toISOString().replace(/[:.]/g, '-') const filename = `adoption-${result.sessionId}-${timestamp}.json` const filepath = path.join(adoptionResultsDir, filename) const data = { ...result, timestamp: Date.now(), date: new Date().toISOString(), // 添加计算方法说明 calculationMethod: { preciseAdoptionRate: '基于平均还原百分比计算: 100% - 平均还原百分比', simpleAdoptionRate: '基于文件数量计算: (总文件数 - 还原文件数) / 总文件数 * 100%', }, } fs.writeFileSync(filepath, JSON.stringify(data, null, 2)) logger.info(`采纳率结果已保存: ${filepath}`) } catch (error) { logger.error('保存采纳率结果失败:', error) } } // 分析采纳率 function analyzeAdoptionRate(session: AdoptionTrackingSession): AdoptionAnalysisResult { if (!session.finalFiles) { throw new Error('缺少最终文件快照') } logger.info(`开始分析采纳率: ${session.sessionId}`) logger.info(` - 任务完成文件数量: ${session.taskCompletionFiles.size}`) logger.info(` - 最终文件数量: ${session.finalFiles.size}`) const fileAnalysis: Array<{ path: string wasReverted: boolean revertPercentage: number }> = [] let totalChanges = 0 let revertedChanges = 0 // 检查是否有任务完成文件 if (session.taskCompletionFiles.size === 0) { logger.warn(`会话 ${session.sessionId} 没有任务完成文件,采纳率设为100%`) return { sessionId: session.sessionId, adoptionRate: 100, totalChanges: 0, revertedChanges: 0, keptChanges: 0, preciseAdoptionRate: 100, simpleAdoptionRate: 100, avgRevertPercentage: 0, totalRevertPercentage: 0, analysisDetails: { fileAnalysis: [] }, } } // 分析每个文件的采纳情况,使用精确的还原百分比计算 let totalRevertPercentage = 0 let fileCount = 0 for (const [filePath, taskCompletionSnapshot] of session.taskCompletionFiles) { const originalSnapshot = session.originalFiles.get(filePath) const finalSnapshot = session.finalFiles.get(filePath) logger.info(`分析文件采纳率: ${filePath}`) logger.info(` - 有原始快照: ${!!originalSnapshot}`) logger.info(` - 有任务完成快照: ${!!taskCompletionSnapshot}`) logger.info(` - 有最终快照: ${!!finalSnapshot}`) const analysis = calculateFileAdoptionRate(originalSnapshot, taskCompletionSnapshot, finalSnapshot) logger.info(` - 被还原: ${analysis.wasReverted}`) logger.info(` - 还原百分比: ${analysis.revertPercentage}%`) fileAnalysis.push({ path: filePath, wasReverted: analysis.wasReverted, revertPercentage: analysis.revertPercentage, }) // 累加还原百分比用于精确计算 totalRevertPercentage += analysis.revertPercentage fileCount += 1 // 保留原有的简单统计逻辑用于兼容性 totalChanges += 1 if (analysis.wasReverted) { revertedChanges += 1 } } // 使用更精确的采纳率计算方式:平均采纳率 = 100% - 平均还原百分比 const avgRevertPercentage = fileCount > 0 ? totalRevertPercentage / fileCount : 0 const preciseAdoptionRate = Math.round(100 - avgRevertPercentage) logger.info(`精确采纳率计算: 总还原百分比 ${totalRevertPercentage}%, 文件数 ${fileCount}, 平均还原 ${avgRevertPercentage.toFixed(2)}%, 精确采纳率 ${preciseAdoptionRate}%`) // 原有的简单采纳率计算(基于文件数量) const simpleAdoptionRate = totalChanges > 0 ? Math.round(((totalChanges - revertedChanges) / totalChanges) * 100) : 100 logger.info(`简单采纳率计算: 总文件 ${totalChanges}, 还原文件 ${revertedChanges}, 简单采纳率 ${simpleAdoptionRate}%`) if (preciseAdoptionRate !== simpleAdoptionRate) { logger.info(`📊 采纳率计算差异: 精确方式 ${preciseAdoptionRate}% vs 简单方式 ${simpleAdoptionRate}% (差异 ${Math.abs(preciseAdoptionRate - simpleAdoptionRate)}%)`) } // 使用精确的采纳率 const adoptionRate = preciseAdoptionRate return { sessionId: session.sessionId, adoptionRate, totalChanges, revertedChanges, keptChanges: totalChanges - revertedChanges, preciseAdoptionRate, simpleAdoptionRate, avgRevertPercentage, totalRevertPercentage, analysisDetails: { fileAnalysis }, } } export function registerAIEditorTrackingRoutes(app: express.Express) { // AI编辑器追踪 - 开始追踪 app.post('/ai-editor/start-tracking', async (req: any, res: any) => { try { const { sessionId, timestamp, metadata } = req.body if (!sessionId) return res.status(400).json({ success: false, error: '缺少必要参数: sessionId' }) if (fileWatcherSessions.has(sessionId)) { return res.status(400).json({ success: false, error: `会话 ${sessionId} 已存在` }) } const workspaceFolder = vscode.workspace.workspaceFolders?.[0] if (!workspaceFolder) return res.status(400).json({ success: false, error: '未找到工作区文件夹' }) const workspaceRoot = metadata?.workspaceRoot || workspaceFolder.uri.fsPath // 检查是否有正在观察期的采纳率跟踪会话,如果有则立即结束观察期 for (const [existingSessionId, adoptionSession] of adoptionTrackingSessions) { if (adoptionSession.adoptionStatus === 'observing' && adoptionSession.workspaceRoot === workspaceRoot) { logger.info(`检测到新任务开始,立即结束采纳率观察期: ${existingSessionId}`) // 如果是已经完成的任务,则直接进行采纳率收集 而不是认为被中断了 await finishAdoptionTracking(existingSessionId) } } logger.info('使用全量监听模式,监听工作区所有文件变更') // 创建初始文件快照用于采纳率分析 const originalFiles = new Map<string, FileSnapshot>() // 扫描当前工作区的源码文件并创建快照 try { const sourceFiles = scanWorkspaceSourceFiles(workspaceRoot) for (const filePath of sourceFiles) { const snapshot = createFileSnapshot(filePath, workspaceRoot) if (snapshot) { originalFiles.set(filePath, snapshot) } } logger.info(`创建了 ${originalFiles.size} 个文件的初始快照 (会话: ${sessionId})`) } catch (error) { logger.warn('创建初始文件快照失败', error) } // 创建多个更精确的监听模式,避免监听不需要的目录 const watchPatterns = [ 'src/**/*', 'components/**/*', 'pages/**/*', 'views/**/*', 'assets/**/*', 'utils/**/*', 'libs/**/*', 'lib/**/*', 'hooks/**/*', 'stores/**/*', 'store/**/*', 'types/**/*', 'apis/**/*', 'api/**/*', 'services/**/*', 'composables/**/*', 'plugins/**/*', 'middleware/**/*', 'layouts/**/*', 'styles/**/*', 'scss/**/*', 'css/**/*', 'public/**/*', '*.ts', '*.tsx', '*.js', '*.jsx', '*.vue', '*.json', '*.md', '*.css', '*.scss', '*.less', ] // 创建组合模式,排除常见的不需要监听的目录 const includePattern = `{${watchPatterns.join(',')}}` const pattern = new vscode.RelativePattern(workspaceFolder, includePattern) const watcher = vscode.workspace.createFileSystemWatcher(pattern) const session: FileWatcherSession = { sessionId, startTime: timestamp || Date.now(), metadata: { ...metadata, workspaceRoot, taskTodos: metadata?.taskTodos }, fileChanges: { created: [], modified: [], deleted: [] }, currentFileStats: new Map(), initialStats: new Map(), originalFiles, // 保存原始文件快照到会话中 watcher, } function getFileCurrentStats(filePath: string, root: string) { try { const fullPath = path.isAbsolute(filePath) ? filePath : path.join(root, filePath) if (!fs.existsSync(fullPath)) return { lines: 0, characters: 0, size: 0 } const content = fs.readFileSync(fullPath, 'utf-8') const lines = content.split('\n').length const characters = content.length const stats = fs.statSync(fullPath) return { lines, characters, size: stats.size } } catch (error) { logger.warn(`获取文件统计失败: ${filePath}`, error) return { lines: 0, characters: 0, size: 0 } } } // 检查路径是否为文件(而非文件夹) async function isFile(uri: vscode.Uri): Promise<boolean> { try { const stat = await vscode.workspace.fs.stat(uri) return stat.type === vscode.FileType.File } catch { // 如果文件不存在或无法访问,假设它是文件(例如删除事件) // 可以通过文件扩展名来判断 const fileName = path.basename(uri.fsPath) return fileName.includes('.') && !fileName.startsWith('.') } } watcher.onDidCreate(async (uri) => { const relativePath = path.relative(workspaceRoot, uri.fsPath) if (shouldIgnoreFile(relativePath)) return // 检查是否为文件(非文件夹) const isActualFile = await isFile(uri) if (!isActualFile) { return // 忽略文件夹创建 } if (!session.fileChanges.created.includes(relativePath) && !session.fileChanges.modified.includes(relativePath)) { session.fileChanges.created.push(relativePath) setTimeout(() => { try { const currentStats = getFileCurrentStats(relativePath, workspaceRoot) session.currentFileStats.set(relativePath, currentStats) logger.info(`✅ 文件创建已记录: ${relativePath} (${currentStats.lines}行, ${currentStats.characters}字符) (会话: ${sessionId})`) } catch (error) { logger.warn(`获取创建文件统计失败: ${relativePath}`, error) } }, 100) updateTaskProgress(sessionId, { status: 'in_progress', progress: Math.min(50 + (session.fileChanges.created.length + session.fileChanges.modified.length) * 5, 90), message: `文件变更中... (新增: ${session.fileChanges.created.length}, 修改: ${session.fileChanges.modified.length})`, }) } }) watcher.onDidChange(async (uri) => { const relativePath = path.relative(workspaceRoot, uri.fsPath) if (shouldIgnoreFile(relativePath)) return // 检查是否为文件(非文件夹) const isActualFile = await isFile(uri) if (!isActualFile) { return // 忽略文件夹修改 } try { const currentStats = getFileCurrentStats(relativePath, workspaceRoot) session.currentFileStats.set(relativePath, currentStats) if (session.fileChanges.created.includes(relativePath)) { logger.info(`文件已在新创建列表中,更新统计: ${relativePath} (${currentStats.lines}行, ${currentStats.characters}字符) (会话: ${sessionId})`) } else if (!session.fileChanges.modified.includes(relativePath)) { session.fileChanges.modified.push(relativePath) logger.info(`✅ 文件修改已记录: ${relativePath} (${currentStats.lines}行, ${currentStats.characters}字符) (会话: ${sessionId})`) updateTaskProgress(sessionId, { status: 'in_progress', progress: Math.min(50 + (session.fileChanges.created.length + session.fileChanges.modified.length) * 5, 90), message: `文件变更中... (新增: ${session.fileChanges.created.length}, 修改: ${session.fileChanges.modified.length})`, }) } } catch (error) { logger.warn(`获取修改文件统计失败: ${relativePath}`, error) } }) watcher.onDidDelete(async (uri) => { const relativePath = path.relative(workspaceRoot, uri.fsPath) if (shouldIgnoreFile(relativePath)) return // 对于删除事件,文件已不存在,通过文件名判断是否为文件 const fileName = path.basename(uri.fsPath) const isActualFile = fileName.includes('.') && !fileName.startsWith('.') if (!isActualFile) { return // 忽略文件夹删除 } if (session.fileChanges.created.includes(relativePath)) { const index = session.fileChanges.created.indexOf(relativePath) session.fileChanges.created.splice(index, 1) session.currentFileStats.delete(relativePath) logger.info(`✅ 文件创建后删除,从新创建列表移除: ${relativePath} (会话: ${sessionId})`) } else if (session.fileChanges.modified.includes(relativePath)) { const index = session.fileChanges.modified.indexOf(relativePath) session.fileChanges.modified.splice(index, 1) session.fileChanges.deleted.push(relativePath) logger.info(`✅ 文件修改后删除,从修改列表移除并记录删除: ${relativePath} (会话: ${sessionId})`) } else if (!session.fileChanges.deleted.includes(relativePath)) { session.fileChanges.deleted.push(relativePath) logger.info(`✅ 文件删除已记录: ${relativePath} (会话: ${sessionId})`) } updateTaskProgress(sessionId, { status: 'in_progress', progress: Math.min(50 + (session.fileChanges.created.length + session.fileChanges.modified.length) * 5, 90), message: `文件变更中... (新增: ${session.fileChanges.created.length}, 修改: ${session.fileChanges.modified.length}, 删除: ${session.fileChanges.deleted.length})`, }) }) fileWatcherSessions.set(sessionId, session) const progressMessage = 'AI编辑器会话开始,监听工作区所有文件变更' updateTaskProgress(sessionId, { status: 'started', progress: 0, message: progressMessage, metadata: session.metadata }) logger.info(`AI编辑器追踪会话开始: ${sessionId}`) // 添加插件会话开始埋点 try { await trackPluginSession('start', { sessionId, workspaceRoot, prompt: metadata?.prompt, tasksTotal: metadata?.taskTodos?.length || 0, }) } catch (analyticsError) { logger.warn('插件会话开始埋点失败:', analyticsError) } res.json({ success: true, message: `AI编辑器追踪会话 ${sessionId} 开始`, data: { sessionId, fileCount: '全部', sampleFiles: [], workspaceRoot } }) } catch (error) { logger.error('开始AI编辑器追踪失败:', error) res.status(500).json({ success: false, error: error instanceof Error ? error.message : String(error) }) } }) // AI编辑器追踪 - 结束追踪 app.post('/ai-editor/end-tracking', async (req: any, res: any) => { try { const { sessionId, timestamp, metadata } = req.body if (!sessionId) return res.status(400).json({ success: false, error: '缺少必要参数: sessionId' }) const session = fileWatcherSessions.get(sessionId) if (!session) return res.status(404).json({ success: false, error: `未找到会话 ${sessionId}` }) const endTime = timestamp || Date.now() const duration = endTime - session.startTime const workspaceRoot = session.metadata?.workspaceRoot || vscode.workspace.workspaceFolders?.[0]?.uri.fsPath || '' let codeGenerated: any = { totalLinesAdded: 0, totalLinesRemoved: 0, totalCharactersAdded: 0, totalCharactersRemoved: 0, filesCreated: session.fileChanges.created.length, filesModified: session.fileChanges.modified.length, filesDeleted: session.fileChanges.deleted.length, } // 使用精确的代码差异分析 const accurateStats = await calculateAccurateCodeStats(session, workspaceRoot) codeGenerated = { totalLinesAdded: accurateStats.totalLinesAdded, totalLinesRemoved: accurateStats.totalLinesRemoved, totalCharactersAdded: accurateStats.totalCharactersAdded, totalCharactersRemoved: accurateStats.totalCharactersRemoved, filesCreated: accurateStats.filesCreated, filesModified: accurateStats.filesModified, filesDeleted: accurateStats.filesDeleted, // 添加详细信息 fileDetails: accurateStats.fileDetails, totalLinesModified: accurateStats.totalLinesModified, } logger.info(`📊 精确代码统计完成: +${accurateStats.totalLinesAdded}行, -${accurateStats.totalLinesRemoved}行, ~${accurateStats.totalLinesModified}行修改, +${accurateStats.totalCharactersAdded}字符, -${accurateStats.totalCharactersRemoved}字符`) if (session.watcher) session.watcher.dispose() if (metadata?.taskTodos) { session.metadata = { ...session.metadata, taskTodos: metadata.taskTodos } } session.endTime = endTime // 创建包含精确修改信息的文件变更统计 const fileChangesWithStats = { created: session.fileChanges.created.map((filePath) => { const detail = codeGenerated.fileDetails?.find((d: any) => d.path === filePath) return { path: filePath, stats: { lines: detail?.linesAdded || 0, // 新创建文件的总行数等于新增行数 characters: detail?.charactersAdded || 0, size: session.currentFileStats.get(filePath)?.size || 0, // 添加详细的修改信息 linesAdded: detail?.linesAdded || 0, linesRemoved: detail?.linesRemoved || 0, linesModified: detail?.linesModified || 0, charactersAdded: detail?.charactersAdded || 0, charactersRemoved: detail?.charactersRemoved || 0, }, } }), modified: session.fileChanges.modified.map((filePath) => { const detail = codeGenerated.fileDetails?.find((d: any) => d.path === filePath) const currentStats = session.currentFileStats.get(filePath) return { path: filePath, stats: { lines: detail?.linesAdded || 0, // 对于修改文件,显示实际修改的行数 characters: detail?.charactersAdded || 0, size: currentStats?.size || 0, // 添加详细的修改信息 linesAdded: detail?.linesAdded || 0, linesRemoved: detail?.linesRemoved || 0, linesModified: detail?.linesModified || 0, charactersAdded: detail?.charactersAdded || 0, charactersRemoved: detail?.charactersRemoved || 0, // 保留文件总行数供参考 totalLines: currentStats?.lines || 0, totalCharacters: currentStats?.characters || 0, }, } }), deleted: session.fileChanges.deleted.map((filePath) => { const detail = codeGenerated.fileDetails?.find((d: any) => d.path === filePath) return { path: filePath, stats: { lines: detail?.linesRemoved || 0, // 删除的文件显示删除的行数 characters: detail?.charactersRemoved || 0, size: 0, // 添加详细的修改信息 linesAdded: 0, linesRemoved: detail?.linesRemoved || 0, linesModified: 0, charactersAdded: 0, charactersRemoved: detail?.charactersRemoved || 0, }, } }), } updateTaskProgress(sessionId, { status: 'completed', progress: 100, message: `AI编辑器会话完成,持续时间: ${(duration / 1000).toFixed(2)}秒`, metadata: session.metadata, result: { duration, codeGenerated, fileChangesWithStats }, }) fileWatcherSessions.delete(sessionId) // 启动采纳率跟踪 try { const workspaceFolder = vscode.workspace.workspaceFolders?.[0] if (!workspaceFolder) { throw new Error('未找到工作区文件夹') } // 创建任务完成时的文件快照 const taskCompletionFiles = new Map<string, FileSnapshot>() const allChangedFiles = [...new Set([...session.fileChanges.created, ...session.fileChanges.modified])] for (const filePath of allChangedFiles) { const snapshot = createFileSnapshot(filePath, workspaceRoot) if (snapshot) { taskCompletionFiles.set(filePath, snapshot) } } logger.info(`创建任务完成文件快照: ${taskCompletionFiles.size} 个文件`) await startAdoptionTracking(sessionId, session.metadata?.workspaceRoot || workspaceFolder.uri.fsPath, session.fileChanges, taskCompletionFiles, session.originalFiles) } catch (error) { trackError(error) logger.warn('启动采纳率跟踪失败:', error) } logger.info(`AI编辑器追踪会话结束: ${sessionId},持续时间: ${duration}ms`) // 添加插件会话结束和代码生成埋点 try { // 计算任务完成数 const completedTasks = metadata?.taskTodos?.filter((todo: any) => todo.status === 'completed')?.length || 0 const todosData = { created: metadata?.taskTodos?.filter((todo: any) => todo.status === 'pending')?.length || 0, updated: metadata?.taskTodos?.filter((todo: any) => todo.status === 'in_progress')?.length || 0, completed: completedTasks, } // 插件会话结束埋点 await trackPluginSession('end', { sessionId, workspaceRoot, duration, tasksTotal: metadata?.taskTodos?.length || 0, tasksCompleted: completedTasks, todoData: todosData, }) // 代码生成埋点 await trackCodeGeneration({ sessionId, workspaceRoot, filesCreated: codeGenerated.filesCreated, filesModified: codeGenerated.filesModified, filesDeleted: codeGenerated.filesDeleted, linesAdded: codeGenerated.totalLinesAdded, linesRemoved: codeGenerated.totalLinesRemoved, linesModified: codeGenerated.totalLinesModified || 0, charactersAdded: codeGenerated.totalCharactersAdded, charactersRemoved: codeGenerated.totalCharactersRemoved, }) } catch (analyticsError) { logger.warn('插件会话结束埋点失败:', analyticsError) } // 发起调查问卷:延迟3秒发送反馈问卷请求,给用户时间查看任务完成结果 try { const durationInSeconds = (duration / 1000).toFixed(2) setTimeout(() => { const task = getTaskById(sessionId) if (task && task.status === 'completed') { sendSSEMessage({ type: 'feedback_request', data: { sessionId, task, timestamp: Date.now() } }) } logger.info(`已为会话 ${sessionId} 发送反馈问卷请求 (持续时间: ${durationInSeconds}秒)`) }, 3000) // 延迟3秒发送 } catch (feedbackError) { logger.warn('发起调查问卷失败:', feedbackError) } res.json({ success: true, message: `AI编辑器追踪会话 ${sessionId} 结束`, data: { sessionId, duration, codeGenerated, fileChanges: session.fileChanges } }) } catch (error) { logger.error('结束AI编辑器追踪失败:', error) res.status(500).json({ success: false, error: error instanceof Error ? error.message : String(error) }) } }) // 获取AI编辑器追踪状态 app.get('/ai-editor/tracking/:sessionId', (req: any, res: any) => { const { sessionId } = req.params const session = fileWatcherSessions.get(sessionId) if (!session) return res.status(404).json({ success: false, error: `未找到会话 ${sessionId}` }) const currentTime = Date.now() const duration = currentTime - session.startTime res.json({ success: true, data: { sessionId: session.sessionId, startTime: session.startTime, duration, fileChanges: session.fileChanges, metadata: session.metadata, isActive: true } }) }) // 获取采纳率跟踪状态 app.get('/ai-editor/adoption/:sessionId', (req: any, res: any) => { const { sessionId } = req.params const adoptionSession = adoptionTrackingSessions.get(sessionId) if (!adoptionSession) { return res.status(404).json({ success: false, error: `未找到采纳率跟踪会话 ${sessionId}` }) } const currentTime = Date.now() const timeRemaining = adoptionSession.adoptionStatus === 'observing' ? Math.max(0, adoptionSession.observationEndTime - currentTime) : 0 res.json({ success: true, data: { sessionId: adoptionSession.sessionId, status: adoptionSession.adoptionStatus, endTime: adoptionSession.endTime, observationEndTime: adoptionSession.observationEndTime, timeRemaining, adoptionRate: adoptionSession.adoptionRate, totalFiles: adoptionSession.taskCompletionFiles.size, hasResult: adoptionSession.adoptionStatus === 'completed' && adoptionSession.adoptionRate !== undefined, }, }) }) // 获取所有采纳率结果 app.get('/ai-editor/adoption-results', (req: any, res: any) => { try { const workspaceFolder = vscode.workspace.workspaceFolders?.[0] if (!workspaceFolder) { return res.status(400).json({ success: false, error: '未找到工作区文件夹' }) } const adoptionResultsDir = path.join(workspaceFolder.uri.fsPath, '.dalidev', 'adoption-results') if (!fs.existsSync(adoptionResultsDir)) { return res.json({ success: true, data: [] }) } const files = fs.readdirSync(adoptionResultsDir) .filter(file => file.startsWith('adoption-') && file.endsWith('.json')) .sort((a, b) => { const statA = fs.statSync(path.join(adoptionResultsDir, a)) const statB = fs.statSync(path.join(adoptionResultsDir, b)) return statB.mtime.getTime() - statA.mtime.getTime() // 最新的在前 }) const results = files.slice(0, 50).map((file) => { // 最多返回50个结果 try { const content = fs.readFileSync(path.join(adoptionResultsDir, file), 'utf-8') return JSON.parse(content) } catch (error) { logger.warn(`读取采纳率结果文件失败: ${file}`, error) return null } }).filter(Boolean) res.json({ success: true, data: results }) } catch (error) { logger.error('获取采纳率结果失败:', error) res.status(500).json({ success: false, error: error instanceof Error ? error.message : String(error) }) } }) } |