app.js 132 KB
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
// U-008: hash-based client-side router (no History API / server catch-all
// needed). U-022 adds the first real page, #/setup (v_project_setup, 02-V
// §2.1); U-023 adds #/goals/new and #/bugs/new; U-025 adds the real #/
// (v_dashboard), #/tasks (v_task_board), #/tasks/:task_id (v_task_detail).

// 02-V's console has no multi-project switcher UI (decision 2), but
// c_task_create/c_bug_report_create both require project_id (03-C §3.1;
// §3.1.1 doesn't list it, but needs it too -- see bug_record.py's
// create_bug_report docstring). Until v_dashboard carries "current project"
// state through some richer UI, the id picked/created in v_project_setup is
// stashed here and read back by the pages that need it.
const CURRENT_PROJECT_KEY = "graphlemon_project_id";
function getCurrentProjectId() {
  return localStorage.getItem(CURRENT_PROJECT_KEY);
}
function setCurrentProjectId(projectId) {
  localStorage.setItem(CURRENT_PROJECT_KEY, projectId);
}

function escapeHtml(text) {
  const div = document.createElement("div");
  div.textContent = text == null ? "" : String(text);
  return div.innerHTML;
}

// c_ws_subscribe (03-C §3.14, U-024): opens a live event feed for a project
// (optionally scoped to one task_id) and auto-reconnects on drop -- 02-V
// §2.2's "实时连接已断开,正在重连" exception state. REQ-12's deeper
// reconnect-catch-up semantics are U-024.5's job (03-C §3.14 itself routes
// that through REST snapshots, not WS replay); this only re-opens the
// socket and reports connection status back to the caller.
function connectEventSocket(projectId, taskId, { onEvent, onStatusChange }) {
  const wsProtocol = window.location.protocol === "https:" ? "wss:" : "ws:";
  let url = wsProtocol + "//" + window.location.host + "/api/ws/projects/" + encodeURIComponent(projectId);
  if (taskId) url += "?task_id=" + encodeURIComponent(taskId);

  let closedByCaller = false;
  let socket = null;

  function open() {
    socket = new WebSocket(url);
    socket.onopen = () => onStatusChange("connected");
    socket.onmessage = (event) => onEvent(JSON.parse(event.data));
    socket.onclose = () => {
      if (closedByCaller) return;
      onStatusChange("disconnected");
      setTimeout(open, 2000);
    };
    socket.onerror = () => socket.close();
  }
  open();

  return {
    close: () => {
      closedByCaller = true;
      if (socket) socket.close();
    },
  };
}

// c_ws_log_tail (03-C §3.6.2, U-027): live tail for one Work Node's raw log.
// No auto-reconnect here, unlike connectEventSocket -- 03-C is explicit that
// the server closes this connection on purpose once the node reaches a
// terminal status, and the caller (mountLogViewer) is expected to switch to
// c_execution_log_get's static mode on close, not treat it as a dropped
// connection to retry.
function connectLogTailSocket(nodeExecId, { onChunk, onClose }) {
  const wsProtocol = window.location.protocol === "https:" ? "wss:" : "ws:";
  const url = wsProtocol + "//" + window.location.host + "/api/ws/work-nodes/" + encodeURIComponent(nodeExecId) + "/log";
  const socket = new WebSocket(url);
  socket.onmessage = (event) => onChunk(JSON.parse(event.data).appended_content);
  socket.onclose = () => onClose();
  socket.onerror = () => socket.close();
  return { close: () => socket.close() };
}

const routes = {
  "#/": { render: renderDashboard, mount: mountDashboard },
  "#/projects": { render: renderProjectList, mount: mountProjectList },
  "#/tasks": { render: renderTaskBoard, mount: mountTaskBoard },
  "#/graph": { render: renderGraphConsole, mount: mountGraphConsole },
  "#/artifacts": { render: renderArtifactBrowser, mount: mountArtifactBrowser },
  "#/skills": { render: renderSkillLibrary, mount: mountSkillLibrary },
  "#/deployment": { render: renderDeploymentStatus, mount: mountDeploymentStatus },
  "#/settings/concurrency": { render: renderConcurrencySettings, mount: mountConcurrencySettings },
  "#/settings/budget": { render: renderBudgetSettings, mount: mountBudgetSettings },
  "#/settings/log-retention": { render: renderLogRetentionSettings, mount: mountLogRetentionSettings },
  "#/setup": { render: renderProjectSetup, mount: mountProjectSetup },
  "#/goals/new": { render: renderGoalComposer, mount: mountGoalComposer },
  "#/bugs/new": { render: renderBugFeedback, mount: mountBugFeedback },
};

// #/tasks/:task_id (v_task_detail), #/skills/:skill_id/audit
// (v_skill_audit_log), and #/artifacts/:artifact_id (v_artifact_browser,
// pre-selecting one artifact) are the only dynamic routes -- not worth a
// full path-matching router for three patterns.
const TASK_DETAIL_RE = /^#\/tasks\/([^/]+)$/;
const SKILL_AUDIT_RE = /^#\/skills\/([^/]+)\/audit$/;
const ARTIFACT_DETAIL_RE = /^#\/artifacts\/([^/]+)$/;
// Org Graph 三节点条点击可达详情 (2026-08-06 SDD, extended 2026-08-13 to 4
// values): v_dashboard's 3-node org-strip and v_task_detail's Org meta-graph
// (now reused from v_graph_console, see mountTaskDetail below) both route
// here. `:org_node` is restricted to the four real values on purpose --
// anything else (typo, stray path segment) falls through to the "Not found"
// fallback in render() instead of reaching renderTaskDetail/mountTaskDetail
// with a bogus org_node that would otherwise need its own defensive checks
// further down. `planner_reviewer` was added so deep links into the 4th Org
// meta-graph stage are reachable, even though v_dashboard's own org-strip
// stays 3-node (planner/coder/validator only) and never links to it.
const ORG_NODE_DETAIL_RE = /^#\/tasks\/([^/]+)\/org\/(planner|planner_reviewer|coder|validator)$/;
// v_run_detail (U-046, 2026-08-06 SDD): "运行历史" (`#gc_runs_list`)
// previously had nowhere real to send a click -- it just called
// onSwitchToTask to switch v_graph_console's own task selector. This is the
// actual run-detail page/route that closes that gap.
const RUN_DETAIL_RE = /^#\/runs\/([^/]+)$/;

let currentRouteCleanup = null;
function registerRouteCleanup(fn) {
  currentRouteCleanup = fn;
}

// U-047: `#/tasks?status=done`-style query strings on hash routes -- a new
// capability, not a bug fix (no route previously carried a query string).
// Hand-rolled instead of `new URLSearchParams(...)` (which mountTaskBoard's
// own outgoing-request building already uses) because this one also has to
// run inside frontend/test_*_smoke.js's bare `vm.createContext` sandbox,
// which has no WHATWG URL globals -- decodeURIComponent is a plain
// ECMAScript global and works there unmodified.
function parseHashQuery(hash) {
  const qIndex = hash.indexOf("?");
  if (qIndex === -1) return { path: hash, params: {} };
  const path = hash.slice(0, qIndex);
  const params = {};
  for (const pair of hash.slice(qIndex + 1).split("&")) {
    if (!pair) continue;
    const eqIndex = pair.indexOf("=");
    const key = eqIndex === -1 ? pair : pair.slice(0, eqIndex);
    const value = eqIndex === -1 ? "" : pair.slice(eqIndex + 1);
    params[decodeURIComponent(key)] = decodeURIComponent(value);
  }
  return { path, params };
}

function render() {
  if (currentRouteCleanup) {
    currentRouteCleanup();
    currentRouteCleanup = null;
  }

  const rawHash = window.location.hash || "#/";
  const { path: hash, params: queryParams } = parseHashQuery(rawHash);
  let route = routes[hash];
  let routeArgs = [];
  if (!route) {
    const taskMatch = hash.match(TASK_DETAIL_RE);
    const orgNodeMatch = hash.match(ORG_NODE_DETAIL_RE);
    const skillMatch = hash.match(SKILL_AUDIT_RE);
    const artifactMatch = hash.match(ARTIFACT_DETAIL_RE);
    const runMatch = hash.match(RUN_DETAIL_RE);
    if (orgNodeMatch) {
      // Reuses v_task_detail itself (same render/mount) with the org_node
      // carried through as a second arg -- no separate view/route handler.
      route = { render: renderTaskDetail, mount: mountTaskDetail };
      routeArgs = [orgNodeMatch[1], orgNodeMatch[2]];
    } else if (taskMatch) {
      route = { render: renderTaskDetail, mount: mountTaskDetail };
      routeArgs = [taskMatch[1]];
    } else if (skillMatch) {
      route = { render: renderSkillAuditLog, mount: mountSkillAuditLog };
      routeArgs = [skillMatch[1]];
    } else if (artifactMatch) {
      // Reuses v_artifact_browser itself (same render/mount as "#/artifacts")
      // with the artifact_id pre-selected -- no separate detail view.
      route = { render: renderArtifactBrowser, mount: mountArtifactBrowser };
      routeArgs = [artifactMatch[1]];
    } else if (runMatch) {
      route = { render: renderRunDetail, mount: mountRunDetail };
      routeArgs = [runMatch[1]];
    }
  }
  if (!route) route = { render: () => "<h1>Not found</h1><p>" + hash + "</p>" };

  document.getElementById("app").innerHTML = route.render(...routeArgs);
  // queryParams always appended after any route-specific captures -- every
  // mount() so far only declares the params it actually reads (e.g.
  // mountTaskBoard(queryParams)), so this trailing arg is silently ignored
  // by the rest (plain JS behavior, not a special case per route).
  if (route.mount) route.mount(...routeArgs, queryParams);

  // `#nav > a`, not `#nav a`: nav_project_context (U-048) nests its own
  // <a> links (project name, status-bucket counts) directly inside #nav --
  // those must never get the same "active" bolding as the fixed route
  // links above them just because their target route happens to match.
  for (const a of document.querySelectorAll("#nav > a")) {
    a.classList.toggle("active", parseHashQuery(a.getAttribute("href")).path === hash);
  }
  refreshNavProjectContext();
}

window.addEventListener("hashchange", render);
window.addEventListener("DOMContentLoaded", render);

// ---- nav bar "current project" context (U-048) ----
// All pages share #nav (index.html), so this is wired into render() itself
// (called once per hashchange/initial load, see above) rather than into any
// one page's mount() -- "piggybacks on the existing hashchange listener, no
// new event plumbing needed" per the approved SDD. Reuses
// `GET /api/tasks?project_id=...` and reduces status counts client-side
// (one fetch per refresh, not one per bucket) -- a dedicated aggregation
// endpoint is a documented revisit if a single project ever reaches
// ~1000-2000 tasks.

// 10 raw task.status values (TASK_STATUSES below, v_task_board) collapsed
// into the 4 buckets the nav bar shows. `statuses.length === 1` buckets
// (pending/done) link to "#/tasks?status=<value>" -- v_task_board's status
// filter is single-select, so multi-status buckets (running/attention) link
// to the unfiltered "#/tasks" instead of picking one arbitrary status.
const NAV_STATUS_BUCKETS = [
  { key: "pending", label: "pending", statuses: ["queued"] },
  { key: "running", label: "running", statuses: [
    "planning_brd_prd_sdd", "coding", "validating", "routed_fast_lane", "routed_full_replan",
  ] },
  { key: "attention", label: "attention", statuses: [
    "planning_failed", "coding_failed", "blocked_pending_human",
  ] },
  { key: "done", label: "done", statuses: ["done"] },
];

function navBucketHref(bucket) {
  return bucket.statuses.length === 1 ? "#/tasks?status=" + bucket.statuses[0] : "#/tasks";
}

function computeNavStatusBucketCounts(tasks) {
  const statusToBucketKey = {};
  for (const bucket of NAV_STATUS_BUCKETS) {
    for (const status of bucket.statuses) statusToBucketKey[status] = bucket.key;
  }
  const counts = {};
  for (const bucket of NAV_STATUS_BUCKETS) counts[bucket.key] = 0;
  for (const task of tasks) {
    const bucketKey = statusToBucketKey[task.status];
    if (bucketKey) counts[bucketKey]++;
  }
  return counts;
}

function renderNavProjectContextHtml(project, counts) {
  if (!project) return "";
  const countsHtml = NAV_STATUS_BUCKETS.map((bucket) =>
    '<a class="nav-count nav-count-' + bucket.key + '" href="' + navBucketHref(bucket) + '">'
    + escapeHtml(bucket.label) + " " + (counts[bucket.key] || 0) + "</a>"
  ).join("");
  return (
    '<a id="nav_project_name" href="#/projects">' + escapeHtml(project.name) + "</a>"
    + '<span class="nav-counts">' + countsHtml + "</span>"
  );
}

// Guards against out-of-order responses: if the current project is switched
// (or this fires again before an earlier fetch resolves), a stale response
// landing after a newer one must not overwrite the nav with old data.
let navProjectContextRequestId = 0;

async function refreshNavProjectContext() {
  const contextEl = document.getElementById("nav_project_context");
  if (!contextEl) return;
  const projectId = getCurrentProjectId();
  const requestId = ++navProjectContextRequestId;
  if (!projectId) {
    // Requirement 1: no project selected -> render nothing, not a hint.
    contextEl.innerHTML = "";
    return;
  }
  try {
    const [projectResp, tasksResp] = await Promise.all([
      fetch("/api/projects/" + encodeURIComponent(projectId)),
      fetch("/api/tasks?project_id=" + encodeURIComponent(projectId)),
    ]);
    if (requestId !== navProjectContextRequestId) return; // superseded by a newer refresh
    if (projectResp.status !== 200) {
      contextEl.innerHTML = "";
      return;
    }
    const project = await projectResp.json();
    const tasks = tasksResp.status === 200 ? await tasksResp.json() : [];
    if (requestId !== navProjectContextRequestId) return;
    contextEl.innerHTML = renderNavProjectContextHtml(project, computeNavStatusBucketCounts(tasks));
  } catch (e) {
    if (requestId === navProjectContextRequestId) contextEl.innerHTML = "";
  }
}

// ---- v_project_list (2026-08-03): project list + CRUD ----
// 02-V originally declared "不做完整多项目管理 UI(项目列表/切换)" as an
// MVP non-goal -- this page is a deliberate, explicit scope expansion
// beyond that, requested directly by the user. Creation still goes through
// v_project_setup's existing flow (pick a folder, optionally git-init it,
// project_scaffold.create_project() already handles a folder that already
// has real code in it correctly -- it only ever adds .graphlemon/ inside,
// nothing about "importing" needs to be built separately). This page adds
// the missing read/update/archive half: list every project, rename,
// archive/reactivate, and select one as "current" to work in.

function renderProjectList() {
  return `
    <div class="page page-wide">
      <h1>项目</h1>
      <div class="actions" style="margin-top:0;">
        <a class="btn btn-primary" href="#/setup">+ 新建 / 导入项目</a>
      </div>
      <table class="data-table">
        <thead>
          <tr><th>名称</th><th>目标目录</th><th>状态</th><th>Goal 数</th><th>创建时间</th><th></th></tr>
        </thead>
        <tbody id="pl_rows"></tbody>
      </table>
    </div>
  `;
}

