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

77.14% Statements 189/245
75.69% Branches 218/288
69.66% Functions 62/89
82.27% Lines 181/220

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                                                                                                                                                                                                      2x                                                                               403x   2x 139x             2x           162x                                                         2x                   297x 297x                                                                               2x                                                         171x 171x                                                                     2x         27x                           2x           40x           40x 40x                                               2x             19x                                     2x 19x 19x                                                             2x         135x                   2x 27x                                                                                     2x             54x                                             2x                                 27x 27x                                                                                       54x                                       2x 28x                           2x       27x                                     27x                           54x                                                                                             2x       27x       27x               27x 27x 27x 27x       27x         27x   13x                                           27x     39x                                                               2x   2x 21x   2x         27x 9x   27x 27x   27x                                                 52x                                       9x                                                                                       2x   2x             2x 135x       2x         27x 27x                                                       108x                                                                 2x 27x 27x   27x   13x     27x   13x     27x       13x     27x       13x     27x       13x     27x       13x     27x   13x     27x       13x     27x                         27x       13x   27x       13x   27x   13x       27x               27x       13x     27x   13x               27x     13x               27x   13x         27x   13x       27x         13x                                   27x       27x     27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x               27x 27x 18x 27x 27x     27x 27x 27x       27x     27x 27x       27x 27x           27x   27x 12x                 27x 1x               27x 2x                                                   27x                       27x                       27x                       27x                 27x 11x               27x 14x                       27x   27x             19x 19x                   27x                   27x 4x                 27x                         27x                         27x                         27x                             27x                   27x 3x                       27x 12x                 27x   27x 27x 27x         27x   27x                                                             40x                                                       12x                                                                   4x                                                                                                                                                                                                                                                       135x                                                                                                       4x   2x                                                                                                                                                                                                                                                                                                 19x                                    
import { modelMaker } from "@/objects/modelOrigin";
import {
  LAYER_CLASSES,
  RULE_LAYERS,
  ruleLayerMeta,
} from "@/apps/user/pages/rules/ruleLayer";
import { boardIcon } from "@/components/appearance/icons";
import { Tone, TONES, toneOf } from "@/components/appearance/tones";
import GeneratedMark from "@/components/badge/GeneratedMark";
import MainPage from "@/components/page/MainPage/MainPage";
import { useSpend } from "@/components/cost";
import { useAuth } from "@/hooks/useAuth";
import { Agent } from "@/objects/Agent";
import { Dashboard } from "@/objects/Dashboard";
import { isSystemManaged } from "@/objects/Doc";
import {
  GovernanceActivityList,
  GovernanceOutcome,
  OUTCOME_HINTS,
  OUTCOME_LABELS,
} from "@/objects/Governance";
import { Knowledge, KnowledgeRepository } from "@/objects/Knowledge";
import { MCPServer } from "@/objects/MCPServer";
import { Model, isSelectableModel } from "@/objects/Model";
import { Organisation } from "@/objects/Organisation";
import { Project } from "@/objects/Project";
import { ReviewSummary } from "@/objects/Review";
import { Rule, RuleLayer } from "@/objects/Rule";
import { Skill } from "@/objects/Skill";
import { Skillset } from "@/objects/Skillset";
import { Toolkit } from "@/objects/Toolkit";
import { BatchReportTotals, Experiment, TestSuite } from "@/objects/Evaluation";
import { APP_ROUTES, ROUTE_PARAMS } from "@/routes/const";
import { UsageStats } from "@/services/api/routers/StatsRouter";
import { QUERY_KEYS } from "@/services/query_keys";
import { useApiHandler } from "@/services/useApiHandler";
import { useQueries, useQuery } from "@tanstack/react-query";
import {
  Activity,
  Bell,
  Bot,
  BrainCog,
  Building,
  ChevronRight,
  Clock,
  Coins,
  Database,
  FileStack,
  Files,
  FolderGit2,
  FlaskConical,
  FolderKanban,
  Globe,
  HardDrive,
  Info,
  Layers3,
  LayoutDashboard,
  LayoutGrid,
  Library,
  Network,
  Plug,
  Plus,
  ScrollText,
  Server,
  Shapes,
  ShieldCheck,
  TestTube,
  TrendingUp,
  TriangleAlert,
  Wrench,
  Zap,
} from "lucide-react";
import { documentsKey } from "@/apps/user/pages/knowledge/figures";
import React from "react";
import { CountUp } from "chainr-frontend-shared";
import { Link } from "react-router-dom";
import {
  GOVERNANCE_OUTCOME,
  MeterBar,
  MeterTone,
  Skeleton,
  StatusBadge,
  encodeResourceId,
} from "@/components/detail";
import { parseServerDate } from "@/util/time";
import { MCP_AVAILABLE } from "@/util/mcp";
 
// ─── Knowledge source type metadata ───────────────────────────────────────────
//
// `key` matches Knowledge.source_type, and each link is the Sources tab
// narrowed to that type — `?section=sources&type=<key>`, the grid's own filter
// rather than a page of its own.
 
const SOURCE_TYPES: {
  key: string;
  label: string;
  icon: React.ElementType;
  to: string;
  tone: Tone;
}[] = [
  {
    key: "file",
    label: "File Storage",
    icon: FileStack,
    to: APP_ROUTES.USER.KNOWLEDGE.SOURCES.file_storage,
    tone: "violet",
  },
  {
    key: "graph",
    label: "Graphs",
    icon: Network,
    to: APP_ROUTES.USER.KNOWLEDGE.SOURCES.graphs,
    tone: "blue",
  },
  {
    key: "web",
    label: "Web / URL",
    icon: Globe,
    to: APP_ROUTES.USER.KNOWLEDGE.SOURCES.web,
    tone: "emerald",
  },
  {
    key: "db",
    label: "Databases",
    icon: Database,
    to: APP_ROUTES.USER.KNOWLEDGE.SOURCES.databases,
    tone: "amber",
  },
  {
    key: "api",
    label: "APIs",
    icon: Plug,
    to: APP_ROUTES.USER.KNOWLEDGE.SOURCES.apis,
    tone: "rose",
  },
];
 
// ─── Primitives ───────────────────────────────────────────────────────────────
 
const fmt = (n: number) => n.toLocaleString();
 
const plural = (n: number, one: string, many = `${one}s`) =>
  `${fmt(n)} ${n === 1 ? one : many}`;
 
// ─── Section header ───────────────────────────────────────────────────────────
//
// Each overview section is one layer of the platform taxonomy. The blurb
// states what the layer *is* so the grouping is self-explanatory.
 
const SectionHeader: React.FC<{
  icon: React.ElementType;
  title: string;
  blurb: string;
  to: string;
}> = ({ icon: Icon, title, blurb, to }) => (
  <div className="flex items-end justify-between gap-4 mb-3">
    <div className="flex items-center gap-2.5 min-w-0">
      <div className="p-1.5 rounded-lg bg-gray-100 dark:bg-gray-700/60 shrink-0">
        <Icon className="size-4 text-gray-600 dark:text-gray-300" />
      </div>
      <div className="min-w-0">
        <h3 className="text-sm font-semibold text-gray-900 dark:text-gray-100 leading-tight">
          {title}
        </h3>
        <p className="text-xs text-gray-500 dark:text-gray-400 truncate">
          {blurb}
        </p>
      </div>
    </div>
    <Link
      to={to}
      className="shrink-0 flex items-center gap-1 text-xs font-medium text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors"
    >
      View all
      <ChevronRight className="size-3" />
    </Link>
  </div>
);
 
// ─── Resource card ────────────────────────────────────────────────────────────
//
// A top-level resource: the things an agent is built from. `meta` names what a
// bundle contains, making the bundle → member relationship visible up front.
 
