All files / src/apps/user/pages Activity.tsx

77.03% Statements 550/714
55.19% Branches 664/1203
83.16% Functions 168/202
78.06% Lines 509/652

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994                                                                                                                                                                                                                                                                                                                    2x     2x                                                                                                                                                         2x                                       2x     11x 11x 3x 3x                       30x 30x   3x                                             755x 755x 755x 755x 206x 206x                     46x                   526x 415x         105x 105x       165x       59x 59x       24x           24x 24x       1004x 3x 3x 3x 3x 3x             2x 39x 39x               2x 45x 45x                                         2x 19x   2x                                         2x         3x           3x       3x 1x             2x                           2x           13x   13x         13x                                                                       2x       17x 17x 17x 17x                                             2x                                                                                                                                                                                                     2x     2x                     2x                                                                                                                 2x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 2x         3x 3x 3x 9x 3x   3x     3x     3x     3x     3x     3x       3x                                                                                                                                                                                                                                                                                                                                                   2x                             2x 2x       2x 2x           2x 2x 2x 2x   2x 2x                                                                             2x             3x 3x   3x 10x   10x 10x   3x 3x   3x                                                             1x             2x                 2x                                                                               2x               3x 3x   3x 3x   3x 3x 3x     3x       3x     3x 3x 3x           3x   3x                                                                                                                                   3x                                       2x               6x 6x       6x             6x                                                                                                                                                                                                                                                       2x       6x     6x             6x                               6x 6x 6x 6x 6x         6x 6x               6x 6x   6x 6x 3x               6x   6x                                                                                                                                                                                                                                                                                                                                   6x                                               2x         39x   39x 39x     39x   39x 39x     39x 9x       39x                                                                                                                                     2x         1757x                       2x 1506x                 2x                                                             2x                                                           2x                                                                               10x 8x         586x             639x                   2x             34x                                                 2x           708x                                           2x         573x 573x 573x 573x   573x                                                                                   2x     5x     5x                                                                 2x       10x 10x 10x 10x 10x       10x   5x     10x   10x 10x 10x 5x   10x     10x                                                                                                                                                                                                                   15x                                                     2x         36x 36x 36x 36x     36x                                                                                                 2x               8x 8x 8x       8x   4x     8x 8x 8x 8x 8x   8x                                                                                                                                     8x                                                                                                             12x           4x 4x 4x   4x                   4x           1x                                                                                     2x                                                                                                                                                                                                     2x 85x             2x         54x 54x   54x                                                                                                                                                     2x     11x 11x 3x                     3x     11x 1x                   2x                         11x 11x 1x                   1x 1x                           2x     11x                                                                                                                                                       2x         11x 11x   11x                                                                                                                                                                               6x                                                                                                               2x   2x 2x   2x         10x 10x 10x                                                                                                                                                       2x       2x 2x 2x                                                                                                                                                                                                                                             2x           2x 3x       2x         35x 35x 35x                                                                                                       2x                 2x       3x 3x 3x   3x         3x                                                                                                   6x                                                                                                             2x         747x   39x   54x               573x               36x               10x               35x                                         2x   2x 702x   32x 28x       38x 37x           632x         2x 8x           2x               8x 8x 8x 8x 15x       1x     8x                                                                                     2x                             31x   6x   11x                   5x   4x                 2x   3x                 2x                                             2x       25x 25x                                                                                                 535x             2418x   22x                                   2x         2x       2x 839x     2x 1652x       372x 23x 23x 372x     2x 372x   372x 372x   372x 372x 372x   372x   372x 372x 372x 372x 62x     372x               372x   62x   372x   372x   62x   372x       372x   62x   372x   372x   62x       372x           372x   62x                 32x 32x   372x         372x     86x         86x     654x 654x     372x   84x       372x     62x       62x     25x 25x           372x   62x                 6x   6x   372x             372x     372x     86x           86x             29x 29x   372x   372x       372x 372x 372x   372x   124x 59x 59x         372x   124x 59x 59x         372x   124x                                         372x 131x 27x           35x           656x           29x           6x               29x             131x   741x             372x 1053x 165x 18x         147x 36x 19x             372x 116x   20x             20x                                   56x                   20x             20x                                                     372x 188x 188x 1053x 1004x     1004x 5x   5x     5x   5x           1001x 92x 1x 91x       2x     998x               998x               1x     997x 906x                             372x                             372x 372x   10x   16x   8x   10x   328x                 372x 1702x           372x 1361x 1702x     372x   188x 906x 906x         372x 372x     372x 122x                             372x 138x 2x       2x           372x 195x             372x 195x       372x   372x   372x 372x 6x     6x     372x 3x 3x 3x 2x 3x     372x 24x     2226x 2476x   372x 11x 6x       372x 6x 6x     372x 5x 2x     372x 4x   372x 1x 1x 1x 1x       372x 372x 372x   372x     372x               372x   1860x           372x                                                                                                                           38x                                                                                                                                                                             30x                                                                                                                                   712x                                           1128x           3x                 23x                                                                                         1x                            
import { makerLabel } from "@/objects/modelOrigin";
import AIGeneratedBadge from "@/components/badge/AIGeneratedBadge";
import DiffViewer from "@/components/diff/DiffViewer/DiffViewer";
import GenerationDetails from "@/components/diff/GenerationDetails/GenerationDetails";
import { DEFAULT_HIDDEN_HISTORY_FIELDS } from "@/components/diff/ResourceHistorySection/ResourceHistorySection";
import RuleEvaluationList from "@/components/chat/ExecutionPipeline/RuleEvaluationList";
import {
  systemNodeIcon,
  systemNodeLabel,
} from "@/components/chat/ExecutionPipeline/nodeMeta";
import MainPage from "@/components/page/MainPage/MainPage";
import { describeCost, formatUsd, useSpend } from "@/components/cost";
import {
  ACTIVITY_DOMAIN_LABELS,
  ActivityDomain,
  ActivityEvent,
  ActivityEventDetail,
  ActivityResourceType,
  ActivitySummary,
  BACKGROUND_KIND_LABELS,
  BACKGROUND_TRIGGER_LABELS,
  BackgroundEvent,
  BackgroundKind,
  RESOURCE_TYPE_DOMAIN,
  RESOURCE_TYPE_LABELS,
} from "@/objects/Activity";
import { Agent } from "@/objects/Agent";
import {
  GENERATION_FLOW_LABELS,
  GenerationRun,
  GenerationStatus,
  HistoryAction,
} from "@/objects/History";
import {
  CITATION_KINDS,
  Citation,
  CitationKind,
  Conversation,
  ConversationMessage,
  Model,
  NodePlanResult,
  QualityOutcome,
  SystemNodeResult,
  TraceEvent,
} from "@/objects/Model";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import resourceHref, {
  chatMessageHref,
  skillRunHref,
} from "@/routes/resourceHref";
import {
  LLMInvocationCall,
  LLMInvocationRecord,
} from "@/services/api/routers/StatsRouter";
import {
  calledModels,
  invocationModelLabel,
  modelLabel,
} from "@/util/invocationModels";
import { BatchReportRow } from "@/objects/Evaluation";
import {
  RunStatusBadge,
  ScoreBadge,
  formatScore,
} from "@/apps/user/pages/evaluation/components";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import {
  groupTraceByNode,
  isGraphTool,
  isKbTool,
  NodeTraceData,
  queriedTools,
} from "@/util/traceUtils";
import { storedCitations } from "@/util/citations";
import QualityCheckBadge from "@/components/chat/QualityCheck/QualityCheckBadge";
import { isRuleNodeId } from "@/util/ruleTrace";
import { useQuery } from "@tanstack/react-query";
import {
  Activity,
  AlertCircle,
  AlertTriangle,
  BookMarked,
  Bot,
  Boxes,
  BrainCog,
  Building2,
  CalendarClock,
  Check,
  CheckCircle2,
  ChevronDown,
  ChevronRight,
  ChevronUp,
  ClipboardCheck,
  Clock,
  Coins,
  Cpu,
  Database,
  Download,
  ExternalLink,
  FileStack,
  FileText,
  FlaskConical,
  FolderKanban,
  GitBranch,
  GitCommitVertical,
  Globe,
  Hammer,
  Hash,
  Layers,
  LayoutDashboard,
  Library,
  MessageSquare,
  Network,
  Package,
  Pencil,
  Plus,
  RefreshCw,
  Search,
  Server,
  Settings2,
  ShieldCheck,
  Sparkles,
  Trash2,
  User as UserIcon,
  Workflow,
  Wrench,
  X,
  Zap,
} from "lucide-react";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Link } from "react-router-dom";
import {
  CopyButton,
  encodeResourceId,
  MetaItem,
  Skeleton,
  StatusBadge,
  StatusScale,
} from "@/components/detail";
import { parseServerDate } from "@/util/time";
import { stackConsecutive } from "@/util/feedStack";
import { recalledMemory, recalledMemoryLabel } from "@/util/agentMemory";
import {
  horizonSource,
  pageCount,
  pageSlice,
  settledHorizon,
} from "@/util/pagedFeed";
import { FeedSource, useFeedSource } from "@/hooks/useFeedSource";
import { Pagination } from "@/components/collection";
 
/** Whether a trace produced anything. Its own two-value vocabulary — an
 *  "empty" run is not a failure, just a run with nothing to show. */
const TRACE_STATUS: StatusScale = { success: "success", empty: "neutral" };
 
/** How background work ended. */
const BACKGROUND_STATUS: StatusScale = { ok: "success", failed: "danger" };
 
// ─── Types ────────────────────────────────────────────────────────────────────
 
type RunType = "model" | "agent" | "unknown";
type RunStatus = "success" | "empty";
type TimeFilter = "all" | "today" | "week" | "month";
 
interface Run {
  conversation: Conversation;
  type: RunType;
  status: RunStatus;
  modelName: string | null;
  agentName: string | null;
}
 
// ─── The Unified Feed ─────────────────────────────────────────────────────────
//
// The page shows one stream of heterogeneous events rather than a tab per
// source, because the question an operator arrives with — "what happened?" —
// does not know in advance which of the four it wants. Every event carries a
// timestamp and an id, so the merge is a sort; everything type-specific lives
// behind the `kind` discriminant, which each row and panel switches on once.
 
/**
 * The top-level filter. `all` is the merged stream; the rest narrow it to one
 * part of the platform rather than to one backing table, so "generative"
 * includes both the invocations themselves and the resource changes they
 * caused.
 */
type ActivityCategory =
  | "all"
  | "inference"
  | "resource"
  | "generative"
  | "background";
 
type ActivityItem =
  | { kind: "run"; id: string; timestamp: string; run: Run }
  | {
      kind: "invocation";
      id: string;
      timestamp: string;
      invocation: LLMInvocationRecord;
    }
  | { kind: "change"; id: string; timestamp: string; event: ActivityEvent }
  | {
      kind: "generation";
      id: string;
      timestamp: string;
      generation: GenerationRun;
    }
  // One evaluation or dataset run — a batch of cells, whatever state it is
  // in. Failed and cancelled runs are here on purpose: the feed lists what
  // happened, and a run that fell over is the one an operator is looking for.
  | {
      kind: "evaluation";
      id: string;
      timestamp: string;
      batch: BatchReportRow;
    }
  // Work the platform did without a request — a dashboard tile regenerated,
  // a website source re-crawled, review flags deleted by retention.
  | {
      kind: "background";
      id: string;
      timestamp: string;
      event: BackgroundEvent;
    };
 
/** Sub-filter for the `inference` category. `evaluation` covers both the
 *  runs themselves and the LLM calls they made. */
type InferenceFilter = "all" | "agent" | "model" | "invocation" | "evaluation";
 
/** Purposes an evaluation stamps on its LLM calls — the cells, and the judge
 *  that grades them. Mirrors `TRACE_PURPOSE` / `JUDGE_TRACE_PURPOSE` in
 *  svc-core's `app/services/evaluation/targets.py`. */
const EVALUATION_PURPOSES = new Set(["evaluation", "evaluation_judge"]);
 
/** What an evaluation's LLM call points back at, read off the invocation's
 *  request snapshot. svc-ai stores whatever svc-core sent as `reference`. */
interface InvocationReference {
  experiment_id?: string;
  dataset_id?: string;
  batch_id?: string;
  variant_id?: string;
  source?: string;
  // A dashboard tile's call (`dashboard_widget`) names its board and tile;
  // a board-generation call names the generation run.
  dashboard_id?: string;
  widget_id?: string;
  generation_id?: string;
  // A standalone skill run names the skill and the run.
  skill_id?: string;
  skill_run_id?: string;
}
 
const invocationReference = (
  invocation: LLMInvocationRecord,
): InvocationReference | null => {
  const raw = invocation.request_config?.reference;
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
  const out: InvocationReference = {};
  for (const key of [
    "experiment_id",
    "dataset_id",
    "batch_id",
    "variant_id",
    "source",
    "dashboard_id",
    "widget_id",
    "generation_id",
    "skill_id",
    "skill_run_id",
  ] as const) {
    const value = (raw as Record<string, unknown>)[key];
    if (typeof value === "string" && value) out[key] = value;
  }
  return Object.keys(out).length ? out : null;
};
 
/** Sub-filter for the `background` category — which kind of work. */
type BackgroundFilter = "all" | BackgroundKind;
 
/** Sub-filter for the `resource` category — the lifecycle action. */
type ActionFilter = "all" | HistoryAction;
 
/** Sub-filter for the `generative` category — how far an invocation got. */
type GenerativeFilter = "all" | GenerationStatus;
 
/** Sub-filter narrowing resource changes to one part of the platform. */
type DomainFilter = "all" | ActivityDomain;
 
 
// ─── Trace Helpers ────────────────────────────────────────────────────────────
// (groupTraceByNode, isKbTool, isGraphTool, queriedTools are imported from
//  @/util/traceUtils)
 
// ─── Format Helpers ───────────────────────────────────────────────────────────
 