function mountProjectList() {
  const rowsEl = document.getElementById("pl_rows");

  async function refresh() {
    const resp = await fetch("/api/projects");
    const projects = await resp.json();
    if (projects.length === 0) {
      rowsEl.innerHTML = '<tr><td colspan="6">还没有项目,<a href="#/setup">创建一个</a></td></tr>';
      return;
    }
    rowsEl.innerHTML = projects.map((p) => (
      '<tr data-project-id="' + p.project_id + '">'
      + '<td><span class="pl-name-view" data-project-id="' + p.project_id + '">' + escapeHtml(p.name) + "</span>"
      + '<span class="pl-name-edit" data-project-id="' + p.project_id + '" style="display:none;">'
      + '<input type="text" class="pl-name-input" value="' + escapeHtml(p.name) + '">'
      + '<button class="btn" data-action="save-rename" data-project-id="' + p.project_id + '" type="button">✓</button>'
      + '<button class="btn" data-action="cancel-rename" data-project-id="' + p.project_id + '" type="button">✕</button>'
      + "</span></td>"
      + "<td>" + escapeHtml(p.target_folder_path) + "</td>"
      + '<td><span class="badge ' + (p.status === "active" ? "done" : "") + '">' + p.status + "</span></td>"
      + "<td>" + p.goal_count + "</td>"
      + "<td>" + escapeHtml(p.created_at) + "</td>"
      + "<td>"
      + '<button class="btn" data-action="select" data-project-id="' + p.project_id + '" type="button">选择</button> '
      + '<button class="btn" data-action="rename" data-project-id="' + p.project_id + '" type="button">重命名</button> '
      + '<button class="btn' + (p.status === "active" ? " btn-danger" : "") + '" data-action="toggle-status" '
      + 'data-project-id="' + p.project_id + '" data-current-status="' + p.status + '" type="button">'
      + (p.status === "active" ? "归档" : "恢复")
      + "</button>"
      + "</td>"
      + "</tr>"
    )).join("");

    for (const btn of rowsEl.querySelectorAll('button[data-action="select"]')) {
      btn.addEventListener("click", () => {
        setCurrentProjectId(btn.dataset.projectId);
        window.location.hash = "#/tasks";
      });
    }
    for (const btn of rowsEl.querySelectorAll('button[data-action="rename"]')) {
      btn.addEventListener("click", () => {
        const id = btn.dataset.projectId;
        rowsEl.querySelector('.pl-name-view[data-project-id="' + id + '"]').style.display = "none";
        rowsEl.querySelector('.pl-name-edit[data-project-id="' + id + '"]').style.display = "inline-block";
      });
    }
    for (const span of rowsEl.querySelectorAll(".pl-name-edit")) {
      const id = span.dataset.projectId;
      span.querySelector('[data-action="cancel-rename"]').addEventListener("click", () => {
        span.style.display = "none";
        rowsEl.querySelector('.pl-name-view[data-project-id="' + id + '"]').style.display = "";
      });
      span.querySelector('[data-action="save-rename"]').addEventListener("click", () => {
        const newName = span.querySelector(".pl-name-input").value.trim();
        if (!newName) return;
        fetch("/api/projects/" + encodeURIComponent(id), {
          method: "PUT",
          body: JSON.stringify({ name: newName }),
        }).then(refresh);
      });
    }
    for (const btn of rowsEl.querySelectorAll('button[data-action="toggle-status"]')) {
      btn.addEventListener("click", () => {
        const nextStatus = btn.dataset.currentStatus === "active" ? "archived" : "active";
        fetch("/api/projects/" + encodeURIComponent(btn.dataset.projectId), {
          method: "PUT",
          body: JSON.stringify({ status: nextStatus }),
        }).then(refresh);
      });
    }
  }

  refresh();
}

// ---- v_project_setup (02-V §2.1): create/switch project ----

function renderProjectSetup() {
  return `
    <div class="top-back"><a href="#/">← 返回仪表盘</a></div>
    <div class="page">
      <h1>创建 / 切换项目</h1>
      <div class="page-sub">选择一个本地文件夹作为目标项目的代码空间</div>
      <div class="panel">
        <div id="setup_error" class="error-banner" style="display:none;"></div>
        <div class="field">
          <label>目标文件夹(folder_path)</label>
          <input type="text" id="folder_path" readonly value="">
          <div class="hint" id="folder_path_hint">点击"选择文件夹"会由后端代为弹出系统原生对话框,不支持手动输入路径(除非返回 DIALOG_UNAVAILABLE)</div>
        </div>
        <button class="btn" id="btn_pick_folder" type="button">📁 选择文件夹</button>
        <div class="field" style="margin-top:20px;">
          <label>项目名称(project_name,非必填)</label>
          <input type="text" id="project_name" placeholder="留空则取文件夹名">
        </div>
        <div class="btn-row">
          <button class="btn btn-primary" id="btn_create" type="button">创建项目</button>
        </div>
        <div class="confirm-banner" id="confirm_banner" style="display:none;">
          该文件夹还不是 Git 仓库,是否代为初始化(<code>git init</code>)?确认前不写入任何文件。
          <div class="btn-row" style="margin-top:10px;">
            <button class="btn" id="btn_cancel_init" type="button">取消</button>
            <button class="btn btn-primary" id="btn_confirm_init" type="button">确认初始化并创建项目</button>
          </div>
        </div>
      </div>
    </div>
  `;
}

function mountProjectSetup() {
  const folderInput = document.getElementById("folder_path");
  const folderHint = document.getElementById("folder_path_hint");
  const nameInput = document.getElementById("project_name");
  const errorBox = document.getElementById("setup_error");
  const confirmBanner = document.getElementById("confirm_banner");

  function showError(message) {
    errorBox.textContent = message;
    errorBox.style.display = "block";
  }
  function clearError() {
    errorBox.style.display = "none";
  }

  document.getElementById("btn_pick_folder").addEventListener("click", async () => {
    clearError();
    const resp = await fetch("/api/system/pick-folder", { method: "POST", body: "{}" });
    const body = await resp.json();
    if (resp.status === 422 && body.error === "DIALOG_UNAVAILABLE") {
      folderInput.removeAttribute("readonly");
      folderHint.textContent = "当前环境不支持弹窗选择,请手动输入路径";
      return;
    }
    if (body.selected_path) {
      folderInput.value = body.selected_path;
    }
    // user canceled the native dialog -> folder_path stays as it was (02-V §2.1)
  });

  async function createProject(initGitIfMissing) {
    clearError();
    confirmBanner.style.display = "none";
    const folderPath = folderInput.value.trim();
    if (!folderPath) {
      showError("请先选择目标文件夹");
      return;
    }
    const resp = await fetch("/api/projects", {
      method: "POST",
      body: JSON.stringify({
        target_folder_path: folderPath,
        name: nameInput.value.trim() || undefined,
        init_git_if_missing: initGitIfMissing,
      }),
    });
    const body = await resp.json();
    if (resp.status === 200) {
      setCurrentProjectId(body.project_id);
      window.location.hash = "#/";
      return;
    }
    if (body.error === "GIT_INIT_DECLINED") {
      confirmBanner.style.display = "block";
      return;
    }
    showError(body.error + (body.detail ? ":" + body.detail : ""));
  }

  document.getElementById("btn_create").addEventListener("click", () => createProject(false));
  document.getElementById("btn_confirm_init").addEventListener("click", () => createProject(true));
  document.getElementById("btn_cancel_init").addEventListener("click", () => {
    confirmBanner.style.display = "none";
  });
}

// ---- shared: pages that need a "current project" to already exist ----

function renderNoProjectSelected() {
  return `
    <div class="page">
      <div class="error-banner" style="display:block;">
        还没有选择项目。请先<a href="#/setup">创建或切换项目</a>。
      </div>
    </div>
  `;
}

// ---- v_goal_composer (02-V §2.3): propose a new goal ----

const GOAL_TEXT_MAX_LEN = 4000;

function renderGoalComposer() {
  if (!getCurrentProjectId()) return renderNoProjectSelected();
  return `
    <div class="top-back"><a href="#/">← 返回仪表盘</a></div>
    <div class="page">
      <h1>提出新目标</h1>
      <div class="page-sub">用自然语言描述你想让 graphlemon 完成的目标</div>
      <div class="panel">
        <div id="goal_error" class="error-banner" style="display:none;"></div>
        <div class="field" id="goal_form">
          <label>目标描述(goal_text,必填,最长 ${GOAL_TEXT_MAX_LEN} 字)</label>
          <textarea id="goal_text" rows="6" maxlength="${GOAL_TEXT_MAX_LEN}"></textarea>
          <div class="btn-row">
            <button class="btn btn-primary" id="btn_submit_goal" type="button">创建任务</button>
          </div>
        </div>
        <div class="confirm-banner" id="goal_confirm_banner" style="display:none;">
          <div id="goal_confirm_summary"></div>
          <div class="btn-row" style="margin-top:10px;">
            <button class="btn" id="btn_edit_goal" type="button">返回编辑</button>
            <button class="btn btn-primary" id="btn_confirm_goal" type="button">确认创建</button>
          </div>
        </div>
      </div>
    </div>
  `;
}

function mountGoalComposer() {
  if (!getCurrentProjectId()) return;
  const textArea = document.getElementById("goal_text");
  const errorBox = document.getElementById("goal_error");
  const form = document.getElementById("goal_form");
  const confirmBanner = document.getElementById("goal_confirm_banner");
  const confirmSummary = document.getElementById("goal_confirm_summary");

  document.getElementById("btn_submit_goal").addEventListener("click", () => {
    errorBox.style.display = "none";
    const goalText = textArea.value.trim();
    if (!goalText) {
      errorBox.textContent = "目标描述不能为空";
      errorBox.style.display = "block";
      return;
    }
    confirmSummary.textContent = "即将创建任务:" + goalText;
    form.style.display = "none";
    confirmBanner.style.display = "block";
  });

  document.getElementById("btn_edit_goal").addEventListener("click", () => {
    confirmBanner.style.display = "none";
    form.style.display = "block";
  });

  document.getElementById("btn_confirm_goal").addEventListener("click", async () => {
    const resp = await fetch("/api/tasks", {
      method: "POST",
      body: JSON.stringify({
        project_id: getCurrentProjectId(),
        goal_text: textArea.value.trim(),
        task_type: "goal",
        created_via: "human_console",
      }),
    });
    const body = await resp.json();
    if (resp.status !== 200) {
      confirmBanner.style.display = "none";
      form.style.display = "block";
      errorBox.textContent = body.error + (body.detail ? ":" + body.detail : "");
      errorBox.style.display = "block";
      return;
    }
    // 02-V §2.3: 成功跳转 v_task_detail
    window.location.hash = "#/tasks/" + body.task_id;
  });
}

// ---- v_bug_feedback (02-V §2.4): report a bug ----

function renderBugFeedback() {
  if (!getCurrentProjectId()) return renderNoProjectSelected();
  return `
    <div class="top-back"><a href="#/">← 返回仪表盘</a></div>
    <div class="page">
      <h1>反馈 Bug</h1>
      <div class="page-sub">人工反馈,与 Validator 自动生成的 bug_record 复用同一张表(source=human)</div>
      <div class="panel">
        <div id="bug_error" class="error-banner" style="display:none;"></div>
        <div id="bug_success" class="success-banner" style="display:none;"></div>
        <div id="bug_form">
          <div class="field">
            <label>问题描述(description,必填)</label>
            <textarea id="bug_description" rows="4"></textarea>
          </div>
          <div class="field">
            <label>复现步骤(repro_steps,非必填)</label>
            <textarea id="bug_repro_steps" rows="3"></textarea>
          </div>
          <div class="field">
            <label>关联任务(related_task_id,非必填)</label>
            <select id="bug_related_task_id">
              <option value="">— 不关联,视为新发现的独立问题 —</option>
            </select>
          </div>
          <div class="btn-row">
            <button class="btn btn-primary" id="btn_submit_bug" type="button">提交反馈</button>
          </div>
        </div>
      </div>
    </div>
  `;
}

function mountBugFeedback() {
  if (!getCurrentProjectId()) return;
  const descriptionArea = document.getElementById("bug_description");
  const reproStepsArea = document.getElementById("bug_repro_steps");
  const relatedTaskIdSelect = document.getElementById("bug_related_task_id");
  const errorBox = document.getElementById("bug_error");
  const successBox = document.getElementById("bug_success");
  const form = document.getElementById("bug_form");

  fetch("/api/tasks?project_id=" + encodeURIComponent(getCurrentProjectId()))
    .then((resp) => resp.json())
    .then((tasks) => {
      for (const task of tasks) {
        const option = document.createElement("option");
        option.value = task.task_id;
        option.textContent = task.goal_text.slice(0, 40) + " (" + task.task_id.slice(0, 8) + ")";
        relatedTaskIdSelect.appendChild(option);
      }
    });

  document.getElementById("btn_submit_bug").addEventListener("click", async () => {
    errorBox.style.display = "none";
    const description = descriptionArea.value.trim();
    if (!description) {
      errorBox.textContent = "问题描述不能为空";
      errorBox.style.display = "block";
      return;
    }
    const relatedTaskId = relatedTaskIdSelect.value || undefined;
    const resp = await fetch("/api/bug-reports", {
      method: "POST",
      body: JSON.stringify({
        project_id: getCurrentProjectId(),
        description: description,
        repro_steps: reproStepsArea.value.trim() || undefined,
        related_task_id: relatedTaskId,
      }),
    });
    const body = await resp.json();
    if (resp.status !== 200) {
      errorBox.textContent = body.error + (body.detail ? ":" + body.detail : "");
      errorBox.style.display = "block";
      return;
    }
    // 02-V §2.4: 跳转到该 bug 的详情视图,MVP 复用 v_task_detail 的 bug 展示区
    // -- only possible when the report was tied to a task; otherwise there's
    // no task detail page to land on, so show the confirmation inline.
    if (relatedTaskId) {
      window.location.hash = "#/tasks/" + relatedTaskId;
      return;
    }
    form.style.display = "none";
    successBox.innerHTML = "已提交,Validator 将进行归因确认(bug <code>" + body.bug_id + "</code>)。"
      + '<a href="#/">返回仪表盘</a>';
    successBox.style.display = "block";
  });
}

// ---- v_dashboard (02-V §2.2): real-time landing page ----

const ORG_NODE_ORDER = ["planner", "coder", "validator"];

// ---- Org Graph 三节点条点击可达详情 (2026-08-06 SDD): shared by
// v_dashboard's `#org_strip` and v_task_detail's own inline org-strip below
// -- both mark each `.org-node` with `data-org-node`, both route through
// `#/tasks/:task_id/org/:org_node`, both pick "最新一次 work_graph_run" for
// that org_node the same way (C6: plain array filtering, no new backend
// query params). DAG/log/artifact display itself stays entirely inside
// renderGraphVisualizerPanel/renderTodoTree/mountLogViewer/v_artifact_browser
// (C3-C5) -- this block only does the "接线": which run is "latest", and
// where on the already-rendered page to scroll/highlight.

function getLatestRunForOrgNode(task, orgNode) {
  // 2026-08-12 (Org Graph unification Phase 2c §2.1): a run's single
  // org_node field is gone -- a merged run genuinely spans several
  // org_nodes now (Planner/Coder/Validator can all append nodes into the
  // SAME run), so "the run for this org_node" is membership in
  // org_nodes_involved (a list, one entry per distinct subagent_type
  // among the run's nodes), not equality against a single value.
  const runs = task.work_graph_runs.filter((r) => (r.org_nodes_involved || []).includes(orgNode));
  return runs.length ? runs[runs.length - 1] : null;
}

// Display label for a run's org_nodes_involved list -- everywhere this
// file used to show the single old org_node value directly.
function orgNodesLabel(run) {
  const nodes = run.org_nodes_involved || [];
  return nodes.length ? nodes.join(" + ") : "(no nodes yet)";
}

// v_dashboard's org-strip: role + hint text, only ever links out to
// v_task_detail (a genuine page change, so plain hash assignment is fine).
function renderDashboardOrgStripHtml(activeOrgNode, runStatusByOrgNode) {
  return ORG_NODE_ORDER.map((node, i) => {
    const isActive = activeOrgNode === node;
    const runStatus = runStatusByOrgNode[node];
    const hint = isActive ? "当前节点" : runStatus === "done" ? "已完成" : runStatus || "未开始";
    const arrow = i < ORG_NODE_ORDER.length - 1 ? '<div class="org-arrow">→</div>' : "";
    return '<div class="org-node' + (isActive ? " active" : "") + '" data-org-node="' + node + '"><div class="role">'
      + node + '</div><div class="hint">' + escapeHtml(hint) + "</div></div>" + arrow;
  }).join("");
}

function mountOrgStripClicks(container, taskId) {
  if (!taskId) return;
  for (const el of container.querySelectorAll(".org-node[data-org-node]")) {
    el.addEventListener("click", () => {
      window.location.hash = "#/tasks/" + taskId + "/org/" + el.dataset.orgNode;
    });
  }
}

function renderDashboard() {
  if (!getCurrentProjectId()) return renderNoProjectSelected();
  return `
    <div class="page page-wide">
      <h1>仪表盘</h1>
      <div id="quota_info_banner" class="info-banner" style="display:none;"></div>
      <div id="ws_disconnected_banner" class="error-banner" style="display:none;">实时连接已断开,正在重连…</div>
      <div class="grid">
        <div>
          <div class="panel">
            <h2>Org Graph 三节点状态</h2>
            <div class="org-strip" id="org_strip"></div>
          </div>
          <div class="panel">
            <h2>当前任务概要</h2>
            <div class="task-summary" id="task_summary"></div>
          </div>
          <div class="actions">
            <a class="btn btn-primary" href="#/goals/new">+ 提出新目标</a>
            <a class="btn" href="#/bugs/new">反馈 Bug</a>
          </div>
        </div>
        <div>
          <div class="panel">
            <h2>预算用量</h2>
            <div id="budget_summary"></div>
          </div>
          <div class="panel">
            <h2>最近事件</h2>
            <div id="event_timeline"></div>
          </div>
        </div>
      </div>
    </div>
  `;
}

