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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
const originalEnv = {
  CREDS_KEY: process.env.CREDS_KEY,
  CREDS_IV: process.env.CREDS_IV,
};

process.env.CREDS_KEY = '0123456789abcdef0123456789abcdef';
process.env.CREDS_IV = '0123456789abcdef';

jest.mock('~/server/services/Config', () => ({
  getCachedTools: jest.fn(),
  getMCPServerTools: jest.fn(),
}));

const mongoose = require('mongoose');
const { v4: uuidv4 } = require('uuid');
const { agentSchema } = require('@librechat/data-schemas');
const { MongoMemoryServer } = require('mongodb-memory-server');
const { AccessRoleIds, ResourceType, PrincipalType } = require('librechat-data-provider');
const {
  getAgent,
  loadAgent,
  createAgent,
  updateAgent,
  deleteAgent,
  getListAgents,
  getListAgentsByAccess,
  revertAgentVersion,
  updateAgentProjects,
  addAgentResourceFile,
  removeAgentResourceFiles,
  generateActionMetadataHash,
} = require('./Agent');
const permissionService = require('~/server/services/PermissionService');
const { getCachedTools, getMCPServerTools } = require('~/server/services/Config');
const { AclEntry } = require('~/db/models');

/**
 * @type {import('mongoose').Model<import('@librechat/data-schemas').IAgent>}
 */
let Agent;

