All files / src/apps/user/pages/evaluation components.tsx

91.21% Statements 374/410
79.83% Branches 380/476
83.5% Functions 167/200
91.94% Lines 331/360

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                                                                                                                                                                                    26x     495x         988x   26x 12x   12x       26x 154x             26x 39x 34x 34x       26x 27x 22x 15x 1x 1x 1x             26x 17x 13x       26x 43x 15x 8x 1x       26x     10x 9x 7x 6x 3x 3x 2x 2x 1x                     26x 37x 34x 34x     26x       11x 4x 4x 3x               26x                 26x   55x                 26x     14x                 26x       60x 3x                 57x         60x             26x     7x 1x                 6x                                       26x                 26x                             26x       14x                     26x       2x                           26x 29x 28x 22x 22x                     26x     12x 10x                         10x                                                                             26x               26x     5x 2x     2x                                                                           26x     5x                                                 5x                               26x     2x                       2x                 26x           208x                       26x 4x             26x       2x 2x                               26x         8x 7x   6x   8x           8x                                                                           8x 1x   6x 1x           6x     39x                               26x     26x   26x           4717x                         26x     166x                                           26x         22x 15x 3x   22x 22x                         26x               6x 6x 6x 2x   6x 6x 6x 6x   6x                     1x             6x                                   1x         1x       2x                                                     1x                                               30x                                                           26x 19x   26x                     19x 19x   19x 1x             19x           19x       40x     1x                                   1x         2x                 3x                           32x                                                                   26x       1x                     1x                                 1x                                                 26x 33x         26x 18x                 26x       12x                                 26x     26x               26x         8x 8x 8x                                                                                                                                                   26x                       53x 53x 53x           53x 1x     53x 4x     53x             78x           63x                 84x       1x                                                                                                                           8x                                                                 26x         85x                                                                                   26x       18x 18x   6x   18x   48x 18x   18x               2x                     24x                                             26x         18x 18x   18x 5x 5x       18x                                                         1x                                                   26x 3x 3x   1x   3x 4x 3x       26x 2x                                     26x 3x 2x     26x           26x                               3x           9x                   26x           7x 1x           6x     8x               3x     1x                                                 26x       249x 249x   249x 1x 1x 1x   249x 1x 1x 1x   1x     249x     3x         1x                   1x                                               26x           317x 41x 317x     117x           40x                   1x                               3x                             26x     248x                     26x 4x   6x 5x               26x       247x 47x 247x     52x           28x             6x                           2x                           26x       247x 12x 247x     34x                   11x                                               1x           1x                   26x 4x 3x 2x             26x 1x   2x                                         26x 146x 44x 44x                   26x                             26x 6x 6x 5x 5x 7x 6x     6x 5x 1x 5x 5x               26x       247x 8x 247x     63x           6x             2x                                                                   1x                     26x 6x   6x                               26x     1x   2x                                                                   26x     1x       1x                                                                 26x       247x 53x 247x     54x                     15x                     1x                                     37x             1x                     26x       250x   4x                                               1x   2x             2x                   1x                                   26x       1x                 1x                                                                 26x         1x                   1x                                      
/**
 * Shared UI primitives for the evaluation section.
 *
 * The evaluation workbench, the dataset page and the Quick try scratchpad
 * all show the same things — a target, a scorer, a score, a pass/fail
 * verdict, a progress bar — so they are defined once here rather than
 * drifting apart in three viewers.
 */
 
import { makerLabel, modelMaker } from "@/objects/modelOrigin";
import { Model, modelDisplayName, selectableModels } from "@/objects/Model";
import { Agent, CostProfileInfo } from "@/objects/Agent";
import { formatUsd } from "@/components/cost/format";
import {
  CaseExample,
  CaseFact,
  CriterionItem,
  CriterionPassRate,
  CriterionVerdict,
  DEFAULT_PASS_MARK,
  ToolCall,
  ToolFixture,
  EvaluationScorer,
  EvaluationStatus,
  ContextMessage,
  MAX_CASE_EXAMPLES,
  EvaluationTarget,
  MODEL_EFFORT_LEVELS,
  ModelEffortLevel,
  RegressionCaseDelta,
  RegressionMetric,
  RegressionReport,
  RegressionVerdict,
  RunSummary,
  RunnableStatus,
  ScorerConfigField,
  ScorerInfo,
  SuspectLabel,
  InconsistentCase,
  TestCase,
} from "@/objects/Evaluation";
import {
  AlertTriangle,
  ArrowRightLeft,
  Bot,
  BrainCog,
  Check,
  ChevronDown,
  ExternalLink,
  Minus,
  Network,
  TrendingDown,
  TrendingUp,
  X,
} from "lucide-react";
import { useScorerCatalogue } from "@/hooks/useScorerCatalogue";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQuery } from "@tanstack/react-query";
import React from "react";
import { Link } from "react-router-dom";
import {
  EVALUATION_STATUS,
  GATE_STATUS,
  MetaGrid,
  MetaItem,
  REGRESSION_VERDICT,
  RUN_STATUS,
  SectionCard as DetailSectionCard,
  SectionCardProps,
  encodeResourceId,
  Skeleton,
  StatusBadge,
} from "@/components/detail";
import { PromotionGate } from "@/services/api/routers/EvaluationRouter";
import { parseServerDate } from "@/util/time";
 
// Re-exported so the evaluation pages keep importing their primitives from
// one place; it needs no specialisation, unlike SectionCard below.
export { Skeleton };
 
/**
 * The evaluation pages' panel: `components/detail`'s `SectionCard` with the
 * section's stacked-card spacing applied.
 *
 * Evaluations, datasets and comparisons all render a column of panels, so
 * the gap between them belongs to the section rather than to each of its ten
 * call sites.
 */
export const SectionCard: React.FC<SectionCardProps> = ({
  className = "",
  ...props
}) => <DetailSectionCard {...props} className={`mb-4 ${className}`.trim()} />;
 
// ─── Formatting ───────────────────────────────────────────────────────────────
 
/** One line per item, for the must-contain / must-not-contain editors. */
export const lines = (value: string[] | undefined): string =>
  (value ?? []).join("\n");
export const parseLines = (text: string): string[] =>
  text
    .split("\n")
    .map((line) => line.trim())
    .filter(Boolean);
 
/** Render a 0–1 score as a percentage, or an em dash when unscored. */
export const formatScore = (value: number | null | undefined): string =>
  typeof value === "number" ? `${Math.round(value * 100)}%` : "—";
 
/**
 * How far a 0–1 score moved between repeats, in percentage points ("± 4
 * pts") — points, not percent, because "± 4%" of a 60% score reads as a
 * relative change. Empty when there were no repeats to measure.
 */
export const formatSpread = (sd: number | null | undefined): string => {
  if (typeof sd !== "number" || !Number.isFinite(sd)) return "";
  const points = sd * 100;
  return `± ${points < 1 ? points.toFixed(1) : Math.round(points)} pts`;
};
 
/** Render a millisecond duration compactly (940ms, 3.2s, 1m 04s). */
export const formatDuration = (ms: number | null | undefined): string => {
  if (typeof ms !== "number" || ms < 0) return "—";
  if (ms < 1000) return `${Math.round(ms)}ms`;
  if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;
  const minutes = Math.floor(ms / 60_000);
  const seconds = Math.round((ms % 60_000) / 1000);
  return `${minutes}m ${String(seconds).padStart(2, "0")}s`;
};
 
/**
 * Render a cost in USD: an em dash when unknown (never "$0" — an unpriced
 * model is not free), otherwise as every page writes spend (`formatUsd`).
 */
export const formatCost = (usd: number | null | undefined): string => {
  if (typeof usd !== "number" || !Number.isFinite(usd)) return "—";
  return formatUsd(usd);
};
 
/** Render a token count compactly (812, 4.2k, 1.1M). */
export const formatTokens = (n: number | null | undefined): string => {
  if (typeof n !== "number") return "—";
  if (n < 1000) return String(n);
  if (n < 1_000_000) return `${(n / 1000).toFixed(1)}k`;
  return `${(n / 1_000_000).toFixed(1)}M`;
};
 
/** The label to show for a target, whichever way it was configured. */
export const targetLabel = (
  target: EvaluationTarget | null | undefined,
): string => {
  if (!target) return "Not configured";
  if (target.label) return target.label;
  if (target.agent_name) return target.agent_name;
  if (target.provider && target.model)
    return `${makerLabel(target.provider, target.model)} · ${target.model}`;
  if (target.model) return target.model;
  Iif (target.agent_id) return "Agent";
  if (target.swarm_id) return "Swarm";
  return "Not configured";
};
 
/** Signed percentage-point delta between two 0–1 rates. */
/**
 * A timestamp as local text, or an em dash.
 *
 * Absent is a real state — a batch row carries no `created_at` until it is
 * inserted — and `new Date(null)` renders "Invalid Date" rather than admitting
 * that.
 */
export const formatTimestamp = (value: string | null | undefined): string => {
  if (!value) return "—";
  const date = parseServerDate(value);
  return Number.isNaN(date.getTime()) ? "—" : date.toLocaleString();
};
 
export const formatDelta = (
  current: number | null | undefined,
  previous: number | null | undefined,
): { text: string; tone: "up" | "down" | "flat" } | null => {
  if (typeof current !== "number" || typeof previous !== "number") return null;
  const points = Math.round((current - previous) * 100);
  if (points === 0) return { text: "±0 pts", tone: "flat" };
  return {
    text: `${points > 0 ? "+" : ""}${points} pts`,
    tone: points > 0 ? "up" : "down",
  };
};
 
// ─── Badges ───────────────────────────────────────────────────────────────────
 
const PILL = "text-[10px] font-medium px-1.5 py-0.5 rounded-full border";
 
/**
 * An evaluation's lifecycle status (draft / active / archived).
 *
 * A named binding of the shared `StatusBadge` to the evaluation scale, so
 * the eleven call sites across the evaluation pages say what they mean
 * without each repeating which vocabulary the status belongs to.
 */