function mountDashboard() {
  const projectId = getCurrentProjectId();
  if (!projectId) return;

  const orgStrip = document.getElementById("org_strip");
  const taskSummary = document.getElementById("task_summary");
  const budgetSummary = document.getElementById("budget_summary");
  const eventTimeline = document.getElementById("event_timeline");
  const quotaBanner = document.getElementById("quota_info_banner");
  const wsBanner = document.getElementById("ws_disconnected_banner");
  const recentEvents = [];
  // Set right before every renderOrgStrip() call below -- org-strip clicks
  // need to know which task_id to route to (#/tasks/:task_id/org/:org_node).
  let orgStripTaskId = null;

  function renderOrgStrip(activeOrgNode, runStatusByOrgNode) {
    orgStrip.innerHTML = renderDashboardOrgStripHtml(activeOrgNode, runStatusByOrgNode);
    mountOrgStripClicks(orgStrip, orgStripTaskId);
  }

  async function refreshTasksAndOrgGraph() {
    const resp = await fetch("/api/tasks?project_id=" + encodeURIComponent(projectId));
    const tasks = await resp.json();
    const active = tasks.find((t) => t.status !== "done") || tasks[0];
    if (!active) {
      orgStripTaskId = null;
      orgStrip.innerHTML = '<div class="hint">暂无运行中任务</div>';
      taskSummary.innerHTML = '<div class="hint">暂无运行中任务 · <a href="#/goals/new">提出第一个目标 →</a></div>';
      quotaBanner.style.display = "none";
      return;
    }
    orgStripTaskId = active.task_id;
    // v_dashboard Start affordance (2026-08-03): the full Pause/Stop set
    // only makes sense on v_task_detail (they need the task's own status
    // context to pick which one to show) -- the dashboard only ever needs
    // "queued and nothing has started yet", so it gets just Start.
    const startRowHtml = active.status !== "queued" ? "" : (
      '<div class="row"><span></span><span>'
      + '<button class="btn btn-primary" id="db_start_task" type="button">开始(execute)</button>'
      + "</span></div>"
    );
    taskSummary.innerHTML = (
      '<div class="row"><span>Goal</span><span>' + escapeHtml(active.goal_text) + "</span></div>"
      + '<div class="row"><span>Loop Round</span><span>' + active.loop_round + "</span></div>"
      + '<div class="row"><span>Status</span><span><a href="#/tasks/' + active.task_id + '">'
      + escapeHtml(active.status) + "</a></span></div>"
      + startRowHtml
    );
    const dbStartBtn = document.getElementById("db_start_task");
    if (dbStartBtn) {
      dbStartBtn.addEventListener("click", async () => {
        dbStartBtn.disabled = true;
        await fetch("/api/tasks/" + active.task_id + "/execute", { method: "POST" });
        refreshTasksAndOrgGraph();
      });
    }

    const detailResp = await fetch("/api/tasks/" + active.task_id);
    const detail = await detailResp.json();
    const runStatusByOrgNode = {};
    let waitingNode = null;
    for (const run of detail.work_graph_runs) {
      for (const orgNode of run.org_nodes_involved || []) runStatusByOrgNode[orgNode] = run.status;
      if (!waitingNode) waitingNode = run.nodes.find((n) => n.status === "waiting_for_quota");
    }
    renderOrgStrip(active.assigned_org_node, runStatusByOrgNode);

    if (waitingNode) {
      quotaBanner.innerHTML = "🕐 有任务正在等待 Claude Code 额度恢复 · "
        + '<a href="#/tasks/' + active.task_id + '">查看详情</a>';
      quotaBanner.style.display = "flex";
    } else {
      quotaBanner.style.display = "none";
    }
  }

  async function refreshBudget() {
    const resp = await fetch("/api/settings/budget");
    const configs = await resp.json();
    if (configs.length === 0) {
      budgetSummary.innerHTML = '<div class="hint">预算护栏未配置</div>';
      return;
    }
    const c = configs[0];
    const pct = c.limit_value > 0 ? Math.min(100, Math.round((c.current_usage / c.limit_value) * 100)) : 0;
    budgetSummary.innerHTML = (
      '<div style="font-size:13px;">' + c.current_usage.toLocaleString() + " / "
      + c.limit_value.toLocaleString() + " " + escapeHtml(c.limit_type) + "</div>"
      + '<div class="progress"><div class="fill" style="width:' + pct + '%"></div></div>'
    );
  }

  function prependEvent(event) {
    recentEvents.unshift(event);
    recentEvents.length = Math.min(recentEvents.length, 20);
    eventTimeline.innerHTML = recentEvents.map((e) =>
      '<div class="event-item"><div>' + escapeHtml(e.event_type) + '</div><div class="t">'
      + escapeHtml(e.created_at || "") + "</div></div>"
    ).join("") || '<div class="hint">暂无事件</div>';
  }

  refreshTasksAndOrgGraph();
  refreshBudget();
  eventTimeline.innerHTML = '<div class="hint">暂无事件</div>';

  let wasDisconnected = false;
  const socket = connectEventSocket(projectId, null, {
    onEvent: (event) => {
      prependEvent(event);
      refreshTasksAndOrgGraph();
      if (event.event_type === "budget_updated") refreshBudget();
    },
    onStatusChange: (status) => {
      wsBanner.style.display = status === "disconnected" ? "block" : "none";
      if (status === "disconnected") {
        wasDisconnected = true;
      } else if (status === "connected" && wasDisconnected) {
        // REQ-12 boundary: reconnect doesn't replay every missed event, but
        // must at least catch up on current state via a fresh snapshot
        // fetch (03-C §3.14's own documented reconnect story).
        wasDisconnected = false;
        refreshTasksAndOrgGraph();
        refreshBudget();
      }
    },
  });
  registerRouteCleanup(() => socket.close());
}

// ---- v_task_board (02-V §2.5): task list with filters ----

const TASK_STATUSES = [
  "queued", "planning_brd_prd_sdd", "planning_failed", "coding", "coding_failed",
  "validating", "routed_fast_lane", "routed_full_replan", "blocked_pending_human", "done",
];

function renderTaskBoard() {
  if (!getCurrentProjectId()) return renderNoProjectSelected();
  return `
    <div class="page page-wide">
      <h1>任务看板</h1>
      <div class="actions" style="margin-top:0;">
        <a class="btn btn-primary" href="#/goals/new">+ 提出新目标</a>
      </div>
      <div class="filters">
        <input type="text" id="tb_keyword" placeholder="搜索 goal_text" maxlength="128">
        <select id="tb_status">
          <option value="">全部状态</option>
          ${TASK_STATUSES.map((s) => '<option value="' + s + '">' + s + "</option>").join("")}
        </select>
        <select id="tb_org_node">
          <option value="">全部 Org 节点</option>
          <option value="planner">planner</option>
          <option value="coder">coder</option>
          <option value="validator">validator</option>
        </select>
        <select id="tb_sort">
          <option value="updated_at:desc">按更新时间(新→旧)</option>
          <option value="updated_at:asc">按更新时间(旧→新)</option>
          <option value="created_at:desc">按创建时间(新→旧)</option>
          <option value="created_at:asc">按创建时间(旧→新)</option>
          <option value="goal_text:asc">按 goal_text(A→Z)</option>
          <option value="status:asc">按状态</option>
        </select>
      </div>
      <table class="data-table">
        <thead>
          <tr><th>task_id</th><th>goal_text</th><th>status</th><th>assigned_org_node</th><th>loop_round</th><th>updated_at</th></tr>
        </thead>
        <tbody id="tb_rows"></tbody>
      </table>
    </div>
  `;
}

// U-047/U-048: nav-bar status-bucket links land on #/tasks as
// "?status=<value>" -- this picks the status to pre-select, on initial
// mount only (same reasoning as v_task_board's other filters: it's a
// starting value the user can then change, not re-applied on every route
// re-render). An unrecognized/stale status value is ignored rather than
// left in a select the <option> list doesn't actually have. Split out as
// its own pure function so it's testable without a real <select> element.
function pickInitialTaskBoardStatus(queryParams) {
  if (queryParams && queryParams.status && TASK_STATUSES.includes(queryParams.status)) {
    return queryParams.status;
  }
  return null;
}

function mountTaskBoard(queryParams) {
  const projectId = getCurrentProjectId();
  if (!projectId) return;
  const rowsEl = document.getElementById("tb_rows");
  const keywordEl = document.getElementById("tb_keyword");
  const statusEl = document.getElementById("tb_status");
  const orgNodeEl = document.getElementById("tb_org_node");
  const sortEl = document.getElementById("tb_sort");

  const initialStatus = pickInitialTaskBoardStatus(queryParams);
  if (initialStatus) statusEl.value = initialStatus;

  async function refresh() {
    const params = new URLSearchParams({ project_id: projectId });
    if (keywordEl.value.trim()) params.set("keyword", keywordEl.value.trim());
    if (statusEl.value) params.set("status", statusEl.value);
    if (orgNodeEl.value) params.set("org_node", orgNodeEl.value);
    const [sortField, sortOrder] = sortEl.value.split(":");
    params.set("sort", sortField);
    params.set("order", sortOrder);
    const resp = await fetch("/api/tasks?" + params.toString());
    const tasks = await resp.json();
    if (tasks.length === 0) {
      rowsEl.innerHTML = '<tr><td colspan="6">暂无任务</td></tr>';
      return;
    }
    rowsEl.innerHTML = tasks.map((t) => (
      '<tr data-task-id="' + t.task_id + '">'
      // task_id links straight to Graph 控制台 (#/graph?task_id=...) so a
      // task can be located there directly, without going through the row's
      // own click-through to #/tasks/:task_id first -- stopPropagation on
      // the anchor keeps that row click-through intact for the other cells.
      + '<td><a href="#/graph?task_id=' + encodeURIComponent(t.task_id) + '" onclick="event.stopPropagation()">' + t.task_id + "</a></td>"
      + "<td>" + escapeHtml(t.goal_text) + "</td>"
      + '<td><span class="badge ' + t.status + '">' + t.status + "</span></td>"
      + "<td>" + t.assigned_org_node + "</td>"
      + "<td>" + t.loop_round + "</td>"
      + "<td>" + escapeHtml(t.updated_at) + "</td>"
      + "</tr>"
    )).join("");
    for (const row of rowsEl.querySelectorAll("tr[data-task-id]")) {
      row.addEventListener("click", () => {
        window.location.hash = "#/tasks/" + row.dataset.taskId;
      });
    }
  }

  keywordEl.addEventListener("input", refresh);
  statusEl.addEventListener("change", refresh);
  orgNodeEl.addEventListener("change", refresh);
  sortEl.addEventListener("change", refresh);
  refresh();

  let wasDisconnected = false;
  const socket = connectEventSocket(projectId, null, {
    onEvent: (event) => {
      if (event.event_type === "task_status_changed") refresh();
    },
    onStatusChange: (status) => {
      if (status === "disconnected") {
        wasDisconnected = true;
      } else if (status === "connected" && wasDisconnected) {
        // REQ-12 boundary: catch up via a fresh snapshot on reconnect.
        wasDisconnected = false;
        refresh();
      }
    },
  });
  registerRouteCleanup(() => socket.close());
}

// ---- v_graph_visualizer (02-V §2.7): embedded Work Graph DAG, layered by
// execution depth (computed from graph_manifest's depends_on edges) and
// colored by work_node_execution.status. Not an independent route --
// embedded into v_task_detail below. The Org Graph layer from the same
// spec section is skipped here since v_task_detail already renders an
// equivalent org-strip panel just above (same classes/data); duplicating
// it a second time immediately below would just be redundant scroll.

function computeGraphLayers(manifestNodes) {
  const nodesById = {};
  for (const n of manifestNodes) nodesById[n.node_id] = n;
  const layerById = {};

  function layerOf(nodeId, seen) {
    if (nodeId in layerById) return layerById[nodeId];
    if (seen.has(nodeId)) return 0; // dependency cycle -- shouldn't happen, don't loop forever
    seen.add(nodeId);
    const deps = (nodesById[nodeId] && nodesById[nodeId].depends_on) || [];
    const layer = deps.length === 0 ? 0 : 1 + Math.max(...deps.map((d) => layerOf(d, seen)));
    layerById[nodeId] = layer;
    return layer;
  }

  for (const n of manifestNodes) layerOf(n.node_id, new Set());
  const maxLayer = manifestNodes.length ? Math.max(...manifestNodes.map((n) => layerById[n.node_id])) : -1;
  const rows = Array.from({ length: maxLayer + 1 }, () => []);
  for (const n of manifestNodes) rows[layerById[n.node_id]].push(n);
  return rows;
}

const GRAPH_LEGEND_HTML = [
  ["pending", "status-pending"], ["running", "status-running"],
  ["reflecting / retrying", "status-reflecting"], ["waiting_for_quota(信息态,非告警)", "status-waiting_for_quota"],
  ["blocked / failed", "status-blocked"], ["done", "status-done"],
].map(([label, cls]) =>
  '<div class="legend-item"><span class="legend-swatch ' + cls + '"></span>' + label + "</div>"
).join("");

// 2026-08-08 (Work Graph self-planning + loop-back): how many times
// node_id was sent back to ITSELF (on_fail.action='retry_self' -- source
// and target are the same node, so there's no on_failure edge to draw,
// see work_graph_orchestrate.py's _LoopBackRequested/_on_failure_target
// design comment). Returns 0 if run.loop_back_events is absent (older
// runs/tasks predating this field) or empty.
function countSelfLoopAttempts(run, nodeId) {
  return (run.loop_back_events || []).filter(
    (e) => e.source_node_id === nodeId && e.target_node_id === nodeId
  ).length;
}

function renderGraphVisualizerPanel(run, options) {
  if (!run.graph_manifest || run.graph_manifest.nodes.length === 0) return "";
  // FR-4 (v_graph_console, 2026-08-03): `options` is new and optional --
  // every existing call site (v_task_detail's `task.work_graph_runs.map(
  // renderGraphVisualizerPanel)`) keeps calling this with a single arg, so
  // `enableNodeClick` stays falsy there and the emitted DOM is byte-for-byte
  // what it always was (no clickable class, no data-clickable-node-exec-id,
  // no log-viewer-slot) -- v_task_detail's existing hover-tooltip-only
  // behavior is unaffected. Only v_graph_console opts in.
  const enableNodeClick = options && options.enableNodeClick;
  const nodesById = {};
  for (const n of run.nodes) nodesById[n.node_id] = n;
  const rowsHtml = computeGraphLayers(run.graph_manifest.nodes).map((row) => {
    const cellsHtml = row.map((gn) => {
      const wn = nodesById[gn.node_id];
      const status = wn ? wn.status : "pending";
      const quotaAttrs = wn && wn.status === "waiting_for_quota"
        ? ' data-quota-limit-type="' + escapeHtml(wn.quota_limit_type || "")
          + '" data-quota-wait-since="' + escapeHtml(wn.quota_wait_started_at || "") + '"'
        : "";
      const clickable = enableNodeClick && wn;
      const clickableAttrs = clickable ? ' data-clickable-node-exec-id="' + wn.node_exec_id + '"' : "";
      const logSlotHtml = clickable ? '<div class="log-viewer-slot"></div>' : "";
      // 2026-08-08: retry_self loops never touch graph_manifest.edges (the
      // target IS the source, so there's nothing to draw a line to) --
      // the only place this is visible is a badge on the node itself,
      // read from loop_back_events (execution_event-backed, see
      // countSelfLoopAttempts's own comment).
      const selfLoopCount = countSelfLoopAttempts(run, gn.node_id);
      const loopBadgeHtml = selfLoopCount > 0
        ? '<span class="loop-badge" title="已原地重试 ' + selfLoopCount + ' 次(on_fail.action=retry_self)">↺ ' + selfLoopCount + "</span>"
        : "";
      return (
        '<div class="work-node status-' + status + (clickable ? " clickable" : "") + '" data-node-exec-id="' + (wn ? wn.node_exec_id : "") + '" data-node-id="' + escapeHtml(gn.node_id) + '"'
        + quotaAttrs + clickableAttrs + ">"
        + '<div class="node-id">' + escapeHtml(gn.node_id) + loopBadgeHtml + "</div>"
        + '<div class="node-skill">' + escapeHtml(wn ? wn.subagent_type : "尚未开始") + "</div>"
        + logSlotHtml
        + "</div>"
      );
    }).join("");
    return '<div class="work-row">' + cellsHtml + "</div>";
  }).join("");

  // 2026-08-08: on_failure edges (graph_manifest.edges, declared whenever a
  // node has on_fail.action='loop_back') are the ones actually worth
  // drawing as lines -- normal depends_on/needs_judgment/zero_token edges
  // are already visually implied by row order (computeGraphLayers), so
  // drawing them too would just be visual noise on top of what the rows
  // already show. Each edge is annotated with how many times it was
  // actually traversed (loop_back_events), not just declared -- a
  // loop_back that was planned but never triggered still shows as a
  // (0x) line, which is itself useful information.
  const onFailureEdges = (run.graph_manifest.edges || []).filter((e) => e.edge_type === "on_failure");
  const edgesDataJson = escapeHtml(JSON.stringify(onFailureEdges.map((e) => {
    const triggerCount = (run.loop_back_events || []).filter(
      (ev) => ev.source_node_id === e.from && ev.target_node_id === e.to
    ).length;
    return { from: e.from, to: e.to, triggerCount: triggerCount };
  })));

  return (
    // id="graph-panel-<run_id>": a stable per-run anchor (e.g. v_task_board's
    // to-do tree "同一份 graph_manifest 的另一种呈现" cross-reference) --
    // additive, doesn't change any existing class/data-* this function
    // already emitted.
    '<div class="panel" id="graph-panel-' + run.run_id + '"><h2>' + orgNodesLabel(run) + " Work Graph DAG 视图(v_graph_visualizer,run_id=" + run.run_id + ")</h2>"
    + '<div class="work-graph" data-on-failure-edges="' + edgesDataJson + '">'
    + '<svg class="graph-edges-svg"></svg>'
    + rowsHtml + "</div>"
    + '<div class="legend" style="margin-top:14px;">' + GRAPH_LEGEND_HTML
    + (onFailureEdges.length ? '<div class="legend-item"><span class="edge-sample edge-on-failure-sample"></span>loop_back(失败回路)</div>' : "")
    + "</div></div>"
  );
}