const ResourceCard: React.FC<{
  icon: React.ElementType;
  label: string;
  blurb: string;
  count: number;
  to: string;
  loading: boolean;
  tone: Tone;
  meta?: React.ReactNode;
}> = ({ icon: Icon, label, blurb, count, to, loading, tone, meta }) => {
  const t = TONES[tone];
  return (
    <Link
      to={to}
      className="group flex flex-col rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-4 shadow-sm hover:shadow-md hover:border-gray-300 dark:hover:border-gray-500 transition-all"
    >
      <div className="flex items-start justify-between mb-3">
        <div className={`p-1.5 rounded-lg ${t.bg}`}>
          <Icon className={`size-4 ${t.fg}`} />
        </div>
        <ChevronRight className="size-3.5 text-gray-300 dark:text-gray-600 group-hover:text-gray-500 dark:group-hover:text-gray-400 transition-colors" />
      </div>
 
      <div className="text-2xl font-bold text-gray-900 dark:text-gray-100 tabular-nums leading-none">
        {loading ? (
          <Skeleton className="inline-block w-10 h-6" />
        ) : (
          <CountUp start={0} end={count} duration={1.2} />
        )}
      </div>
      <div className="text-sm font-medium text-gray-800 dark:text-gray-200 mt-1">
        {label}
      </div>
      <p className="text-xs text-gray-500 dark:text-gray-400 mt-0.5 leading-snug">
        {blurb}
      </p>
 
      {meta !== undefined && (
        <div className="mt-3 pt-2.5 border-t border-gray-100 dark:border-gray-700/80 text-[11px] text-gray-500 dark:text-gray-400">
          {loading ? <Skeleton className="h-3 w-24" /> : meta}
        </div>
      )}
    </Link>
  );
};
 
// ─── Member row ───────────────────────────────────────────────────────────────
//
// A building block — something that only reaches an agent through the bundle
// above it. Rendered flat and inset so it never reads as a peer of a bundle.
 
const MemberRow: React.FC<{
  icon: React.ElementType;
  label: string;
  note?: string;
  count: number;
  to: string;
  loading: boolean;
  tone: Tone;
  /** Count of members not in any bundle — unusable by agents until grouped. */
  loose?: number;
  looseLabel?: string;
  /** Draws the sparkle when the row *is* one resource — a board, say. A row
   *  standing for a whole class of resource ("Skills", "Tools") has no single
   *  provenance to report, so it leaves this unset. */
  generated?: boolean | null;
  generatedLabel?: string;
}> = ({
  icon: Icon,
  label,
  note,
  count,
  to,
  loading,
  tone,
  loose = 0,
  looseLabel = "unbundled",
  generated,
  generatedLabel = "AI generated",
}) => {
  const t = TONES[tone];
  return (
    <Link
      to={to}
      className="group flex items-center gap-2.5 rounded-lg px-2.5 py-2 hover:bg-white dark:hover:bg-gray-800 border border-transparent hover:border-gray-200 dark:hover:border-gray-700 transition-all"
    >
      <GeneratedMark generated={generated} size="sm" label={generatedLabel}>
        <div className={`p-1 rounded-md ${t.bg} shrink-0`}>
          <Icon className={`size-3 ${t.fg}`} />
        </div>
      </GeneratedMark>
      <span className="text-xs font-medium text-gray-700 dark:text-gray-300 truncate">
        {label}
      </span>
      {note && (
        <span className="text-[11px] text-gray-400 dark:text-gray-500 truncate hidden lg:inline">
          {note}
        </span>
      )}
      {!loading && loose > 0 && (
        <span
          className="shrink-0 rounded-full bg-amber-50 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 px-1.5 py-px text-[10px] font-medium"
          title={`${loose} not in any bundle — agents can't use these yet`}
        >
          {loose} {looseLabel}
        </span>
      )}
      <span className="ml-auto shrink-0 text-xs font-semibold text-gray-800 dark:text-gray-100 tabular-nums">
        {loading ? <Skeleton className="inline-block w-5 h-3.5" /> : fmt(count)}
      </span>
      <ChevronRight className="size-3 shrink-0 text-gray-300 dark:text-gray-600 group-hover:text-gray-500 dark:group-hover:text-gray-400 transition-colors" />
    </Link>
  );
};
 
/** Tray holding the building blocks that compose the cards above it. */
const MemberTray: React.FC<{
  caption: string;
  children: React.ReactNode;
  className?: string;
}> = ({ caption, children, className = "" }) => (
  <div
    className={`rounded-xl border border-dashed border-gray-200 dark:border-gray-700 bg-gray-50/70 dark:bg-gray-800/30 p-3 ${className}`}
  >
    <p className="text-[10px] uppercase tracking-wider text-gray-400 dark:text-gray-500 font-semibold mb-1.5 px-1">
      {caption}
    </p>
    <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-1">{children}</div>
  </div>
);
 
// ─── Notifications ────────────────────────────────────────────────────────────
 
type NotificationType = "info" | "warning" | "tip";
 
const NotificationItem: React.FC<{
  type: NotificationType;
  title: string;
  description: string;
  action?: { label: string; to: string };
}> = ({ type, title, description, action }) => {
  const styles: Record<NotificationType, string> = {
    info: "bg-blue-50 dark:bg-blue-950/40 border-blue-200 dark:border-blue-800 text-blue-800 dark:text-blue-200",
    warning:
      "bg-amber-50 dark:bg-amber-950/40 border-amber-200 dark:border-amber-800 text-amber-800 dark:text-amber-200",
    tip: "bg-emerald-50 dark:bg-emerald-950/40 border-emerald-200 dark:border-emerald-800 text-emerald-800 dark:text-emerald-200",
  };
  const Icon = type === "warning" ? TriangleAlert : type === "tip" ? Zap : Info;
  return (
    <div
      className={`flex items-start gap-3 rounded-lg border px-4 py-3 text-sm ${styles[type]}`}
    >
      <Icon className="size-4 mt-0.5 shrink-0" />
      <div className="flex-1 min-w-0">
        <span className="font-semibold">{title}</span>
        {description && <span className="ml-1 opacity-80">{description}</span>}
      </div>
      {action && (
        <Link
          to={action.to}
          className="shrink-0 flex items-center gap-1 font-semibold underline underline-offset-2 hover:opacity-70 transition-opacity"
        >
          {action.label}
          <ChevronRight className="size-3" />
        </Link>
      )}
    </div>
  );
};
 
// ─── Recent activity ──────────────────────────────────────────────────────────
 
const ActivityRow: React.FC<{
  icon: React.ElementType;
  label: string;
  name: string;
  date: string;
  to: string;
}> = ({ icon: Icon, label, name, date, to }) => (
  <Link
    to={to}
    className="group flex items-center gap-3 py-2.5 border-b border-gray-100 dark:border-gray-700 last:border-0 hover:bg-gray-50 dark:hover:bg-gray-800/50 rounded px-2 -mx-2 transition-colors"
  >
    <div className="p-1.5 rounded-md bg-gray-100 dark:bg-gray-700 shrink-0">
      <Icon className="size-3.5 text-gray-500 dark:text-gray-400" />
    </div>
    <div className="flex-1 min-w-0">
      <div className="text-sm font-medium text-gray-800 dark:text-gray-200 truncate">
        {name}
      </div>
      <div className="text-xs text-gray-400 dark:text-gray-500">{label}</div>
    </div>
    <div className="text-xs text-gray-400 dark:text-gray-500 shrink-0">
      {date}
    </div>
  </Link>
);
 
const formatDate = (iso?: string) => {
  Iif (!iso) return "—";
  return parseServerDate(iso).toLocaleDateString(undefined, {
    month: "short",
    day: "numeric",
    year: "numeric",
  });
};
 
function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
 
function formatRelativeDate(iso: string): string {
  const diff = Date.now() - parseServerDate(iso).getTime();
  const mins = Math.floor(diff / 60000);
  if (mins < 1) return "just now";
  if (mins < 60) return `${mins}m ago`;
  const hrs = Math.floor(mins / 60);
  if (hrs < 24) return `${hrs}h ago`;
  const days = Math.floor(hrs / 24);
  if (days < 30) return `${days}d ago`;
  return parseServerDate(iso).toLocaleDateString(undefined, {
    day: "numeric",
    month: "short",
    year: "numeric",
  });
}
 