export const EvalStatusBadge: React.FC<{ status: EvaluationStatus }> = ({
  status,
}) => <StatusBadge status={status} scale={EVALUATION_STATUS} size="sm" />;
 
/**
 * One run's outcome. Distinct from {@link EvalStatusBadge} because
 * `completed` means "it succeeded" for a run and merely "it is over" for a
 * lifecycle — see `RUN_STATUS` in `components/detail/StatusBadge`.
 *
 * A run with no status yet has not started, so it reads as queued.
 */
export const RunStatusBadge: React.FC<{
  status: RunnableStatus | null | undefined;
}> = ({ status }) => (
  <StatusBadge status={status ?? "queued"} scale={RUN_STATUS} size="sm" />
);
 
/**
 * A 0–1 score rendered as a colour-coded percentage.
 *
 * The colour encodes the same thresholds a reader would apply by eye, so a
 * matrix of scores is scannable without reading every number.
 */
export const ScoreBadge: React.FC<{
  value: number | null | undefined;
  className?: string;
}> = ({ value, className = "" }) => {
  if (typeof value !== "number") {
    return (
      <span
        className={`${PILL} border-transparent text-gray-300 dark:text-gray-600 ${className}`}
      >
        —
      </span>
    );
  }
  const tone =
    value >= 0.8
      ? "bg-green-50 dark:bg-green-950/40 text-green-700 dark:text-green-300 border-green-200 dark:border-green-800"
      : value >= 0.5
        ? "bg-amber-50 dark:bg-amber-950/40 text-amber-700 dark:text-amber-300 border-amber-200 dark:border-amber-800"
        : "bg-red-50 dark:bg-red-950/40 text-red-700 dark:text-red-300 border-red-200 dark:border-red-800";
  return (
    <span className={`${PILL} font-mono tabular-nums ${tone} ${className}`}>
      {formatScore(value)}
    </span>
  );
};
 
export const PassBadge: React.FC<{ passed: boolean | null | undefined }> = ({
  passed,
}) => {
  if (passed === null || passed === undefined) {
    return (
      <span
        title="Not scored"
        className="inline-flex items-center justify-center size-5 rounded-full bg-gray-50 dark:bg-gray-800 text-gray-300 dark:text-gray-600"
      >
        <Minus className="size-3" />
      </span>
    );
  }
  return passed ? (
    <span
      title="Passed"
      className="inline-flex items-center justify-center size-5 rounded-full bg-green-50 dark:bg-green-950/40 text-green-600 dark:text-green-400"
    >
      <Check className="size-3" />
    </span>
  ) : (
    <span
      title="Failed"
      className="inline-flex items-center justify-center size-5 rounded-full bg-red-50 dark:bg-red-950/40 text-red-600 dark:text-red-400"
    >
      <X className="size-3" />
    </span>
  );
};
 
// ─── Regression ───────────────────────────────────────────────────────────────
 
/** Verdict wording that says what happened, not which enum member it is. */
const VERDICT_LABELS: Record<RegressionVerdict, string> = {
  regressed: "Regressed",
  improved: "Improved",
  unchanged: "No change",
  no_baseline: "First run",
  incomparable: "Not comparable",
};
 
const VERDICT_ICONS: Record<RegressionVerdict, React.ElementType | undefined> =
  {
    regressed: TrendingDown,
    improved: TrendingUp,
    unchanged: Minus,
    no_baseline: undefined,
    incomparable: undefined,
  };
 
/**
 * How a run compared to its baseline.
 *
 * Reads the verdict the backend reached rather than recomputing it here: the
 * tolerance that decides whether a 1-point drop is noise belongs to the suite,
 * and two implementations of that judgement would eventually disagree.
 */
export const RegressionBadge: React.FC<{
  verdict: RegressionVerdict | null | undefined;
  size?: "xs" | "sm";
}> = ({ verdict, size = "sm" }) =>
  verdict ? (
    <StatusBadge
      status={verdict}
      scale={REGRESSION_VERDICT}
      icon={VERDICT_ICONS[verdict]}
      label={VERDICT_LABELS[verdict]}
      size={size}
    />
  ) : null;
 
/** A promotion gate's verdict. */
export const GateBadge: React.FC<{
  status: PromotionGate["status"];
  size?: "xs" | "sm";
}> = ({ status, size = "sm" }) => (
  <StatusBadge
    status={status}
    scale={GATE_STATUS}
    label={
      status === "clear"
        ? "Gate clear"
        : status === "blocked"
          ? "Gate blocked"
          : "Not measured"
    }
    size={size}
  />
);
 
const metricValue = (value: number | null, key: string): string => {
  if (value === null) return "—";
  if (key === "mean_latency_ms") return `${Math.round(value)} ms`;
  Iif (key === "tokens_per_case") return `${Math.round(value)} tok`;
  return value.toFixed(3);
};
 
/**
 * Every tracked metric, before and after.
 *
 * Non-gating metrics are shown in the same table rather than hidden: a prompt
 * that scores the same for twice the tokens is something a reader should see,
 * even though it is not a reason to block anything. The `gating` column is what
 * distinguishes "worse" from "worse in a way that counts".
 */