// 2026-08-08 (Work Graph self-planning + loop-back): draws the on_failure
// edges renderGraphVisualizerPanel embedded as data-on-failure-edges --
// requires REAL layout (getBoundingClientRect), so it can only run after
// the panel's HTML is actually in the document, same reason
// mountGraphVisualizerTooltips is a separate mount step rather than
// inline in the render* function. A .work-node's real width depends on
// its content, so positions can't be precomputed at render time.
function mountGraphVisualizerEdges(container) {
  for (const graph of container.querySelectorAll(".work-graph[data-on-failure-edges]")) {
    let edges;
    try {
      edges = JSON.parse(graph.dataset.onFailureEdges || "[]");
    } catch (e) {
      edges = [];
    }
    const svg = graph.querySelector(".graph-edges-svg");
    if (!svg || edges.length === 0) continue;

    const graphRect = graph.getBoundingClientRect();
    svg.setAttribute("width", graphRect.width);
    svg.setAttribute("height", graphRect.height);
    if (!svg.querySelector("defs")) {
      svg.innerHTML =
        '<defs><marker id="arrow-on-failure" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">'
        + '<path d="M0,0 L6,3 L0,6 Z" fill="#dc2626"></path></marker></defs>';
    }

    const nodeCenter = (nodeId) => {
      const el = graph.querySelector('.work-node[data-node-id="' + CSS.escape(nodeId) + '"]');
      if (!el) return null;
      const r = el.getBoundingClientRect();
      return { x: r.left - graphRect.left + r.width / 2, y: r.top - graphRect.top + r.height / 2, w: r.width, h: r.height };
    };

    const linesHtml = edges.map((edge) => {
      const from = nodeCenter(edge.from);
      const to = nodeCenter(edge.to);
      if (!from || !to) return "";
      // pull the endpoint back to the target node's edge (roughly, using
      // its own half-height) so the arrowhead doesn't render buried
      // underneath the node box.
      const dy = to.y - from.y;
      const pullBack = dy === 0 ? 0 : Math.min(to.h / 2, Math.abs(dy) / 2) * Math.sign(dy);
      const label = edge.triggerCount > 0 ? edge.triggerCount + "x" : "0x(已声明,未触发)";
      return (
        '<line x1="' + from.x + '" y1="' + from.y + '" x2="' + to.x + '" y2="' + (to.y - pullBack)
        + '" class="edge-on-failure" marker-end="url(#arrow-on-failure)"></line>'
        + '<text x="' + (from.x + to.x) / 2 + '" y="' + (from.y + to.y) / 2
        + '" class="edge-label">' + escapeHtml(label) + "</text>"
      );
    }).join("");
    svg.innerHTML = svg.querySelector("defs").outerHTML + linesHtml;
  }
}

function mountGraphVisualizerTooltips(container) {
  const tooltip = document.getElementById("graph-tooltip");
  if (!tooltip) return;
  for (const node of container.querySelectorAll(".work-node")) {
    node.addEventListener("mousemove", (evt) => {
      const lines = ["skill: " + (node.querySelector(".node-skill").textContent || "")];
      if (node.dataset.quotaLimitType) {
        lines.push("quota_limit_type: " + node.dataset.quotaLimitType);
        lines.push("已等待:" + formatWaitDuration(node.dataset.quotaWaitSince));
      }
      tooltip.innerHTML = "<b>" + escapeHtml(node.dataset.nodeExecId || node.querySelector(".node-id").textContent) + "</b><br>"
        + lines.map(escapeHtml).join("<br>");
      tooltip.style.left = evt.pageX + 12 + "px";
      tooltip.style.top = evt.pageY + 12 + "px";
      tooltip.classList.add("show");
    });
    node.addEventListener("mouseout", () => tooltip.classList.remove("show"));
  }
}

// FR-4 (v_graph_console): click-to-expand-logs, opt-in via
// renderGraphVisualizerPanel(run, { enableNodeClick: true }) above. This is
// a `click` listener, deliberately not `mousemove`/`mouseout` like
// mountGraphVisualizerTooltips -- the two can be mounted on the same
// container at once without conflicting, so v_graph_console keeps the
// hover tooltip *and* gains click-to-expand as an additive capability.
function mountWorkNodeClickExpand(container, { onNodeClick }) {
  for (const node of container.querySelectorAll(".work-node.clickable[data-clickable-node-exec-id]")) {
    node.addEventListener("click", () => {
      const nodeExecId = node.dataset.clickableNodeExecId;
      const statusClass = Array.from(node.classList).find((c) => c.startsWith("status-"));
      const status = statusClass ? statusClass.slice("status-".length) : "pending";
      onNodeClick(nodeExecId, status, node);
    });
  }
}

function formatWaitDuration(sqliteTimestamp) {
  if (!sqliteTimestamp) return "未知时长";
  const startedAt = new Date(sqliteTimestamp.replace(" ", "T") + "Z").getTime();
  const minutes = Math.max(0, Math.round((Date.now() - startedAt) / 60000));
  return minutes < 60 ? minutes + " 分钟" : Math.round(minutes / 60) + " 小时";
}

// ---- v_log_viewer (02-V §2.7.1): embedded raw execution log ----
// Non-terminal node status -> realtime scroll mode via c_ws_log_tail;
// terminal status -> one-shot static fetch via c_execution_log_get.
// Embedded per node_exec_id inside v_task_detail's to-do tree, mounted
// lazily the first time a to-do row is expanded (mountTaskDetail wires the
// click handler and tracks cleanup for whichever ones got opened).

function renderLogViewerHtml(nodeExecId) {
  return (
    '<div class="log-toolbar">'
    + '<label><input type="checkbox" class="log-autoscroll" checked> 自动滚动到最新</label>'
    + '<a class="btn" href="/api/work-nodes/' + encodeURIComponent(nodeExecId) + '/log?download=true">下载完整日志</a>'
    + "</div>"
    + '<div class="log-viewer" id="log-viewer-' + nodeExecId + '"><div class="hint">加载中…</div></div>'
  );
}

function mountLogViewer(nodeExecId, initialStatus) {
  const viewerEl = document.getElementById("log-viewer-" + nodeExecId);
  const autoScrollEl = document.querySelector('#todo-detail-' + nodeExecId + " .log-autoscroll");
  if (!viewerEl) return () => {};

  function appendLine(text) {
    const line = document.createElement("div");
    line.className = "line";
    line.textContent = text;
    viewerEl.appendChild(line);
    if (autoScrollEl && autoScrollEl.checked) viewerEl.scrollTop = viewerEl.scrollHeight;
  }

  async function loadStatic() {
    try {
      const resp = await fetch("/api/work-nodes/" + encodeURIComponent(nodeExecId) + "/log");
      if (resp.status === 404) {
        viewerEl.innerHTML = '<div class="hint">日志暂不可用</div>';
        return;
      }
      if (resp.status === 410) {
        viewerEl.innerHTML = '<div class="hint">该日志已超过保留期限被清理,保留天数可在设置中调整</div>';
        return;
      }
      const body = await resp.json();
      viewerEl.innerHTML = "";
      if (!body.content) {
        viewerEl.innerHTML = '<div class="hint">暂无日志内容</div>';
        return;
      }
      for (const line of body.content.split("\n")) appendLine(line);
    } catch (e) {
      viewerEl.innerHTML = '<div class="hint">日志暂不可用</div>';
    }
  }

  if (isTerminalNodeStatus(initialStatus)) {
    loadStatic();
    return () => {};
  }

  // live mode still needs to show everything written so far, not just
  // chunks appended after this connection opens -- backfill via the same
  // static read before tailing new content (mounting is re-triggered on
  // every task-level refresh, e.g. from v_task_detail's own WS feed, so
  // this also re-populates content a reconnect would otherwise have wiped)
  loadStatic();
  const socket = connectLogTailSocket(nodeExecId, {
    onChunk: (chunk) => { for (const line of chunk.split("\n")) if (line) appendLine(line); },
    onClose: () => loadStatic(), // server closes on terminal status (03-C §3.6.2) -- switch to static mode
  });
  return () => socket.close();
}

const TERMINAL_NODE_STATUSES = new Set(["done", "blocked", "failed"]);
function isTerminalNodeStatus(status) {
  return TERMINAL_NODE_STATUSES.has(status);
}

// ---- v_task_detail (02-V §2.6): task detail / process inspection ----
// Embeds a to-do tree built from graph_manifest (01-M 1.3's "补充说明")
// and the v_graph_visualizer DAG view above. The raw-log v_log_viewer is a
// separate Unit (U-027) and shows as a clearly-labeled placeholder here
// until it lands, rather than faking its content.

function renderTaskDetail(taskId) {
  if (!getCurrentProjectId()) return renderNoProjectSelected();
  return `
    <div class="page page-wide">
      <div class="breadcrumb"><a href="#/tasks">任务</a> / ${taskId}</div>
      <div id="td_content"><div class="hint">加载中…</div></div>
    </div>
  `;
}

