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 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 | 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 2x 2x 2x 2x 2x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1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 10x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 6x 6x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 7x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 6x 1x 6x 2x 2x 1x 1x 10x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 5x 1x 1x 1x 5x 10x 68x 68x 68x 68x 68x 66x 66x 66x 66x 66x 68x 68x 68x 68x 68x 6x 1x 1x 1x 5x 5x 5x 5x 4x 6x 1x 1x 1x 1x 1x 6x 68x 68x 68x 68x 68x 7x 7x 7x 7x 7x 7x 7x 7x 7x 4x 4x 4x 4x 4x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 2x 2x 2x 2x 7x 3x 3x 3x 3x 3x 1x 1x 1x 1x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1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6x 6x 6x 3x 3x 3x 3x 6x 68x 68x 14x 11x 11x 11x 9x 9x 2x 3x 1x 1x 1x 1x 1x 11x 3x 6x 2x 2x 1x 1x 14x 68x 68x 7x 7x 7x 7x 7x 8x 8x 8x 8x 8x 14x 3x 2x 2x 1x 1x 1x 11x 14x 1x 1x 10x 13x 1x 1x 9x 9x 13x 1x 1x 8x 8x 8x 8x 8x 8x 8x 7x 7x 7x 7x 7x 7x 68x 68x 4x 7x 7x 7x 7x 7x 7x 7x 4x 68x 68x 6x 6x 6x 6x 6x 12x 4x 4x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 68x 68x 33x 33x 68x 68x 9x 9x 9x 9x 9x 68x 68x 6x 6x 6x 6x 5x 6x 6x 68x 68x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 1x 1x 2x 2x 2x 2x 2x 2x 2x 68x 68x 68x | /**
* SidebarProvider.js
*
* Proveedor de vista para la barra lateral de VS Code
* Muestra una interfaz web para configurar y generar documentos
*/
const vscode = require("vscode");
const fs = require("fs");
const path = require("path");
const { EXTENSION_VERSION, EXTENSION_INFO } = require("../config/version");
const { AzureDevOpsService } = require("../api/azureDevOps");
const { SharePointService } = require("../api/sharePoint");
const DevToolsGeneratorV2 = require("../generators/devToolsGeneratorV2");
const { SummaryService } = require("../api/copilot");
const { Logger } = require("../utils/logger");
const { PRReviewService } = require("../api/prReview");
const WorkItemPDFModal = require("./components/WorkItemPDFModal");
const WorkItemAttachmentsModal = require("./components/WorkItemAttachmentsModal");
const WorkItemRFCModal = require("./components/WorkItemRFCModal");
const WorkItemSubtasksModal = require("./components/WorkItemSubtasksModal");
const TestPlanModal = require("./components/TestPlanModal");
const {
getDefaultCopilotModels,
mapCopilotModels,
buildDetectedModelsLogMessage,
buildPRReviewStatusPayload,
buildAvailableModelsPayload,
} = require("./sidebarProviderHelpers");
const { persistSidebarConfig } = require("./sidebarConfigPersistence");
const {
buildCommitsByTicket,
buildDocumentGenerationPayload,
resolveDocumentOutputTarget,
} = require("./sidebarDocumentGenerationHelpers");
const { executeSidebarPrReview } = require("./sidebarPrReviewFlow");
// Constantes para límites de Azure DevOps
const AZURE_COMMENT_MAX_LENGTH = 150000; // 150KB límite seguro
const DEFAULT_LARGE_PR_AUTO_LITE_ENABLED = true;
const DEFAULT_LARGE_PR_FILES_THRESHOLD = 180;
const DEFAULT_LARGE_PR_BLOCKS_THRESHOLD = 24;
class SidebarProvider {
constructor(context, logger = null) {
this._view = null;
this._context = context;
this._logger = logger || new Logger(context); // Usar logger compartido o crear nuevo
this._disposables = []; // Array para event listeners y recursos
this._workItemPDFModal = null; // Modal de PDFs de work items
this._workItemAttachmentsModal = null; // Modal de adjuntos de work items
this._workItemRFCModal = null; // Modal de RFC de work items
this._workItemSubtasksModal = null; // Modal de subtareas base
this._testPlanModal = null; // Modal de generación de planes de prueba
}
/**
* Resuelve la vista del webview
*/
resolveWebviewView(webviewView) {
this._view = webviewView;
webviewView.webview.options = {
enableScripts: true,
localResourceRoots: [
this._context.extensionUri,
vscode.Uri.joinPath(this._context.extensionUri, "media"),
],
};
webviewView.webview.html = this._getHtmlContent(webviewView.webview);
// Inicializar contexto de PR review al abrir Sidebar
this._initializePRReviewContext();
// Manejar mensajes desde el webview con disposable
const messageListener = webviewView.webview.onDidReceiveMessage(
async (data) => {
// Log de todos los mensajes recibidos para debugging
this._logger.info(`📬 Mensaje recibido del webview: ${data.type || data.command || 'unknown'}`);
// Intentar delegar a WorkItemPDFModal primero
if (this._workItemPDFModal) {
const handled = await this._workItemPDFModal.handleMessage(data);
if (handled) {
return; // Mensaje manejado por el modal
}
}
if (this._workItemAttachmentsModal) {
const handled =
await this._workItemAttachmentsModal.handleMessage(data);
if (handled) {
return; // Mensaje manejado por el modal de adjuntos
}
}
if (this._workItemRFCModal) {
const handled = await this._workItemRFCModal.handleMessage(data);
if (handled) {
return; // Mensaje manejado por el modal RFC
}
}
if (this._workItemSubtasksModal) {
const handled = await this._workItemSubtasksModal.handleMessage(data);
if (handled) {
return; // Mensaje manejado por el modal de subtareas
}
}
if (this._testPlanModal) {
const handled = await this._testPlanModal.handleMessage(data);
if (handled) {
return; // Mensaje manejado por el modal de planes de prueba
}
}
switch (data.type) {
case "generate":
await this._handleGenerate(data.config);
break;
case "testConnection":
await this._handleTestConnection(data.service);
break;
case "loadConfig":
await this._handleLoadConfig();
break;
case "saveConfig":
await this._handleSaveConfig(data.config);
break;
case "selectStyle":
await this._handleSelectStyle(data.style);
break;
case "reviewPR":
await this._handleReviewPR(data);
break;
case "getAvailableModels":
await this._handleGetAvailableModels();
break;
case "openDocs":
await this._handleOpenDocs(data.doc);
break;
case "openWorkItemPDFModal":
await this._handleOpenWorkItemPDFModal();
break;
case "openTestPlanModal":
await this._handleOpenTestPlanModal();
break;
case "openWorkItemAttachmentsModal":
await this._handleOpenWorkItemAttachmentsModal();
break;
case "openWorkItemRFCModal":
await this._handleOpenWorkItemRFCModal();
break;
case "openWorkItemSubtasksModal":
await this._handleOpenWorkItemSubtasksModal();
break;
case "generateManualIndex":
await this._handleGenerateManualIndex();
break;
case "browseFolder":
await this._handleBrowseFolder(data.target);
break;
case "browseFileOrFolder":
await this._handleBrowseFileOrFolder(data.target);
break;
case "showError":
vscode.window.showErrorMessage(data.message);
break;
case "showInfo":
vscode.window.showInformationMessage(data.message);
break;
}
},
);
this._disposables.push(messageListener);
// Limpiar cuando la vista se oculte
webviewView.onDidDispose(() => {
this.dispose();
});
// Cargar configuración inicial
this._loadInitialConfig();
}
/**
* Inicializa contexto de revisión de PR para asegurar reglas base disponibles
* desde que el Sidebar se abre.
*/
async _initializePRReviewContext() {
try {
const reviewService = new PRReviewService(this._logger, this._context);
await reviewService.initializeReviewContext();
} catch (error) {
this._logger.warn(
`⚠️ No se pudo inicializar contexto de PR review al abrir Sidebar: ${error.message}`,
);
vscode.window.showWarningMessage(
"No se pudo inicializar el contexto de PR Review al abrir el Sidebar. La revision puede funcionar con contexto reducido.",
);
}
}
/**
* Carga la configuración inicial y la envía al webview
*/
async _loadInitialConfig() {
const config = vscode.workspace.getConfiguration("gbot");
if (this._view) {
this._view.webview.postMessage({
type: "configLoaded",
config: {
azureOrg: config.get("azure.organization"),
azurePat: this._maskSensitiveValue(config.get("azure.pat")),
devopsOrg: config.get("devops.organization"),
devopsPat: this._maskSensitiveValue(config.get("devops.pat")),
sharePointPath: config.get("sharepoint.localPath"),
sharePointUrl: config.get("sharepoint.baseUrl"),
subdirectories: config.get("sharepoint.subdirectories"),
outputDir: config.get("template.outputDir"),
summaryMethod: config.get("summary.method") || "local",
docxConversionMode: config.get("docxConversionMode") || "js",
standardsSqlPath: config.get("standards.sqlPath"),
standardsAngularPath: config.get("standards.angularPath"),
standardsDotnetPath: config.get("standards.dotnetPath"),
standardsSsisPath: config.get("standards.ssisPath"),
ignoredFilePatterns: config.get("prReview.ignoredFilePatterns") || [],
autoLiteModeEnabled:
config.get(
"prReview.autoLiteMode.enabled",
DEFAULT_LARGE_PR_AUTO_LITE_ENABLED,
) !== false,
autoLiteModeFilesThreshold: config.get(
"prReview.autoLiteMode.filesThreshold",
DEFAULT_LARGE_PR_FILES_THRESHOLD,
),
autoLiteModeBlocksThreshold: config.get(
"prReview.autoLiteMode.blocksThreshold",
DEFAULT_LARGE_PR_BLOCKS_THRESHOLD,
),
lastPaseNumber: config.get("lastPaseNumber"),
lastTitle: config.get("lastTitle"),
lastObjective: config.get("lastObjective"),
lastAreaAfectada: config.get("lastAreaAfectada"),
},
});
}
}
/**
* Enmascara un valor sensible mostrando solo los últimos 4 caracteres
*/
_maskSensitiveValue(value) {
if (!value || typeof value !== "string") return "";
if (value.length <= 4) return "****";
return "****" + value.slice(-4);
}
/**
* Verifica si un valor es enmascarado (no debe sobrescribir el original)
*/
_isMaskedValue(value) {
return (
typeof value === "string" && value.startsWith("****") && value.length <= 8
);
}
/**
* Maneja la generación de documento
*/
async _handleGenerate(configData) {
// Limpiar y mostrar Output Channel AUTOMÁTICAMENTE
this._logger.clear();
this._logger.show(true); // true = no robar foco, pero visible
// Usar Progress Notification (ventana flotante)
return vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: "G-Bot",
cancellable: false,
},
async (progress) => {
return this._executeGeneration(configData, progress);
},
);
}
/**
* Ejecuta la generación con progreso
*/
async _executeGeneration(configData, progress) {
const config = vscode.workspace.getConfiguration("gbot");
const paseNumber = configData.paseNumber;
const title = configData.paseTitle || `Pase a Producción ${paseNumber}`;
const objective = configData.paseObjective || "Implementación de mejoras";
const areaAfectada = configData.areaAfectada || "Sistema de Aplicaciones";
try {
this._sendMessage("status", {
message: "🚀 Iniciando generación...",
type: "info",
});
this._logger.info(`🚀 Iniciando generación para pase: ${paseNumber}`);
this._logger.info(` Título: ${title}`);
this._logger.info(` Objetivo: ${objective}`);
this._logger.info(` Área: ${areaAfectada}`);
this._logger.info("");
// Progreso: 10%
progress.report({ increment: 10, message: "Buscando Pull Requests..." });
this._sendProgress(10, "🔍 Buscando Pull Requests...");
this._logger.info("📋 PASO 1/8: Buscando Pull Requests...");
const devopsOrg = config.get("devops.organization");
const devopsPat = config.get("devops.pat");
if (!devopsOrg || !devopsPat) {
throw new Error(
"❌ Configuración de Azure DevOps incompleta. Verifica organización y PAT.",
);
}
const azureService = new AzureDevOpsService(
devopsOrg,
devopsPat,
this._logger.info.bind(this._logger),
);
const pullRequests =
await azureService.searchPullRequestsByPase(paseNumber);
if (pullRequests.length === 0) {
this._logger.warn(
`⚠️ No se encontraron PRs para el pase ${paseNumber}`,
);
this._sendMessage("status", {
message: `⚠️ No se encontraron PRs para ${paseNumber}`,
type: "warning",
});
} else {
this._logger.info(
`✅ Encontrados ${pullRequests.length} Pull Request(s)`,
);
}
this._logger.info("");
// Progreso: 20%
progress.report({ increment: 10, message: "Obteniendo commits..." });
this._sendProgress(20, "📝 Obteniendo commits de PRs...");
this._logger.info("📋 PASO 2/8: Obteniendo commits de PRs...");
const commitsByPR =
await azureService.getCommitsForPullRequests(pullRequests);
const totalCommits = Object.values(commitsByPR).reduce(
(acc, commits) => acc + commits.length,
0,
);
this._logger.info(
`✅ Procesados ${totalCommits} commit(s) de ${pullRequests.length} PR(s)`,
);
this._logger.info("");
// Progreso: 30%
progress.report({ increment: 10, message: "Consultando Work Items..." });
this._sendProgress(30, "🎯 Consultando Work Items...");
this._logger.info("📋 PASO 3/8: Consultando Work Items...");
const azureOrg = config.get("azure.organization");
const azurePat = config.get("azure.pat");
if (!azureOrg || !azurePat) {
throw new Error(
"❌ Configuración de Azure incompleta. Verifica organización y PAT principal.",
);
}
// Validar paseNumber para prevenir inyección WIQL
if (!/^[A-Za-z0-9\-_]{1,50}$/.test(paseNumber)) {
throw new Error(
"❌ Número de pase inválido. Solo se permiten letras, números, guiones y guiones bajos.",
);
}
const wiql = `SELECT [System.Id], [System.Title], [System.State]
FROM WorkItems
WHERE [System.Tags] CONTAINS '${paseNumber}'
ORDER BY [System.Id]`;
const workItems = await azureService.queryWorkItems(
wiql,
azureOrg,
azurePat,
);
this._logger.info(
`✅ Encontrados ${workItems.length} Work Item(s) para el pase ${paseNumber}`,
);
if (workItems.length === 0) {
this._logger.warn(
`⚠️ No se encontraron Work Items con tag '${paseNumber}'`,
);
this._sendMessage("status", {
message: `⚠️ No se encontraron Work Items con tag '${paseNumber}'`,
type: "warning",
});
}
this._logger.info("");
// Progreso: 40%
progress.report({
increment: 10,
message: "Listando documentos SharePoint...",
});
this._sendProgress(40, "📂 Listando documentos SharePoint...");
this._logger.info("📋 PASO 4/8: Listando documentos SharePoint...");
const spPath = config.get("sharepoint.localPath");
const spUrl = config.get("sharepoint.baseUrl");
const spSubdirs = config.get("sharepoint.subdirectories");
if (!spPath || !spUrl) {
throw new Error(
"❌ Configuración de SharePoint incompleta. Verifica ruta local y URL base.",
);
}
const spService = new SharePointService(
spPath,
spUrl,
this._logger.info.bind(this._logger),
spSubdirs,
);
const spDocuments = await spService.listAllDocuments();
const totalDocs = Object.values(spDocuments).reduce(
(acc, docs) => acc + docs.length,
0,
);
this._logger.info(
`✅ Encontrados ${totalDocs} documento(s) en ${
Object.keys(spDocuments).length
} categoría(s)`,
);
this._logger.info("");
// Progreso: 50%
const summaryMethod = config.get("summary.method");
const useCopilot = summaryMethod === "copilot";
progress.report({
increment: 10,
message: useCopilot
? "Generando resumen con Copilot..."
: "Generando resumen...",
});
this._sendProgress(
50,
useCopilot
? "🤖 Generando resumen inteligente con Copilot..."
: "📋 Generando resumen básico de commits...",
);
this._logger.info(
`📋 PASO 5/8: Generando resumen (${
useCopilot ? "Copilot" : "básico"
})...`,
);
const commitsByTicket = buildCommitsByTicket(commitsByPR);
const summaryService = new SummaryService(
this._logger.info.bind(this._logger),
);
const summary = await summaryService.generateSummary(
commitsByTicket,
useCopilot,
);
this._logger.info(
`✅ Resumen generado usando ${useCopilot ? "Copilot" : "método básico"}`,
);
this._logger.info("");
// Progreso: 60%
progress.report({ increment: 10, message: "Preparando datos..." });
this._sendProgress(60, "⚙️ Preparando datos para documento...");
this._logger.info("📋 PASO 6/8: Preparando datos para documento...");
const data = buildDocumentGenerationPayload({
paseNumber,
title,
objective,
areaAfectada,
summary,
workItems,
pullRequests,
azureOrg,
spDocuments,
solicitante: config.get("template.solicitante"),
});
this._logger.info("✅ Datos preparados correctamente");
this._logger.info(` PRs: ${pullRequests.length}`);
this._logger.info(` Work Items: ${workItems.length}`);
this._logger.info(` Documentos SP: ${totalDocs}`);
this._logger.info("");
// Progreso: 70%
progress.report({ increment: 10, message: "Validando configuración..." });
this._sendProgress(70, "� Validando configuración...");
this._logger.info("📋 PASO 7/8: Validando configuración de salida...");
const outputDir = config.get("template.outputDir");
const { finalFilename, outputPath } = resolveDocumentOutputTarget({
outputDir,
requestedFileName: configData.filename,
paseNumber,
fileExists: (targetPath) => fs.existsSync(targetPath),
joinPath: (basePath, fileName) => path.join(basePath, fileName),
});
this._logger.info(`✅ Directorio de salida: ${outputDir}`);
this._logger.info(`📄 Archivo de salida: ${finalFilename}`);
this._logger.info("");
// Progreso: 80%
progress.report({
increment: 10,
message: "Generando documento Word...",
});
this._sendProgress(80, "📄 Generando documento Word...");
this._logger.info("📋 PASO 8/8: Generando documento Word...");
const wordGenerator = new DevToolsGeneratorV2();
await wordGenerator.generateDocument(data, outputPath);
this._logger.info("✅ Documento Word generado");
this._logger.info("");
// Progreso: 100%
progress.report({ increment: 20, message: "¡Completado!" });
this._sendProgress(100, "✅ Documento generado exitosamente!");
this._logger.info("=".repeat(60));
this._logger.info(`🎉 ¡DOCUMENTO GENERADO EXITOSAMENTE!`);
this._logger.info("=".repeat(60));
this._logger.info(`📦 Archivo: ${finalFilename}`);
this._logger.info(`📁 Ubicación: ${outputPath}`);
this._logger.info(
`📏 Tamaño: ${(fs.statSync(outputPath).size / 1024).toFixed(2)} KB`,
);
this._logger.info("=".repeat(60));
if (!fs.existsSync(outputPath)) {
throw new Error(
`❌ El archivo no se generó correctamente: ${outputPath}`,
);
}
this._sendMessage("status", {
message: `✅ Documento generado: ${finalFilename}`,
type: "success",
});
const action = await vscode.window.showInformationMessage(
`🎉 ¡Documento generado! ${finalFilename}`,
"📁 Abrir Carpeta",
"📄 Abrir Documento",
"📋 Ver Log",
);
if (action === "📁 Abrir Carpeta") {
await this._openFileOrFolder(outputDir);
} else if (action === "📄 Abrir Documento") {
await this._openFileOrFolder(outputPath);
} else if (action === "📋 Ver Log") {
await this._logger.openLogFile();
}
} catch (error) {
this._logger.error("=".repeat(60));
this._logger.error(`💥 ERROR EN GENERACIÓN`);
this._logger.error("=".repeat(60));
this._logger.error(`Mensaje: ${error.message}`);
if (error.stack) {
this._logger.error(`Stack trace:`);
this._logger.error(error.stack);
}
this._logger.error("=".repeat(60));
this._logger.error(
`📋 Log guardado en: ${this._logger.getLogFilePath()}`,
);
this._logger.error("=".repeat(60));
this._sendMessage("status", {
message: `❌ Error: ${error.message}`,
type: "error",
});
const action = await vscode.window.showErrorMessage(
`💥 Error en generación: ${error.message}`,
"📋 Ver Log Completo",
"📁 Abrir Carpeta de Logs",
);
if (action === "📋 Ver Log Completo") {
await this._logger.openLogFile();
} else if (action === "📁 Abrir Carpeta de Logs") {
const logDir = path.dirname(this._logger.getLogFilePath());
await this._openFileOrFolder(logDir);
}
}
}
/**
* Envía actualización de progreso al webview
*/
_sendProgress(percentage, message) {
this._sendMessage("progress", {
percentage: percentage,
message: message,
});
}
/**
* Abre un archivo o carpeta de forma segura usando la API de VS Code
*/
async _openFileOrFolder(filePath) {
if (!fs.existsSync(filePath)) {
vscode.window.showErrorMessage(`El archivo no existe: ${filePath}`);
return;
}
try {
const uri = vscode.Uri.file(filePath);
await vscode.env.openExternal(uri);
this._logger.info(`✅ Archivo abierto: ${path.basename(filePath)}`);
} catch (error) {
this._logger.error(`Error abriendo: ${error.message}`);
vscode.window.showErrorMessage(
`No se pudo abrir el archivo: ${path.basename(filePath)}`,
);
}
}
/**
* Maneja prueba de conexión
*/
async _handleTestConnection(service) {
try {
this._sendMessage("status", {
message: `🔄 Probando conexión a ${service}...`,
type: "info",
});
const config = vscode.workspace.getConfiguration("gbot");
if (service === "azure") {
// Test Azure DevOps connection
const azureOrg = config.get("azure.organization");
const azurePat = config.get("azure.pat");
if (!azureOrg || !azurePat) {
throw new Error(
"❌ Configuración de Azure incompleta. Verifica organización y PAT.",
);
}
this._logger.info(`🔍 Probando conexión a Azure DevOps...`);
this._logger.info(` Organización: ${azureOrg}`);
// Test simple con API de proyectos en lugar de WIQL
const axios = require("axios");
const testUrl = `https://dev.azure.com/${azureOrg}/_apis/projects?api-version=7.0`;
try {
const response = await axios.get(testUrl, {
auth: {
username: "",
password: azurePat,
},
});
if (response.data && response.data.count >= 0) {
this._logger.info(`✅ Conexión exitosa a Azure DevOps`);
this._logger.info(
` Proyectos disponibles: ${response.data.count}`,
);
this._sendMessage("status", {
message: `✅ Conexión a Azure DevOps exitosa (${response.data.count} proyectos)`,
type: "success",
});
vscode.window.showInformationMessage(
`✅ Conexión exitosa a Azure DevOps: ${azureOrg} (${response.data.count} proyectos)`,
);
} else {
throw new Error("Respuesta inesperada del servidor");
}
} catch (error) {
throw new Error(
`Error de conexión: ${error.response?.status || error.message}`,
);
}
} else if (service === "sharepoint") {
// Test SharePoint connection
const spPath = config.get("sharepoint.localPath");
const spUrl = config.get("sharepoint.baseUrl");
if (!spPath || !spUrl) {
throw new Error(
"❌ Configuración de SharePoint incompleta. Verifica ruta local y URL.",
);
}
this._logger.info(`🔍 Probando acceso a SharePoint local...`);
this._logger.info(` Ruta: ${spPath}`);
if (!fs.existsSync(spPath)) {
throw new Error(`❌ La ruta de SharePoint no existe: ${spPath}`);
}
const spService = new SharePointService(
spPath,
spUrl,
this._logger.info.bind(this._logger),
);
const docs = await spService.listAllDocuments();
const totalDocs = Object.values(docs).reduce(
(acc, docList) => acc + docList.length,
0,
);
this._logger.info(
`✅ Acceso exitoso - ${totalDocs} documento(s) encontrados`,
);
this._sendMessage("status", {
message: `✅ Conexión a SharePoint exitosa (${totalDocs} docs)`,
type: "success",
});
vscode.window.showInformationMessage(
`✅ Acceso exitoso a SharePoint: ${totalDocs} documento(s) encontrados`,
);
}
} catch (error) {
this._logger.error(`\n💥 ERROR EN PRUEBA DE CONEXIÓN:`);
this._logger.error(` Servicio: ${service}`);
this._logger.error(` Mensaje: ${error.message}`);
this._sendMessage("status", {
message: `❌ Error conectando a ${service}: ${error.message}`,
type: "error",
});
vscode.window.showErrorMessage(
`💥 Error conectando a ${service}: ${error.message}`,
);
}
}
/**
* Maneja la apertura de documentación
*/
async _handleOpenDocs(docType) {
try {
// Intentar obtener URL de VS Code settings
const config = vscode.workspace.getConfiguration("gbot");
let url = config.get("documentation.url");
// Si no está en settings, intentar desde config.json
if (!url) {
try {
const fs = require("fs");
const path = require("path");
const configPath = path.join(
__dirname,
"..",
"..",
"..",
"config.json",
);
if (fs.existsSync(configPath)) {
const configContent = fs.readFileSync(configPath, "utf-8");
const configData = JSON.parse(configContent);
url = configData.documentation?.url;
}
} catch (error) {
this._logger.warn(`⚠️ No se pudo leer config.json: ${error.message}`);
}
}
// Si se especifica un tipo de documento, agregar ancla o path
if (docType === "ignoredPatterns" && url) {
// Asegurar que termine con /
if (!url.endsWith("/")) {
url += "/";
}
url += "GUIA_ARCHIVOS_IGNORADOS_PR.md";
}
if (url) {
// Abrir URL en navegador externo
await vscode.env.openExternal(vscode.Uri.parse(url));
this._logger.info(`📚 Abriendo documentación: ${url}`);
vscode.window.showInformationMessage(
"📚 Abriendo documentación en el navegador...",
);
} else {
const message =
"⚠️ URL de documentación no configurada. " +
"Verifica gbot.documentation.url en Settings o documentation.url en config.json.";
vscode.window.showWarningMessage(message);
this._logger.warn(message);
}
} catch (error) {
this._logger.error(`❌ Error abriendo documentación: ${error.message}`);
vscode.window.showErrorMessage(
`❌ No se pudo abrir la documentación: ${error.message}`,
);
}
}
/**
* Maneja la carga de configuración
*/
async _handleLoadConfig() {
await this._loadInitialConfig();
}
/**
* Maneja el guardado de configuración
*/
async _handleSaveConfig(configData) {
try {
this._logger.info("💾 Guardando configuración...");
const config = vscode.workspace.getConfiguration("gbot");
await persistSidebarConfig(
config,
configData,
this._isMaskedValue.bind(this),
);
this._logger.info("✅ Configuración guardada exitosamente");
// Notificación de VS Code (abajo a la derecha)
vscode.window.showInformationMessage(
"✅ Configuración guardada correctamente",
);
this._sendMessage("status", {
message: "✅ Configuración guardada correctamente",
type: "success",
});
} catch (error) {
this._logger.error(`❌ Error al guardar configuración: ${error.message}`);
this._logger.error(`Stack trace: ${error.stack}`);
// Notificación de error de VS Code
vscode.window.showErrorMessage(
`❌ Error al guardar configuración: ${error.message}`,
);
this._sendMessage("status", {
message: `❌ Error guardando configuración: ${error.message}`,
type: "error",
});
throw error;
}
}
/**
* Maneja selección de estilo
*/
async _handleSelectStyle(style) {
try {
// Aquí podrías guardar la preferencia de estilo
const config = vscode.workspace.getConfiguration("gbot");
await config.update("style.selected", style, true);
this._sendMessage("status", {
message: `✅ Estilo cambiado a: ${style}`,
type: "success",
});
} catch (error) {
this._sendMessage("status", {
message: `❌ Error cambiando estilo: ${error.message}`,
type: "error",
});
}
}
/**
* Maneja la selección de carpeta mediante explorador
*/
async _handleBrowseFolder(target) {
try {
const options = {
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
openLabel: "Seleccionar carpeta",
};
const uri = await vscode.window.showOpenDialog(options);
if (uri && uri[0]) {
const selectedPath = uri[0].fsPath;
// Enviar la ruta seleccionada al webview
this._view?.webview.postMessage({
type: "folderSelected",
target: target,
path: selectedPath,
});
this._logger.info(
`📂 Carpeta seleccionada (${target}): ${selectedPath}`,
);
}
} catch (error) {
this._logger.error(`❌ Error seleccionando carpeta: ${error.message}`);
vscode.window.showErrorMessage(
`❌ Error seleccionando carpeta: ${error.message}`,
);
}
}
/**
* Maneja la selección de archivo o carpeta mediante explorador
*/
async _handleBrowseFileOrFolder(target) {
try {
// Mostrar menú de opciones
const choice = await vscode.window.showQuickPick(
[
{ label: "📄 Archivo", value: "file" },
{ label: "📁 Carpeta", value: "folder" },
],
{
placeHolder: "¿Qué deseas seleccionar?",
},
);
if (!choice) return;
let uri;
if (choice.value === "file") {
const options = {
canSelectFiles: true,
canSelectFolders: false,
canSelectMany: false,
openLabel: "Seleccionar archivo",
filters: {
Documentos: ["txt", "md", "html", "doc", "docx"],
Todos: ["*"],
},
};
uri = await vscode.window.showOpenDialog(options);
} else {
const options = {
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
openLabel: "Seleccionar carpeta",
};
uri = await vscode.window.showOpenDialog(options);
}
if (uri && uri[0]) {
const selectedPath = uri[0].fsPath;
// Enviar la ruta seleccionada al webview
this._view?.webview.postMessage({
type: "folderSelected",
target: target,
path: selectedPath,
});
this._logger.info(`📂 Ruta seleccionada (${target}): ${selectedPath}`);
}
} catch (error) {
this._logger.error(`❌ Error seleccionando ruta: ${error.message}`);
vscode.window.showErrorMessage(
`❌ Error seleccionando ruta: ${error.message}`,
);
}
}
/**
* Maneja la revisión de Pull Request
*/
async _handleReviewPR(data) {
try {
const config = vscode.workspace.getConfiguration("gbot");
await executeSidebarPrReview({
data,
config,
context: this._context,
logger: this._logger,
sendMessage: (type, payload) => this._sendMessage(type, payload),
commentMaxLength: AZURE_COMMENT_MAX_LENGTH,
autoLiteDefaults: {
autoLiteModeEnabled: DEFAULT_LARGE_PR_AUTO_LITE_ENABLED,
filesThreshold: DEFAULT_LARGE_PR_FILES_THRESHOLD,
blocksThreshold: DEFAULT_LARGE_PR_BLOCKS_THRESHOLD,
},
});
} catch (error) {
this._logger.error(`❌ Error en revisión de PR: ${error.message}`);
this._sendMessage(
"prReviewStatus",
buildPRReviewStatusPayload("error", { errorMessage: error.message }),
);
}
}
/**
* Obtiene los modelos de IA disponibles de GitHub Copilot
*/
async _handleGetAvailableModels() {
try {
this._logger.info("🔍 Detectando modelos de IA disponibles...");
// Obtener modelos disponibles del selector de Copilot
const models = await vscode.lm.selectChatModels({
vendor: "copilot",
});
if (!models || models.length === 0) {
this._logger.warn(
"⚠️ No se detectaron modelos de GitHub Copilot. Usando GPT-4o por defecto.",
);
this._sendMessage(
"availableModels",
buildAvailableModelsPayload({
models: getDefaultCopilotModels(),
}),
);
return;
}
// Mapear modelos a formato simple
const modelList = mapCopilotModels(models);
this._logger.info(buildDetectedModelsLogMessage(modelList));
// Obtener modelo previamente guardado
const config = vscode.workspace.getConfiguration("gbot");
const savedModel = config.get("prReview.aiModel", "gpt-4o");
// Enviar modelos al webview con modelo guardado
this._sendMessage(
"availableModels",
buildAvailableModelsPayload({
models: modelList,
savedModel: savedModel,
}),
);
} catch (error) {
this._logger.error(
`❌ Error detectando modelos: ${error.message}. Usando GPT-4o por defecto.`,
);
// Obtener modelo guardado incluso en caso de error
const config = vscode.workspace.getConfiguration("gbot");
const savedModel = config.get("prReview.aiModel", "gpt-4o");
// Fallback: enviar modelo por defecto
this._sendMessage(
"availableModels",
buildAvailableModelsPayload({
models: getDefaultCopilotModels(),
savedModel: savedModel,
}),
);
}
}
/**
* Envía mensaje al webview
*/
_sendMessage(type, data) {
if (this._view) {
this._view.webview.postMessage({ type, ...data });
}
}
/**
* Refresca la vista
*/
refresh() {
if (this._view) {
this._view.webview.html = this._getHtmlContent(this._view.webview);
}
}
/**
* Genera el contenido HTML del webview
*/
_getHtmlContent(webview) {
// Generar nonce para CSP
const nonce = this._getNonce();
// URIs para CSS y JS del modal de work items
const workitemModalCssUri = webview.asWebviewUri(
vscode.Uri.joinPath(
this._context.extensionUri,
"media",
"workitem-modal.css",
),
);
const workitemModalJsUri = webview.asWebviewUri(
vscode.Uri.joinPath(
this._context.extensionUri,
"media",
"workitem-modal.js",
),
);
const workitemAttachmentsModalJsUri = webview.asWebviewUri(
vscode.Uri.joinPath(
this._context.extensionUri,
"media",
"workitem-attachments-modal.js",
),
);
const workitemRfcModalJsUri = webview.asWebviewUri(
vscode.Uri.joinPath(
this._context.extensionUri,
"media",
"workitem-rfc-modal.js",
),
);
const workitemSubtasksModalJsUri = webview.asWebviewUri(
vscode.Uri.joinPath(
this._context.extensionUri,
"media",
"workitem-subtasks-modal.js",
),
);
return `<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src ${webview.cspSource} 'unsafe-inline'; script-src 'nonce-${nonce}'; img-src ${webview.cspSource} https:;">
<title>G-Bot</title>
<link rel="stylesheet" href="${workitemModalCssUri}">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: var(--vscode-font-family);
font-size: var(--vscode-font-size);
color: var(--vscode-foreground);
background: var(--vscode-editor-background);
padding: 12px;
}
/* Tab Navigation */
.tab-bar {
display: flex;
gap: 2px;
margin-bottom: 15px;
background: var(--vscode-editorGroupHeader-tabsBackground);
border-radius: 4px;
padding: 3px;
position: sticky;
top: 0;
z-index: 100;
}
.tab-button {
flex: 1;
padding: 8px 4px;
background: transparent;
color: var(--vscode-foreground);
border: none;
border-radius: 3px;
cursor: pointer;
font-size: 11px;
font-family: var(--vscode-font-family);
transition: all 0.2s;
text-align: center;
opacity: 0.7;
margin-bottom: 0;
width: auto;
}
.tab-button:hover {
background: var(--vscode-list-hoverBackground);
opacity: 1;
}
.tab-button.active {
background: var(--vscode-button-background);
color: var(--vscode-button-foreground);
opacity: 1;
}
.tab-button .tab-icon {
display: block;
font-size: 16px;
margin-bottom: 2px;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
h2 {
font-size: 14px;
margin-bottom: 12px;
color: var(--vscode-foreground);
border-bottom: 1px solid var(--vscode-panel-border);
padding-bottom: 8px;
}
h3 {
font-size: 12px;
margin: 15px 0 10px 0;
color: var(--vscode-descriptionForeground);
}
.section {
margin-bottom: 20px;
}
.form-group {
margin-bottom: 12px;
}
label {
display: block;
margin-bottom: 4px;
font-size: 13px;
color: var(--vscode-foreground);
}
input[type="checkbox"] {
width: auto;
margin: 0;
}
input, select, textarea {
width: 100%;
padding: 6px 8px;
background: var(--vscode-input-background);
color: var(--vscode-input-foreground);
border: 1px solid var(--vscode-input-border);
border-radius: 2px;
font-size: 13px;
font-family: var(--vscode-font-family);
}
input:focus, select:focus, textarea:focus {
outline: 1px solid var(--vscode-focusBorder);
}
textarea {
min-height: 60px;
resize: vertical;
}
button {
padding: 8px 14px;
background: var(--vscode-button-background);
color: var(--vscode-button-foreground);
border: none;
border-radius: 2px;
cursor: pointer;
font-size: 13px;
font-family: var(--vscode-font-family);
width: 100%;
margin-bottom: 8px;
transition: background 0.2s;
}
button:hover {
background: var(--vscode-button-hoverBackground);
}
button.secondary {
background: var(--vscode-button-secondaryBackground);
color: var(--vscode-button-secondaryForeground);
}
button.secondary:hover {
background: var(--vscode-button-secondaryHoverBackground);
}
.style-selector {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 8px;
}
.style-option {
padding: 12px;
background: var(--vscode-input-background);
border: 2px solid var(--vscode-input-border);
border-radius: 4px;
cursor: pointer;
text-align: center;
transition: all 0.2s;
}
.style-option:hover {
border-color: var(--vscode-focusBorder);
}
.style-option.selected {
border-color: var(--vscode-button-background);
background: var(--vscode-list-hoverBackground);
}
.style-option .emoji {
font-size: 24px;
display: block;
margin-bottom: 4px;
}
.style-option .name {
font-size: 11px;
font-weight: bold;
}
.status {
padding: 10px;
margin-bottom: 15px;
border-radius: 4px;
font-size: 12px;
display: none;
}
.status.info {
background: var(--vscode-inputValidation-infoBackground);
border: 1px solid var(--vscode-inputValidation-infoBorder);
}
.status.success {
background: var(--vscode-testing-message-info-background);
border: 1px solid var(--vscode-testing-message-info-lineBackground);
}
.status.error {
background: var(--vscode-inputValidation-errorBackground);
border: 1px solid var(--vscode-inputValidation-errorBorder);
}
.quick-actions {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 15px;
}
.document-actions-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 8px;
margin-top: 10px;
}
.document-actions-grid .action-button {
margin-bottom: 0;
text-align: left;
border: 1px solid var(--vscode-panel-border);
background: var(--vscode-button-secondaryBackground);
color: var(--vscode-button-secondaryForeground);
border-radius: 6px;
padding: 10px 12px;
min-height: 54px;
display: flex;
align-items: center;
gap: 8px;
}
.document-actions-grid .action-button:hover {
background: var(--vscode-button-secondaryHoverBackground);
}
.document-actions-grid .action-icon {
font-size: 16px;
width: 20px;
text-align: center;
flex-shrink: 0;
}
.document-actions-grid .action-text {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.document-actions-grid .action-title {
font-size: 12px;
font-weight: 600;
line-height: 1.25;
}
.document-actions-grid .action-subtitle {
font-size: 11px;
opacity: 0.85;
line-height: 1.2;
}
.collapsible {
cursor: pointer;
user-select: none;
}
.collapsible::before {
content: '▼ ';
display: inline-block;
transition: transform 0.2s;
}
.collapsible.collapsed::before {
transform: rotate(-90deg);
}
.collapsible-content {
max-height: 2000px;
overflow-y: auto;
overflow-x: hidden;
transition: max-height 0.3s ease-out;
}
.collapsible-content.hidden {
max-height: 0;
overflow: hidden;
}
</style>
</head>
<body>
<div id="status" class="status"></div>
<!-- Tab Navigation -->
<div class="tab-bar">
<button class="tab-button active" data-tab="reviewer">
<span class="tab-icon">🔍</span>
Revisor
</button>
<button class="tab-button" data-tab="documents">
<span class="tab-icon">📄</span>
Documentos
</button>
<button class="tab-button" data-tab="config">
<span class="tab-icon">⚙️</span>
Config
</button>
<button class="tab-button" data-tab="info">
<span class="tab-icon">ℹ️</span>
Info
</button>
</div>
<!-- Tab 1: Revisor de PR (Default) -->
<div class="tab-content active" id="tab-reviewer">
<p style="font-size: 11px; color: var(--vscode-descriptionForeground); margin-bottom: 15px;">
Analiza automáticamente Pull Requests usando GitHub Copilot y agrega comentarios de revisión en Azure DevOps.
</p>
<div class="form-group">
<label>URL del Pull Request:</label>
<input type="text" id="prUrl" placeholder="https://dev.azure.com/org/project/_git/repo/pullrequest/12345">
<small style="color: var(--vscode-descriptionForeground);">Pega el enlace completo del PR desde Azure DevOps</small>
</div>
<div class="form-group">
<label>Tipo de Revisión:</label>
<select id="reviewType">
<option value="auto">🤖 Auto-detectar tecnologías</option>
<option value="sql">🗄️ SQL - Base de Datos</option>
<option value="angular">🅰️ Angular - Frontend</option>
<option value="dotnet">⚙️ .NET - Backend</option>
<option value="ssis">📊 SSIS - ETL</option>
</select>
</div>
<div class="form-group">
<label>Nivel de Detalle:</label>
<select id="reviewDetail">
<option value="standard">📋 Estándar</option>
<option value="detailed">📝 Detallado</option>
<option value="critical">🚨 Solo Críticos</option>
</select>
</div>
<div class="form-group">
<label>Modelo de IA:</label>
<select id="aiModel">
<option value="loading">🔄 Cargando modelos disponibles...</option>
</select>
<small style="color: var(--vscode-descriptionForeground);" id="aiModelStatus">Detectando modelos de GitHub Copilot...</small>
</div>
<div class="form-group" style="margin-top: 15px;">
<label style="display: flex; align-items: flex-start; gap: 8px; cursor: pointer;">
<input type="checkbox" id="autoComment" checked style="margin-top: 2px; flex-shrink: 0;">
<span style="flex: 1;">Publicar comentarios automáticamente en Azure DevOps</span>
</label>
</div>
<div class="form-group" style="margin-top: 10px;">
<label style="display: flex; align-items: flex-start; gap: 8px; cursor: pointer;">
<input type="checkbox" id="includeSuggestions" checked style="margin-top: 2px; flex-shrink: 0;">
<span style="flex: 1;">Incluir sugerencias de mejora</span>
</label>
</div>
<button id="btnReviewPR" style="font-size: 14px; padding: 12px;">
🔍 Iniciar Revisión
</button>
<div id="prReviewStatus" style="margin-top: 15px; padding: 10px; border-radius: 4px; display: none; background: var(--vscode-inputValidation-infoBackground); border-left: 3px solid var(--vscode-inputValidation-infoBorder);">
<p style="margin: 0; font-size: 12px;" id="prReviewMessage"></p>
</div>
</div>
<!-- Tab 2: Documentos (Estilo + Datos) -->
<div class="tab-content" id="tab-documents">
<!-- Selección de Estilo -->
<div class="section">
<h2 class="collapsible" data-action="toggleSection">🎨 Estilo de Documento</h2>
<div class="collapsible-content">
<div class="style-selector">
<div class="style-option selected" data-style="default">
<span class="emoji">📘</span>
<span class="name">Default</span>
</div>
<div class="style-option" data-style="formal">
<span class="emoji">📕</span>
<span class="name">Formal</span>
</div>
<div class="style-option" data-style="modern">
<span class="emoji">📗</span>
<span class="name">Modern</span>
</div>
<div class="style-option" data-style="colorful">
<span class="emoji">📙</span>
<span class="name">Colorful</span>
</div>
</div>
</div>
</div>
<!-- Datos del Documento -->
<div class="section">
<h2 class="collapsible" data-action="toggleSection">📄 Datos del Documento</h2>
<div class="collapsible-content">
<div class="form-group">
<label>Número de Pase:</label>
<input type="text" id="paseNumber" placeholder="PN-7501">
</div>
<div class="form-group">
<label>Título del Pase:</label>
<input type="text" id="paseTitle" placeholder="Implementación de nuevas funcionalidades">
</div>
<div class="form-group">
<label>Objetivo:</label>
<textarea id="paseObjective" placeholder="Descripción del objetivo del pase..."></textarea>
</div>
<div class="form-group">
<label>Áreas Afectadas:</label>
<textarea id="areaAfectada" placeholder="Módulos y áreas que serán impactadas..."></textarea>
</div>
<div class="form-group">
<label>Nombre del Archivo:</label>
<input type="text" id="filename" placeholder="Pase-2026-001.docx">
<small style="color: var(--vscode-descriptionForeground);">Si no se especifica, se usará "Pase-[número].docx"</small>
</div>
<div class="document-actions-grid">
<button id="btnGenerateDoc" class="action-button" type="button">
<span class="action-icon">📄</span>
<span class="action-text">
<span class="action-title">Generar Resumen del Pase</span>
<span class="action-subtitle">Documento principal del pase</span>
</span>
</button>
<button id="btnOpenTestPlanModal" class="action-button" type="button">
<span class="action-icon">🧪</span>
<span class="action-text">
<span class="action-title">Generar Plan de Pruebas</span>
<span class="action-subtitle">Escenarios funcionales con IA</span>
</span>
</button>
<button id="btnOpenPDFModal" class="action-button" type="button">
<span class="action-icon">📑</span>
<span class="action-text">
<span class="action-title">Generar PDFs de Work Items</span>
<span class="action-subtitle">Exportación masiva en PDF</span>
</span>
</button>
<button id="btnOpenAttachmentsModal" class="action-button" type="button">
<span class="action-icon">📎</span>
<span class="action-text">
<span class="action-title">Extraer Adjuntos</span>
<span class="action-subtitle">Descarga de archivos en lote</span>
</span>
</button>
<button id="btnOpenRFCModal" class="action-button" type="button">
<span class="action-icon">🧾</span>
<span class="action-text">
<span class="action-title">Generar RFC</span>
<span class="action-subtitle">Comentario técnico desde WI</span>
</span>
</button>
<button id="btnOpenSubtasksModal" class="action-button" type="button">
<span class="action-icon">🧩</span>
<span class="action-text">
<span class="action-title">Generar Subtareas Base</span>
<span class="action-subtitle">Plantilla editable para ADO</span>
</span>
</button>
</div>
</div>
</div>
<div class="section">
<h2 class="collapsible collapsed" data-action="toggleSection">⚙️ Configuración de Documentos</h2>
<div class="collapsible-content hidden">
<h3>SharePoint</h3>
<div class="form-group">
<label>Ruta SharePoint Local:</label>
<div style="display: flex; gap: 8px;">
<input type="text" id="sharePointPath" placeholder="C:\\Users\\...\\OneDrive" readonly style="flex: 1; cursor: pointer;" title="Clic en 'Buscar' para seleccionar carpeta">
<button id="browseSharePointPath" type="button" style="min-width: 80px;">📂 Buscar</button>
</div>
<small style="color: var(--vscode-descriptionForeground);">Usar botón 'Buscar' para seleccionar la carpeta de SharePoint local</small>
</div>
<div class="form-group">
<label>URL Base SharePoint:</label>
<input type="text" id="sharePointUrl" placeholder="https://miempresa.sharepoint.com/sites/...">
<small style="color: var(--vscode-descriptionForeground);">Copiar URL desde SharePoint (se limpiarán automáticamente parámetros extra)</small>
</div>
<div class="form-group">
<label>Subdirectorios (separados por coma):</label>
<textarea id="subdirectories" placeholder="Plan de Montaje,PPT CRT,VB DB,VB CRT,Ciclos de Prueba,Pruebas Preprod"></textarea>
</div>
<h3>Documento</h3>
<div class="form-group">
<label>Directorio de Salida:</label>
<div style="display: flex; gap: 8px;">
<input type="text" id="outputDir" placeholder="C:\\Documentos" readonly style="flex: 1; cursor: pointer;" title="Clic en 'Buscar' para seleccionar carpeta">
<button id="browseOutputDir" type="button" style="min-width: 80px;">📂 Buscar</button>
</div>
<small style="color: var(--vscode-descriptionForeground);">Usar botón 'Buscar' para seleccionar el directorio donde se guardará el documento</small>
</div>
<div class="form-group">
<label>Método de Resumen:</label>
<select id="summaryMethod">
<option value="local">🧠Local (Análisis Inteligente)</option>
<option value="copilot">🤖GitHub Copilot</option>
</select>
</div>
<div class="form-group">
<label>Modo de Conversión DOCX a PDF:</label>
<select id="docxConversionMode">
<option value="js">JS (mammoth + pdf-lib)</option>
<option value="office">Office (Word/LibreOffice)</option>
<option value="auto">Auto</option>
<option value="manual">Manual</option>
</select>
<small style="color: var(--vscode-descriptionForeground);">Controla cómo se convierte DOCX a PDF al generar adjuntos</small>
</div>
<button id="btnSaveConfigDocuments">💾 Guardar Configuración</button>
</div>
</div>
</div>
<!-- Tab 3: Configuración (Acciones Rápidas + Config) -->
<div class="tab-content" id="tab-config">
<!-- Acciones Rápidas -->
<div class="section">
<h2 class="collapsible" data-action="toggleSection">⚡ Acciones Rápidas</h2>
<div class="collapsible-content">
<div class="quick-actions">
<button id="btnTestAzure" style="font-size: 14px; padding: 12px;">🔗 Test Azure</button>
<button id="btnLoadConfig" style="font-size: 14px; padding: 12px;">🔄 Recargar</button>
</div>
</div>
</div>
<!-- Configuración -->
<div class="section">
<h2 class="collapsible collapsed" data-action="toggleSection">⚙️ Configuración</h2>
<div class="collapsible-content hidden">
<h3>Azure DevOps (Boards)</h3>
<div class="form-group">
<label>Organización Azure Boards:</label>
<input type="text" id="azureOrg" placeholder="mi-organizacion">
</div>
<div class="form-group">
<label>PAT Azure Boards:</label>
<input type="password" id="azurePat" placeholder="Personal Access Token">
</div>
<h3>Azure DevOps (Git/PRs)</h3>
<div class="form-group">
<label>Organización Azure DevOps:</label>
<input type="text" id="devopsOrg" placeholder="mi-organizacion">
</div>
<div class="form-group">
<label>PAT Azure DevOps:</label>
<input type="password" id="devopsPat" placeholder="Personal Access Token">
</div>
<h3>Estándares de Código (PR Review)</h3>
<div class="form-group">
<label>Ruta Estándares SQL:</label>
<div style="display: flex; gap: 8px;">
<input type="text" id="standardsSqlPath" placeholder="C:\\Users\\...\\OneDrive\\Thunderlight - Documentación_2026\\Estándares" readonly style="flex: 1; cursor: pointer;" title="Clic en 'Buscar' para seleccionar archivo o carpeta">
<button id="browseStandardsSql" type="button" style="min-width: 80px;">📂 Buscar</button>
</div>
<small style="color: var(--vscode-descriptionForeground);">Archivo (.txt, .md, .html, .doc, .docx) o directorio con múltiples archivos</small>
</div>
<div class="form-group">
<label>Ruta Estándares Angular:</label>
<div style="display: flex; gap: 8px;">
<input type="text" id="standardsAngularPath" placeholder="C:\\Users\\...\\OneDrive\\Thunderlight - Documentación_2026\\Estándares" readonly style="flex: 1; cursor: pointer;" title="Clic en 'Buscar' para seleccionar archivo o carpeta">
<button id="browseStandardsAngular" type="button" style="min-width: 80px;">📂 Buscar</button>
</div>
<small style="color: var(--vscode-descriptionForeground);">Archivo (.txt, .md, .html, .doc, .docx) o directorio con múltiples archivos</small>
</div>
<div class="form-group">
<label>Ruta Estándares .NET:</label>
<div style="display: flex; gap: 8px;">
<input type="text" id="standardsDotnetPath" placeholder="C:\\Users\\...\\OneDrive\\Thunderlight - Documentación_2026\\Estándares" readonly style="flex: 1; cursor: pointer;" title="Clic en 'Buscar' para seleccionar archivo o carpeta">
<button id="browseStandardsDotnet" type="button" style="min-width: 80px;">📂 Buscar</button>
</div>
<small style="color: var(--vscode-descriptionForeground);">Archivo (.txt, .md, .html, .doc, .docx) o directorio con múltiples archivos</small>
</div>
<div class="form-group">
<label>Ruta Estándares SSIS:</label>
<div style="display: flex; gap: 8px;">
<input type="text" id="standardsSsisPath" placeholder="C:\\Users\\...\\OneDrive\\Thunderlight - Documentación_2026\\Estándares" readonly style="flex: 1; cursor: pointer;" title="Clic en 'Buscar' para seleccionar archivo o carpeta">
<button id="browseStandardsSsis" type="button" style="min-width: 80px;">📂 Buscar</button>
</div>
<small style="color: var(--vscode-descriptionForeground);">Archivo (.txt, .md, .html, .doc, .docx) o directorio con múltiples archivos</small>
</div>
<h3>Archivos Ignorados (PR Review)</h3>
<div class="form-group">
<label>Patrones de archivos ignorados:</label>
<textarea id="ignoredFilePatterns" placeholder="\\.vs/\n\\.dacpac$\nnode_modules/" rows="8" style="font-family: 'Courier New', monospace; font-size: 11px;"></textarea>
<small style="color: var(--vscode-descriptionForeground); display: block; margin-top: 4px;">
<strong>📝 Un patrón por línea.</strong> Expresiones regulares (case-insensitive).<br>
<strong>Ejemplos:</strong><br>
• <code>\\.dacpac$</code> - Archivos .dacpac<br>
• <code>\\.vs/</code> - Carpeta .vs<br>
• <code>bin/</code> - Carpeta bin<br>
Ver <a href="#" id="linkOpenDocsIgnoredPatterns" style="color: var(--vscode-textLink-foreground);">documentación completa</a>
</small>
</div>
<h3>Modo Liviano Automático (PR Grandes)</h3>
<div class="form-group">
<label style="display: flex; align-items: center; gap: 8px;">
<input type="checkbox" id="autoLiteModeEnabled">
Activar modo liviano automático para PRs grandes
</label>
<small style="color: var(--vscode-descriptionForeground); display: block; margin-top: 4px;">
Reduce riesgo de out-of-memory: desactiva sugerencias y baja detalle <code>detailed → standard</code> cuando el PR supera umbrales.
</small>
</div>
<div class="form-group" style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
<div>
<label>Umbral por archivos:</label>
<input type="number" id="autoLiteModeFilesThreshold" min="1" step="1" placeholder="180">
<small style="color: var(--vscode-descriptionForeground);">Activa modo liviano si el PR supera este número de archivos.</small>
</div>
<div>
<label>Umbral por bloques:</label>
<input type="number" id="autoLiteModeBlocksThreshold" min="1" step="1" placeholder="24">
<small style="color: var(--vscode-descriptionForeground);">Activa modo liviano si el PR supera este número de bloques.</small>
</div>
</div>
<button id="btnSaveConfig">💾 Guardar Configuración</button>
</div>
</div>
</div>
<!-- Tab 4: Información -->
<div class="tab-content" id="tab-info">
<div class="section">
<h2>ℹ️ Información</h2>
<p style="font-size: 12px; line-height: 1.6; color: var(--vscode-descriptionForeground);">
<strong>${EXTENSION_INFO.displayName} v${EXTENSION_VERSION}</strong><br>
<strong>Creado por:</strong> Gerald Barquero Valverde<br>
<strong>Equipo:</strong> ${EXTENSION_INFO.publisher} Team<br>
<em>En colaboración con GitHub Copilot</em><br><br>
Genera documentos Word con datos de:<br>
• Azure DevOps (Work Items & PRs)<br>
• SharePoint (Documentos)<br>
• Configuraciones personalizables<br><br>
4 estilos predefinidos disponibles.
</p>
</div>
</div>
<!-- Modal de Generación de PDFs de Work Items -->
<div id="workItemPDFModal" class="modal" hidden>
<div class="modal-overlay"></div>
<div class="modal-dialog">
<div class="modal-header">
<h2>📑 Generar PDFs de Work Items</h2>
<button class="modal-close" id="closeWorkItemModal">✕</button>
</div>
<div class="modal-body">
<!-- Información sobre la generación de PDFs -->
<div class="modal-info-box" style="margin-bottom: 20px; padding: 12px; background-color: var(--vscode-editor-inactiveSelectionBackground); border-left: 3px solid var(--vscode-editorInfo-foreground); border-radius: 3px;">
<p style="margin: 0; font-size: 13px; color: var(--vscode-foreground);">
<strong>ℹ️ Generación de PDFs con contenido completo:</strong> El PDF se generará obteniendo datos desde la API REST de Azure DevOps y construyendo el documento programáticamente.
Incluye <strong>descripción, criterios de aceptación, comentarios con imágenes embebidas, metadata del work item, child items, y enlaces clickeables</strong>. El formato HTML se preserva (negritas, listas, párrafos).
</p>
</div>
<!-- Configuración de campos a incluir -->
<div class="modal-section" style="margin-bottom: 15px; padding: 12px; background-color: var(--vscode-input-background); border-radius: 3px;">
<h3 style="margin: 0 0 10px 0; font-size: 13px; font-weight: 600;">📝 Campos a incluir en el PDF</h3>
<div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px;">
<label style="display: flex; align-items: center; font-size: 12px; cursor: pointer;">
<input type="checkbox" class="field-checkbox" value="description" checked style="margin-right: 6px;">
Descripción
</label>
<label style="display: flex; align-items: center; font-size: 12px; cursor: pointer;">
<input type="checkbox" class="field-checkbox" value="acceptanceCriteria" checked style="margin-right: 6px;">
Criterios de Aceptación
</label>
<label style="display: flex; align-items: center; font-size: 12px; cursor: pointer;">
<input type="checkbox" class="field-checkbox" value="iteration" checked style="margin-right: 6px;">
Iteración
</label>
<label style="display: flex; align-items: center; font-size: 12px; cursor: pointer;">
<input type="checkbox" class="field-checkbox" value="area" checked style="margin-right: 6px;">
Área
</label>
<label style="display: flex; align-items: center; font-size: 12px; cursor: pointer;">
<input type="checkbox" class="field-checkbox" value="tags" checked style="margin-right: 6px;">
Tags
</label>
<label style="display: flex; align-items: center; font-size: 12px; cursor: pointer;">
<input type="checkbox" class="field-checkbox" value="childItems" checked style="margin-right: 6px;">
Child Items
</label>
</div>
</div>
<!-- Tabla de work items -->
<div class="workitems-table-container">
<table id="workItemsPDFTable">
<thead>
<tr>
<th>
<input type="checkbox" id="selectAllWorkItems" title="Seleccionar todos">
</th>
<th>ID</th>
<th>Título</th>
<th>Proyecto</th>
<th>Iteración</th>
<th>Estado</th>
<th>Carpeta Destino</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="7" class="empty-state">
<div class="empty-state-icon">📋</div>
<p><span class="loading-spinner"></span> Cargando work items...</p>
</td>
</tr>
</tbody>
</table>
</div>
<p style="margin-top: 15px; font-size: 12px; color: var(--vscode-descriptionForeground);">
<strong id="workItemCount">0 work item(s) encontrado(s)</strong>
</p>
</div>
<div class="modal-footer">
<button id="cancelPDFModalBtn" class="secondary">Cancelar</button>
<button id="generatePDFsBtn">Generar PDFs</button>
</div>
</div>
</div>
<!-- Modal de Adjuntos de Work Items -->
<div id="workItemAttachmentsModal" class="modal" hidden>
<div class="modal-overlay"></div>
<div class="modal-dialog">
<div class="modal-header">
<h2>📎 Extraer adjuntos de Work Items</h2>
<button class="modal-close" id="closeWorkItemAttachmentsModal">✕</button>
</div>
<div class="modal-body">
<div class="modal-info-box" style="margin-bottom: 20px; padding: 12px; background-color: var(--vscode-editor-inactiveSelectionBackground); border-left: 3px solid var(--vscode-editorInfo-foreground); border-radius: 3px;">
<p style="margin: 0; font-size: 13px; color: var(--vscode-foreground);">
<strong>ℹ️ Descarga de adjuntos:</strong> Selecciona los adjuntos por work item. Si Microsoft Word está instalado se convertirá automáticamente a PDF. Si no, podrás abrir el archivo en Word Online para convertirlo manualmente.
</p>
</div>
<div id="manualConversionNotice" class="manual-conversion-notice" hidden>
<div class="manual-conversion-title">Conversión manual requerida</div>
<div id="manualConversionList" class="manual-conversion-list"></div>
</div>
<div class="workitems-table-container">
<table id="workItemAttachmentsTable">
<thead>
<tr>
<th>
<input type="checkbox" id="selectAllWorkItemsAttachments" title="Seleccionar todos">
</th>
<th>ID</th>
<th>Título</th>
<th>Adjuntos</th>
<th>Carpeta Destino</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5" class="empty-state">
<div class="empty-state-icon">📎</div>
<p><span class="loading-spinner"></span> Cargando work items...</p>
</td>
</tr>
</tbody>
</table>
</div>
<p style="margin-top: 15px; font-size: 12px; color: var(--vscode-descriptionForeground);">
<strong id="workItemAttachmentsCount">0 work item(s) encontrado(s)</strong>
</p>
</div>
<div class="modal-footer">
<button id="cancelAttachmentsModalBtn" class="secondary">Cancelar</button>
<button id="downloadAttachmentsBtn">Descargar adjuntos</button>
</div>
</div>
</div>
<!-- Modal de RFC desde Work Items -->
<div id="workItemRFCModal" class="modal" hidden>
<div class="modal-overlay"></div>
<div class="modal-dialog">
<div class="modal-header">
<h2>🧾 Generar RFC desde Work Item</h2>
<button class="modal-close" id="closeWorkItemRFCModal">✕</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Work Item ID:</label>
<div style="display: flex; flex-direction: column; gap: 8px;">
<input type="text" id="rfcWorkItemId" placeholder="12345">
<button id="btnLoadRFCPreview" type="button">Cargar vista previa</button>
</div>
<small style="color: var(--vscode-descriptionForeground);">Usa el ID del work item de Azure Boards</small>
</div>
<div id="rfcMissingFields" class="rfc-warning" hidden></div>
<div class="form-group">
<label>Vista previa (editable):</label>
<textarea id="rfcPreview" class="rfc-preview" placeholder="Genera la vista previa para editar el comentario"></textarea>
</div>
<div id="rfcStatus" class="modal-status" hidden></div>
</div>
<div class="modal-footer">
<button id="cancelRFCModalBtn" class="secondary">Cancelar</button>
<button id="btnCopyRFC" class="secondary">Copiar</button>
<button id="btnPublishRFC">Publicar comentario</button>
</div>
</div>
</div>
<!-- Modal de Subtareas base -->
<div id="workItemSubtasksModal" class="modal" hidden>
<div class="modal-overlay"></div>
<div class="modal-dialog">
<div class="modal-header">
<h2>🧩 Generar subtareas base</h2>
<button class="modal-close" id="closeWorkItemSubtasksModal">✕</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>Work Item ID:</label>
<div style="display: flex; flex-direction: column; gap: 8px;">
<input type="text" id="subtasksWorkItemId" placeholder="12345">
<div style="display: flex; gap: 8px;">
<button id="btnLoadSubtasksTemplate" type="button">Cargar plantilla</button>
<button id="btnSuggestSubtasks" type="button" class="secondary">Sugerir con Copilot</button>
</div>
</div>
</div>
<div style="display: flex; gap: 8px; margin-bottom: 10px;">
<button id="btnAddSubtaskRow" type="button" class="secondary" style="width: auto;">Agregar tarea</button>
</div>
<div id="subtasksList" class="subtasks-list"></div>
<div id="subtasksStatus" class="modal-status" hidden></div>
</div>
<div class="modal-footer">
<button id="cancelSubtasksModalBtn" class="secondary">Cancelar</button>
<button id="btnCreateSubtasks">Crear subtareas</button>
</div>
</div>
</div>
<!-- Modal de Planes de Prueba -->
<div id="testPlanModal" class="modal" hidden>
<div class="modal-overlay"></div>
<div class="modal-dialog">
<div class="modal-header">
<h2>🧪 Generar Plan de Pruebas</h2>
<button class="modal-close" id="closeTestPlanModal">✕</button>
</div>
<div class="modal-body">
<div class="modal-info-box" style="margin-bottom: 20px; padding: 12px; background-color: var(--vscode-editor-inactiveSelectionBackground); border-left: 3px solid var(--vscode-editorInfo-foreground); border-radius: 3px;">
<p style="margin: 0; font-size: 13px; color: var(--vscode-foreground);">
<strong>ℹ️ Generación automática de planes de prueba:</strong> Proporciona el URL del Work Item y opcionalmente los URLs de Pull Requests.
El sistema analizará los PRs, extraerá comentarios de PR Review (issues detectados por G-Bot), y generará escenarios de prueba automáticamente.
El documento se guardará localmente en <code>~/Documents/G-Bot/</code> y se abrirá automáticamente.
</p>
</div>
<div class="form-group">
<label>Work Item URL <span style="color: var(--vscode-errorForeground);">*</span></label>
<input type="text" id="testPlanWorkItemUrl" placeholder="https://dev.azure.com/org/project/_workitems/edit/12345">
<small style="color: var(--vscode-descriptionForeground);">URL completo del Work Item en Azure DevOps</small>
</div>
<div class="form-group">
<label>Pull Request URLs <span style="color: var(--vscode-descriptionForeground);">(opcional)</span></label>
<textarea id="testPlanPRUrls" placeholder="https://dev.azure.com/org/project/_git/repo/pullrequest/123 https://dev.azure.com/org/project/_git/repo/pullrequest/456" rows="4"></textarea>
<small style="color: var(--vscode-descriptionForeground);">URLs de PRs relacionados, uno por línea. Se analizarán los archivos cambiados y comentarios de PR Review.</small>
</div>
<div class="form-group">
<label>Contexto Adicional <span style="color: var(--vscode-descriptionForeground);">(opcional)</span></label>
<textarea id="testPlanAdditionalContext" placeholder="Ejemplo: Esta feature usa nueva API de ServiceNow. Validar manejo de errores HTTP 401/403." rows="3"></textarea>
<small style="color: var(--vscode-descriptionForeground);">Información adicional para enriquecer los escenarios de prueba</small>
</div>
<div class="form-group">
<label>Modelo de IA para Escenarios</label>
<select id="testPlanAiModel">
<option value="loading">🔄 Cargando modelos disponibles...</option>
</select>
<small style="color: var(--vscode-descriptionForeground);" id="testPlanAiModelStatus">Detectando modelos de GitHub Copilot...</small>
</div>
<div id="testPlanStatus" class="modal-status" hidden></div>
</div>
<div class="modal-footer">
<button id="cancelTestPlanModalBtn" class="secondary">Cancelar</button>
<button id="btnGenerateTestPlan">Generar Plan de Pruebas</button>
</div>
</div>
</div>
<script nonce="${nonce}">
// Hacer vscode disponible globalmente para otros scripts
window.vscode = acquireVsCodeApi();
const vscode = window.vscode;
let currentStyle = 'default';
// ============================================================
// DEFINIR TODAS LAS FUNCIONES PRIMERO (antes de usarlas)
// ============================================================
// Función para cargar modelos de IA disponibles
function loadAvailableModels() {
vscode.postMessage({ type: 'getAvailableModels' });
}
// Generar documento
function generateDocument() {
const paseNumber = document.getElementById('paseNumber').value;
const paseTitle = document.getElementById('paseTitle').value;
const paseObjective = document.getElementById('paseObjective').value;
const areaAfectada = document.getElementById('areaAfectada').value;
const filename = document.getElementById('filename').value;
// Validar campos requeridos
if (!paseNumber) {
showStatus('❌ Por favor ingresa el número de pase', 'error');
return;
}
if (!paseTitle) {
showStatus('❌ Por favor ingresa el título del pase', 'error');
return;
}
showStatus('🚀 Generando documento...', 'info');
vscode.postMessage({
type: 'generate',
config: {
paseNumber,
paseTitle,
paseObjective,
areaAfectada,
filename
}
});
}
// Generar indice de manuales
function generateManualIndex() {
showStatus('📚 Generando indice de manuales...', 'info');
vscode.postMessage({ type: 'generateManualIndex' });
}
// Seleccionar estilo
function selectStyle(style) {
currentStyle = style;
document.querySelectorAll('.style-option').forEach(opt => {
opt.classList.remove('selected');
});
const selectedStyle = document.querySelector('[data-style="' + style + '"]');
if (selectedStyle) {
selectedStyle.classList.add('selected');
}
vscode.postMessage({ type: 'selectStyle', style });
}
// Probar conexión Azure
function testAzure() {
showStatus('🔄 Probando conexión...', 'info');
vscode.postMessage({ type: 'testConnection', service: 'azure' });
}
// Revisar Pull Request
function reviewPullRequest() {
const prUrl = document.getElementById('prUrl').value.trim();
const reviewType = document.getElementById('reviewType').value;
const reviewDetail = document.getElementById('reviewDetail').value;
const aiModel = document.getElementById('aiModel').value;
const autoComment = document.getElementById('autoComment').checked;
const includeSuggestions = document.getElementById('includeSuggestions').checked;
if (!prUrl) {
showPRStatus('❌ Por favor ingresa la URL del Pull Request', 'error');
return;
}
// Validar que sea una URL de Azure DevOps válida
const parsedPrUrl = parseReviewPullRequestUrl(prUrl);
if (!parsedPrUrl) {
showPRStatus('❌ URL inválida. Formatos esperados: https://dev.azure.com/org/project/_git/repo/pullrequest/12345 o https://org.visualstudio.com/project/_git/repo/pullrequest/12345', 'error');
return;
}
const organization = parsedPrUrl.organization;
const project = parsedPrUrl.project;
const repository = parsedPrUrl.repository;
const prId = parsedPrUrl.prId;
showPRStatus('🔄 Iniciando revisión del PR #' + prId + '...', 'info');
vscode.postMessage({
type: 'reviewPR',
prUrl,
organization,
project,
repository,
prId,
reviewType,
reviewDetail,
aiModel,
autoComment,
includeSuggestions
});
}
// Mostrar estado de revisión de PR
function showPRStatus(message, type) {
const statusDiv = document.getElementById('prReviewStatus');
const messageP = document.getElementById('prReviewMessage');
statusDiv.style.display = 'block';
messageP.textContent = message;
// Cambiar color según tipo
if (type === 'error') {
statusDiv.style.background = 'var(--vscode-inputValidation-errorBackground)';
statusDiv.style.borderLeftColor = 'var(--vscode-inputValidation-errorBorder)';
} else if (type === 'success') {
statusDiv.style.background = 'var(--vscode-inputValidation-infoBackground)';
statusDiv.style.borderLeftColor = 'var(--vscode-inputValidation-infoBorder)';
} else {
statusDiv.style.background = 'var(--vscode-inputValidation-warningBackground)';
statusDiv.style.borderLeftColor = 'var(--vscode-inputValidation-warningBorder)';
}
}
// Cargar configuración
function loadConfig() {
showStatus('🔄 Cargando configuración...', 'info');
vscode.postMessage({ type: 'loadConfig' });
}
// Guardar configuración
function saveConfig() {
// El mensaje se mostrará como notificación de VS Code (abajo a la derecha)
// Procesar patrones ignorados: dividir por líneas, limpiar y filtrar vacíos
const ignoredPatternsText = document.getElementById('ignoredFilePatterns').value;
const ignoredFilePatterns = ignoredPatternsText
.split('\\n')
.map(line => line.trim())
.filter(line => line.length > 0);
const rawFilesThreshold = Number(document.getElementById('autoLiteModeFilesThreshold').value);
const rawBlocksThreshold = Number(document.getElementById('autoLiteModeBlocksThreshold').value);
const autoLiteModeFilesThreshold = Number.isFinite(rawFilesThreshold) && rawFilesThreshold > 0
? Math.floor(rawFilesThreshold)
: 180;
const autoLiteModeBlocksThreshold = Number.isFinite(rawBlocksThreshold) && rawBlocksThreshold > 0
? Math.floor(rawBlocksThreshold)
: 24;
const config = {
azureOrg: document.getElementById('azureOrg').value,
azurePat: document.getElementById('azurePat').value,
devopsOrg: document.getElementById('devopsOrg').value,
devopsPat: document.getElementById('devopsPat').value,
sharePointPath: document.getElementById('sharePointPath').value,
sharePointUrl: document.getElementById('sharePointUrl').value,
subdirectories: document.getElementById('subdirectories').value,
outputDir: document.getElementById('outputDir').value,
summaryMethod: document.getElementById('summaryMethod').value,
docxConversionMode: document.getElementById('docxConversionMode').value,
standardsSqlPath: document.getElementById('standardsSqlPath').value,
standardsAngularPath: document.getElementById('standardsAngularPath').value,
standardsDotnetPath: document.getElementById('standardsDotnetPath').value,
standardsSsisPath: document.getElementById('standardsSsisPath').value,
ignoredFilePatterns: ignoredFilePatterns, // Array de patrones
autoLiteModeEnabled: document.getElementById('autoLiteModeEnabled').checked,
autoLiteModeFilesThreshold: autoLiteModeFilesThreshold,
autoLiteModeBlocksThreshold: autoLiteModeBlocksThreshold,
paseNumber: document.getElementById('paseNumber').value,
paseTitle: document.getElementById('paseTitle').value,
paseObjective: document.getElementById('paseObjective').value,
areaAfectada: document.getElementById('areaAfectada').value,
aiModel: document.getElementById('aiModel').value // Persistir modelo seleccionado
};
vscode.postMessage({ type: 'saveConfig', config });
}
// Seleccionar pestaña
function selectTab(tabId) {
// Remover active de todos los botones y contenidos
document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
// Activar el botón y contenido seleccionado
const tabButton = document.querySelector('.tab-button[data-tab="' + tabId + '"]');
const tabContent = document.getElementById('tab-' + tabId);
if (!tabButton || !tabContent) {
return;
}
tabButton.classList.add('active');
tabContent.classList.add('active');
// Persistir la pestaña seleccionada
try {
localStorage.setItem('G-Bot-active-tab', tabId);
} catch (e) {
// Ignorar errores de localStorage
}
}
// Hacer selectTab disponible globalmente para debugging
window.selectTab = selectTab;
// Restaurar pestaña guardada
function restoreSavedTab() {
try {
const savedTab = localStorage.getItem('G-Bot-active-tab');
if (savedTab && document.getElementById('tab-' + savedTab)) {
selectTab(savedTab);
}
} catch (e) {
// Ignorar errores de localStorage
}
}
// Toggle secciones colapsables (acordeón)
function toggleSection(header) {
header.classList.toggle('collapsed');
const content = header.nextElementSibling;
content.classList.toggle('hidden');
}
// Actualizar selector de modelos dinámicamente
function updateModelSelector(models, savedModel) {
const select = document.getElementById('aiModel');
const statusText = document.getElementById('aiModelStatus');
// También actualizar el selector del plan de pruebas si está visible
const testPlanSelect = document.getElementById('testPlanAiModel');
const testPlanStatusText = document.getElementById('testPlanAiModelStatus');
if (!models || models.length === 0) {
select.innerHTML = '<option value="gpt-4o">🚀 GPT-4o (Predeterminado)</option>';
if (statusText) {
statusText.textContent = '⚠️ No se pudieron detectar modelos. Usando GPT-4o por defecto.';
statusText.style.color = 'var(--vscode-errorForeground)';
}
if (testPlanSelect) {
testPlanSelect.innerHTML = '<option value="gpt-4o">🚀 GPT-4o (Predeterminado)</option>';
}
if (testPlanStatusText) {
testPlanStatusText.textContent = '⚠️ No se pudieron detectar modelos. Usando GPT-4o por defecto.';
testPlanStatusText.style.color = 'var(--vscode-errorForeground)';
}
return;
}
// Actualizar selector del Revisor
select.innerHTML = '';
// Actualizar selector del Plan de Pruebas
if (testPlanSelect) {
testPlanSelect.innerHTML = '';
}
// Agrupar modelos por vendor
const grouped = {};
models.forEach(model => {
const vendor = model.vendor || 'Otros';
if (!grouped[vendor]) {
grouped[vendor] = [];
}
grouped[vendor].push(model);
});
// Crear options agrupados para ambos selectores
Object.keys(grouped).forEach(vendor => {
// Para el selector del Revisor
const optgroup = document.createElement('optgroup');
optgroup.label = vendor;
// Para el selector del Plan de Pruebas
const testPlanOptgroup = testPlanSelect ? document.createElement('optgroup') : null;
if (testPlanOptgroup) {
testPlanOptgroup.label = vendor;
}
grouped[vendor].forEach((model, index) => {
const option = document.createElement('option');
option.value = model.id;
// Agregar emoji según el modelo
const emoji = getModelEmoji(model.family);
option.textContent = emoji + ' ' + (model.name || model.family);
// Marcar el primero como seleccionado
if (vendor === Object.keys(grouped)[0] && index === 0) {
option.selected = true;
}
optgroup.appendChild(option);
// Clonar para el plan de pruebas
if (testPlanOptgroup) {
const testPlanOption = option.cloneNode(true);
testPlanOptgroup.appendChild(testPlanOption);
}
});
select.appendChild(optgroup);
if (testPlanOptgroup && testPlanSelect) {
testPlanSelect.appendChild(testPlanOptgroup);
}
});
// Restaurar modelo previamente guardado en Revisor
if (savedModel) {
select.value = savedModel;
// Si el modelo guardado no existe en la lista, usar el primero disponible
if (!select.value && models.length > 0) {
select.value = models[0].id;
}
}
// Pre-seleccionar modelo pendiente en Plan de Pruebas
if (testPlanSelect && window._pendingTestPlanAiModel) {
testPlanSelect.value = window._pendingTestPlanAiModel;
if (!testPlanSelect.value && models.length > 0) {
testPlanSelect.value = models[0].id;
}
delete window._pendingTestPlanAiModel;
} else if (testPlanSelect && savedModel) {
// Si no hay modelo pendiente, usar el guardado
testPlanSelect.value = savedModel;
if (!testPlanSelect.value && models.length > 0) {
testPlanSelect.value = models[0].id;
}
}
if (statusText) {
statusText.textContent = '✅ ' + models.length + ' modelo(s) disponible(s)';
statusText.style.color = 'var(--vscode-descriptionForeground)';
}
if (testPlanStatusText) {
testPlanStatusText.textContent = '✅ ' + models.length + ' modelo(s) disponible(s)';
testPlanStatusText.style.color = 'var(--vscode-descriptionForeground)';
}
}
// Obtener emoji según el modelo
function getModelEmoji(family) {
const emojiMap = {
'gpt-4o': '🚀',
'gpt-4': '🤖',
'gpt-4-turbo': '⚡',
'gpt-3.5-turbo': '💨',
'gpt-5': '🌟',
'claude-3-opus': '🧠',
'claude-3-sonnet': '🎯',
'claude-3-haiku': '⚡',
'claude-sonnet-4': '🎯',
'gemini-pro': '💎',
'gemini-ultra': '🌟',
};
// Buscar coincidencia parcial
for (const [key, emoji] of Object.entries(emojiMap)) {
if (family && family.toLowerCase().includes(key.toLowerCase())) {
return emoji;
}
}
return '🤖'; // Default
}
// Mostrar estado
function showStatus(message, type) {
const status = document.getElementById('status');
status.textContent = message;
status.className = 'status ' + type;
status.style.display = 'block';
if (type === 'success' || type === 'error') {
setTimeout(() => {
status.style.display = 'none';
}, 5000);
}
}
// Recibir mensajes desde la extensión
window.addEventListener('message', event => {
const message = event.data;
switch (message.type) {
case 'configLoaded':
if (message.config) {
document.getElementById('azureOrg').value = message.config.azureOrg || '';
document.getElementById('azurePat').value = message.config.azurePat || '';
document.getElementById('devopsOrg').value = message.config.devopsOrg || '';
document.getElementById('devopsPat').value = message.config.devopsPat || '';
document.getElementById('sharePointPath').value = message.config.sharePointPath || '';
document.getElementById('sharePointUrl').value = message.config.sharePointUrl || '';
document.getElementById('outputDir').value = message.config.outputDir || '';
document.getElementById('subdirectories').value = message.config.subdirectories || '';
document.getElementById('summaryMethod').value = message.config.summaryMethod || 'local';
document.getElementById('docxConversionMode').value = message.config.docxConversionMode || 'js';
document.getElementById('standardsSqlPath').value = message.config.standardsSqlPath || '';
document.getElementById('standardsAngularPath').value = message.config.standardsAngularPath || '';
document.getElementById('standardsDotnetPath').value = message.config.standardsDotnetPath || '';
document.getElementById('standardsSsisPath').value = message.config.standardsSsisPath || '';
// Cargar patrones de archivos ignorados (array a texto con saltos de línea)
const patterns = message.config.ignoredFilePatterns || [];
document.getElementById('ignoredFilePatterns').value = Array.isArray(patterns) ? patterns.join('\\n') : '';
// Cargar configuración de modo liviano automático para PRs grandes
document.getElementById('autoLiteModeEnabled').checked = message.config.autoLiteModeEnabled !== false;
document.getElementById('autoLiteModeFilesThreshold').value = message.config.autoLiteModeFilesThreshold || 180;
document.getElementById('autoLiteModeBlocksThreshold').value = message.config.autoLiteModeBlocksThreshold || 24;
// Cargar datos del último pase
document.getElementById('paseNumber').value = message.config.lastPaseNumber || '';
document.getElementById('paseTitle').value = message.config.lastTitle || '';
document.getElementById('paseObjective').value = message.config.lastObjective || '';
document.getElementById('areaAfectada').value = message.config.lastAreaAfectada || '';
}
showStatus('✅ Configuración cargada', 'success');
break;
case 'status':
showStatus(message.message, message.type);
break;
case 'prReviewStatus':
showPRStatus(message.message, message.type);
break;
case 'availableModels':
updateModelSelector(message.models, message.savedModel);
break;
case 'folderSelected':
if (message.target && message.path) {
const input = document.getElementById(message.target);
if (input) {
input.value = message.path;
showStatus('✅ Ruta seleccionada: ' + message.path, 'success');
}
}
break;
case 'showWorkItemPDFModal':
showWorkItemPDFModal();
break;
case 'showWorkItemAttachmentsModal':
showWorkItemAttachmentsModal();
break;
case 'showWorkItemRFCModal':
showWorkItemRFCModal();
break;
case 'showWorkItemSubtasksModal':
showWorkItemSubtasksModal();
break;
case 'showTestPlanModal':
showTestPlanModal(message.aiModel);
break;
case 'testPlanProgress':
{
const statusDiv = document.getElementById('testPlanStatus');
if (statusDiv) {
statusDiv.textContent = message.message || 'Procesando...';
statusDiv.className = 'modal-status info';
statusDiv.hidden = false;
}
}
break;
case 'testPlanSuccess':
{
const statusDiv = document.getElementById('testPlanStatus');
if (statusDiv) {
statusDiv.textContent = 'Plan de pruebas generado: ' + message.result.scenariosCount + ' escenarios. Documento abierto automaticamente.';
statusDiv.className = 'modal-status success';
statusDiv.hidden = false;
}
const btn = document.getElementById('btnGenerateTestPlan');
if (btn) {
btn.disabled = false;
btn.textContent = 'Generar Plan de Pruebas';
}
// Cerrar modal después de 3 segundos
setTimeout(() => {
document.getElementById('testPlanModal').hidden = true;
}, 3000);
}
break;
case 'testPlanError':
{
const statusDiv = document.getElementById('testPlanStatus');
if (statusDiv) {
statusDiv.textContent = '❌ Error: ' + message.error.message;
statusDiv.className = 'modal-status error';
statusDiv.hidden = false;
}
// Re-habilitar botón
const btn = document.getElementById('btnGenerateTestPlan');
if (btn) {
btn.disabled = false;
btn.textContent = 'Generar Plan de Pruebas';
}
}
break;
}
});
// Función para abrir el modal de PDFs de work items
function openWorkItemPDFModal() {
vscode.postMessage({ type: 'openWorkItemPDFModal' });
}
// Función para abrir el modal de adjuntos de work items
function openWorkItemAttachmentsModal() {
vscode.postMessage({ type: 'openWorkItemAttachmentsModal' });
}
// Función para abrir el modal de RFC
function openWorkItemRFCModal() {
vscode.postMessage({ type: 'openWorkItemRFCModal' });
}
// Función para abrir el modal de subtareas
function openWorkItemSubtasksModal() {
vscode.postMessage({ type: 'openWorkItemSubtasksModal' });
}
// Función para abrir el modal de planes de prueba
function openTestPlanModal() {
vscode.postMessage({ type: 'openTestPlanModal' });
}
// Función para mostrar el modal (llamada desde extensión)
function showWorkItemPDFModal() {
const modal = document.getElementById('workItemPDFModal');
if (modal) {
modal.hidden = false;
// Inicializar modal
if (typeof window.initWorkItemModal === 'function') {
window.initWorkItemModal();
} else {
console.error('❌ window.initWorkItemModal no es una función');
}
} else {
console.error('❌ No se encontró el elemento con id "workItemPDFModal"');
}
}
// Función para mostrar el modal de adjuntos (llamada desde extensión)
function showWorkItemAttachmentsModal() {
const modal = document.getElementById('workItemAttachmentsModal');
if (modal) {
modal.hidden = false;
if (typeof window.initWorkItemAttachmentsModal === 'function') {
window.initWorkItemAttachmentsModal();
} else {
console.error('❌ window.initWorkItemAttachmentsModal no es una función');
}
} else {
console.error('❌ No se encontró el elemento con id "workItemAttachmentsModal"');
}
}
// Función para mostrar el modal de RFC
function showWorkItemRFCModal() {
const modal = document.getElementById('workItemRFCModal');
if (modal) {
modal.hidden = false;
if (typeof window.initWorkItemRFCModal === 'function') {
window.initWorkItemRFCModal();
} else {
console.error('❌ window.initWorkItemRFCModal no es una función');
}
} else {
console.error('❌ No se encontró el elemento con id "workItemRFCModal"');
}
}
// Función para mostrar el modal de subtareas
function showWorkItemSubtasksModal() {
const modal = document.getElementById('workItemSubtasksModal');
if (modal) {
modal.hidden = false;
if (typeof window.initWorkItemSubtasksModal === 'function') {
window.initWorkItemSubtasksModal();
} else {
console.error('❌ window.initWorkItemSubtasksModal no es una función');
}
} else {
console.error('❌ No se encontró el elemento con id "workItemSubtasksModal"');
}
}
// Función para mostrar el modal de planes de prueba
function showTestPlanModal(aiModel) {
const modal = document.getElementById('testPlanModal');
if (modal) {
modal.hidden = false;
// Limpiar campos
document.getElementById('testPlanWorkItemUrl').value = '';
document.getElementById('testPlanPRUrls').value = '';
document.getElementById('testPlanAdditionalContext').value = '';
// Cargar modelos disponibles (usa la misma función que el Revisor)
vscode.postMessage({ type: 'getAvailableModels' });
// Pre-seleccionar modelo si se proporciona (se aplicará cuando se carguen los modelos)
if (aiModel) {
// Guardar temporalmente para aplicar después
window._pendingTestPlanAiModel = aiModel;
}
const statusDiv = document.getElementById('testPlanStatus');
if (statusDiv) {
statusDiv.hidden = true;
statusDiv.textContent = '';
}
const btn = document.getElementById('btnGenerateTestPlan');
if (btn) {
btn.disabled = false;
btn.textContent = 'Generar Plan de Pruebas';
}
} else {
console.error('❌ No se encontró el elemento con id "testPlanModal"');
vscode.postMessage({
type: 'showError',
message: 'Error interno: Modal no encontrado en DOM'
});
}
}
function parseReviewPullRequestUrl(url) {
try {
const rawInput = String(url || '').trim();
if (!rawInput) {
return null;
}
let urlCandidate = rawInput;
if (rawInput.startsWith('[') && rawInput.endsWith(')')) {
const separatorIndex = rawInput.indexOf('](');
if (separatorIndex > 1) {
urlCandidate = rawInput.slice(separatorIndex + 2, -1).trim();
}
}
const normalizedUrl =
urlCandidate.startsWith('<') && urlCandidate.endsWith('>')
? urlCandidate.slice(1, -1).trim()
: urlCandidate;
const parsed = new URL(normalizedUrl);
const hostname = parsed.hostname.toLowerCase();
const segments = parsed.pathname.split('/').filter(Boolean);
if (hostname === 'dev.azure.com') {
if (segments.length < 6) {
return null;
}
if (segments[2].toLowerCase() !== '_git' || segments[4].toLowerCase() !== 'pullrequest') {
return null;
}
if (!/^[0-9]+$/.test(segments[5])) {
return null;
}
return {
organization: decodeURIComponent(segments[0]),
project: decodeURIComponent(segments[1]),
repository: decodeURIComponent(segments[3]),
prId: parseInt(segments[5], 10),
};
}
if (hostname.endsWith('.visualstudio.com')) {
if (segments.length < 5) {
return null;
}
if (segments[1].toLowerCase() !== '_git' || segments[3].toLowerCase() !== 'pullrequest') {
return null;
}
if (!/^[0-9]+$/.test(segments[4])) {
return null;
}
const organization = hostname.replace('.visualstudio.com', '');
if (!organization) {
return null;
}
return {
organization,
project: decodeURIComponent(segments[0]),
repository: decodeURIComponent(segments[2]),
prId: parseInt(segments[4], 10),
};
}
return null;
} catch (error) {
return null;
}
}
function isValidWorkItemUrl(url) {
try {
const parsed = new URL(url);
if (parsed.hostname.toLowerCase() !== 'dev.azure.com') {
return false;
}
const segments = parsed.pathname.split('/').filter(Boolean);
if (segments.length < 5) {
return false;
}
return (
segments[2].toLowerCase() === '_workitems' &&
segments[3].toLowerCase() === 'edit' &&
/^[0-9]+$/.test(segments[4])
);
} catch (error) {
return false;
}
}
function isValidPullRequestUrl(url) {
try {
const parsed = new URL(url);
if (parsed.hostname.toLowerCase() !== 'dev.azure.com') {
return false;
}
const segments = parsed.pathname.split('/').filter(Boolean);
if (segments.length < 6) {
return false;
}
return (
segments[2].toLowerCase() === '_git' &&
segments[4].toLowerCase() === 'pullrequest' &&
/^[0-9]+$/.test(segments[5])
);
} catch (error) {
return false;
}
}
// ============================================================
// REGISTRAR EVENT LISTENERS (después de definir funciones)
// ============================================================
function bindEventById(id, eventName, handler) {
const element = document.getElementById(id);
if (!element) {
console.warn('Elemento no encontrado para listener:', id);
return;
}
element.addEventListener(eventName, handler);
}
function bindClick(id, handler) {
bindEventById(id, 'click', handler);
}
function initializeTabNavigation() {
document.addEventListener('click', (event) => {
const target = event.target;
if (!target || typeof target.closest !== 'function') {
return;
}
const tabButton = target.closest('.tab-button[data-tab]');
if (!tabButton) {
return;
}
event.preventDefault();
const tabId = tabButton.getAttribute('data-tab');
if (tabId) {
selectTab(tabId);
}
});
}
// Tab navigation (delegado para mayor robustez)
initializeTabNavigation();
// Style options
document.querySelectorAll('.style-option[data-style]').forEach(opt => {
opt.addEventListener('click', () => selectStyle(opt.getAttribute('data-style')));
});
// Collapsible sections
document.querySelectorAll('[data-action="toggleSection"]').forEach(h => {
h.addEventListener('click', () => toggleSection(h));
});
// Action buttons - Reviewer tab
bindClick('btnReviewPR', reviewPullRequest);
bindClick('btnTestAzure', testAzure);
// Action buttons - Documents tab
bindClick('btnGenerateDoc', generateDocument);
bindClick('btnOpenPDFModal', openWorkItemPDFModal);
bindClick('btnOpenAttachmentsModal', openWorkItemAttachmentsModal);
bindClick('btnOpenRFCModal', openWorkItemRFCModal);
bindClick('btnOpenSubtasksModal', openWorkItemSubtasksModal);
bindClick('btnOpenTestPlanModal', openTestPlanModal);
// Config buttons
bindClick('btnLoadConfig', loadConfig);
bindClick('btnSaveConfig', saveConfig);
bindClick('btnSaveConfigDocuments', saveConfig);
// Documentation link
bindClick('linkOpenDocsIgnoredPatterns', (e) => {
e.preventDefault();
vscode.postMessage({type: 'openDocs', doc: 'ignoredPatterns'});
});
// Browse buttons
bindClick('browseSharePointPath', () => {
vscode.postMessage({ type: 'browseFolder', target: 'sharePointPath' });
});
bindClick('browseOutputDir', () => {
vscode.postMessage({ type: 'browseFolder', target: 'outputDir' });
});
bindClick('browseStandardsSql', () => {
vscode.postMessage({ type: 'browseFileOrFolder', target: 'standardsSqlPath' });
});
bindClick('browseStandardsAngular', () => {
vscode.postMessage({ type: 'browseFileOrFolder', target: 'standardsAngularPath' });
});
bindClick('browseStandardsDotnet', () => {
vscode.postMessage({ type: 'browseFileOrFolder', target: 'standardsDotnetPath' });
});
bindClick('browseStandardsSsis', () => {
vscode.postMessage({ type: 'browseFileOrFolder', target: 'standardsSsisPath' });
});
// TestPlan Modal event listeners
bindClick('closeTestPlanModal', () => {
document.getElementById('testPlanModal').hidden = true;
});
bindClick('cancelTestPlanModalBtn', () => {
document.getElementById('testPlanModal').hidden = true;
});
bindClick('btnGenerateTestPlan', () => {
const workItemUrl = document.getElementById('testPlanWorkItemUrl').value.trim();
const prUrls = document.getElementById('testPlanPRUrls').value.trim();
const additionalContext = document.getElementById('testPlanAdditionalContext').value.trim();
const aiModel = document.getElementById('testPlanAiModel').value;
// Validar campo requerido
if (!workItemUrl) {
const statusDiv = document.getElementById('testPlanStatus');
statusDiv.textContent = '⚠️ Por favor ingresa el URL del Work Item';
statusDiv.className = 'modal-status error';
statusDiv.hidden = false;
return;
}
if (!isValidWorkItemUrl(workItemUrl)) {
const statusDiv = document.getElementById('testPlanStatus');
statusDiv.textContent = '⚠️ El URL del Work Item no tiene un formato válido de Azure DevOps';
statusDiv.className = 'modal-status error';
statusDiv.hidden = false;
return;
}
// Parsear URLs de PRs (uno por línea)
const pullRequestUrls = prUrls
.split(/[\\n\\r,;\\t]+/)
.map(url => url.trim())
.filter(url => url.length > 0);
const invalidPullRequestUrl = pullRequestUrls.find(url => !isValidPullRequestUrl(url));
if (invalidPullRequestUrl) {
const statusDiv = document.getElementById('testPlanStatus');
statusDiv.textContent = '⚠️ URL de Pull Request inválida: ' + invalidPullRequestUrl;
statusDiv.className = 'modal-status error';
statusDiv.hidden = false;
return;
}
// Mostrar estado de progreso
const statusDiv = document.getElementById('testPlanStatus');
statusDiv.textContent = '🔄 Generando plan de pruebas...';
statusDiv.className = 'modal-status info';
statusDiv.hidden = false;
// Deshabilitar botón durante generación
const btn = document.getElementById('btnGenerateTestPlan');
btn.disabled = true;
btn.textContent = 'Generando...';
// Enviar mensaje para generar
vscode.postMessage({
command: 'generateTestPlan',
data: {
workItemUrl,
aiModel,
pullRequestUrls,
additionalContext,
}
});
});
// ============================================================
// INICIALIZACIÓN (al final de todo)
// ============================================================
// Cargar modelos y configuración al iniciar
try {
loadAvailableModels();
loadConfig();
} catch (error) {
console.error('Error inicializando carga de modelos/configuración:', error);
}
// Restaurar pestaña guardada con fallback seguro
try {
restoreSavedTab();
const hasActiveTab = document.querySelector('.tab-content.active');
if (!hasActiveTab) {
selectTab('reviewer');
}
} catch (error) {
console.error('Error restaurando pestaña activa, aplicando fallback:', error);
selectTab('reviewer');
}
// Guardar automáticamente cuando cambia el modelo de IA
bindEventById('aiModel', 'change', function() {
const config = { aiModel: this.value };
vscode.postMessage({ type: 'saveConfig', config });
});
</script>
<!-- Script del modal de work items -->
<script nonce="${nonce}" src="${workitemModalJsUri}"></script>
<script nonce="${nonce}" src="${workitemAttachmentsModalJsUri}"></script>
<script nonce="${nonce}" src="${workitemRfcModalJsUri}"></script>
<script nonce="${nonce}" src="${workitemSubtasksModalJsUri}"></script>
</body>
</html>`;
}
/**
* Genera nonce para Content Security Policy
*/
_getNonce() {
let text = "";
const possible =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < 32; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
/**
* Limpia recursos cuando se destruye la vista
*/
/**
* Handler para abrir modal de generación de PDFs de work items
*/
async _handleOpenWorkItemPDFModal() {
try {
this._logger.info(
"📄 Abriendo modal de generación de PDFs de work items...",
);
// Cargar configuración desde VS Code settings
const vsConfig = vscode.workspace.getConfiguration("gbot");
// Construir objeto de configuración compatible con WorkItemPDFModal
const config = {
azure: {
organization: vsConfig.get("azure.organization", ""),
pat: vsConfig.get("azure.pat", ""),
},
devops: {
organization: vsConfig.get("devops.organization", ""),
pat: vsConfig.get("devops.pat", ""),
},
sharepoint: {
localPath: vsConfig.get("sharepoint.localPath", ""),
baseUrl: vsConfig.get("sharepoint.baseUrl", ""),
},
};
// Inicializar modal si no existe
if (!this._workItemPDFModal) {
this._workItemPDFModal = new WorkItemPDFModal(
this._view.webview,
config,
this._logger,
);
}
// Enviar comando al webview para mostrar el modal
this._view.webview.postMessage({
type: "showWorkItemPDFModal",
});
} catch (error) {
this._logger.error(`❌ Error abriendo modal de PDFs: ${error.message}`);
vscode.window.showErrorMessage(`Error abriendo modal: ${error.message}`);
}
}
/**
* Handler para abrir modal de generación de planes de prueba
*/
async _handleOpenTestPlanModal() {
try {
this._logger.info("🧪 Abriendo modal de generación de planes de prueba...");
// Verificar que tenemos una view activa
if (!this._view) {
throw new Error("Vista de sidebar no inicializada");
}
// Cargar configuración
const vsConfig = vscode.workspace.getConfiguration("gbot");
this._logger.info("📋 Cargando configuración de Azure DevOps...");
const config = {
azure: {
organization: vsConfig.get("azure.organization", ""),
pat: vsConfig.get("azure.pat", ""),
},
devops: {
organization: vsConfig.get("devops.organization", ""),
pat: vsConfig.get("devops.pat", ""),
},
};
this._logger.info(` Azure Org: ${config.azure.organization || '(no configurado)'}`);
this._logger.info(` DevOps Org: ${config.devops.organization || '(no configurado)'}`);
// Inicializar servicios si no existen
if (!this._azureDevOpsService) {
const devopsOrg = config.devops.organization;
const devopsPat = config.devops.pat;
if (devopsOrg && devopsPat) {
this._logger.info("🔧 Inicializando AzureDevOpsService...");
this._azureDevOpsService = new AzureDevOpsService(
devopsOrg,
devopsPat,
this._logger.info.bind(this._logger)
);
} else {
this._logger.warn("⚠️ Azure DevOps no configurado, algunas funciones no estarán disponibles");
}
}
if (!this._summaryService) {
this._logger.info("🤖 Inicializando SummaryService...");
this._summaryService = new SummaryService(this._logger.info.bind(this._logger));
}
// Inicializar modal si no existe
if (!this._testPlanModal) {
this._logger.info("📝 Creando TestPlanModal...");
this._testPlanModal = new TestPlanModal(
this._view.webview,
config,
this._azureDevOpsService,
this._summaryService,
this._logger
);
this._logger.info("✅ TestPlanModal creado exitosamente");
}
// Leer configuración del modelo de IA
const aiModel = vsConfig.get("testPlan.aiModel", "gpt-4o");
this._logger.info(` Modelo de IA configurado: ${aiModel}`);
// Enviar comando al webview para mostrar el modal
this._logger.info("📤 Enviando comando al webview para mostrar modal...");
this._view.webview.postMessage({
type: "showTestPlanModal",
aiModel,
});
this._logger.info("✅ Modal de planes de prueba abierto correctamente");
} catch (error) {
this._logger.error(`❌ Error abriendo modal de planes de prueba: ${error.message}`);
this._logger.error(` Stack: ${error.stack}`);
vscode.window.showErrorMessage(`Error abriendo modal de planes de prueba: ${error.message}`);
}
}
/**
* Handler para abrir modal de adjuntos de work items
*/
async _handleOpenWorkItemAttachmentsModal() {
try {
this._logger.info("📎 Abriendo modal de adjuntos de work items...");
const vsConfig = vscode.workspace.getConfiguration("gbot");
const config = {
azure: {
organization: vsConfig.get("azure.organization", ""),
pat: vsConfig.get("azure.pat", ""),
},
devops: {
organization: vsConfig.get("devops.organization", ""),
pat: vsConfig.get("devops.pat", ""),
},
sharepoint: {
localPath: vsConfig.get("sharepoint.localPath", ""),
baseUrl: vsConfig.get("sharepoint.baseUrl", ""),
},
};
if (!this._workItemAttachmentsModal) {
this._workItemAttachmentsModal = new WorkItemAttachmentsModal(
this._view.webview,
config,
this._logger,
);
}
this._view.webview.postMessage({
type: "showWorkItemAttachmentsModal",
});
} catch (error) {
this._logger.error(
`❌ Error abriendo modal de adjuntos: ${error.message}`,
);
vscode.window.showErrorMessage(`Error abriendo modal: ${error.message}`);
}
}
/**
* Handler para abrir modal de RFC de work items
*/
async _handleOpenWorkItemRFCModal() {
try {
this._logger.info("🧾 Abriendo modal de RFC de work items...");
const vsConfig = vscode.workspace.getConfiguration("gbot");
const config = {
azure: {
organization: vsConfig.get("azure.organization", ""),
pat: vsConfig.get("azure.pat", ""),
},
devops: {
organization: vsConfig.get("devops.organization", ""),
pat: vsConfig.get("devops.pat", ""),
},
};
if (!this._workItemRFCModal) {
this._workItemRFCModal = new WorkItemRFCModal(
this._view.webview,
config,
this._logger,
);
}
this._view.webview.postMessage({
type: "showWorkItemRFCModal",
});
} catch (error) {
this._logger.error(`❌ Error abriendo modal RFC: ${error.message}`);
vscode.window.showErrorMessage(`Error abriendo modal: ${error.message}`);
}
}
/**
* Handler para abrir modal de subtareas base
*/
async _handleOpenWorkItemSubtasksModal() {
try {
this._logger.info("🧩 Abriendo modal de subtareas base...");
const vsConfig = vscode.workspace.getConfiguration("gbot");
const config = {
azure: {
organization: vsConfig.get("azure.organization", ""),
pat: vsConfig.get("azure.pat", ""),
},
devops: {
organization: vsConfig.get("devops.organization", ""),
pat: vsConfig.get("devops.pat", ""),
},
};
if (!this._workItemSubtasksModal) {
this._workItemSubtasksModal = new WorkItemSubtasksModal(
this._view.webview,
config,
this._logger,
);
}
this._view.webview.postMessage({
type: "showWorkItemSubtasksModal",
});
} catch (error) {
this._logger.error(
`❌ Error abriendo modal de subtareas: ${error.message}`,
);
vscode.window.showErrorMessage(`Error abriendo modal: ${error.message}`);
}
}
/**
* Handler para generar indice de manuales (PDF/MP4)
*/
async _handleGenerateManualIndex() {
try {
this._logger.info("📚 Generando indice de manuales...");
const config = vscode.workspace.getConfiguration("gbot");
const docsConfig = vscode.workspace.getConfiguration("gbotDocs");
const workspaceFolder =
vscode.workspace.workspaceFolders?.[0]?.uri?.fsPath || "";
const sourceOverride = docsConfig.get("manuals.sourceDir");
const outputOverride = docsConfig.get("manuals.outputDir");
const sourceDir = this._resolveManualsSourceDir(
workspaceFolder,
sourceOverride,
);
let outputDir = outputOverride || config.get("template.outputDir");
if (!sourceDir) {
throw new Error(
"No se encontro la carpeta fuente de manuales. Configure gbotDocs.manuals.sourceDir.",
);
}
if (!outputDir) {
outputDir = await this._promptForManualOutputDir();
if (!outputDir) {
this._sendMessage("status", {
message:
"⚠️ Selecciona una carpeta de salida para generar el indice.",
type: "warning",
});
return;
}
await docsConfig.update("manuals.outputDir", outputDir, true);
}
if (!fs.existsSync(sourceDir)) {
throw new Error(`La carpeta fuente no existe: ${sourceDir}`);
}
if (!fs.existsSync(outputDir)) {
const selectedDir = await this._promptForManualOutputDir();
if (!selectedDir) {
this._sendMessage("status", {
message: "⚠️ Selecciona una carpeta de salida valida.",
type: "warning",
});
return;
}
outputDir = selectedDir;
await docsConfig.update("manuals.outputDir", outputDir, true);
}
const manualFiles = await this._collectManualFiles(sourceDir, [
".pdf",
".mp4",
]);
if (manualFiles.length === 0) {
this._sendMessage("status", {
message:
"⚠️ No se encontraron manuales PDF o MP4 en la carpeta fuente.",
type: "warning",
});
return;
}
const outputInsideSource = this._isPathInside(outputDir, sourceDir);
if (!outputInsideSource) {
await this._copyManualFiles(manualFiles, sourceDir, outputDir);
}
const indexContent = this._buildManualIndex(manualFiles, {
sourceDir,
outputDir,
outputInsideSource,
});
const indexPath = path.join(outputDir, "Indice-Manuales.md");
await fs.promises.writeFile(indexPath, indexContent, "utf-8");
this._logger.info(`✅ Indice generado: ${indexPath}`);
this._sendMessage("status", {
message: "✅ Indice de manuales generado.",
type: "success",
});
const action = await vscode.window.showInformationMessage(
"✅ Indice de manuales generado.",
"📁 Abrir carpeta",
"📄 Abrir indice",
);
if (action === "📁 Abrir carpeta") {
await this._openFileOrFolder(outputDir);
} else if (action === "📄 Abrir indice") {
await this._openFileOrFolder(indexPath);
}
} catch (error) {
this._logger.error(`❌ Error generando indice: ${error.message}`);
this._sendMessage("status", {
message: `❌ Error generando indice: ${error.message}`,
type: "error",
});
vscode.window.showErrorMessage(
`Error generando indice de manuales: ${error.message}`,
);
}
}
async _promptForManualOutputDir() {
const selection = await vscode.window.showOpenDialog({
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
openLabel: "Seleccionar carpeta de salida",
});
if (!selection || !selection[0]) {
return "";
}
return selection[0].fsPath;
}
_resolveManualsSourceDir(workspaceFolder, overridePath) {
if (overridePath && typeof overridePath === "string") {
const trimmed = overridePath.trim();
if (trimmed) {
if (path.isAbsolute(trimmed)) {
return trimmed;
}
if (workspaceFolder) {
return path.join(workspaceFolder, trimmed);
}
return trimmed;
}
}
if (!workspaceFolder) {
return "";
}
return path.join(workspaceFolder, "docs", "guias");
}
async _collectManualFiles(rootDir, extensions) {
const normalizedExt = (extensions || []).map((ext) => ext.toLowerCase());
const results = [];
const ignoredNames = new Set(["Indice-Manuales.md"]);
const walk = async (currentDir) => {
const entries = await fs.promises.readdir(currentDir, {
withFileTypes: true,
});
for (const entry of entries) {
if (entry.isDirectory()) {
if (entry.name === ".git" || entry.name === "node_modules") {
continue;
}
await walk(path.join(currentDir, entry.name));
continue;
}
if (!entry.isFile()) {
continue;
}
if (ignoredNames.has(entry.name)) {
continue;
}
const ext = path.extname(entry.name).toLowerCase();
if (!normalizedExt.includes(ext)) {
continue;
}
results.push({
fullPath: path.join(currentDir, entry.name),
ext,
fileName: entry.name,
});
}
};
await walk(rootDir);
results.sort((a, b) => a.fullPath.localeCompare(b.fullPath));
return results;
}
async _copyManualFiles(files, sourceDir, outputDir) {
for (const file of files) {
const relative = path.relative(sourceDir, file.fullPath);
const destPath = path.join(outputDir, relative);
const destFolder = path.dirname(destPath);
await fs.promises.mkdir(destFolder, { recursive: true });
await fs.promises.copyFile(file.fullPath, destPath);
}
}
_buildManualIndex(files, { sourceDir, outputDir, outputInsideSource }) {
const today = new Date().toISOString().split("T")[0];
const pdfs = files.filter((file) => file.ext === ".pdf");
const videos = files.filter((file) => file.ext === ".mp4");
const buildLinks = (items) => {
if (items.length === 0) {
return "- (sin archivos)";
}
return items
.map((file) => {
const relativeFromSource = path.relative(sourceDir, file.fullPath);
const linkPath = outputInsideSource
? path.relative(outputDir, file.fullPath)
: relativeFromSource;
const normalizedPath = this._normalizeManualPath(linkPath);
const displayPath = this._normalizeManualPath(relativeFromSource);
const encodedLink = this._encodeManualLink(normalizedPath);
return `- [${displayPath}](${encodedLink})`;
})
.join("\n");
};
return [
"# Indice de manuales",
"",
`Generado: ${today}`,
`Fuente: ${this._normalizeManualPath(sourceDir)}`,
"",
`## PDFs (${pdfs.length})`,
buildLinks(pdfs),
"",
`## Videos MP4 (${videos.length})`,
buildLinks(videos),
"",
].join("\n");
}
_normalizeManualPath(value) {
return String(value || "").replace(/\\/g, "/");
}
_encodeManualLink(linkPath) {
return this._normalizeManualPath(linkPath)
.split("/")
.map((segment) => encodeURIComponent(segment))
.join("/");
}
_isPathInside(candidatePath, parentPath) {
const normalizedCandidate = path.resolve(candidatePath);
const normalizedParent = path.resolve(parentPath);
return (
normalizedCandidate === normalizedParent ||
normalizedCandidate.startsWith(normalizedParent + path.sep)
);
}
dispose() {
// Limpiar workItemPDFModal
if (this._workItemPDFModal) {
this._workItemPDFModal.dispose();
this._workItemPDFModal = null;
}
if (this._workItemAttachmentsModal) {
this._workItemAttachmentsModal.dispose();
this._workItemAttachmentsModal = null;
}
if (this._workItemRFCModal) {
this._workItemRFCModal.dispose();
this._workItemRFCModal = null;
}
if (this._workItemSubtasksModal) {
this._workItemSubtasksModal.dispose();
this._workItemSubtasksModal = null;
}
if (this._testPlanModal) {
this._testPlanModal.dispose();
this._testPlanModal = null;
}
// Limpiar todos los disposables (incluye event listeners)
if (this._disposables) {
this._disposables.forEach((d) => {
try {
d.dispose();
} catch (error) {
console.error("Error disposing resource:", error);
}
});
this._disposables = [];
}
// Limpiar referencias
this._view = null;
}
}
module.exports = SidebarProvider;
|