describe('models/Agent', () => {
  describe('Agent Resource File Operations', () => {
    let mongoServer;

    beforeAll(async () => {
      mongoServer = await MongoMemoryServer.create();
      const mongoUri = mongoServer.getUri();
      Agent = mongoose.models.Agent || mongoose.model('Agent', agentSchema);
      await mongoose.connect(mongoUri);
    }, 20000);

    afterAll(async () => {
      await mongoose.disconnect();
      await mongoServer.stop();
      process.env.CREDS_KEY = originalEnv.CREDS_KEY;
      process.env.CREDS_IV = originalEnv.CREDS_IV;
    });

    beforeEach(async () => {
      await Agent.deleteMany({});
    });

    test('should add tool_resource to tools if missing', async () => {
      const agent = await createBasicAgent();
      const fileId = uuidv4();
      const toolResource = 'file_search';

      const updatedAgent = await addAgentResourceFile({
        agent_id: agent.id,
        tool_resource: toolResource,
        file_id: fileId,
      });

      expect(updatedAgent.tools).toContain(toolResource);
      expect(Array.isArray(updatedAgent.tools)).toBe(true);
      // Should not duplicate
      const count = updatedAgent.tools.filter((t) => t === toolResource).length;
      expect(count).toBe(1);
    });

    test('should not duplicate tool_resource in tools if already present', async () => {
      const agent = await createBasicAgent();
      const fileId1 = uuidv4();
      const fileId2 = uuidv4();
      const toolResource = 'file_search';

      // First add
      await addAgentResourceFile({
        agent_id: agent.id,
        tool_resource: toolResource,
        file_id: fileId1,
      });

      // Second add (should not duplicate)
      const updatedAgent = await addAgentResourceFile({
        agent_id: agent.id,
        tool_resource: toolResource,
        file_id: fileId2,
      });

      expect(updatedAgent.tools).toContain(toolResource);
      expect(Array.isArray(updatedAgent.tools)).toBe(true);
      const count = updatedAgent.tools.filter((t) => t === toolResource).length;
      expect(count).toBe(1);
    });

    test('should handle concurrent file additions', async () => {
      const agent = await createBasicAgent();
      const fileIds = Array.from({ length: 10 }, () => uuidv4());

      // Concurrent additions
      const additionPromises = createFileOperations(agent.id, fileIds, 'add');

      await Promise.all(additionPromises);

      const updatedAgent = await Agent.findOne({ id: agent.id });
      expect(updatedAgent.tool_resources.test_tool.file_ids).toBeDefined();
      expect(updatedAgent.tool_resources.test_tool.file_ids).toHaveLength(10);
      expect(new Set(updatedAgent.tool_resources.test_tool.file_ids).size).toBe(10);
    });

    test('should handle concurrent additions and removals', async () => {
      const agent = await createBasicAgent();
      const initialFileIds = Array.from({ length: 5 }, () => uuidv4());

      await Promise.all(createFileOperations(agent.id, initialFileIds, 'add'));

      const newFileIds = Array.from({ length: 5 }, () => uuidv4());
      const operations = [
        ...newFileIds.map((fileId) =>
          addAgentResourceFile({
            agent_id: agent.id,
            tool_resource: 'test_tool',
            file_id: fileId,
          }),
        ),
        ...initialFileIds.map((fileId) =>
          removeAgentResourceFiles({
            agent_id: agent.id,
            files: [{ tool_resource: 'test_tool', file_id: fileId }],
          }),
        ),
      ];

      await Promise.all(operations);

      const updatedAgent = await Agent.findOne({ id: agent.id });
      expect(updatedAgent.tool_resources.test_tool.file_ids).toBeDefined();
      expect(updatedAgent.tool_resources.test_tool.file_ids).toHaveLength(5);
    });

    test('should initialize array when adding to non-existent tool resource', async () => {
      const agent = await createBasicAgent();
      const fileId = uuidv4();

      const updatedAgent = await addAgentResourceFile({
        agent_id: agent.id,
        tool_resource: 'new_tool',
        file_id: fileId,
      });

      expect(updatedAgent.tool_resources.new_tool.file_ids).toBeDefined();
      expect(updatedAgent.tool_resources.new_tool.file_ids).toHaveLength(1);
      expect(updatedAgent.tool_resources.new_tool.file_ids[0]).toBe(fileId);
    });

    test('should handle rapid sequential modifications to same tool resource', async () => {
      const agent = await createBasicAgent();
      const fileId = uuidv4();

      for (let i = 0; i < 10; i++) {
        await addAgentResourceFile({
          agent_id: agent.id,
          tool_resource: 'test_tool',
          file_id: `${fileId}_${i}`,
        });

        if (i % 2 === 0) {
          await removeAgentResourceFiles({
            agent_id: agent.id,
            files: [{ tool_resource: 'test_tool', file_id: `${fileId}_${i}` }],
          });
        }
      }

      const updatedAgent = await Agent.findOne({ id: agent.id });
      expect(updatedAgent.tool_resources.test_tool.file_ids).toBeDefined();
      expect(Array.isArray(updatedAgent.tool_resources.test_tool.file_ids)).toBe(true);
    });

    test('should handle multiple tool resources concurrently', async () => {
      const agent = await createBasicAgent();
      const toolResources = ['tool1', 'tool2', 'tool3'];
      const operations = [];

      toolResources.forEach((tool) => {
        const fileIds = Array.from({ length: 5 }, () => uuidv4());
        fileIds.forEach((fileId) => {
          operations.push(
            addAgentResourceFile({
              agent_id: agent.id,
              tool_resource: tool,
              file_id: fileId,
            }),
          );
        });
      });

      await Promise.all(operations);

      const updatedAgent = await Agent.findOne({ id: agent.id });
      toolResources.forEach((tool) => {
        expect(updatedAgent.tool_resources[tool].file_ids).toBeDefined();
        expect(updatedAgent.tool_resources[tool].file_ids).toHaveLength(5);
      });
    });

    test.each([
      {
        name: 'duplicate additions',
        operation: 'add',
        duplicateCount: 5,
        expectedLength: 1,
        expectedContains: true,
      },
      {
        name: 'duplicate removals',
        operation: 'remove',
        duplicateCount: 5,
        expectedLength: 0,
        expectedContains: false,
        setupFile: true,
      },
    ])(
      'should handle concurrent $name',
      async ({ operation, duplicateCount, expectedLength, expectedContains, setupFile }) => {
        const agent = await createBasicAgent();
        const fileId = uuidv4();

        if (setupFile) {
          await addAgentResourceFile({
            agent_id: agent.id,
            tool_resource: 'test_tool',
            file_id: fileId,
          });
        }

        const promises = Array.from({ length: duplicateCount }).map(() =>
          operation === 'add'
            ? addAgentResourceFile({
                agent_id: agent.id,
                tool_resource: 'test_tool',
                file_id: fileId,
              })
            : removeAgentResourceFiles({
                agent_id: agent.id,
                files: [{ tool_resource: 'test_tool', file_id: fileId }],
              }),
        );

        await Promise.all(promises);

        const updatedAgent = await Agent.findOne({ id: agent.id });
        const fileIds = updatedAgent.tool_resources?.test_tool?.file_ids ?? [];

        expect(fileIds).toHaveLength(expectedLength);
        if (expectedContains) {
          expect(fileIds[0]).toBe(fileId);
        } else {
          expect(fileIds).not.toContain(fileId);
        }
      },
    );

    test('should handle concurrent add and remove of the same file', async () => {
      const agent = await createBasicAgent();
      const fileId = uuidv4();

      await addAgentResourceFile({
        agent_id: agent.id,
        tool_resource: 'test_tool',
        file_id: fileId,
      });

      const operations = [
        addAgentResourceFile({
          agent_id: agent.id,
          tool_resource: 'test_tool',
          file_id: fileId,
        }),
        removeAgentResourceFiles({
          agent_id: agent.id,
          files: [{ tool_resource: 'test_tool', file_id: fileId }],
        }),
      ];

      await Promise.all(operations);

      const updatedAgent = await Agent.findOne({ id: agent.id });
      const finalFileIds = updatedAgent.tool_resources.test_tool.file_ids;
      const count = finalFileIds.filter((id) => id === fileId).length;

      expect(count).toBeLessThanOrEqual(1);
      if (count === 0) {
        expect(finalFileIds).toHaveLength(0);
      } else {
        expect(finalFileIds).toHaveLength(1);
        expect(finalFileIds[0]).toBe(fileId);
      }
    });

    test('should handle concurrent removals of different files', async () => {
      const agent = await createBasicAgent();
      const fileIds = Array.from({ length: 10 }, () => uuidv4());

      // Add all files first
      await Promise.all(
        fileIds.map((fileId) =>
          addAgentResourceFile({
            agent_id: agent.id,
            tool_resource: 'test_tool',
            file_id: fileId,
          }),
        ),
      );

      // Concurrently remove all files
      const removalPromises = fileIds.map((fileId) =>
        removeAgentResourceFiles({
          agent_id: agent.id,
          files: [{ tool_resource: 'test_tool', file_id: fileId }],
        }),
      );

      await Promise.all(removalPromises);

      const updatedAgent = await Agent.findOne({ id: agent.id });
      // Check if the array is empty or the tool resource itself is removed
      const finalFileIds = updatedAgent.tool_resources?.test_tool?.file_ids ?? [];
      expect(finalFileIds).toHaveLength(0);
    });

    describe('Edge Cases', () => {
      describe.each([
        {
          operation: 'add',
          name: 'empty file_id',
          needsAgent: true,
          params: { tool_resource: 'file_search', file_id: '' },
          shouldResolve: true,
        },
        {
          operation: 'add',
          name: 'non-existent agent',
          needsAgent: false,
          params: { tool_resource: 'file_search', file_id: 'file123' },
          shouldResolve: false,
          error: 'Agent not found for adding resource file',
        },
      ])('addAgentResourceFile with $name', ({ needsAgent, params, shouldResolve, error }) => {
        test(`should ${shouldResolve ? 'resolve' : 'reject'}`, async () => {
          const agent = needsAgent ? await createBasicAgent() : null;
          const agent_id = needsAgent ? agent.id : `agent_${uuidv4()}`;

          if (shouldResolve) {
            await expect(addAgentResourceFile({ agent_id, ...params })).resolves.toBeDefined();
          } else {
            await expect(addAgentResourceFile({ agent_id, ...params })).rejects.toThrow(error);
          }
        });
      });

      describe.each([
        {
          name: 'empty files array',
          files: [],
          needsAgent: true,
          shouldResolve: true,
        },
        {
          name: 'non-existent tool_resource',
          files: [{ tool_resource: 'non_existent_tool', file_id: 'file123' }],
          needsAgent: true,
          shouldResolve: true,
        },
        {
          name: 'non-existent agent',
          files: [{ tool_resource: 'file_search', file_id: 'file123' }],
          needsAgent: false,
          shouldResolve: false,
          error: 'Agent not found for removing resource files',
        },
      ])('removeAgentResourceFiles with $name', ({ files, needsAgent, shouldResolve, error }) => {
        test(`should ${shouldResolve ? 'resolve' : 'reject'}`, async () => {
          const agent = needsAgent ? await createBasicAgent() : null;
          const agent_id = needsAgent ? agent.id : `agent_${uuidv4()}`;

          if (shouldResolve) {
            const result = await removeAgentResourceFiles({ agent_id, files });
            expect(result).toBeDefined();
            if (agent) {
              expect(result.id).toBe(agent.id);
            }
          } else {
            await expect(removeAgentResourceFiles({ agent_id, files })).rejects.toThrow(error);
          }
        });
      });
    });
  });

  describe('Agent CRUD Operations', () => {
    let mongoServer;
    let AccessRole;

    beforeAll(async () => {
      mongoServer = await MongoMemoryServer.create();
      const mongoUri = mongoServer.getUri();
      Agent = mongoose.models.Agent || mongoose.model('Agent', agentSchema);
      await mongoose.connect(mongoUri);

      // Initialize models
      const dbModels = require('~/db/models');
      AccessRole = dbModels.AccessRole;

      // Create necessary access roles for agents
      await AccessRole.create({
        accessRoleId: AccessRoleIds.AGENT_OWNER,
        name: 'Owner',
        description: 'Full control over agents',
        resourceType: ResourceType.AGENT,
        permBits: 15, // VIEW | EDIT | DELETE | SHARE
      });
    }, 20000);

    afterAll(async () => {
      await mongoose.disconnect();
      await mongoServer.stop();
    });

    beforeEach(async () => {
      await Agent.deleteMany({});
    });

    test('should create and get an agent', async () => {
      const { agentId, authorId } = createTestIds();

      const newAgent = await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        description: 'Test description',
      });

      expect(newAgent).toBeDefined();
      expect(newAgent.id).toBe(agentId);
      expect(newAgent.name).toBe('Test Agent');

      const retrievedAgent = await getAgent({ id: agentId });
      expect(retrievedAgent).toBeDefined();
      expect(retrievedAgent.id).toBe(agentId);
      expect(retrievedAgent.name).toBe('Test Agent');
      expect(retrievedAgent.description).toBe('Test description');
    });

    test('should delete an agent', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Agent To Delete',
        provider: 'test',
        model: 'test-model',
        author: authorId,
      });

      const agentBeforeDelete = await getAgent({ id: agentId });
      expect(agentBeforeDelete).toBeDefined();

      await deleteAgent({ id: agentId });

      const agentAfterDelete = await getAgent({ id: agentId });
      expect(agentAfterDelete).toBeNull();
    });

    test('should remove ACL entries when deleting an agent', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      // Create agent
      const agent = await createAgent({
        id: agentId,
        name: 'Agent With Permissions',
        provider: 'test',
        model: 'test-model',
        author: authorId,
      });

      // Grant permissions (simulating sharing)
      await permissionService.grantPermission({
        principalType: PrincipalType.USER,
        principalId: authorId,
        resourceType: ResourceType.AGENT,
        resourceId: agent._id,
        accessRoleId: AccessRoleIds.AGENT_OWNER,
        grantedBy: authorId,
      });

      // Verify ACL entry exists
      const aclEntriesBefore = await AclEntry.find({
        resourceType: ResourceType.AGENT,
        resourceId: agent._id,
      });
      expect(aclEntriesBefore).toHaveLength(1);

      // Delete the agent
      await deleteAgent({ id: agentId });

      // Verify agent is deleted
      const agentAfterDelete = await getAgent({ id: agentId });
      expect(agentAfterDelete).toBeNull();

      // Verify ACL entries are removed
      const aclEntriesAfter = await AclEntry.find({
        resourceType: ResourceType.AGENT,
        resourceId: agent._id,
      });
      expect(aclEntriesAfter).toHaveLength(0);
    });

    test('should list agents by author', async () => {
      const authorId = new mongoose.Types.ObjectId();
      const otherAuthorId = new mongoose.Types.ObjectId();

      const agentIds = [];
      for (let i = 0; i < 5; i++) {
        const id = `agent_${uuidv4()}`;
        agentIds.push(id);
        await createAgent({
          id,
          name: `Agent ${i}`,
          provider: 'test',
          model: 'test-model',
          author: authorId,
        });
      }

      for (let i = 0; i < 3; i++) {
        await createAgent({
          id: `other_agent_${uuidv4()}`,
          name: `Other Agent ${i}`,
          provider: 'test',
          model: 'test-model',
          author: otherAuthorId,
        });
      }

      const result = await getListAgents({ author: authorId.toString() });

      expect(result).toBeDefined();
      expect(result.data).toBeDefined();
      expect(result.data).toHaveLength(5);
      expect(result.has_more).toBe(true);

      for (const agent of result.data) {
        expect(agent.author).toBe(authorId.toString());
      }
    });

    test('should update agent projects', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();
      const projectId1 = new mongoose.Types.ObjectId();
      const projectId2 = new mongoose.Types.ObjectId();
      const projectId3 = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Project Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        projectIds: [projectId1],
      });

      await updateAgent(
        { id: agentId },
        { $addToSet: { projectIds: { $each: [projectId2, projectId3] } } },
      );

      await updateAgent({ id: agentId }, { $pull: { projectIds: projectId1 } });

      await updateAgent({ id: agentId }, { projectIds: [projectId2, projectId3] });

      const updatedAgent = await getAgent({ id: agentId });
      expect(updatedAgent.projectIds).toHaveLength(2);
      expect(updatedAgent.projectIds.map((id) => id.toString())).toContain(projectId2.toString());
      expect(updatedAgent.projectIds.map((id) => id.toString())).toContain(projectId3.toString());
      expect(updatedAgent.projectIds.map((id) => id.toString())).not.toContain(
        projectId1.toString(),
      );

      await updateAgent({ id: agentId }, { projectIds: [] });

      const emptyProjectsAgent = await getAgent({ id: agentId });
      expect(emptyProjectsAgent.projectIds).toHaveLength(0);

      const nonExistentId = `agent_${uuidv4()}`;
      await expect(
        updateAgentProjects({
          id: nonExistentId,
          projectIds: [projectId1],
        }),
      ).rejects.toThrow();
    });

    test('should handle ephemeral agent loading', async () => {
      const agentId = 'ephemeral_test';
      const endpoint = 'openai';

      const originalModule = jest.requireActual('librechat-data-provider');

      const mockDataProvider = {
        ...originalModule,
        Constants: {
          ...originalModule.Constants,
          EPHEMERAL_AGENT_ID: 'ephemeral_test',
        },
      };

      jest.doMock('librechat-data-provider', () => mockDataProvider);

      expect(agentId).toBeDefined();
      expect(endpoint).toBeDefined();

      jest.dontMock('librechat-data-provider');
    });

    test('should handle loadAgent functionality and errors', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Load Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        tools: ['tool1', 'tool2'],
      });

      const agent = await getAgent({ id: agentId });

      expect(agent).toBeDefined();
      expect(agent.id).toBe(agentId);
      expect(agent.name).toBe('Test Load Agent');
      expect(agent.tools).toEqual(expect.arrayContaining(['tool1', 'tool2']));

      const mockLoadAgent = jest.fn().mockResolvedValue(agent);
      const loadedAgent = await mockLoadAgent();
      expect(loadedAgent).toBeDefined();
      expect(loadedAgent.id).toBe(agentId);

      const nonExistentId = `agent_${uuidv4()}`;
      const nonExistentAgent = await getAgent({ id: nonExistentId });
      expect(nonExistentAgent).toBeNull();

      const mockLoadAgentError = jest.fn().mockRejectedValue(new Error('No agent found with ID'));
      await expect(mockLoadAgentError()).rejects.toThrow('No agent found with ID');
    });

    describe('Edge Cases', () => {
      test.each([
        {
          name: 'getAgent with undefined search parameters',
          fn: () => getAgent(undefined),
          expected: null,
        },
        {
          name: 'deleteAgent with non-existent agent',
          fn: () => deleteAgent({ id: 'non-existent' }),
          expected: null,
        },
      ])('$name should return null', async ({ fn, expected }) => {
        const result = await fn();
        expect(result).toBe(expected);
      });

      test('should handle getListAgents with invalid author format', async () => {
        try {
          const result = await getListAgents({ author: 'invalid-object-id' });
          expect(result.data).toEqual([]);
        } catch (error) {
          expect(error).toBeDefined();
        }
      });

      test('should handle getListAgents with no agents', async () => {
        const authorId = new mongoose.Types.ObjectId();
        const result = await getListAgents({ author: authorId.toString() });

        expect(result).toBeDefined();
        expect(result.data).toEqual([]);
        expect(result.has_more).toBe(false);
        expect(result.first_id).toBeNull();
        expect(result.last_id).toBeNull();
      });

      test('should handle updateAgentProjects with non-existent agent', async () => {
        const nonExistentId = `agent_${uuidv4()}`;
        const userId = new mongoose.Types.ObjectId();
        const projectId = new mongoose.Types.ObjectId();

        const result = await updateAgentProjects({
          user: { id: userId.toString() },
          agentId: nonExistentId,
          projectIds: [projectId.toString()],
        });

        expect(result).toBeNull();
      });
    });
  });

  describe('Agent Version History', () => {
    let mongoServer;

    beforeAll(async () => {
      mongoServer = await MongoMemoryServer.create();
      const mongoUri = mongoServer.getUri();
      Agent = mongoose.models.Agent || mongoose.model('Agent', agentSchema);
      await mongoose.connect(mongoUri);
    }, 20000);

    afterAll(async () => {
      await mongoose.disconnect();
      await mongoServer.stop();
    });

    beforeEach(async () => {
      await Agent.deleteMany({});
    });

    test('should create an agent with a single entry in versions array', async () => {
      const agent = await createBasicAgent();

      expect(agent.versions).toBeDefined();
      expect(Array.isArray(agent.versions)).toBe(true);
      expect(agent.versions).toHaveLength(1);
      expect(agent.versions[0].name).toBe('Test Agent');
      expect(agent.versions[0].provider).toBe('test');
      expect(agent.versions[0].model).toBe('test-model');
    });

    test('should accumulate version history across multiple updates', async () => {
      const agentId = `agent_${uuidv4()}`;
      const author = new mongoose.Types.ObjectId();
      await createAgent({
        id: agentId,
        name: 'First Name',
        provider: 'test',
        model: 'test-model',
        author,
        description: 'First description',
      });

      await updateAgent(
        { id: agentId },
        { name: 'Second Name', description: 'Second description' },
      );
      await updateAgent({ id: agentId }, { name: 'Third Name', model: 'new-model' });
      const finalAgent = await updateAgent({ id: agentId }, { description: 'Final description' });

      expect(finalAgent.versions).toBeDefined();
      expect(Array.isArray(finalAgent.versions)).toBe(true);
      expect(finalAgent.versions).toHaveLength(4);

      expect(finalAgent.versions[0].name).toBe('First Name');
      expect(finalAgent.versions[0].description).toBe('First description');
      expect(finalAgent.versions[0].model).toBe('test-model');

      expect(finalAgent.versions[1].name).toBe('Second Name');
      expect(finalAgent.versions[1].description).toBe('Second description');
      expect(finalAgent.versions[1].model).toBe('test-model');

      expect(finalAgent.versions[2].name).toBe('Third Name');
      expect(finalAgent.versions[2].description).toBe('Second description');
      expect(finalAgent.versions[2].model).toBe('new-model');

      expect(finalAgent.versions[3].name).toBe('Third Name');
      expect(finalAgent.versions[3].description).toBe('Final description');
      expect(finalAgent.versions[3].model).toBe('new-model');

      expect(finalAgent.name).toBe('Third Name');
      expect(finalAgent.description).toBe('Final description');
      expect(finalAgent.model).toBe('new-model');
    });

    test('should not include metadata fields in version history', async () => {
      const agentId = `agent_${uuidv4()}`;
      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: new mongoose.Types.ObjectId(),
      });

      const updatedAgent = await updateAgent({ id: agentId }, { description: 'New description' });

      expect(updatedAgent.versions).toHaveLength(2);
      expect(updatedAgent.versions[0]._id).toBeUndefined();
      expect(updatedAgent.versions[0].__v).toBeUndefined();
      expect(updatedAgent.versions[0].name).toBe('Test Agent');
      expect(updatedAgent.versions[0].author).toBeUndefined();

      expect(updatedAgent.versions[1]._id).toBeUndefined();
      expect(updatedAgent.versions[1].__v).toBeUndefined();
    });

    test('should not recursively include previous versions', async () => {
      const agentId = `agent_${uuidv4()}`;
      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: new mongoose.Types.ObjectId(),
      });

      await updateAgent({ id: agentId }, { name: 'Updated Name 1' });
      await updateAgent({ id: agentId }, { name: 'Updated Name 2' });
      const finalAgent = await updateAgent({ id: agentId }, { name: 'Updated Name 3' });

      expect(finalAgent.versions).toHaveLength(4);

      finalAgent.versions.forEach((version) => {
        expect(version.versions).toBeUndefined();
      });
    });

    test('should handle MongoDB operators and field updates correctly', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();
      const projectId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'MongoDB Operator Test',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        tools: ['tool1'],
      });

      await updateAgent(
        { id: agentId },
        {
          description: 'Updated description',
          $push: { tools: 'tool2' },
          $addToSet: { projectIds: projectId },
        },
      );

      const firstUpdate = await getAgent({ id: agentId });
      expect(firstUpdate.description).toBe('Updated description');
      expect(firstUpdate.tools).toContain('tool1');
      expect(firstUpdate.tools).toContain('tool2');
      expect(firstUpdate.projectIds.map((id) => id.toString())).toContain(projectId.toString());
      expect(firstUpdate.versions).toHaveLength(2);

      await updateAgent(
        { id: agentId },
        {
          tools: ['tool2', 'tool3'],
        },
      );

      const secondUpdate = await getAgent({ id: agentId });
      expect(secondUpdate.tools).toHaveLength(2);
      expect(secondUpdate.tools).toContain('tool2');
      expect(secondUpdate.tools).toContain('tool3');
      expect(secondUpdate.tools).not.toContain('tool1');
      expect(secondUpdate.versions).toHaveLength(3);

      await updateAgent(
        { id: agentId },
        {
          $push: { tools: 'tool3' },
        },
      );

      const thirdUpdate = await getAgent({ id: agentId });
      const toolCount = thirdUpdate.tools.filter((t) => t === 'tool3').length;
      expect(toolCount).toBe(2);
      expect(thirdUpdate.versions).toHaveLength(4);
    });

    test('should handle parameter objects correctly', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Parameters Test',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        model_parameters: { temperature: 0.7 },
      });

      const updatedAgent = await updateAgent(
        { id: agentId },
        { model_parameters: { temperature: 0.8 } },
      );

      expect(updatedAgent.versions).toHaveLength(2);
      expect(updatedAgent.model_parameters.temperature).toBe(0.8);

      await updateAgent(
        { id: agentId },
        {
          model_parameters: {
            temperature: 0.8,
            max_tokens: 1000,
          },
        },
      );

      const complexAgent = await getAgent({ id: agentId });
      expect(complexAgent.versions).toHaveLength(3);
      expect(complexAgent.model_parameters.temperature).toBe(0.8);
      expect(complexAgent.model_parameters.max_tokens).toBe(1000);

      await updateAgent({ id: agentId }, { model_parameters: {} });

      const emptyParamsAgent = await getAgent({ id: agentId });
      expect(emptyParamsAgent.versions).toHaveLength(4);
      expect(emptyParamsAgent.model_parameters).toEqual({});
    });

    test('should not create new version for duplicate updates', async () => {
      const authorId = new mongoose.Types.ObjectId();
      const testCases = generateVersionTestCases();

      for (const testCase of testCases) {
        const testAgentId = `agent_${uuidv4()}`;

        await createAgent({
          id: testAgentId,
          provider: 'test',
          model: 'test-model',
          author: authorId,
          ...testCase.initial,
        });

        const updatedAgent = await updateAgent({ id: testAgentId }, testCase.update);
        expect(updatedAgent.versions).toHaveLength(2); // No new version created

        // Update with duplicate data should succeed but not create a new version
        const duplicateUpdate = await updateAgent({ id: testAgentId }, testCase.duplicate);

        expect(duplicateUpdate.versions).toHaveLength(2); // No new version created

        const agent = await getAgent({ id: testAgentId });
        expect(agent.versions).toHaveLength(2);
      }
    });

    test('should track updatedBy when a different user updates an agent', async () => {
      const agentId = `agent_${uuidv4()}`;
      const originalAuthor = new mongoose.Types.ObjectId();
      const updatingUser = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Original Agent',
        provider: 'test',
        model: 'test-model',
        author: originalAuthor,
        description: 'Original description',
      });

      const updatedAgent = await updateAgent(
        { id: agentId },
        { name: 'Updated Agent', description: 'Updated description' },
        { updatingUserId: updatingUser.toString() },
      );

      expect(updatedAgent.versions).toHaveLength(2);
      expect(updatedAgent.versions[1].updatedBy.toString()).toBe(updatingUser.toString());
      expect(updatedAgent.author.toString()).toBe(originalAuthor.toString());
    });

    test('should include updatedBy even when the original author updates the agent', async () => {
      const agentId = `agent_${uuidv4()}`;
      const originalAuthor = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Original Agent',
        provider: 'test',
        model: 'test-model',
        author: originalAuthor,
        description: 'Original description',
      });

      const updatedAgent = await updateAgent(
        { id: agentId },
        { name: 'Updated Agent', description: 'Updated description' },
        { updatingUserId: originalAuthor.toString() },
      );

      expect(updatedAgent.versions).toHaveLength(2);
      expect(updatedAgent.versions[1].updatedBy.toString()).toBe(originalAuthor.toString());
      expect(updatedAgent.author.toString()).toBe(originalAuthor.toString());
    });

    test('should track multiple different users updating the same agent', async () => {
      const agentId = `agent_${uuidv4()}`;
      const originalAuthor = new mongoose.Types.ObjectId();
      const user1 = new mongoose.Types.ObjectId();
      const user2 = new mongoose.Types.ObjectId();
      const user3 = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Original Agent',
        provider: 'test',
        model: 'test-model',
        author: originalAuthor,
        description: 'Original description',
      });

      // User 1 makes an update
      await updateAgent(
        { id: agentId },
        { name: 'Updated by User 1', description: 'First update' },
        { updatingUserId: user1.toString() },
      );

      // Original author makes an update
      await updateAgent(
        { id: agentId },
        { description: 'Updated by original author' },
        { updatingUserId: originalAuthor.toString() },
      );

      // User 2 makes an update
      await updateAgent(
        { id: agentId },
        { name: 'Updated by User 2', model: 'new-model' },
        { updatingUserId: user2.toString() },
      );

      // User 3 makes an update
      const finalAgent = await updateAgent(
        { id: agentId },
        { description: 'Final update by User 3' },
        { updatingUserId: user3.toString() },
      );

      expect(finalAgent.versions).toHaveLength(5);
      expect(finalAgent.author.toString()).toBe(originalAuthor.toString());

      // Check that each version has the correct updatedBy
      expect(finalAgent.versions[0].updatedBy).toBeUndefined(); // Initial creation has no updatedBy
      expect(finalAgent.versions[1].updatedBy.toString()).toBe(user1.toString());
      expect(finalAgent.versions[2].updatedBy.toString()).toBe(originalAuthor.toString());
      expect(finalAgent.versions[3].updatedBy.toString()).toBe(user2.toString());
      expect(finalAgent.versions[4].updatedBy.toString()).toBe(user3.toString());

      // Verify the final state
      expect(finalAgent.name).toBe('Updated by User 2');
      expect(finalAgent.description).toBe('Final update by User 3');
      expect(finalAgent.model).toBe('new-model');
    });

    test('should preserve original author during agent restoration', async () => {
      const agentId = `agent_${uuidv4()}`;
      const originalAuthor = new mongoose.Types.ObjectId();
      const updatingUser = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Original Agent',
        provider: 'test',
        model: 'test-model',
        author: originalAuthor,
        description: 'Original description',
      });

      await updateAgent(
        { id: agentId },
        { name: 'Updated Agent', description: 'Updated description' },
        { updatingUserId: updatingUser.toString() },
      );

      const { revertAgentVersion } = require('./Agent');
      const revertedAgent = await revertAgentVersion({ id: agentId }, 0);

      expect(revertedAgent.author.toString()).toBe(originalAuthor.toString());
      expect(revertedAgent.name).toBe('Original Agent');
      expect(revertedAgent.description).toBe('Original description');
    });

    test('should detect action metadata changes and force version update', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();
      const actionId = 'testActionId123';

      // Create agent with actions
      await createAgent({
        id: agentId,
        name: 'Agent with Actions',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        actions: [`test.com_action_${actionId}`],
        tools: ['listEvents_action_test.com', 'createEvent_action_test.com'],
      });

      // First update with forceVersion should create a version
      const firstUpdate = await updateAgent(
        { id: agentId },
        { tools: ['listEvents_action_test.com', 'createEvent_action_test.com'] },
        { updatingUserId: authorId.toString(), forceVersion: true },
      );

      expect(firstUpdate.versions).toHaveLength(2);

      // Second update with same data but forceVersion should still create a version
      const secondUpdate = await updateAgent(
        { id: agentId },
        { tools: ['listEvents_action_test.com', 'createEvent_action_test.com'] },
        { updatingUserId: authorId.toString(), forceVersion: true },
      );

      expect(secondUpdate.versions).toHaveLength(3);

      // Update without forceVersion and no changes should not create a version
      const duplicateUpdate = await updateAgent(
        { id: agentId },
        { tools: ['listEvents_action_test.com', 'createEvent_action_test.com'] },
        { updatingUserId: authorId.toString(), forceVersion: false },
      );

      expect(duplicateUpdate.versions).toHaveLength(3); // No new version created
    });

    test('should handle isDuplicateVersion with arrays containing null/undefined values', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        tools: ['tool1', null, 'tool2', undefined],
      });

      // Update with same array but different null/undefined arrangement
      const updatedAgent = await updateAgent({ id: agentId }, { tools: ['tool1', 'tool2'] });

      expect(updatedAgent.versions).toHaveLength(2);
      expect(updatedAgent.tools).toEqual(['tool1', 'tool2']);
    });

    test('should handle isDuplicateVersion with empty objects in tool_kwargs', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        tool_kwargs: [
          { tool: 'tool1', config: { setting: 'value' } },
          {},
          { tool: 'tool2', config: {} },
        ],
      });

      // Try to update with reordered but equivalent tool_kwargs
      const updatedAgent = await updateAgent(
        { id: agentId },
        {
          tool_kwargs: [
            { tool: 'tool2', config: {} },
            { tool: 'tool1', config: { setting: 'value' } },
            {},
          ],
        },
      );

      // Should create new version as order matters for arrays
      expect(updatedAgent.versions).toHaveLength(2);
    });

    test('should handle isDuplicateVersion with mixed primitive and object arrays', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        mixed_array: [1, 'string', { key: 'value' }, true, null],
      });

      // Update with same values but different types
      const updatedAgent = await updateAgent(
        { id: agentId },
        { mixed_array: ['1', 'string', { key: 'value' }, 'true', null] },
      );

      // Should create new version as types differ
      expect(updatedAgent.versions).toHaveLength(2);
    });

    test('should handle isDuplicateVersion with deeply nested objects', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      const deepObject = {
        level1: {
          level2: {
            level3: {
              level4: {
                value: 'deep',
                array: [1, 2, { nested: true }],
              },
            },
          },
        },
      };

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        model_parameters: deepObject,
      });

      // First create a version with changes
      await updateAgent({ id: agentId }, { description: 'Updated' });

      // Then try to create duplicate of the original version
      await updateAgent(
        { id: agentId },
        {
          model_parameters: deepObject,
          description: undefined,
        },
      );

      // Since we're updating back to the same model_parameters but with a different description,
      // it should create a new version
      const agent = await getAgent({ id: agentId });
      expect(agent.versions).toHaveLength(3);
    });

    test('should handle version comparison with special field types', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();
      const projectId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        projectIds: [projectId],
        model_parameters: { temperature: 0.7 },
      });

      // Update with a real field change first
      const firstUpdate = await updateAgent({ id: agentId }, { description: 'New description' });

      expect(firstUpdate.versions).toHaveLength(2);

      // Update with model parameters change
      const secondUpdate = await updateAgent(
        { id: agentId },
        { model_parameters: { temperature: 0.8 } },
      );

      expect(secondUpdate.versions).toHaveLength(3);
    });

    test('should detect changes in support_contact fields', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      // Create agent with initial support_contact
      await createAgent({
        id: agentId,
        name: 'Agent with Support Contact',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        support_contact: {
          name: 'Initial Support',
          email: 'initial@support.com',
        },
      });

      // Update support_contact name only
      const firstUpdate = await updateAgent(
        { id: agentId },
        {
          support_contact: {
            name: 'Updated Support',
            email: 'initial@support.com',
          },
        },
      );

      expect(firstUpdate.versions).toHaveLength(2);
      expect(firstUpdate.support_contact.name).toBe('Updated Support');
      expect(firstUpdate.support_contact.email).toBe('initial@support.com');

      // Update support_contact email only
      const secondUpdate = await updateAgent(
        { id: agentId },
        {
          support_contact: {
            name: 'Updated Support',
            email: 'updated@support.com',
          },
        },
      );

      expect(secondUpdate.versions).toHaveLength(3);
      expect(secondUpdate.support_contact.email).toBe('updated@support.com');

      // Try to update with same support_contact - should be detected as duplicate but return successfully
      const duplicateUpdate = await updateAgent(
        { id: agentId },
        {
          support_contact: {
            name: 'Updated Support',
            email: 'updated@support.com',
          },
        },
      );

      // Should not create a new version
      expect(duplicateUpdate.versions).toHaveLength(3);
      expect(duplicateUpdate.version).toBe(3);
      expect(duplicateUpdate.support_contact.email).toBe('updated@support.com');
    });

    test('should handle support_contact from empty to populated', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      // Create agent without support_contact
      const agent = await createAgent({
        id: agentId,
        name: 'Agent without Support',
        provider: 'test',
        model: 'test-model',
        author: authorId,
      });

      // Verify support_contact is undefined since it wasn't provided
      expect(agent.support_contact).toBeUndefined();

      // Update to add support_contact
      const updated = await updateAgent(
        { id: agentId },
        {
          support_contact: {
            name: 'New Support Team',
            email: 'support@example.com',
          },
        },
      );

      expect(updated.versions).toHaveLength(2);
      expect(updated.support_contact.name).toBe('New Support Team');
      expect(updated.support_contact.email).toBe('support@example.com');
    });

    test('should handle support_contact edge cases in isDuplicateVersion', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      // Create agent with support_contact
      await createAgent({
        id: agentId,
        name: 'Edge Case Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        support_contact: {
          name: 'Support',
          email: 'support@test.com',
        },
      });

      // Update to empty support_contact
      const emptyUpdate = await updateAgent(
        { id: agentId },
        {
          support_contact: {},
        },
      );

      expect(emptyUpdate.versions).toHaveLength(2);
      expect(emptyUpdate.support_contact).toEqual({});

      // Update back to populated support_contact
      const repopulated = await updateAgent(
        { id: agentId },
        {
          support_contact: {
            name: 'Support',
            email: 'support@test.com',
          },
        },
      );

      expect(repopulated.versions).toHaveLength(3);

      // Verify all versions have correct support_contact
      const finalAgent = await getAgent({ id: agentId });
      expect(finalAgent.versions[0].support_contact).toEqual({
        name: 'Support',
        email: 'support@test.com',
      });
      expect(finalAgent.versions[1].support_contact).toEqual({});
      expect(finalAgent.versions[2].support_contact).toEqual({
        name: 'Support',
        email: 'support@test.com',
      });
    });

    test('should preserve support_contact in version history', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      // Create agent
      await createAgent({
        id: agentId,
        name: 'Version History Test',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        support_contact: {
          name: 'Initial Contact',
          email: 'initial@test.com',
        },
      });

      // Multiple updates with different support_contact values
      await updateAgent(
        { id: agentId },
        {
          support_contact: {
            name: 'Second Contact',
            email: 'second@test.com',
          },
        },
      );

      await updateAgent(
        { id: agentId },
        {
          support_contact: {
            name: 'Third Contact',
            email: 'third@test.com',
          },
        },
      );

      const finalAgent = await getAgent({ id: agentId });

      // Verify version history
      expect(finalAgent.versions).toHaveLength(3);
      expect(finalAgent.versions[0].support_contact).toEqual({
        name: 'Initial Contact',
        email: 'initial@test.com',
      });
      expect(finalAgent.versions[1].support_contact).toEqual({
        name: 'Second Contact',
        email: 'second@test.com',
      });
      expect(finalAgent.versions[2].support_contact).toEqual({
        name: 'Third Contact',
        email: 'third@test.com',
      });

      // Current state should match last version
      expect(finalAgent.support_contact).toEqual({
        name: 'Third Contact',
        email: 'third@test.com',
      });
    });

    test('should handle partial support_contact updates', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      // Create agent with full support_contact
      await createAgent({
        id: agentId,
        name: 'Partial Update Test',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        support_contact: {
          name: 'Original Name',
          email: 'original@email.com',
        },
      });

      // MongoDB's findOneAndUpdate will replace the entire support_contact object
      // So we need to verify that partial updates still work correctly
      const updated = await updateAgent(
        { id: agentId },
        {
          support_contact: {
            name: 'New Name',
            email: '', // Empty email
          },
        },
      );

      expect(updated.versions).toHaveLength(2);
      expect(updated.support_contact.name).toBe('New Name');
      expect(updated.support_contact.email).toBe('');

      // Verify isDuplicateVersion works with partial changes - should return successfully without creating new version
      const duplicateUpdate = await updateAgent(
        { id: agentId },
        {
          support_contact: {
            name: 'New Name',
            email: '',
          },
        },
      );

      // Should not create a new version since content is the same
      expect(duplicateUpdate.versions).toHaveLength(2);
      expect(duplicateUpdate.version).toBe(2);
      expect(duplicateUpdate.support_contact.name).toBe('New Name');
      expect(duplicateUpdate.support_contact.email).toBe('');
    });

    // Edge Cases
    describe.each([
      {
        operation: 'add',
        name: 'empty file_id',
        needsAgent: true,
        params: { tool_resource: 'file_search', file_id: '' },
        shouldResolve: true,
      },
      {
        operation: 'add',
        name: 'non-existent agent',
        needsAgent: false,
        params: { tool_resource: 'file_search', file_id: 'file123' },
        shouldResolve: false,
        error: 'Agent not found for adding resource file',
      },
    ])('addAgentResourceFile with $name', ({ needsAgent, params, shouldResolve, error }) => {
      test(`should ${shouldResolve ? 'resolve' : 'reject'}`, async () => {
        const agent = needsAgent ? await createBasicAgent() : null;
        const agent_id = needsAgent ? agent.id : `agent_${uuidv4()}`;

        if (shouldResolve) {
          await expect(addAgentResourceFile({ agent_id, ...params })).resolves.toBeDefined();
        } else {
          await expect(addAgentResourceFile({ agent_id, ...params })).rejects.toThrow(error);
        }
      });
    });

    describe.each([
      {
        name: 'empty files array',
        files: [],
        needsAgent: true,
        shouldResolve: true,
      },
      {
        name: 'non-existent tool_resource',
        files: [{ tool_resource: 'non_existent_tool', file_id: 'file123' }],
        needsAgent: true,
        shouldResolve: true,
      },
      {
        name: 'non-existent agent',
        files: [{ tool_resource: 'file_search', file_id: 'file123' }],
        needsAgent: false,
        shouldResolve: false,
        error: 'Agent not found for removing resource files',
      },
    ])('removeAgentResourceFiles with $name', ({ files, needsAgent, shouldResolve, error }) => {
      test(`should ${shouldResolve ? 'resolve' : 'reject'}`, async () => {
        const agent = needsAgent ? await createBasicAgent() : null;
        const agent_id = needsAgent ? agent.id : `agent_${uuidv4()}`;

        if (shouldResolve) {
          const result = await removeAgentResourceFiles({ agent_id, files });
          expect(result).toBeDefined();
          if (agent) {
            expect(result.id).toBe(agent.id);
          }
        } else {
          await expect(removeAgentResourceFiles({ agent_id, files })).rejects.toThrow(error);
        }
      });
    });

    describe('Edge Cases', () => {
      test('should handle extremely large version history', async () => {
        const agentId = `agent_${uuidv4()}`;
        const authorId = new mongoose.Types.ObjectId();

        await createAgent({
          id: agentId,
          name: 'Version Test',
          provider: 'test',
          model: 'test-model',
          author: authorId,
        });

        for (let i = 0; i < 20; i++) {
          await updateAgent({ id: agentId }, { description: `Version ${i}` });
        }

        const agent = await getAgent({ id: agentId });
        expect(agent.versions).toHaveLength(21);
        expect(agent.description).toBe('Version 19');
      });

      test('should handle revertAgentVersion with invalid version index', async () => {
        const agentId = `agent_${uuidv4()}`;
        const authorId = new mongoose.Types.ObjectId();

        await createAgent({
          id: agentId,
          name: 'Test Agent',
          provider: 'test',
          model: 'test-model',
          author: authorId,
        });

        await expect(revertAgentVersion({ id: agentId }, 5)).rejects.toThrow('Version 5 not found');
      });

      test('should handle revertAgentVersion with non-existent agent', async () => {
        const nonExistentId = `agent_${uuidv4()}`;

        await expect(revertAgentVersion({ id: nonExistentId }, 0)).rejects.toThrow(
          'Agent not found',
        );
      });

      test('should handle updateAgent with empty update object', async () => {
        const agentId = `agent_${uuidv4()}`;
        const authorId = new mongoose.Types.ObjectId();

        await createAgent({
          id: agentId,
          name: 'Test Agent',
          provider: 'test',
          model: 'test-model',
          author: authorId,
        });

        const updatedAgent = await updateAgent({ id: agentId }, {});

        expect(updatedAgent).toBeDefined();
        expect(updatedAgent.name).toBe('Test Agent');
        expect(updatedAgent.versions).toHaveLength(1);
      });
    });
  });

  describe('Action Metadata and Hash Generation', () => {
    let mongoServer;

    beforeAll(async () => {
      mongoServer = await MongoMemoryServer.create();
      const mongoUri = mongoServer.getUri();
      Agent = mongoose.models.Agent || mongoose.model('Agent', agentSchema);
      await mongoose.connect(mongoUri);
    }, 20000);

    afterAll(async () => {
      await mongoose.disconnect();
      await mongoServer.stop();
    });

    beforeEach(async () => {
      await Agent.deleteMany({});
    });

    test('should generate consistent hash for same action metadata', async () => {
      const actionIds = ['test.com_action_123', 'example.com_action_456'];
      const actions = [
        {
          action_id: '123',
          metadata: { version: '1.0', endpoints: ['GET /api/test'], schema: { type: 'object' } },
        },
        {
          action_id: '456',
          metadata: {
            version: '2.0',
            endpoints: ['POST /api/example'],
            schema: { type: 'string' },
          },
        },
      ];

      const hash1 = await generateActionMetadataHash(actionIds, actions);
      const hash2 = await generateActionMetadataHash(actionIds, actions);

      expect(hash1).toBe(hash2);
      expect(typeof hash1).toBe('string');
      expect(hash1.length).toBe(64); // SHA-256 produces 64 character hex string
    });

    test('should generate different hashes for different action metadata', async () => {
      const actionIds = ['test.com_action_123'];
      const actions1 = [
        { action_id: '123', metadata: { version: '1.0', endpoints: ['GET /api/test'] } },
      ];
      const actions2 = [
        { action_id: '123', metadata: { version: '2.0', endpoints: ['GET /api/test'] } },
      ];

      const hash1 = await generateActionMetadataHash(actionIds, actions1);
      const hash2 = await generateActionMetadataHash(actionIds, actions2);

      expect(hash1).not.toBe(hash2);
    });

    test('should handle empty action arrays', async () => {
      const hash = await generateActionMetadataHash([], []);
      expect(hash).toBe('');
    });

    test('should handle null or undefined action arrays', async () => {
      const hash1 = await generateActionMetadataHash(null, []);
      const hash2 = await generateActionMetadataHash(undefined, []);

      expect(hash1).toBe('');
      expect(hash2).toBe('');
    });

    test('should handle missing action metadata gracefully', async () => {
      const actionIds = ['test.com_action_123', 'missing.com_action_999'];
      const actions = [
        { action_id: '123', metadata: { version: '1.0' } },
        // missing action with id '999'
      ];

      const hash = await generateActionMetadataHash(actionIds, actions);
      expect(typeof hash).toBe('string');
      expect(hash.length).toBe(64);
    });

    test('should sort action IDs for consistent hashing', async () => {
      const actionIds1 = ['b.com_action_2', 'a.com_action_1'];
      const actionIds2 = ['a.com_action_1', 'b.com_action_2'];
      const actions = [
        { action_id: '1', metadata: { version: '1.0' } },
        { action_id: '2', metadata: { version: '2.0' } },
      ];

      const hash1 = await generateActionMetadataHash(actionIds1, actions);
      const hash2 = await generateActionMetadataHash(actionIds2, actions);

      expect(hash1).toBe(hash2);
    });

    test('should handle complex nested metadata objects', async () => {
      const actionIds = ['complex.com_action_1'];
      const actions = [
        {
          action_id: '1',
          metadata: {
            version: '1.0',
            schema: {
              type: 'object',
              properties: {
                name: { type: 'string' },
                nested: {
                  type: 'object',
                  properties: {
                    id: { type: 'number' },
                    tags: { type: 'array', items: { type: 'string' } },
                  },
                },
              },
            },
            endpoints: [
              { path: '/api/test', method: 'GET', params: ['id'] },
              { path: '/api/create', method: 'POST', body: true },
            ],
          },
        },
      ];

      const hash = await generateActionMetadataHash(actionIds, actions);
      expect(typeof hash).toBe('string');
      expect(hash.length).toBe(64);
    });

    describe('Edge Cases', () => {
      test('should handle generateActionMetadataHash with null metadata', async () => {
        const hash = await generateActionMetadataHash(
          ['test.com_action_1'],
          [{ action_id: '1', metadata: null }],
        );
        expect(typeof hash).toBe('string');
      });

      test('should handle generateActionMetadataHash with deeply nested metadata', async () => {
        const deepMetadata = {
          level1: {
            level2: {
              level3: {
                level4: {
                  level5: 'deep value',
                  array: [1, 2, { nested: true }],
                },
              },
            },
          },
        };

        const hash = await generateActionMetadataHash(
          ['test.com_action_1'],
          [{ action_id: '1', metadata: deepMetadata }],
        );

        expect(typeof hash).toBe('string');
        expect(hash.length).toBe(64);
      });

      test('should handle generateActionMetadataHash with special characters', async () => {
        const specialMetadata = {
          unicode: '🚀🎉👍',
          symbols: '!@#$%^&*()_+-=[]{}|;:,.<>?',
          quotes: 'single\'s and "doubles"',
          newlines: 'line1\nline2\r\nline3',
        };

        const hash = await generateActionMetadataHash(
          ['test.com_action_1'],
          [{ action_id: '1', metadata: specialMetadata }],
        );

        expect(typeof hash).toBe('string');
        expect(hash.length).toBe(64);
      });
    });
  });

  describe('Load Agent Functionality', () => {
    let mongoServer;

    beforeAll(async () => {
      mongoServer = await MongoMemoryServer.create();
      const mongoUri = mongoServer.getUri();
      Agent = mongoose.models.Agent || mongoose.model('Agent', agentSchema);
      await mongoose.connect(mongoUri);
    }, 20000);

    afterAll(async () => {
      await mongoose.disconnect();
      await mongoServer.stop();
    });

    beforeEach(async () => {
      await Agent.deleteMany({});
    });

    test('should return null when agent_id is not provided', async () => {
      const mockReq = { user: { id: 'user123' } };
      const result = await loadAgent({
        req: mockReq,
        agent_id: null,
        endpoint: 'openai',
        model_parameters: { model: 'gpt-4' },
      });

      expect(result).toBeNull();
    });

    test('should return null when agent_id is empty string', async () => {
      const mockReq = { user: { id: 'user123' } };
      const result = await loadAgent({
        req: mockReq,
        agent_id: '',
        endpoint: 'openai',
        model_parameters: { model: 'gpt-4' },
      });

      expect(result).toBeNull();
    });

    test('should test ephemeral agent loading logic', async () => {
      const { EPHEMERAL_AGENT_ID } = require('librechat-data-provider').Constants;

      getCachedTools.mockResolvedValue({
        tool1_mcp_server1: {},
        tool2_mcp_server2: {},
        another_tool: {},
      });

      // Mock getMCPServerTools to return tools for each server
      getMCPServerTools.mockImplementation(async (_userId, server) => {
        if (server === 'server1') {
          return { tool1_mcp_server1: {} };
        } else if (server === 'server2') {
          return { tool2_mcp_server2: {} };
        }
        return null;
      });

      const mockReq = {
        user: { id: 'user123' },
        body: {
          promptPrefix: 'Test instructions',
          ephemeralAgent: {
            execute_code: true,
            web_search: true,
            mcp: ['server1', 'server2'],
          },
        },
      };

      const result = await loadAgent({
        req: mockReq,
        agent_id: EPHEMERAL_AGENT_ID,
        endpoint: 'openai',
        model_parameters: { model: 'gpt-4', temperature: 0.7 },
      });

      if (result) {
        expect(result.id).toBe(EPHEMERAL_AGENT_ID);
        expect(result.instructions).toBe('Test instructions');
        expect(result.provider).toBe('openai');
        expect(result.model).toBe('gpt-4');
        expect(result.model_parameters.temperature).toBe(0.7);
        expect(result.tools).toContain('execute_code');
        expect(result.tools).toContain('web_search');
        expect(result.tools).toContain('tool1_mcp_server1');
        expect(result.tools).toContain('tool2_mcp_server2');
      } else {
        expect(result).toBeNull();
      }
    });

    test('should return null for non-existent agent', async () => {
      const mockReq = { user: { id: 'user123' } };
      const result = await loadAgent({
        req: mockReq,
        agent_id: 'non_existent_agent',
        endpoint: 'openai',
        model_parameters: { model: 'gpt-4' },
      });

      expect(result).toBeNull();
    });

    test('should load agent when user is the author', async () => {
      const userId = new mongoose.Types.ObjectId();
      const agentId = `agent_${uuidv4()}`;

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'openai',
        model: 'gpt-4',
        author: userId,
        description: 'Test description',
        tools: ['web_search'],
      });

      const mockReq = { user: { id: userId.toString() } };
      const result = await loadAgent({
        req: mockReq,
        agent_id: agentId,
        endpoint: 'openai',
        model_parameters: { model: 'gpt-4' },
      });

      expect(result).toBeDefined();
      expect(result.id).toBe(agentId);
      expect(result.name).toBe('Test Agent');
      expect(result.author.toString()).toBe(userId.toString());
      expect(result.version).toBe(1);
    });

    test('should return agent even when user is not author (permissions checked at route level)', async () => {
      const authorId = new mongoose.Types.ObjectId();
      const userId = new mongoose.Types.ObjectId();
      const agentId = `agent_${uuidv4()}`;

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'openai',
        model: 'gpt-4',
        author: authorId,
      });

      const mockReq = { user: { id: userId.toString() } };
      const result = await loadAgent({
        req: mockReq,
        agent_id: agentId,
        endpoint: 'openai',
        model_parameters: { model: 'gpt-4' },
      });

      // With the new permission system, loadAgent returns the agent regardless of permissions
      // Permission checks are handled at the route level via middleware
      expect(result).toBeTruthy();
      expect(result.id).toBe(agentId);
      expect(result.name).toBe('Test Agent');
    });

    test('should handle ephemeral agent with no MCP servers', async () => {
      const { EPHEMERAL_AGENT_ID } = require('librechat-data-provider').Constants;

      getCachedTools.mockResolvedValue({});

      const mockReq = {
        user: { id: 'user123' },
        body: {
          promptPrefix: 'Simple instructions',
          ephemeralAgent: {
            execute_code: false,
            web_search: false,
            mcp: [],
          },
        },
      };

      const result = await loadAgent({
        req: mockReq,
        agent_id: EPHEMERAL_AGENT_ID,
        endpoint: 'openai',
        model_parameters: { model: 'gpt-3.5-turbo' },
      });

      if (result) {
        expect(result.tools).toEqual([]);
        expect(result.instructions).toBe('Simple instructions');
      } else {
        expect(result).toBeFalsy();
      }
    });

    test('should handle ephemeral agent with undefined ephemeralAgent in body', async () => {
      const { EPHEMERAL_AGENT_ID } = require('librechat-data-provider').Constants;

      getCachedTools.mockResolvedValue({});

      const mockReq = {
        user: { id: 'user123' },
        body: {
          promptPrefix: 'Basic instructions',
        },
      };

      const result = await loadAgent({
        req: mockReq,
        agent_id: EPHEMERAL_AGENT_ID,
        endpoint: 'openai',
        model_parameters: { model: 'gpt-4' },
      });

      if (result) {
        expect(result.tools).toEqual([]);
      } else {
        expect(result).toBeFalsy();
      }
    });

    describe('Edge Cases', () => {
      test('should handle loadAgent with malformed req object', async () => {
        const result = await loadAgent({
          req: null,
          agent_id: 'test',
          endpoint: 'openai',
          model_parameters: { model: 'gpt-4' },
        });

        expect(result).toBeNull();
      });

      test('should handle ephemeral agent with extremely large tool list', async () => {
        const { EPHEMERAL_AGENT_ID } = require('librechat-data-provider').Constants;

        const largeToolList = Array.from({ length: 100 }, (_, i) => `tool_${i}_mcp_server1`);
        const availableTools = largeToolList.reduce((acc, tool) => {
          acc[tool] = {};
          return acc;
        }, {});

        getCachedTools.mockResolvedValue(availableTools);

        // Mock getMCPServerTools to return all tools for server1
        getMCPServerTools.mockImplementation(async (_userId, server) => {
          if (server === 'server1') {
            return availableTools; // All 100 tools belong to server1
          }
          return null;
        });

        const mockReq = {
          user: { id: 'user123' },
          body: {
            promptPrefix: 'Test',
            ephemeralAgent: {
              execute_code: true,
              web_search: true,
              mcp: ['server1'],
            },
          },
        };

        const result = await loadAgent({
          req: mockReq,
          agent_id: EPHEMERAL_AGENT_ID,
          endpoint: 'openai',
          model_parameters: { model: 'gpt-4' },
        });

        if (result) {
          expect(result.tools.length).toBeGreaterThan(100);
        }
      });

      test('should return agent from different project (permissions checked at route level)', async () => {
        const authorId = new mongoose.Types.ObjectId();
        const userId = new mongoose.Types.ObjectId();
        const agentId = `agent_${uuidv4()}`;
        const projectId = new mongoose.Types.ObjectId();

        await createAgent({
          id: agentId,
          name: 'Project Agent',
          provider: 'openai',
          model: 'gpt-4',
          author: authorId,
          projectIds: [projectId],
        });

        const mockReq = { user: { id: userId.toString() } };
        const result = await loadAgent({
          req: mockReq,
          agent_id: agentId,
          endpoint: 'openai',
          model_parameters: { model: 'gpt-4' },
        });

        // With the new permission system, loadAgent returns the agent regardless of permissions
        // Permission checks are handled at the route level via middleware
        expect(result).toBeTruthy();
        expect(result.id).toBe(agentId);
        expect(result.name).toBe('Project Agent');
      });
    });
  });

  describe('Agent Edge Cases and Error Handling', () => {
    let mongoServer;

    beforeAll(async () => {
      mongoServer = await MongoMemoryServer.create();
      const mongoUri = mongoServer.getUri();
      Agent = mongoose.models.Agent || mongoose.model('Agent', agentSchema);
      await mongoose.connect(mongoUri);
    }, 20000);

    afterAll(async () => {
      await mongoose.disconnect();
      await mongoServer.stop();
    });

    beforeEach(async () => {
      await Agent.deleteMany({});
    });

    test('should handle agent creation with minimal required fields', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      const agent = await createAgent({
        id: agentId,
        provider: 'test',
        model: 'test-model',
        author: authorId,
      });

      expect(agent).toBeDefined();
      expect(agent.id).toBe(agentId);
      expect(agent.versions).toHaveLength(1);
      expect(agent.versions[0].provider).toBe('test');
      expect(agent.versions[0].model).toBe('test-model');
    });

    test('should handle agent creation with all optional fields', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();
      const projectId = new mongoose.Types.ObjectId();

      const agent = await createAgent({
        id: agentId,
        name: 'Complex Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        description: 'Complex description',
        instructions: 'Complex instructions',
        tools: ['tool1', 'tool2'],
        actions: ['action1', 'action2'],
        model_parameters: { temperature: 0.8, max_tokens: 1000 },
        projectIds: [projectId],
        avatar: 'https://example.com/avatar.png',
        isCollaborative: true,
        tool_resources: {
          file_search: { file_ids: ['file1', 'file2'] },
        },
      });

      expect(agent).toBeDefined();
      expect(agent.name).toBe('Complex Agent');
      expect(agent.description).toBe('Complex description');
      expect(agent.instructions).toBe('Complex instructions');
      expect(agent.tools).toEqual(['tool1', 'tool2']);
      expect(agent.actions).toEqual(['action1', 'action2']);
      expect(agent.model_parameters.temperature).toBe(0.8);
      expect(agent.model_parameters.max_tokens).toBe(1000);
      expect(agent.projectIds.map((id) => id.toString())).toContain(projectId.toString());
      expect(agent.avatar).toBe('https://example.com/avatar.png');
      expect(agent.isCollaborative).toBe(true);
      expect(agent.tool_resources.file_search.file_ids).toEqual(['file1', 'file2']);
    });

    test('should handle updateAgent with empty update object', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
      });

      const updatedAgent = await updateAgent({ id: agentId }, {});

      expect(updatedAgent).toBeDefined();
      expect(updatedAgent.name).toBe('Test Agent');
      expect(updatedAgent.versions).toHaveLength(1); // No new version should be created
    });

    test('should handle concurrent updates to different agents', async () => {
      const agent1Id = `agent_${uuidv4()}`;
      const agent2Id = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agent1Id,
        name: 'Agent 1',
        provider: 'test',
        model: 'test-model',
        author: authorId,
      });

      await createAgent({
        id: agent2Id,
        name: 'Agent 2',
        provider: 'test',
        model: 'test-model',
        author: authorId,
      });

      // Concurrent updates to different agents
      const [updated1, updated2] = await Promise.all([
        updateAgent({ id: agent1Id }, { description: 'Updated Agent 1' }),
        updateAgent({ id: agent2Id }, { description: 'Updated Agent 2' }),
      ]);

      expect(updated1.description).toBe('Updated Agent 1');
      expect(updated2.description).toBe('Updated Agent 2');
      expect(updated1.versions).toHaveLength(2);
      expect(updated2.versions).toHaveLength(2);
    });

    test('should handle agent deletion with non-existent ID', async () => {
      const nonExistentId = `agent_${uuidv4()}`;
      const result = await deleteAgent({ id: nonExistentId });

      expect(result).toBeNull();
    });

    test('should handle getListAgents with no agents', async () => {
      const authorId = new mongoose.Types.ObjectId();
      const result = await getListAgents({ author: authorId.toString() });

      expect(result).toBeDefined();
      expect(result.data).toEqual([]);
      expect(result.has_more).toBe(false);
      expect(result.first_id).toBeNull();
      expect(result.last_id).toBeNull();
    });

    test('should handle updateAgent with MongoDB operators mixed with direct updates', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        tools: ['tool1'],
      });

      // Test with $push and direct field update
      const updatedAgent = await updateAgent(
        { id: agentId },
        {
          name: 'Updated Name',
          $push: { tools: 'tool2' },
        },
      );

      expect(updatedAgent.name).toBe('Updated Name');
      expect(updatedAgent.tools).toContain('tool1');
      expect(updatedAgent.tools).toContain('tool2');
      expect(updatedAgent.versions).toHaveLength(2);
    });

    test('should handle revertAgentVersion with invalid version index', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
      });

      // Try to revert to non-existent version
      await expect(revertAgentVersion({ id: agentId }, 5)).rejects.toThrow('Version 5 not found');
    });

    test('should handle revertAgentVersion with non-existent agent', async () => {
      const nonExistentId = `agent_${uuidv4()}`;

      await expect(revertAgentVersion({ id: nonExistentId }, 0)).rejects.toThrow('Agent not found');
    });

    test('should handle addAgentResourceFile with non-existent agent', async () => {
      const nonExistentId = `agent_${uuidv4()}`;
      const mockReq = { user: { id: 'user123' } };

      await expect(
        addAgentResourceFile({
          req: mockReq,
          agent_id: nonExistentId,
          tool_resource: 'file_search',
          file_id: 'file123',
        }),
      ).rejects.toThrow('Agent not found for adding resource file');
    });

    test('should handle removeAgentResourceFiles with non-existent agent', async () => {
      const nonExistentId = `agent_${uuidv4()}`;

      await expect(
        removeAgentResourceFiles({
          agent_id: nonExistentId,
          files: [{ tool_resource: 'file_search', file_id: 'file123' }],
        }),
      ).rejects.toThrow('Agent not found for removing resource files');
    });

    test('should handle updateAgent with complex nested updates', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        model_parameters: { temperature: 0.5 },
        tools: ['tool1'],
      });

      // First update with $push operation
      const firstUpdate = await updateAgent(
        { id: agentId },
        {
          $push: { tools: 'tool2' },
        },
      );

      expect(firstUpdate.tools).toContain('tool1');
      expect(firstUpdate.tools).toContain('tool2');

      // Second update with direct field update and $addToSet
      const secondUpdate = await updateAgent(
        { id: agentId },
        {
          name: 'Updated Agent',
          model_parameters: { temperature: 0.8, max_tokens: 500 },
          $addToSet: { tools: 'tool3' },
        },
      );

      expect(secondUpdate.name).toBe('Updated Agent');
      expect(secondUpdate.model_parameters.temperature).toBe(0.8);
      expect(secondUpdate.model_parameters.max_tokens).toBe(500);
      expect(secondUpdate.tools).toContain('tool1');
      expect(secondUpdate.tools).toContain('tool2');
      expect(secondUpdate.tools).toContain('tool3');
      expect(secondUpdate.versions).toHaveLength(3);
    });

    test('should preserve version order in versions array', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Version 1',
        provider: 'test',
        model: 'test-model',
        author: authorId,
      });

      await updateAgent({ id: agentId }, { name: 'Version 2' });
      await updateAgent({ id: agentId }, { name: 'Version 3' });
      const finalAgent = await updateAgent({ id: agentId }, { name: 'Version 4' });

      expect(finalAgent.versions).toHaveLength(4);
      expect(finalAgent.versions[0].name).toBe('Version 1');
      expect(finalAgent.versions[1].name).toBe('Version 2');
      expect(finalAgent.versions[2].name).toBe('Version 3');
      expect(finalAgent.versions[3].name).toBe('Version 4');
      expect(finalAgent.name).toBe('Version 4');
    });

    test('should handle updateAgentProjects error scenarios', async () => {
      const nonExistentId = `agent_${uuidv4()}`;
      const userId = new mongoose.Types.ObjectId();
      const projectId = new mongoose.Types.ObjectId();

      // Test with non-existent agent
      const result = await updateAgentProjects({
        user: { id: userId.toString() },
        agentId: nonExistentId,
        projectIds: [projectId.toString()],
      });

      expect(result).toBeNull();
    });

    test('should handle revertAgentVersion properly', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Original Name',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        description: 'Original description',
      });

      await updateAgent(
        { id: agentId },
        { name: 'Updated Name', description: 'Updated description' },
      );

      const revertedAgent = await revertAgentVersion({ id: agentId }, 0);

      expect(revertedAgent.name).toBe('Original Name');
      expect(revertedAgent.description).toBe('Original description');
      expect(revertedAgent.author.toString()).toBe(authorId.toString());
    });

    test('should handle action-related updates with getActions error', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      // Create agent with actions that might cause getActions to fail
      await createAgent({
        id: agentId,
        name: 'Agent with Actions',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        actions: ['test.com_action_invalid_id'],
      });

      // Update should still work even if getActions fails
      const updatedAgent = await updateAgent(
        { id: agentId },
        { description: 'Updated description' },
      );

      expect(updatedAgent).toBeDefined();
      expect(updatedAgent.description).toBe('Updated description');
      expect(updatedAgent.versions).toHaveLength(2);
    });

    test('should handle updateAgent with combined MongoDB operators', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();
      const projectId1 = new mongoose.Types.ObjectId();
      const projectId2 = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        tools: ['tool1'],
        projectIds: [projectId1],
      });

      // Use multiple operators in single update - but avoid conflicting operations on same field
      const updatedAgent = await updateAgent(
        { id: agentId },
        {
          name: 'Updated Name',
          $push: { tools: 'tool2' },
          $addToSet: { projectIds: projectId2 },
        },
      );

      const finalAgent = await updateAgent(
        { id: agentId },
        {
          $pull: { projectIds: projectId1 },
        },
      );

      expect(updatedAgent).toBeDefined();
      expect(updatedAgent.name).toBe('Updated Name');
      expect(updatedAgent.tools).toContain('tool1');
      expect(updatedAgent.tools).toContain('tool2');
      expect(updatedAgent.projectIds.map((id) => id.toString())).toContain(projectId2.toString());

      expect(finalAgent).toBeDefined();
      expect(finalAgent.projectIds.map((id) => id.toString())).not.toContain(projectId1.toString());
      expect(finalAgent.versions).toHaveLength(3);
    });

    test('should handle updateAgent when agent does not exist', async () => {
      const nonExistentId = `agent_${uuidv4()}`;

      const result = await updateAgent({ id: nonExistentId }, { name: 'New Name' });

      expect(result).toBeNull();
    });

    test('should handle concurrent updates with database errors', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
      });

      // Mock findOneAndUpdate to simulate database error
      const cleanup = mockFindOneAndUpdateError(2);

      // Concurrent updates where one fails
      const promises = [
        updateAgent({ id: agentId }, { name: 'Update 1' }),
        updateAgent({ id: agentId }, { name: 'Update 2' }),
        updateAgent({ id: agentId }, { name: 'Update 3' }),
      ];

      const results = await Promise.allSettled(promises);

      cleanup();

      const succeeded = results.filter((r) => r.status === 'fulfilled').length;
      const failed = results.filter((r) => r.status === 'rejected').length;

      expect(succeeded).toBe(2);
      expect(failed).toBe(1);
    });

    test('should handle removeAgentResourceFiles when agent is deleted during operation', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        tool_resources: {
          file_search: {
            file_ids: ['file1', 'file2', 'file3'],
          },
        },
      });

      // Mock findOneAndUpdate to return null (simulating deletion)
      const originalFindOneAndUpdate = Agent.findOneAndUpdate;
      Agent.findOneAndUpdate = jest.fn().mockImplementation(() => ({
        lean: jest.fn().mockResolvedValue(null),
      }));

      // Try to remove files from deleted agent
      await expect(
        removeAgentResourceFiles({
          agent_id: agentId,
          files: [
            { tool_resource: 'file_search', file_id: 'file1' },
            { tool_resource: 'file_search', file_id: 'file2' },
          ],
        }),
      ).rejects.toThrow('Failed to update agent during file removal (pull step)');

      Agent.findOneAndUpdate = originalFindOneAndUpdate;
    });

    test('should handle loadEphemeralAgent with malformed MCP tool names', async () => {
      const { EPHEMERAL_AGENT_ID } = require('librechat-data-provider').Constants;

      getCachedTools.mockResolvedValue({
        malformed_tool_name: {}, // No mcp delimiter
        tool__server1: {}, // Wrong delimiter
        tool_mcp_server1: {}, // Correct format
        tool_mcp_server2: {}, // Different server
      });

      // Mock getMCPServerTools to return only tools matching the server
      getMCPServerTools.mockImplementation(async (_userId, server) => {
        if (server === 'server1') {
          // Only return tool that correctly matches server1 format
          return { tool_mcp_server1: {} };
        } else if (server === 'server2') {
          return { tool_mcp_server2: {} };
        }
        return null;
      });

      const mockReq = {
        user: { id: 'user123' },
        body: {
          promptPrefix: 'Test instructions',
          ephemeralAgent: {
            execute_code: false,
            web_search: false,
            mcp: ['server1'],
          },
        },
      };

      const result = await loadAgent({
        req: mockReq,
        agent_id: EPHEMERAL_AGENT_ID,
        endpoint: 'openai',
        model_parameters: { model: 'gpt-4' },
      });

      if (result) {
        expect(result.tools).toEqual(['tool_mcp_server1']);
        expect(result.tools).not.toContain('malformed_tool_name');
        expect(result.tools).not.toContain('tool__server1');
        expect(result.tools).not.toContain('tool_mcp_server2');
      }
    });

    test('should handle addAgentResourceFile when array initialization fails', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
      });

      // Mock the updateOne operation to fail but let updateAgent succeed
      const originalUpdateOne = Agent.updateOne;
      let updateOneCalled = false;
      Agent.updateOne = jest.fn().mockImplementation((...args) => {
        if (!updateOneCalled) {
          updateOneCalled = true;
          return Promise.reject(new Error('Database error'));
        }
        return originalUpdateOne.apply(Agent, args);
      });

      try {
        const result = await addAgentResourceFile({
          agent_id: agentId,
          tool_resource: 'new_tool',
          file_id: 'file123',
        });

        expect(result).toBeDefined();
        expect(result.tools).toContain('new_tool');
      } catch (error) {
        expect(error.message).toBe('Database error');
      }

      Agent.updateOne = originalUpdateOne;
    });
  });

  describe('Agent IDs Field in Version Detection', () => {
    let mongoServer;

    beforeAll(async () => {
      mongoServer = await MongoMemoryServer.create();
      const mongoUri = mongoServer.getUri();
      Agent = mongoose.models.Agent || mongoose.model('Agent', agentSchema);
      await mongoose.connect(mongoUri);
    }, 20000);

    afterAll(async () => {
      await mongoose.disconnect();
      await mongoServer.stop();
    });

    beforeEach(async () => {
      await Agent.deleteMany({});
    });

    test('should now create new version when agent_ids field changes', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      const agent = await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        agent_ids: ['agent1', 'agent2'],
      });

      expect(agent).toBeDefined();
      expect(agent.versions).toHaveLength(1);

      const updated = await updateAgent(
        { id: agentId },
        { agent_ids: ['agent1', 'agent2', 'agent3'] },
      );

      // Since agent_ids is no longer excluded, this should create a new version
      expect(updated.versions).toHaveLength(2);
      expect(updated.agent_ids).toEqual(['agent1', 'agent2', 'agent3']);
    });

    test('should detect duplicate version if agent_ids is updated to same value', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        agent_ids: ['agent1', 'agent2'],
      });

      const updatedAgent = await updateAgent(
        { id: agentId },
        { agent_ids: ['agent1', 'agent2', 'agent3'] },
      );
      expect(updatedAgent.versions).toHaveLength(2);

      // Update with same agent_ids should succeed but not create a new version
      const duplicateUpdate = await updateAgent(
        { id: agentId },
        { agent_ids: ['agent1', 'agent2', 'agent3'] },
      );
      expect(duplicateUpdate.versions).toHaveLength(2); // No new version created
    });

    test('should handle agent_ids field alongside other fields', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        description: 'Initial description',
        agent_ids: ['agent1'],
      });

      const updated = await updateAgent(
        { id: agentId },
        {
          agent_ids: ['agent1', 'agent2'],
          description: 'Updated description',
        },
      );

      expect(updated.versions).toHaveLength(2);
      expect(updated.agent_ids).toEqual(['agent1', 'agent2']);
      expect(updated.description).toBe('Updated description');

      const updated2 = await updateAgent({ id: agentId }, { description: 'Another description' });

      expect(updated2.versions).toHaveLength(3);
      expect(updated2.agent_ids).toEqual(['agent1', 'agent2']);
      expect(updated2.description).toBe('Another description');
    });

    test('should skip version creation when skipVersioning option is used', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();
      const projectId1 = new mongoose.Types.ObjectId();
      const projectId2 = new mongoose.Types.ObjectId();

      // Create agent with initial projectIds
      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        projectIds: [projectId1],
      });

      // Share agent using updateAgentProjects (which uses skipVersioning)
      const shared = await updateAgentProjects({
        user: { id: authorId.toString() }, // Use the same author ID
        agentId: agentId,
        projectIds: [projectId2.toString()],
      });

      // Should NOT create a new version due to skipVersioning
      expect(shared.versions).toHaveLength(1);
      expect(shared.projectIds.map((id) => id.toString())).toContain(projectId1.toString());
      expect(shared.projectIds.map((id) => id.toString())).toContain(projectId2.toString());

      // Unshare agent using updateAgentProjects
      const unshared = await updateAgentProjects({
        user: { id: authorId.toString() },
        agentId: agentId,
        removeProjectIds: [projectId1.toString()],
      });

      // Still should NOT create a new version
      expect(unshared.versions).toHaveLength(1);
      expect(unshared.projectIds.map((id) => id.toString())).not.toContain(projectId1.toString());
      expect(unshared.projectIds.map((id) => id.toString())).toContain(projectId2.toString());

      // Regular update without skipVersioning should create a version
      const regularUpdate = await updateAgent(
        { id: agentId },
        { description: 'Updated description' },
      );

      expect(regularUpdate.versions).toHaveLength(2);
      expect(regularUpdate.description).toBe('Updated description');

      // Direct updateAgent with MongoDB operators should still create versions
      const directUpdate = await updateAgent(
        { id: agentId },
        { $addToSet: { projectIds: { $each: [projectId1] } } },
      );

      expect(directUpdate.versions).toHaveLength(3);
      expect(directUpdate.projectIds.length).toBe(2);
    });

    test('should preserve agent_ids in version history', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        agent_ids: ['agent1'],
      });

      await updateAgent({ id: agentId }, { agent_ids: ['agent1', 'agent2'] });

      await updateAgent({ id: agentId }, { agent_ids: ['agent3'] });

      const finalAgent = await getAgent({ id: agentId });

      expect(finalAgent.versions).toHaveLength(3);
      expect(finalAgent.versions[0].agent_ids).toEqual(['agent1']);
      expect(finalAgent.versions[1].agent_ids).toEqual(['agent1', 'agent2']);
      expect(finalAgent.versions[2].agent_ids).toEqual(['agent3']);
      expect(finalAgent.agent_ids).toEqual(['agent3']);
    });

    test('should handle empty agent_ids arrays', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
        agent_ids: ['agent1', 'agent2'],
      });

      const updated = await updateAgent({ id: agentId }, { agent_ids: [] });

      expect(updated.versions).toHaveLength(2);
      expect(updated.agent_ids).toEqual([]);

      // Update with same empty agent_ids should succeed but not create a new version
      const duplicateUpdate = await updateAgent({ id: agentId }, { agent_ids: [] });
      expect(duplicateUpdate.versions).toHaveLength(2); // No new version created
      expect(duplicateUpdate.agent_ids).toEqual([]);
    });

    test('should handle agent without agent_ids field', async () => {
      const agentId = `agent_${uuidv4()}`;
      const authorId = new mongoose.Types.ObjectId();

      const agent = await createAgent({
        id: agentId,
        name: 'Test Agent',
        provider: 'test',
        model: 'test-model',
        author: authorId,
      });

      expect(agent.agent_ids).toEqual([]);

      const updated = await updateAgent({ id: agentId }, { agent_ids: ['agent1'] });

      expect(updated.versions).toHaveLength(2);
      expect(updated.agent_ids).toEqual(['agent1']);
    });
  });
});