function mountTaskDetail(taskId, initialOrgNode) {
  const projectId = getCurrentProjectId();
  if (!projectId) return;
  const content = document.getElementById("td_content");

  // Org Graph 三节点条点击可达详情 (2026-08-06 SDD, reuses v_graph_console's
  // Org meta-graph as of 2026-08-13 -- see mountOrgMetaGraph's comment):
  // which stage's panel is currently focused -- seeded from the
  // #/tasks/:task_id/org/:org_node route (deep link / dashboard click) and
  // updated in place when the meta-graph below is clicked while already on
  // this page, so a WS-triggered refresh() re-render keeps pointing at the
  // same stage instead of losing focus.
  let focusedOrgNode = initialOrgNode || null;

  // v_log_viewer instances (02-V §2.7.1) mounted lazily on first to-do
  // expand -- tracked here so a re-render (WS-triggered refresh) or leaving
  // the page closes any live c_ws_log_tail connections instead of leaking them.
  const activeLogViewers = new Map();
  function closeAllLogViewers() {
    for (const close of activeLogViewers.values()) close();
    activeLogViewers.clear();
  }

  // Wires the Org meta-graph's own work-node click-to-expand (enableNodeClick
  // opt-in below, mirrors mountGraphConsole's onWorkNodeClick) into this
  // page's own activeLogViewers/mountLogViewer machinery instead of a
  // page-local one, so a WS-triggered refresh()/route change closes these
  // sockets the same way it already does for the to-do tree's log viewers.
  //
  // ponytail: activeLogViewers is keyed by node_exec_id only, and both the
  // to-do tree (below) and the meta-graph's expanded panels can show the
  // very same node_exec_id (a Phase 2c merged run can be "the latest run"
  // for more than one org_node, and to-do-tree/meta-graph both render off
  // the same task.work_graph_runs). If a node's log is already open in one
  // location, clicking it in the other doesn't spin up a second competing
  // c_ws_log_tail connection or a duplicate `#log-viewer-<id>` DOM id (that
  // would be a real bug) -- it just scrolls to the already-open one instead
  // of also mounting a second copy there. Ceiling: the second location shows
  // an empty slot until the first is closed, rather than a live mirrored
  // view. Upgrade path if that turns out to matter in practice: a
  // location-aware key (e.g. `locationId + ":" + nodeExecId`) with each
  // entry recording which slot currently owns the DOM, so either location's
  // click can steal/re-home it instead of just deflecting.
  function onOrgMetaWorkNodeClick(nodeExecId, status, nodeEl) {
    const slot = nodeEl.querySelector(".log-viewer-slot");
    if (!slot) return;
    if (slot.querySelector(".log-viewer")) {
      // This slot owns the mounted viewer -- close it for real.
      if (activeLogViewers.has(nodeExecId)) {
        activeLogViewers.get(nodeExecId)();
        activeLogViewers.delete(nodeExecId);
      }
      slot.innerHTML = "";
      nodeEl.classList.remove("expanded");
      return;
    }
    if (activeLogViewers.has(nodeExecId)) {
      const existing = document.getElementById("log-viewer-" + nodeExecId);
      if (existing && existing.scrollIntoView) existing.scrollIntoView({ behavior: "smooth", block: "center" });
      return;
    }
    slot.innerHTML = '<div id="todo-detail-' + nodeExecId + '">' + renderLogViewerHtml(nodeExecId) + "</div>";
    activeLogViewers.set(nodeExecId, mountLogViewer(nodeExecId, status));
    nodeEl.classList.add("expanded");
  }

  function renderTodoTree(run) {
    if (!run.graph_manifest) return "";
    const nodesById = {};
    for (const n of run.nodes) nodesById[n.node_id] = n;
    const items = run.graph_manifest.nodes.map((gn) => {
      const wn = nodesById[gn.node_id];
      const status = wn ? wn.status : "pending";
      const detail = wn ? (
        '<div class="todo-detail" id="todo-detail-' + wn.node_exec_id + '" data-status="' + status + '">'
        + "retry_count: " + wn.retry_count
        + (wn.reflection_notes ? "<br>reflection_notes: " + escapeHtml(wn.reflection_notes) : "")
        + '<div class="log-viewer-slot" id="log-slot-' + wn.node_exec_id + '"></div>'
        + "</div>"
      ) : "";
      return (
        '<li class="status-' + status + '">'
        + '<div class="todo-row" data-node-exec-id="' + (wn ? wn.node_exec_id : "") + '">'
        + '<span class="dot"></span>'
        + '<span class="todo-id">to-do: ' + escapeHtml(gn.node_id) + "</span>"
        + '<span class="todo-status">' + status + (wn ? " · node_exec_id=" + wn.node_exec_id : "") + "</span>"
        + "</div>" + detail + "</li>"
      );
    }).join("");
    return (
      // id="todo-tree-<run_id>": secondary scroll/highlight target when the
      // DAG panel above didn't render (graph_manifest missing).
      '<div class="panel" id="todo-tree-' + run.run_id + '"><h2>' + orgNodesLabel(run) + " Work Graph 的 to-do 树(run_id=" + run.run_id + ")</h2>"
      + '<ul class="todo-tree">' + items + "</ul>"
      + '<div class="see-more">DAG 视图(同一份 graph_manifest 的另一种呈现)见下方 v_graph_visualizer</div>'
      + "</div>"
    );
  }

  function renderDetail(task) {
    closeAllLogViewers();

    // v_task_detail Start/Pause/Stop (2026-08-03): a task only ever has one
    // real thing "running" against it at a time -- exactly one of these
    // three blocks is shown, keyed off task.status, matching the states
    // task_execution.py itself understands (see its module docstring for
    // why Pause/Stop are a soft stop reusing blocked_pending_human rather
    // than a genuine subprocess kill / new status enum value).
    const isUserPauseStop = task.status === "blocked_pending_human"
      && (task.blocked_reason === "user_paused" || task.blocked_reason === "user_stopped");
    const execControlsHtml = task.status === "queued" ? (
      '<div class="btn-row" style="margin:0 0 16px;">'
      + '<button class="btn btn-primary" id="btn_start_task" type="button">开始(execute)</button></div>'
    ) : (task.status === "planning_brd_prd_sdd" || task.status === "coding") ? (
      '<div class="btn-row" style="margin:0 0 16px;">'
      + '<button class="btn" id="btn_pause_task" type="button">暂停(pause)</button>'
      + '<button class="btn btn-danger" id="btn_stop_task" type="button">停止(stop)</button></div>'
    ) : "";

    const alertHtml = task.status !== "blocked_pending_human" ? "" : isUserPauseStop ? (
      '<div class="alert-banner">' + (task.blocked_reason === "user_paused" ? "⏸ 已暂停" : "⏹ 已停止")
      + '<button class="btn btn-primary" id="btn_manual_resume" type="button">继续执行</button></div>'
    ) : (
      '<div class="alert-banner">⚠ 已阻塞(' + escapeHtml(task.blocked_reason || "") + '),需要人工干预'
      + '<button class="btn btn-danger" id="btn_manual_resume" type="button">人工干预(manual_resume)</button></div>'
    );

    const todoTreesHtml = task.work_graph_runs.map(renderTodoTree).join("");
    const graphVisualizerHtml = task.work_graph_runs.map(renderGraphVisualizerPanel).join("");

    const artifactsHtml = task.artifacts.length ? (
      '<ul class="simple-list">' + task.artifacts.map((a) =>
        "<li><span>" + escapeHtml(a.file_path) + "</span><span>"
        + escapeHtml(a.artifact_type) + " · " + escapeHtml(a.validation_status) + "</span></li>"
      ).join("") + "</ul>"
    ) : '<div class="hint">暂无 Artifact</div>';

    const bugsHtml = task.bug_records.length ? (
      '<ul class="simple-list">' + task.bug_records.map((b) =>
        "<li><span>" + escapeHtml(b.description) + "</span><span>"
        + escapeHtml(b.root_cause_category || "待归因") + " · " + escapeHtml(b.status) + "</span></li>"
      ).join("") + "</ul>"
    ) : '<div class="hint">暂无 Bug 记录</div>';

    // v_goal_list CRUD (2026-08-03): editing/deleting a goal is only safe
    // while it's still 'queued' -- once real work has started, artifacts/
    // bug_records/work_graph_runs all reference this task_id, and the
    // backend (task_query.TaskNotEditableError) rejects both operations
    // past that point anyway; hiding the controls here just avoids
    // presenting an action that would visibly fail.
    const goalCrudHtml = task.status !== "queued" ? "" : (
      '<div class="btn-row" style="margin:0 0 16px;">'
      + '<button class="btn" id="btn_edit_goal_text" type="button">编辑目标</button>'
      + '<button class="btn btn-danger" id="btn_delete_goal" type="button">删除任务</button>'
      + "</div>"
      + '<div class="panel" id="edit_goal_panel" style="display:none;">'
      + '<div class="field"><label>目标描述(goal_text)</label>'
      + '<textarea id="edit_goal_textarea" rows="4">' + escapeHtml(task.goal_text) + "</textarea></div>"
      + '<div id="edit_goal_error" class="error-banner" style="display:none;"></div>'
      + '<div class="btn-row">'
      + '<button class="btn" id="btn_cancel_edit_goal" type="button">取消</button>'
      + '<button class="btn btn-primary" id="btn_save_goal_text" type="button">保存</button>'
      + "</div></div>"
      + '<div class="confirm-banner" id="delete_goal_confirm" style="display:none;">'
      + "确认删除这个任务?此操作不可撤销。"
      + '<div class="btn-row" style="margin-top:10px;">'
      + '<button class="btn" id="btn_cancel_delete_goal" type="button">取消</button>'
      + '<button class="btn btn-danger" id="btn_confirm_delete_goal" type="button">确认删除</button>'
      + "</div></div>"
    );

    content.innerHTML = (
      "<h1>" + escapeHtml(task.goal_text) + "</h1>"
      + goalCrudHtml
      + execControlsHtml
      + alertHtml
      + '<div class="meta-row">'
      + "<div><b>STATUS</b>" + escapeHtml(task.status) + "</div>"
      + "<div><b>LOOP_ROUND</b>" + task.loop_round + "</div>"
      + "<div><b>ASSIGNED_ORG_NODE</b>" + task.assigned_org_node + "</div>"
      + "<div><b>CREATED_VIA</b>" + escapeHtml(task.created_via) + "</div>"
      + "</div>"
      // Org Graph panel (2026-08-13): reuses v_graph_console's 4-stage Org
      // meta-graph (renderOrgMetaGraph/mountOrgMetaGraph, planner ->
      // planner_reviewer -> coder -> validator) instead of this page's old
      // 3-node org-strip + separate "Org 节点详情" combo panel -- gains
      // planner_reviewer visibility for free. Filled in and wired up right
      // after this innerHTML assignment (needs a real container element).
      + '<div class="panel"><h2>Org Graph</h2><div id="td_org_meta_graph"></div></div>'
      + todoTreesHtml
      + graphVisualizerHtml
      + '<div class="tooltip" id="graph-tooltip"></div>'
      + '<div class="panel"><h2>关联 Artifact</h2>' + artifactsHtml + "</div>"
      + '<div class="panel"><h2>关联 Bug 记录</h2>' + bugsHtml + "</div>"
    );

    for (const row of content.querySelectorAll(".todo-row[data-node-exec-id]")) {
      row.addEventListener("click", () => {
        const nodeExecId = row.dataset.nodeExecId;
        if (!nodeExecId) return;
        const detail = document.getElementById("todo-detail-" + nodeExecId);
        if (!detail) return;
        detail.classList.toggle("open");
        if (detail.classList.contains("open") && !activeLogViewers.has(nodeExecId)) {
          const slot = document.getElementById("log-slot-" + nodeExecId);
          slot.innerHTML = renderLogViewerHtml(nodeExecId);
          activeLogViewers.set(nodeExecId, mountLogViewer(nodeExecId, detail.dataset.status));
        }
      });
    }
    mountGraphVisualizerTooltips(content);
    mountGraphVisualizerEdges(content);

    // Org Graph panel: render + wire the reused Org meta-graph.
    // enableNodeClick:true + onNodeClick opts into real per-node live
    // log-tail expansion via this page's own machinery above --
    // v_graph_console's own usage of mountOrgMetaGraph passes no options at
    // all, so it stays enableNodeClick:false/read-only, unaffected by this.
    // onStageExpand mirrors what the old org-strip's click handler used to
    // do: update focusedOrgNode + the URL (history.replaceState, no
    // hashchange -> no full route re-render) and the focused highlight, per
    // 02-V happy path 2.2 -- just without a scroll, since the panel now
    // expands in place right where the click happened instead of pointing
    // at a separate DAG section further down the page.
    const orgMetaGraphEl = content.querySelector("#td_org_meta_graph");
    orgMetaGraphEl.innerHTML = renderOrgMetaGraph(task);
    const orgMetaGraphOptions = {
      enableNodeClick: true,
      onNodeClick: onOrgMetaWorkNodeClick,
      onStageExpand: (stage) => {
        focusedOrgNode = stage;
        const newHash = "#/tasks/" + taskId + "/org/" + focusedOrgNode;
        if (window.location.hash !== newHash) history.replaceState(null, "", newHash);
        for (const el of orgMetaGraphEl.querySelectorAll(".graph-topo-node[data-meta-stage]")) {
          el.classList.toggle("org-node-focused", el.dataset.metaStage === focusedOrgNode);
        }
      },
    };
    mountOrgMetaGraph(orgMetaGraphEl, task, orgMetaGraphOptions);
    // Deep link / dashboard click landed here with an org_node already
    // known -- expand + scroll/highlight it once, right after this render
    // (equivalent to the old focusOrgNodePanel()).
    if (focusedOrgNode) focusOrgMetaStage(orgMetaGraphEl, task, focusedOrgNode, orgMetaGraphOptions);

    const resumeBtn = document.getElementById("btn_manual_resume");
    if (resumeBtn) {
      resumeBtn.addEventListener("click", async () => {
        resumeBtn.disabled = true;
        await fetch("/api/tasks/" + taskId + "/route", {
          method: "POST",
          body: JSON.stringify({ decided_route: "manual_resume" }),
        });
        refresh();
      });
    }

    const startBtn = document.getElementById("btn_start_task");
    if (startBtn) {
      startBtn.addEventListener("click", async () => {
        startBtn.disabled = true;
        await fetch("/api/tasks/" + taskId + "/execute", { method: "POST" });
        refresh();
      });
    }
    const pauseBtn = document.getElementById("btn_pause_task");
    if (pauseBtn) {
      pauseBtn.addEventListener("click", async () => {
        pauseBtn.disabled = true;
        await fetch("/api/tasks/" + taskId + "/pause", { method: "POST" });
        refresh();
      });
    }
    const stopBtn = document.getElementById("btn_stop_task");
    if (stopBtn) {
      stopBtn.addEventListener("click", async () => {
        stopBtn.disabled = true;
        await fetch("/api/tasks/" + taskId + "/stop", { method: "POST" });
        refresh();
      });
    }

    const editBtn = document.getElementById("btn_edit_goal_text");
    const deleteBtn = document.getElementById("btn_delete_goal");
    if (editBtn) {
      const editPanel = document.getElementById("edit_goal_panel");
      const deleteConfirm = document.getElementById("delete_goal_confirm");
      const textarea = document.getElementById("edit_goal_textarea");
      const errorBox = document.getElementById("edit_goal_error");

      editBtn.addEventListener("click", () => {
        deleteConfirm.style.display = "none";
        editPanel.style.display = "block";
      });
      document.getElementById("btn_cancel_edit_goal").addEventListener("click", () => {
        editPanel.style.display = "none";
      });
      document.getElementById("btn_save_goal_text").addEventListener("click", async () => {
        errorBox.style.display = "none";
        const goalText = textarea.value.trim();
        if (!goalText) {
          errorBox.textContent = "目标描述不能为空";
          errorBox.style.display = "block";
          return;
        }
        const resp = await fetch("/api/tasks/" + taskId, {
          method: "PUT",
          body: JSON.stringify({ goal_text: goalText }),
        });
        const body = await resp.json();
        if (resp.status !== 200) {
          errorBox.textContent = body.error + (body.detail ? ":" + body.detail : "");
          errorBox.style.display = "block";
          return;
        }
        editPanel.style.display = "none";
        refresh();
      });

      deleteBtn.addEventListener("click", () => {
        editPanel.style.display = "none";
        deleteConfirm.style.display = "block";
      });
      document.getElementById("btn_cancel_delete_goal").addEventListener("click", () => {
        deleteConfirm.style.display = "none";
      });
      document.getElementById("btn_confirm_delete_goal").addEventListener("click", async () => {
        await fetch("/api/tasks/" + taskId, { method: "DELETE" });
        window.location.hash = "#/tasks";
      });
    }
  }

  async function refresh() {
    const resp = await fetch("/api/tasks/" + taskId);
    if (resp.status === 404) {
      content.innerHTML = '<div class="error-banner" style="display:block;">任务不存在</div>';
      return;
    }
    renderDetail(await resp.json());
  }

  refresh();

  let wasDisconnected = false;
  const socket = connectEventSocket(projectId, taskId, {
    onEvent: () => refresh(),
    onStatusChange: (status) => {
      if (status === "disconnected") {
        wasDisconnected = true;
      } else if (status === "connected" && wasDisconnected) {
        // REQ-12 boundary: catch up via a fresh snapshot on reconnect.
        wasDisconnected = false;
        refresh();
      }
    },
  });
  registerRouteCleanup(() => {
    socket.close();
    closeAllLogViewers();
  });
}

// ---- v_run_detail (`#/runs/:run_id`, U-046 2026-08-06 SDD): single Work
// Graph Run detail -- every work_node_execution the run contains, each with
// its own log (live c_ws_log_tail while running, static c_execution_log_get
// once terminal). Reuses renderGraphVisualizerPanel/mountLogViewer
// unmodified, same as v_task_detail's todo tree above; the one DOM-id
// contract mountLogViewer relies on (`#todo-detail-<node_exec_id>
// .log-autoscroll`) is reproduced here via renderRunNodeListHtml so the
// existing auto-scroll checkbox keeps working without touching
// mountLogViewer itself.

// D (2026-08-06, time-travel debugging, FR-4): only a 'done' node is a
// valid fork point (work_graph_fork.create_fork's own FR-1 requirement --
// its output_payload has to exist to be substituted). The form itself is
// plain textarea + button, no native prompt()/confirm() (this codebase
// doesn't use those anywhere, matches the existing btn-rollback pattern's
// inline-form style instead).
function renderRunNodeListHtml(run) {
  if (!run.nodes.length) return '<div class="hint">该运行尚无节点</div>';
  const items = run.nodes.map((wn) => {
    const status = wn.status;
    const forkHtml = status === "done" ? (
      '<div class="fork-panel">'
      + '<button class="btn btn-fork" type="button">🔀 从这里分叉</button>'
      + '<div class="fork-form" style="display:none;">'
      + '<textarea class="fork-content" rows="4" placeholder="新的 content(替换这个节点的产出,下游节点会用这份新内容真正重新执行)"></textarea>'
      + '<button class="btn btn-fork-submit" type="button">提交分叉</button>'
      + '<div class="fork-error error-banner" style="display:none;"></div>'
      + "</div>"
      + "</div>"
    ) : "";
    return (
      '<li class="status-' + status + '">'
      + '<div class="todo-row" data-node-exec-id="' + wn.node_exec_id + '">'
      + '<span class="dot"></span>'
      + '<span class="todo-id">' + escapeHtml(wn.node_id) + "</span>"
      + '<span class="todo-status">' + escapeHtml(status) + " · " + escapeHtml(wn.subagent_type)
      + " · retry_count=" + wn.retry_count + " · node_exec_id=" + wn.node_exec_id + "</span>"
      + "</div>"
      + '<div class="todo-detail" id="todo-detail-' + wn.node_exec_id + '" data-status="' + status + '">'
      + (wn.reflection_notes ? "reflection_notes: " + escapeHtml(wn.reflection_notes) + "<br>" : "")
      + '<div class="log-viewer-slot" id="log-slot-' + wn.node_exec_id + '"></div>'
      + forkHtml
      + "</div>"
      + "</li>"
    );
  }).join("");
  return '<ul class="todo-tree">' + items + "</ul>";
}

// D (2026-08-06, FR-4): a forked run shows where it came from, linking
// back to the parent run -- read-only, no "set as primary" action (the
// requirements doc's own non-goal #3, see design doc §5/§7).
function renderForkBadgeHtml(run) {
  if (!run.parent_run_id) return "";
  return (
    '<div class="fork-badge">🔀 从节点 <code>' + escapeHtml(run.fork_of_node_exec_id) + '</code> 分叉自 '
    + '<a href="#/runs/' + encodeURIComponent(run.parent_run_id) + '">' + escapeHtml(run.parent_run_id) + "</a></div>"
  );
}

function mountForkPanels(container) {
  for (const panel of container.querySelectorAll(".fork-panel")) {
    const nodeExecId = panel.closest(".todo-detail").id.replace("todo-detail-", "");
    const toggleBtn = panel.querySelector(".btn-fork");
    const form = panel.querySelector(".fork-form");
    const textarea = panel.querySelector(".fork-content");
    const submitBtn = panel.querySelector(".btn-fork-submit");
    const errorEl = panel.querySelector(".fork-error");

    toggleBtn.addEventListener("click", (e) => {
      e.stopPropagation();
      form.style.display = form.style.display === "none" ? "block" : "none";
    });
    // clicking inside the form must not toggle the parent .todo-detail row
    form.addEventListener("click", (e) => e.stopPropagation());

    submitBtn.addEventListener("click", async () => {
      const content = textarea.value;
      if (!content.trim()) {
        errorEl.textContent = "请输入新的 content";
        errorEl.style.display = "block";
        return;
      }
      errorEl.style.display = "none";
      submitBtn.disabled = true;
      const resp = await fetch("/api/work-nodes/" + encodeURIComponent(nodeExecId) + "/fork", {
        method: "POST",
        body: JSON.stringify({ new_output_payload: { content: content } }),
      });
      submitBtn.disabled = false;
      const body = await resp.json();
      if (resp.status !== 200) {
        errorEl.textContent = body.error + (body.detail ? ":" + body.detail : "");
        errorEl.style.display = "block";
        return;
      }
      window.location.hash = "#/runs/" + encodeURIComponent(body.run_id);
    });
  }
}

function renderRunDetail(runId) {
  if (!getCurrentProjectId()) return renderNoProjectSelected();
  return `
    <div class="page page-wide">
      <div class="breadcrumb"><a href="#/graph">Graph 控制台</a> / run ${escapeHtml(runId)}</div>
      <div id="rd_content"><div class="hint">加载中…</div></div>
    </div>
  `;
}

function mountRunDetail(runId) {
  const projectId = getCurrentProjectId();
  if (!projectId) return;
  const content = document.getElementById("rd_content");

  // Same "track open log viewers, close them on re-render/route-leave"
  // pattern as mountTaskDetail/mountGraphConsole above.
  const activeLogViewers = new Map();
  function closeAllLogViewers() {
    for (const close of activeLogViewers.values()) close();
    activeLogViewers.clear();
  }

  // The event socket needs task_id, which we only learn from the run's own
  // response -- opened lazily on the first successful render, not before.
  let socket = null;

  function renderDetail(run) {
    closeAllLogViewers();
    content.innerHTML = (
      "<h1>" + escapeHtml(orgNodesLabel(run)) + " Work Graph Run</h1>"
      + renderForkBadgeHtml(run)
      + '<div class="meta-row">'
      + "<div><b>RUN_ID</b>" + escapeHtml(run.run_id) + "</div>"
      + "<div><b>STATUS</b>" + escapeHtml(run.status) + "</div>"
      + "<div><b>STARTED_AT</b>" + escapeHtml(run.started_at || "") + "</div>"
      + "<div><b>COMPLETED_AT</b>" + escapeHtml(run.completed_at || "") + "</div>"
      + '<div><b>TASK</b><a href="#/tasks/' + encodeURIComponent(run.task_id) + '">' + escapeHtml(run.task_id) + "</a></div>"
      + "</div>"
      + renderGraphVisualizerPanel(run)
      + '<div class="tooltip" id="graph-tooltip"></div>'
      + '<div class="panel"><h2>节点列表</h2>' + renderRunNodeListHtml(run) + "</div>"
    );

    for (const row of content.querySelectorAll(".todo-row[data-node-exec-id]")) {
      row.addEventListener("click", () => {
        const nodeExecId = row.dataset.nodeExecId;
        if (!nodeExecId) return;
        const detail = document.getElementById("todo-detail-" + nodeExecId);
        if (!detail) return;
        detail.classList.toggle("open");
        if (detail.classList.contains("open") && !activeLogViewers.has(nodeExecId)) {
          const slot = document.getElementById("log-slot-" + nodeExecId);
          slot.innerHTML = renderLogViewerHtml(nodeExecId);
          activeLogViewers.set(nodeExecId, mountLogViewer(nodeExecId, detail.dataset.status));
        }
      });
    }
    mountForkPanels(content);
    mountGraphVisualizerTooltips(content);
    mountGraphVisualizerEdges(content);

    if (!socket) {
      socket = connectEventSocket(projectId, run.task_id, {
        onEvent: () => refresh(),
        onStatusChange: () => {},
      });
    }
  }

  async function refresh() {
    const resp = await fetch("/api/work-graph-runs/" + encodeURIComponent(runId));
    if (resp.status === 404) {
      content.innerHTML = '<div class="error-banner" style="display:block;">运行不存在</div>';
      return;
    }
    renderDetail(await resp.json());
  }

  refresh();

  registerRouteCleanup(() => {
    if (socket) socket.close();
    closeAllLogViewers();
  });
}