function formatRelative(iso: string): string {
  const diff = Date.now() - parseServerDate(iso).getTime();
  const mins = Math.floor(diff / 60_000);
  Iif (mins < 1) return "just now";
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  Eif (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(hrs / 24);
  if (days < 30) return `${days}d ago`;
  return parseServerDate(iso).toLocaleDateString(undefined, {
    day: "numeric",
    month: "short",
    year: "numeric",
  });
}
 
function formatTimestamp(iso: string): string {
  return parseServerDate(iso).toLocaleString(undefined, {
    month: "short",
    day: "numeric",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}
 
function formatTokens(n: number): string {
  if (n < 1_000) return String(n);
  Eif (n < 1_000_000) return `${(n / 1_000).toFixed(1)}k`;
  return `${(n / 1_000_000).toFixed(2)}M`;
}
 
function formatDuration(ms: number): string {
  Iif (ms < 1000) return `${ms}ms`;
  return `${(ms / 1000).toFixed(1)}s`;
}
 
function truncate(str: string, max = 80): string {
  return str.length <= max ? str : `${str.slice(0, max)}…`;
}
 
function getFirstUserMessage(conversation: Conversation): string | null {
  const msg = conversation.messages.find((m) => m.role === "user");
  return msg?.content ?? null;
}
 
function deriveRunType(conversation: Conversation): RunType {
  Eif (conversation.agent_id) return "agent";
  if (conversation.ai_model_id) return "model";
  return "unknown";
}
 
function deriveStatus(conversation: Conversation): RunStatus {
  Iif (conversation.messages.length === 0) return "empty";
  return "success";
}
 
function isInTimeRange(iso: string, filter: TimeFilter): boolean {
  if (filter === "all") return true;
  const d = parseServerDate(iso).getTime();
  const now = Date.now();
  const day = 86_400_000;
  Iif (filter === "today") return now - d < day;
  Eif (filter === "week") return now - d < 7 * day;
  if (filter === "month") return now - d < 30 * day;
  return true;
}
 
// ─── Primitives ───────────────────────────────────────────────────────────────
 
const StatusDot: React.FC<{ status: RunStatus }> = ({ status }) => {
  Eif (status === "success")
    return (
      <span className="size-2 rounded-full bg-emerald-400 dark:bg-emerald-500 shrink-0" />
    );
  return (
    <span className="size-2 rounded-full bg-gray-300 dark:bg-gray-600 shrink-0" />
  );
};
 
const TypeBadge: React.FC<{ type: RunType }> = ({ type }) => {
  Eif (type === "agent")
    return (
      <span className="inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded-full bg-violet-50 dark:bg-violet-950/40 text-violet-700 dark:text-violet-300 border border-violet-200 dark:border-violet-800">
        <Bot className="size-2.5" />
        Agent
      </span>
    );
  if (type === "model")
    return (
      <span className="inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded-full bg-blue-50 dark:bg-blue-950/40 text-blue-700 dark:text-blue-300 border border-blue-200 dark:border-blue-800">
        <BrainCog className="size-2.5" />
        Model
      </span>
    );
  return (
    <span className="inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded-full bg-gray-50 dark:bg-gray-800 text-gray-500 dark:text-gray-400 border border-gray-200 dark:border-gray-700">
      Unknown
    </span>
  );
};
 
/** A model, named with its maker — never the platform that served it. */
const withMaker = (modelName: string, provider?: string | null): string =>
  provider ? `${makerLabel(provider, modelName)} · ${modelName}` : modelName;
 
const ModelBadge: React.FC<{ modelName: string; provider?: string }> = ({
  modelName,
  provider,
}) => (
  <span
    title={withMaker(modelName, provider)}
    className="inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded-full bg-indigo-50 dark:bg-indigo-950/40 text-indigo-700 dark:text-indigo-300 border border-indigo-200 dark:border-indigo-800 max-w-[140px] truncate"
  >
    <BrainCog className="size-2.5 shrink-0" />
    <span className="truncate">{withMaker(modelName, provider)}</span>
  </span>
);
 
/**
 * Which revision of the agent produced this result.
 *
 * The number is stamped on the turn when the agent's configuration is *read*,
 * so it survives every later edit — which is what makes a result traceable
 * rather than merely attributed to an agent whose prompt has since changed
 * five times. Links into that agent's history opened on this exact version.
 */
const AgentVersionBadge: React.FC<{
  agentId?: string;
  version: number;
}> = ({ agentId, version }) => {
  const label = (
    <>
      <GitCommitVertical className="size-2.5 shrink-0" />
      <span className="truncate">v{version}</span>
    </>
  );
  const className =
    "inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded-full bg-violet-50 dark:bg-violet-950/40 text-violet-700 dark:text-violet-300 border border-violet-200 dark:border-violet-800";
 
  // Without an agent id there is nothing to resolve the version against, so
  // the badge states it without pretending to link anywhere.
  if (!agentId) {
    return (
      <span title={`Agent version ${version}`} className={className}>
        {label}
      </span>
    );
  }
 
  return (
    <Link
      to={`${APP_ROUTES.USER.INFERENCE.AGENTS.id.replace(
        ROUTE_PARAMS.AGENT.id,
        encodeResourceId(agentId),
      )}?version=${version}`}
      title={`Agent version ${version} — open this revision's history`}
      className={`${className} hover:bg-violet-100 dark:hover:bg-violet-900/40 transition-colors`}
    >
      {label}
    </Link>
  );
};
 
const OutputBlock: React.FC<{
  label: string;
  content: string;
  variant?: "system" | "default" | "transparent";
  labelIcon?: React.ReactNode;
}> = ({ label, content, variant = "system", labelIcon }) => {
  const [expanded, setExpanded] = useState(false);
  const preCls =
    variant === "system"
      ? "bg-blue-50 dark:bg-blue-950/20 border border-blue-100 dark:border-blue-900/40"
      : variant === "default"
        ? "bg-gray-50 dark:bg-gray-700/50 border border-gray-100 dark:border-gray-700"
        : "";
  return (
    <div>
      <div className="flex items-center justify-between mb-1.5">
        <p className="text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500 flex items-center gap-1">
          {labelIcon}
          {label}
        </p>
        <button
          type="button"
          onClick={() => setExpanded((v) => !v)}
          className="flex items-center gap-0.5 text-[10px] text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 transition-colors shrink-0 ml-2"
        >
          {expanded ? (
            <>
              <ChevronUp className="size-2.5" />
              Collapse
            </>
          ) : (
            <>
              <ChevronDown className="size-2.5" />
              Expand
            </>
          )}
        </button>
      </div>
      <pre
        className={`whitespace-pre-wrap break-words text-[11px] font-mono text-gray-600 dark:text-gray-400 rounded-lg px-3 py-2 leading-relaxed overflow-y-auto transition-all ${preCls} ${expanded ? "" : "max-h-48"}`}
      >
        {content}
      </pre>
    </div>
  );
};
 
// ─── Token Bar ────────────────────────────────────────────────────────────────
 
const TokenBar: React.FC<{ input: number; output: number }> = ({
  input,
  output,
}) => {
  const total = input + output;
  Iif (total === 0) return null;
  const inPct = Math.round((input / total) * 100);
  return (
    <div>
      <div className="flex items-center justify-between text-[10px] text-gray-400 dark:text-gray-500 mb-1">
        <span className="text-blue-500 dark:text-blue-400 font-medium">
          ↑ {formatTokens(input)} in ({inPct}%)
        </span>
        <span className="text-violet-500 dark:text-violet-400 font-medium">
          ↓ {formatTokens(output)} out ({100 - inPct}%)
        </span>
      </div>
      <div className="h-1.5 rounded-full overflow-hidden bg-gray-100 dark:bg-gray-700 flex">
        <div
          className="bg-blue-400 dark:bg-blue-500 h-full transition-all"
          style={{ width: `${inPct}%` }}
        />
        <div className="bg-violet-400 dark:bg-violet-500 h-full flex-1" />
      </div>
    </div>
  );
};
 
// ─── Tool Call Detail ─────────────────────────────────────────────────────────
 
const ToolCallDetail: React.FC<{
  tc: NodeTraceData["tools"][number];
  index: number;
}> = ({ tc, index }) => {
  const [open, setOpen] = useState(false);
  const isKb = isKbTool(tc.tool);
  const isError = tc.status === "error";
  const hasParams = tc.params && Object.keys(tc.params).length > 0;
  const hasDetail = hasParams || !!tc.output_preview;
 
  const borderCls = isError
    ? "border-red-200 dark:border-red-800/60 bg-red-50 dark:bg-red-950/20"
    : isKb
      ? "border-teal-200 dark:border-teal-800/40 bg-teal-50/50 dark:bg-teal-950/10"
      : "border-amber-200 dark:border-amber-800/40 bg-amber-50/50 dark:bg-amber-950/10";
 
  return (
    <div className={`rounded-lg border text-xs overflow-hidden ${borderCls}`}>
      <button
        type="button"
        onClick={() => hasDetail && setOpen((v) => !v)}
        className={`w-full flex items-center gap-2 px-3 py-2 text-left ${hasDetail ? "" : "cursor-default"}`}
      >
        <span className="text-[10px] font-bold tabular-nums text-gray-400 dark:text-gray-600 w-4 shrink-0">
          {index + 1}
        </span>
        {isError ? (
          <AlertCircle className="size-3 text-red-500 shrink-0" />
        ) : isKb ? (
          isGraphTool(tc.tool) ? (
            <Network className="size-3 text-teal-500 shrink-0" />
          ) : (
            <Database className="size-3 text-blue-500 shrink-0" />
          )
        ) : (
          <Hammer className="size-3 text-amber-500 shrink-0" />
        )}
        <span className="font-mono font-semibold text-gray-700 dark:text-gray-300 flex-1 truncate">
          {tc.tool}
        </span>
        {isKb && (
          <span className="shrink-0 px-1.5 py-0.5 rounded text-[10px] font-semibold bg-teal-100 dark:bg-teal-900/40 text-teal-700 dark:text-teal-300">
            KB
          </span>
        )}
        <span
          className={`shrink-0 px-1.5 py-0.5 rounded text-[10px] font-semibold ${
            isError
              ? "bg-red-100 dark:bg-red-900/40 text-red-600 dark:text-red-400"
              : "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-600 dark:text-emerald-400"
          }`}
        >
          {tc.status}
        </span>
        {hasDetail &&
          (open ? (
            <ChevronUp className="size-3 text-gray-400 shrink-0" />
          ) : (
            <ChevronDown className="size-3 text-gray-400 shrink-0" />
          ))}
      </button>
 
      {open && hasDetail && (
        <div className="px-3 pb-3 border-t border-inherit space-y-2">
          {hasParams && (
            <div>
              <p className="text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500 mt-2 mb-1.5">
                Parameters
              </p>
              <div className="space-y-0.5">
                {Object.entries(tc.params!).map(([k, v]) => (
                  <div key={k} className="flex gap-2 font-mono text-[11px]">
                    <span className="text-blue-500 dark:text-blue-400 shrink-0">
                      {k}:
                    </span>
                    <span className="text-gray-600 dark:text-gray-400 break-all">
                      {typeof v === "string" ? v : JSON.stringify(v)}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          )}
          {tc.output_preview && (
            <OutputBlock
              label="Output"
              content={tc.output_preview}
              variant="transparent"
            />
          )}
        </div>
      )}
    </div>
  );
};
 
// ─── System Node Content ──────────────────────────────────────────────────────
 
const ACTIVITY_LABEL_CLS =
  "text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500 mb-1.5";
 
/** What triage's scope check found, as a person reads it. */
const SCOPE_CHECK_TEXT: Record<string, string> = {
  clear: "clear — nothing to ask",
  ambiguous: "unclear — asked first",
  unavailable: "could not run",
};
 
/**
 * The task's shape — complexity, skill graph, scope check, suggested tools
 * and notes. Triage decides it in the same call as the route; stored traces
 * from before October 2026 carry it on a separate `__recon__` stage.
 */
const TaskShape: React.FC<{ shape?: Record<string, unknown> }> = ({ shape }) => {
  const complexity = shape?.complexity ? String(shape.complexity) : "";
  const useSkillGraph = shape?.use_skill_graph !== false;
  const tools = Array.isArray(shape?.relevant_tools)
    ? (shape.relevant_tools as unknown[]).map(String)
    : [];
  const notes = shape?.resource_notes ? String(shape.resource_notes) : "";
  const scope = shape?.scope_check ? String(shape.scope_check) : "";
  const reason = shape?.ambiguity_reason ? String(shape.ambiguity_reason) : "";
  return (
    <>
      {complexity && (
        <div className="flex flex-wrap gap-3 text-[11px] font-mono">
          <span className="flex items-center gap-1.5">
            <span className="text-gray-400 dark:text-gray-500">complexity:</span>
            <span className="font-semibold text-blue-600 dark:text-blue-400">
              {complexity}
            </span>
          </span>
          <span className="flex items-center gap-1.5">
            <span className="text-gray-400 dark:text-gray-500">skill graph:</span>
            <span
              className={`font-semibold ${useSkillGraph ? "text-emerald-600 dark:text-emerald-400" : "text-amber-600 dark:text-amber-400"}`}
            >
              {useSkillGraph ? "yes" : "no"}
            </span>
          </span>
        </div>
      )}
      {scope && (
        <p className="text-xs text-gray-600 dark:text-gray-400">
          {`Scope check: ${SCOPE_CHECK_TEXT[scope] ?? scope}`}
          {reason && (
            <span className="block text-gray-400 dark:text-gray-500">{reason}</span>
          )}
        </p>
      )}
      {tools.length > 0 && (
        <div>
          <p className={ACTIVITY_LABEL_CLS}>Suggested Tools</p>
          <p className="text-[11px] font-mono text-gray-600 dark:text-gray-400">
            {tools.join(", ")}
          </p>
        </div>
      )}
      {notes && (
        <div>
          <p className={ACTIVITY_LABEL_CLS}>Strategy Notes</p>
          <p className="text-xs text-gray-600 dark:text-gray-400 leading-relaxed">
            {notes}
          </p>
        </div>
      )}
    </>
  );
};
 
const SystemNodeContent: React.FC<{
  nodeId: string;
  systemResult?: SystemNodeResult;
  nodeInput?: Record<string, unknown>;
}> = ({ nodeId, systemResult, nodeInput }) => {
  const labelCls = ACTIVITY_LABEL_CLS;
 
  function renderInputSection() {
    if (!nodeInput || Object.keys(nodeInput).length === 0) return null;
    return (
      <div className="space-y-1.5 border-b border-blue-100 dark:border-blue-900/40 pb-3 mb-3">
        <p className={labelCls}>Node Input</p>
        {nodeInput.input != null && (
          <OutputBlock label="input" content={String(nodeInput.input)} />
        )}
        {Object.entries(nodeInput)
          .filter(([k]) => k !== "input")
          .map(([k, v]) => {
            const display =
              typeof v === "boolean"
                ? String(v)
                : Array.isArray(v)
                  ? (v as unknown[]).join(", ") || "—"
                  : v != null
                    ? String(v)
                    : "—";
            return (
              <div key={k} className="flex gap-2 text-[11px] font-mono">
                <span className="text-blue-500 dark:text-blue-400 shrink-0">
                  {k}:
                </span>
                <span className="text-gray-500 dark:text-gray-400 break-all">
                  {display}
                </span>
              </div>
            );
          })}
      </div>
    );
  }
 
  const errBlock = (msg: string) => (
    <div className="rounded-lg border border-red-200 dark:border-red-800/60 bg-red-50 dark:bg-red-950/20 px-3 py-2.5 space-y-1.5">
      <p className="text-xs font-semibold text-red-600 dark:text-red-400 flex items-center gap-1.5">
        <AlertCircle className="size-3 shrink-0" />
        Error
      </p>
      <pre className="whitespace-pre-wrap break-words text-[11px] font-mono text-red-500 dark:text-red-400 leading-relaxed max-h-48 overflow-y-auto">
        {msg}
      </pre>
    </div>
  );
 
  if (isRuleNodeId(nodeId)) {
    return <RuleEvaluationList nodeId={nodeId} result={systemResult} />;
  }
 
  if (nodeId === "__gate__") {
    const gate = systemResult as
      | {
          route?: string;
          retrieval_type?: string;
          trivial_output?: string;
          kb_metadata?: string;
        }
      | undefined;
    const route = gate?.route ?? "";
    // Meaningful only for a retrieve route: "direct · internal" read as an
    // internal search that never ran.
    const rtype = route === "retrieve" ? (gate?.retrieval_type ?? "") : "";
    const trivialOutput = gate?.trivial_output ?? "";
    const kbMeta = gate?.kb_metadata ?? "";
    const ROUTE_DESC: Record<string, string> = {
      direct: "Answered directly — no planning or retrieval required.",
      plan: "Complex task — planning executed before skill nodes.",
      retrieve: "Retrieval executed before skill nodes (no planning).",
      plan_retrieve: "Full pipeline — planning and retrieval both executed.",
      trivial: "Trivial input — answered without LLM.",
    };
    return (
      <div className="space-y-2.5">
        {renderInputSection()}
        {trivialOutput ? (
          <OutputBlock
            label="Trivial Bypass"
            content={trivialOutput}
            labelIcon={<GitBranch className="size-3" />}
          />
        ) : (
          <div className="rounded-lg bg-blue-50/50 dark:bg-blue-950/10 border border-blue-100 dark:border-blue-900/30 px-3 py-2.5 space-y-1">
            <p className="text-xs text-blue-600 dark:text-blue-400 font-medium flex items-center gap-1.5">
              <GitBranch className="size-3 shrink-0" />
              {route
                ? `Route: ${route}${rtype ? ` · retrieval: ${rtype}` : ""}`
                : "Routing classification performed"}
            </p>
            {route && (
              <p className="text-[11px] text-blue-500/70 dark:text-blue-400/60">
                {ROUTE_DESC[route] ?? `Execution route: ${route}`}
              </p>
            )}
          </div>
        )}
        {!trivialOutput && (
          <TaskShape shape={systemResult as Record<string, unknown> | undefined} />
        )}
        {kbMeta && (
          <OutputBlock
            label="Knowledge Base Contents (used for routing)"
            content={kbMeta}
          />
        )}
      </div>
    );
  }
 
  // Stored traces from before triage decided the task's shape itself.
  if (nodeId === "__recon__") {
    const recon = systemResult as { recon_context?: string } | undefined;
    const reconCtx = recon?.recon_context ?? "";
    return (
      <div className="space-y-2.5">
        {renderInputSection()}
        <TaskShape shape={systemResult as Record<string, unknown> | undefined} />
        {reconCtx && <OutputBlock label="Recon Context" content={reconCtx} />}
      </div>
    );
  }
 
  if (nodeId === "__planning__") {
    const hasPlanResult = systemResult && "overall_goal" in systemResult;
    if (!hasPlanResult) {
      return (
        <div className="space-y-2.5">
          {renderInputSection()}
          <p className="text-xs text-gray-400 dark:text-gray-500 italic">
            Plan data not recorded for this run.
          </p>
        </div>
      );
    }
    const plan = systemResult as {
      task_summary: string;
      overall_goal: string;
      retrieval_focus: string;
      node_plans: NodePlanResult[];
      plan_error?: string;
    };
    const hasContent =
      plan.overall_goal ||
      plan.task_summary ||
      plan.retrieval_focus ||
      (plan.node_plans && plan.node_plans.length > 0);
    if (!hasContent) {
      return (
        <div className="space-y-2.5">
          {renderInputSection()}
          {plan.plan_error ? (
            errBlock(plan.plan_error)
          ) : (
            <p className="text-xs text-gray-400 dark:text-gray-500 italic">
              Planning completed — no structured plan details available.
            </p>
          )}
        </div>
      );
    }
    return (
      <div className="space-y-3">
        {renderInputSection()}
        {plan.overall_goal && (
          <div>
            <p className={labelCls}>Goal</p>
            <p className="text-xs text-gray-700 dark:text-gray-300 leading-relaxed">
              {plan.overall_goal}
            </p>
          </div>
        )}
        {plan.task_summary && (
          <div>
            <p className={labelCls}>Task Summary</p>
            <p className="text-xs text-gray-600 dark:text-gray-400 leading-relaxed">
              {plan.task_summary}
            </p>
          </div>
        )}
        {plan.retrieval_focus && (
          <div>
            <p className={labelCls}>Retrieval Focus</p>
            <p className="text-xs text-gray-600 dark:text-gray-400 leading-relaxed">
              {plan.retrieval_focus}
            </p>
          </div>
        )}
        {plan.node_plans && plan.node_plans.length > 0 && (
          <div>
            <p className={labelCls}>Node Plans ({plan.node_plans.length})</p>
            <div className="space-y-2">
              {plan.node_plans.map((np, i) => (
                <div
                  key={i}
                  className="bg-blue-50 dark:bg-blue-950/20 border border-blue-100 dark:border-blue-900/40 rounded-lg px-3 py-2 space-y-1"
                >
                  <p className="text-[10px] font-bold font-mono text-blue-600 dark:text-blue-400">
                    {np.node_id}
                  </p>
                  <p className="text-xs text-gray-700 dark:text-gray-300">
                    {np.goal}
                  </p>
                  {np.expected_output && (
                    <p className="text-[11px] text-gray-500 dark:text-gray-400">
                      Expected: {np.expected_output}
                    </p>
                  )}
                  {np.success_criteria && (
                    <p className="text-[11px] text-emerald-600 dark:text-emerald-400">
                      ✓ {np.success_criteria}
                    </p>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  }
 
  if (
    nodeId === "__retrieval__" ||
    nodeId === "__internal_retrieval__" ||
    nodeId === "__retrieval_join__"
  ) {
    const r = systemResult as
      { retrieval_context?: string; error?: string } | undefined;
    const ctx = r?.retrieval_context ?? "";
    return (
      <div className="space-y-2.5">
        {renderInputSection()}
        {r?.error && !ctx ? (
          errBlock(r.error)
        ) : ctx ? (
          <OutputBlock label="Internal KB Context" content={ctx} />
        ) : null}
      </div>
    );
  }
 
  if (nodeId === "__external_retrieval__") {
    const r = systemResult as
      { retrieval_context?: string; error?: string } | undefined;
    const ctx = r?.retrieval_context ?? "";
    return (
      <div className="space-y-2.5">
        {renderInputSection()}
        {r?.error && !ctx ? (
          errBlock(r.error)
        ) : ctx ? (
          <OutputBlock label="External Sources Context" content={ctx} />
        ) : null}
      </div>
    );
  }
 
  if (nodeId === "__tool_retrieval__") {
    const r = systemResult as
      { retrieval_context?: string; error?: string } | undefined;
    const ctx = r?.retrieval_context ?? "";
    return (
      <div className="space-y-2.5">
        {renderInputSection()}
        {r?.error && !ctx ? (
          errBlock(r.error)
        ) : ctx ? (
          <OutputBlock label="Tool Results Context" content={ctx} />
        ) : null}
      </div>
    );
  }
 
  if (nodeId === "__synthesis__") {
    const synth = systemResult as
      { output?: string; error?: string } | undefined;
    return (
      <div className="space-y-2.5">
        {renderInputSection()}
        {synth?.error && !synth.output ? (
          errBlock(synth.error)
        ) : synth?.output ? (
          <OutputBlock label="Synthesis Output" content={synth.output} />
        ) : null}
      </div>
    );
  }
 
  if (nodeId === "__memory_read__") {
    const raw = (systemResult as { memories?: unknown } | undefined)?.memories;
    const memories = Array.isArray(raw) ? raw.map(recalledMemory) : [];
    return (
      <div className="space-y-2.5">
        {renderInputSection()}
        <div>
          <p className={labelCls}>
            {memories.length === 0
              ? "No prior memories for this user"
              : `${memories.length} memor${memories.length === 1 ? "y" : "ies"} recalled`}
          </p>
          {memories.length > 0 && (
            <div className="space-y-1.5 mt-1">
              {memories.map((m, i) => (
                <OutputBlock
                  key={i}
                  label={`Memory ${i + 1} — ${recalledMemoryLabel(m)}`}
                  content={m.text}
                />
              ))}
            </div>
          )}
        </div>
      </div>
    );
  }
 
  if (nodeId === "__memory_write__") {
    const { stored, content } = (systemResult ?? {}) as {
      stored?: boolean;
      content?: string;
    };
    return (
      <div className="space-y-2.5">
        {renderInputSection()}
        {stored ? (
          <OutputBlock label="Stored Memory" content={String(content ?? "")} />
        ) : (
          <p className="text-xs text-gray-400 dark:text-gray-500 italic">
            Nothing stored — no output to persist.
          </p>
        )}
      </div>
    );
  }
 
  if (nodeId === "__evaluator__") {
    const ev = (systemResult ?? {}) as {
      passed?: boolean;
      score?: number;
      gaps?: string[];
      critique?: string;
      final_output?: string;
    };
    const passed = ev.passed;
    const score = ev.score;
    const gaps = ev.gaps ?? [];
    const critique = ev.critique ?? "";
    const finalOut = ev.final_output ?? "";
    const scoreCls =
      score === undefined
        ? ""
        : score >= 80
          ? "text-emerald-600 dark:text-emerald-400"
          : score >= 50
            ? "text-amber-600 dark:text-amber-400"
            : "text-red-600 dark:text-red-400";
    return (
      <div className="space-y-3">
        {renderInputSection()}
        <div className="flex items-center gap-4 text-xs font-mono">
          {score !== undefined && (
            <span className={`font-bold text-sm ${scoreCls}`}>{score}/100</span>
          )}
          {passed !== undefined && (
            <span
              className={`px-2 py-0.5 rounded-full text-[10px] font-semibold ${passed ? "bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300" : "bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300"}`}
            >
              {passed ? "passed" : "sent back to the agent"}
            </span>
          )}
        </div>
        {critique && (
          <p className="text-xs text-gray-500 dark:text-gray-400 italic">
            {critique}
          </p>
        )}
        {gaps.length > 0 && (
          <div>
            <p className={labelCls}>
              Gaps identified &amp; filled ({gaps.length})
            </p>
            <div className="space-y-1">
              {gaps.map((g, i) => (
                <div
                  key={i}
                  className="flex items-start gap-1.5 text-[11px] bg-amber-50 dark:bg-amber-950/20 border border-amber-100 dark:border-amber-900/30 rounded px-2 py-1 font-mono text-amber-700 dark:text-amber-300"
                >
                  <span className="shrink-0">↳</span>
                  <span>{g}</span>
                </div>
              ))}
            </div>
          </div>
        )}
        {finalOut && <OutputBlock label="Final Output" content={finalOut} />}
      </div>
    );
  }
 
  // Fallback: show raw result + input for unknown node types
  const hasResult = systemResult && Object.keys(systemResult).length > 0;
  const hasInput = nodeInput && Object.keys(nodeInput).length > 0;
  if (!hasResult && !hasInput) return null;
  return (
    <div className="space-y-2.5">
      {renderInputSection()}
      {hasResult && (
        <OutputBlock
          label="Node Data"
          content={JSON.stringify(systemResult, null, 2)}
        />
      )}
    </div>
  );
};
 
// ─── Node Card ────────────────────────────────────────────────────────────────
 
const NodeCard: React.FC<{
  node: NodeTraceData;
  index: number;
  total: number;
}> = ({ node, index, total }) => {
  const [open, setOpen] = useState(false);
  const totalTok = node.tokens.input + node.tokens.output;
  const hasTools = node.tools.length > 0;
  const hasError = node.tools.some((t) => t.status === "error");
  const isSys = node.is_system_node;
 
  const borderCls = isSys
    ? "border-blue-200 dark:border-blue-800/50"
    : "border-gray-200 dark:border-gray-700";
  const headerCls = isSys
    ? "bg-blue-50 dark:bg-blue-950/30 hover:bg-blue-100/60 dark:hover:bg-blue-900/30"
    : "bg-gray-50 dark:bg-gray-800/60 hover:bg-gray-100 dark:hover:bg-gray-700/50";
  const bodyBorderCls = isSys
    ? "border-blue-100 dark:border-blue-900/40"
    : "border-gray-100 dark:border-gray-700";
  const counterCls = isSys
    ? "bg-blue-100 dark:bg-blue-900/40 border-blue-200 dark:border-blue-800"
    : "bg-violet-100 dark:bg-violet-900/40 border-violet-200 dark:border-violet-800";
  const counterTextCls = isSys
    ? "text-blue-600 dark:text-blue-400"
    : "text-violet-600 dark:text-violet-400";
  const metaCls = isSys
    ? "text-blue-400 dark:text-blue-500"
    : "text-gray-400 dark:text-gray-500";
 
  return (
    <div className="relative">
      {index < total - 1 && (
        <div
          className={`absolute left-[19px] top-full w-px h-2 z-10 ${
            isSys
              ? "bg-blue-200 dark:bg-blue-800/50"
              : "bg-gray-200 dark:bg-gray-700"
          }`}
        />
      )}
 
      <div className={`rounded-lg border overflow-hidden ${borderCls}`}>
        <button
          type="button"
          onClick={() => setOpen((v) => !v)}
          className={`w-full flex items-center gap-3 px-3 py-2.5 transition-colors text-left ${headerCls}`}
        >
          {/* Step counter / system icon */}
          {isSys ? (
            <div
              className={`size-5 rounded-full border flex items-center justify-center shrink-0 ${counterCls}`}
            >
              <span className={counterTextCls}>
                {systemNodeIcon(node.node_id, "size-3 shrink-0")}
              </span>
            </div>
          ) : (
            <div
              className={`size-5 rounded-full border flex items-center justify-center shrink-0 ${counterCls}`}
            >
              <span className={`text-[10px] font-bold ${counterTextCls}`}>
                {index + 1}
              </span>
            </div>
          )}
 
          {isSys ? (
            <span
              className={`text-xs font-semibold flex-1 truncate ${counterTextCls}`}
            >
              {systemNodeLabel(node.node_id)}
            </span>
          ) : (
            <>
              <Zap className="size-3 text-violet-400 dark:text-violet-500 shrink-0" />
              <span className="font-mono text-xs font-semibold text-gray-700 dark:text-gray-300 truncate">
                {node.node_id}
              </span>
              {node.model_name && (
                <ModelBadge
                  modelName={node.model_name}
                  provider={node.provider}
                />
              )}
            </>
          )}
 
          {isSys && (
            <span className="px-1.5 py-0.5 rounded text-[10px] font-semibold bg-blue-100 dark:bg-blue-900/50 text-blue-600 dark:text-blue-300 shrink-0">
              SYSTEM
            </span>
          )}
 
          <div
            className={`flex items-center gap-2.5 text-[10px] shrink-0 ${metaCls}`}
          >
            {hasError && (
              <AlertCircle className="size-3 text-red-400 shrink-0" />
            )}
            {hasTools && (
              <span className="flex items-center gap-1">
                <Hammer className="size-2.5 text-amber-400" />
                {node.tools.length}
              </span>
            )}
            {totalTok > 0 && (
              <span className="flex items-center gap-1 tabular-nums">
                <Coins className="size-2.5" />
                {formatTokens(totalTok)}
              </span>
            )}
            {node.duration_ms > 0 && (
              <span className="flex items-center gap-1 tabular-nums">
                <Clock className="size-2.5" />
                {formatDuration(node.duration_ms)}
              </span>
            )}
            {open ? (
              <ChevronUp className="size-3" />
            ) : (
              <ChevronDown className="size-3" />
            )}
          </div>
        </button>
 
        {open && (
          <div
            className={`px-4 py-3 space-y-3 border-t bg-white dark:bg-gray-800 ${bodyBorderCls}`}
          >
            {totalTok > 0 && (
              <div>
                <p className="text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500 mb-1.5">
                  Token Usage
                </p>
                <TokenBar
                  input={node.tokens.input}
                  output={node.tokens.output}
                />
                <div className="flex items-center gap-4 mt-1.5 text-[10px] text-gray-500 dark:text-gray-400">
                  <span>
                    <span className="font-semibold text-blue-500 dark:text-blue-400">
                      {node.tokens.input.toLocaleString()}
                    </span>{" "}
                    input
                  </span>
                  <span>
                    <span className="font-semibold text-violet-500 dark:text-violet-400">
                      {node.tokens.output.toLocaleString()}
                    </span>{" "}
                    output
                  </span>
                  <span>
                    <span className="font-semibold text-gray-600 dark:text-gray-300">
                      {totalTok.toLocaleString()}
                    </span>{" "}
                    total
                  </span>
                </div>
              </div>
            )}
 
            {hasTools && (
              <div>
                <p className="text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500 mb-1.5">
                  Tool Calls ({node.tools.length})
                </p>
                <div className="space-y-1.5">
                  {node.tools.map((tc, i) => (
                    <ToolCallDetail key={i} tc={tc} index={i} />
                  ))}
                </div>
              </div>
            )}
 
            {isSys ? (
              <SystemNodeContent
                nodeId={node.node_id}
                systemResult={node.system_result}
                nodeInput={node.system_input}
              />
            ) : (
              node.output_preview && (
                <OutputBlock
                  label="Node Output"
                  content={node.output_preview}
                  variant="default"
                />
              )
            )}
          </div>
        )}
      </div>
    </div>
  );
};
 
// ─── Sources Panel ────────────────────────────────────────────────────────────
 
/** How each kind of cited source is headed in a turn's sources panel. */
const SOURCE_GROUPS: Record<CitationKind, { label: string; icon: React.ReactNode }> = {
  web: { label: "Web", icon: <Globe className="size-3 shrink-0" /> },
  knowledge: {
    label: "Knowledge bases",
    icon: <Database className="size-3 shrink-0" />,
  },
  graph: {
    label: "Knowledge graphs",
    icon: <Network className="size-3 shrink-0" />,
  },
  document: { label: "Documents", icon: <FileText className="size-3 shrink-0" /> },
  other: { label: "Other tools", icon: <Hammer className="size-3 shrink-0" /> },
};
 
function citationHref(citation: Citation): string | null {
  const href = citation.url || citation.source;
  return href && /^https?:\/\//.test(href) ? href : null;
}
 
function hostnameOf(href: string): string {
  try {
    return new URL(href).hostname;
  } catch {
    return "";
  }
}
 
const CitedSourceRow: React.FC<{ citation: Citation }> = ({ citation }) => {
  const href = citationHref(citation);
  const host = href ? hostnameOf(href) : "";
  const name = citation.title || host || citation.source || citation.tool;
  // Where it came from: the knowledge base, else the site.
  const where = citation.kb_name || (host && host !== name ? host : "");
  return (
    <li className="flex items-center gap-2 text-xs min-w-0">
      {href ? (
        <a
          href={href}
          target="_blank"
          rel="noopener noreferrer"
          className="font-medium text-gray-700 dark:text-gray-300 truncate hover:underline"
        >
          {name}
        </a>
      ) : (
        <span className="font-medium text-gray-700 dark:text-gray-300 truncate">
          {name}
        </span>
      )}
      {where && (
        <span className="text-[10px] text-gray-400 dark:text-gray-500 truncate shrink-0 max-w-[40%]">
          {where}
        </span>
      )}
    </li>
  );
};
 
/**
 * The sources a turn's answer cites, grouped by what each is a source of,
 * beside what its quality check concluded.
 *
 * This was "Grounding Sources … fully grounded": every `search_*` call the
 * turn made, claimed as grounding whenever each returned anything. It saw
 * neither the web nor the quality check, so an answer written from web
 * results, which failed its check, read as fully grounded in a knowledge
 * base it never used. It now lists what the answer itself cites
 * (`meta.cited_sources`) in neutral colours, and the verdict is the quality
 * check's badge alone. A turn stored before its sources were has only its
 * trace, which says what was asked, not what the answer used: "Tools
 * queried", with no claim either way.
 */
const SourcesPanel: React.FC<{
  nodes: NodeTraceData[];
  /** `undefined`: the turn was stored without its sources. */
  citedSources?: Citation[];
  evalOutcome?: QualityOutcome;
  evalScore?: number;
}> = ({ nodes, citedSources, evalOutcome, evalScore }) => {
  const tools = citedSources ? [] : queriedTools(nodes);
  Iif (!citedSources && tools.length === 0) return null;
 
  const groups = citedSources
    ? CITATION_KINDS.map((kind) => ({
        kind,
        sources: citedSources.filter((c) => (c.kind ?? "other") === kind),
      })).filter((g) => g.sources.length > 0)
    : [];
  const count = citedSources ? citedSources.length : tools.length;
  const noun = citedSources ? "source" : "tool";
 
  return (
    <section
      aria-label={citedSources ? "Sources the answer cites" : "Tools queried"}
      className="rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/40 overflow-hidden"
    >
      <div className="flex items-center gap-2 px-3 py-2 border-b border-gray-200 dark:border-gray-700">
        {citedSources ? (
          <BookMarked className="size-3.5 text-gray-400 dark:text-gray-500 shrink-0" />
        ) : (
          <Hammer className="size-3.5 text-gray-400 dark:text-gray-500 shrink-0" />
        )}
        <span className="text-xs font-semibold text-gray-700 dark:text-gray-300">
          {citedSources ? "Sources the answer cites" : "Tools queried"}
        </span>
        <span className="text-[10px] text-gray-400 dark:text-gray-500 tabular-nums">
          {count} {noun}
          {count !== 1 ? "s" : ""}
        </span>
        {evalOutcome && (
          <span className="ml-auto">
            <QualityCheckBadge outcome={evalOutcome} score={evalScore} />
          </span>
        )}
      </div>
      <div className="px-3 py-2.5 space-y-2.5">
        {citedSources && citedSources.length === 0 && (
          <p className="text-xs text-gray-500 dark:text-gray-400">
            The answer cites no sources.
          </p>
        )}
        {groups.map(({ kind, sources }) => (
          <div key={kind} role="group" aria-label={SOURCE_GROUPS[kind].label}>
            <p className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500 mb-1">
              {SOURCE_GROUPS[kind].icon}
              {SOURCE_GROUPS[kind].label}
            </p>
            <ul className="space-y-1 pl-4">
              {sources.map((c, i) => (
                <CitedSourceRow key={`${c.index}-${i}`} citation={c} />
              ))}
            </ul>
          </div>
        ))}
        {tools.length > 0 && (
          <>
            <ul className="space-y-1.5">
              {tools.map((t) => (
                <li
                  key={`${t.tool}-${t.knowledgeBase ?? ""}`}
                  className="flex items-center gap-2.5 text-xs text-gray-400 dark:text-gray-500"
                >
                  {t.isKnowledge ? (
                    isGraphTool(t.tool) ? (
                      <Network className="size-3 shrink-0" />
                    ) : (
                      <Database className="size-3 shrink-0" />
                    )
                  ) : (
                    <Hammer className="size-3 shrink-0" />
                  )}
                  <span className="font-mono font-medium text-gray-700 dark:text-gray-300 truncate">
                    {t.tool}
                  </span>
                  {t.knowledgeBase && (
                    <span className="truncate">{t.knowledgeBase}</span>
                  )}
                  <span className="ml-auto shrink-0 text-[10px] tabular-nums">
                    {t.calls}× called
                    {t.errors > 0 && ` · ${t.errors} failed`}
                  </span>
                </li>
              ))}
            </ul>
            <p className="text-[10px] text-gray-400 dark:text-gray-500 pt-0.5">
              What this turn asked its tools. Its answer has no stored sources
              (stored before answers kept them, or blocked), so which of these
              the answer used is not recorded.
            </p>
          </>
        )}
      </div>
    </section>
  );
};
 
// ─── Trace View ───────────────────────────────────────────────────────────────
 
const TraceView: React.FC<{
  trace: TraceEvent[];
  /** The sources the answer cites, as stored with it; `undefined` for a
   *  turn stored before they were. */
  citedSources?: Citation[];
  evalOutcome?: QualityOutcome;
  evalScore?: number;
}> = ({ trace, citedSources, evalOutcome, evalScore }) => {
  const nodes = groupTraceByNode(trace);
  Iif (nodes.length === 0) return null;
 
  const skillNodes = nodes.filter((n) => !n.is_system_node);
  const sysNodes = nodes.filter((n) => n.is_system_node);
 
  const totalTools = skillNodes.reduce((s, n) => s + n.tools.length, 0);
  const skillTok = skillNodes.reduce(
    (s, n) => s + n.tokens.input + n.tokens.output,
    0,
  );
  const sysTok = sysNodes.reduce(
    (s, n) => s + n.tokens.input + n.tokens.output,
    0,
  );
  const totalMs = nodes.reduce((s, n) => s + n.duration_ms, 0);
 
  // Collect unique provider/model pairs across all nodes
  const modelSet = new Map<string, { modelName: string; provider?: string }>();
  for (const n of nodes) {
    Iif (n.model_name) {
      const key = n.provider ? `${n.provider}/${n.model_name}` : n.model_name;
      if (!modelSet.has(key))
        modelSet.set(key, { modelName: n.model_name, provider: n.provider });
    }
  }
  const uniqueModels = Array.from(modelSet.values());
 
  return (
    <div className="rounded-xl border border-violet-200 dark:border-violet-800/40 bg-violet-50/30 dark:bg-violet-950/10 overflow-hidden">
      {/* Header */}
      <div className="flex flex-col gap-2 px-4 py-2.5 border-b border-violet-200 dark:border-violet-800/40 bg-violet-50 dark:bg-violet-950/20">
        <div className="flex items-center gap-2">
          <Layers className="size-3.5 text-violet-500 shrink-0" />
          <span className="text-xs font-semibold text-violet-700 dark:text-violet-300">
            Execution Trace
          </span>
          {uniqueModels.length > 0 && (
            <div className="flex items-center gap-1 flex-wrap ml-1">
              {uniqueModels.map((m) => (
                <ModelBadge
                  key={
                    m.provider ? `${m.provider}/${m.modelName}` : m.modelName
                  }
                  modelName={m.modelName}
                  provider={m.provider}
                />
              ))}
            </div>
          )}
        </div>
        <div className="flex items-center gap-3 text-[10px] text-violet-500/70 dark:text-violet-400/60">
          <span>
            {skillNodes.length} skill node{skillNodes.length !== 1 ? "s" : ""}
            {sysNodes.length > 0 && (
              <span className="text-blue-400 dark:text-blue-500 ml-1">
                + {sysNodes.length} system
              </span>
            )}
          </span>
          {totalTools > 0 && (
            <span className="flex items-center gap-0.5">
              <Hammer className="size-2.5" />
              {totalTools} tool{totalTools !== 1 ? "s" : ""}
            </span>
          )}
          {skillTok > 0 && (
            <span
              className="flex items-center gap-0.5"
              title="Skill node tokens"
            >
              <Coins className="size-2.5" />
              {formatTokens(skillTok)}
              {sysTok > 0 && (
                <span
                  className="text-blue-400 dark:text-blue-500 ml-0.5"
                  title={`+${formatTokens(sysTok)} system overhead`}
                >
                  +{formatTokens(sysTok)}
                </span>
              )}
            </span>
          )}
          {totalMs > 0 && (
            <span className="flex items-center gap-0.5">
              <Clock className="size-2.5" />
              {formatDuration(totalMs)}
            </span>
          )}
        </div>
      </div>
 
      <div className="px-4 py-3 space-y-2">
        {nodes.map((node, i) => (
          <NodeCard
            key={`${node.node_id}-${i}`}
            node={node}
            index={i}
            total={nodes.length}
          />
        ))}
        <SourcesPanel
          nodes={nodes}
          citedSources={citedSources}
          evalOutcome={evalOutcome}
          evalScore={evalScore}
        />
      </div>
    </div>
  );
};
 
// ─── Exchange View ────────────────────────────────────────────────────────────
 
const ExchangeView: React.FC<{
  userMsg: ConversationMessage;
  assistantMsg: ConversationMessage;
  index: number;
  /** Where this turn lives, so the panel can hand the reader the actual
   *  conversation rather than a transcript of it. */
  conversation: Conversation;
}> = ({ userMsg, assistantMsg, index, conversation }) => {
  const [responseExpanded, setResponseExpanded] = useState(false);
  const hasTrace = assistantMsg.trace && assistantMsg.trace.length > 0;
  // This exact turn in the chat it happened in. A trace explains what the run
  // did; opening the message is how a reader carries on from it — reply,
  // re-run, or read what came next.
  const messageHref = chatMessageHref({
    agentId: conversation.agent_id,
    modelId: conversation.ai_model_id,
    conversationId: conversation.id,
    messageId: assistantMsg.id,
  });
 
  return (
    <div
      className={`space-y-3 ${index > 0 ? "pt-4 border-t border-gray-100 dark:border-gray-700" : ""}`}
    >
      {/* Turn label */}
      {index > 0 && (
        <p className="text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500">
          Turn {index + 1}
        </p>
      )}
 
      {/* User message */}
      <div className="flex items-start gap-3">
        <div className="size-6 rounded-full bg-blue-100 dark:bg-blue-900/40 border border-blue-200 dark:border-blue-800 flex items-center justify-center shrink-0 mt-0.5">
          <span className="text-[10px] font-bold text-blue-600 dark:text-blue-400">
            U
          </span>
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-1.5">
            <span className="text-xs font-semibold text-gray-600 dark:text-gray-400">
              User
            </span>
            {userMsg.sent_at && (
              <span className="text-[10px] text-gray-400 dark:text-gray-500">
                {formatRelative(userMsg.sent_at)}
              </span>
            )}
            {userMsg.token_count > 0 && (
              <span className="ml-auto text-[10px] text-gray-400 dark:text-gray-500 tabular-nums">
                {userMsg.token_count.toLocaleString()} tok
              </span>
            )}
          </div>
          <div className="bg-blue-50 dark:bg-blue-950/30 border border-blue-100 dark:border-blue-900/60 rounded-xl px-4 py-3 relative group/user">
            <p className="text-sm text-gray-800 dark:text-gray-200 whitespace-pre-wrap leading-relaxed">
              {userMsg.content}
            </p>
            <div className="absolute top-2.5 right-2.5 opacity-0 group-hover/user:opacity-100 transition-opacity">
              <CopyButton variant="bare" value={userMsg.content} />
            </div>
          </div>
        </div>
      </div>
 
      {/* Execution trace */}
      {hasTrace && (
        <TraceView
          trace={assistantMsg.trace as TraceEvent[]}
          citedSources={storedCitations(assistantMsg.meta)}
          evalOutcome={assistantMsg.meta?.eval_outcome}
          evalScore={assistantMsg.meta?.eval_score}
        />
      )}
 
      {/* Assistant message */}
      <div className="flex items-start gap-3">
        <div className="size-6 rounded-full bg-violet-100 dark:bg-violet-900/40 border border-violet-200 dark:border-violet-800 flex items-center justify-center shrink-0 mt-0.5">
          <Zap className="size-3 text-violet-600 dark:text-violet-400" />
        </div>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-1.5 flex-wrap">
            <span className="text-xs font-semibold text-gray-600 dark:text-gray-400">
              Assistant
            </span>
            {assistantMsg.meta?.model_name && (
              <ModelBadge
                modelName={assistantMsg.meta.model_name as string}
                provider={assistantMsg.meta.provider as string | undefined}
              />
            )}
            {typeof assistantMsg.meta?.agent_version === "number" && (
              <AgentVersionBadge
                agentId={assistantMsg.meta.agent_id as string | undefined}
                version={assistantMsg.meta.agent_version}
              />
            )}
            {assistantMsg.sent_at && (
              <span className="text-[10px] text-gray-400 dark:text-gray-500">
                {formatRelative(assistantMsg.sent_at)}
              </span>
            )}
            {assistantMsg.token_count > 0 && (
              <span className="text-[10px] text-gray-400 dark:text-gray-500 tabular-nums">
                {assistantMsg.token_count.toLocaleString()} tok
              </span>
            )}
            <div className="ml-auto flex items-center gap-2">
              {messageHref && (
                <Link
                  to={messageHref}
                  title="Open this message in the chat"
                  className="inline-flex items-center gap-1 text-[10px] text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-200 transition-colors"
                >
                  <MessageSquare className="size-3" />
                  Open in chat
                </Link>
              )}
              <button
                onClick={() => setResponseExpanded((v) => !v)}
                className="text-[10px] text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
              >
                {responseExpanded ? "Collapse" : "Expand"}
              </button>
            </div>
          </div>
          <div className="bg-violet-50 dark:bg-violet-950/20 border border-violet-100 dark:border-violet-900/50 rounded-xl px-4 py-3 relative group/resp">
            <pre
              className={`whitespace-pre-wrap break-words text-sm text-gray-800 dark:text-gray-200 font-sans leading-relaxed ${responseExpanded ? "" : "line-clamp-6"}`}
            >
              {assistantMsg.content}
            </pre>
            <div className="absolute top-2.5 right-2.5 opacity-0 group-hover/resp:opacity-100 transition-opacity">
              <CopyButton variant="bare" value={assistantMsg.content} />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
 
// ─── Run Detail Panel ─────────────────────────────────────────────────────────
 
const RunDetailPanel: React.FC<{
  run: Run;
  onClose: () => void;
}> = ({ run, onClose }) => {
  const { conversation, type, status, modelName, agentName } = run;
 
  const displayName =
    agentName ??
    modelName ??
    conversation.agent_id ??
    conversation.ai_model_id ??
    "—";
 
  const entityHref =
    type === "agent" && conversation.agent_id
      ? APP_ROUTES.USER.INFERENCE.AGENTS.id.replace(
          ROUTE_PARAMS.AGENT.id,
          encodeResourceId(conversation.agent_id),
        )
      : type === "model" && conversation.ai_model_id
        ? APP_ROUTES.USER.INFERENCE.MODELS.id.replace(
            ROUTE_PARAMS.MODEL.id,
            encodeResourceId(conversation.ai_model_id),
          )
        : null;
 
  // Build user/assistant exchange pairs
  const exchanges: {
    user: ConversationMessage;
    assistant: ConversationMessage;
  }[] = [];
  const msgs = conversation.messages;
  let i = 0;
  while (i < msgs.length) {
    if (
      msgs[i].role === "user" &&
      i + 1 < msgs.length &&
      msgs[i + 1].role === "assistant"
    ) {
      exchanges.push({ user: msgs[i], assistant: msgs[i + 1] });
      i += 2;
    } else E{
      i++;
    }
  }
 
  // Aggregate token usage from all nodes across all traces.
  // Split skill vs system so the summary doesn't inflate apparent model usage.
  const allNodes = exchanges.flatMap(({ assistant }) =>
    assistant.trace ? groupTraceByNode(assistant.trace) : [],
  );
  const skillNodes = allNodes.filter((n) => !n.is_system_node);
  const skillNodeTok = skillNodes.reduce(
    (s, n) => ({
      input: s.input + n.tokens.input,
      output: s.output + n.tokens.output,
    }),
    { input: 0, output: 0 },
  );
 
  const hasTotalTok =
    conversation.total_input_tokens > 0 || conversation.total_output_tokens > 0;
 
  return (
    <aside
      aria-label="Activity detail"
      className="flex flex-col h-full overflow-hidden rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shadow-sm"
    >
      {/* Header */}
      <div className="flex items-center justify-between gap-2 px-4 py-3 border-b border-gray-100 dark:border-gray-700 shrink-0">
        <div className="flex items-center gap-2 min-w-0">
          <Activity className="size-4 text-gray-500 dark:text-gray-400 shrink-0" />
          <span className="text-sm font-semibold text-gray-700 dark:text-gray-300 truncate">
            Run Detail
          </span>
          <StatusBadge scale={TRACE_STATUS} size="sm" status={status} />
        </div>
        <button
          onClick={onClose}
          aria-label="Close detail panel"
          className="p-1 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors shrink-0"
        >
          <X className="size-4" />
        </button>
      </div>
 
      <div className="flex-1 overflow-y-auto">
        {/* Summary grid */}
        <div className="px-4 py-4 border-b border-gray-100 dark:border-gray-700 space-y-4">
          <div className="grid grid-cols-2 gap-3">
            <MetaItem
              size="sm"
              icon={Hash}
              label="Run ID"
              value={
                <span
                  className="font-mono text-xs truncate block"
                  title={conversation.id}
                >
                  {conversation.id.slice(0, 16)}…
                </span>
              }
              action={<CopyButton variant="bare" value={conversation.id} />}
            />
            <MetaItem
              size="sm"
              icon={Clock}
              label="Created"
              value={formatTimestamp(conversation.created_at)}
            />
            <MetaItem
              size="sm"
              icon={type === "agent" ? Bot : BrainCog}
              label="Type"
              value={
                <div className="flex items-center gap-1.5">
                  <TypeBadge type={type} />
                  {entityHref ? (
                    <Link
                      to={entityHref}
                      className="text-xs text-gray-600 dark:text-gray-400 hover:underline truncate"
                    >
                      {displayName}
                    </Link>
                  ) : (
                    <span className="text-xs text-gray-600 dark:text-gray-400 truncate">
                      {displayName}
                    </span>
                  )}
                </div>
              }
            />
            <MetaItem
              size="sm"
              icon={MessageSquare}
              label="Turns"
              value={
                <span>
                  {exchanges.length} turn{exchanges.length !== 1 ? "s" : ""}
                  <span className="text-gray-400 dark:text-gray-500 font-normal ml-1">
                    ({msgs.length} msg{msgs.length !== 1 ? "s" : ""})
                  </span>
                </span>
              }
            />
          </div>
 
          {/* Token bar */}
          {hasTotalTok && (
            <div>
              <p className="text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500 mb-2 flex items-center gap-1">
                <Coins className="size-3" />
                Token Usage
                <span className="ml-auto font-normal normal-case">
                  {formatTokens(conversation.total_tokens)} total
                </span>
              </p>
              <TokenBar
                input={conversation.total_input_tokens}
                output={conversation.total_output_tokens}
              />
              {skillNodes.length > 0 &&
                skillNodeTok.input + skillNodeTok.output > 0 && (
                  <p className="text-[10px] text-gray-400 dark:text-gray-500 mt-1.5">
                    Skill nodes used{" "}
                    <span className="font-medium text-gray-600 dark:text-gray-400">
                      {formatTokens(skillNodeTok.input + skillNodeTok.output)}
                    </span>{" "}
                    across {skillNodes.length} node
                    {skillNodes.length !== 1 ? "s" : ""}
                    {allNodes.length > skillNodes.length && (
                      <span className="text-blue-400 dark:text-blue-500">
                        {" "}
                        (+{allNodes.length - skillNodes.length} system)
                      </span>
                    )}
                  </p>
                )}
            </div>
          )}
 
          {/* Actions */}
          <div className="flex items-center gap-2">
            <button
              onClick={() => {
                const data = JSON.stringify(conversation, null, 2);
                const blob = new Blob([data], { type: "application/json" });
                const url = URL.createObjectURL(blob);
                const a = document.createElement("a");
                a.href = url;
                a.download = `run-${conversation.id.slice(0, 8)}.json`;
                a.click();
                URL.revokeObjectURL(url);
              }}
              className="flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 px-2.5 py-1.5 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-500 transition-colors"
            >
              <Download className="size-3" />
              Export JSON
            </button>
            {entityHref && (
              <Link
                to={entityHref}
                className="flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 px-2.5 py-1.5 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-500 transition-colors"
              >
                <ChevronRight className="size-3" />
                View {type === "agent" ? "Agent" : "Model"}
              </Link>
            )}
          </div>
        </div>
 
        {/* Conversation */}
        {exchanges.length > 0 ? (
          <div className="px-4 py-4">
            <div className="flex items-center gap-2 mb-4">
              <MessageSquare className="size-3.5 text-gray-500 dark:text-gray-400" />
              <h4 className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide">
                Conversation
              </h4>
              <span className="ml-auto text-[10px] text-gray-400 dark:text-gray-500">
                {exchanges.length} turn{exchanges.length !== 1 ? "s" : ""}
              </span>
            </div>
            <div className="space-y-0">
              {exchanges.map((ex, idx) => (
                <ExchangeView
                  key={ex.user.id}
                  userMsg={ex.user}
                  assistantMsg={ex.assistant}
                  index={idx}
                  conversation={conversation}
                />
              ))}
            </div>
          </div>
        ) : (
          <div className="px-4 py-8 text-center">
            <p className="text-xs text-gray-400 dark:text-gray-500">
              No messages recorded for this run.
            </p>
          </div>
        )}
      </div>
    </aside>
  );
};
 
// ─── Run Row ──────────────────────────────────────────────────────────────────
 
const RunRow: React.FC<{
  run: Run;
  selected: boolean;
  onClick: () => void;
}> = ({ run, selected, onClick }) => {
  const { conversation, type, status } = run;
  const displayName =
    run.agentName ?? run.modelName ?? (type === "agent" ? "Agent" : "Model");
  const preview = getFirstUserMessage(conversation);
 
  // Quick trace summary
  const lastAssistant = [...conversation.messages]
    .reverse()
    .find((m) => m.role === "assistant");
  const traceNodes: NodeTraceData[] = lastAssistant?.trace
    ? groupTraceByNode(lastAssistant.trace)
    : [];
  const traceToolCount: number = traceNodes.reduce(
    (s, n) => s + n.tools.length,
    0,
  );
 
  return (
    <button
      onClick={onClick}
      className={`w-full text-left flex items-start gap-3 px-3 py-2.5 rounded-lg transition-colors group ${
        selected
          ? "bg-gray-100 dark:bg-gray-700/60"
          : "hover:bg-gray-50 dark:hover:bg-gray-700/30"
      }`}
    >
      <div className="flex items-center gap-1.5 pt-1 shrink-0">
        <StatusDot status={status} />
      </div>
      <div className="flex-1 min-w-0 space-y-1">
        <div className="flex items-center gap-1.5 flex-wrap">
          <TypeBadge type={type} />
          <span className="text-xs font-medium text-gray-800 dark:text-gray-200 truncate">
            {displayName}
          </span>
        </div>
        {preview ? (
          <p className="text-xs text-gray-500 dark:text-gray-400 truncate">
            {truncate(preview, 70)}
          </p>
        ) : (
          <p className="text-xs text-gray-300 dark:text-gray-600 italic">
            No input
          </p>
        )}
        <div className="flex items-center gap-2 text-[10px] text-gray-400 dark:text-gray-500">
          <span>{formatRelative(conversation.created_at)}</span>
          {conversation.total_tokens > 0 && (
            <>
              <span className="text-gray-200 dark:text-gray-700">·</span>
              <Coins className="size-2.5" />
              <span className="tabular-nums">
                {formatTokens(conversation.total_tokens)}
              </span>
            </>
          )}
          {traceNodes.length > 0 && (
            <>
              <span className="text-gray-200 dark:text-gray-700">·</span>
              <Layers className="size-2.5 text-violet-400" />
              <span>{traceNodes.length}</span>
            </>
          )}
          {traceToolCount > 0 && (
            <>
              <Hammer className="size-2.5 text-amber-400" />
              <span>{traceToolCount}</span>
            </>
          )}
        </div>
      </div>
      <ChevronRight
        className={`size-3.5 mt-1 shrink-0 transition-colors ${
          selected
            ? "text-gray-600 dark:text-gray-300"
            : "text-gray-300 dark:text-gray-600 group-hover:text-gray-500 dark:group-hover:text-gray-400"
        }`}
      />
    </button>
  );
};
 
// ─── Stats Strip ──────────────────────────────────────────────────────────────
 
const StatItem: React.FC<{
  label: string;
  value: React.ReactNode;
  loading: boolean;
}> = ({ label, value, loading }) => (
  <div className="flex items-baseline gap-1.5">
    {loading ? (
      <Skeleton className="w-8 h-4" />
    ) : (
      <span className="text-sm font-semibold tabular-nums text-gray-800 dark:text-gray-200">
        {value}
      </span>
    )}
    <span className="text-xs text-gray-400 dark:text-gray-500">{label}</span>
  </div>
);
 
const Divider: React.FC = () => (
  <span className="text-gray-200 dark:text-gray-600 select-none">·</span>
);
 
// ─── Resource Change Meta ─────────────────────────────────────────────────────
//
// One entry per HistoryEnum.ResourceType. Typed as a total Record so adding a
// resource type to svc-core and forgetting it here fails the build rather than
// rendering a nameless row.
 
const RESOURCE_TYPE_ICON: Record<ActivityResourceType, React.ElementType> = {
  agent: Bot,
  toolkit: Package,
  skillset: Layers,
  skill: Zap,
  tool: Wrench,
  mcp_server: Server,
  custom_worker: Cpu,
  knowledge: BookMarked,
  knowledge_repository: Library,
  rule: ShieldCheck,
  pipeline: Workflow,
  experiment: FlaskConical,
  test_suite: ClipboardCheck,
  simulation_world: Globe,
  dashboard: LayoutDashboard,
  project: FolderKanban,
  organisation: Building2,
  uploaded_file: FileText,
  swarm: Network,
};
 
const ACTION_META: Record<
  HistoryAction,
  {
    label: string;
    verb: string;
    Icon: React.ElementType;
    badge: string;
    dot: string;
  }
> = {
  created: {
    label: "Created",
    verb: "created",
    Icon: Plus,
    badge:
      "bg-emerald-50 dark:bg-emerald-950/40 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800",
    dot: "bg-emerald-500",
  },
  updated: {
    label: "Updated",
    verb: "updated",
    Icon: Pencil,
    badge:
      "bg-amber-50 dark:bg-amber-950/40 text-amber-700 dark:text-amber-300 border-amber-200 dark:border-amber-800",
    dot: "bg-amber-500",
  },
  deleted: {
    label: "Deleted",
    verb: "deleted",
    Icon: Trash2,
    badge:
      "bg-red-50 dark:bg-red-950/40 text-red-700 dark:text-red-300 border-red-200 dark:border-red-800",
    dot: "bg-red-500",
  },
};
 
const GENERATION_STATUS_META: Record<
  GenerationStatus,
  { label: string; badge: string; dot: string }
> = {
  running: {
    label: "Running",
    badge:
      "bg-sky-50 dark:bg-sky-950/40 text-sky-700 dark:text-sky-300 border-sky-200 dark:border-sky-800",
    dot: "bg-sky-500",
  },
  proposed: {
    label: "Proposed",
    badge:
      "bg-amber-50 dark:bg-amber-950/40 text-amber-700 dark:text-amber-300 border-amber-200 dark:border-amber-800",
    dot: "bg-amber-500",
  },
  applied: {
    label: "Applied",
    badge:
      "bg-emerald-50 dark:bg-emerald-950/40 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800",
    dot: "bg-emerald-500",
  },
  failed: {
    label: "Failed",
    badge:
      "bg-red-50 dark:bg-red-950/40 text-red-700 dark:text-red-300 border-red-200 dark:border-red-800",
    dot: "bg-red-500",
  },
};
 
/**
 * Where an activity event's resource lives, or null when it has nowhere to go.
 *
 * A `deleted` event never links anywhere — the row it points at is gone, and
 * a 404 is a worse answer than no link. The type-to-route table itself is
 * shared with the generative-provenance view (`routes/resourceHref`), which
 * is handed the same soft `(resource_type, resource_id)` pairs.
 */
function eventHref(
  type: ActivityResourceType,
  id: string,
  action: HistoryAction,
): string | null {
  if (action === "deleted") return null;
  return resourceHref(type, id);
}
 
/** `system_prompt` → `System prompt`, for field chips and diff labels. */
function humaniseField(field: string): string {
  return field.replace(/_/g, " ").replace(/^\w/, (c) => c.toUpperCase());
}
 
function actorLabel(event: {
  actor_name?: string | null;
  actor_email?: string | null;
}): string {
  return event.actor_name || event.actor_email || "Unknown user";
}
 
// ─── Panel Shell ──────────────────────────────────────────────────────────────
 
/**
 * The frame every detail panel shares — header with icon, title, status badge
 * and a close button, over a scrolling body. Extracted so the four kinds of
 * detail stay visually identical while differing only in content.
 */
const PanelShell: React.FC<{
  icon: React.ReactNode;
  title: string;
  badge?: React.ReactNode;
  onClose: () => void;
  children: React.ReactNode;
}> = ({ icon, title, badge, onClose, children }) => (
  <aside
    aria-label="Activity detail"
    className="flex flex-col h-full overflow-hidden rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shadow-sm"
  >
    <div className="flex items-center justify-between gap-2 px-4 py-3 border-b border-gray-100 dark:border-gray-700 shrink-0">
      <div className="flex items-center gap-2 min-w-0">
        {icon}
        <span className="text-sm font-semibold text-gray-700 dark:text-gray-300 truncate">
          {title}
        </span>
        {badge}
      </div>
      <button
        onClick={onClose}
        aria-label="Close detail panel"
        className="p-1 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors shrink-0"
      >
        <X className="size-4" />
      </button>
    </div>
    <div className="flex-1 overflow-y-auto">{children}</div>
  </aside>
);
 
/** The row frame every feed row shares, so a mixed stream reads as one list. */
const FeedRow: React.FC<{
  selected: boolean;
  onClick: () => void;
  dot: React.ReactNode;
  children: React.ReactNode;
}> = ({ selected, onClick, dot, children }) => (
  <button
    onClick={onClick}
    className={`w-full text-left flex items-start gap-3 px-3 py-2.5 rounded-lg transition-colors group ${
      selected
        ? "bg-gray-100 dark:bg-gray-700/60"
        : "hover:bg-gray-50 dark:hover:bg-gray-700/30"
    }`}
  >
    <div className="flex items-center gap-1.5 pt-1 shrink-0">{dot}</div>
    <div className="flex-1 min-w-0 space-y-1">{children}</div>
    <ChevronRight
      className={`size-3.5 mt-1 shrink-0 transition-colors ${
        selected
          ? "text-gray-600 dark:text-gray-300"
          : "text-gray-300 dark:text-gray-600 group-hover:text-gray-500 dark:group-hover:text-gray-400"
      }`}
    />
  </button>
);
 
// ─── Resource Change Row ──────────────────────────────────────────────────────
 
const ResourceChangeRow: React.FC<{
  event: ActivityEvent;
  selected: boolean;
  onClick: () => void;
}> = ({ event, selected, onClick }) => {
  const action = ACTION_META[event.action];
  const TypeIcon = RESOURCE_TYPE_ICON[event.resource_type];
  const typeLabel = RESOURCE_TYPE_LABELS[event.resource_type];
  const name = event.resource_name ?? typeLabel;
 
  return (
    <FeedRow
      selected={selected}
      onClick={onClick}
      dot={<span className={`size-2 rounded-full shrink-0 ${action.dot}`} />}
    >
      <div className="flex items-center gap-1.5 flex-wrap">
        <span
          className={`inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded-full border ${action.badge}`}
        >
          <action.Icon className="size-2.5" />
          {action.label}
        </span>
        <span className="inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded-full bg-gray-50 dark:bg-gray-800 text-gray-600 dark:text-gray-300 border border-gray-200 dark:border-gray-700">
          <TypeIcon className="size-2.5" />
          {typeLabel}
        </span>
        {event.is_ai_generated && <AIGeneratedBadge compact />}
      </div>
      <p className="text-xs font-medium text-gray-800 dark:text-gray-200 truncate">
        {name}
      </p>
      {event.changed_fields.length > 0 && (
        <p className="text-xs text-gray-500 dark:text-gray-400 truncate">
          {event.changed_fields.map(humaniseField).join(", ")}
        </p>
      )}
      <div className="flex items-center gap-2 text-[10px] text-gray-400 dark:text-gray-500">
        <span>{event.created_at ? formatRelative(event.created_at) : "—"}</span>
        <span className="text-gray-200 dark:text-gray-700">·</span>
        <span>v{event.version_number}</span>
        <span className="text-gray-200 dark:text-gray-700">·</span>
        <UserIcon className="size-2.5" />
        <span className="truncate">{actorLabel(event)}</span>
      </div>
    </FeedRow>
  );
};
 
// ─── Resource Change Panel ────────────────────────────────────────────────────
 
/** Added/removed grant ids per child collection, when a version changed them. */
const ChildrenDiff: React.FC<{
  childrenDiff: Record<string, { added: string[]; removed: string[] }>;
}> = ({ childrenDiff }) => {
  const entries = Object.entries(childrenDiff).filter(
    ([, v]) => v.added.length > 0 || v.removed.length > 0,
  );
  Eif (entries.length === 0) return null;
  return (
    <div className="space-y-2">
      <p className="text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500 flex items-center gap-1">
        <Boxes className="size-3" />
        Grants changed
      </p>
      {entries.map(([key, value]) => (
        <div key={key} className="text-xs">
          <p className="text-gray-600 dark:text-gray-300 font-medium mb-1">
            {humaniseField(key)}
          </p>
          <div className="space-y-0.5 font-mono text-[11px]">
            {value.added.map((id) => (
              <p
                key={`a-${id}`}
                className="text-emerald-600 dark:text-emerald-400"
              >
                + {id}
              </p>
            ))}
            {value.removed.map((id) => (
              <p key={`r-${id}`} className="text-red-600 dark:text-red-400">
                − {id}
              </p>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
};
 
const ResourceChangePanel: React.FC<{
  event: ActivityEvent;
  onClose: () => void;
}> = ({ event, onClose }) => {
  const { getApiHandler } = useApiHandler();
  const action = ACTION_META[event.action];
  const TypeIcon = RESOURCE_TYPE_ICON[event.resource_type];
  const typeLabel = RESOURCE_TYPE_LABELS[event.resource_type];
  const href = eventHref(event.resource_type, event.resource_id, event.action);
 
  // The diff is fetched rather than carried on the row: a feed of a few
  // hundred events should not ship every snapshot to render a list.
  const { data, isLoading } = useQuery({
    queryKey: [QUERY_KEYS.GET.ACTIVITY_EVENT, event.id],
    queryFn: () => getApiHandler().activity_router.get(event.id),
    staleTime: 5 * 60_000,
  });
  const detail: ActivityEventDetail | null = data ?? null;
 
  const fieldLabels = useMemo(() => {
    const labels: Record<string, string> = {};
    (detail?.diff?.fields ?? []).forEach((f) => {
      labels[f.field] = humaniseField(f.field);
    });
    return labels;
  }, [detail]);
 
  return (
    <PanelShell
      icon={
        <TypeIcon className="size-4 text-gray-500 dark:text-gray-400 shrink-0" />
      }
      title={event.resource_name ?? typeLabel}
      badge={
        <span
          className={`inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 rounded-full border ${action.badge}`}
        >
          <action.Icon className="size-2.5" />
          {action.label}
        </span>
      }
      onClose={onClose}
    >
      <div className="px-4 py-4 border-b border-gray-100 dark:border-gray-700">
        <div className="grid grid-cols-2 gap-3">
          <MetaItem
            size="sm"
            icon={TypeIcon}
            label="Resource"
            value={<span className="truncate block">{typeLabel}</span>}
          />
          <MetaItem
            size="sm"
            icon={Hash}
            label="Resource ID"
            value={
              <span
                className="font-mono text-xs truncate block"
                title={event.resource_id}
              >
                {event.resource_id.slice(0, 16)}…
              </span>
            }
            action={<CopyButton variant="bare" value={event.resource_id} />}
          />
          <MetaItem
            size="sm"
            icon={GitBranch}
            label="Version"
            value={`v${event.version_number}`}
          />
          <MetaItem
            size="sm"
            icon={Clock}
            label="When"
            value={event.created_at ? formatTimestamp(event.created_at) : "—"}
          />
          <MetaItem
            size="sm"
            icon={UserIcon}
            label="Actor"
            value={actorLabel(event)}
          />
          <MetaItem
            size="sm"
            icon={Sparkles}
            label="Origin"
            value={event.is_ai_generated ? "AI generated" : "Hand-built"}
          />
        </div>
 
        {href && (
          <Link
            to={href}
            className="mt-3 inline-flex items-center gap-1.5 text-xs font-medium text-gray-700 dark:text-gray-300 hover:underline"
          >
            <ExternalLink className="size-3" />
            Open {typeLabel.toLowerCase()}
          </Link>
        )}
        {event.action === "deleted" && (
          <p className="mt-3 text-[11px] text-gray-400 dark:text-gray-500 italic">
            This resource has been deleted. Its history outlives it — the
            snapshot below is the last state it held.
          </p>
        )}
      </div>
 
      {event.generation && (
        <div className="px-4 py-3 border-b border-gray-100 dark:border-gray-700">
          <p className="text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500 mb-1">
            Why this exists
          </p>
          <GenerationDetails
            generationId={event.generation.id}
            summary={event.generation}
            variant="full"
            excludeResourceId={event.resource_id}
          />
        </div>
      )}
 
      <div className="px-4 py-4 space-y-4">
        <div>
          <p className="text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500 mb-2 flex items-center gap-1">
            <FileStack className="size-3" />
            {detail?.diff?.from_version != null
              ? `Changes from v${detail.diff.from_version} to v${detail.diff.to_version}`
              : "Initial state"}
          </p>
          {isLoading ? (
            <div className="space-y-2">
              {Array.from({ length: 3 }).map((_, i) => (
                <Skeleton key={i} className="h-12 w-full" />
              ))}
            </div>
          ) : detail?.diff ? (
            <DiffViewer
              fields={detail.diff.fields}
              fieldLabels={fieldLabels}
              hiddenFields={DEFAULT_HIDDEN_HISTORY_FIELDS}
              emptyMessage="No field-level changes were recorded for this version."
            />
          ) : (
            <p className="text-xs text-gray-400 dark:text-gray-500 italic">
              Could not load the diff for this event.
            </p>
          )}
        </div>
 
        {detail?.diff?.children_diff && (
          <ChildrenDiff childrenDiff={detail.diff.children_diff} />
        )}
      </div>
    </PanelShell>
  );
};
 
// ─── Generative Invocation Row & Panel ────────────────────────────────────────
 
const GenerationRow: React.FC<{
  generation: GenerationRun;
  selected: boolean;
  onClick: () => void;
}> = ({ generation, selected, onClick }) => {
  const meta = GENERATION_STATUS_META[generation.status];
  const flowLabel = GENERATION_FLOW_LABELS[generation.flow] ?? generation.flow;
  const prompt = Object.values(generation.arguments ?? {}).find(
    (v): v is string => typeof v === "string" && v.trim().length > 0,
  );
 
  return (
    <FeedRow
      selected={selected}
      onClick={onClick}
      dot={<span className={`size-2 rounded-full shrink-0 ${meta.dot}`} />}
    >
      <div className="flex items-center gap-1.5 flex-wrap">
        <span className="inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded-full bg-violet-50 dark:bg-violet-950/40 text-violet-700 dark:text-violet-300 border border-violet-200 dark:border-violet-800">
          <Sparkles className="size-2.5" />
          {flowLabel}
        </span>
        <span
          className={`inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded-full border ${meta.badge}`}
        >
          {meta.label}
        </span>
      </div>
      {prompt ? (
        <p className="text-xs text-gray-500 dark:text-gray-400 truncate">
          {truncate(prompt, 70)}
        </p>
      ) : (
        <p className="text-xs text-gray-300 dark:text-gray-600 italic">
          No arguments recorded
        </p>
      )}
      <div className="flex items-center gap-2 text-[10px] text-gray-400 dark:text-gray-500">
        <span>
          {generation.created_at ? formatRelative(generation.created_at) : "—"}
        </span>
        {generation.model_name && (
          <>
            <span className="text-gray-200 dark:text-gray-700">·</span>
            <BrainCog className="size-2.5" />
            <span className="truncate">{generation.model_name}</span>
          </>
        )}
        {(generation.warnings?.length ?? 0) > 0 && (
          <>
            <span className="text-gray-200 dark:text-gray-700">·</span>
            <AlertTriangle className="size-2.5 text-amber-400" />
            <span>{generation.warnings?.length}</span>
          </>
        )}
      </div>
    </FeedRow>
  );
};
 
const GenerationRunPanel: React.FC<{
  generation: GenerationRun;
  onClose: () => void;
  onOpenResource: (resourceType: ActivityResourceType, id: string) => void;
  /** Whether this run's output still has a row in the loaded feed. A resource
   *  created outside the page's window has nothing to jump to. */
  canOpenResource: (resourceType: ActivityResourceType, id: string) => boolean;
}> = ({ generation, onClose, onOpenResource, canOpenResource }) => {
  const { getApiHandler } = useApiHandler();
  const meta = GENERATION_STATUS_META[generation.status];
  const flowLabel = GENERATION_FLOW_LABELS[generation.flow] ?? generation.flow;
 
  // `produced` is only on the detail read — the list endpoint deliberately
  // does not walk the version trail for every row.
  const { data, isLoading } = useQuery({
    queryKey: [QUERY_KEYS.GET.GENERATION, generation.id],
    queryFn: () => getApiHandler().generation_router.get(generation.id),
    staleTime: 5 * 60_000,
  });
  const detail: GenerationRun | null = data ?? null;
  const produced = detail?.produced ?? [];
  const args = Object.entries(detail?.arguments ?? generation.arguments ?? {});
  const warnings = detail?.warnings ?? generation.warnings ?? [];
  const error = detail?.error ?? generation.error;
 
  return (
    <PanelShell
      icon={<Sparkles className="size-4 text-violet-500 shrink-0" />}
      title={flowLabel}
      badge={
        <span
          className={`inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 rounded-full border ${meta.badge}`}
        >
          {meta.label}
        </span>
      }
      onClose={onClose}
    >
      <div className="px-4 py-4 border-b border-gray-100 dark:border-gray-700 grid grid-cols-2 gap-3">
        <MetaItem
          size="sm"
          icon={Hash}
          label="Generation ID"
          value={
            <span
              className="font-mono text-xs truncate block"
              title={generation.id}
            >
              {generation.id.slice(0, 16)}…
            </span>
          }
          action={<CopyButton variant="bare" value={generation.id} />}
        />
        <MetaItem
          size="sm"
          icon={Clock}
          label="Invoked"
          value={
            generation.created_at ? formatTimestamp(generation.created_at) : "—"
          }
        />
        <MetaItem
          size="sm"
          icon={BrainCog}
          label="Model"
          value={
            generation.model_name
              ? withMaker(generation.model_name, generation.provider)
              : "—"
          }
        />
        <MetaItem
          size="sm"
          icon={Check}
          label="Applied"
          value={
            generation.applied_at
              ? formatTimestamp(generation.applied_at)
              : "Not applied"
          }
        />
      </div>
 
      <div className="px-4 py-4 space-y-4">
        <div>
          <p className="text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500 mb-2 flex items-center gap-1">
            <Settings2 className="size-3" />
            Request arguments
          </p>
          {args.length > 0 ? (
            <dl className="space-y-2">
              {args.map(([key, value]) => (
                <div key={key}>
                  <dt className="text-[10px] uppercase tracking-wide text-gray-400 dark:text-gray-500">
                    {humaniseField(key)}
                  </dt>
                  <dd className="text-xs text-gray-700 dark:text-gray-300 whitespace-pre-wrap break-words">
                    {typeof value === "string"
                      ? value
                      : JSON.stringify(value, null, 2)}
                  </dd>
                </div>
              ))}
            </dl>
          ) : (
            <p className="text-xs text-gray-400 dark:text-gray-500 italic">
              No arguments recorded. Arguments are redacted before storage, so a
              request that carried only credentials records none.
            </p>
          )}
        </div>
 
        {warnings.length > 0 && (
          <div>
            <p className="text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500 mb-2 flex items-center gap-1">
              <AlertTriangle className="size-3 text-amber-500" />
              Warnings
            </p>
            <ul className="space-y-1">
              {warnings.map((warning, i) => (
                <li
                  key={i}
                  className="flex items-start gap-1.5 text-xs text-amber-700 dark:text-amber-400"
                >
                  <AlertTriangle className="size-3 mt-0.5 shrink-0" />
                  <span>{warning}</span>
                </li>
              ))}
            </ul>
          </div>
        )}
 
        {error && (
          <div className="flex items-start gap-1.5 px-3 py-2 rounded-lg bg-red-50 dark:bg-red-950/40 border border-red-200 dark:border-red-800 text-xs text-red-700 dark:text-red-300">
            <AlertCircle className="size-3.5 shrink-0 mt-0.5" />
            <span className="break-words">{error}</span>
          </div>
        )}
 
        <div>
          <p className="text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500 mb-2 flex items-center gap-1">
            <Boxes className="size-3" />
            What came of it
          </p>
          {isLoading ? (
            <div className="space-y-1">
              {Array.from({ length: 3 }).map((_, i) => (
                <Skeleton key={i} className="h-8 w-full" />
              ))}
            </div>
          ) : produced.length > 0 ? (
            <ul className="space-y-1">
              {produced.map((resource) => {
                const type = resource.resource_type as ActivityResourceType;
                const Icon = RESOURCE_TYPE_ICON[type] ?? Boxes;
                const openable = canOpenResource(type, resource.resource_id);
                const body = (
                  <>
                    <Icon className="size-3.5 text-gray-400 shrink-0" />
                    <span className="text-xs text-gray-700 dark:text-gray-300 truncate">
                      {resource.name ?? "Unnamed"}
                    </span>
                    <span className="ml-auto text-[10px] text-gray-400 dark:text-gray-500 shrink-0">
                      {RESOURCE_TYPE_LABELS[type] ?? resource.resource_type}
                    </span>
                  </>
                );
                return (
                  <li key={`${resource.resource_type}-${resource.resource_id}`}>
                    {openable ? (
                      <button
                        type="button"
                        onClick={() =>
                          onOpenResource(type, resource.resource_id)
                        }
                        className="w-full flex items-center gap-2 px-2.5 py-1.5 rounded-lg text-left hover:bg-gray-50 dark:hover:bg-gray-700/40 transition-colors"
                      >
                        {body}
                      </button>
                    ) : (
                      <div
                        title="No matching event in the current view"
                        className="w-full flex items-center gap-2 px-2.5 py-1.5 rounded-lg"
                      >
                        {body}
                      </div>
                    )}
                  </li>
                );
              })}
            </ul>
          ) : (
            <p className="text-xs text-gray-400 dark:text-gray-500 italic">
              {generation.status === "running"
                ? "Still working — nothing is created until the proposal is accepted."
                : generation.status === "proposed"
                ? "Proposed but never accepted, so nothing was created."
                : generation.status === "failed"
                  ? "This invocation failed before it produced anything."
                  : "Nothing was recorded as created by this invocation."}
            </p>
          )}
        </div>
      </div>
    </PanelShell>
  );
};
 
// ─── LLM Invocations ──────────────────────────────────────────────────────────
//
// Flat trace of every recorded LLM call — conversation executions and
// platform flows (e.g. generative agent setup) alike.
 
const PURPOSE_META: Record<
  string,
  { label: string; icon: React.ReactNode; badge: string }
> = {
  model: {
    label: "Model chat",
    icon: <MessageSquare className="size-3" />,
    badge:
      "bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 border-gray-200 dark:border-gray-600",
  },
  agent: {
    label: "Agent run",
    icon: <Bot className="size-3" />,
    badge:
      "bg-emerald-50 dark:bg-emerald-950/40 text-emerald-700 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800",
  },
  skill: {
    label: "Skill",
    icon: <Zap className="size-3" />,
    badge:
      "bg-violet-50 dark:bg-violet-950/40 text-violet-700 dark:text-violet-300 border-violet-200 dark:border-violet-800",
  },
  worker: {
    label: "Worker",
    icon: <Cpu className="size-3" />,
    badge:
      "bg-blue-50 dark:bg-blue-950/40 text-blue-700 dark:text-blue-300 border-blue-200 dark:border-blue-800",
  },
  graph: {
    label: "Graph",
    icon: <Network className="size-3" />,
    badge:
      "bg-amber-50 dark:bg-amber-950/40 text-amber-700 dark:text-amber-300 border-amber-200 dark:border-amber-800",
  },
  pipeline: {
    label: "Pipeline",
    icon: <Workflow className="size-3" />,
    badge:
      "bg-cyan-50 dark:bg-cyan-950/40 text-cyan-700 dark:text-cyan-300 border-cyan-200 dark:border-cyan-800",
  },
  agent_generation: {
    label: "Agent generation",
    icon: <Sparkles className="size-3" />,
    badge:
      "bg-violet-100 dark:bg-violet-900/50 text-violet-700 dark:text-violet-300 border-violet-300 dark:border-violet-700",
  },
  // Evaluation cells used to arrive as "model" / "agent" — indistinguishable
  // from a chat — and under a system user, so they were in nobody's feed.
  evaluation: {
    label: "Evaluation",
    icon: <FlaskConical className="size-3" />,
    badge:
      "bg-sky-50 dark:bg-sky-950/40 text-sky-700 dark:text-sky-300 border-sky-200 dark:border-sky-800",
  },
  evaluation_judge: {
    label: "Evaluation judge",
    icon: <ClipboardCheck className="size-3" />,
    badge:
      "bg-sky-50 dark:bg-sky-950/40 text-sky-700 dark:text-sky-300 border-sky-200 dark:border-sky-800",
  },
  // Dashboard tiles borrow the evaluation execution path, and used to arrive
  // labelled "evaluation" because of it.
  dashboard_widget: {
    label: "Dashboard widget",
    icon: <LayoutDashboard className="size-3" />,
    badge:
      "bg-teal-50 dark:bg-teal-950/40 text-teal-700 dark:text-teal-300 border-teal-200 dark:border-teal-800",
  },
  dashboard_generation: {
    label: "Dashboard generation",
    icon: <Sparkles className="size-3" />,
    badge:
      "bg-violet-100 dark:bg-violet-900/50 text-violet-700 dark:text-violet-300 border-violet-300 dark:border-violet-700",
  },
  knowledge_indexing: {
    label: "Knowledge indexing",
    icon: <Database className="size-3" />,
    badge:
      "bg-teal-50 dark:bg-teal-950/40 text-teal-700 dark:text-teal-300 border-teal-200 dark:border-teal-800",
  },
  knowledge_retrieval: {
    label: "Knowledge search",
    icon: <Search className="size-3" />,
    badge:
      "bg-teal-50 dark:bg-teal-950/40 text-teal-700 dark:text-teal-300 border-teal-200 dark:border-teal-800",
  },
  simulation: {
    label: "Simulation",
    icon: <Boxes className="size-3" />,
    badge:
      "bg-amber-50 dark:bg-amber-950/40 text-amber-700 dark:text-amber-300 border-amber-200 dark:border-amber-800",
  },
  // Model calls an endpoint did not trace itself, recorded by svc-ai's
  // catch-all under the endpoint that made them.
  untraced: {
    label: "Untraced call",
    icon: <AlertTriangle className="size-3" />,
    badge:
      "bg-amber-50 dark:bg-amber-950/40 text-amber-700 dark:text-amber-300 border-amber-200 dark:border-amber-800",
  },
};
 
const purposeMeta = (purpose: string | null) =>
  PURPOSE_META[purpose ?? ""] ?? {
    label: purpose ?? "Unknown",
    icon: <Activity className="size-3" />,
    badge:
      "bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 border-gray-200 dark:border-gray-600",
  };
 
const InvocationRow: React.FC<{
  invocation: LLMInvocationRecord;
  selected: boolean;
  onClick: () => void;
}> = ({ invocation, selected, onClick }) => {
  const meta = purposeMeta(invocation.purpose);
  const isError = invocation.status === "error";
 
  return (
    <FeedRow
      selected={selected}
      onClick={onClick}
      dot={
        <span
          className={`size-2 rounded-full shrink-0 ${
            isError ? "bg-red-500" : "bg-emerald-500"
          }`}
        />
      }
    >
      <div className="flex items-center gap-1.5 flex-wrap">
        <span
          className={`inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded-full border ${meta.badge}`}
        >
          {meta.icon}
          {meta.label}
        </span>
        <span className="text-xs font-medium text-gray-800 dark:text-gray-200 truncate">
          {invocationModelLabel(invocation)}
        </span>
      </div>
      {invocation.output_preview ? (
        <p className="text-xs text-gray-500 dark:text-gray-400 truncate">
          {truncate(invocation.output_preview, 70)}
        </p>
      ) : isError && invocation.error_detail ? (
        <p className="text-xs text-red-500 dark:text-red-400 truncate">
          {truncate(invocation.error_detail, 70)}
        </p>
      ) : null}
      <div className="flex items-center gap-2 text-[10px] text-gray-400 dark:text-gray-500">
        <span>
          {invocation.created_at ? formatRelative(invocation.created_at) : "—"}
        </span>
        {invocation.total_tokens > 0 && (
          <>
            <span className="text-gray-200 dark:text-gray-700">·</span>
            <Coins className="size-2.5" />
            <span className="tabular-nums">
              {formatTokens(invocation.total_tokens)}
            </span>
          </>
        )}
        {invocation.latency_ms != null && (
          <>
            <span className="text-gray-200 dark:text-gray-700">·</span>
            <Clock className="size-2.5" />
            <span className="tabular-nums">
              {formatDuration(invocation.latency_ms)}
            </span>
          </>
        )}
        {invocation.estimated_cost_usd != null && (
          <>
            <span className="text-gray-200 dark:text-gray-700">·</span>
            <span className="tabular-nums">
              {formatUsd(invocation.estimated_cost_usd)}
            </span>
          </>
        )}
      </div>
    </FeedRow>
  );
};
 
/**
 * Where an LLM call came from.
 *
 * A dashboard tile's call links to its board, a skill run's to the run. An evaluation cell links to
 * the evaluation or dataset that ran it; a Quick try call
 * says so, because there is nothing saved to open. Rendered from the
 * reference svc-core stamps on the call, so a call with none shows nothing.
 */
const InvocationReferenceLink: React.FC<{
  invocation: LLMInvocationRecord;
}> = ({ invocation }) => {
  const reference = invocationReference(invocation);
  if (!reference) return null;
  Iif (reference.skill_id && reference.skill_run_id) {
    return (
      <Link
        to={skillRunHref(reference.skill_id, reference.skill_run_id)}
        className="inline-flex items-center gap-1.5 text-xs font-medium text-gray-700 dark:text-gray-300 hover:underline"
      >
        <Zap className="size-3" />
        Open skill run
      </Link>
    );
  }
  const board = reference.dashboard_id
    ? resourceHref("dashboard", reference.dashboard_id)
    : null;
  if (board) {
    return (
      <Link
        to={board}
        className="inline-flex items-center gap-1.5 text-xs font-medium text-gray-700 dark:text-gray-300 hover:underline"
      >
        <LayoutDashboard className="size-3" />
        Open dashboard
      </Link>
    );
  }
  const owner = reference.experiment_id
    ? {
        type: "experiment" as const,
        id: reference.experiment_id,
        label: "Open evaluation",
      }
    : reference.dataset_id
      ? {
          type: "test_suite" as const,
          id: reference.dataset_id,
          label: "Open dataset",
        }
      : null;
  const href = owner ? resourceHref(owner.type, owner.id) : null;
  if (owner && href) {
    return (
      <Link
        to={href}
        className="inline-flex items-center gap-1.5 text-xs font-medium text-gray-700 dark:text-gray-300 hover:underline"
      >
        <FlaskConical className="size-3" />
        {owner.label}
      </Link>
    );
  }
  Eif (reference.source === "quick_try") {
    return (
      <p className="text-xs text-gray-500 dark:text-gray-400">
        Made from Quick try — nothing was saved.
      </p>
    );
  }
  return null;
};
 
/**
 * Every model call an invocation made, in order — which node called which
 * model, and what each cost. A failed call stays on the list against the
 * model it went to, so a retry or fallback reads as what it was.
 */
const InvocationCallList: React.FC<{ calls: LLMInvocationCall[] }> = ({
  calls,
}) => {
  Eif (calls.length === 0) return null;
  return (
    <div>
      <p className="text-[10px] font-semibold uppercase tracking-wide text-gray-400 dark:text-gray-500 flex items-center gap-1 mb-1.5">
        <Cpu className="size-3" />
        Model calls ({calls.length})
      </p>
      <ol className="space-y-1">
        {calls.map((call) => {
          const failed = call.status !== "success";
          return (
            <li
              key={call.sequence}
              className={`rounded-lg border px-2.5 py-1.5 text-xs ${
                failed
                  ? "border-red-200 dark:border-red-800/60 bg-red-50 dark:bg-red-950/20"
                  : "border-gray-100 dark:border-gray-700 bg-gray-50 dark:bg-gray-700/40"
              }`}
            >
              <div className="flex items-center gap-1.5 min-w-0">
                {call.node && (
                  <span className="shrink-0 text-[10px] font-medium px-1.5 py-0.5 rounded-full bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-300">
                    {systemNodeLabel(call.node)}
                  </span>
                )}
                <span
                  className="font-medium text-gray-800 dark:text-gray-200 truncate"
                  title={withMaker(call.model_name, call.provider)}
                >
                  {modelLabel(call.model_name, call.model_display_name)}
                </span>
                <span className="text-[10px] text-gray-400 dark:text-gray-500 shrink-0">
                  {makerLabel(call.provider, call.model_name)}
                  {call.kind !== "chat" && ` · ${call.kind}`}
                </span>
              </div>
              <div className="flex items-center gap-2 mt-0.5 text-[10px] text-gray-500 dark:text-gray-400 tabular-nums">
                <span>
                  ↑ {formatTokens(call.prompt_tokens)}
                  {(call.cache_read_tokens ?? 0) > 0 &&
                    ` (${formatTokens(call.cache_read_tokens ?? 0)} cached)`}
                  {(call.cache_write_tokens ?? 0) > 0 &&
                    ` (${formatTokens(call.cache_write_tokens ?? 0)} written to cache)`}{" "}
                  ↓ {formatTokens(call.completion_tokens)}
                </span>
                {call.latency_ms != null && (
                  <span>{formatDuration(call.latency_ms)}</span>
                )}
                <span
                  title={
                    call.pricing?.unpriced_reason ??
                    (call.pricing?.long_context
                      ? "Long-context rates applied to the whole call"
                      : undefined)
                  }
                >
                  {call.estimated_cost_usd != null
                    ? formatUsd(call.estimated_cost_usd)
                    : failed
                      ? "—"
                      : "unpriced"}
                </span>
              </div>
              {failed && call.error_detail && (
                <p className="mt-0.5 text-[10px] text-red-600 dark:text-red-400 break-words">
                  {call.error_detail}
                </p>
              )}
            </li>
          );
        })}
      </ol>
    </div>
  );
};
 
const InvocationDetailPanel: React.FC<{
  invocation: LLMInvocationRecord;
  onClose: () => void;
  onOpenRun: ((conversationId: string) => void) | null;
}> = ({ invocation, onClose, onOpenRun }) => {
  const meta = purposeMeta(invocation.purpose);
  const isError = invocation.status === "error";
 
  return (
    <PanelShell
      icon={
        <Zap className="size-4 text-gray-500 dark:text-gray-400 shrink-0" />
      }
      title={invocationModelLabel(invocation)}
      badge={
        <span
          className={`inline-flex items-center gap-1 text-[10px] font-semibold px-1.5 py-0.5 rounded-full border ${meta.badge}`}
        >
          {meta.icon}
          {meta.label}
        </span>
      }
      onClose={onClose}
    >
      <div className="px-4 py-4 border-b border-gray-100 dark:border-gray-700 space-y-4">
        <div className="grid grid-cols-2 gap-3">
          <MetaItem
            size="sm"
            icon={Hash}
            label="Invocation ID"
            value={
              <span
                className="font-mono text-xs truncate block"
                title={invocation.id}
              >
                {invocation.id.slice(0, 16)}…
              </span>
            }
            action={<CopyButton variant="bare" value={invocation.id} />}
          />
          <MetaItem
            size="sm"
            icon={Clock}
            label="When"
            value={
              invocation.created_at
                ? formatTimestamp(invocation.created_at)
                : "—"
            }
          />
          <MetaItem
            size="sm"
            icon={BrainCog}
            label={invocation.model_name ? "Model" : "Models"}
            value={
              invocation.model_name
                ? withMaker(invocation.model_name, invocation.provider)
                : calledModels(invocation)
                    .map((m) => m.label)
                    .join(", ") || invocationModelLabel(invocation)
            }
          />
          <MetaItem
            size="sm"
            icon={isError ? AlertCircle : Check}
            label="Status"
            value={<span className="capitalize">{invocation.status}</span>}
          />
          <MetaItem
            size="sm"
            icon={Clock}
            label="Latency"
            value={
              invocation.latency_ms != null
                ? formatDuration(invocation.latency_ms)
                : "—"
            }
          />
          <MetaItem
            size="sm"
            icon={Coins}
            label="Cost"
            value={
              describeCost({ cost_usd: invocation.estimated_cost_usd }).text
            }
          />
        </div>
 
        <TokenBar
          input={invocation.prompt_tokens}
          output={invocation.completion_tokens}
        />
 
        {invocation.conversation_id && onOpenRun && (
          <button
            type="button"
            onClick={() => onOpenRun(invocation.conversation_id!)}
            className="inline-flex items-center gap-1.5 text-xs font-medium text-gray-700 dark:text-gray-300 hover:underline"
          >
            <MessageSquare className="size-3" />
            View conversation run
          </button>
        )}
 
        <InvocationReferenceLink invocation={invocation} />
      </div>
 
      <div className="px-4 py-4 space-y-4">
        <InvocationCallList calls={invocation.calls ?? []} />
        {isError && invocation.error_detail && (
          <div className="flex items-start gap-1.5 px-3 py-2 rounded-lg bg-red-50 dark:bg-red-950/40 border border-red-200 dark:border-red-800 text-xs text-red-700 dark:text-red-300">
            <AlertCircle className="size-3.5 shrink-0 mt-0.5" />
            <span className="break-words">{invocation.error_detail}</span>
          </div>
        )}
        {invocation.output_preview && (
          <OutputBlock
            label={
              invocation.purpose === "agent_generation"
                ? "Generated configuration"
                : "Produced output"
            }
            content={invocation.output_preview}
            variant="default"
            labelIcon={
              invocation.purpose === "agent_generation" ? (
                <Sparkles className="size-3 text-violet-500" />
              ) : (
                <MessageSquare className="size-3" />
              )
            }
          />
        )}
        {invocation.request_config && (
          <OutputBlock
            label="Request config"
            content={JSON.stringify(invocation.request_config, null, 2)}
            variant="default"
            labelIcon={<Settings2 className="size-3" />}
          />
        )}
      </div>
    </PanelShell>
  );
};
 
// ─── Evaluation Run Row / Panel ───────────────────────────────────────────────
//
// One batch — an evaluation's variants over its dataset, or a dataset run
// against one target. Read from the cross-experiment report with unfinished
// runs included, so a queued, failed or cancelled run is an event here too.
 
const EVALUATION_RUN_LABEL = "Experiment run";
 
const evaluationHref = (batch: BatchReportRow): string | null =>
  resourceHref("experiment", batch.experiment_id);
 
const EvaluationRunRow: React.FC<{
  batch: BatchReportRow;
  selected: boolean;
  onClick: () => void;
}> = ({ batch, selected, onClick }) => {
  const failed = batch.status === "failed";
  const running = batch.status === "queued" || batch.status === "running";
  return (
    <FeedRow
      selected={selected}
      onClick={onClick}
      dot={
        <span
          className={`size-2 rounded-full shrink-0 ${
            failed
              ? "bg-red-500"
              : running
                ? "bg-blue-500 animate-pulse"
                : batch.status === "cancelled"
                  ? "bg-gray-400"
                  : "bg-sky-500"
          }`}
        />
      }
    >
      <div className="flex items-center gap-1.5 flex-wrap">
        <span className="inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded-full border bg-sky-50 dark:bg-sky-950/40 text-sky-700 dark:text-sky-300 border-sky-200 dark:border-sky-800">
          <FlaskConical className="size-3" />
          {EVALUATION_RUN_LABEL}
        </span>
        <span className="text-xs font-medium text-gray-800 dark:text-gray-200 truncate">
          {batch.experiment_name}
        </span>
        {batch.label && (
          <span className="text-[10px] text-gray-400 dark:text-gray-500">
            {batch.label}
          </span>
        )}
        {batch.dataset_name && (
          <span className="text-[10px] text-gray-400 dark:text-gray-500 truncate">
            on {batch.dataset_name}
          </span>
        )}
      </div>
      <div className="flex items-center gap-2 flex-wrap">
        <RunStatusBadge status={batch.status ?? "queued"} />
        {batch.status === "completed" && (
          <ScoreBadge value={batch.mean_score} />
        )}
        {failed && batch.error && (
          <span className="text-xs text-red-500 dark:text-red-400 truncate">
            {truncate(batch.error, 60)}
          </span>
        )}
      </div>
      <div className="flex items-center gap-2 text-[10px] text-gray-400 dark:text-gray-500">
        <span>
          {batch.finished_at ?? batch.created_at
            ? formatRelative((batch.finished_at ?? batch.created_at)!)
            : "—"}
        </span>
        {batch.total_cases != null && (
          <>
            <span className="text-gray-200 dark:text-gray-700">·</span>
            <span className="tabular-nums">
              {batch.total_cases} case{batch.total_cases === 1 ? "" : "s"}
            </span>
          </>
        )}
        {batch.total_tokens != null && batch.total_tokens > 0 && (
          <>
            <span className="text-gray-200 dark:text-gray-700">·</span>
            <Coins className="size-2.5" />
            <span className="tabular-nums">
              {formatTokens(batch.total_tokens)}
            </span>
          </>
        )}
      </div>
    </FeedRow>
  );
};
 
const EvaluationRunPanel: React.FC<{
  batch: BatchReportRow;
  onClose: () => void;
}> = ({ batch, onClose }) => {
  const href = evaluationHref(batch);
  const when = batch.finished_at ?? batch.created_at;
  return (
    <PanelShell
      icon={
        <FlaskConical className="size-4 text-sky-500 dark:text-sky-400 shrink-0" />
      }
      title={batch.experiment_name}
      badge={<RunStatusBadge status={batch.status ?? "queued"} />}
      onClose={onClose}
    >
      <div className="px-4 py-4 border-b border-gray-100 dark:border-gray-700 space-y-4">
        <div className="grid grid-cols-2 gap-3">
          <MetaItem
            size="sm"
            icon={Hash}
            label="Batch ID"
            value={
              <span
                className="font-mono text-xs truncate block"
                title={batch.batch_id}
              >
                {batch.batch_id.slice(0, 16)}…
              </span>
            }
            action={<CopyButton variant="bare" value={batch.batch_id} />}
          />
          <MetaItem
            size="sm"
            icon={Clock}
            label={batch.finished_at ? "Finished" : "Started"}
            value={when ? formatTimestamp(when) : "—"}
          />
          <MetaItem
            size="sm"
            icon={FlaskConical}
            label="Kind"
            value={
              <span>
                {batch.label ?? "Run"}
                {batch.variants > 1 ? ` · ${batch.variants} variants` : ""}
                {batch.dataset_name ? ` · on ${batch.dataset_name}` : ""}
              </span>
            }
          />
          <MetaItem
            size="sm"
            icon={ClipboardCheck}
            label="Scorer"
            value={batch.scorer ?? "—"}
          />
          <MetaItem
            size="sm"
            icon={CheckCircle2}
            label="Mean score"
            value={<ScoreBadge value={batch.mean_score} />}
          />
          <MetaItem
            size="sm"
            icon={Check}
            label="Pass rate"
            value={formatScore(batch.pass_rate)}
          />
          <MetaItem
            size="sm"
            icon={Layers}
            label="Cases"
            value={batch.total_cases ?? "—"}
          />
          <MetaItem
            size="sm"
            icon={AlertCircle}
            label="Errors"
            value={batch.errors ?? "—"}
          />
        </div>
 
        {batch.total_tokens != null && batch.total_tokens > 0 && (
          <div className="flex items-center gap-3 text-xs text-gray-500 dark:text-gray-400">
            <Coins className="size-3" />
            <span className="tabular-nums">
              {formatTokens(batch.total_tokens)} tokens
            </span>
            {batch.duration_ms != null && (
              <span className="tabular-nums">
                · {formatDuration(batch.duration_ms)}
              </span>
            )}
          </div>
        )}
 
        {href && (
          <Link
            to={href}
            className="inline-flex items-center gap-1.5 text-xs font-medium text-gray-700 dark:text-gray-300 hover:underline"
          >
            <ExternalLink className="size-3" />
            Open evaluation
          </Link>
        )}
      </div>
 
      {batch.error && (
        <div className="px-4 py-4">
          <div className="flex items-start gap-1.5 px-3 py-2 rounded-lg bg-red-50 dark:bg-red-950/40 border border-red-200 dark:border-red-800 text-xs text-red-700 dark:text-red-300">
            <AlertCircle className="size-3.5 shrink-0 mt-0.5" />
            <span className="break-words">{batch.error}</span>
          </div>
        </div>
      )}
    </PanelShell>
  );
};
 
// ─── Background Work ──────────────────────────────────────────────────────────
//
// What the platform did without being asked in a request: a dashboard tile
// regenerated (on the scheduler, or because a board was opened), a website
// source re-crawled, review flags deleted by retention. One row per subject,
// from `/app/activity/background`.
 
const BACKGROUND_KIND_ICON: Record<BackgroundKind, React.ElementType> = {
  widget_refresh: LayoutDashboard,
  knowledge_crawl: Globe,
  review_retention: Trash2,
};
 
const backgroundSubjectHref = (event: BackgroundEvent): string | null =>
  event.subject_type && event.subject_id
    ? resourceHref(event.subject_type, event.subject_id)
    : null;
 
const BackgroundRow: React.FC<{
  event: BackgroundEvent;
  selected: boolean;
  onClick: () => void;
}> = ({ event, selected, onClick }) => {
  const Icon = BACKGROUND_KIND_ICON[event.kind] ?? RefreshCw;
  const failed = event.status === "failed";
  return (
    <FeedRow
      selected={selected}
      onClick={onClick}
      dot={
        <span
          className={`size-2 rounded-full shrink-0 ${
            failed ? "bg-red-500" : "bg-teal-500"
          }`}
        />
      }
    >
      <div className="flex items-center gap-1.5 flex-wrap">
        <span className="inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded-full border bg-teal-50 dark:bg-teal-950/40 text-teal-700 dark:text-teal-300 border-teal-200 dark:border-teal-800">
          <Icon className="size-3" />
          {BACKGROUND_KIND_LABELS[event.kind] ?? event.kind}
        </span>
        {event.subject_name && (
          <span className="text-xs font-medium text-gray-800 dark:text-gray-200 truncate">
            {event.subject_name}
          </span>
        )}
      </div>
      <p
        className={`text-xs truncate ${
          failed
            ? "text-red-500 dark:text-red-400"
            : "text-gray-500 dark:text-gray-400"
        }`}
      >
        {truncate(event.summary, 70)}
      </p>
      <div className="flex items-center gap-2 text-[10px] text-gray-400 dark:text-gray-500">
        <span>{formatRelative(event.finished_at)}</span>
        <span className="text-gray-200 dark:text-gray-700">·</span>
        <CalendarClock className="size-2.5" />
        <span>{BACKGROUND_TRIGGER_LABELS[event.trigger] ?? event.trigger}</span>
        {event.duration_ms != null && (
          <>
            <span className="text-gray-200 dark:text-gray-700">·</span>
            <Clock className="size-2.5" />
            <span className="tabular-nums">
              {formatDuration(event.duration_ms)}
            </span>
          </>
        )}
      </div>
    </FeedRow>
  );
};
 
/** The figures behind a crawl's one-line summary. */
const CRAWL_COUNTS: { key: string; label: string }[] = [
  { key: "pages_fetched", label: "Fetched" },
  { key: "pages_new", label: "New" },
  { key: "pages_changed", label: "Changed" },
  { key: "pages_unchanged", label: "Unchanged" },
  { key: "pages_gone", label: "Gone" },
  { key: "pages_failed", label: "Failed" },
];
 
const BackgroundPanel: React.FC<{
  event: BackgroundEvent;
  onClose: () => void;
}> = ({ event, onClose }) => {
  const Icon = BACKGROUND_KIND_ICON[event.kind] ?? RefreshCw;
  const href = backgroundSubjectHref(event);
  const detail = event.detail ?? {};
  const note =
    event.kind === "knowledge_crawl" &&
    event.status !== "failed" &&
    typeof detail.note === "string"
      ? detail.note
      : null;
  return (
    <PanelShell
      icon={
        <Icon className="size-4 text-teal-500 dark:text-teal-400 shrink-0" />
      }
      title={event.subject_name ?? BACKGROUND_KIND_LABELS[event.kind]}
      badge={
        <StatusBadge
          scale={BACKGROUND_STATUS}
          size="sm"
          status={event.status}
        />
      }
      onClose={onClose}
    >
      <div className="px-4 py-4 border-b border-gray-100 dark:border-gray-700 space-y-4">
        <p className="text-sm text-gray-700 dark:text-gray-300">
          {event.summary}
        </p>
        <div className="grid grid-cols-2 gap-3">
          <MetaItem
            size="sm"
            icon={Icon}
            label="Kind"
            value={BACKGROUND_KIND_LABELS[event.kind] ?? event.kind}
          />
          <MetaItem
            size="sm"
            icon={CalendarClock}
            label="Triggered by"
            value={BACKGROUND_TRIGGER_LABELS[event.trigger] ?? event.trigger}
          />
          <MetaItem
            size="sm"
            icon={Clock}
            label="Finished"
            value={formatTimestamp(event.finished_at)}
          />
          <MetaItem
            size="sm"
            icon={Zap}
            label="Took"
            value={
              event.duration_ms != null
                ? formatDuration(event.duration_ms)
                : "—"
            }
          />
          {event.kind === "knowledge_crawl" &&
            CRAWL_COUNTS.map(({ key, label }) => (
              <MetaItem
                key={key}
                size="sm"
                icon={Hash}
                label={label}
                value={typeof detail[key] === "number" ? String(detail[key]) : "—"}
              />
            ))}
          {event.kind === "widget_refresh" &&
            typeof detail.widget_title === "string" && (
              <MetaItem
                size="sm"
                icon={LayoutDashboard}
                label="Tile"
                value={detail.widget_title}
              />
            )}
        </div>
 
        {note && (
          <p className="text-xs text-gray-500 dark:text-gray-400">{note}</p>
        )}
 
        {href && (
          <Link
            to={href}
            className="inline-flex items-center gap-1.5 text-xs font-medium text-gray-700 dark:text-gray-300 hover:underline"
          >
            <ExternalLink className="size-3" />
            {event.subject_type === "dashboard"
              ? "Open dashboard"
              : event.subject_type === "knowledge"
                ? "Open knowledge source"
                : "Open"}
          </Link>
        )}
      </div>
 
      {event.error && (
        <div className="px-4 py-4">
          <div className="flex items-start gap-1.5 px-3 py-2 rounded-lg bg-red-50 dark:bg-red-950/40 border border-red-200 dark:border-red-800 text-xs text-red-700 dark:text-red-300">
            <AlertCircle className="size-3.5 shrink-0 mt-0.5" />
            <span className="break-words">{event.error}</span>
          </div>
        </div>
      )}
    </PanelShell>
  );
};
 
// ─── Feed Dispatchers ─────────────────────────────────────────────────────────
//
// One switch each, so adding a sixth kind of activity means adding a row, a
// panel and two cases — never touching the page's filter or merge logic.
 
const ActivityRow: React.FC<{
  item: ActivityItem;
  selected: boolean;
  onClick: () => void;
}> = ({ item, selected, onClick }) => {
  switch (item.kind) {
    case "run":
      return <RunRow run={item.run} selected={selected} onClick={onClick} />;
    case "invocation":
      return (
        <InvocationRow
          invocation={item.invocation}
          selected={selected}
          onClick={onClick}
        />
      );
    case "change":
      return (
        <ResourceChangeRow
          event={item.event}
          selected={selected}
          onClick={onClick}
        />
      );
    case "generation":
      return (
        <GenerationRow
          generation={item.generation}
          selected={selected}
          onClick={onClick}
        />
      );
    case "evaluation":
      return (
        <EvaluationRunRow
          batch={item.batch}
          selected={selected}
          onClick={onClick}
        />
      );
    case "background":
      return (
        <BackgroundRow
          event={item.event}
          selected={selected}
          onClick={onClick}
        />
      );
  }
};
 
// ─── Stacking ─────────────────────────────────────────────────────────────────
//
// Routine work repeats: a board with a dozen tiles refreshes a dozen times an
// hour, and an evaluation run makes a call per cell. Consecutive items that
// are "the same thing again" fold into one stack, drawn as its newest item
// with the rest behind it, like a burst of notifications from one app.
//
// A tile's LLM call and the refresh it belongs to share a key, because they
// arrive interleaved and are one activity to the reader. A failure never
// stacks: it is the row the feed exists to show.
 
const DASHBOARD_STACK = "dashboard";
 
const stackKeyOf = (item: ActivityItem): string | null => {
  switch (item.kind) {
    case "background":
      if (item.event.status === "failed") return null;
      return item.event.kind === "widget_refresh"
        ? DASHBOARD_STACK
        : `background:${item.event.kind}`;
    case "invocation":
      if (item.invocation.status === "error") return null;
      return item.invocation.purpose === "dashboard_widget"
        ? DASHBOARD_STACK
        : `invocation:${item.invocation.purpose ?? "unknown"}`;
    default:
      // Runs, changes, generations and evaluation runs are each something a
      // person did or asked for, so each keeps its own row.
      return null;
  }
};
 
/** What a stack is a pile of, in the words its rows already use. */
const stackLabel = (key: string, top: ActivityItem): string => {
  Eif (key === DASHBOARD_STACK) return BACKGROUND_KIND_LABELS.widget_refresh;
  if (top.kind === "background") return BACKGROUND_KIND_LABELS[top.event.kind];
  if (top.kind === "invocation") return purposeMeta(top.invocation.purpose).label;
  return "Similar events";
};
 
const ActivityStack: React.FC<{
  stackKey: string;
  items: ActivityItem[];
  expanded: boolean;
  onToggle: () => void;
  selectedId: string | null;
  onSelect: (id: string) => void;
}> = ({ stackKey, items, expanded, onToggle, selectedId, onSelect }) => {
  const [top, ...rest] = items;
  const label = stackLabel(stackKey, top);
  const oldest = items[items.length - 1].timestamp;
  const row = (item: ActivityItem) => (
    <ActivityRow
      key={item.id}
      item={item}
      selected={selectedId === item.id}
      onClick={() => onSelect(item.id)}
    />
  );
  return (
    <div role="group" aria-label={`${label} stack`} className="mb-1.5">
      <div className="relative z-10 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
        {row(top)}
        <button
          onClick={onToggle}
          aria-expanded={expanded}
          aria-label={`${expanded ? "Collapse" : "Show"} ${rest.length} more ${label}`}
          className="w-full flex items-center gap-1.5 px-3 py-1.5 border-t border-gray-100 dark:border-gray-700 text-[10px] text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700/30 rounded-b-lg transition-colors"
        >
          <Layers className="size-3 shrink-0" />
          <span className="font-medium tabular-nums">{rest.length} more</span>
          <span className="truncate">
            · {label}
            {oldest ? ` since ${formatRelative(oldest)}` : ""}
          </span>
          <span className="ml-auto inline-flex items-center gap-0.5 shrink-0">
            {expanded ? "Collapse" : "Expand"}
            {expanded ? (
              <ChevronUp className="size-3" />
            ) : (
              <ChevronDown className="size-3" />
            )}
          </span>
        </button>
      </div>
      {expanded ? (
        <div className="mt-1 ml-3 pl-1 border-l-2 border-gray-100 dark:border-gray-700">
          {rest.map(row)}
        </div>
      ) : (
        // The edges of the cards underneath — two at most, like a phone's.
        <div aria-hidden>
          <div className="mx-2 h-1.5 rounded-b-lg border border-t-0 border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/80" />
          {rest.length > 1 && (
            <div className="mx-4 h-1.5 rounded-b-lg border border-t-0 border-gray-200 dark:border-gray-700 bg-gray-100 dark:bg-gray-800/60" />
          )}
        </div>
      )}
    </div>
  );
};
 
const ActivityDetail: React.FC<{
  item: ActivityItem;
  onClose: () => void;
  onOpenRun: (conversationId: string) => void;
  onOpenResource: (resourceType: ActivityResourceType, id: string) => void;
  runExists: (conversationId: string | null) => boolean;
  canOpenResource: (resourceType: ActivityResourceType, id: string) => boolean;
}> = ({
  item,
  onClose,
  onOpenRun,
  onOpenResource,
  runExists,
  canOpenResource,
}) => {
  switch (item.kind) {
    case "run":
      return <RunDetailPanel run={item.run} onClose={onClose} />;
    case "invocation":
      return (
        <InvocationDetailPanel
          invocation={item.invocation}
          onClose={onClose}
          onOpenRun={
            runExists(item.invocation.conversation_id) ? onOpenRun : null
          }
        />
      );
    case "change":
      return <ResourceChangePanel event={item.event} onClose={onClose} />;
    case "generation":
      return (
        <GenerationRunPanel
          generation={item.generation}
          onClose={onClose}
          onOpenResource={onOpenResource}
          canOpenResource={canOpenResource}
        />
      );
    case "evaluation":
      return <EvaluationRunPanel batch={item.batch} onClose={onClose} />;
    case "background":
      return <BackgroundPanel event={item.event} onClose={onClose} />;
  }
};
 
// ─── Empty State ──────────────────────────────────────────────────────────────
 
const CATEGORY_EMPTY_COPY: Record<
  ActivityCategory,
  { empty: string; hint: string }
> = {
  all: {
    empty: "No activity yet",
    hint: "Runs, LLM calls, resource changes, generative invocations and background work all land here.",
  },
  inference: {
    empty: "No inference yet",
    hint: "Start a model or agent conversation to see runs and LLM calls here.",
  },
  resource: {
    empty: "No resource changes yet",
    hint: "Creating, editing or deleting any resource writes an append-only version here.",
  },
  generative: {
    empty: "No generative invocations yet",
    hint: "Generate an agent, skill, skillset, dashboard or knowledge repository to see the invocation behind it.",
  },
  background: {
    empty: "No background work yet",
    hint: "Dashboard tiles refreshing, website sources re-crawling and retention purges land here.",
  },
};
 
const EmptyActivity: React.FC<{
  filtered: boolean;
  category: ActivityCategory;
}> = ({ filtered, category }) => {
  const copy = CATEGORY_EMPTY_COPY[category];
  return (
    <div className="flex flex-col items-center justify-center py-16 text-center px-4">
      <Activity className="size-8 text-gray-300 dark:text-gray-600 mb-3" />
      <p className="text-sm font-medium text-gray-500 dark:text-gray-400">
        {filtered ? "No activity matches your filters" : copy.empty}
      </p>
      <p className="text-xs text-gray-400 dark:text-gray-500 mt-1 max-w-sm">
        {filtered ? "Try adjusting the search or filters" : copy.hint}
      </p>
      {!filtered && category !== "resource" && (
        <div className="flex items-center gap-2 mt-4">
          <Link
            to={APP_ROUTES.USER.INFERENCE.models}
            className="flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-500 transition-colors"
          >
            <BrainCog className="size-3.5" />
            Browse Models
          </Link>
          <Link
            to={APP_ROUTES.USER.INFERENCE.agents}
            className="flex items-center gap-1.5 text-xs text-gray-500 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 px-3 py-1.5 rounded-lg border border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-500 transition-colors"
          >
            <Bot className="size-3.5" />
            Browse Agents
          </Link>
        </div>
      )}
    </div>
  );
};
 
// ─── Filter Chip Group ────────────────────────────────────────────────────────
 
/**
 * The segmented control the filter row is made of. Every filter on the page
 * renders through it, so a new category's sub-filter costs one call rather
 * than another copy of the button markup.
 */
function ChipGroup<T extends string>({
  options,
  value,
  onChange,
  label,
}: {
  options: { value: T; label: string }[];
  value: T;
  onChange: (value: T) => void;
  label: string;
}): React.ReactElement {
  return (
    <div
      role="group"
      aria-label={label}
      className="flex items-center rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 overflow-hidden shrink-0"
    >
      {options.map((option) => (
        <button
          key={option.value}
          onClick={() => onChange(option.value)}
          aria-pressed={value === option.value}
          className={`px-3 py-2 text-xs font-medium transition-colors ${
            value === option.value
              ? "bg-gray-900 dark:bg-white text-white dark:text-gray-900"
              : "text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700"
          }`}
        >
          {option.label}
        </button>
      ))}
    </div>
  );
}
 
// ─── Activity Page ────────────────────────────────────────────────────────────
 
/** Rows read from each source per request. */
const SOURCE_PAGE_SIZE = 100;
 
/** Events drawn per page of the feed. Stacks are folded within a page, so a
 *  run of refreshes crossing a page boundary continues as a stack on the
 *  next one. */
const FEED_ITEMS_PER_PAGE = 50;
 
/** What a source has loaded, with a "+" while it has more — a source read
 *  a page at a time does not know its length until it reaches the end. */
const loadedCount = (source: FeedSource<unknown>): string =>
  `${source.items.length}${source.exhausted ? "" : "+"}`;
 
/** A server timestamp in epoch ms; NaN for a missing one. */
const serverTime = (iso: string | null | undefined): number =>
  iso ? parseServerDate(iso).getTime() : NaN;
 
/** Earliest timestamp a time filter admits, or null for "all time". */
function timeFilterSince(filter: TimeFilter): string | null {
  if (filter === "all") return null;
  const day = 86_400_000;
  const days = filter === "today" ? 1 : filter === "week" ? 7 : 30;
  return new Date(Date.now() - days * day).toISOString();
}
 
const ActivityPage: React.FC = () => {
  const { getApiHandler } = useApiHandler();
 
  const [search, setSearch] = useState("");
  const [category, setCategory] = useState<ActivityCategory>("all");
  const [inferenceFilter, setInferenceFilter] =
    useState<InferenceFilter>("all");
  const [actionFilter, setActionFilter] = useState<ActionFilter>("all");
  const [domainFilter, setDomainFilter] = useState<DomainFilter>("all");
  const [generativeFilter, setGenerativeFilter] =
    useState<GenerativeFilter>("all");
  const [backgroundFilter, setBackgroundFilter] =
    useState<BackgroundFilter>("all");
  const [timeFilter, setTimeFilter] = useState<TimeFilter>("all");
  const [selectedId, setSelectedId] = useState<string | null>(null);
  const [expandedStacks, setExpandedStacks] = useState<Set<string>>(
    () => new Set(),
  );
 
  const since = timeFilterSince(timeFilter);
 
  // Each source is fetched whole and merged client-side. The four are
  // independent reads with independent shapes, so a server-side union would
  // have to flatten them; the page-size cap keeps the merge bounded.
  // Each read is bound to an explicitly typed const: the pinned TypeScript
  // cannot infer react-query v5's return type, so `data` arrives as `any` and
  // every downstream callback parameter would lose its type with it.
  const { data: conversationData, isLoading: convsLoading } = useQuery({
    queryKey: [QUERY_KEYS.GET.CONVERSATIONS],
    queryFn: () => getApiHandler().conversation_router.list(),
  });
  const conversations: Conversation[] = conversationData ?? [];
 
  const { data: agentData, isLoading: agentsLoading } = useQuery({
    queryKey: [QUERY_KEYS.GET.AGENTS],
    queryFn: () => getApiHandler().agent_router.list(undefined),
  });
  const agents: Agent[] = agentData ?? [];
 
  // Archived models too, so a run on a model since taken out of the
  // catalogue still names it.
  const { data: modelData, isLoading: modelsLoading } = useQuery({
    queryKey: [QUERY_KEYS.GET.MODELS_WITH_ARCHIVED],
    queryFn: () => getApiHandler().model_router.list({ includeArchived: true }),
  });
  const models: Model[] = modelData ?? [];
 
  const { data: usageStats, isLoading: statsLoading } = useQuery({
    queryKey: [QUERY_KEYS.GET.USAGE_STATS],
    queryFn: () => getApiHandler().stats_router.getUsage(),
    staleTime: 60_000,
  });
  // Spend from the usage ledger, the figure every other page shows.
  const spend = useSpend({ period: "all_time" });
 
  // The five sources below are read a page at a time, newest first, and
  // paged further back on demand (see `util/pagedFeed`). Their keys carry a
  // "feed" segment so these infinite queries never share a cache entry with
  // the plain list queries other pages make on the same endpoints.
  const invocationSource = useFeedSource<LLMInvocationRecord>({
    queryKey: [QUERY_KEYS.GET.LLM_INVOCATIONS, "feed"],
    fetchPage: async (offset, limit) => ({
      rows:
        (await getApiHandler().stats_router.listInvocations(
          undefined,
          limit,
          offset,
        )) ?? [],
    }),
    pageSize: SOURCE_PAGE_SIZE,
    idOf: (row) => row.id,
    sortTime: (row) => serverTime(row.created_at),
  });
  const invocations = invocationSource.items;
 
  // The time window is pushed to the server for the two feeds that support
  // it, so a narrow window costs a smaller response rather than a larger
  // client-side filter.
  const changeSource = useFeedSource<ActivityEvent>({
    queryKey: [QUERY_KEYS.GET.ACTIVITY, "feed", since],
    fetchPage: async (offset, limit) => {
      const res = await getApiHandler().activity_router.list({
        limit,
        offset,
        ...(since ? { since } : {}),
      });
      return { rows: res?.events ?? [], total: res?.total };
    },
    pageSize: SOURCE_PAGE_SIZE,
    idOf: (row) => row.id,
    sortTime: (row) => serverTime(row.created_at),
  });
 
  const { data: activitySummary, isLoading: summaryLoading } = useQuery({
    queryKey: [QUERY_KEYS.GET.ACTIVITY_SUMMARY, since],
    queryFn: () => getApiHandler().activity_router.summary(since ?? undefined),
    staleTime: 60_000,
  });
 
  const generationSource = useFeedSource<GenerationRun>({
    queryKey: [QUERY_KEYS.GET.GENERATIONS, "feed"],
    fetchPage: async (offset, limit) => {
      const res = await getApiHandler().generation_router.list({
        limit,
        offset,
      });
      return { rows: res?.generations ?? [], total: res?.total };
    },
    pageSize: SOURCE_PAGE_SIZE,
    idOf: (row) => row.id,
    sortTime: (row) => serverTime(row.created_at),
  });
 
  // Every evaluation and dataset run, whatever state it reached. The report
  // lists completed batches by default because it is about figures; here a
  // run is an event, and the failed one is the one that must not be missing.
  const batchSource = useFeedSource<BatchReportRow>({
    queryKey: [QUERY_KEYS.GET.BATCH_REPORT, "activity", "feed"],
    fetchPage: async (offset, limit) => ({
      rows: await getApiHandler().evaluation_router.reportBatches({
        days: 90,
        limit,
        offset,
        include_unfinished: true,
      }),
    }),
    pageSize: SOURCE_PAGE_SIZE,
    idOf: (row) => row.batch_id,
    // The server orders runs by when they were asked for.
    sortTime: (row) => serverTime(row.created_at),
  });
  const batches = batchSource.items;
 
  // Scheduled and other background work, windowed on the server like the
  // change feed — and narrowed by kind there too, because this is the
  // high-volume source: filtering a minute-by-minute refresh stream in the
  // client would page through thousands of rows to find one crawl.
  const backgroundKinds =
    category === "background" && backgroundFilter !== "all"
      ? [backgroundFilter]
      : undefined;
  const backgroundSource = useFeedSource<BackgroundEvent>({
    queryKey: [QUERY_KEYS.GET.ACTIVITY_BACKGROUND, "feed", since, backgroundKinds],
    fetchPage: async (offset, limit) => {
      const res = await getApiHandler().activity_router.background({
        limit,
        offset,
        ...(since ? { since } : {}),
        ...(backgroundKinds ? { kind: backgroundKinds } : {}),
      });
      return {
        rows: res?.events ?? [],
        total: res?.total,
        meta: { retention_days: res?.retention_days ?? null },
      };
    },
    pageSize: SOURCE_PAGE_SIZE,
    idOf: (row) => row.id,
    sortTime: (row) => serverTime(row.finished_at),
  });
  const backgroundEvents = backgroundSource.items;
  const retentionDays =
    typeof backgroundSource.meta?.retention_days === "number"
      ? backgroundSource.meta.retention_days
      : null;
 
  const changes = changeSource.items;
  const generations = generationSource.items;
  const summary: ActivitySummary | null = activitySummary ?? null;
 
  const agentMap = useMemo(
    () =>
      agents.reduce<Record<string, Agent>>((acc, a) => {
        acc[a.id] = a;
        return acc;
      }, {}),
    [agents],
  );
 
  const modelMap = useMemo(
    () =>
      models.reduce<Record<string, Model>>((acc, m) => {
        acc[m.id] = m;
        return acc;
      }, {}),
    [models],
  );
 
  const runs: Run[] = useMemo(
    () =>
      conversations.map((conv) => ({
        conversation: conv,
        type: deriveRunType(conv),
        status: deriveStatus(conv),
        modelName: conv.ai_model_id
          ? (modelMap[conv.ai_model_id]?.display_name ??
            modelMap[conv.ai_model_id]?.model_name ??
            null)
          : null,
        agentName: conv.agent_id
          ? (agentMap[conv.agent_id]?.name ?? null)
          : null,
      })),
    [conversations, agentMap, modelMap],
  );
 
  // ── The merged stream ────────────────────────────────────────────────────
  //
  // Built once from every source and sorted by timestamp; the category and
  // sub-filters narrow this list rather than choosing between four of them,
  // so "all" is the same code path as every other view.
  const items: ActivityItem[] = useMemo(() => {
    const merged: ActivityItem[] = [
      ...runs.map((run): ActivityItem => ({
        kind: "run",
        id: `run:${run.conversation.id}`,
        timestamp: run.conversation.created_at,
        run,
      })),
      ...invocations.map((invocation): ActivityItem => ({
        kind: "invocation",
        id: `invocation:${invocation.id}`,
        timestamp: invocation.created_at ?? "",
        invocation,
      })),
      ...changes.map((event): ActivityItem => ({
        kind: "change",
        id: `change:${event.id}`,
        timestamp: event.created_at ?? "",
        event,
      })),
      ...generations.map((generation): ActivityItem => ({
        kind: "generation",
        id: `generation:${generation.id}`,
        timestamp: generation.created_at ?? "",
        generation,
      })),
      ...batches.map((batch): ActivityItem => ({
        kind: "evaluation",
        id: `evaluation:${batch.batch_id}`,
        // A finished run sits at the moment it produced its result; one still
        // going, or one that never finished, at the moment it was asked for.
        timestamp: batch.finished_at ?? batch.created_at ?? "",
        batch,
      })),
      ...backgroundEvents.map((event): ActivityItem => ({
        kind: "background",
        id: `background:${event.id}`,
        timestamp: event.finished_at,
        event,
      })),
    ];
    return merged.sort(
      (a, b) =>
        parseServerDate(b.timestamp).getTime() - parseServerDate(a.timestamp).getTime(),
    );
  }, [runs, invocations, changes, generations, batches, backgroundEvents]);
 
  /** Which category an item belongs to. A generated resource change counts as
   *  both a resource change and generative activity — the provenance is the
   *  point, so it must be reachable from the filter that asks about it. */
  const inCategory = (item: ActivityItem, cat: ActivityCategory): boolean => {
    if (cat === "all") return true;
    if (cat === "inference")
      return (
        item.kind === "run" ||
        item.kind === "invocation" ||
        item.kind === "evaluation"
      );
    if (cat === "resource") return item.kind === "change";
    if (cat === "background") return item.kind === "background";
    return (
      item.kind === "generation" ||
      (item.kind === "change" && item.event.is_ai_generated === true)
    );
  };
 
  /** The free-text haystack for an item, matched case-insensitively. */
  const haystack = (item: ActivityItem): string => {
    switch (item.kind) {
      case "run":
        return [
          item.run.conversation.id,
          item.run.agentName ?? "",
          item.run.modelName ?? "",
          getFirstUserMessage(item.run.conversation) ?? "",
        ].join(" ");
      case "invocation":
        return [
          item.invocation.id,
          item.invocation.purpose ?? "",
          purposeMeta(item.invocation.purpose).label,
          item.invocation.model_name ?? "",
          item.invocation.provider
            ? makerLabel(item.invocation.provider, item.invocation.model_name)
            : "",
          invocationModelLabel(item.invocation),
          ...(item.invocation.calls ?? []).flatMap((c) => [
            c.model_name,
            c.model_display_name ?? "",
            makerLabel(c.provider, c.model_name),
            c.node ?? "",
          ]),
          item.invocation.conversation_id ?? "",
        ].join(" ");
      case "change":
        return [
          item.event.id,
          item.event.resource_id,
          item.event.resource_name ?? "",
          RESOURCE_TYPE_LABELS[item.event.resource_type],
          item.event.action,
          actorLabel(item.event),
          item.event.changed_fields.join(" "),
        ].join(" ");
      case "generation":
        return [
          item.generation.id,
          item.generation.flow,
          GENERATION_FLOW_LABELS[item.generation.flow] ?? "",
          item.generation.status,
          item.generation.model_name ?? "",
          Object.values(item.generation.arguments ?? {})
            .filter((v): v is string => typeof v === "string")
            .join(" "),
        ].join(" ");
      case "evaluation":
        return [
          item.batch.batch_id,
          item.batch.experiment_id,
          item.batch.dataset_id ?? "",
          item.batch.dataset_name ?? "",
          item.batch.experiment_name,
          item.batch.label ?? "",
          EVALUATION_RUN_LABEL,
          item.batch.status ?? "",
          item.batch.scorer ?? "",
        ].join(" ");
      case "background":
        return [
          item.event.id,
          item.event.subject_name ?? "",
          item.event.summary,
          BACKGROUND_KIND_LABELS[item.event.kind] ?? "",
          BACKGROUND_TRIGGER_LABELS[item.event.trigger] ?? "",
          item.event.status,
        ].join(" ");
    }
  };
 
  const filteredItems = useMemo(() => {
    const q = search.trim().toLowerCase();
    return items.filter((item) => {
      if (!inCategory(item, category)) return false;
      Iif (item.timestamp && !isInTimeRange(item.timestamp, timeFilter))
        return false;
 
      if (category === "inference" && inferenceFilter !== "all") {
        Iif (inferenceFilter === "invocation") {
          if (item.kind !== "invocation") return false;
        } else if (inferenceFilter === "evaluation") {
          // The runs, and the LLM calls those runs made — cells and judge.
          const isEvaluationCall =
            item.kind === "invocation" &&
            EVALUATION_PURPOSES.has(item.invocation.purpose ?? "");
          if (item.kind !== "evaluation" && !isEvaluationCall) return false;
        } else Eif (item.kind !== "run" || item.run.type !== inferenceFilter) {
          return false;
        }
      }
 
      if (category === "resource" && item.kind === "change") {
        if (actionFilter !== "all" && item.event.action !== actionFilter)
          return false;
        if (
          domainFilter !== "all" &&
          RESOURCE_TYPE_DOMAIN[item.event.resource_type] !== domainFilter
        )
          return false;
      }
 
      Iif (
        category === "background" &&
        backgroundFilter !== "all" &&
        !(item.kind === "background" && item.event.kind === backgroundFilter)
      ) {
        return false;
      }
 
      if (
        category === "generative" &&
        generativeFilter !== "all" &&
        !(
          item.kind === "generation" &&
          item.generation.status === generativeFilter
        )
      ) {
        return false;
      }
 
      if (q && !haystack(item).toLowerCase().includes(q)) return false;
      return true;
    });
  }, [
    items,
    category,
    inferenceFilter,
    actionFilter,
    domainFilter,
    generativeFilter,
    backgroundFilter,
    timeFilter,
    search,
  ]);
 
  const loading =
    convsLoading ||
    agentsLoading ||
    modelsLoading ||
    invocationSource.isLoading ||
    changeSource.isLoading ||
    generationSource.isLoading ||
    batchSource.isLoading ||
    backgroundSource.isLoading;
 
  // ── Paging ───────────────────────────────────────────────────────────────
  //
  // Only the sources the current category draws from hold the horizon back:
  // under Resources, how far back the refresh stream has been read is
  // irrelevant. A source read back past the time window has nothing more to
  // offer either, whatever the server says.
  const pagedSources: FeedSource<unknown>[] = (() => {
    switch (category) {
      case "inference":
        return [invocationSource, batchSource];
      case "resource":
        return [changeSource];
      case "generative":
        return [generationSource, changeSource];
      case "background":
        return [backgroundSource];
      default:
        return [
          invocationSource,
          changeSource,
          generationSource,
          batchSource,
          backgroundSource,
        ];
    }
  })();
  const sinceMs = since ? Date.parse(since) : null;
  const windows = pagedSources.map((source) => ({
    oldest: source.oldest,
    exhausted:
      source.exhausted ||
      (sinceMs !== null && source.oldest !== null && source.oldest < sinceMs),
  }));
  const horizon = settledHorizon(windows);
  const hasMore = windows.some((w) => !w.exhausted);
  const fetchingMore = pagedSources.some((source) => source.isFetchingMore);
 
  /** The filtered items the merged order is certain of — see `pagedFeed`. */
  const settledItems = useMemo(
    () =>
      filteredItems.filter((item) => {
        const t = serverTime(item.timestamp);
        return Number.isNaN(t) ? horizon === -Infinity : t >= horizon;
      }),
    [filteredItems, horizon],
  );
 
  const [page, setPage] = useState(1);
  const knownPages = pageCount(settledItems.length, FEED_ITEMS_PER_PAGE);
 
  // A new question starts on page one.
  useEffect(() => {
    setPage(1);
  }, [
    category,
    inferenceFilter,
    actionFilter,
    domainFilter,
    generativeFilter,
    backgroundFilter,
    timeFilter,
    search,
  ]);
 
  // Asked for a page past what is loaded: read further back, one page of
  // the source holding the horizon at a time, until the page fills or every
  // source runs out — then settle on the last page there is.
  useEffect(() => {
    if (loading || page <= knownPages) return;
    Iif (!hasMore) {
      setPage(knownPages);
      return;
    }
    Eif (!fetchingMore) pagedSources[horizonSource(windows)]?.loadMore();
    // `pagedSources` and `windows` are rebuilt every render; `horizon` and
    // `hasMore` are what they contribute.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [page, knownPages, hasMore, fetchingMore, horizon, loading]);
 
  const pageItems = useMemo(
    () => pageSlice(settledItems, page, FEED_ITEMS_PER_PAGE),
    [settledItems, page],
  );
 
  // Stacking is drawn over the page being shown, so a filter that separates
  // two kinds of event also separates their stacks, and counts stay per
  // event.
  const feedEntries = useMemo(
    () => stackConsecutive(pageItems, stackKeyOf, (item) => item.id),
    [pageItems],
  );
 
  const pageStart = (page - 1) * FEED_ITEMS_PER_PAGE + 1;
  /** How many events the feed holds, "+" while older ones remain unread. */
  const eventCount = `${settledItems.length}${hasMore ? "+" : ""}`;
 
  const feedScrollRef = useRef<HTMLDivElement>(null);
  const goToPage = (next: number) => {
    setPage(Math.max(1, next));
    // The pane scrolls on its own, so a new page starts at its top rather
    // than wherever the last one was left.
    Eif (feedScrollRef.current) feedScrollRef.current.scrollTop = 0;
  };
 
  const toggleStack = (id: string) =>
    setExpandedStacks((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
 
  const toggleSelected = (id: string) =>
    setSelectedId(selectedId === id ? null : id);
 
  const selectedItem =
    filteredItems.find((i) => i.id === selectedId) ??
    items.find((i) => i.id === selectedId);
 
  const runExists = (conversationId: string | null) =>
    conversationId != null &&
    runs.some((r) => r.conversation.id === conversationId);
 
  /** Jump from an invocation (or a generated resource) to the run/change that
   *  it refers to, switching the category so the target is not filtered out. */
  const openRun = (conversationId: string) => {
    setCategory("all");
    setSelectedId(`run:${conversationId}`);
  };
 
  const findChange = (resourceType: ActivityResourceType, id: string) =>
    changes.find(
      (c) => c.resource_id === id && c.resource_type === resourceType,
    );
 
  const canOpenResource = (resourceType: ActivityResourceType, id: string) =>
    findChange(resourceType, id) != null;
 
  const openResource = (resourceType: ActivityResourceType, id: string) => {
    const change = findChange(resourceType, id);
    Iif (!change) return;
    setCategory("all");
    setSelectedId(`change:${change.id}`);
  };
 
 
  const totalTokens = usageStats?.all_time?.total_tokens ?? 0;
  const totalRuns = usageStats?.all_time?.invocation_count ?? runs.length;
  const changeCount = summary?.total ?? changes.length;
  const generatedCount =
    summary?.ai_generated ?? changes.filter((c) => c.is_ai_generated).length;
 
  const filtersActive =
    search !== "" ||
    timeFilter !== "all" ||
    (category === "inference" && inferenceFilter !== "all") ||
    (category === "resource" &&
      (actionFilter !== "all" || domainFilter !== "all")) ||
    (category === "generative" && generativeFilter !== "all") ||
    (category === "background" && backgroundFilter !== "all");
 
  const domainOptions: { value: DomainFilter; label: string }[] = [
    { value: "all", label: "All areas" },
    ...(Object.keys(ACTIVITY_DOMAIN_LABELS) as ActivityDomain[]).map((d) => ({
      value: d as DomainFilter,
      label: ACTIVITY_DOMAIN_LABELS[d],
    })),
  ];
 
  return (
    <MainPage title="Activity">
      {/* Stats Strip */}
      <div className="flex flex-wrap items-center gap-x-5 gap-y-2 px-4 py-3 rounded-xl bg-gray-50 dark:bg-gray-800/60 border border-gray-100 dark:border-gray-700 mb-5">
        <StatItem label="Runs" value={totalRuns} loading={statsLoading} />
        <Divider />
        <StatItem
          label="LLM calls"
          value={loadedCount(invocationSource)}
          loading={invocationSource.isLoading}
        />
        <Divider />
        <StatItem
          label="Experiment runs"
          value={loadedCount(batchSource)}
          loading={batchSource.isLoading}
        />
        <Divider />
        <StatItem
          label="Background"
          value={backgroundSource.total ?? loadedCount(backgroundSource)}
          loading={backgroundSource.isLoading}
        />
        <Divider />
        <StatItem
          label="Changes"
          value={changeCount}
          loading={summaryLoading || changeSource.isLoading}
        />
        <Divider />
        <StatItem
          label="Generated"
          value={generatedCount}
          loading={summaryLoading || changeSource.isLoading}
        />
        <Divider />
        <StatItem
          label="Total tokens"
          value={formatTokens(totalTokens)}
          loading={statsLoading}
        />
        {spend.figure && (
          <>
            <Divider />
            <StatItem
              label={spend.label}
              value={spend.figure.text}
              loading={spend.isLoading}
            />
          </>
        )}
      </div>
 
      {/* Filter Row */}
      <div className="flex flex-wrap items-center gap-2 mb-4">
        <div className="relative flex-1 min-w-48">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 size-3.5 text-gray-400 pointer-events-none" />
          <input
            type="text"
            aria-label="Search activity"
            placeholder="Search by ID, name, resource, or input…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-8 pr-3 py-2 text-sm rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-1 focus:ring-gray-400 dark:focus:ring-gray-500 transition"
          />
          {search && (
            <button
              onClick={() => setSearch("")}
              aria-label="Clear search"
              className="absolute right-2.5 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
            >
              <X className="size-3.5" />
            </button>
          )}
        </div>
 
        <ChipGroup<ActivityCategory>
          label="Activity category"
          value={category}
          onChange={setCategory}
          options={[
            { value: "all", label: "All" },
            { value: "inference", label: "Inference" },
            { value: "resource", label: "Resources" },
            { value: "generative", label: "Generative" },
            { value: "background", label: "Background" },
          ]}
        />
 
        {category === "inference" && (
          <ChipGroup<InferenceFilter>
            label="Inference type"
            value={inferenceFilter}
            onChange={setInferenceFilter}
            options={[
              { value: "all", label: "All" },
              { value: "agent", label: "Agent" },
              { value: "model", label: "Model" },
              { value: "invocation", label: "LLM calls" },
              { value: "evaluation", label: "Experiments" },
            ]}
          />
        )}
 
        {category === "resource" && (
          <>
            <ChipGroup<ActionFilter>
              label="Change action"
              value={actionFilter}
              onChange={setActionFilter}
              options={[
                { value: "all", label: "All" },
                { value: "created", label: "Created" },
                { value: "updated", label: "Updated" },
                { value: "deleted", label: "Deleted" },
              ]}
            />
            <ChipGroup<DomainFilter>
              label="Platform area"
              value={domainFilter}
              onChange={setDomainFilter}
              options={domainOptions}
            />
          </>
        )}
 
        {category === "generative" && (
          <ChipGroup<GenerativeFilter>
            label="Generation status"
            value={generativeFilter}
            onChange={setGenerativeFilter}
            options={[
              { value: "all", label: "All" },
              { value: "applied", label: "Applied" },
              { value: "proposed", label: "Proposed" },
              { value: "running", label: "Running" },
              { value: "failed", label: "Failed" },
            ]}
          />
        )}
 
        {category === "background" && (
          <ChipGroup<BackgroundFilter>
            label="Background work"
            value={backgroundFilter}
            onChange={setBackgroundFilter}
            options={[
              { value: "all", label: "All" },
              ...(Object.keys(BACKGROUND_KIND_LABELS) as BackgroundKind[]).map(
                (k) => ({
                  value: k as BackgroundFilter,
                  label: BACKGROUND_KIND_LABELS[k],
                }),
              ),
            ]}
          />
        )}
 
        <ChipGroup<TimeFilter>
          label="Time range"
          value={timeFilter}
          onChange={setTimeFilter}
          options={[
            { value: "all", label: "All time" },
            { value: "today", label: "Today" },
            { value: "week", label: "7d" },
            { value: "month", label: "30d" },
          ]}
        />
 
        {settledItems.length > 0 && (
          <span className="text-xs text-gray-400 dark:text-gray-500 shrink-0 ml-1">
            {eventCount} event
            {settledItems.length !== 1 || hasMore ? "s" : ""}
          </span>
        )}
      </div>
 
      {/* Main Content — a fixed-height pane beside a fixed-height panel, each
          scrolling on its own, so opening an event far down the feed shows
          its detail beside it rather than back at the top of the page. */}
      <div
        className={`grid gap-4 h-[calc(100dvh-8rem)] min-h-[520px] ${
          !selectedItem ? "grid-cols-1" : "grid-cols-5"
        }`}
      >
        {/* Feed */}
        <div
          className={`${
            !selectedItem ? "col-span-1" : "col-span-2"
          } min-h-0 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 shadow-sm overflow-hidden flex flex-col`}
        >
          <div className="px-3 py-2.5 border-b border-gray-100 dark:border-gray-700 flex items-center gap-2 shrink-0">
            <Activity className="size-3.5 text-gray-500 dark:text-gray-400" />
            <span className="text-xs font-semibold text-gray-600 dark:text-gray-400">
              Activity
            </span>
            <span className="text-[10px] text-gray-400 dark:text-gray-500 hidden sm:inline">
              runs, LLM calls, evaluation runs, resource changes,
              generative invocations and background work
            </span>
            <span className="ml-auto text-[10px] text-gray-400 dark:text-gray-500 tabular-nums">
              {eventCount}
            </span>
          </div>
 
          <div
            ref={feedScrollRef}
            role="region"
            aria-label="Activity feed"
            className="flex-1 min-h-0 overflow-y-auto p-2"
          >
            {loading ? (
              <div className="space-y-1 p-1">
                {Array.from({ length: 8 }).map((_, i) => (
                  <div
                    key={i}
                    className="flex items-start gap-3 px-3 py-2.5 animate-pulse"
                  >
                    <Skeleton className="size-2 rounded-full mt-1.5 shrink-0" />
                    <div className="flex-1 space-y-1.5">
                      <Skeleton className="h-3 w-24" />
                      <Skeleton className="h-2.5 w-48" />
                      <Skeleton className="h-2 w-32" />
                    </div>
                  </div>
                ))}
              </div>
            ) : pageItems.length === 0 && page > knownPages ? (
              <div className="flex items-center justify-center gap-2 py-12 text-xs text-gray-400 dark:text-gray-500">
                <RefreshCw className="size-3.5 animate-spin" />
                Loading older activity…
              </div>
            ) : settledItems.length === 0 ? (
              <EmptyActivity filtered={filtersActive} category={category} />
            ) : (
              feedEntries.map((entry) =>
                entry.kind === "stack" ? (
                  <ActivityStack
                    key={entry.id}
                    stackKey={entry.key}
                    items={entry.items}
                    expanded={expandedStacks.has(entry.id)}
                    onToggle={() => toggleStack(entry.id)}
                    selectedId={selectedId}
                    onSelect={toggleSelected}
                  />
                ) : (
                  <ActivityRow
                    key={entry.item.id}
                    item={entry.item}
                    selected={selectedId === entry.item.id}
                    onClick={() => toggleSelected(entry.item.id)}
                  />
                ),
              )
            )}
          </div>
 
          {!loading && (settledItems.length > 0 || hasMore) && (
            <div className="flex flex-wrap items-center gap-x-3 gap-y-1.5 px-3 py-2 border-t border-gray-100 dark:border-gray-700 shrink-0">
              <div className="min-w-0 text-[10px] text-gray-400 dark:text-gray-500">
                {pageItems.length > 0 ? (
                  <span className="tabular-nums">
                    {pageStart}–{pageStart + pageItems.length - 1} of{" "}
                    {eventCount}
                  </span>
                ) : (
                  <span>Nothing in the activity loaded so far</span>
                )}
                {retentionDays !== null &&
                  (category === "all" || category === "background") && (
                    <span className="block">
                      Background work is kept for {retentionDays} day
                      {retentionDays !== 1 ? "s" : ""}.
                    </span>
                  )}
              </div>
              <div className="ml-auto">
                <Pagination
                  label="Activity pages"
                  page={page}
                  pageCount={knownPages}
                  hasMore={hasMore}
                  loading={fetchingMore}
                  onPageChange={goToPage}
                />
              </div>
            </div>
          )}
        </div>
 
        {/* Detail Panel */}
        {selectedItem && (
          <div className="col-span-3 min-h-0">
            <ActivityDetail
              item={selectedItem}
              onClose={() => setSelectedId(null)}
              onOpenRun={openRun}
              onOpenResource={openResource}
              runExists={runExists}
              canOpenResource={canOpenResource}
            />
          </div>
        )}
      </div>
    </MainPage>
  );
};
 
export default ActivityPage;