describe('Support Contact Field', () => {
  let mongoServer;

  beforeAll(async () => {
    mongoServer = await MongoMemoryServer.create();
    const mongoUri = mongoServer.getUri();
    Agent = mongoose.models.Agent || mongoose.model('Agent', agentSchema);
    await mongoose.connect(mongoUri);
  }, 20000);

  afterAll(async () => {
    await mongoose.disconnect();
    await mongoServer.stop();
  });

  beforeEach(async () => {
    await Agent.deleteMany({});
  });

  it('should not create subdocument with ObjectId for support_contact', async () => {
    const userId = new mongoose.Types.ObjectId();
    const agentData = {
      id: 'agent_test_support',
      name: 'Test Agent',
      provider: 'openai',
      model: 'gpt-4',
      author: userId,
      support_contact: {
        name: 'Support Team',
        email: 'support@example.com',
      },
    };

    // Create agent
    const agent = await createAgent(agentData);

    // Verify support_contact is stored correctly
    expect(agent.support_contact).toBeDefined();
    expect(agent.support_contact.name).toBe('Support Team');
    expect(agent.support_contact.email).toBe('support@example.com');

    // Verify no _id field is created in support_contact
    expect(agent.support_contact._id).toBeUndefined();

    // Fetch from database to double-check
    const dbAgent = await Agent.findOne({ id: agentData.id });
    expect(dbAgent.support_contact).toBeDefined();
    expect(dbAgent.support_contact.name).toBe('Support Team');
    expect(dbAgent.support_contact.email).toBe('support@example.com');
    expect(dbAgent.support_contact._id).toBeUndefined();
  });

  it('should handle empty support_contact correctly', async () => {
    const userId = new mongoose.Types.ObjectId();
    const agentData = {
      id: 'agent_test_empty_support',
      name: 'Test Agent',
      provider: 'openai',
      model: 'gpt-4',
      author: userId,
      support_contact: {},
    };

    const agent = await createAgent(agentData);

    // Verify empty support_contact is stored as empty object
    expect(agent.support_contact).toEqual({});
    expect(agent.support_contact._id).toBeUndefined();
  });

  it('should handle missing support_contact correctly', async () => {
    const userId = new mongoose.Types.ObjectId();
    const agentData = {
      id: 'agent_test_no_support',
      name: 'Test Agent',
      provider: 'openai',
      model: 'gpt-4',
      author: userId,
    };

    const agent = await createAgent(agentData);

    // Verify support_contact is undefined when not provided
    expect(agent.support_contact).toBeUndefined();
  });

  describe('getListAgentsByAccess - Security Tests', () => {
    let userA, userB;
    let agentA1, agentA2, agentA3;

    beforeEach(async () => {
      Agent = mongoose.models.Agent || mongoose.model('Agent', agentSchema);
      await Agent.deleteMany({});
      await AclEntry.deleteMany({});

      // Create two users
      userA = new mongoose.Types.ObjectId();
      userB = new mongoose.Types.ObjectId();

      // Create agents for user A
      agentA1 = await createAgent({
        id: `agent_${uuidv4().slice(0, 12)}`,
        name: 'Agent A1',
        description: 'User A agent 1',
        provider: 'openai',
        model: 'gpt-4',
        author: userA,
      });

      agentA2 = await createAgent({
        id: `agent_${uuidv4().slice(0, 12)}`,
        name: 'Agent A2',
        description: 'User A agent 2',
        provider: 'openai',
        model: 'gpt-4',
        author: userA,
      });

      agentA3 = await createAgent({
        id: `agent_${uuidv4().slice(0, 12)}`,
        name: 'Agent A3',
        description: 'User A agent 3',
        provider: 'openai',
        model: 'gpt-4',
        author: userA,
      });
    });

    test('should return empty list when user has no accessible agents (empty accessibleIds)', async () => {
      // User B has no agents and no shared agents
      const result = await getListAgentsByAccess({
        accessibleIds: [],
        otherParams: {},
      });

      expect(result.data).toHaveLength(0);
      expect(result.has_more).toBe(false);
      expect(result.first_id).toBeNull();
      expect(result.last_id).toBeNull();
    });

    test('should not return other users agents when accessibleIds is empty', async () => {
      // User B trying to list agents with empty accessibleIds should not see User A's agents
      const result = await getListAgentsByAccess({
        accessibleIds: [],
        otherParams: { author: userB },
      });

      expect(result.data).toHaveLength(0);
      expect(result.has_more).toBe(false);
    });

    test('should only return agents in accessibleIds list', async () => {
      // Give User B access to only one of User A's agents
      const accessibleIds = [agentA1._id];

      const result = await getListAgentsByAccess({
        accessibleIds,
        otherParams: {},
      });

      expect(result.data).toHaveLength(1);
      expect(result.data[0].id).toBe(agentA1.id);
      expect(result.data[0].name).toBe('Agent A1');
    });

    test('should return multiple accessible agents when provided', async () => {
      // Give User B access to two of User A's agents
      const accessibleIds = [agentA1._id, agentA3._id];

      const result = await getListAgentsByAccess({
        accessibleIds,
        otherParams: {},
      });

      expect(result.data).toHaveLength(2);
      const returnedIds = result.data.map((agent) => agent.id);
      expect(returnedIds).toContain(agentA1.id);
      expect(returnedIds).toContain(agentA3.id);
      expect(returnedIds).not.toContain(agentA2.id);
    });

    test('should respect other query parameters while enforcing accessibleIds', async () => {
      // Give access to all agents but filter by name
      const accessibleIds = [agentA1._id, agentA2._id, agentA3._id];

      const result = await getListAgentsByAccess({
        accessibleIds,
        otherParams: { name: 'Agent A2' },
      });

      expect(result.data).toHaveLength(1);
      expect(result.data[0].id).toBe(agentA2.id);
    });

    test('should handle pagination correctly with accessibleIds filter', async () => {
      // Create more agents
      const moreAgents = [];
      for (let i = 4; i <= 10; i++) {
        const agent = await createAgent({
          id: `agent_${uuidv4().slice(0, 12)}`,
          name: `Agent A${i}`,
          description: `User A agent ${i}`,
          provider: 'openai',
          model: 'gpt-4',
          author: userA,
        });
        moreAgents.push(agent);
      }

      // Give access to all agents
      const allAgentIds = [agentA1, agentA2, agentA3, ...moreAgents].map((a) => a._id);

      // First page
      const page1 = await getListAgentsByAccess({
        accessibleIds: allAgentIds,
        otherParams: {},
        limit: 5,
      });

      expect(page1.data).toHaveLength(5);
      expect(page1.has_more).toBe(true);
      expect(page1.after).toBeTruthy();

      // Second page
      const page2 = await getListAgentsByAccess({
        accessibleIds: allAgentIds,
        otherParams: {},
        limit: 5,
        after: page1.after,
      });

      expect(page2.data).toHaveLength(5);
      expect(page2.has_more).toBe(false);

      // Verify no overlap between pages
      const page1Ids = page1.data.map((a) => a.id);
      const page2Ids = page2.data.map((a) => a.id);
      const intersection = page1Ids.filter((id) => page2Ids.includes(id));
      expect(intersection).toHaveLength(0);
    });

    test('should return empty list when accessibleIds contains non-existent IDs', async () => {
      // Try with non-existent agent IDs
      const fakeIds = [new mongoose.Types.ObjectId(), new mongoose.Types.ObjectId()];

      const result = await getListAgentsByAccess({
        accessibleIds: fakeIds,
        otherParams: {},
      });

      expect(result.data).toHaveLength(0);
      expect(result.has_more).toBe(false);
    });

    test('should handle undefined accessibleIds as empty array', async () => {
      // When accessibleIds is undefined, it should be treated as empty array
      const result = await getListAgentsByAccess({
        accessibleIds: undefined,
        otherParams: {},
      });

      expect(result.data).toHaveLength(0);
      expect(result.has_more).toBe(false);
    });

    test('should combine accessibleIds with author filter correctly', async () => {
      // Create an agent for User B
      const agentB1 = await createAgent({
        id: `agent_${uuidv4().slice(0, 12)}`,
        name: 'Agent B1',
        description: 'User B agent 1',
        provider: 'openai',
        model: 'gpt-4',
        author: userB,
      });

      // Give User B access to one of User A's agents
      const accessibleIds = [agentA1._id, agentB1._id];

      // Filter by author should further restrict the results
      const result = await getListAgentsByAccess({
        accessibleIds,
        otherParams: { author: userB },
      });

      expect(result.data).toHaveLength(1);
      expect(result.data[0].id).toBe(agentB1.id);
      expect(result.data[0].author).toBe(userB.toString());
    });
  });
});