// ---- v_graph_console (`#/graph`, 2026-08-03 SDD): Org/Work Graph
// visualization + Planner output overview. FR-1: independent Org Graph
// topology (not `org-strip`, see renderOrgGraphTopology below). FR-2/3:
// reuses computeGraphLayers/renderGraphVisualizerPanel via a task switcher.
// FR-4: click-to-expand logs, wired through the `enableNodeClick` param
// added to renderGraphVisualizerPanel above. FR-5: a read-only "most
// recent N + 查看全部" overview of documents/code/graph runs/tasks below
// the graphs -- no local filtering/pagination reimplemented here, matching
// the SDD's explicit non-goal.

function renderOrgGraphTopology(activeOrgNode, runStatusByOrgNode, route) {
  const nodesHtml = ORG_NODE_ORDER.map((node, i) => {
    const status = runStatusByOrgNode[node] || "not_started";
    const isActive = activeOrgNode === node;
    const nodeHtml = (
      '<div class="graph-topo-node status-' + status + (isActive ? " active" : "") + '">'
      + '<div class="role">' + node + "</div>"
      + '<div class="hint">' + escapeHtml(status) + "</div>"
      + "</div>"
    );
    const flowEdgeHtml = i < ORG_NODE_ORDER.length - 1 ? '<div class="graph-edge flow">→</div>' : "";
    return nodeHtml + flowEdgeHtml;
  }).join("");

  // 04-P p_org_loop_route semantics: fast_lane loops back validator->coder,
  // full_replan loops back validator->planner. task.route is null until the
  // first loop actually happens -- no retry edge drawn in that case.
  let retryEdgeHtml = "";
  if (route === "fast_lane") {
    retryEdgeHtml = '<div class="graph-edge retry-loop">↩ validator → coder(fast_lane)</div>';
  } else if (route === "full_replan") {
    retryEdgeHtml = '<div class="graph-edge retry-loop">↩ validator → planner(full_replan)</div>';
  }

  return '<div class="graph-topo-row">' + nodesHtml + "</div>" + retryEdgeHtml;
}

// ---- Org 元图 (FR-5a, Org Graph unification Phase 3, 2026-08-13): a
// standalone four-stage top-level meta-graph (Planner -> 复核 Planner
// Reviewer -> Coder -> 终审 Validator), separate from renderOrgGraphTopology
// above -- that function is still called by mountGraphConsole's own
// existing "Org Graph" panel and is pinned by test_graph_console_smoke.js's
// 3-node ORG_NODE_ORDER shape, so it's left untouched rather than stretched
// to 4 stages. Each stage expands in place into that stage's real Work
// Graph run, reusing renderGraphVisualizerPanel unmodified -- except
// planner_reviewer, which never self-plans a Work Graph
// (org_node_trigger.trigger_org_node() is one flat call, see
// e2e_pipeline.py::_record_planner_review_event) and instead shows its own
// verdict trail (task.planner_review_events, task_query.py::
// _planner_review_events_for_task).
const ORG_META_STAGE_ORDER = ["planner", "planner_reviewer", "coder", "validator"];
const ORG_META_STAGE_LABELS = {
  planner: "Planner", planner_reviewer: "复核(Planner Reviewer)",
  coder: "Coder", validator: "终审(Validator)",
};

function orgMetaStageStatus(task, stage) {
  if (stage === "planner_reviewer") {
    const events = task.planner_review_events || [];
    if (events.length === 0) return "not_started";
    return events[events.length - 1].verdict === "PASS" ? "done" : "reflecting";
  }
  const run = getLatestRunForOrgNode(task, stage);
  return run ? run.status : "not_started";
}

function renderOrgMetaGraph(task) {
  const nodesHtml = ORG_META_STAGE_ORDER.map((stage, i) => {
    const status = orgMetaStageStatus(task, stage);
    const arrow = i < ORG_META_STAGE_ORDER.length - 1 ? '<div class="graph-edge">→</div>' : "";
    return (
      '<div class="graph-topo-node status-' + status + '" data-meta-stage="' + stage + '" style="cursor:pointer;">'
      + '<div class="role">' + escapeHtml(ORG_META_STAGE_LABELS[stage]) + "</div>"
      + '<div class="hint">' + escapeHtml(status) + "</div>"
      + "</div>" + arrow
    );
  }).join("");
  const detailsHtml = ORG_META_STAGE_ORDER.map((stage) =>
    '<div class="org-meta-stage-detail" id="org-meta-detail-' + stage + '" data-meta-stage="' + stage + '" style="display:none;"></div>'
  ).join("");
  return '<div class="graph-topo-row">' + nodesHtml + "</div>" + detailsHtml;
}

function renderPlannerReviewEventsList(events) {
  if (!events || events.length === 0) return '<div class="hint">尚无复核记录</div>';
  return '<ul class="simple-list">' + events.map((e) =>
    "<li><span>attempt " + e.attempt + " · " + escapeHtml(e.verdict)
    + (e.used_existing_artifacts ? "(复用已有产出)" : "") + "</span><span>"
    + escapeHtml(e.created_at || "") + "</span></li>"
  ).join("") + "</ul>";
}

// planner/coder/validator branch renders the same empty-run/empty-DAG
// fallback text v_task_detail's old combo panel used to. `enableNodeClick`
// (2026-08-13, Org Graph unification/console reuse into v_task_detail) is
// threaded straight into renderGraphVisualizerPanel's own existing options
// param -- v_graph_console's call sites never pass it (stays `undefined` ->
// falsy -> `{ enableNodeClick: false }`, byte-for-byte what this already
// rendered), while v_task_detail's usage below opts in for real per-node
// live log-tail expansion instead of the read-only DAG snapshot.
function renderOrgMetaStageDetailHtml(task, stage, enableNodeClick) {
  if (stage === "planner_reviewer") {
    return '<div class="panel"><h2>Planner 产出复核记录</h2>' + renderPlannerReviewEventsList(task.planner_review_events) + "</div>";
  }
  const run = getLatestRunForOrgNode(task, stage);
  if (!run) return '<div class="hint">' + escapeHtml(stage) + " 尚未开始(暂无 Work Graph run)</div>";
  const panelHtml = renderGraphVisualizerPanel(run, { enableNodeClick: !!enableNodeClick });
  return panelHtml
    ? panelHtml + renderLoopBackTimelineHtml(run)
    : '<div class="hint">最新一次 run_id=' + escapeHtml(run.run_id) + "(status=" + escapeHtml(run.status) + ")· 该 run 尚未生成 Work Graph</div>";
}

// `options` (2026-08-13, v_task_detail reuse): `{ enableNodeClick, onNodeClick,
// onStageExpand }`, all optional -- v_graph_console's existing call
// (`mountOrgMetaGraph(orgMetaGraphEl, task)`, no third arg) leaves every one
// of them `undefined`, so `enableNodeClick` stays falsy (read-only DAG
// snapshot, unchanged) and `mountWorkNodeClickExpand`/`onStageExpand` are
// never invoked -- v_graph_console's behavior is untouched by this refactor.
// v_task_detail passes `enableNodeClick: true` + a real `onNodeClick` wired
// to its own `activeLogViewers` map (mountTaskDetail below) for real
// per-node live log-tail expansion, and `onStageExpand` to keep the deep-link
// URL/focus state in sync when a stage is opened by a direct click (not just
// the initial deep-link landing, which calls expandOrgMetaStage directly).
function expandOrgMetaStage(container, task, stage, options) {
  const detail = container.querySelector("#org-meta-detail-" + stage);
  if (!detail) return;
  const enableNodeClick = options && options.enableNodeClick;
  detail.innerHTML = renderOrgMetaStageDetailHtml(task, stage, enableNodeClick);
  detail.style.display = "block";
  mountGraphVisualizerTooltips(detail);
  mountGraphVisualizerEdges(detail);
  mountLoopBackTimeline(detail);
  if (enableNodeClick) mountWorkNodeClickExpand(detail, { onNodeClick: options.onNodeClick });
}

function collapseOrgMetaStage(container, stage) {
  const detail = container.querySelector("#org-meta-detail-" + stage);
  if (!detail) return;
  detail.style.display = "none";
  detail.innerHTML = "";
}

function mountOrgMetaGraph(container, task, options) {
  for (const el of container.querySelectorAll(".graph-topo-node[data-meta-stage]")) {
    el.addEventListener("click", () => {
      const stage = el.dataset.metaStage;
      const detail = container.querySelector("#org-meta-detail-" + stage);
      if (!detail) return;
      if (detail.style.display !== "none") {
        collapseOrgMetaStage(container, stage);
        return;
      }
      expandOrgMetaStage(container, task, stage, options);
      if (options && options.onStageExpand) options.onStageExpand(stage);
    });
  }
}

// Deep-link / focus entry point (2026-08-13, replaces the old
// focusOrgNodePanel): called on initial mount when the route already carries
// an org_node (#/tasks/:task_id/org/:org_node) -- expands that stage's panel
// and scrolls/highlights it into view, equivalent to what focusOrgNodePanel
// used to do for the old inline org-strip + combo panel.
function focusOrgMetaStage(container, task, stage, options) {
  for (const el of container.querySelectorAll(".graph-topo-node[data-meta-stage]")) {
    el.classList.toggle("org-node-focused", el.dataset.metaStage === stage);
  }
  expandOrgMetaStage(container, task, stage, options);
  const target = container.querySelector("#org-meta-detail-" + stage);
  if (target && target.scrollIntoView) {
    target.scrollIntoView({ behavior: "smooth", block: "start" });
    target.classList.add("org-highlight-flash");
    setTimeout(() => target.classList.remove("org-highlight-flash"), 1600);
  }
}

// ---- Loop-back 历史回放时间轴 (FR-5b, Org Graph unification Phase 3,
// 2026-08-13): task_query.py's _loop_back_events_for_run() already exposes
// run.loop_back_events (source_node_id/target_node_id/attempt_number/
// feedback[]/created_at) -- renderGraphVisualizerPanel only ever reduces
// them to a self-loop badge count / on_failure edge trigger count, never
// the feedback text itself. This is a separate, additive component (not a
// rewrite of the DAG renderer) rendered alongside it at each of its call
// sites, ordered by attempt_number, one entry per real loop_back.
function renderLoopBackTimelineHtml(run) {
  const events = run.loop_back_events || [];
  if (events.length === 0) return "";
  const itemsHtml = events.map((e, i) =>
    '<li class="timeline-item" data-attempt-index="' + i + '" style="cursor:pointer;">'
    + "<span>attempt " + e.attempt_number + " · " + escapeHtml(e.source_node_id) + " → " + escapeHtml(e.target_node_id) + "</span>"
    + "<span>" + escapeHtml(e.created_at || "") + "</span>"
    + "</li>"
  ).join("");
  const feedbackPanelsHtml = events.map((e, i) =>
    '<div class="timeline-feedback" data-attempt-index="' + i + '" style="display:none;">'
    + ((e.feedback || []).length
      ? "<ul>" + e.feedback.map((f) => "<li>" + escapeHtml(f) + "</li>").join("") + "</ul>"
      : '<div class="hint">该次 loop_back 未记录 feedback</div>')
    + "</div>"
  ).join("");
  return (
    '<div class="panel loop-back-timeline"><h2>Loop-back 历史回放(按 attempt_number)</h2>'
    + '<ul class="simple-list timeline-list">' + itemsHtml + "</ul>"
    + feedbackPanelsHtml
    + "</div>"
  );
}

function mountLoopBackTimeline(container) {
  for (const timeline of container.querySelectorAll(".loop-back-timeline")) {
    for (const item of timeline.querySelectorAll(".timeline-item[data-attempt-index]")) {
      item.addEventListener("click", () => {
        const idx = item.dataset.attemptIndex;
        for (const panel of timeline.querySelectorAll(".timeline-feedback")) {
          panel.style.display = panel.dataset.attemptIndex === idx ? "block" : "none";
        }
      });
    }
  }
}

const GC_DOC_ARTIFACT_TYPES = ["brd", "prd", "sdd", "benchmark"];
const GC_CODE_ARTIFACT_TYPES = ["code_diff", "test_report"];

function renderArtifactSummaryList(artifacts, types, emptyText) {
  const filtered = artifacts.filter((a) => types.includes(a.artifact_type)).slice(0, 5);
  if (filtered.length === 0) return '<div class="hint">' + emptyText + "</div>";
  // Each item links to v_artifact_browser (#/artifacts/:artifact_id) --
  // click handlers are wired in mountArtifactsOverviewPanel after this HTML
  // is inserted into the DOM. This deliberately reuses the existing
  // browser/preview view rather than building a second content display.
  return '<ul class="simple-list">' + filtered.map((a) =>
    '<li data-artifact-id="' + a.artifact_id + '" style="cursor:pointer;"><span>' + escapeHtml(a.artifact_type) + " · " + escapeHtml(a.file_path.split("/").pop()) + "</span><span>"
    + escapeHtml(a.validation_status) + "</span></li>"
  ).join("") + "</ul>";
}

// FR-5: "查看全部" for documents/code/tasks intentionally lands on
// #/artifacts / #/tasks with no filter pre-applied -- v_artifact_browser
// and v_task_board don't parse URL query params today, and adding that is
// out of scope for this page (SDD §2.5's explicit, recorded trade-off).
// Graph run rows: U-046 fixed the previous shortcut (switching this same
// page's own task switcher via onSwitchToTask, because there was no
// separate "run detail" route) to navigate to the real v_run_detail page
// (#/runs/:run_id) instead.
async function mountArtifactsOverviewPanel(container, projectId) {
  container.innerHTML = '<div class="panel"><h2>Planner 产出总览</h2><div class="hint">加载中…</div></div>';
  const [artifacts, runs, tasks] = await Promise.all([
    fetch("/api/artifacts?project_id=" + encodeURIComponent(projectId)).then((r) => r.json()),
    fetch("/api/work-graph-runs?project_id=" + encodeURIComponent(projectId) + "&limit=10").then((r) => (r.ok ? r.json() : [])),
    fetch("/api/tasks?project_id=" + encodeURIComponent(projectId)).then((r) => r.json()),
  ]);

  const docsHtml = renderArtifactSummaryList(artifacts, GC_DOC_ARTIFACT_TYPES, "暂无文档类 Artifact");
  const codeHtml = renderArtifactSummaryList(artifacts, GC_CODE_ARTIFACT_TYPES, "暂无代码类 Artifact");

  const runsHtml = runs.length === 0 ? '<div class="hint">暂无 Graph 运行记录</div>' : (
    '<ul class="simple-list" id="gc_runs_list">' + runs.slice(0, 10).map((r) =>
      '<li data-run-id="' + r.run_id + '" style="cursor:pointer;"><span>' + escapeHtml(orgNodesLabel(r)) + " · run "
      + r.run_id.slice(0, 8) + (r.parent_run_id ? " 🔀" : "") + "</span><span>"
      + escapeHtml(r.status) + " · " + r.node_count + " 节点</span></li>"
    ).join("") + "</ul>"
  );

  const recentTasks = tasks.slice(0, 10);
  const tasksHtml = recentTasks.length === 0 ? '<div class="hint">暂无任务</div>' : (
    '<ul class="simple-list">' + recentTasks.map((t) =>
      "<li><span>" + escapeHtml(t.goal_text.slice(0, 40)) + "</span><span>" + escapeHtml(t.status) + "</span></li>"
    ).join("") + "</ul>"
  );

  container.innerHTML = (
    '<div class="panel"><h2>Planner 产出总览</h2>'
    + '<div class="overview-grid">'
    + '<div><h3>文档列表(brd/prd/sdd/benchmark)</h3>' + docsHtml + '<div class="see-more"><a href="#/artifacts">查看全部 →</a></div></div>'
    + '<div><h3>代码列表(code_diff/test_report)</h3>' + codeHtml + '<div class="see-more"><a href="#/artifacts">查看全部 →</a></div></div>'
    + '<div><h3>Graph 运行历史</h3>' + runsHtml + "</div>"
    + '<div><h3>任务列表</h3>' + tasksHtml + '<div class="see-more"><a href="#/tasks">查看全部 →</a></div></div>'
    + "</div></div>"
  );

  const runsListEl = document.getElementById("gc_runs_list");
  if (runsListEl) {
    for (const li of runsListEl.querySelectorAll("li[data-run-id]")) {
      li.addEventListener("click", () => {
        window.location.hash = "#/runs/" + encodeURIComponent(li.dataset.runId);
      });
    }
  }

  // Doc/code list items: jump to the existing v_artifact_browser detail
  // view (#/artifacts/:artifact_id) pre-selecting this artifact. "查看全部"
  // links above stay pointed at unfiltered #/artifacts per the FR-5 note.
  for (const li of container.querySelectorAll("li[data-artifact-id]")) {
    li.addEventListener("click", () => {
      window.location.hash = "#/artifacts/" + encodeURIComponent(li.dataset.artifactId);
    });
  }
}