export const RegressionMetrics: React.FC<{ metrics: RegressionMetric[] }> = ({
  metrics,
}) => {
  if (metrics.length === 0) return null;
  return (
    <div className="overflow-x-auto">
      <table className="w-full text-xs">
        <thead className="text-gray-400 dark:text-gray-500">
          <tr className="text-left">
            <th className="font-medium py-1 pr-3">Metric</th>
            <th className="font-medium py-1 pr-3 text-right">Baseline</th>
            <th className="font-medium py-1 pr-3 text-right">This run</th>
            <th className="font-medium py-1 text-right">Change</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-gray-100 dark:divide-gray-800">
          {metrics.map((metric) => (
            <tr key={metric.key}>
              <td className="py-1.5 pr-3 text-gray-700 dark:text-gray-300">
                {metric.label}
                {!metric.gating && (
                  <span
                    title="Reported, but never blocks a promotion"
                    className="ml-1.5 text-[10px] text-gray-400 dark:text-gray-500"
                  >
                    (informational)
                  </span>
                )}
              </td>
              <td className="py-1.5 pr-3 text-right font-mono tabular-nums text-gray-500 dark:text-gray-400">
                {metricValue(metric.baseline, metric.key)}
              </td>
              <td className="py-1.5 pr-3 text-right font-mono tabular-nums text-gray-700 dark:text-gray-300">
                {metricValue(metric.current, metric.key)}
              </td>
              <td
                className={`py-1.5 text-right font-mono tabular-nums ${
                  metric.regressed
                    ? "text-red-600 dark:text-red-400"
                    : metric.improved
                      ? "text-green-600 dark:text-green-400"
                      : "text-gray-400 dark:text-gray-500"
                }`}
              >
                {metric.delta === null
                  ? "—"
                  : `${metric.delta > 0 ? "+" : ""}${metricValue(metric.delta, metric.key)}`}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};
 
const CASE_KIND_LABELS: Record<RegressionCaseDelta["kind"], string> = {
  broke: "Now failing",
  fixed: "Now passing",
  score_drop: "Lower score",
  score_gain: "Higher score",
};
 
/** Per-case movement, worst first. */
export const RegressionCases: React.FC<{
  cases: RegressionReport["cases"];
}> = ({ cases }) => {
  if (cases.deltas.length === 0) return null;
  return (
    <ul className="space-y-1">
      {cases.deltas.map((delta) => (
        <li
          key={delta.case_id}
          className="flex items-center gap-2 text-xs py-1 border-b border-gray-100 dark:border-gray-800 last:border-0"
        >
          <PassBadge passed={delta.baseline_passed} />
          <ArrowRightLeft className="size-3 text-gray-300 dark:text-gray-600 shrink-0" />
          <PassBadge passed={delta.current_passed} />
          <span className="text-gray-700 dark:text-gray-300 truncate flex-1">
            {delta.case_name ?? delta.case_id}
          </span>
          <span
            className={`text-[10px] shrink-0 ${
              delta.kind === "broke" || delta.kind === "score_drop"
                ? "text-red-600 dark:text-red-400"
                : "text-green-600 dark:text-green-400"
            }`}
          >
            {CASE_KIND_LABELS[delta.kind]}
          </span>
          <ScoreBadge value={delta.current_score} />
        </li>
      ))}
      {cases.truncated && (
        <li className="text-[10px] text-gray-400 dark:text-gray-500 pt-1">
          Showing the most significant changes only.
        </li>
      )}
    </ul>
  );
};
 
/**
 * The whole comparison: verdict, why, what else changed, and the numbers.
 *
 * `target_changed` and `dataset_changed` are shown as context rather than as
 * caveats that excuse the verdict — a model swap that scores worse is exactly
 * what this is for.
 */
export const RegressionReportView: React.FC<{
  report: RegressionReport;
}> = ({ report }) => (
  <div className="space-y-3">
    <div className="flex items-center gap-2 flex-wrap">
      <RegressionBadge verdict={report.verdict} />
      {report.baseline && (
        <span className="text-xs text-gray-500 dark:text-gray-400">
          against {report.baseline.label ?? "the previous run"}
          {report.baseline.finished_at &&
            ` · ${formatTimestamp(report.baseline.finished_at)}`}
        </span>
      )}
      {report.target_changed && (
        <span className="text-[10px] text-amber-600 dark:text-amber-400">
          target changed
        </span>
      )}
      {report.dataset_changed && (
        <span className="text-[10px] text-amber-600 dark:text-amber-400">
          dataset changed
        </span>
      )}
    </div>
 
    {report.reasons.length > 0 && (
      <ul className="text-xs text-gray-600 dark:text-gray-400 space-y-0.5 list-disc list-inside">
        {report.reasons.map((reason) => (
          <li key={reason}>{reason}</li>
        ))}
      </ul>
    )}
 
    <RegressionMetrics metrics={report.metrics} />
    <RegressionCases cases={report.cases} />
  </div>
);
 
/**
 * What the gate makes of promoting a variant, shown before the decision.
 *
 * An `unmeasured` gate is rendered as a warning rather than as silence: the
 * promotion is allowed, and the reader should know nothing checked it.
 */
export const PromotionGateView: React.FC<{ gate: PromotionGate }> = ({
  gate,
}) => (
  <div className="space-y-2">
    <div className="flex items-center gap-2 flex-wrap">
      <GateBadge status={gate.status} />
      {gate.control && (
        <span className="text-xs text-gray-500 dark:text-gray-400">
          against {gate.control.variant_name}
          {gate.batch?.label && ` in ${gate.batch.label}`}
        </span>
      )}
    </div>
    <ul className="text-xs text-gray-600 dark:text-gray-400 space-y-0.5 list-disc list-inside">
      {gate.reasons.map((reason) => (
        <li key={reason}>{reason}</li>
      ))}
    </ul>
    <RegressionMetrics metrics={gate.metrics} />
  </div>
);
 
// ─── Layout ───────────────────────────────────────────────────────────────────
 
export const EmptyBlock: React.FC<{
  icon: React.ElementType;
  message: string;
  hint?: string;
  action?: React.ReactNode;
}> = ({ icon: Icon, message, hint, action }) => (
  <div className="flex flex-col items-center justify-center py-8 text-center">
    <Icon className="size-6 text-gray-200 dark:text-gray-600 mb-2" />
    <p className="text-sm text-gray-400 dark:text-gray-500">{message}</p>
    {hint && (
      <p className="text-xs text-gray-400 dark:text-gray-500 mt-1 max-w-md">
        {hint}
      </p>
    )}
    {action && <div className="mt-3">{action}</div>}
  </div>
);
 
export const ErrorNote: React.FC<{ message: string }> = ({ message }) => (
  <div className="flex items-start gap-2 rounded-lg border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-950/30 px-3 py-2 text-xs text-red-700 dark:text-red-300">
    <AlertTriangle className="size-3.5 shrink-0 mt-0.5" />
    <span className="min-w-0 break-words">{message}</span>
  </div>
);
 
/** Determinate progress bar for an in-flight run. */
export const ProgressBar: React.FC<{ completed: number; total: number }> = ({
  completed,
  total,
}) => {
  const pct = total > 0 ? Math.min(100, (completed / total) * 100) : 0;
  return (
    <div className="flex items-center gap-2">
      <div className="flex-1 h-1.5 rounded-full bg-gray-100 dark:bg-gray-700 overflow-hidden">
        <div
          className="h-full rounded-full bg-blue-500 transition-[width] duration-500"
          style={{ width: `${pct}%` }}
        />
      </div>
      <span className="text-[10px] font-mono tabular-nums text-gray-400 dark:text-gray-500 shrink-0">
        {completed}/{total}
      </span>
    </div>
  );
};
 
/** The headline numbers of a finished run. */
export const SummaryStrip: React.FC<{
  summary: RunSummary | null | undefined;
  /** The previous run's summary, to show a regression delta against. */
  previous?: RunSummary | null;
}> = ({ summary, previous }) => {
  if (!summary) return null;
  if (summary.error) return <ErrorNote message={summary.error} />;
 
  const delta = formatDelta(summary.pass_rate, previous?.pass_rate);
  const deltaTone =
    delta?.tone === "up"
      ? "text-green-600 dark:text-green-400"
      : delta?.tone === "down"
        ? "text-red-600 dark:text-red-400"
        : "text-gray-400 dark:text-gray-500";
 
  const cells: { label: string; value: React.ReactNode }[] = [
    {
      label: "Pass rate",
      value: (
        <span className="flex items-baseline gap-1.5">
          {formatScore(summary.pass_rate)}
          {delta && (
            <span className={`text-[10px] font-normal ${deltaTone}`}>
              {delta.text}
            </span>
          )}
        </span>
      ),
    },
    {
      label: "Mean score",
      value: (
        <span className="flex items-baseline gap-1.5">
          {formatScore(summary.mean_score)}
          {summary.score_sd != null && (
            <span
              className="text-[10px] font-normal text-gray-500 dark:text-gray-400"
              title="How far the mean score moved between repeats (standard deviation)"
            >
              {formatSpread(summary.score_sd)}
            </span>
          )}
        </span>
      ),
    },
    {
      label: "Passed",
      value: `${summary.passed}/${summary.total}`,
    },
    { label: "Avg latency", value: formatDuration(summary.mean_latency_ms) },
    { label: "Tokens", value: formatTokens(summary.total_tokens) },
    { label: "Duration", value: formatDuration(summary.duration_ms) },
  ];
  if (summary.errors > 0) {
    cells.splice(3, 0, { label: "Errors", value: String(summary.errors) });
  }
  if ((summary.repeats ?? 1) > 1) {
    cells.push(
      { label: "Repeats", value: `×${summary.repeats}` },
      { label: "Consistent", value: formatScore(summary.consistency) },
    );
  }
 
  return (
    <div className="flex flex-wrap gap-x-6 gap-y-3 rounded-xl bg-gray-50 dark:bg-gray-800/60 border border-gray-100 dark:border-gray-700 px-4 py-3">
      {cells.map((cell) => (
        <div key={cell.label}>
          <div className="text-[10px] uppercase tracking-wide font-medium text-gray-400 dark:text-gray-500">
            {cell.label}
          </div>
          <div className="text-sm font-semibold text-gray-800 dark:text-gray-200 tabular-nums">
            {cell.value}
          </div>
        </div>
      ))}
    </div>
  );
};
 
// ─── Form controls ────────────────────────────────────────────────────────────
 
export const inputCls =
  "w-full rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 px-3 py-2 text-sm text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-400 dark:focus:ring-gray-500";
 
export const labelCls =
  "block text-xs font-medium text-gray-600 dark:text-gray-400 mb-1";
 
export const Field: React.FC<{
  label: string;
  hint?: string;
  children: React.ReactNode;
  className?: string;
}> = ({ label, hint, children, className = "" }) => (
  <div className={className}>
    <label className={labelCls}>
      {label}
      {hint && (
        <span className="ml-1.5 font-normal text-gray-400 dark:text-gray-500">
          {hint}
        </span>
      )}
    </label>
    {children}
  </div>
);
 
export const Select: React.FC<
  React.SelectHTMLAttributes<HTMLSelectElement>
> = ({ className = "", children, ...props }) => (
  <div className="relative">
    <select
      {...props}
      className={`${inputCls} appearance-none pr-8 ${className}`}
    >
      {children}
    </select>
    <ChevronDown className="pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 size-3.5 text-gray-400" />
  </div>
);
 
// ─── Target picker ────────────────────────────────────────────────────────────
 
/**
 * Choose what an evaluation invokes: a model (with its own inference config)
 * or one of the user's agents (which brings its tools and knowledge).
 *
 * Defaults to temperature 0 — evaluation is only meaningful when a re-run of
 * the same prompt is comparable to the last one.
 */
/** The model a variant will actually run on: an agent's override, else its
 *  own model, else the chosen model. Null when it cannot be told. */
export const effectiveModel = (
  target: EvaluationTarget | null,
  models: Model[],
  agents: Agent[],
): Model | null => {
  if (!target) return null;
  const agent = target.agent_id
    ? agents.find((a) => a.id === target.agent_id)
    : undefined;
  const id = target.model_id ?? agent?.model_id ?? null;
  return (id && models.find((m) => m.id === id)) || null;
};
 
/**
 * A variant's settings — the same list whatever it runs on.
 *
 * Every one is an override: blank keeps the base's own. An agent can also be
 * switched onto another model, so "this agent on three models" is three
 * variants of one agent. Controls the effective model does not honour are
 * disabled with the reason, because svc-ai drops them silently — a
 * temperature on a model that rejects it would look like a setting and
 * change nothing.
 */
export const VariantSettings: React.FC<{
  value: EvaluationTarget;
  onChange: (target: EvaluationTarget) => void;
  models: Model[];
  agents: Agent[];
  /** `GET /app/agents/cost-profiles`. Empty hides the setting. */
  costProfiles?: CostProfileInfo[];
}> = ({ value, onChange, models, agents, costProfiles = [] }) => {
  const isAgent = !!value.agent_id;
  const agent = isAgent ? agents.find((a) => a.id === value.agent_id) : null;
  const ownModel = agent?.model_id
    ? models.find((m) => m.id === agent.model_id)
    : undefined;
  const model = effectiveModel(value, models, agents);
  const noTemperature = model?.supports_temperature === false;
  const noEffort = model?.supports_effort === false;
  const set = (patch: Partial<EvaluationTarget>) => onChange({ ...value, ...patch });
 
  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
      {isAgent && (
        <Field
          label="Model"
          hint="run the agent on another model; blank keeps its own"
          className="sm:col-span-2"
        >
          <Select
            aria-label="Model"
            value={value.model_id ?? ""}
            onChange={(e) => set({ model_id: e.target.value || null })}
          >
            <option value="">
              Agent&apos;s own
              {ownModel ? ` — ${modelDisplayName(ownModel)}` : ""}
            </option>
            {selectableModels(models, value.model_id).map((m) => (
              <option key={m.id} value={m.id}>
                {modelMaker(m)} ·{" "}
                {modelDisplayName(m)}
                {m.is_available ? "" : " (not available here)"}
              </option>
            ))}
          </Select>
        </Field>
      )}
      {isAgent && costProfiles.length > 0 && (
        <Field
          label="Cost profile"
          hint="how much work each answer does; blank keeps the agent's own"
          className="sm:col-span-2"
        >
          <Select
            aria-label="Cost profile"
            value={value.cost_profile ?? ""}
            onChange={(e) => set({ cost_profile: e.target.value || null })}
          >
            <option value="">
              Agent&apos;s own
              {agent?.cost_profile
                ? ` — ${costProfiles.find((p) => p.key === agent.cost_profile)?.label ?? agent.cost_profile}`
                : ""}
            </option>
            {costProfiles.map((p) => (
              <option key={p.key} value={p.key}>
                {p.label}
                {p.measured ? "" : " (not yet measured)"}
              </option>
            ))}
          </Select>
        </Field>
      )}
      <Field
        label="Temperature"
        hint={
          noTemperature
            ? `${model ? modelDisplayName(model) : "This model"} does not take temperature — use effort`
            : "blank keeps the default; 0 = most repeatable"
        }
      >
        <input
          type="number"
          min={0}
          max={2}
          step={0.1}
          aria-label="Temperature"
          disabled={noTemperature}
          className={`${inputCls} disabled:opacity-50`}
          placeholder="default"
          value={value.temperature ?? ""}
          onChange={(e) =>
            set({
              temperature: e.target.value === "" ? null : Number(e.target.value),
            })
          }
        />
      </Field>
      <Field
        label="Effort"
        hint={
          noEffort
            ? `${model ? modelDisplayName(model) : "This model"} does not take an effort level`
            : "how hard a reasoning model thinks"
        }
      >
        <Select
          aria-label="Effort"
          disabled={noEffort}
          value={value.effort ?? ""}
          onChange={(e) =>
            set({ effort: (e.target.value || null) as ModelEffortLevel | null })
          }
        >
          <option value="">Default</option>
          {MODEL_EFFORT_LEVELS.map((level) => (
            <option key={level} value={level}>
              {level}
            </option>
          ))}
        </Select>
      </Field>
      <Field label="Max tokens" hint="blank keeps the default">
        <input
          type="number"
          min={1}
          max={32000}
          step={128}
          aria-label="Max tokens"
          className={inputCls}
          placeholder="default"
          value={value.max_tokens ?? ""}
          onChange={(e) =>
            set({
              max_tokens: e.target.value === "" ? null : Number(e.target.value),
            })
          }
        />
      </Field>
    </div>
  );
};
 
type TargetKind = "model" | "agent" | "swarm";
 
/** What kind of target a variant runs on. */
export const targetKind = (value: EvaluationTarget | null | undefined): TargetKind =>
  value?.type === "swarm" ? "swarm" : value?.agent_id ? "agent" : "model";
 
export const TargetPicker: React.FC<{
  value: EvaluationTarget | null;
  onChange: (target: EvaluationTarget | null) => void;
  models: Model[];
  agents: Agent[];
  /** The workspace's swarms, where a swarm may be the target; omit where it
   *  may not (a judge, Quick try). */
  swarms?: { id: string; name: string }[];
  /** Label for the "nothing selected" option; omit to require a choice. */
  placeholder?: string;
}> = ({ value, onChange, models, agents, swarms, placeholder }) => {
  const kind = targetKind(value);
  const offered = selectableModels(models, value?.model_id);
 
  const setKind = (next: TargetKind) =>
    onChange(
      next === "swarm"
        ? { type: "swarm", swarm_id: swarms?.[0]?.id ?? "" }
        : next === "agent"
          ? { type: "agent", agent_id: agents[0]?.id ?? "" }
          : { type: "model", model_id: selectableModels(models)[0]?.id ?? "" },
    );
  const kinds = [
    { key: "model" as const, label: "Model", Icon: BrainCog },
    { key: "agent" as const, label: "Agent", Icon: Bot },
    ...(swarms ? [{ key: "swarm" as const, label: "Swarm", Icon: Network }] : []),
  ];
 
  return (
    <div className="space-y-3">
      <div className="flex gap-2">
        {kinds.map(({ key, label, Icon }) => (
          <button
            key={key}
            type="button"
            onClick={() => setKind(key)}
            className={`flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg border transition-colors ${
              kind === key
                ? "border-gray-900 dark:border-white bg-gray-900 dark:bg-white text-white dark:text-gray-900"
                : "border-gray-200 dark:border-gray-600 text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700"
            }`}
          >
            <Icon className="size-3.5" />
            {label}
          </button>
        ))}
      </div>
 
      {kind === "swarm" ? (
        <Select
          aria-label="Swarm"
          value={value?.swarm_id ?? ""}
          onChange={(e) =>
            onChange(e.target.value ? { type: "swarm", swarm_id: e.target.value } : null)
          }
        >
          <option value="">{placeholder ?? "Select a swarm…"}</option>
          {(swarms ?? []).map((s) => (
            <option key={s.id} value={s.id}>
              {s.name}
            </option>
          ))}
        </Select>
      ) : kind === "model" ? (
        <Select
          value={value?.model_id ?? ""}
          onChange={(e) =>
            onChange(
              e.target.value
                ? {
                    ...value,
                    type: "model",
                    agent_id: null,
                    model_id: e.target.value,
                  }
                : null,
            )
          }
        >
          <option value="">{placeholder ?? "Select a model…"}</option>
          {offered.map((m) => (
            <option key={m.id} value={m.id}>
              {modelMaker(m)} ·{" "}
              {modelDisplayName(m)}
              {m.is_available ? "" : " (not available here)"}
            </option>
          ))}
        </Select>
      ) : (
        <Select
          value={value?.agent_id ?? ""}
          onChange={(e) =>
            onChange(
              e.target.value
                ? { type: "agent", agent_id: e.target.value }
                : null,
            )
          }
        >
          <option value="">{placeholder ?? "Select an agent…"}</option>
          {agents.map((a) => (
            <option key={a.id} value={a.id}>
              {a.name}
            </option>
          ))}
        </Select>
      )}
 
    </div>
  );
};
 
/** A swarm variant's settings: its budget and time cap a case, else the
 *  swarm's own defaults. A swarm has no model, prompt, knowledge or tools of
 *  its own to vary — its agents answer as they are. */
export const SwarmVariantSettings: React.FC<{
  value: EvaluationTarget;
  onChange: (target: EvaluationTarget) => void;
}> = ({ value, onChange }) => (
  <div className="grid gap-3 sm:grid-cols-2">
    <Field label="Budget a case ($)" hint="blank uses the swarm's own">
      <input
        aria-label="Budget a case"
        type="number"
        min={0.05}
        step={0.05}
        className={inputCls}
        placeholder="the swarm's"
        value={value.budget_usd ?? ""}
        onChange={(e) =>
          onChange({
            ...value,
            budget_usd: e.target.value === "" ? null : Number(e.target.value),
          })
        }
      />
    </Field>
    <Field label="Time cap a case (minutes)" hint="blank uses the swarm's own">
      <input
        aria-label="Time cap a case"
        type="number"
        min={5}
        max={480}
        className={inputCls}
        placeholder="the swarm's"
        value={value.time_cap_s != null ? Math.round(value.time_cap_s / 60) : ""}
        onChange={(e) =>
          onChange({
            ...value,
            time_cap_s: e.target.value === "" ? null : Number(e.target.value) * 60,
          })
        }
      />
    </Field>
    <p className="sm:col-span-2 text-[11px] text-gray-400 dark:text-gray-500">
      Each case is one whole run of the swarm, unattended — no plan to approve,
      no questions — and its answer is what is graded. Its spend is this
      evaluation's.
    </p>
  </div>
);
 
/**
 * Where an evaluation lives, and where a dataset lives.
 *
 * One definition each. There were five: the list page, the reports table,
 * Quick try's save and both viewers each spelled out the same
 * `APP_ROUTES…replace(ROUTE_PARAMS…, encodeResourceId(id))`, so renaming
 * either route meant finding all five. Here rather than beside the create
 * modal, because the viewers link to an evaluation without having any
 * business importing a modal they never render.
 */
export const experimentHref = (id: string) =>
  APP_ROUTES.USER.GOVERNANCE.EVALUATION.EXPERIMENTS.id.replace(
    ROUTE_PARAMS.EXPERIMENT.id,
    encodeResourceId(id),
  );
 
export const datasetHref = (id: string) =>
  APP_ROUTES.USER.GOVERNANCE.EVALUATION.DATASETS.id.replace(
    ROUTE_PARAMS.DATASET.id,
    encodeResourceId(id),
  );
 
/**
 * A dataset's pass mark — the mean score that passes it — marked when it is
 * the platform default rather than one the dataset sets.
 */
export const PassMark: React.FC<{
  value: number | null | undefined;
  className?: string;
}> = ({ value, className = "" }) => (
  <span
    className={`font-mono tabular-nums ${className}`}
    title="The mean score a model or agent must reach to pass this dataset"
  >
    {(value ?? DEFAULT_PASS_MARK).toFixed(2)}
    {value == null && (
      <span className="font-sans text-gray-400 dark:text-gray-500">
        {" "}
        (default)
      </span>
    )}
  </span>
);
 
// ─── Scorer picker ────────────────────────────────────────────────────────────
 
/** Where the long-form explanation of every scorer lives. */
export const SCORER_DOCS_HREF = `${import.meta.env.VITE_PUBLIC_DOMAIN}/docs/guides/evaluations#scorers`;
 
/** Read a config value as lines of text, tolerating the legacy string form. */
const asLines = (value: unknown): string =>
  Array.isArray(value)
    ? (value as string[]).join("\n")
    : typeof value === "string"
      ? value
      : "";
 
/** One setting, rendered from the catalogue's description of it. */
const ScorerConfigControl: React.FC<{
  field: ScorerConfigField;
  value: unknown;
  onChange: (value: unknown) => void;
}> = ({ field, value, onChange }) => {
  Eif (field.type === "boolean") {
    const checked = (value ?? field.default ?? false) === true;
    return (
      <label className="flex items-start gap-2 cursor-pointer">
        <input
          type="checkbox"
          checked={checked}
          onChange={(e) => onChange(e.target.checked)}
          className="mt-0.5 size-3.5 rounded border-gray-300 dark:border-gray-600 accent-gray-900 dark:accent-white"
        />
        <span className="text-xs text-gray-700 dark:text-gray-300">
          {field.label}
          {field.hint && (
            <span className="block text-gray-400 dark:text-gray-500">
              {field.hint}
            </span>
          )}
        </span>
      </label>
    );
  }
 
  return (
    <Field label={field.label} hint={field.hint}>
      {field.type === "lines" ? (
        <textarea
          rows={3}
          className={`${inputCls} resize-none font-mono`}
          placeholder={field.placeholder}
          value={asLines(value)}
          onChange={(e) =>
            onChange(
              e.target.value
                .split("\n")
                .map((line) => line.trim())
                .filter(Boolean),
            )
          }
        />
      ) : field.type === "textarea" ? (
        <textarea
          rows={3}
          className={`${inputCls} resize-none`}
          placeholder={field.placeholder}
          value={(value as string) ?? ""}
          onChange={(e) => onChange(e.target.value)}
        />
      ) : (
        <input
          className={`${inputCls} font-mono`}
          placeholder={field.placeholder}
          value={(value as string) ?? ""}
          onChange={(e) => onChange(e.target.value)}
        />
      )}
    </Field>
  );
};
 
/**
 * Choose how outputs are graded, and configure the chosen scorer.
 *
 * Everything shown — the choices, their labels, the one-line "when to use",
 * the explanation of how the number is arrived at, and which settings to
 * render — comes from `GET /app/evaluations/scorers`. The picker holds no
 * list of its own, so a scorer added to svc-core's registry appears here
 * explained, and a scorer retired from it stops being offered without a
 * frontend release.
 *
 * Two things are deliberate. A **score nobody can explain is not evidence**,
 * so the selected scorer always says how it computes its number and what it
 * needs from the dataset, with the deeper nuances a click away rather than
 * squeezed into a hint. And where the cases are known, the picker says
 * *before the run* how many of them the scorer cannot grade — that used to
 * be discovered as a column of nulls after paying for the run.
 */
export const ScorerPicker: React.FC<{
  scorer: EvaluationScorer;
  config: Record<string, unknown>;
  onChange: (scorer: EvaluationScorer, config: Record<string, unknown>) => void;
  /** The cases this scorer will grade, when the caller knows them. */
  cases?: Pick<TestCase, "expected_output">[];
  /** Which model grades, for the LLM judge. Null means the platform default. */
  judge?: EvaluationTarget | null;
  /** Omit to hide the judge picker entirely (a caller that cannot store one). */
  onJudgeChange?: (judge: EvaluationTarget | null) => void;
}> = ({ scorer, config, onChange, cases, judge, onJudgeChange }) => {
  const { byKind, grouped, default_pass_threshold, isLoading } =
    useScorerCatalogue();
  const info = byKind[scorer];
  const set = (patch: Record<string, unknown>) =>
    onChange(scorer, { ...config, ...patch });
 
  // Switching scorer drops the previous one's settings: a strict-JSON flag
  // left behind on an exact-match evaluation is invisible and would come
  // back if the user switched back, having meanwhile been forgotten.
  const select = (kind: EvaluationScorer) =>
    onChange(kind, { pass_threshold: config.pass_threshold });
 
  const missingExpected =
    info?.requires_expected && cases
      ? cases.filter((c) => !c.expected_output?.trim()).length
      : 0;
 
  return (
    <div className="space-y-3">
      <div>
        <span className={labelCls}>Scoring</span>
        {isLoading ? (
          <div className="space-y-2">
            {Array.from({ length: 3 }).map((_, i) => (
              <Skeleton key={i} className="h-11 w-full" />
            ))}
          </div>
        ) : (
          <div className="space-y-3">
            {grouped.map(({ group, scorers }) => (
              <div key={group.key}>
                <p className="text-[10px] uppercase tracking-wide font-medium text-gray-400 dark:text-gray-500 mb-1.5">
                  {group.label}
                  <span className="ml-1.5 normal-case tracking-normal font-normal">
                    {group.summary}
                  </span>
                </p>
                <div className="space-y-1.5">
                  {scorers.map((s) => (
                    <ScorerOption
                      key={s.kind}
                      info={s}
                      selected={s.kind === scorer}
                      onSelect={() => select(s.kind)}
                    />
                  ))}
                </div>
              </div>
            ))}
            {/* A superseded scorer is never offered, but an evaluation that
                already chose one must still show what it is — and say what
                to move to. */}
            {info?.superseded_by && (
              <ScorerOption info={info} selected onSelect={() => {}} />
            )}
          </div>
        )}
      </div>
 
      {info && (
        <div className="rounded-lg bg-gray-50 dark:bg-gray-700/40 px-3 py-2.5 space-y-1.5">
          <p className="text-xs text-gray-600 dark:text-gray-300 leading-relaxed">
            {info.how_it_scores}
          </p>
          <p className="text-xs text-gray-500 dark:text-gray-400">
            <span className="font-medium text-gray-600 dark:text-gray-300">
              Needs:
            </span>{" "}
            {info.needs}
          </p>
          <a
            href={SCORER_DOCS_HREF}
            target="_blank"
            rel="noreferrer"
            className="inline-flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
          >
            How scoring works
            <ExternalLink className="size-3" />
          </a>
        </div>
      )}
 
      {info?.superseded_by && (
        <WarningNote>
          This scorer has been superseded by{" "}
          <span className="font-medium">
            {byKind[info.superseded_by]?.label ?? info.superseded_by}
          </span>
          , which does the same and more. It still grades exactly as it always
          has, so runs stay comparable — switch when you next change what this
          experiment measures.
        </WarningNote>
      )}
 
      {missingExpected > 0 && (
        <WarningNote>
          {missingExpected} of {cases!.length} case
          {cases!.length === 1 ? "" : "s"} in this dataset ha
          {missingExpected === 1 ? "s" : "ve"} no expected output. This scorer
          needs one, so those cases will run and cost tokens but come back
          unscored.
        </WarningNote>
      )}
 
      {info?.config_fields.map((field) => (
        <ScorerConfigControl
          key={field.key}
          field={field}
          value={config[field.key]}
          onChange={(value) => set({ [field.key]: value })}
        />
      ))}
 
      {scorer === "llm" && onJudgeChange && (
        <JudgePicker value={judge ?? null} onChange={onJudgeChange} />
      )}
 
      {info?.uses_threshold && (
        <Field
          label="Pass mark"
          hint={`a case passes at or above this score — ${default_pass_threshold} by default`}
        >
          <input
            type="number"
            min={0}
            max={1}
            step={0.05}
            className={inputCls}
            value={(config.pass_threshold as number) ?? default_pass_threshold}
            onChange={(e) => set({ pass_threshold: Number(e.target.value) })}
          />
        </Field>
      )}
    </div>
  );
};
 
/** One choosable scorer: what it is called, and when to reach for it. */
const ScorerOption: React.FC<{
  info: ScorerInfo;
  selected: boolean;
  onSelect: () => void;
}> = ({ info, selected, onSelect }) => (
  <button
    type="button"
    role="radio"
    aria-checked={selected}
    onClick={onSelect}
    className={`w-full flex items-start gap-2.5 text-left rounded-lg border px-3 py-2 transition-colors ${
      selected
        ? "border-gray-900 dark:border-white bg-gray-50 dark:bg-gray-700/50"
        : "border-gray-200 dark:border-gray-600 hover:bg-gray-50 dark:hover:bg-gray-700/40"
    }`}
  >
    <span
      className={`mt-1 size-3 shrink-0 rounded-full border-2 ${
        selected
          ? "border-gray-900 dark:border-white bg-gray-900 dark:bg-white"
          : "border-gray-300 dark:border-gray-500"
      }`}
    />
    <span className="min-w-0">
      <span className="block text-sm font-medium text-gray-900 dark:text-gray-100">
        {info.label}
      </span>
      <span className="block text-xs text-gray-500 dark:text-gray-400">
        {info.summary}
      </span>
    </span>
  </button>
);
 
/**
 * Which model grades an LLM-judged evaluation.
 *
 * Worth choosing rather than leaving implicit: the judge is a model call per
 * answer on the user's own spend, and two models do not agree on a score —
 * so a run graded by one is not comparable with a run graded by another,
 * which is exactly what a regression verdict rests on.
 *
 * It offers no temperature: grading is pinned to 0 in svc-core whichever
 * model does it, because a judge that answers differently on a re-run turns
 * provider noise into a reported regression. Only the *identity* of the
 * grader is the user's to choose.
 */
const JudgePicker: React.FC<{
  value: EvaluationTarget | null;
  onChange: (judge: EvaluationTarget | null) => void;
}> = ({ value, onChange }) => {
  const { getApiHandler } = useApiHandler();
  const { data } = useQuery<Model[]>({
    queryKey: [QUERY_KEYS.GET.MODELS],
    queryFn: () => getApiHandler().model_router.list() as Promise<Model[]>,
  });
  const models: Model[] = data ?? [];
  // Only a chat model can grade, and only an available one can be called.
  const usable = models.filter((m) => m.is_chat && m.is_available);
  const platformDefault = usable.find((m) => m.is_default);
 
  return (
    <Field
      label="Grading model"
      hint="a run graded by one model is not comparable with a run graded by another"
    >
      <Select
        value={value?.model_id ?? ""}
        onChange={(e) =>
          onChange(
            e.target.value ? { type: "model", model_id: e.target.value } : null,
          )
        }
      >
        <option value="">
          {platformDefault
            ? `Platform default — ${modelDisplayName(platformDefault)}`
            : "Platform default"}
        </option>
        {usable.map((m) => (
          <option key={m.id} value={m.id}>
            {modelMaker(m)} ·{" "}
            {modelDisplayName(m)}
          </option>
        ))}
      </Select>
      <p className="text-xs text-gray-400 dark:text-gray-500 mt-1">
        Grading runs at temperature 0 so the same answer scores the same on a
        re-run. Judge calls are your spend, and governed by your rules.
      </p>
    </Field>
  );
};
 
/**
 * How a locked evaluation grades, read-only.
 *
 * Rendered from the same catalogue the picker is, so a scorer's settings are
 * described here in the words it declares rather than a second set that
 * drifts. Locked does not mean hidden: what an evaluation measures is the
 * thing a reader most needs to see, and it is only the *editing* that the
 * lock takes away.
 */
export const ScorerSummary: React.FC<{
  scorer: EvaluationScorer;
  config: Record<string, unknown>;
  judge?: EvaluationTarget | null;
}> = ({ scorer, config, judge }) => {
  const { byKind, default_pass_threshold, isLoading } = useScorerCatalogue();
  const info = byKind[scorer];
 
  const shown = (info?.config_fields ?? []).filter((field) => {
    const value = config[field.key];
    Eif (field.type === "boolean") return value === true;
    return Array.isArray(value) ? value.length > 0 : !!value;
  });
 
  return (
    <div className="space-y-2">
      <MetaGrid>
        <MetaItem
          label="Scoring"
          value={info?.label ?? scorer.replace(/_/g, " ")}
        />
        {info?.uses_threshold && (
          <MetaItem
            label="Pass mark"
            value={String(
              (config.pass_threshold as number) ?? default_pass_threshold,
            )}
          />
        )}
        {scorer === "llm" && (
          <MetaItem
            label="Grading model"
            value={
              judge?.model_id ? (
                <JudgeName modelId={judge.model_id} />
              ) : (
                "Platform default"
              )
            }
          />
        )}
      </MetaGrid>
      {shown.map((field) => (
        <div key={field.key} className="text-xs">
          <span className="text-gray-400 dark:text-gray-500">
            {field.label}:{" "}
          </span>
          <span className="text-gray-700 dark:text-gray-300 break-words">
            {field.type === "boolean"
              ? "on"
              : Array.isArray(config[field.key])
                ? (config[field.key] as string[]).join(", ")
                : String(config[field.key])}
          </span>
        </div>
      ))}
      {/* Only once the catalogue has answered: every scorer is unrecognised
          while it is still in flight, and saying so would be a lie that
          flashes on every load. */}
      {!info && !isLoading && (
        <p className="text-xs text-gray-400 dark:text-gray-500">
          This experiment grades with a scorer this build does not recognise.
        </p>
      )}
    </div>
  );
};
 
/** A judge's model id as its name, falling back to the id while it loads. */
const JudgeName: React.FC<{ modelId: string }> = ({ modelId }) => {
  const { getApiHandler } = useApiHandler();
  const { data } = useQuery<Model[]>({
    queryKey: [QUERY_KEYS.GET.MODELS],
    queryFn: () => getApiHandler().model_router.list() as Promise<Model[]>,
  });
  const models: Model[] = data ?? [];
  const model = models.find((m) => m.id === modelId);
  return <>{model ? modelDisplayName(model) : modelId}</>;
};
 
/** An amber aside — something that will bite at run time if left as it is. */
const WarningNote: React.FC<{ children: React.ReactNode }> = ({ children }) => (
  <div className="flex items-start gap-2 rounded-lg border border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-950/30 px-3 py-2 text-xs text-amber-800 dark:text-amber-300">
    <AlertTriangle className="size-3.5 shrink-0 mt-0.5" />
    <span className="min-w-0">{children}</span>
  </div>
);
 
// ─── Context ──────────────────────────────────────────────────────────────────
 
/**
 * What a variant may reach while it answers.
 *
 * The three-state control is the whole point and the reason this is not a
 * plain multi-select: **inherit** keeps the agent's own knowledge or tools,
 * **none** takes them away, and a list replaces them. Without the middle
 * state there is no way to ask "does this repository actually help?", which is
 * the question the feature exists for.
 */
export type ContextMode = "inherit" | "none" | "custom";
 
export const contextModeOf = (value: string[] | undefined): ContextMode => {
  if (value === undefined) return "inherit";
  return value.length === 0 ? "none" : "custom";
};
 
const MODE_LABELS: Record<ContextMode, string> = {
  inherit: "Use the agent's own",
  none: "None",
  custom: "Choose…",
};
 
export const ContextModePicker: React.FC<{
  label: string;
  hint?: string;
  mode: ContextMode;
  onModeChange: (mode: ContextMode) => void;
  /** The modes to offer. A bare model has nothing of its own to inherit. */
  modes?: ContextMode[];
  children?: React.ReactNode;
}> = ({
  label,
  hint,
  mode,
  onModeChange,
  modes = ["inherit", "none", "custom"],
  children,
}) => (
  <Field label={label} hint={hint}>
    <Select
      value={mode}
      onChange={(e) => onModeChange(e.target.value as ContextMode)}
    >
      {modes.map((option) => (
        <option key={option} value={option}>
          {MODE_LABELS[option]}
        </option>
      ))}
    </Select>
    {mode === "custom" && <div className="mt-2">{children}</div>}
  </Field>
);
 
/** A checkbox list — the picker behind a `custom` context mode. */
export const CheckList: React.FC<{
  options: { value: string; label: string; hint?: string }[];
  selected: string[];
  onChange: (selected: string[]) => void;
  emptyHint: string;
}> = ({ options, selected, onChange, emptyHint }) => {
  if (options.length === 0) {
    return (
      <p className="text-xs text-gray-400 dark:text-gray-500 italic py-2">
        {emptyHint}
      </p>
    );
  }
  return (
    <div className="max-h-40 overflow-y-auto rounded-lg border border-gray-200 dark:border-gray-700 divide-y divide-gray-100 dark:divide-gray-800">
      {options.map((option) => (
        <label
          key={option.value}
          className="flex items-center gap-2 px-3 py-2 text-xs cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/40"
        >
          <input
            type="checkbox"
            checked={selected.includes(option.value)}
            onChange={(e) =>
              onChange(
                e.target.checked
                  ? [...selected, option.value]
                  : selected.filter((v) => v !== option.value),
              )
            }
          />
          <span className="text-gray-700 dark:text-gray-300">
            {option.label}
          </span>
          {option.hint && (
            <span className="text-gray-400 dark:text-gray-500 truncate">
              {option.hint}
            </span>
          )}
        </label>
      ))}
    </div>
  );
};
 
/**
 * Name/value pairs substituted into the prompt as `{{name}}`.
 *
 * Substitution, not a language: there are no expressions, conditionals or
 * loops, because the moment there are, every prompt becomes a program and the
 * evaluation harness has a runtime nobody asked for.
 */
export const VariableEditor: React.FC<{
  variables: Record<string, string>;
  onChange: (variables: Record<string, string>) => void;
}> = ({ variables, onChange }) => {
  const rows = Object.entries(variables);
  const set = (name: string, value: string) =>
    onChange({ ...variables, [name]: value });
  const remove = (name: string) => {
    const next = { ...variables };
    delete next[name];
    onChange(next);
  };
  const rename = (from: string, to: string) => {
    const next: Record<string, string> = {};
    for (const [key, value] of Object.entries(variables)) {
      next[key === from ? to : key] = value;
    }
    onChange(next);
  };
 
  return (
    <div className="space-y-2">
      {rows.map(([name, value]) => (
        <div key={name} className="flex items-center gap-2">
          <input
            className={`${inputCls} font-mono`}
            value={name}
            placeholder="persona"
            onChange={(e) => rename(name, e.target.value)}
          />
          <input
            className={inputCls}
            value={value}
            placeholder="a frustrated customer"
            onChange={(e) => set(name, e.target.value)}
          />
          <button
            type="button"
            onClick={() => remove(name)}
            className="text-gray-400 hover:text-red-500 shrink-0"
            aria-label={`Remove ${name}`}
          >
            <X className="size-3.5" />
          </button>
        </div>
      ))}
      <button
        type="button"
        onClick={() => set(`var_${rows.length + 1}`, "")}
        className="text-xs text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
      >
        + Add variable
      </button>
    </div>
  );
};
 
/**
 * Criteria as a list: one thing a good answer does per row, each optionally
 * must-pass. Items rather than a paragraph, so the judge marks every one and
 * a result says which failed.
 */
export const CriteriaEditor: React.FC<{
  items: CriterionItem[];
  onChange: (items: CriterionItem[]) => void;
  placeholder?: string;
  label?: string;
}> = ({ items, onChange, placeholder, label = "Criterion" }) => {
  const patch = (index: number, change: Partial<CriterionItem>) =>
    onChange(items.map((c, i) => (i === index ? { ...c, ...change } : c)));
  return (
    <div className="space-y-2">
      {items.map((item, index) => (
        <div key={index} className="flex items-center gap-2">
          <input
            className={inputCls}
            value={item.text}
            placeholder={index === 0 ? placeholder : undefined}
            aria-label={`${label} ${index + 1}`}
            onChange={(e) => patch(index, { text: e.target.value })}
          />
          <label
            className="flex items-center gap-1 text-[11px] text-gray-500 dark:text-gray-400 shrink-0 cursor-pointer"
            title="Failing a must-pass criterion scores the case 0, whatever else was met"
          >
            <input
              type="checkbox"
              checked={item.gate}
              aria-label={`${label} ${index + 1} must pass`}
              onChange={(e) => patch(index, { gate: e.target.checked })}
            />
            Must pass
          </label>
          <button
            type="button"
            onClick={() => onChange(items.filter((_, i) => i !== index))}
            className="text-gray-400 hover:text-red-500 shrink-0"
            aria-label={`Remove ${label.toLowerCase()} ${index + 1}`}
          >
            <X className="size-3.5" />
          </button>
        </div>
      ))}
      <button
        type="button"
        onClick={() => onChange([...items, { text: "", gate: false }])}
        className="text-xs text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
      >
        + Add {label.toLowerCase()}
      </button>
    </div>
  );
};
 
/** One named value of a case's data, as the editor holds it. */
export interface DataRow {
  name: string;
  value: string;
}
 
export const dataToRows = (
  data: Record<string, unknown> | undefined | null,
): DataRow[] =>
  Object.entries(data ?? {}).map(([name, value]) => ({
    name,
    value:
      value === null || value === undefined
        ? ""
        : typeof value === "object"
          ? JSON.stringify(value)
          : String(value),
  }));
 
/** Rows as stored: unnamed rows dropped, an empty value is "not provided". */
export const rowsToData = (rows: DataRow[]): Record<string, string | null> =>
  Object.fromEntries(
    rows
      .filter((r) => r.name.trim())
      .map((r) => [r.name.trim(), r.value.trim() ? r.value.trim() : null]),
  );
 
/**
 * A case's data: named values shown to the agent after the prompt. Nothing
 * has to reference them, and a name with no value is shown as "not
 * provided" — which is how a case asks about missing information.
 */
export const DataEditor: React.FC<{
  rows: DataRow[];
  onChange: (rows: DataRow[]) => void;
}> = ({ rows, onChange }) => {
  const patch = (index: number, change: Partial<DataRow>) =>
    onChange(rows.map((r, i) => (i === index ? { ...r, ...change } : r)));
  return (
    <div className="space-y-2">
      {rows.map((row, index) => (
        <div key={index} className="flex items-center gap-2">
          <input
            className={`${inputCls} font-mono`}
            value={row.name}
            placeholder="investment_cost"
            aria-label={`Data ${index + 1} name`}
            onChange={(e) => patch(index, { name: e.target.value })}
          />
          <input
            className={inputCls}
            value={row.value}
            placeholder="100000 — or empty for not provided"
            aria-label={`Data ${index + 1} value`}
            onChange={(e) => patch(index, { value: e.target.value })}
          />
          <button
            type="button"
            onClick={() => onChange(rows.filter((_, i) => i !== index))}
            className="text-gray-400 hover:text-red-500 shrink-0"
            aria-label={`Remove data ${index + 1}`}
          >
            <X className="size-3.5" />
          </button>
        </div>
      ))}
      <button
        type="button"
        onClick={() => onChange([...rows, { name: "", value: "" }])}
        className="text-xs text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
      >
        + Add data
      </button>
    </div>
  );
};
 
/**
 * Scripted tools: a name, what it is for, and the response every call gets.
 * A name matching a real tool replaces it (keeping its shape); any other name
 * adds a tool — so a case about a live share price can fix the price.
 */
export const ToolFixtureEditor: React.FC<{
  fixtures: ToolFixture[];
  onChange: (fixtures: ToolFixture[]) => void;
}> = ({ fixtures, onChange }) => {
  const patch = (index: number, change: Partial<ToolFixture>) =>
    onChange(fixtures.map((f, i) => (i === index ? { ...f, ...change } : f)));
  return (
    <div className="space-y-2">
      {fixtures.map((fixture, index) => (
        <div
          key={index}
          className="rounded-lg border border-gray-200 dark:border-gray-700 p-2 space-y-2"
        >
          <div className="flex items-center gap-2">
            <input
              className={`${inputCls} font-mono`}
              value={fixture.name}
              placeholder="market_data"
              aria-label={`Scripted tool ${index + 1} name`}
              onChange={(e) => patch(index, { name: e.target.value })}
            />
            <button
              type="button"
              onClick={() => onChange(fixtures.filter((_, i) => i !== index))}
              className="text-gray-400 hover:text-red-500 shrink-0"
              aria-label={`Remove scripted tool ${index + 1}`}
            >
              <X className="size-3.5" />
            </button>
          </div>
          <input
            className={inputCls}
            value={fixture.description ?? ""}
            placeholder="What it does — shown to the agent (a real tool's own is kept)"
            aria-label={`Scripted tool ${index + 1} description`}
            onChange={(e) => patch(index, { description: e.target.value })}
          />
          <textarea
            rows={3}
            className={`${inputCls} resize-y font-mono text-xs`}
            value={fixture.response}
            placeholder='{"symbol": "NVDA", "price": 120.50, "as_of": "2026-09-23T14:30Z"}'
            aria-label={`Scripted tool ${index + 1} response`}
            onChange={(e) => patch(index, { response: e.target.value })}
          />
        </div>
      ))}
      <button
        type="button"
        onClick={() => onChange([...fixtures, { name: "", response: "" }])}
        className="text-xs text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
      >
        + Add scripted tool
      </button>
    </div>
  );
};
 
/** Scripted tools with unnamed rows dropped, ready to save. */
export const cleanFixtures = (fixtures: ToolFixture[]): ToolFixture[] =>
  fixtures
    .filter((f) => f.name.trim())
    .map((f) => ({
      name: f.name.trim(),
      response: f.response,
      ...(f.description?.trim() ? { description: f.description.trim() } : {}),
    }));
 
/** The tools an agent called during one cell, with what came back. */
export const ToolCallList: React.FC<{ calls: ToolCall[] }> = ({ calls }) => (
  <ol className="space-y-2">
    {calls.map((call, i) => (
      <li key={i} className="text-xs">
        <div className="font-mono text-gray-800 dark:text-gray-200 break-all">
          {i + 1}. {call.name}({JSON.stringify(call.args ?? {})})
        </div>
        {call.output !== null && (
          <pre
            className={`mt-0.5 whitespace-pre-wrap break-all rounded bg-gray-50 dark:bg-gray-900/40 px-2 py-1 max-h-40 overflow-auto ${
              call.error
                ? "text-red-600 dark:text-red-400"
                : "text-gray-600 dark:text-gray-400"
            }`}
          >
            {call.output}
          </pre>
        )}
      </li>
    ))}
  </ol>
);
 
/** Criteria with blank rows dropped and text trimmed, ready to save. */
export const cleanCriteria = (items: CriterionItem[]): CriterionItem[] =>
  items
    .map((i) => ({ text: i.text.trim(), gate: i.gate }))
    .filter((i) => i.text);
 
/** A fact as the editor holds it: the value as typed. */
export interface FactDraft {
  label: string;
  value: string;
  tolerance: string;
  gate: boolean;
}
 
export const factToDraft = (fact: CaseFact): FactDraft => ({
  label: fact.label ?? "",
  value: Array.isArray(fact.value) ? fact.value.join(" | ") : String(fact.value),
  tolerance:
    fact.tolerance_pct === null || fact.tolerance_pct === undefined
      ? ""
      : String(fact.tolerance_pct),
  gate: fact.gate === true,
});
 
/**
 * A fact from the editor. A value that reads as one number ("19,781",
 * "£2.2m" is left to the server) is sent as a number; "a | b" is a list of
 * accepted spellings; anything else is text.
 */
export const draftToFact = (draft: FactDraft): CaseFact | null => {
  const raw = draft.value.trim();
  if (!raw) return null;
  const plain = raw.replace(/[,£$€\s]/g, "");
  const numeric = /^-?\d+(\.\d+)?$/.test(plain) ? Number(plain) : null;
  const spellings = raw.split("|").map((v) => v.trim()).filter(Boolean);
  const fact: CaseFact = {
    value: numeric ?? (spellings.length > 1 ? spellings : raw),
  };
  if (draft.label.trim()) fact.label = draft.label.trim();
  if (draft.tolerance.trim() && numeric !== null)
    fact.tolerance_pct = Math.max(0, Number(draft.tolerance) || 0);
  if (draft.gate) fact.gate = true;
  return fact;
};
 
/**
 * Facts: what a correct answer states, checked by code. A number matches
 * anywhere in the answer however it is written ("£19,781", "19,780.99"),
 * within its tolerance; text matches any of its "|"-separated spellings.
 */
export const FactEditor: React.FC<{
  facts: FactDraft[];
  onChange: (facts: FactDraft[]) => void;
}> = ({ facts, onChange }) => {
  const patch = (index: number, change: Partial<FactDraft>) =>
    onChange(facts.map((f, i) => (i === index ? { ...f, ...change } : f)));
  return (
    <div className="space-y-2">
      {facts.map((fact, index) => (
        <div key={index} className="flex items-center gap-2 flex-wrap">
          <input
            className={`${inputCls} flex-1 min-w-[6rem]`}
            value={fact.label}
            placeholder="Label (optional)"
            aria-label={`Fact ${index + 1} label`}
            onChange={(e) => patch(index, { label: e.target.value })}
          />
          <input
            className={`${inputCls} flex-1 min-w-[6rem] font-mono`}
            value={fact.value}
            placeholder="19781 or May | Maybe"
            aria-label={`Fact ${index + 1} value`}
            onChange={(e) => patch(index, { value: e.target.value })}
          />
          <input
            type="number"
            min={0}
            step={0.5}
            className={`${inputCls} w-20`}
            value={fact.tolerance}
            placeholder="±1%"
            aria-label={`Fact ${index + 1} tolerance percent`}
            onChange={(e) => patch(index, { tolerance: e.target.value })}
          />
          <label className="flex items-center gap-1 text-[11px] text-gray-500 dark:text-gray-400 shrink-0 cursor-pointer">
            <input
              type="checkbox"
              checked={fact.gate}
              aria-label={`Fact ${index + 1} must pass`}
              onChange={(e) => patch(index, { gate: e.target.checked })}
            />
            Must pass
          </label>
          <button
            type="button"
            onClick={() => onChange(facts.filter((_, i) => i !== index))}
            className="text-gray-400 hover:text-red-500 shrink-0"
            aria-label={`Remove fact ${index + 1}`}
          >
            <X className="size-3.5" />
          </button>
        </div>
      ))}
      <button
        type="button"
        onClick={() =>
          onChange([...facts, { label: "", value: "", tolerance: "", gate: false }])
        }
        className="text-xs text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
      >
        + Add fact
      </button>
    </div>
  );
};
 
/** Criteria as a read-only list, must-pass items marked. */
export const CriteriaList: React.FC<{ items: CriterionItem[] }> = ({ items }) => (
  <ul className="space-y-1">
    {items.map((item, i) => (
      <li key={i} className="text-sm text-gray-700 dark:text-gray-300 flex gap-2">
        <span className="text-gray-400">•</span>
        <span className="flex-1 whitespace-pre-wrap">
          {item.text}
          {item.gate && (
            <span className="ml-1.5 text-[10px] uppercase tracking-wide font-medium text-amber-600 dark:text-amber-400">
              must pass
            </span>
          )}
        </span>
      </li>
    ))}
  </ul>
);
 
/** How the scorer judged each criterion and fact on one cell. */
export const CriterionVerdicts: React.FC<{ verdicts: CriterionVerdict[] }> = ({
  verdicts,
}) => (
  <ul className="space-y-1.5">
    {verdicts.map((v, i) => (
      <li key={i} className="flex gap-2 text-xs">
        <span
          className={`shrink-0 font-medium ${
            v.met
              ? "text-emerald-600 dark:text-emerald-400"
              : "text-red-600 dark:text-red-400"
          }`}
        >
          {v.met ? "Met" : "Missed"}
        </span>
        <span className="flex-1 text-gray-700 dark:text-gray-300">
          {v.text}
          {v.gate && (
            <span className="ml-1.5 text-[10px] uppercase tracking-wide font-medium text-amber-600 dark:text-amber-400">
              must pass
            </span>
          )}
          {v.source === "fact" && (
            <span className="ml-1.5 text-[10px] uppercase tracking-wide text-gray-400">
              fact
            </span>
          )}
          {v.reason && (
            <span className="block text-gray-500 dark:text-gray-400">
              {v.reason}
            </span>
          )}
        </span>
      </li>
    ))}
  </ul>
);
 
/** How often each dataset criterion was met across a run or a variant. */
export const CriterionPassRates: React.FC<{ rates: CriterionPassRate[] }> = ({
  rates,
}) => (
  <div className="overflow-x-auto">
    <table className="min-w-full text-xs">
      <tbody>
        {rates.map((rate) => (
          <tr
            key={rate.text}
            className="border-t border-gray-50 dark:border-gray-700/50"
          >
            <td className="py-1.5 pr-3 text-gray-700 dark:text-gray-300">
              {rate.text}
              {rate.gate && (
                <span className="ml-1.5 text-[10px] uppercase tracking-wide font-medium text-amber-600 dark:text-amber-400">
                  must pass
                </span>
              )}
            </td>
            <td className="py-1.5 pr-3 text-right tabular-nums text-gray-500 dark:text-gray-400 whitespace-nowrap">
              {rate.met} / {rate.total}
            </td>
            <td className="py-1.5 text-right tabular-nums whitespace-nowrap">
              <ScoreBadge value={rate.total ? rate.met / rate.total : null} />
            </td>
          </tr>
        ))}
      </tbody>
    </table>
  </div>
);
 
/**
 * A case's graded examples: answers scored in advance, each with why.
 *
 * Several points on the scale — a 1.0, a 0.5, a 0.0 — calibrate an LLM judge
 * better than one reference answer can, because the judge sees what the
 * *middle* of the scale looks like for this question. Scores are 0–1, the
 * scale every scorer reports on.
 */
export const ExampleEditor: React.FC<{
  examples: CaseExample[];
  onChange: (examples: CaseExample[]) => void;
}> = ({ examples, onChange }) => {
  const patch = (index: number, change: Partial<CaseExample>) =>
    onChange(examples.map((e, i) => (i === index ? { ...e, ...change } : e)));
  return (
    <div className="space-y-2">
      {examples.map((example, index) => (
        <div
          key={index}
          className="rounded-lg border border-gray-200 dark:border-gray-700 p-2 space-y-2"
        >
          <div className="flex items-start gap-2">
            <textarea
              rows={2}
              className={`${inputCls} resize-y`}
              value={example.output}
              placeholder="An answer to this question"
              aria-label={`Example ${index + 1} answer`}
              onChange={(e) => patch(index, { output: e.target.value })}
            />
            <input
              type="number"
              min={0}
              max={1}
              step={0.1}
              className={`${inputCls} w-20 shrink-0`}
              value={example.score}
              aria-label={`Example ${index + 1} score`}
              onChange={(e) =>
                patch(index, {
                  score: Math.max(0, Math.min(1, Number(e.target.value) || 0)),
                })
              }
            />
            <button
              type="button"
              onClick={() => onChange(examples.filter((_, i) => i !== index))}
              className="text-gray-400 hover:text-red-500 shrink-0 mt-2"
              aria-label={`Remove example ${index + 1}`}
            >
              <X className="size-3.5" />
            </button>
          </div>
          <input
            className={inputCls}
            value={example.note ?? ""}
            placeholder="Why it earns that score (shown to the judge)"
            aria-label={`Example ${index + 1} note`}
            onChange={(e) => patch(index, { note: e.target.value })}
          />
        </div>
      ))}
      {examples.length < MAX_CASE_EXAMPLES && (
        <button
          type="button"
          onClick={() => onChange([...examples, { output: "", score: 0.5 }])}
          className="text-xs text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
        >
          + Add graded example
        </button>
      )}
    </div>
  );
};
 
/** Prior turns a case starts from — "five turns into a complaint". */
export const HistoryEditor: React.FC<{
  history: ContextMessage[];
  onChange: (history: ContextMessage[]) => void;
}> = ({ history, onChange }) => (
  <div className="space-y-2">
    {history.map((message, index) => (
      <div key={index} className="flex items-start gap-2">
        <Select
          value={message.role}
          onChange={(e) =>
            onChange(
              history.map((m, i) =>
                i === index
                  ? { ...m, role: e.target.value as ContextMessage["role"] }
                  : m,
              ),
            )
          }
          className="w-32 shrink-0"
        >
          <option value="user">User</option>
          <option value="assistant">Assistant</option>
          <option value="system">System</option>
        </Select>
        <textarea
          rows={2}
          className={`${inputCls} resize-y`}
          value={message.content}
          placeholder="What was said"
          onChange={(e) =>
            onChange(
              history.map((m, i) =>
                i === index ? { ...m, content: e.target.value } : m,
              ),
            )
          }
        />
        <button
          type="button"
          onClick={() => onChange(history.filter((_, i) => i !== index))}
          className="text-gray-400 hover:text-red-500 shrink-0 mt-2"
          aria-label={`Remove turn ${index + 1}`}
        >
          <X className="size-3.5" />
        </button>
      </div>
    ))}
    <button
      type="button"
      onClick={() => onChange([...history, { role: "user", content: "" }])}
      className="text-xs text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
    >
      + Add turn
    </button>
  </div>
);
 
// ─── Suspect labels ───────────────────────────────────────────────────────────
 
/**
 * Cases every variant failed in this run.
 *
 * Not a verdict on the dataset — a prompt to look at it. When several
 * differently configured answerers all fail one case, a wrong reference
 * answer or a criterion nobody could meet is often the likelier cause, and
 * the results would otherwise blame every agent for it.
 */
export const SuspectLabels: React.FC<{
  suspects: SuspectLabel[];
  datasetId: string;
}> = ({ suspects, datasetId }) => (
  <div className="rounded-lg border border-amber-200 dark:border-amber-800/60 bg-amber-50 dark:bg-amber-900/20 p-3">
    <div className="text-xs font-medium text-amber-900 dark:text-amber-100">
      Every variant failed {suspects.length} case
      {suspects.length === 1 ? "" : "s"} — check{" "}
      {suspects.length === 1 ? "its label" : "their labels"} before blaming
      the agents
    </div>
    <ul className="mt-2 space-y-1.5">
      {suspects.map((suspect) => (
        <li
          key={suspect.case_id ?? suspect.case_name}
          className="text-xs text-amber-900/90 dark:text-amber-100/90"
        >
          <span className="font-medium">{suspect.case_name}</span>{" "}
          <span className="text-amber-700 dark:text-amber-300">
            ({suspect.answers} answers)
          </span>
          {suspect.reasons[0] && (
            <span className="block text-amber-800/80 dark:text-amber-200/80">
              {suspect.reasons[0]}
            </span>
          )}
        </li>
      ))}
    </ul>
    {datasetId && (
      <Link
        to={datasetHref(datasetId)}
        className="inline-block mt-2 text-xs font-medium text-amber-900 dark:text-amber-100 hover:underline"
      >
        Open the dataset
      </Link>
    )}
  </div>
);
 
/**
 * Cases a variant passed on some repeats and failed on others. Listed the way
 * suspect labels are — a prompt to read those answers, not a verdict: most
 * often a case at the edge of what the configuration can do, or a criterion
 * loose enough for the judge to read two ways.
 */
export const InconsistentCases: React.FC<{
  cases: InconsistentCase[];
  total: number;
  variantName: (variantId: string) => string;
}> = ({ cases, total, variantName }) => (
  <div className="rounded-lg border border-gray-200 dark:border-gray-700 p-3">
    <div className="text-xs font-medium text-gray-800 dark:text-gray-200">
      {total} answer{total === 1 ? "" : "s"} changed verdict between repeats
    </div>
    <p className="text-[11px] text-gray-500 dark:text-gray-400">
      The same variant passed and failed the same case — its score there is
      chance as much as configuration.
    </p>
    <ul className="mt-2 space-y-1">
      {cases.map((c) => (
        <li
          key={`${c.variant_id}:${c.case_id ?? c.case_name}`}
          className="text-xs text-gray-700 dark:text-gray-300"
        >
          <span className="font-medium">{c.case_name ?? "Case"}</span>
          <span className="text-gray-500 dark:text-gray-400">
            {" "}
            · {variantName(c.variant_id)} · passed {c.passed} of {c.answers}
          </span>
        </li>
      ))}
    </ul>
    {total > cases.length && (
      <p className="mt-1 text-[11px] text-gray-400 dark:text-gray-500">
        and {total - cases.length} more
      </p>
    )}
  </div>
);