// ─── Quick actions ────────────────────────────────────────────────────────────
 
const QuickAction: React.FC<{
  icon: React.ElementType;
  label: string;
  to: string;
}> = ({ icon: Icon, label, to }) => (
  <Link
    to={to}
    className="flex items-center gap-2.5 px-3 py-2 rounded-lg border border-dashed border-gray-300 dark:border-gray-600 text-sm text-gray-600 dark:text-gray-400 hover:border-gray-500 dark:hover:border-gray-400 hover:text-gray-900 dark:hover:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-800 transition-all"
  >
    <Plus className="size-3.5 shrink-0 text-gray-400" />
    <Icon className="size-3.5 shrink-0" />
    <span>{label}</span>
  </Link>
);
 
const QuickActionsCard: React.FC = () => (
  <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-5 shadow-sm h-full">
    <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
      Quick Actions
    </h3>
    <div className="flex flex-col gap-2">
      <QuickAction
        icon={Bot}
        label="New Agent"
        to={APP_ROUTES.USER.INFERENCE.AGENTS.new}
      />
      <QuickAction
        icon={Layers3}
        label="New Skillset"
        to={APP_ROUTES.USER.INFERENCE.skillsets}
      />
      {MCP_AVAILABLE && (
        <QuickAction
          icon={Wrench}
          label="New Toolkit"
          to={APP_ROUTES.USER.INFERENCE.toolkits}
        />
      )}
      <QuickAction
        icon={FolderGit2}
        label="New Repository"
        to={APP_ROUTES.USER.KNOWLEDGE.repositories}
      />
      <QuickAction
        icon={Library}
        label="New Knowledge Source"
        to={APP_ROUTES.USER.KNOWLEDGE.new}
      />
      <QuickAction
        icon={FolderKanban}
        label="New Project"
        to={APP_ROUTES.USER.PROJECTS.new}
      />
    </div>
  </div>
);
 
// ─── Token usage ──────────────────────────────────────────────────────────────
 
const UsageBar: React.FC<{
  label: string;
  value: number;
  allTime: number;
  tone: MeterTone;
  loading: boolean;
}> = ({ label, value, allTime, tone, loading }) => (
  <div>
    <div className="flex justify-between text-xs text-gray-500 dark:text-gray-400 mb-1">
      <span>{label}</span>
      {loading ? (
        <Skeleton className="w-24 h-3" />
      ) : (
        <span className="font-mono">
          {fmt(value)}
          <span className="text-gray-300 dark:text-gray-600 ml-1">
            / {fmt(allTime)} total
          </span>
        </span>
      )}
    </div>
    <MeterBar
      share={allTime > 0 ? value / allTime : 0}
      tone={tone}
      loading={loading}
      label={label}
    />
  </div>
);
 
const TokenUsageCard: React.FC<{
  loading: boolean;
  thisMonth: {
    input_tokens: number;
    output_tokens: number;
    total_tokens: number;
    invocation_count: number;
  } | null;
  allTime: {
    input_tokens: number;
    output_tokens: number;
    total_tokens: number;
    invocation_count: number;
  } | null;
}> = ({ loading, thisMonth, allTime }) => {
  // Spend from the usage ledger, as every cost card and the Stats page read
  // it — svc-ai's own sum counted unpriced calls as nothing.
  const spend = useSpend({ period: "this_month" });
  return (
  <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-5 shadow-sm h-full">
    <div className="flex items-center gap-2 mb-4">
      <Coins className="size-4 text-gray-500" />
      <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
        Token Usage
      </h3>
      <span className="ml-auto text-xs text-gray-400 dark:text-gray-500 bg-gray-100 dark:bg-gray-700 px-2 py-0.5 rounded-full">
        This month
      </span>
    </div>
 
    <div className="space-y-3">
      <UsageBar
        label="Input tokens"
        value={thisMonth?.input_tokens ?? 0}
        allTime={allTime?.input_tokens ?? 0}
        tone="info"
        loading={loading}
      />
      <UsageBar
        label="Output tokens"
        value={thisMonth?.output_tokens ?? 0}
        allTime={allTime?.output_tokens ?? 0}
        tone="accent"
        loading={loading}
      />
    </div>
 
    <div className="mt-4 pt-3 border-t border-gray-100 dark:border-gray-700 grid grid-cols-2 gap-3">
      {[
        {
          label: "Invocations",
          value: loading ? null : fmt(thisMonth?.invocation_count ?? 0),
        },
        {
          label: spend.label,
          value: spend.isLoading
            ? null
            : spend.figure
              ? spend.figure.text
              : "—",
        },
      ].map(({ label, value }) => (
        <div key={label}>
          <div className="text-[10px] uppercase tracking-wide text-gray-400 dark:text-gray-500 font-medium">
            {label}
          </div>
          {value === null ? (
            <Skeleton className="h-4 w-16 mt-0.5" />
          ) : (
            <div className="text-sm font-semibold text-gray-800 dark:text-gray-100 mt-0.5">
              {value}
            </div>
          )}
        </div>
      ))}
    </div>
  </div>
  );
};
 
// ─── Trace counts ─────────────────────────────────────────────────────────────
 
const avgRange = (avg: number | null, std: number | null) => {
  Eif (avg === null) return "—";
  if (std === null) return avg.toFixed(1);
  return `${avg.toFixed(1)} ± ${std.toFixed(1)}`;
};
 
interface TracePeriod {
  llm_invocation_count: number;
  tool_invocation_count: number;
  avg_llm_per_conversation: number | null;
  stddev_llm_per_conversation: number | null;
  avg_tool_per_conversation: number | null;
  stddev_tool_per_conversation: number | null;
}
 
const TraceCountsCard: React.FC<{
  loading: boolean;
  thisMonth: TracePeriod | null;
}> = ({ loading, thisMonth }) => {
  const rows = [
    {
      icon: BrainCog,
      label: "LLM invocations",
      count: thisMonth?.llm_invocation_count ?? 0,
      avg: thisMonth?.avg_llm_per_conversation ?? null,
      std: thisMonth?.stddev_llm_per_conversation ?? null,
      tone: "blue" as Tone,
    },
    {
      icon: Wrench,
      label: "Tool invocations",
      count: thisMonth?.tool_invocation_count ?? 0,
      avg: thisMonth?.avg_tool_per_conversation ?? null,
      std: thisMonth?.stddev_tool_per_conversation ?? null,
      tone: "amber" as Tone,
    },
  ];
 
  return (
    <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-5 shadow-sm h-full flex flex-col">
      <div className="flex items-center gap-2 mb-4">
        <TrendingUp className="size-4 text-gray-500" />
        <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
          Trace Counts
        </h3>
        <span className="ml-auto text-xs text-gray-400 dark:text-gray-500 bg-gray-100 dark:bg-gray-700 px-2 py-0.5 rounded-full">
          This month
        </span>
      </div>
 
      <div className="space-y-4 flex-1">
        {rows.map((row) => (
          <div key={row.label}>
            <div className="flex items-center gap-2 mb-1">
              <div className={`p-1 rounded-md ${TONES[row.tone].bg} shrink-0`}>
                <row.icon className={`size-3 ${TONES[row.tone].fg}`} />
              </div>
              <span className="text-xs text-gray-500 dark:text-gray-400 flex-1 truncate">
                {row.label}
              </span>
              {loading ? (
                <Skeleton className="w-10 h-4" />
              ) : (
                <span className="text-sm font-bold text-gray-900 dark:text-gray-100 tabular-nums">
                  {fmt(row.count)}
                </span>
              )}
            </div>
            <div className="ml-6 flex items-baseline gap-1">
              {loading ? (
                <Skeleton className="w-28 h-3" />
              ) : (
                <>
                  <span className="text-xs font-semibold text-gray-700 dark:text-gray-300 tabular-nums">
                    {avgRange(row.avg, row.std)}
                  </span>
                  {row.avg !== null && (
                    <span className="text-[10px] text-gray-400 dark:text-gray-500">
                      per conversation
                    </span>
                  )}
                </>
              )}
            </div>
          </div>
        ))}
      </div>
 
      <div className="mt-4 pt-3 border-t border-gray-100 dark:border-gray-700">
        <p className="text-[10px] text-gray-400 dark:text-gray-500">
          Avg ± std. dev. across all conversations this month
        </p>
      </div>
    </div>
  );
};
 