function renderGraphConsole() {
  if (!getCurrentProjectId()) return renderNoProjectSelected();
  return `
    <div class="page page-wide">
      <h1>Graph 控制台</h1>
      <div class="page-sub">Org Graph / Work Graph 拓扑与执行状态 · 点击 Work Graph 节点查看 Agent 日志</div>
      <div class="filters">
        <select id="gc_task_select"></select>
      </div>
      <div class="panel">
        <h2>Org Graph</h2>
        <div id="gc_org_topology"><div class="hint">加载中…</div></div>
      </div>
      <div class="panel">
        <h2>Org 元图(点击每段展开真实 Work Graph 详情)</h2>
        <div id="gc_org_meta_graph"><div class="hint">加载中…</div></div>
      </div>
      <div id="gc_work_graph_panels"><div class="hint">加载中…</div></div>
      <div class="tooltip" id="graph-tooltip"></div>
      <div id="gc_artifacts_overview"><div class="hint">加载中…</div></div>
    </div>
  `;
}

function mountGraphConsole(queryParams) {
  const projectId = getCurrentProjectId();
  if (!projectId) return;

  const taskSelect = document.getElementById("gc_task_select");
  const orgTopologyEl = document.getElementById("gc_org_topology");
  const orgMetaGraphEl = document.getElementById("gc_org_meta_graph");
  const workGraphPanelsEl = document.getElementById("gc_work_graph_panels");
  const artifactsOverviewEl = document.getElementById("gc_artifacts_overview");

  // "#/graph?task_id=<id>"-style deep link (e.g. from v_task_board's task_id
  // column) preselects this task on first load, same pattern as
  // pickInitialTaskBoardStatus. populateTaskSelect below already falls back
  // to the default "first non-done" task if this id doesn't match any task
  // in the project, so an unknown/stale id is silently ignored.
  let currentTaskId = (queryParams && queryParams.task_id) || null;

  // Same "track open log viewers, close them all on re-render/route-leave"
  // pattern as mountTaskDetail's activeLogViewers/closeAllLogViewers, so a
  // task switch or WS-triggered refresh doesn't leak c_ws_log_tail sockets.
  const activeLogViewers = new Map();
  function closeAllLogViewers() {
    for (const close of activeLogViewers.values()) close();
    activeLogViewers.clear();
  }

  function onWorkNodeClick(nodeExecId, status, nodeEl) {
    const slot = nodeEl.querySelector(".log-viewer-slot");
    if (!slot) return;
    if (activeLogViewers.has(nodeExecId)) {
      activeLogViewers.get(nodeExecId)();
      activeLogViewers.delete(nodeExecId);
      slot.innerHTML = "";
      nodeEl.classList.remove("expanded");
      return;
    }
    // Wrapping element id `todo-detail-<nodeExecId>` reuses the same
    // selector mountLogViewer already looks for (`#todo-detail-<id>
    // .log-autoscroll`) -- lets the existing auto-scroll checkbox work here
    // too without touching mountLogViewer's own implementation at all.
    slot.innerHTML = '<div id="todo-detail-' + nodeExecId + '">' + renderLogViewerHtml(nodeExecId) + "</div>";
    activeLogViewers.set(nodeExecId, mountLogViewer(nodeExecId, status));
    nodeEl.classList.add("expanded");
  }

  function refreshArtifactsOverview() {
    mountArtifactsOverviewPanel(artifactsOverviewEl, projectId);
  }

  async function loadTaskAndRender(taskId) {
    closeAllLogViewers();
    currentTaskId = taskId;
    // Keep the URL in sync with whichever task is actually showing --
    // including the initial auto-preselect, not just explicit dropdown
    // switches -- so the address bar is always a valid deep link back to
    // this exact task (same history.replaceState/no-hashchange pattern
    // v_task_detail's org-strip click-through already uses above).
    const newHash = "#/graph?task_id=" + encodeURIComponent(taskId);
    if (window.location.hash !== newHash) history.replaceState(null, "", newHash);
    workGraphPanelsEl.innerHTML = '<div class="hint">加载中…</div>';
    const resp = await fetch("/api/tasks/" + encodeURIComponent(taskId));
    if (resp.status !== 200) {
      workGraphPanelsEl.innerHTML = '<div class="hint">任务不存在</div>';
      return;
    }
    const task = await resp.json();

    const runStatusByOrgNode = {};
    for (const run of task.work_graph_runs) {
      for (const orgNode of run.org_nodes_involved || []) runStatusByOrgNode[orgNode] = run.status;
    }
    orgTopologyEl.innerHTML = renderOrgGraphTopology(task.assigned_org_node, runStatusByOrgNode, task.route);
    orgMetaGraphEl.innerHTML = renderOrgMetaGraph(task);
    mountOrgMetaGraph(orgMetaGraphEl, task);

    const panelsHtml = task.work_graph_runs
      .map((run) => renderGraphVisualizerPanel(run, { enableNodeClick: true }) + renderLoopBackTimelineHtml(run))
      .join("");
    if (!panelsHtml) {
      workGraphPanelsEl.innerHTML = '<div class="panel"><div class="hint">尚未开始规划</div></div>';
      return;
    }
    workGraphPanelsEl.innerHTML = panelsHtml;
    mountGraphVisualizerTooltips(workGraphPanelsEl);
    mountGraphVisualizerEdges(workGraphPanelsEl);
    mountWorkNodeClickExpand(workGraphPanelsEl, { onNodeClick: onWorkNodeClick });
    mountLoopBackTimeline(workGraphPanelsEl);
  }

  async function populateTaskSelect() {
    const tasks = await fetch("/api/tasks?project_id=" + encodeURIComponent(projectId)).then((r) => r.json());
    if (tasks.length === 0) {
      taskSelect.innerHTML = '<option value="">暂无任务</option>';
      orgTopologyEl.innerHTML = '<div class="hint">暂无任务 · <a href="#/goals/new">提出第一个目标 →</a></div>';
      orgMetaGraphEl.innerHTML = "";
      workGraphPanelsEl.innerHTML = "";
      return;
    }
    taskSelect.innerHTML = tasks.map((t) =>
      '<option value="' + t.task_id + '">' + escapeHtml(t.goal_text.slice(0, 50)) + " (" + t.task_id.slice(0, 8) + ")</option>"
    ).join("");
    // 默认选中当前项目下第一个非 done 的任务,与 v_dashboard.
    // refreshTasksAndOrgGraph 的既有约定一致(app.js: `tasks.find((t) =>
    // t.status !== "done") || tasks[0]`)。
    const active = tasks.find((t) => t.status !== "done") || tasks[0];
    const preselect = (currentTaskId && tasks.some((t) => t.task_id === currentTaskId)) ? currentTaskId : active.task_id;
    taskSelect.value = preselect;
    await loadTaskAndRender(preselect);
  }

  taskSelect.addEventListener("change", () => loadTaskAndRender(taskSelect.value));

  populateTaskSelect();
  refreshArtifactsOverview();

  let wasDisconnected = false;
  const socket = connectEventSocket(projectId, null, {
    onEvent: (event) => {
      if (
        (event.event_type === "task_status_changed" || event.event_type === "node_status_changed")
        && currentTaskId && event.task_id === currentTaskId
      ) {
        loadTaskAndRender(currentTaskId);
      }
      if (event.event_type === "artifact_created") refreshArtifactsOverview();
    },
    onStatusChange: (status) => {
      if (status === "disconnected") {
        wasDisconnected = true;
      } else if (status === "connected" && wasDisconnected) {
        // REQ-12 boundary: catch up via a fresh snapshot on reconnect.
        wasDisconnected = false;
        if (currentTaskId) loadTaskAndRender(currentTaskId);
        refreshArtifactsOverview();
      }
    },
  });
  registerRouteCleanup(() => {
    socket.close();
    closeAllLogViewers();
  });
}

// ---- v_artifact_browser (02-V §2.8): artifact list + read-only preview ----
// Preview renders content in a plain <pre> block for every artifact_type --
// 02-V asks for Markdown rendering / syntax highlighting, but pulling in a
// markdown/highlighting library would be this frontend's first external
// dependency (05 §5.7's "no build step" ethos extends to keeping the
// console vanilla-JS-only); a monospace raw-text preview is a deliberate,
// documented simplification, not a missed requirement.

const ARTIFACT_TYPES = ["brd", "prd", "sdd", "benchmark", "bug_record", "code_diff", "test_report"];

function renderArtifactBrowser() {
  if (!getCurrentProjectId()) return renderNoProjectSelected();
  return `
    <div class="page page-wide">
      <h1>Artifact 浏览器</h1>
      <div class="filters">
        <select id="ab_type_filter">
          <option value="">全部类型(artifact_type_filter)</option>
          ${ARTIFACT_TYPES.map((t) => '<option value="' + t + '">' + t + "</option>").join("")}
        </select>
        <select id="ab_task_filter">
          <option value="">全部任务(task_id_filter)</option>
        </select>
      </div>
      <div class="artifact-browser-grid">
        <ul class="artifact-list" id="ab_list"></ul>
        <div class="preview" id="ab_preview"><div class="hint">选择左侧一个 Artifact 查看预览</div></div>
      </div>
    </div>
  `;
}

function mountArtifactBrowser(initialArtifactId) {
  const projectId = getCurrentProjectId();
  if (!projectId) return;
  const listEl = document.getElementById("ab_list");
  const previewEl = document.getElementById("ab_preview");
  const typeFilterEl = document.getElementById("ab_type_filter");
  const taskFilterEl = document.getElementById("ab_task_filter");
  // Seeded from the #/artifacts/:artifact_id route (v_graph_console's
  // Planner 产出总览 list links here). refreshList()'s existing fallback
  // below already handles an id that turns out invalid/filtered-out --
  // falls back to the first artifact in the (possibly filtered) list.
  let selectedArtifactId = initialArtifactId || null;

  fetch("/api/tasks?project_id=" + encodeURIComponent(projectId))
    .then((resp) => resp.json())
    .then((tasks) => {
      for (const task of tasks) {
        const option = document.createElement("option");
        option.value = task.task_id;
        option.textContent = task.goal_text.slice(0, 40) + " (" + task.task_id.slice(0, 8) + ")";
        taskFilterEl.appendChild(option);
      }
    });

  async function showPreview(artifactId) {
    selectedArtifactId = artifactId;
    for (const li of listEl.querySelectorAll("li")) {
      li.classList.toggle("active", li.dataset.artifactId === artifactId);
    }
    previewEl.innerHTML = '<div class="hint">加载中…</div>';
    const artifact = await fetch("/api/artifacts/" + encodeURIComponent(artifactId)).then((r) => r.json());
    const lineageHtml = artifact.lineage.map((a, i) => {
      const isCurrent = a.artifact_id === artifactId;
      const label = escapeHtml(a.artifact_type) + (isCurrent ? "(当前)" : "");
      const arrow = i < artifact.lineage.length - 1 ? " → " : "";
      return '<span class="node">' + label + "</span>" + arrow;
    }).join("");
    previewEl.innerHTML = (
      '<div class="lineage">血缘链:' + lineageHtml + "</div>"
      + '<pre class="code">' + (artifact.content == null ? "(文件不可用)" : escapeHtml(artifact.content)) + "</pre>"
    );
  }

  async function refreshList() {
    const params = new URLSearchParams({ project_id: projectId });
    if (typeFilterEl.value) params.set("artifact_type", typeFilterEl.value);
    if (taskFilterEl.value) params.set("task_id", taskFilterEl.value);
    const artifacts = await fetch("/api/artifacts?" + params.toString()).then((r) => r.json());
    if (artifacts.length === 0) {
      listEl.innerHTML = '<li class="hint" style="cursor:default;">暂无产物</li>';
      previewEl.innerHTML = '<div class="hint">暂无产物</div>';
      return;
    }
    listEl.innerHTML = artifacts.map((a) =>
      '<li data-artifact-id="' + a.artifact_id + '"><div class="type">' + escapeHtml(a.artifact_type) + "</div>"
      + escapeHtml(a.file_path.split("/").pop()) + "</li>"
    ).join("");
    for (const li of listEl.querySelectorAll("li[data-artifact-id]")) {
      li.addEventListener("click", () => showPreview(li.dataset.artifactId));
    }
    if (selectedArtifactId && artifacts.some((a) => a.artifact_id === selectedArtifactId)) {
      showPreview(selectedArtifactId);
    } else {
      showPreview(artifacts[0].artifact_id);
    }
  }

  typeFilterEl.addEventListener("change", refreshList);
  taskFilterEl.addEventListener("change", refreshList);
  refreshList();

  const socket = connectEventSocket(projectId, null, {
    onEvent: (event) => { if (event.event_type === "artifact_created") refreshList(); },
    onStatusChange: () => {},
  });
  registerRouteCleanup(() => socket.close());
}

// ---- v_skill_library (02-V §2.9) + v_skill_audit_log (02-V §2.10) ----
// Skills are a platform-wide asset living in graphlemon's own repo (see
// skill_query.py), not scoped to any target project -- these two pages
// deliberately don't check getCurrentProjectId(), unlike every other real
// page in this console.

const SOURCE_TAG_LABELS = {
  migrated_from_hermes: "migrated_from_hermes", new: "new", auto_iterated: "auto_iterated",
};

function renderSkillLibrary() {
  return `
    <div class="page page-wide">
      <h1>技能库</h1>
      <div id="skill_groups"><div class="hint">加载中…</div></div>
    </div>
  `;
}

function mountSkillLibrary() {
  const groupsEl = document.getElementById("skill_groups");

  fetch("/api/skills").then((r) => r.json()).then((skills) => {
    if (skills.length === 0) {
      groupsEl.innerHTML = '<div class="hint">暂无 Skill</div>';
      return;
    }
    const byOrgNode = { planner: [], coder: [], validator: [] };
    for (const s of skills) (byOrgNode[s.owner_org_node] || []).push(s);

    groupsEl.innerHTML = ORG_NODE_ORDER.map((node) => {
      const rows = byOrgNode[node];
      if (!rows || rows.length === 0) return "";
      const rowsHtml = rows.map((s) =>
        '<div class="skill-row" data-skill-id="' + s.skill_id + '">'
        + '<span class="name">' + escapeHtml(s.skill_id) + "</span>"
        + '<span class="tag' + (s.source === "auto_iterated" ? " auto" : "") + '">'
        + escapeHtml(SOURCE_TAG_LABELS[s.source] || s.source) + "</span>"
        + "</div>"
      ).join("");
      return (
        '<div class="group"><h2>' + node.charAt(0).toUpperCase() + node.slice(1) + "</h2>"
        + '<div class="skill-list">' + rowsHtml + "</div></div>"
      );
    }).join("");

    for (const row of groupsEl.querySelectorAll(".skill-row")) {
      row.addEventListener("click", () => {
        window.location.hash = "#/skills/" + row.dataset.skillId + "/audit";
      });
    }
  });
}

function renderSkillAuditLog(skillId) {
  return `
    <div class="page page-wide">
      <div class="breadcrumb"><a href="#/skills">技能库</a> / ${escapeHtml(skillId)}</div>
      <h1>${escapeHtml(skillId)} 变更审计</h1>
      <div id="skill_audit_error" class="error-banner" style="display:none;"></div>
      <h2>Skill 内容</h2>
      <div id="skill_content"><div class="hint">加载中…</div></div>
      <h2>迭代记录</h2>
      <div id="skill_audit_list"><div class="hint">加载中…</div></div>
    </div>
  `;
}