function createBasicAgent(overrides = {}) {
  const defaults = {
    id: `agent_${uuidv4()}`,
    name: 'Test Agent',
    provider: 'test',
    model: 'test-model',
    author: new mongoose.Types.ObjectId(),
  };
  return createAgent({ ...defaults, ...overrides });
}

function createTestIds() {
  return {
    agentId: `agent_${uuidv4()}`,
    authorId: new mongoose.Types.ObjectId(),
    projectId: new mongoose.Types.ObjectId(),
    fileId: uuidv4(),
  };
}

function createFileOperations(agentId, fileIds, operation = 'add') {
  return fileIds.map((fileId) =>
    operation === 'add'
      ? addAgentResourceFile({ agent_id: agentId, tool_resource: 'test_tool', file_id: fileId })
      : removeAgentResourceFiles({
          agent_id: agentId,
          files: [{ tool_resource: 'test_tool', file_id: fileId }],
        }),
  );
}

function mockFindOneAndUpdateError(errorOnCall = 1) {
  const original = Agent.findOneAndUpdate;
  let callCount = 0;

  Agent.findOneAndUpdate = jest.fn().mockImplementation((...args) => {
    callCount++;
    if (callCount === errorOnCall) {
      throw new Error('Database connection lost');
    }
    return original.apply(Agent, args);
  });

  return () => {
    Agent.findOneAndUpdate = original;
  };
}

function generateVersionTestCases() {
  const projectId1 = new mongoose.Types.ObjectId();
  const projectId2 = new mongoose.Types.ObjectId();

  return [
    {
      name: 'simple field update',
      initial: {
        name: 'Test Agent',
        description: 'Initial description',
      },
      update: { name: 'Updated Name' },
      duplicate: { name: 'Updated Name' },
    },
    {
      name: 'object field update',
      initial: {
        model_parameters: { temperature: 0.7 },
      },
      update: { model_parameters: { temperature: 0.8 } },
      duplicate: { model_parameters: { temperature: 0.8 } },
    },
    {
      name: 'array field update',
      initial: {
        tools: ['tool1', 'tool2'],
      },
      update: { tools: ['tool2', 'tool3'] },
      duplicate: { tools: ['tool2', 'tool3'] },
    },
    {
      name: 'projectIds update',
      initial: {
        projectIds: [projectId1],
      },
      update: { projectIds: [projectId1, projectId2] },
      duplicate: { projectIds: [projectId2, projectId1] },
    },
  ];
}