// ─── File storage strip ───────────────────────────────────────────────────────
 
const FileStorageStrip: React.FC<{
  fileKbs: Knowledge[];
  knowledgeLoading: boolean;
}> = ({ fileKbs, knowledgeLoading }) => {
  const { getApiHandler } = useApiHandler();
 
  // `useQueries` keeps the hook count stable as `fileKbs` resolves — a plain
  // `useQuery` per item would change hook order between renders.
  const docQueries = useQueries({
    queries: fileKbs.map((kb) => ({
      queryKey: documentsKey(kb.id),
      queryFn: () => getApiHandler().knowledge_router.listDocuments(kb.id),
      staleTime: 60_000,
    })),
  });
 
  const loading = knowledgeLoading || docQueries.some((q) => q.isLoading);
  const allDocs = docQueries.flatMap((q) => q.data ?? []);
  const totalFiles = allDocs.length;
  const totalBytes = allDocs.reduce(
    (sum, d) => sum + (d.document_metadata?.size_bytes ?? 0),
    0,
  );
  const latestUpload = allDocs.reduce<string | null>(
    (acc, d) => (!acc || d.created_at > acc ? d.created_at : acc),
    null,
  );
 
  if (fileKbs.length === 0 && !loading) return null;
 
  const cells = [
    {
      icon: Files,
      label: "Files",
      value: loading ? null : fmt(totalFiles),
    },
    {
      icon: HardDrive,
      label: "Size",
      value: loading ? null : totalFiles > 0 ? formatBytes(totalBytes) : "—",
    },
    {
      icon: Clock,
      label: "Last upload",
      value: loading
        ? null
        : latestUpload
          ? formatRelativeDate(latestUpload)
          : "—",
    },
  ];
 
  return (
    <div className="mt-3 pt-3 border-t border-gray-100 dark:border-gray-700 grid grid-cols-3 gap-2">
      {cells.map(({ icon: Icon, label, value }) => (
        <div
          key={label}
          className="flex flex-col gap-1 px-2 py-2 rounded-lg bg-gray-50 dark:bg-gray-700/40"
        >
          <div className="flex items-center gap-1 text-[9px] uppercase tracking-wide text-gray-400 dark:text-gray-500 font-medium">
            <Icon className="size-2.5 shrink-0" />
            {label}
          </div>
          {value === null ? (
            <Skeleton className="h-3 w-10 mt-0.5" />
          ) : (
            <div className="text-xs font-semibold text-gray-800 dark:text-gray-200 truncate">
              {value}
            </div>
          )}
        </div>
      ))}
    </div>
  );
};
 
// ─── Boards ───────────────────────────────────────────────────────────────────
//
// The boards themselves, not just how many there are. A dashboard is the one
// resource on this page somebody opens to *read* rather than to configure, so
// the summary's job is to land them in the right board in one click — a count
// alone would send them to the list to pick one.
//
// The home board leads; the rest keep the order the Dashboards page shows
// them in, which `Array.prototype.sort` preserves within each group.
 
/** Boards shown before the row turns into "and N more". */
const BOARD_PREVIEW = 6;
 
const boardHref = (board: Dashboard) =>
  APP_ROUTES.USER.DASHBOARDS.id.replace(ROUTE_PARAMS.DASHBOARD.id, board.id);
 
const BoardList: React.FC<{
  boards: Dashboard[];
  loading: boolean;
  className?: string;
}> = ({ boards, loading, className = "" }) => {
  const ordered = [...boards].sort(
    (a, b) => Number(b.is_home) - Number(a.is_home),
  );
  const shown = ordered.slice(0, BOARD_PREVIEW);
  const widgets = boards.reduce((sum, b) => sum + (b.widget_count ?? 0), 0);
 
  return (
    <div
      className={`rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-4 shadow-sm ${className}`.trim()}
    >
      <div className="flex items-center justify-between gap-2 mb-2">
        <div className="flex items-baseline gap-2 min-w-0">
          <h4 className="text-sm font-medium text-gray-800 dark:text-gray-200">
            Your boards
          </h4>
          <span className="text-xs text-gray-400 dark:text-gray-500 truncate">
            open one straight from here
          </span>
        </div>
        <span className="text-sm font-semibold text-gray-900 dark:text-gray-100 tabular-nums shrink-0">
          {loading ? (
            <Skeleton className="inline-block w-6 h-4" />
          ) : (
            plural(widgets, "widget")
          )}
        </span>
      </div>
 
      {loading ? (
        <div className="grid sm:grid-cols-2 gap-1">
          {[0, 1, 2, 3].map((i) => (
            <Skeleton key={i} className="h-8" />
          ))}
        </div>
      ) : shown.length === 0 ? (
        <div className="py-6 text-center">
          <p className="text-sm text-gray-400 dark:text-gray-500">
            No boards yet.
          </p>
          <Link
            to={APP_ROUTES.USER.dashboards}
            className="mt-1 inline-flex items-center gap-1 text-xs font-medium text-blue-600 dark:text-blue-400 hover:underline"
          >
            <Plus className="size-3" />
            Compose one
          </Link>
        </div>
      ) : (
        <>
          <div className="grid sm:grid-cols-2 gap-1">
            {shown.map((board) => (
              <MemberRow
                key={board.id}
                icon={boardIcon(board.icon)}
                label={board.name}
                note={board.is_home ? "home board" : undefined}
                count={board.widget_count ?? 0}
                to={boardHref(board)}
                loading={false}
                tone={toneOf(board.accent)}
                generated={board.is_ai_generated}
                generatedLabel="AI generated dashboard"
              />
            ))}
          </div>
          {ordered.length > shown.length && (
            <Link
              to={APP_ROUTES.USER.dashboards}
              className="mt-2 inline-flex items-center gap-1 text-[11px] text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors"
            >
              {plural(ordered.length - shown.length, "more board")}
              <ChevronRight className="size-3" />
            </Link>
          )}
        </>
      )}
    </div>
  );
};
 
// ─── Rule activity ────────────────────────────────────────────────────────────
//
// The last day of rule evaluations, split by what each one came to.
//
// The two reassuring outcomes sit beside the two that ask for attention on
// purpose. A redaction rule that ran over a clean prompt has done its job, and
// a summary counting only blocks would report a well-governed fleet as an idle
// one — which is the question the Activity log was built to answer.
//
// Every cell is a link into Governance → Rules → Activity already narrowed to
// that slice: the log holds its filters in the URL, so a deep link lands on the
// rows behind the number rather than on the unfiltered backlog.
 
/** The window the card reports, in days. Matches the Governance tab's own
 *  badge, so the two agree and share one cached response. */
const ACTIVITY_WINDOW_DAYS = 1;
 
const OUTCOME_ORDER: GovernanceOutcome[] = [
  "applied",
  "blocked",
  "no_change",
  "not_matched",
];
 
const activityHref = (outcome?: GovernanceOutcome) =>
  `${APP_ROUTES.USER.GOVERNANCE.activity}&window=${ACTIVITY_WINDOW_DAYS}${
    outcome ? `&outcome=${outcome}` : ""
  }`;
 