function mountSkillAuditLog(skillId) {
  const listEl = document.getElementById("skill_audit_list");
  const errorEl = document.getElementById("skill_audit_error");
  const contentEl = document.getElementById("skill_content");

  // Independent of the iteration-history panel below (a skill can have real
  // content with zero skill_iteration rows -- that's the normal post-
  // migration state) -- fetched and rendered separately, side by side, not
  // as an either/or with refresh()'s own list.
  fetch("/api/skills/" + encodeURIComponent(skillId) + "/content").then(async (resp) => {
    if (resp.status !== 200) {
      const body = await resp.json();
      contentEl.innerHTML = '<div class="hint">' + (body.error === "CONTENT_MISSING" ? "该 Skill 的真实文件尚未迁移" : "该 Skill 不存在") + "</div>";
      return;
    }
    const skill = await resp.json();
    const supportHtml = skill.support_files.length
      ? '<div class="hint">支持文件:' + skill.support_files.map(escapeHtml).join("、") + "</div>"
      : "";
    contentEl.innerHTML = supportHtml + '<pre class="code">' + escapeHtml(skill.content) + "</pre>";
  });

  async function refresh() {
    const resp = await fetch("/api/skills/" + encodeURIComponent(skillId) + "/audit");
    if (resp.status === 404) {
      listEl.innerHTML = "";
      errorEl.textContent = "该 Skill 不存在";
      errorEl.style.display = "block";
      return;
    }
    const iterations = await resp.json();
    if (iterations.length === 0) {
      listEl.innerHTML = '<div class="hint">该 Skill 尚无自主迭代记录</div>';
      return;
    }
    // newest first for display, oldest-first order from the API gives each its #N
    listEl.innerHTML = iterations.slice().reverse().map((it, i) => {
      const number = iterations.length - i;
      return (
        '<div class="iteration" data-iteration-id="' + it.iteration_id + '" '
        + 'data-before="' + it.before_git_commit_sha + '" data-after="' + it.after_git_commit_sha + '">'
        + '<div class="top"><b>迭代 #' + number + "</b><span class=\"t\">applied_at: " + escapeHtml(it.applied_at) + "</span></div>"
        + '<div class="summary">triggered_by_bug_id: ' + escapeHtml(it.triggered_by_bug_id) + " · " + escapeHtml(it.change_summary) + "</div>"
        + '<div class="actions">'
        + '<button class="btn btn-diff" type="button">查看 diff</button>'
        + '<button class="btn btn-rollback" type="button">回滚到此版本前</button>'
        + "</div>"
        + '<pre class="code diff-output" style="display:none;"></pre>'
        + "</div>"
      );
    }).join("");

    for (const el of listEl.querySelectorAll(".iteration")) {
      const diffOutput = el.querySelector(".diff-output");
      el.querySelector(".btn-diff").addEventListener("click", async () => {
        if (diffOutput.style.display === "block") {
          diffOutput.style.display = "none";
          return;
        }
        diffOutput.textContent = "加载中…";
        diffOutput.style.display = "block";
        const resp = await fetch(
          "/api/skills/diff?before=" + encodeURIComponent(el.dataset.before) + "&after=" + encodeURIComponent(el.dataset.after)
        );
        const body = await resp.json();
        diffOutput.textContent = body.diff_text || "(无差异)";
      });
      el.querySelector(".btn-rollback").addEventListener("click", async () => {
        const resp = await fetch("/api/skills/" + encodeURIComponent(skillId) + "/rollback", {
          method: "POST",
          body: JSON.stringify({ iteration_id: el.dataset.iterationId }),
        });
        if (resp.status !== 200) {
          const body = await resp.json();
          errorEl.textContent = body.error + (body.detail ? ":" + body.detail : "");
          errorEl.style.display = "block";
          return;
        }
        errorEl.style.display = "none";
        refresh();
      });
    }
  }

  refresh();
}

// ---- v_deployment_status (U-043, PH5 -- no 02-V spec exists for this view,
// it's a PH5-only addition; DOM/class conventions below follow the existing
// pages' own patterns rather than a wireframe that was never written) ----
// Not project-scoped (there's exactly one graphlemon self-target, not one
// per project, same reasoning v_skill_library's pages already apply).
// deployment.status changes aren't pushed over c_ws_subscribe (Deploy
// Supervisor writes deployment/deploy_health_signal rows directly, no
// execution_event of its own) -- this page polls on an interval instead of
// reusing connectEventSocket, and cleans the interval up via
// registerRouteCleanup like every other page cleans up its own sockets.

const DEPLOYMENT_POLL_INTERVAL_MS = 5000;

const DEPLOYMENT_STATUS_LABELS = {
  staged: "已暂存", candidate_starting: "候选启动中", health_check_running: "健康检查中",
  health_check_passed: "健康检查通过", health_check_failed: "健康检查失败",
  cutover_in_progress: "切换中", live: "已上线", monitoring: "监控中",
  anomaly_detected: "检测到异常", rollback_in_progress: "回滚中", rolled_back: "已回滚",
  rollback_failed: "回滚失败", blocked_pending_human: "需要人工介入",
  monitoring_window_clean: "监控窗口正常", finalized: "已完成",
};

function renderDeploymentStatus() {
  return `
    <div class="page page-wide">
      <h1>部署状态</h1>
      <div id="deployment_current"><div class="hint">加载中…</div></div>
      <h2 style="margin-top:24px;">历史部署</h2>
      <div id="deployment_history"><div class="hint">加载中…</div></div>
    </div>
  `;
}

function mountDeploymentStatus() {
  const currentEl = document.getElementById("deployment_current");
  const historyEl = document.getElementById("deployment_history");

  function renderSignals(signals) {
    if (!signals || signals.length === 0) return '<div class="hint">尚无健康信号采样</div>';
    return '<div class="signal-list">' + signals.map((s) =>
      '<div class="signal-row status-' + escapeHtml(s.status) + '">'
      + '<span class="type">' + escapeHtml(s.signal_type) + '</span>'
      + '<span class="tag">' + escapeHtml(s.status) + '</span>'
      + '<span class="t">' + escapeHtml(s.sampled_at) + '</span>'
      + (s.detail ? '<span class="detail">' + escapeHtml(s.detail) + '</span>' : '')
      + '</div>'
    ).join('') + '</div>';
  }

  function renderCurrent(current) {
    if (!current) {
      currentEl.innerHTML = '<div class="panel"><div class="hint">当前没有进行中的 deployment</div></div>';
      return;
    }
    const label = DEPLOYMENT_STATUS_LABELS[current.status] || current.status;
    currentEl.innerHTML = (
      '<div class="panel">'
      + '<div class="top"><b>deployment_id: ' + escapeHtml(current.deployment_id) + '</b>'
      + '<span class="tag status-' + escapeHtml(current.status) + '">' + escapeHtml(label) + '</span></div>'
      + '<div class="summary">commit ' + escapeHtml((current.git_commit_hash || '').slice(0, 12))
      + ' · started_at ' + escapeHtml(current.started_at || '-') + '</div>'
      + '</div>'
    );
  }

  function renderHistory(deployments) {
    if (deployments.length === 0) {
      historyEl.innerHTML = '<div class="hint">暂无历史部署记录</div>';
      return;
    }
    historyEl.innerHTML = deployments.map((d) => {
      const label = DEPLOYMENT_STATUS_LABELS[d.status] || d.status;
      return (
        '<div class="deployment-row" data-deployment-id="' + d.deployment_id + '">'
        + '<span class="name">' + escapeHtml(d.deployment_id.slice(0, 8)) + '</span>'
        + '<span class="tag status-' + escapeHtml(d.status) + '">' + escapeHtml(label) + '</span>'
        + '<span class="t">' + escapeHtml(d.cutover_at || d.started_at || '-') + '</span>'
        + '</div>'
      );
    }).join('');

    for (const row of historyEl.querySelectorAll('.deployment-row')) {
      row.addEventListener('click', async () => {
        const detail = await fetch('/api/deployments/' + encodeURIComponent(row.dataset.deploymentId)).then((r) => r.json());
        currentEl.innerHTML = (
          '<div class="panel">'
          + '<div class="top"><b>deployment_id: ' + escapeHtml(detail.deployment_id) + '</b>'
          + '<span class="tag status-' + escapeHtml(detail.status) + '">'
          + escapeHtml(DEPLOYMENT_STATUS_LABELS[detail.status] || detail.status) + '</span></div>'
          + '<div class="summary">commit ' + escapeHtml((detail.git_commit_hash || '').slice(0, 12)) + '</div>'
          + '<h3>最近健康信号</h3>' + renderSignals(detail.health_signals)
          + '</div>'
        );
      });
    }
  }

  async function refresh() {
    const [current, history] = await Promise.all([
      fetch('/api/deployments/current').then((r) => r.json()),
      fetch('/api/deployments').then((r) => r.json()),
    ]);
    renderCurrent(current);
    renderHistory(history);
  }

  refresh();
  const intervalId = setInterval(refresh, DEPLOYMENT_POLL_INTERVAL_MS);
  registerRouteCleanup(() => clearInterval(intervalId));
}

// ---- v_concurrency_settings / v_budget_settings / v_log_retention_settings
// (02-V §2.11/§2.12/§2.13) -- three small config pages, none of them
// project-scoped (all three tables are platform-wide singletons, config_id
// ='default'), so like the Skill pages they skip the getCurrentProjectId()
// guard. renderSettingsSubnav() stands in for 02-V's nav-dropdown, which
// this shell's single-level #nav bar doesn't have room for.

function renderSettingsSubnav(active) {
  const items = [["concurrency", "并发数"], ["budget", "预算护栏"], ["log-retention", "日志保留"]];
  return '<div class="filters">' + items.map(([key, label]) =>
    '<a class="btn' + (key === active ? " btn-primary" : "") + '" href="#/settings/' + key + '">' + label + "</a>"
  ).join("") + "</div>";
}

function renderConcurrencySettings() {
  return `
    <div class="page">
      <h1>并发数配置</h1>
      ${renderSettingsSubnav("concurrency")}
      <div id="cs_error" class="error-banner" style="display:none;"></div>
      <div id="cs_success" class="success-banner" style="display:none;"></div>
      <div class="panel">
        <div class="field">
          <label>最大并发 Goal 数(max_concurrent_goals,1-50)</label>
          <input type="number" id="cs_max_concurrent_goals" min="1" max="50" value="1">
          <div class="hint">调大后下一个新 Goal 起生效</div>
        </div>
        <button class="btn btn-primary" id="btn_save_concurrency" type="button">保存</button>
      </div>
    </div>
  `;
}

function mountConcurrencySettings() {
  const input = document.getElementById("cs_max_concurrent_goals");
  const errorEl = document.getElementById("cs_error");
  const successEl = document.getElementById("cs_success");

  fetch("/api/settings/concurrency").then((r) => r.json()).then((config) => {
    if (config) input.value = config.max_concurrent_goals;
  });

  document.getElementById("btn_save_concurrency").addEventListener("click", async () => {
    errorEl.style.display = "none";
    successEl.style.display = "none";
    const resp = await fetch("/api/settings/concurrency", {
      method: "PUT",
      body: JSON.stringify({ max_concurrent_goals: Number(input.value) }),
    });
    const body = await resp.json();
    if (resp.status !== 200) {
      errorEl.textContent = body.error + (body.detail ? ":" + body.detail : "");
      errorEl.style.display = "block";
      return;
    }
    successEl.textContent = "已更新,下一个新 Goal 起生效";
    successEl.style.display = "block";
  });
}

function renderBudgetSettings() {
  return `
    <div class="page">
      <h1>预算护栏配置</h1>
      ${renderSettingsSubnav("budget")}
      <div class="page-sub">人工配置层,与 Claude Code plan 额度耗尽是两套独立机制</div>
      <div id="bs_error" class="error-banner" style="display:none;"></div>
      <div id="bs_success" class="success-banner" style="display:none;"></div>
      <div class="panel">
        <div class="field">
          <label>作用范围(scope)</label>
          <select id="bs_scope">
            <option value="global">global</option>
            <option value="per_task">per_task</option>
            <option value="per_day">per_day</option>
          </select>
        </div>
        <div class="field">
          <label>限额类型(limit_type)</label>
          <select id="bs_limit_type">
            <option value="token_count">token_count</option>
            <option value="call_count">call_count</option>
          </select>
        </div>
        <div class="field">
          <label>限额值(limit_value)</label>
          <input type="number" id="bs_limit_value" value="100000">
        </div>
        <div id="bs_usage" class="hint"></div>
        <div class="progress"><div class="fill" id="bs_usage_fill" style="width:0%"></div></div>
        <div id="bs_alert" class="alert-banner" style="display:none; margin-top:14px;"></div>
        <button class="btn btn-primary" id="btn_save_budget" type="button" style="margin-top:16px;">保存</button>
      </div>
    </div>
  `;
}

function mountBudgetSettings() {
  const scopeEl = document.getElementById("bs_scope");
  const limitTypeEl = document.getElementById("bs_limit_type");
  const limitValueEl = document.getElementById("bs_limit_value");
  const usageEl = document.getElementById("bs_usage");
  const usageFillEl = document.getElementById("bs_usage_fill");
  const alertEl = document.getElementById("bs_alert");
  const errorEl = document.getElementById("bs_error");
  const successEl = document.getElementById("bs_success");

  async function refresh() {
    const configs = await fetch("/api/settings/budget").then((r) => r.json());
    const config = configs[0];
    if (config) {
      scopeEl.value = config.scope;
      limitTypeEl.value = config.limit_type;
      limitValueEl.value = config.limit_value;
      usageEl.textContent = "当前用量:" + config.current_usage.toLocaleString() + " / " + config.limit_value.toLocaleString();
      const pct = config.limit_value > 0 ? Math.min(100, Math.round((config.current_usage / config.limit_value) * 100)) : 0;
      usageFillEl.style.width = pct + "%";
    } else {
      usageEl.textContent = "尚未配置";
    }

    const projectId = getCurrentProjectId();
    const blocked = projectId
      ? await fetch("/api/tasks?project_id=" + encodeURIComponent(projectId) + "&status=blocked_pending_human")
          .then((r) => (r.ok ? r.json() : []))
      : [];
    if (blocked.length > 0) {
      alertEl.innerHTML = "已有 " + blocked.length + " 个任务处于 blocked_pending_human · " + '<a href="#/tasks">查看已暂停任务</a>';
      alertEl.style.display = "flex";
    } else {
      alertEl.style.display = "none";
    }
  }

  document.getElementById("btn_save_budget").addEventListener("click", async () => {
    errorEl.style.display = "none";
    successEl.style.display = "none";
    const resp = await fetch("/api/settings/budget", {
      method: "PUT",
      body: JSON.stringify({ scope: scopeEl.value, limit_type: limitTypeEl.value, limit_value: Number(limitValueEl.value) }),
    });
    const body = await resp.json();
    if (resp.status !== 200) {
      errorEl.textContent = body.error + (body.detail ? ":" + body.detail : "");
      errorEl.style.display = "block";
      return;
    }
    successEl.textContent = "已更新" + (body.resumed_task_ids.length ? ",已恢复 " + body.resumed_task_ids.length + " 个因超限阻塞的任务" : "");
    successEl.style.display = "block";
    refresh();
  });

  refresh();
}

function renderLogRetentionSettings() {
  return `
    <div class="page">
      <h1>日志保留策略配置</h1>
      ${renderSettingsSubnav("log-retention")}
      <div id="lrs_error" class="error-banner" style="display:none;"></div>
      <div id="lrs_success" class="success-banner" style="display:none;"></div>
      <div class="panel">
        <div class="field">
          <label>保留天数(retention_days,&gt;0)</label>
          <input type="number" id="lrs_retention_days" value="14">
        </div>
        <div class="field">
          <label>总大小上限(max_total_size_mb,非必填)</label>
          <input type="number" id="lrs_max_total_size_mb" placeholder="不限制">
          <div class="hint">超过该天数的 closed 状态日志会被清理任务标记 purged 并删除物理文件;清理任务触发频率本身不可配</div>
        </div>
        <button class="btn btn-primary" id="btn_save_log_retention" type="button">保存</button>
      </div>
    </div>
  `;
}

function mountLogRetentionSettings() {
  const daysEl = document.getElementById("lrs_retention_days");
  const sizeEl = document.getElementById("lrs_max_total_size_mb");
  const errorEl = document.getElementById("lrs_error");
  const successEl = document.getElementById("lrs_success");

  fetch("/api/settings/log-retention").then((r) => r.json()).then((config) => {
    if (config) {
      daysEl.value = config.retention_days;
      if (config.max_total_size_mb != null) sizeEl.value = config.max_total_size_mb;
    }
  });

  document.getElementById("btn_save_log_retention").addEventListener("click", async () => {
    errorEl.style.display = "none";
    successEl.style.display = "none";
    const resp = await fetch("/api/settings/log-retention", {
      method: "PUT",
      body: JSON.stringify({
        retention_days: Number(daysEl.value),
        max_total_size_mb: sizeEl.value ? Number(sizeEl.value) : undefined,
      }),
    });
    const body = await resp.json();
    if (resp.status !== 200) {
      errorEl.textContent = body.error + (body.detail ? ":" + body.detail : "");
      errorEl.style.display = "block";
      return;
    }
    successEl.textContent = "已更新";
    successEl.style.display = "block";
  });
}