const RuleActivityCard: React.FC<{
  activity: GovernanceActivityList | null;
  loading: boolean;
  className?: string;
}> = ({ activity, loading, className = "" }) => {
  const summary = activity?.summary ?? null;
  return (
    <div
      className={`rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-4 shadow-sm ${className}`.trim()}
    >
      <div className="flex items-center justify-between gap-2 mb-2">
        <div className="flex items-baseline gap-2 min-w-0">
          <h4 className="text-sm font-medium text-gray-800 dark:text-gray-200">
            Rule activity
          </h4>
          <span className="text-xs text-gray-400 dark:text-gray-500 truncate">
            every rule evaluated in the last 24 hours
          </span>
        </div>
        <Link
          to={activityHref()}
          className="shrink-0 flex items-center gap-1 text-xs text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors"
        >
          {loading ? (
            <Skeleton className="inline-block w-10 h-4" />
          ) : (
            plural(summary?.total ?? 0, "evaluation")
          )}
          <ChevronRight className="size-3" />
        </Link>
      </div>
 
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-1">
        {OUTCOME_ORDER.map((outcome) => (
          <Link
            key={outcome}
            to={activityHref(outcome)}
            title={OUTCOME_HINTS[outcome]}
            className="flex flex-col gap-1 rounded-lg px-2.5 py-2 border border-transparent hover:bg-gray-50 dark:hover:bg-gray-700/40 hover:border-gray-200 dark:hover:border-gray-700 transition-all"
          >
            <StatusBadge
              status={outcome}
              scale={GOVERNANCE_OUTCOME}
              label={OUTCOME_LABELS[outcome]}
              className="self-start"
            />
            <span className="text-lg font-semibold text-gray-900 dark:text-gray-100 tabular-nums leading-none">
              {loading ? (
                <Skeleton className="inline-block w-8 h-5" />
              ) : (
                fmt(summary?.[outcome] ?? 0)
              )}
            </span>
          </Link>
        ))}
      </div>
 
      <p className="mt-2.5 pt-2.5 border-t border-gray-100 dark:border-gray-700/80 text-[11px] text-gray-500 dark:text-gray-400 leading-snug">
        A rule that matched and found nothing to do is a rule working — that is
        why it is counted here rather than left out.
      </p>
    </div>
  );
};
 
// ─── Overview ─────────────────────────────────────────────────────────────────
 
const Overview: React.FC = () => {
  const { user } = useAuth();
  const { getApiHandler } = useApiHandler();
 
  const { data: models, isLoading: modelsLoading } = useQuery<Model[] | null>({
    queryKey: [QUERY_KEYS.GET.MODELS],
    queryFn: () => getApiHandler().model_router.list(),
  });
 
  const { data: agents, isLoading: agentsLoading } = useQuery<Agent[] | null>({
    queryKey: [QUERY_KEYS.GET.AGENTS],
    queryFn: () => getApiHandler().agent_router.list(),
  });
 
  const { data: projects, isLoading: projectsLoading } = useQuery<
    Project[] | null
  >({
    queryKey: [QUERY_KEYS.GET.PROJECTS],
    queryFn: () => getApiHandler().project_router.list(),
  });
 
  const { data: knowledge, isLoading: knowledgeLoading } = useQuery<
    Knowledge[] | null
  >({
    queryKey: [QUERY_KEYS.GET.KNOWLEDGE],
    queryFn: () => getApiHandler().knowledge_router.list(),
  });
 
  const { data: repositories, isLoading: repositoriesLoading } = useQuery<
    KnowledgeRepository[] | null
  >({
    queryKey: [QUERY_KEYS.GET.REPOSITORIES],
    queryFn: () => getApiHandler().repository_router.list(),
  });
 
  const { data: organisations, isLoading: orgsLoading } = useQuery<
    Organisation[] | null
  >({
    queryKey: [QUERY_KEYS.GET.ORGANISATIONS],
    queryFn: () => getApiHandler().organisation_router.list(),
  });
 
  const { data: skills, isLoading: skillsLoading } = useQuery<Skill[] | null>({
    queryKey: [QUERY_KEYS.GET.SKILLS],
    queryFn: () => getApiHandler().skill_router.list(),
  });
 
  const { data: skillsets, isLoading: skillsetsLoading } = useQuery<
    Skillset[] | null
  >({
    queryKey: [QUERY_KEYS.GET.SKILLSETS],
    queryFn: () => getApiHandler().skillset_router.list(),
  });
 
  const { data: toolkits, isLoading: toolkitsLoading } = useQuery<
    Toolkit[] | null
  >({
    queryKey: [QUERY_KEYS.GET.TOOLKITS],
    queryFn: () => getApiHandler().toolkit_router.list(),
    // Toolkits and MCP servers are not available in this release
    // (util/mcp.ts): neither list is asked for, so every count, tip and
    // activity entry below that reads them is empty.
    enabled: MCP_AVAILABLE,
  });
 
  // Evaluation was absent from this page while every other Inference
  // resource had a tile, which is part of why the tab read as dead.
  const { data: experiments, isLoading: experimentsLoading } = useQuery<
    Experiment[] | null
  >({
    queryKey: [QUERY_KEYS.GET.EXPERIMENTS],
    queryFn: () => getApiHandler().evaluation_router.listExperiments(),
  });
  const { data: testSuites, isLoading: testSuitesLoading } = useQuery<
    TestSuite[] | null
  >({
    queryKey: [QUERY_KEYS.GET.TEST_SUITES],
    queryFn: () => getApiHandler().evaluation_router.listTestSuites(),
  });
  const { data: evaluationTotals } = useQuery<BatchReportTotals | null>({
    queryKey: [QUERY_KEYS.GET.BATCH_REPORT_SUMMARY, 30],
    queryFn: () => getApiHandler().evaluation_router.reportSummary({ days: 30 }),
  });
 
 
  const { data: mcpServers, isLoading: mcpLoading } = useQuery<
    MCPServer[] | null
  >({
    queryKey: [QUERY_KEYS.GET.USER_MCP_SERVERS],
    queryFn: () => getApiHandler().mcp_server_router.list(),
    enabled: MCP_AVAILABLE,
  });
 
  const { data: dashboards, isLoading: dashboardsLoading } = useQuery<
    Dashboard[] | null
  >({
    queryKey: [QUERY_KEYS.GET.DASHBOARDS],
    queryFn: () => getApiHandler().dashboard_router.list(),
  });
 
  const { data: rules, isLoading: rulesLoading } = useQuery<Rule[] | null>({
    queryKey: [QUERY_KEYS.GET.RULES],
    queryFn: () => getApiHandler().rule_router.list(),
  });
 
  // The same window, params and cache key the Governance tab badge uses, so
  // the two never disagree and opening Governance costs no second request.
  // `limit: 1` because only the summary is read here — the rows behind it are
  // a page of the log nobody is looking at yet.
  const { data: ruleActivity, isLoading: ruleActivityLoading } =
    useQuery<GovernanceActivityList | null>({
      queryKey: [QUERY_KEYS.GET.RULE_ACTIVITY, "badge"],
      queryFn: () =>
        getApiHandler().rule_router.activity({
          days: ACTIVITY_WINDOW_DAYS,
          limit: 1,
        }),
      staleTime: 30_000,
    });
 
  const { data: reviewSummary, isLoading: reviewsLoading } =
    useQuery<ReviewSummary | null>({
      queryKey: [QUERY_KEYS.GET.REVIEWS_SUMMARY],
      queryFn: () => getApiHandler().review_router.summary(),
      staleTime: 30_000,
    });
 
  const { data: usageStats, isLoading: statsLoading } =
    useQuery<UsageStats | null>({
      queryKey: [QUERY_KEYS.GET.USAGE_STATS],
      queryFn: () => getApiHandler().stats_router.getUsage(),
      staleTime: 60_000,
    });
 
  const { data: traceStats, isLoading: traceLoading } = useQuery<{
    this_month: TracePeriod;
    all_time: TracePeriod;
  } | null>({
    queryKey: [QUERY_KEYS.GET.TRACE_STATS],
    queryFn: () => getApiHandler().stats_router.getTraces(),
    staleTime: 60_000,
  });
 
  // ── Composition ──
  //
  // Agents never integrate a primitive directly — skills arrive via a skillset,
  // tools and MCP servers via a toolkit, knowledge sources via a repository.
  // Anything left out of a bundle is invisible to every agent, so the counts
  // below drive both the "unbundled" badges and the setup notifications.
 
  // `useQuery` resolves as `any` under the installed react-query/TS pair, so
  // these typed lists are the single boundary where results become typed —
  // every read below goes through them rather than the raw query data.
  // Only the models an agent can run on. The catalogue keeps every model it
  // has ever served — on Amazon Bedrock that includes routes this account
  // has no access to — so counting all of it said 15 models were available
  // to agents when two were.
  const modelList: Model[] = (models ?? []).filter(isSelectableModel);
  // CHAINR Bot arrives in the agent listing so every picker offers it, but it
  // is the platform's rather than part of the user's fleet: it is not counted
  // as one of their agents, and it is what a new user is pointed at first.
  const agentList: Agent[] = (agents ?? []).filter(
    (a: Agent) => !isSystemManaged(a),
  );
  const builtInAgent: Agent | undefined = (agents ?? []).find(isSystemManaged);
  const projectList: Project[] = projects ?? [];
  const organisationList: Organisation[] = organisations ?? [];
  const skillsetList: Skillset[] = skillsets ?? [];
  const toolkitList: Toolkit[] = toolkits ?? [];
  const experimentList: Experiment[] = experiments ?? [];
  const testSuiteList: TestSuite[] = testSuites ?? [];
  const repositoryList: KnowledgeRepository[] = repositories ?? [];
  const skillList: Skill[] = skills ?? [];
  const mcpList: MCPServer[] = mcpServers ?? [];
  const sourceList: Knowledge[] = knowledge ?? [];
  const boardList: Dashboard[] = dashboards ?? [];
  const ruleList: Rule[] = rules ?? [];
 
  // ── Governance ──
  //
  // Three counts, each answering a different question: what is configured
  // (rules), what it has been doing (activity), and what it has asked a
  // person to decide (reviews). The last is the only one that is work
  // outstanding, so it is the only one that raises a notification.
  const activeRules = ruleList.filter((r) => r.is_active).length;
  const rulesInLayer = (layer: RuleLayer) =>
    ruleList.filter((r) => r.layer === layer).length;
  const pendingReviews = reviewSummary?.pending ?? 0;
  const resolvedReviews =
    (reviewSummary?.reviewed ?? 0) + (reviewSummary?.dismissed ?? 0);
 
  const bundledSkillIds = new Set(skillsetList.flatMap((s) => s.skill_ids));
  const bundledMcpIds = new Set(toolkitList.flatMap((t) => t.mcp_server_ids));
  const bundledSourceIds = new Set(
    repositoryList.flatMap((r) => r.knowledge_ids),
  );
 
  const looseSkills = skillList.filter(
    (s) => !bundledSkillIds.has(s.id),
  ).length;
  const looseMcp = mcpList.filter((s) => !bundledMcpIds.has(s.id)).length;
  const looseSources = sourceList.filter(
    (k) => !bundledSourceIds.has(k.id),
  ).length;
 
  const fileKbs = sourceList.filter((k) => k.source_type === "file");
  const cachedMcpTools = mcpList.reduce(
    (sum, s) => sum + (s.tools_cache?.length ?? 0),
    0,
  );
 
  // ── Notifications ──
  const notifications: React.ComponentProps<typeof NotificationItem>[] = [];
 
  if (!modelsLoading && modelList.length === 0) {
    notifications.push({
      type: "warning",
      title: "No models connected.",
      description:
        "Contact your admin to register LLM models before using agents.",
    });
  }
  // Ahead of every setup tip below: a pending flag is work somebody asked a
  // person to do, not a suggestion about how to configure the platform.
  if (!reviewsLoading && pendingReviews > 0) {
    notifications.push({
      type: "warning",
      title: `${plural(pendingReviews, "flag")} waiting for review.`,
      description:
        "An audit rule asked for a person's decision — a flag stays pending until one is recorded.",
      action: { label: "Open queue", to: APP_ROUTES.USER.GOVERNANCE.reviews },
    });
  }
  if (!agentsLoading && agentList.length === 0 && modelList.length > 0) {
    notifications.push(
      builtInAgent
        ? {
            type: "tip",
            title: "Start with CHAINR Bot.",
            description:
              "The built-in assistant is ready now — ask it how CHAIN-R works, or anything else. When you need an agent that answers from your own documents and tools, create one.",
            action: {
              label: "Chat with CHAINR Bot",
              to: APP_ROUTES.USER.INFERENCE.AGENTS.chat.replace(
                ROUTE_PARAMS.AGENT.id,
                encodeResourceId(builtInAgent.id),
              ),
            },
          }
        : {
            type: "tip",
            title: "No agents yet.",
            description: "Create your first agent to start automating workflows.",
            action: {
              label: "New agent",
              to: APP_ROUTES.USER.INFERENCE.AGENTS.new,
            },
          },
    );
  }
  Iif (!skillsLoading && !skillsetsLoading && looseSkills > 0) {
    notifications.push({
      type: "tip",
      title: `${plural(looseSkills, "skill")} not in a skillset.`,
      description:
        "Agents only integrate skills through a skillset — group these to make them usable.",
      action: {
        label: "New skillset",
        to: APP_ROUTES.USER.INFERENCE.skillsets,
      },
    });
  }
  Iif (!mcpLoading && !toolkitsLoading && looseMcp > 0) {
    notifications.push({
      type: "tip",
      title: `${plural(looseMcp, "MCP server")} not in a toolkit.`,
      description:
        "Agents only integrate MCP servers through a toolkit — group these to make them usable.",
      action: {
        label: "New toolkit",
        to: APP_ROUTES.USER.INFERENCE.toolkits,
      },
    });
  }
  Iif (!knowledgeLoading && !repositoriesLoading && looseSources > 0) {
    notifications.push({
      type: "tip",
      title: `${plural(looseSources, "knowledge source")} not in a repository.`,
      description:
        "Agents retrieve from whole repositories, not individual sources — group these to make them searchable.",
      action: {
        label: "New repository",
        to: APP_ROUTES.USER.KNOWLEDGE.repositories,
      },
    });
  }
  Iif (!rulesLoading && ruleList.length === 0 && agentList.length > 0) {
    notifications.push({
      type: "info",
      title: "Nothing is governing your invocations yet.",
      description:
        "Rules are evaluated on every invocation — whether it may run, what the model reads and what comes back. Scope one to an agent, a project or the whole account.",
      action: { label: "New rule", to: APP_ROUTES.USER.GOVERNANCE.RULES.new },
    });
  }
  if (!dashboardsLoading && boardList.length === 0) {
    notifications.push({
      type: "tip",
      title: "No dashboards yet.",
      description:
        "Compose a board of widgets to watch spend, activity and live feeds beside the agents that produce them.",
      action: { label: "New dashboard", to: APP_ROUTES.USER.dashboards },
    });
  }
  if (!projectsLoading && projectList.length === 0) {
    notifications.push({
      type: "info",
      title: "Organise your work with projects.",
      description:
        "Projects group agents and knowledge together by workstream.",
      action: { label: "New project", to: APP_ROUTES.USER.PROJECTS.new },
    });
  }
 
  // ── Recent activity ──
  const recentActivity: (React.ComponentProps<typeof ActivityRow> & {
    ts: number;
  })[] = [];
 
  const pushActivity = (
    icon: React.ElementType,
    label: string,
    name: string,
    created_at: string | undefined,
    to: string,
  ) => {
    Iif (!created_at) return;
    recentActivity.push({
      icon,
      label,
      name,
      date: formatDate(created_at),
      to,
      ts: parseServerDate(created_at).getTime(),
    });
  };
 
  agentList.forEach((a) =>
    pushActivity(
      Bot,
      "Agent created",
      a.name,
      a.created_at,
      APP_ROUTES.USER.INFERENCE.AGENTS.id.replace(":agentId", encodeResourceId(a.id ?? "")),
    ),
  );
 
  modelList.forEach((m) =>
    pushActivity(
      BrainCog,
      "Model registered",
      `${modelMaker(m)} — ${m.display_name ?? m.model_name}`,
      m.created_at,
      APP_ROUTES.USER.INFERENCE.MODELS.id.replace(":modelId", encodeResourceId(m.id ?? "")),
    ),
  );
 
  skillsetList.forEach((s) =>
    pushActivity(
      Layers3,
      "Skillset created",
      s.name,
      s.created_at,
      APP_ROUTES.USER.INFERENCE.SKILLSETS.id.replace(
        ROUTE_PARAMS.SKILLSET.id,
        encodeResourceId(s.id),
      ),
    ),
  );
 
  toolkitList.forEach((t) =>
    pushActivity(
      Wrench,
      "Toolkit created",
      t.name,
      t.created_at,
      APP_ROUTES.USER.INFERENCE.TOOLKITS.id.replace(
        ROUTE_PARAMS.TOOLKIT.id,
        encodeResourceId(t.id),
      ),
    ),
  );
 
  repositoryList.forEach((r) =>
    pushActivity(
      FolderGit2,
      "Repository created",
      r.name,
      r.created_at,
      APP_ROUTES.USER.KNOWLEDGE.REPOSITORIES.id.replace(
        ROUTE_PARAMS.REPOSITORY.id,
        encodeResourceId(r.id),
      ),
    ),
  );
 
  sourceList.forEach((k) => {
    const meta = SOURCE_TYPES.find((t) => t.key === k.source_type);
    pushActivity(
      meta?.icon ?? Library,
      `${meta?.label ?? k.source_type} source created`,
      k.name,
      k.created_at,
      APP_ROUTES.USER.KNOWLEDGE.id.replace(
        ROUTE_PARAMS.KNOWLEDGE.id,
        encodeResourceId(k.id),
      ),
    );
  });
 
 
  mcpList.forEach((s) =>
    pushActivity(
      Server,
      "MCP server added",
      s.name,
      s.created_at,
      APP_ROUTES.USER.INFERENCE.mcp,
    ),
  );
 
  ruleList.forEach((r) =>
    pushActivity(
      ruleLayerMeta(r.layer).Icon,
      `${ruleLayerMeta(r.layer).label} rule created`,
      r.name,
      r.created_at,
      APP_ROUTES.USER.GOVERNANCE.RULES.id.replace(
        ROUTE_PARAMS.RULE.id,
        encodeResourceId(r.id),
      ),
    ),
  );
 
  boardList.forEach((b) =>
    pushActivity(
      boardIcon(b.icon),
      "Dashboard created",
      b.name,
      b.created_at ?? undefined,
      boardHref(b),
    ),
  );
 
  recentActivity.sort((a, b) => b.ts - a.ts);
 
  const greeting = () => {
    const h = new Date().getHours();
    Eif (h < 12) return "Good morning";
    if (h < 18) return "Good afternoon";
    return "Good evening";
  };
 
  const firstName = user?.name?.split(" ")[0] ?? "there";
 
  return (
    <MainPage title="Overview">
      {/* Greeting */}
      <div className="flex items-center justify-between mb-6">
        <div>
          <h2 className="text-2xl font-semibold text-gray-900 dark:text-gray-100">
            {greeting()}, {firstName}
          </h2>
          <p className="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
            {new Date().toLocaleDateString(undefined, {
              weekday: "long",
              year: "numeric",
              month: "long",
              day: "numeric",
            })}
          </p>
        </div>
        <div className="flex items-center gap-1.5 text-xs text-gray-400 dark:text-gray-500 bg-gray-100 dark:bg-gray-800 border border-gray-200 dark:border-gray-700 px-3 py-1.5 rounded-full">
          <Activity className="size-3.5" />
          Platform overview
        </div>
      </div>
 
      {/* Notifications */}
      {notifications.length > 0 && (
        <div className="mb-6 space-y-2">
          <div className="flex items-center gap-1.5 text-xs font-medium text-gray-500 dark:text-gray-400 mb-2">
            <Bell className="size-3.5" />
            Notifications
          </div>
          {notifications.map((n, i) => (
            <NotificationItem key={i} {...n} />
          ))}
        </div>
      )}
 
      {/* ── Dashboards ── */}
      {/*
        First, as it is in the nav: a board is where somebody *reads* the
        platform, and the sections below are where they configure it.
      */}
      <section className="mb-8">
        <SectionHeader
          icon={LayoutDashboard}
          title="Dashboards"
          blurb="Where you watch it all — boards mixing platform data, live feeds and model-generated analysis"
          to={APP_ROUTES.USER.dashboards}
        />
 
        <div className="grid lg:grid-cols-3 gap-3">
          <ResourceCard
            icon={LayoutDashboard}
            label="Dashboards"
            blurb="Boards you compose from widgets, each marked by where its content came from"
            count={boardList.length}
            to={APP_ROUTES.USER.dashboards}
            loading={dashboardsLoading}
            tone="indigo"
            meta={
              boardList.some((b) => b.is_home)
                ? "One board is your home"
                : "No home board set"
            }
          />
 
          <BoardList
            boards={boardList}
            loading={dashboardsLoading}
            className="lg:col-span-2"
          />
        </div>
      </section>
 
      {/* ── Inference ── */}
      <section className="mb-8">
        <SectionHeader
          icon={Bot}
          title="Inference"
          blurb="What your agents run on — models, agents, and the bundles attached to them"
          to={APP_ROUTES.USER.inference}
        />
 
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3 mb-3">
          <ResourceCard
            icon={BrainCog}
            label="Models"
            blurb="LLMs available to your agents"
            count={modelList.length}
            to={APP_ROUTES.USER.INFERENCE.models}
            loading={modelsLoading}
            tone="blue"
            meta={
              modelList.length > 0
                ? `${new Set(modelList.map((m) => modelMaker(m))).size} makers`
                : "None connected"
            }
          />
          <ResourceCard
            icon={Bot}
            label="Agents"
            blurb="Run tasks using a model plus attached bundles"
            count={agentList.length}
            to={APP_ROUTES.USER.INFERENCE.agents}
            loading={agentsLoading}
            tone="emerald"
            meta={
              MCP_AVAILABLE
                ? `${plural(skillsetList.length, "skillset")} · ${plural(toolkitList.length, "toolkit")} available`
                : `${plural(skillsetList.length, "skillset")} available`
            }
          />
          <ResourceCard
            icon={Layers3}
            label="Skillsets"
            blurb="Bundles of skills — the only way an agent gains a skill"
            count={skillsetList.length}
            to={APP_ROUTES.USER.INFERENCE.skillsets}
            loading={skillsetsLoading}
            tone="sky"
            meta={`${plural(bundledSkillIds.size, "skill")} bundled`}
          />
          {MCP_AVAILABLE && (
            <ResourceCard
              icon={Wrench}
              label="Toolkits"
              blurb="Bundles of MCP servers granted as one unit"
              count={toolkitList.length}
              to={APP_ROUTES.USER.INFERENCE.toolkits}
              loading={toolkitsLoading}
              tone="amber"
              meta={`${plural(bundledMcpIds.size, "server")} bundled`}
            />
          )}
        </div>
 
        <MemberTray caption="Building blocks — reach an agent only inside a bundle">
          <MemberRow
            icon={Shapes}
            label="Skills"
            note="in skillsets"
            count={skillList.length}
            to={APP_ROUTES.USER.INFERENCE.skills}
            loading={skillsLoading || skillsetsLoading}
            tone="violet"
            loose={looseSkills}
          />
          {MCP_AVAILABLE && (
            <MemberRow
              icon={Server}
              label="MCP Servers"
              note={
                cachedMcpTools > 0
                  ? `${cachedMcpTools} cached tools`
                  : undefined
              }
              count={mcpList.length}
              to={APP_ROUTES.USER.INFERENCE.mcp}
              loading={mcpLoading || toolkitsLoading}
              tone="sky"
              loose={looseMcp}
            />
          )}
        </MemberTray>
      </section>
 
      {/* ── Knowledge ── */}
      <section className="mb-8">
        <SectionHeader
          icon={Library}
          title="Knowledge"
          blurb="What your agents can retrieve — sources grouped into repositories"
          to={APP_ROUTES.USER.knowledge}
        />
 
        <div className="grid lg:grid-cols-3 gap-3">
          <ResourceCard
            icon={FolderGit2}
            label="Repositories"
            blurb="Bundles of sources — agents retrieve from a whole repository"
            count={repositoryList.length}
            to={APP_ROUTES.USER.KNOWLEDGE.repositories}
            loading={repositoriesLoading}
            tone="indigo"
            meta={`${plural(bundledSourceIds.size, "source")} bundled`}
          />
 
          <div className="lg:col-span-2 rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-4 shadow-sm">
            <div className="flex items-center justify-between gap-2 mb-2">
              <div className="flex items-baseline gap-2 min-w-0">
                <h4 className="text-sm font-medium text-gray-800 dark:text-gray-200">
                  Sources
                </h4>
                <span className="text-xs text-gray-400 dark:text-gray-500 truncate">
                  the raw material a repository bundles
                </span>
              </div>
              <div className="flex items-center gap-2 shrink-0">
                {!knowledgeLoading && looseSources > 0 && (
                  <span
                    className="rounded-full bg-amber-50 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 px-1.5 py-px text-[10px] font-medium"
                    title="Not in any repository — no agent can retrieve these yet"
                  >
                    {looseSources} unbundled
                  </span>
                )}
                <span className="text-sm font-semibold text-gray-900 dark:text-gray-100 tabular-nums">
                  {knowledgeLoading ? (
                    <Skeleton className="inline-block w-6 h-4" />
                  ) : (
                    fmt(sourceList.length)
                  )}
                </span>
              </div>
            </div>
 
            <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-1">
              {SOURCE_TYPES.map((t) => (
                <MemberRow
                  key={t.key}
                  icon={t.icon}
                  label={t.label}
                  count={
                    sourceList.filter((k) => k.source_type === t.key).length
                  }
                  to={t.to}
                  loading={knowledgeLoading}
                  tone={t.tone}
                />
              ))}
            </div>
 
            <FileStorageStrip
              fileKbs={fileKbs}
              knowledgeLoading={knowledgeLoading}
            />
          </div>
        </div>
      </section>
 
      {/* ── Governance ── */}
      {/*
        Third in the main nav, and third here: what runs (Inference), what
        grounds it (Knowledge), and the standards it is held to — rules and
        evaluations.
      */}
      <section className="mb-8">
        <SectionHeader
          icon={ScrollText}
          title="Governance"
          blurb="The standards your fleet is held to — rules enforced on every invocation, evaluations that show each agent is fit for purpose, what the rules did, and what needs a person"
          to={APP_ROUTES.USER.governance}
        />
 
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-3">
          <ResourceCard
            icon={ShieldCheck}
            label="Rules"
            blurb="Access, input and output rules, evaluated on every invocation"
            count={ruleList.length}
            to={APP_ROUTES.USER.GOVERNANCE.rules}
            loading={rulesLoading}
            tone="rose"
            meta={
              ruleList.length === 0 ? (
                "None written"
              ) : (
                <span className="flex flex-wrap items-center gap-1">
                  {/* Neutral, in flow order: the layer registry names them
                      (rules/ruleLayer.ts), never a class written here. */}
                  {RULE_LAYERS.filter((layer) => rulesInLayer(layer) > 0).map(
                    (layer) => (
                      <span
                        key={layer}
                        className={`rounded-full border px-1.5 py-px text-[10px] font-medium ${LAYER_CLASSES.tag}`}
                      >
                        {fmt(rulesInLayer(layer))} {ruleLayerMeta(layer).label}
                      </span>
                    ),
                  )}
                  {activeRules < ruleList.length && (
                    <span className="text-[11px] text-gray-500 dark:text-gray-400">
                      · {fmt(ruleList.length - activeRules)} inactive
                    </span>
                  )}
                </span>
              )
            }
          />
 
          <ResourceCard
            icon={FlaskConical}
            label="Evaluations"
            blurb="Score prompts, models and agents against the same cases"
            count={experimentList.length}
            to={APP_ROUTES.USER.GOVERNANCE.evaluation}
            loading={experimentsLoading}
            tone="rose"
            meta={
              evaluationTotals && evaluationTotals.batches > 0
                ? `${plural(evaluationTotals.batches, "run")} in 30 days`
                : "No runs in 30 days"
            }
          />
          <ResourceCard
            icon={TestTube}
            label="Datasets"
            blurb="Reusable cases and grading any evaluation can run against"
            count={testSuiteList.length}
            to={APP_ROUTES.USER.GOVERNANCE.EVALUATION.datasets}
            loading={testSuitesLoading}
            tone="slate"
            meta={`${plural(experimentList.length, "evaluation")} can point at one`}
          />
 
          <ResourceCard
            icon={ScrollText}
            label="Pending reviews"
            blurb="Audit flags and regressed evaluation runs awaiting a decision"
            count={pendingReviews}
            to={APP_ROUTES.USER.GOVERNANCE.reviews}
            loading={reviewsLoading}
            tone="amber"
            meta={
              // Pending is the number on the card because it is the only one
              // that is work outstanding; resolved is what says the queue is
              // being worked rather than ignored.
              resolvedReviews > 0
                ? `${plural(resolvedReviews, "item")} already resolved`
                : "Nothing resolved yet"
            }
          />
 
          <RuleActivityCard
            activity={ruleActivity ?? null}
            loading={ruleActivityLoading}
            className="sm:col-span-2"
          />
        </div>
      </section>
 
      {/* ── Workspace ── */}
      <section className="mb-8">
        <SectionHeader
          icon={LayoutGrid}
          title="Workspace"
          blurb="Where your work lives — ownership and access boundaries"
          to={APP_ROUTES.USER.projects}
        />
 
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-3">
          <ResourceCard
            icon={FolderKanban}
            label="Projects"
            blurb="Group agents and knowledge by workstream"
            count={projectList.length}
            to={APP_ROUTES.USER.projects}
            loading={projectsLoading}
            tone="violet"
          />
          <ResourceCard
            icon={Building}
            label="Organisations"
            blurb="Shared ownership across a team"
            count={organisationList.length}
            to={APP_ROUTES.USER.organisations}
            loading={orgsLoading}
            tone="slate"
          />
        </div>
      </section>
 
      {/* ── Operations ── */}
      <section>
        <SectionHeader
          icon={Activity}
          title="Operations"
          blurb="What your platform has been doing"
          to={APP_ROUTES.USER.activity}
        />
 
        <div className="grid lg:grid-cols-3 gap-4 mb-4">
          <TraceCountsCard
            loading={traceLoading}
            thisMonth={traceStats?.this_month ?? null}
          />
          <TokenUsageCard
            loading={statsLoading}
            thisMonth={usageStats?.this_month ?? null}
            allTime={usageStats?.all_time ?? null}
          />
          <QuickActionsCard />
        </div>
 
        <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-5 shadow-sm">
          <div className="flex items-center gap-2 mb-3">
            <Activity className="size-4 text-gray-500" />
            <h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
              Recent Activity
            </h3>
            {recentActivity.length > 0 && (
              <Link
                to={APP_ROUTES.USER.activity}
                className="ml-auto flex items-center gap-1 text-xs text-gray-400 dark:text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition-colors"
              >
                View all
                <ChevronRight className="size-3" />
              </Link>
            )}
          </div>
          {recentActivity.length === 0 ? (
            <p className="text-sm text-gray-400 dark:text-gray-500 py-6 text-center">
              No recent activity to display.
            </p>
          ) : (
            <div>
              {recentActivity.slice(0, 10).map((event, i) => (
                <ActivityRow
                  key={i}
                  icon={event.icon}
                  label={event.label}
                  name={event.name}
                  date={event.date}
                  to={event.to}
                />
              ))}
            </div>
          )}
        </div>
      </section>
    </MainPage>
  );
};
 
export default Overview;