probe-code 0.6.0

AI-friendly, fully local, semantic code search tool for large codebases
Documentation
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
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Probe - AI-Native Code Understanding</title>
	<!-- Add Marked.js for Markdown rendering -->
	<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
	<!-- Add Highlight.js for syntax highlighting -->
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github.min.css">
	<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
	<!-- Add Mermaid.js for diagram rendering -->
	<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
	<style>
		body {
			font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
			margin: 0;
			padding: 0;
			line-height: 1.5;
			color: #333;
			min-height: 100vh;
			overflow-x: hidden;
			overflow-y: auto;
		}

		#chat-container {
			max-width: 868px;
			/* 900px - 16px padding on each side */
			margin: 0 auto;
			display: flex;
			flex-direction: column;
			min-height: 100vh;
			/* Changed from height to min-height to allow expansion */
			position: relative;
			box-sizing: border-box;
		}

		.header {
			padding: 10px 0;
			border-bottom: 1px solid #eee;
		}

		.header-container {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.header-left {
			display: flex;
			align-items: center;
		}

		.header-logo {
			height: 30px;
			margin-right: 10px;
		}

		.new-chat-link {
			font-size: 15px;
			color: #555;
			text-decoration: none;
			font-weight: 500;
			padding: 5px 10px;
			border: 1px solid #ddd;
			border-radius: 4px;
			margin-left: 5px;
			transition: all 0.2s ease;
		}

		.new-chat-link:hover {
			background-color: #f5f5f5;
			border-color: #ccc;
		}

		#messages {
			flex: 1;
			background-color: #fff;
			/* Removed overflow-y: auto to let the page handle scrolling */
			margin-bottom: 80px;
			/* Keep margin for fixed input form */
			margin-top: 20px;
			/* Space for fixed input form */
		}

		.tool-call {
			margin: 10px 0;
			border: 1px solid #ddd;
			border-radius: 8px;
			background-color: #f8f9fa;
			overflow: hidden;
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
			transition: all 0.2s ease;
		}

		.tool-call:hover {
			box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
		}

		.tool-call-header {
			background-color: #e9ecef;
			padding: 10px 14px;
			font-weight: bold;
			border-bottom: 1px solid #ddd;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.tool-call-name {
			color: #0066cc;
			font-size: 1.05em;
		}

		.tool-call-timestamp {
			font-size: 0.8em;
			color: #666;
			font-style: italic;
		}

		.tool-call-content {
			padding: 12px;
		}

		.tool-call-description {
			background-color: #ffffff;
			padding: 10px 12px;
			border-radius: 6px;
			border-left: 3px solid #44CDF3;
			margin-bottom: 10px;
			font-size: 0.95em;
			color: #333;
		}

		.tool-call-args {
			background-color: #ffffff;
			padding: 10px;
			border-radius: 6px;
			border: 1px solid #eee;
			font-family: SFMono-Regular, Consolas, Liberation Mono, Menlo, monospace;
			font-size: 0.9em;
			margin-bottom: 10px;
			white-space: pre-wrap;
		}

		.tool-call-result {
			background-color: #f0f8ff;
			padding: 10px;
			border-radius: 6px;
			border: 1px solid #e0e8ff;
			font-family: SFMono-Regular, Consolas, Liberation Mono, Menlo, monospace;
			font-size: 0.9em;
			white-space: pre-wrap;
			max-height: 300px;
			overflow-y: auto;
		}


		#input-form {
			position: fixed;
			display: flex;
			padding: 16px 0;
			background-color: white;
			border-top: 1px solid #ddd;
			z-index: 100;
			max-width: 868px;
			width: calc(100% - 32px);
			margin: 0 auto;
			left: 50%;
			transform: translateX(-50%);
			box-sizing: border-box;
			align-items: flex-end;
			/* Align items to the bottom */
		}

		#input-form.centered {
			top: 50%;
			transform: translate(-50%, -50%);
			border-top: none;
		}

		.centered-logo-container {
			text-align: center;
			margin-bottom: 20px;
			position: fixed;
			top: 35%;
			left: 50%;
			transform: translate(-50%, -100%);
			z-index: 99;
		}

		.api-setup-mode .centered-logo-container {
			position: static;
			margin: 40px auto 20px;
			width: 100%;
			max-width: 800px;
			transform: none;
		}

		.centered-logo-container h1 {
			font-weight: 300;
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 0;
		}

		.centered-logo-container h1 img {
			height: 80px;
			margin-right: 16px;
		}

		.centered-logo-container h1 {
			font-size: 38px;
		}

		#input-form.bottom {
			bottom: 0;
		}

		.search-suggestions {
			color: #999;
			font-size: 0.85em;
			display: none;
			text-align: left;
			padding: 0;
			position: fixed;
			max-width: 868px;
			width: calc(100% - 32px);
			margin: 0 auto;
			background-color: white;
			left: 50%;
			transform: translateX(-50%);
			z-index: 99;
		}

		.search-suggestions ul {
			list-style: none;
			padding: 0;
			margin: 0;
			display: flex;
			flex-wrap: wrap;
		}

		.search-suggestions li {
			padding: 6px 16px 6px 0;
			white-space: nowrap;
			cursor: pointer;
		}

		.search-suggestions li:hover {
			color: #44CDF3;
		}

		#input-form.centered .search-suggestions {
			display: block;
		}

		.folder-info {
			color: #666;
			font-size: 0.9em;
			margin-top: 10px;
			padding-top: 10px;
			border-top: 1px solid #e0e0e0;
			font-style: italic;
			font-weight: 500;
		}

		#input-form.centered .folder-info {
			display: block;
		}


		#message-input {
			resize: none;
			flex: 1;
			padding: 12px 16px;
			border: 1px solid #ddd;
			border-radius: 8px;
			font-size: 14px;
			box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
			resize: none;
			overflow-y: auto;
			height: 1.5em;
			/* Changed from 44px to auto */
			min-height: 44px;
			/* Ensures 1 row minimum */
			max-height: 200px;
			/* Limits to ~10 rows */
			line-height: 1.5em;

			box-sizing: border-box;
		}

		button {
			padding: 12px 24px;
			margin-left: 10px;
			background-color: #44CDF3;
			color: white;
			border: none;
			border-radius: 8px;
			cursor: pointer;
			font-weight: bold;
			font-size: 18px;
			box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
			transition: all 0.2s ease;
			align-self: flex-end;
			/* Ensure button aligns to bottom */
			height: 44px;
			/* Match the height of the single-line textarea */
		}

		button:hover {
			background-color: #2bb5db;
		}


		#folder-list ul {
			margin: 4px 0;
			padding-left: 20px;
		}

		#folder-list li {
			padding: 2px 0;
		}

		#folder-list strong {
			color: #333;
			font-weight: 600;
		}

		.footer {
			text-align: center;
			padding: 10px;
			font-size: 14px;
			color: #666;
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: white;
			border-top: 1px solid #eee;
			z-index: 50;
		}

		.footer a {
			color: #2196F3;
			text-decoration: none;
		}

		.footer a:hover {
			text-decoration: underline;
		}

		.header-container {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}

		.example {
			font-style: italic;
			color: #666;
			margin: 8px 0;
		}

		/* Markdown styling */
		.markdown-content {
			line-height: 1.6;
		}

		.markdown-content h1,
		.markdown-content h2,
		.markdown-content h3 {
			margin-top: 24px;
			margin-bottom: 16px;
			font-weight: 600;
			line-height: 1.25;
		}

		.markdown-content h1 {
			font-size: 2em;
		}

		.markdown-content h2 {
			font-size: 1.5em;
		}

		.markdown-content h3 {
			font-size: 1.25em;
		}

		.markdown-content p,
		.markdown-content ul,
		.markdown-content ol {
			margin-top: 0;
			margin-bottom: 16px;
		}

		.markdown-content code {
			padding: 0.2em 0.4em;
			margin: 0;
			font-size: 85%;
			background-color: rgba(27, 31, 35, 0.05);
			border-radius: 3px;
			font-family: SFMono-Regular, Consolas, Liberation Mono, Menlo, monospace;
		}

		.markdown-content pre {
			padding: 16px;
			overflow: auto;
			font-size: 85%;
			line-height: 1.45;
			background-color: #f6f8fa;
			border-radius: 3px;
			margin-top: 0;
			margin-bottom: 16px;
		}

		.markdown-content pre code {
			padding: 0;
			margin: 0;
			font-size: 100%;
			background-color: transparent;
			border: 0;
		}

		.user-message {
			background-color: #f1f1f1;
			padding: 10px 14px;
			border-radius: 18px;
			margin-bottom: 12px;
			max-width: 80%;
			align-self: flex-end;
			font-weight: 500;
		}

		.ai-message {
			background-color: transparent;
			padding: 10px 14px;
			margin-bottom: 4px;
			max-width: 90%;
			align-self: flex-start;
		}

		.message-container {
			display: flex;
			flex-direction: column;
		}

		.copy-button-container {
			align-self: flex-start;
			margin-bottom: 12px;
			margin-top: -20px;
		}

		.copy-button {
			background-color: white;
			border-radius: 4px;
			padding: 4px 8px;
			cursor: pointer;
			font-size: 12px;
			color: #666;
			display: flex;
			align-items: center;
			border: none;
		}

		.copy-button:hover {
			background-color: #d0d0d0;
		}

		.copy-button svg {
			width: 16px;
			height: 16px;
			margin-right: 4px;
		}

		.message-container {
			display: flex;
			flex-direction: column;
		}

		/* Mermaid diagram styling */
		.mermaid {
			background-color: #f8f9fa;
			padding: 16px;
			border-radius: 8px;
			margin: 16px 0;
			overflow-x: auto;
			text-align: center;
			position: relative;
		}

		.mermaid svg,
		.mermaid-png {
			max-width: 100%;
			height: auto;
			transition: transform 0.2s ease;
		}

		/* Zoom icon overlay */
		.mermaid-container {
			position: relative;
			display: inline-block;
		}

		.zoom-icon {
			position: absolute;
			top: 10px;
			right: 10px;
			background-color: rgba(255, 255, 255, 0.8);
			border-radius: 50%;
			width: 32px;
			height: 32px;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
			opacity: 0;
			transition: opacity 0.2s ease;
			box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
			z-index: 10;
		}

		.mermaid-container:hover .zoom-icon {
			opacity: 1;
		}

		.zoom-icon svg {
			width: 18px;
			height: 18px;
		}

		/* Fullscreen dialog */
		.diagram-dialog {
			position: fixed;
			top: 0;
			left: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.85);
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 1000;
			padding: 40px;
			box-sizing: border-box;
			opacity: 0;
			pointer-events: none;
			transition: opacity 0.3s ease;
			overflow: hidden;
			/* Prevent any scrolling */
		}

		.diagram-dialog.active {
			opacity: 1;
			pointer-events: auto;
		}

		.diagram-dialog-content {
			max-width: 90%;
			max-height: 90%;
			background-color: white;
			border-radius: 8px;
			padding: 20px;
			position: relative;
			display: flex;
			align-items: center;
			justify-content: center;
			overflow: hidden;
			/* Prevent scrollbars */
		}

		.diagram-dialog img,
		.diagram-dialog svg {
			max-width: 100%;
			max-height: 100%;
			object-fit: contain;
			/* Ensure image fits while maintaining aspect ratio */
			display: block;
		}

		.close-dialog {
			position: absolute;
			top: 10px;
			right: 10px;
			background-color: rgba(255, 255, 255, 0.8);
			border-radius: 50%;
			width: 36px;
			height: 36px;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
			box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
			z-index: 1001;
		}

		.close-dialog svg {
			width: 20px;
			height: 20px;
		}

		/* Token usage display styles */
		.token-usage {
			position: fixed;
			bottom: 80px;
			right: 20px;
			background-color: rgba(255, 255, 255, 0.95);
			border: 1px solid #ddd;
			border-radius: 8px;
			padding: 10px 14px;
			font-size: 12px;
			color: #666;
			box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
			z-index: 100;
			display: none;
			/* Hidden by default, shown after first message */
		}

		.token-usage-content {
			display: flex;
			flex-direction: column;
			gap: 6px;
		}

		.token-usage-table {
			display: table;
			width: 100%;
			border-collapse: collapse;
		}

		.token-usage-row {
			display: table-row;
		}

		.token-label {
			display: table-cell;
			font-weight: bold;
			color: #444;
			padding-right: 10px;
			text-align: left;
			white-space: nowrap;
		}

		.token-value {
			display: table-cell;
			text-align: right;
			white-space: nowrap;
		}

		.cache-info {
			color: #888;
			font-size: 11px;
			margin-left: 5px;
		}
	</style>
	<style>
		/* Styles for the API key setup message */
		#api-key-setup {
			display: none;
			background-color: #f8f9fa;
			border: 1px solid #ddd;
			border-radius: 8px;
			padding: 20px;
			margin: 20px auto;
			max-width: 800px;
			box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
		}

		#api-key-setup h2 {
			color: #333;
			margin-top: 0;
			border-bottom: 1px solid #eee;
			padding-bottom: 10px;
		}

		#api-key-setup code {
			background-color: #f1f1f1;
			padding: 2px 5px;
			border-radius: 3px;
			font-family: monospace;
		}

		/* API Key Form Styles */
		#api-key-form {
			background-color: #fff;
			border: 1px solid #ddd;
			border-radius: 8px;
			padding: 20px;
			margin-top: 20px;
		}

		#api-key-form h3 {
			margin-top: 0;
			color: #44CDF3;
		}

		#api-key-form .form-group {
			margin-bottom: 15px;
		}

		#api-key-form label {
			display: block;
			margin-bottom: 5px;
			font-weight: 500;
		}

		#api-key-form select,
		#api-key-form input {
			width: 100%;
			padding: 10px;
			border: 1px solid #ddd;
			border-radius: 4px;
			font-size: 14px;
		}

		#api-key-form .buttons {
			display: flex;
			justify-content: space-between;
			margin-top: 20px;
		}

		#api-key-form button {
			padding: 10px 15px;
			background-color: #44CDF3;
			color: white;
			border: none;
			border-radius: 4px;
			cursor: pointer;
			font-weight: bold;
		}

		#api-key-form button:hover {
			background-color: #2bb5db;
		}

		#reset-api-key {
			background-color: #f44336 !important;
		}

		#reset-api-key:hover {
			background-color: #d32f2f !important;
		}

		.api-key-status {
			margin-top: 10px;
			padding: 10px;
			border-radius: 4px;
			font-size: 14px;
		}

		.api-key-status.success {
			background-color: #e8f5e9;
			color: #2e7d32;
			border-left: 4px solid #4caf50;
		}

		.api-key-status.error {
			background-color: #ffebee;
			color: #c62828;
			border-left: 4px solid #f44336;
		}

		h1 a:hover {
			text-decoration: underline;
		}
	</style>
</head>

<body>
	<div id="chat-container">
		<div class="header">
			<div class="header-container">
				<div class="header-left">
					<img src="logo.png" alt="Probe Logo" class="header-logo">
					<a href="#" class="new-chat-link">New chat</a>
				</div>
				<div id="api-settings">
					<a href="#" id="header-reset-api-key"
						style="display: none; font-size: 12px; color: #f44336; text-decoration: none;">Reset API Key</a>
				</div>
			</div>
		</div>

		<div id="empty-state-logo" class="centered-logo-container">
			<h1><img src="logo.png" alt="Probe Logo"><a href="https://probeai.dev/"
					style="color: inherit; text-decoration: none;">Probe </a>&nbsp;- AI-Native Code Understanding</h1>
		</div>

		<!-- API Key Setup Instructions -->
		<div id="api-key-setup">
			<h2>API Key Setup Required</h2>
			<p>To use the Probe AI chat interface, you need to configure at least one API key. You have two options:</p>

			<!-- API Key Web Form -->
			<div id="api-key-form">
				<h3>Option 1: Configure API Key in Browser</h3>
				<p>Enter your API key details below to start using the chat interface immediately:</p>

				<div class="form-group">
					<label for="api-provider">API Provider:</label>
					<select id="api-provider">
						<option value="anthropic">Anthropic Claude</option>
						<option value="openai">OpenAI</option>
						<option value="google">Google AI</option>
					</select>
				</div>

				<div class="form-group">
					<label for="api-key">API Key:</label>
					<input type="password" id="api-key" placeholder="Enter your API key">
				</div>

				<div class="form-group">
					<label for="api-url">Custom API URL (Optional):</label>
					<input type="text" id="api-url" placeholder="Leave blank for default API URL">
				</div>

				<div class="api-key-status" id="api-key-status" style="display: none;"></div>

				<div class="buttons">
					<button type="button" id="save-api-key">Save API Key</button>
				</div>

				<p style="margin-top: 10px; font-size: 0.9em; color: #666;">
					Your API key will be stored in your browser's local storage and sent with each request.
					No data is stored on our servers.
				</p>
			</div>

			<div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee;">
				<h3>Option 2: Using Server-Side Configuration</h3>
				<p>Alternatively, you can configure API keys on the server:</p>

				<div style="background-color: #f8f9fa; padding: 15px; border-radius: 6px; margin-top: 10px;">
					<p><strong>Using a .env file:</strong></p>
					<ol style="margin-left: 20px;">
						<li>Create a <code>.env</code> file in the current directory by copying <code>.env.example</code></li>
						<li>Add your API key to the <code>.env</code> file (uncomment and replace with your key)</li>
						<li>Restart the application</li>
					</ol>

					<p style="margin-top: 15px;"><strong>Using environment variables:</strong></p>
					<ul style="margin-left: 20px;">
						<li>Anthropic: <code>ANTHROPIC_API_KEY=your_anthropic_api_key</code></li>
						<li>OpenAI: <code>OPENAI_API_KEY=your_openai_api_key</code></li>
						<li>Google AI: <code>GOOGLE_API_KEY=your_google_api_key</code></li>
					</ul>
				</div>
			</div>
		</div>
		<div id="messages" class="message-container"></div>
	</div>
	<form id="input-form" onsubmit="return false;">
		<textarea id="message-input" placeholder="Ask about code..." required rows="1"></textarea>
		<button type="button" id="search-button">Search</button>
	</form>
	<div class="search-suggestions">
		<ul>
			<li>Find functions that handle user authentication</li>
			<li>Search for database connection implementations</li>
			<li>Show error handling patterns in the codebase</li>
			<li>List all API endpoints in the project</li>
			<li>Find code that processes user input</li>
			<li>Show how configuration is loaded</li>
			<li>Find file parsing implementations</li>
		</ul>
		<div id="folder-info" class="folder-info"></div>
	</div>
	<div id="token-usage" class="token-usage">
		<div class="token-usage-content">
			<div class="token-usage-table">
				<div class="token-usage-row">
					<div class="token-label">Current:</div>
					<div class="token-value">
						<span id="current-request">0</span> req / <span id="current-response">0</span> resp
					</div>
				</div>
				<div class="token-usage-row">
					<div class="token-label">Cache:</div>
					<div class="token-value">
						<span id="current-cache-read">0</span> read / <span id="current-cache-write">0</span> write
					</div>
				</div>
				<div class="token-usage-row">
					<div class="token-label">Context:</div>
					<div class="token-value">
						<span id="context-window">0</span> tokens
					</div>
				</div>
				<div class="token-usage-row">
					<div class="token-label">Total Cache:</div>
					<div class="token-value">
						<span id="total-cache-read">0</span> read / <span id="total-cache-write">0</span> write
					</div>
				</div>
				<div class="token-usage-row">
					<div class="token-label">Total:</div>
					<div class="token-value">
						<span id="total-request">0</span> req / <span id="total-response">0</span> resp
					</div>
				</div>
			</div>
		</div>
	</div>
	<div class="footer">
		Powered by <a href="https://probeai.dev/" target="_blank">Probe</a>
	</div>
	</div>
	<script>
		// Token Usage Display Functionality
		// Function to update token usage display
		function updateTokenUsageDisplay(tokenUsage) {
			if (!tokenUsage) return;

			console.log('[TokenUsage] Updating display with:', tokenUsage);

			// Update current token usage
			if (tokenUsage.current) {
				document.getElementById('current-request').textContent = tokenUsage.current.request || 0;
				document.getElementById('current-response').textContent = tokenUsage.current.response || 0;

				// Update cache information in separate row
				const cacheRead = tokenUsage.current.cacheRead || 0;
				const cacheWrite = tokenUsage.current.cacheWrite || 0;
				document.getElementById('current-cache-read').textContent = cacheRead;
				document.getElementById('current-cache-write').textContent = cacheWrite;
			}

			// Update context window - force display even if 0
			const contextWindow = tokenUsage.contextWindow || 0;
			document.getElementById('context-window').textContent = contextWindow;

			// Update total cache information
			if (tokenUsage.total && tokenUsage.total.cache) {
				const totalCacheRead = tokenUsage.total.cache.read || 0;
				const totalCacheWrite = tokenUsage.total.cache.write || 0;
				document.getElementById('total-cache-read').textContent = totalCacheRead;
				document.getElementById('total-cache-write').textContent = totalCacheWrite;
			} else if (tokenUsage.total) {
				// Fallback to direct properties if cache object is not available
				const totalCacheRead = tokenUsage.total.cacheRead || 0;
				const totalCacheWrite = tokenUsage.total.cacheWrite || 0;
				document.getElementById('total-cache-read').textContent = totalCacheRead;
				document.getElementById('total-cache-write').textContent = totalCacheWrite;
			}

			// Update total token usage
			if (tokenUsage.total) {
				document.getElementById('total-request').textContent = tokenUsage.total.request || 0;
				document.getElementById('total-response').textContent = tokenUsage.total.response || 0;
			}

			// Show token usage display
			const tokenUsageElement = document.getElementById('token-usage');
			if (tokenUsageElement) {
				tokenUsageElement.style.display = 'block';
			}
		}

		// Make token usage functions available globally
		window.tokenUsageDisplay = {
			update: updateTokenUsageDisplay,
			fetch: function (sessionId) {
				if (!sessionId) {
					console.log('[TokenUsage] No session ID provided for fetchTokenUsage');
					// Try to get session ID from window object
					if (window.sessionId) {
						console.log(`[TokenUsage] Using session ID from window object: ${window.sessionId}`);
						sessionId = window.sessionId;
					} else {
						console.log('[TokenUsage] No session ID available, cannot fetch token usage');
						return;
					}
				}

				// Check if this session is still the current one
				if (sessionId !== window.sessionId) {
					console.log(`[TokenUsage] Session ID mismatch: ${sessionId} vs current ${window.sessionId}, skipping fetch`);
					return;
				}

				console.log(`[TokenUsage] Fetching token usage for session: ${sessionId}`);
				// Use a more reliable fetch with keepalive for Firefox
				fetch(`/api/token-usage?sessionId=${sessionId}`, {
					method: 'GET',
					cache: 'no-store',
					keepalive: true,
					headers: {
						'Cache-Control': 'no-cache',
						'Pragma': 'no-cache'
					}
				})
					.then(response => {
						console.log(`[TokenUsage] Response status: ${response.status}`);

						if (response.ok) {
							return response.json();
						}
						throw new Error('Failed to fetch token usage');
					})
					.then(data => {
						console.log('[TokenUsage] Received token usage data:', data);
						updateTokenUsageDisplay(data);
					})
					.catch(error => {
						console.error('[TokenUsage] Error fetching token usage:', error);
						// Display a small error indicator in the token usage display
						const tokenUsageElement = document.getElementById('token-usage');
						if (tokenUsageElement && tokenUsageElement.style.display !== 'none') {
							const errorIndicator = document.createElement('div');
							errorIndicator.style.color = '#f44336';
							errorIndicator.style.fontSize = '10px';
							errorIndicator.style.marginTop = '5px';
							errorIndicator.textContent = 'Error updating token usage';

							// Remove any existing error indicators
							const existingIndicators = tokenUsageElement.querySelectorAll('[data-error-indicator]');
							existingIndicators.forEach(el => el.remove());

							// Add the data attribute for future reference
							errorIndicator.setAttribute('data-error-indicator', 'true');

							// Add to the token usage display
							tokenUsageElement.querySelector('.token-usage-content').appendChild(errorIndicator);

							// Remove after 5 seconds
							setTimeout(() => {
								if (errorIndicator.parentNode) {
									errorIndicator.parentNode.removeChild(errorIndicator);
								}
							}, 5000);
						}
					});
			}
		};

		function convertSvgToPng(svgElement, containerDiv, index) {
			if (!svgElement) {
				console.error('No SVG found!');
				return;
			}

			try {
				// Get the actual rendered size of the SVG
				const rect = svgElement.getBoundingClientRect();
				const svgWidth = rect.width;
				const svgHeight = rect.height;
				console.log(`SVG rendered size: ${svgWidth}x${svgHeight}`);

				// Define scale factor for higher resolution (increase for more clarity)
				const scale = 6; // Try 3 or 4 if still blurry

				// Create canvas with scaled dimensions
				const canvasWidth = svgWidth * scale;
				const canvasHeight = svgHeight * scale;
				const canvas = document.createElement('canvas');
				canvas.width = canvasWidth;
				canvas.height = canvasHeight;
				const ctx = canvas.getContext('2d');

				// Enable image smoothing for better quality
				ctx.imageSmoothingEnabled = true;
				ctx.imageSmoothingQuality = 'high';

				// Serialize SVG to string
				const svgString = new XMLSerializer().serializeToString(svgElement);
				const svgDataUrl = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svgString);

				const img = new Image();
				img.onload = function () {
					// Draw the image onto the canvas at scaled size
					ctx.drawImage(img, 0, 0, canvasWidth, canvasHeight);

					// Convert canvas to PNG data URL
					const pngDataUrl = canvas.toDataURL('image/png');

					// Create the PNG image element
					const pngImage = document.createElement('img');
					pngImage.src = pngDataUrl;
					pngImage.width = svgWidth; // Display at original size
					pngImage.height = svgHeight;
					pngImage.alt = 'Diagram as PNG';
					pngImage.className = 'mermaid-png';
					pngImage.setAttribute('data-full-size', pngDataUrl); // Store full-size image URL for zoom

					// Log PNG natural size to verify resolution
					pngImage.onload = function () {
						console.log(`PNG natural size: ${this.naturalWidth}x${this.naturalHeight}`);
					};

					// Create a container for the image with zoom functionality
					const container = document.createElement('div');
					container.className = 'mermaid-container';

					// Create zoom icon
					const zoomIcon = document.createElement('div');
					zoomIcon.className = 'zoom-icon';
					zoomIcon.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line><line x1="11" y1="8" x2="11" y2="14"></line><line x1="8" y1="11" x2="14" y2="11"></line></svg>';

					// Add click event to zoom icon
					zoomIcon.addEventListener('click', function (e) {
						e.stopPropagation();
						showDiagramDialog(pngDataUrl);
					});

					// Replace the SVG with the PNG image in the container
					svgElement.style.display = 'none';
					container.appendChild(pngImage);
					container.appendChild(zoomIcon);
					svgElement.insertAdjacentElement('afterend', container);

					console.log(`Replaced SVG with PNG image (index: ${index || 0})`);
				};
				img.onerror = function () {
					console.error('Error loading SVG image for conversion');
				};
				img.src = svgDataUrl;
			} catch (error) {
				console.error('Error in SVG to PNG conversion process:', error);
			}
		}

		// Function to show diagram in fullscreen dialog
		function showDiagramDialog(imageUrl) {
			// Create dialog if it doesn't exist
			let dialog = document.getElementById('diagram-dialog');
			if (!dialog) {
				dialog = document.createElement('div');
				dialog.id = 'diagram-dialog';
				dialog.className = 'diagram-dialog';

				const dialogContent = document.createElement('div');
				dialogContent.className = 'diagram-dialog-content';

				const closeButton = document.createElement('div');
				closeButton.className = 'close-dialog';
				closeButton.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>';
				closeButton.addEventListener('click', function () {
					dialog.classList.remove('active');
				});

				dialog.appendChild(dialogContent);
				dialog.appendChild(closeButton);
				document.body.appendChild(dialog);

				// Close dialog when clicking outside content
				dialog.addEventListener('click', function (e) {
					if (e.target === dialog) {
						dialog.classList.remove('active');
					}
				});

				// Close dialog with Escape key
				document.addEventListener('keydown', function (e) {
					if (e.key === 'Escape' && dialog.classList.contains('active')) {
						dialog.classList.remove('active');
					}
				});
			}

			// Update dialog content with the image
			const dialogContent = dialog.querySelector('.diagram-dialog-content');
			dialogContent.innerHTML = '';

			const img = document.createElement('img');
			img.src = imageUrl;
			img.alt = 'Diagram (Full Size)';

			// Ensure image fits screen by checking dimensions after loading
			img.onload = function () {
				// Image is now loaded, ensure it fits within the dialog content
				const viewportWidth = window.innerWidth * 0.9 - 40; // 90% of viewport minus padding
				const viewportHeight = window.innerHeight * 0.9 - 40; // 90% of viewport minus padding

				console.log(`Image natural size: ${img.naturalWidth}x${img.naturalHeight}`);
				console.log(`Available viewport space: ${viewportWidth}x${viewportHeight}`);

				// Image will be constrained by CSS max-width/max-height and object-fit
			};

			dialogContent.appendChild(img);

			// Show dialog
			dialog.classList.add('active');
		}
		// Generate a new session ID on every page load, store only in memory
		let sessionId = crypto.randomUUID();
		console.log(`Initialized new session with ID: ${sessionId}`);

		// Make session ID available to other scripts
		// We use both direct property assignment and event dispatch for compatibility
		// Direct property is used by internal functions like tokenUsageDisplay.fetch
		window.sessionId = sessionId;

		// Dispatch an event with the session ID for any external scripts that may be listening
		window.dispatchEvent(new MessageEvent('message', {
			data: { sessionId: sessionId }
		}));
		const messagesDiv = document.getElementById('messages');
		const form = document.getElementById('input-form');
		const searchSuggestionsDiv = document.querySelector('.search-suggestions');
		const input = document.getElementById('message-input');
		const folderListDiv = document.getElementById('folder-list');

		// Position the input form in the center initially and handle UI elements visibility
		function positionInputForm() {
			const footer = document.querySelector('.footer');
			const header = document.querySelector('.header');
			const emptyStateLogo = document.getElementById('empty-state-logo');

			if (messagesDiv.children.length === 0) {
				form.classList.add('centered');
				form.classList.remove('bottom');
				// Show footer when no messages
				if (footer) {
					footer.style.display = 'block';
				}
				// Hide the top header and show the centered logo
				if (header) {
					header.style.display = 'none';
				}
				if (emptyStateLogo) {
					emptyStateLogo.style.display = 'block';
				}
			} else {
				form.classList.remove('centered');
				form.classList.add('bottom');
				// Hide footer when chat is started
				if (footer) {
					footer.style.display = 'none';
				}
				// Show the top header and hide the centered logo
				if (header) {
					header.style.display = 'block';
				}
				if (emptyStateLogo) {
					emptyStateLogo.style.display = 'none';
				}
			}
		}

		// Make search suggestions clickable
		function setupSearchSuggestions() {
			document.querySelectorAll('.search-suggestions li').forEach(item => {
				item.addEventListener('click', () => {
					input.value = item.textContent;
					input.focus();
				});
			});
		}

		// Initialize on page load
		window.addEventListener('load', () => {
			setupSearchSuggestions();
			positionInputForm();
			positionSearchSuggestions();

			// Focus the input field on page load
			setTimeout(() => {
				const inputField = document.getElementById('message-input');
				if (inputField) {
					inputField.focus();
				}
			}, 100);
		});


		// Position search suggestions relative to input form
		function positionSearchSuggestions() {
			const formRect = form.getBoundingClientRect();

			if (form.classList.contains('centered')) {
				// Position directly below the form
				searchSuggestionsDiv.style.top = formRect.bottom + 'px';
				searchSuggestionsDiv.style.display = 'block';
			} else {
				searchSuggestionsDiv.style.display = 'none';
			}
		}

		// Update search suggestions position when window is resized
		window.addEventListener('resize', positionSearchSuggestions);

		// Check if Mermaid is properly loaded
		function checkMermaidLoaded() {
			if (typeof mermaid === 'undefined') {
				console.error('Mermaid is not loaded properly');
				return false;
			}
			console.log('Mermaid version:', mermaid.version);
			return true;
		}

		// Initialize mermaid
		if (checkMermaidLoaded()) {
			mermaid.initialize({
				startOnLoad: false,
				theme: 'default',
				securityLevel: 'loose',
				flowchart: { htmlLabels: true },
				logLevel: 3, // Add logging for debugging (1: error, 2: warn, 3: info, 4: debug, 5: trace)
				fontFamily: 'monospace'
			});

			// Run mermaid on page load to render the test diagram
			window.addEventListener('DOMContentLoaded', () => {
				setTimeout(() => {
					try {
						console.log('Running mermaid on page load');
						mermaid.run();
					} catch (error) {
						console.error('Error initializing mermaid:', error);
					}
				}, 500);
			});
		}

		// Configure marked.js
		// Configure Marked.js with logging
		marked.setOptions({
			highlight: function (code, lang) {
				console.log(`Highlighting code with language: ${lang}`);
				if (lang === 'mermaid') {
					console.log('Returning mermaid div');
					return `<div class="mermaid">${code}</div>`;
				}
				const language = hljs.getLanguage(lang) ? lang : 'plaintext';
				return hljs.highlight(code, { language }).value;
			},
			langPrefix: 'hljs language-',
			gfm: true,
			breaks: true
		});
		// Fetch API key status and check for no API keys mode on page load
		window.addEventListener('DOMContentLoaded', async () => {
			// First check if we have an API key in local storage
			const storedApiKey = localStorage.getItem('probeApiKey');
			if (storedApiKey) {
				// Show the reset button in the header
				const headerResetButton = document.getElementById('header-reset-api-key');
				if (headerResetButton) {
					headerResetButton.style.display = 'inline-block';
				}
			}
			// Check if we're in API key setup mode
			const apiKeySetupDiv = document.getElementById('api-key-setup');
			const inputForm = document.getElementById('input-form');
			const searchSuggestions = document.querySelector('.search-suggestions');

			// If API key setup is visible, we're in API setup mode
			if (apiKeySetupDiv && window.getComputedStyle(apiKeySetupDiv).display !== 'none') {
				// Add class to body for API setup mode styling
				document.body.classList.add('api-setup-mode');

				// Hide search suggestions and input form
				if (inputForm) inputForm.style.display = 'none';
				if (searchSuggestions) searchSuggestions.style.display = 'none';
			} else {
				// Remove API setup mode class if not in setup mode
				document.body.classList.remove('api-setup-mode');
			}

			try {
				const response = await fetch('/folders');
				const data = await response.json();

				// Check if we're in no API keys mode
				if (data.noApiKeysMode) {
					handleNoApiKeysMode();
				}

				// Display folder information
				displayFolderInfo(data.folders);
			} catch (error) {
				console.error('Error fetching API status:', error);
			}
		});

		// Function to display folder information
		function displayFolderInfo(folders) {
			const folderInfoDiv = document.getElementById('folder-info');

			if (!folderInfoDiv) return;

			// Clear any existing content
			folderInfoDiv.innerHTML = '';

			// Set a loading message
			folderInfoDiv.textContent = 'Determining search location...';

			// Fetch the current directory from the server's /folders endpoint
			fetch('/folders')
				.then(response => response.json())
				.then(data => {
					// Use the currentDir property which contains the absolute path
					if (data.currentDir) {
						// Display the absolute path from the server
						folderInfoDiv.textContent = `Searching in: ${data.currentDir}`;

						// If there are multiple folders, show that info
						if (data.folders && data.folders.length > 1) {
							folderInfoDiv.textContent += ` (and ${data.folders.length - 1} other folder${data.folders.length > 2 ? 's' : ''})`;
						}
					}
					// Fallback to folders if currentDir is not available
					else if (data.folders && data.folders.length > 0) {
						folderInfoDiv.textContent = `Searching in: ${data.folders[0]}`;

						if (data.folders.length > 1) {
							folderInfoDiv.textContent += ` (and ${data.folders.length - 1} other folder${data.folders.length > 2 ? 's' : ''})`;
						}
					}
					// Last resort fallback
					else {
						folderInfoDiv.textContent = `Searching in: . (current directory)`;
					}
				})
				.catch(error => {
					console.error('Error fetching folder info:', error);
					folderInfoDiv.textContent = `Searching in: . (current directory)`;
				});
		}

		// Handle no API keys mode
		function handleNoApiKeysMode() {
			// Check if body has the data-no-api-keys attribute
			const noApiKeys = document.body.getAttribute('data-no-api-keys') === 'true';

			// Check if API key is already stored in local storage
			const storedApiKey = localStorage.getItem('probeApiKey');

			// Add or remove api-setup-mode class based on whether we need to show the API key setup
			if (noApiKeys && !storedApiKey) {
				document.body.classList.add('api-setup-mode');
			} else {
				document.body.classList.remove('api-setup-mode');
			}

			// Get UI elements
			const apiKeySetupDiv = document.getElementById('api-key-setup');
			const inputForm = document.getElementById('input-form');
			const searchSuggestions = document.querySelector('.search-suggestions');

			if (noApiKeys && !storedApiKey) {
				console.log('No API keys detected and no local storage key - showing setup instructions');

				// Show the API key setup div
				if (apiKeySetupDiv) {
					apiKeySetupDiv.style.display = 'block';
				}

				// Hide the chat interface elements
				if (inputForm) {
					inputForm.style.display = 'none';
				}

				if (searchSuggestions) {
					searchSuggestions.style.display = 'none';
				}
			} else if (noApiKeys && storedApiKey) {
				console.log('No server API keys but local storage key found - enabling chat interface');

				// Hide the API key setup div
				if (apiKeySetupDiv) {
					apiKeySetupDiv.style.display = 'none';
				}

				// Show the chat interface elements
				if (inputForm) {
					inputForm.style.display = 'flex';
				}

				// Remove API setup mode class
				document.body.classList.remove('api-setup-mode');
			}
		}


		// Render markdown content
		function renderMarkdown(text) {
			// Just parse the markdown and return the HTML
			return marked.parse(text);
		}

		// Test function to manually render a Mermaid diagram
		function testMermaidRendering() {
			console.log('Testing Mermaid rendering...');
			try {
				// Create a simple test diagram directly
				const testDiv = document.createElement('div');
				testDiv.className = 'mermaid';
				testDiv.textContent = 'graph TD;\nA-->B;';
				document.body.appendChild(testDiv);

				console.log('Created test diagram with content:', testDiv.textContent);

				// Render the direct mermaid div
				setTimeout(() => {
					try {
						console.log('Running mermaid on test div');
						if (typeof mermaid.run === 'function') {
							console.log('Using mermaid.run() for test');
							mermaid.run({
								nodes: [testDiv]
							});
						} else if (typeof mermaid.init === 'function') {
							console.log('Using mermaid.init() for test');
							mermaid.init(undefined, [testDiv]);
						}

						// Verify if rendering worked
						setTimeout(() => {
							const svg = testDiv.querySelector('svg');
							if (svg) {
								console.log('Test diagram rendered successfully!');
							} else {
								console.error('Test diagram did not render to SVG');
							}

							// Remove test div after verification
							document.body.removeChild(testDiv);
						}, 100);
					} catch (error) {
						console.error('Error rendering test mermaid diagram:', error);
						console.error('Error details:', error.message);

						// Remove test div on error
						document.body.removeChild(testDiv);
					}
				}, 200);
			} catch (error) {
				console.error('Unexpected error in test function:', error);
			}
		}

		// Run test on page load
		window.addEventListener('DOMContentLoaded', () => {
			setTimeout(testMermaidRendering, 1000);
		});

		// Connect to SSE endpoint for tool calls
		let eventSource;
		let currentAiMessageDiv = null;

		function connectToToolEvents() {
			// Close existing connection if any
			if (eventSource) {
				console.log('Closing existing SSE connection');
				eventSource.close();
			}

			// Clear any existing displayed tool calls when connecting with a new session ID
			if (window.displayedToolCalls) {
				window.displayedToolCalls.clear();
				console.log('Cleared displayed tool calls for new session');
			}

			console.log(`%c Connecting to SSE endpoint with session ID: ${sessionId}`, 'background: #FF9800; color: white; padding: 2px 5px; border-radius: 2px;');
			// Connect to SSE endpoint with session ID
			const sseUrl = `/api/tool-events?sessionId=${sessionId}`;
			console.log('SSE URL:', sseUrl);

			// Add a timestamp to prevent caching in Firefox
			const nocacheUrl = `${sseUrl}&_nocache=${Date.now()}`;
			eventSource = new EventSource(nocacheUrl);

			// Handle connection event
			eventSource.addEventListener('connection', (event) => {
				console.log('%c Connected to tool events stream', 'background: #4CAF50; color: white; padding: 2px 5px; border-radius: 2px;', event.data);
				try {
					const connectionData = JSON.parse(event.data);
					console.log('Connection data:', connectionData);
				} catch (error) {
					console.error('Error parsing connection data:', error, event.data);
				}
			});

			// Handle test events
			eventSource.addEventListener('test', (event) => {
				console.log('%c Received test event:', 'background: #9C27B0; color: white; padding: 2px 5px; border-radius: 2px;', event.data);
				try {
					const testData = JSON.parse(event.data);
					console.log('%c Test data:', 'background: #673AB7; color: white; padding: 2px 5px; border-radius: 2px;', testData);

					// Log specific test data properties
					console.log('Test message:', testData.message);
					console.log('Test timestamp:', testData.timestamp);
					console.log('Test session ID:', testData.sessionId);

					if (testData.status) {
						console.log('Test status:', testData.status);
					}

					if (testData.connectionInfo) {
						console.log('Connection info:', testData.connectionInfo);
					}

					if (testData.sequence === 2) {
						console.log('%c SSE connection fully verified with follow-up test', 'background: #4CAF50; color: white; padding: 2px 5px; border-radius: 2px;');
					}

					// Add a visual indicator that the SSE connection is working
					const connectionIndicator = document.createElement('div');
					connectionIndicator.style.position = 'fixed';
					connectionIndicator.style.bottom = '10px';
					connectionIndicator.style.right = '10px';
					connectionIndicator.style.backgroundColor = '#4CAF50';
					connectionIndicator.style.color = 'white';
					connectionIndicator.style.padding = '5px 10px';
					connectionIndicator.style.borderRadius = '4px';
					connectionIndicator.style.fontSize = '12px';
					connectionIndicator.style.zIndex = '1000';
					connectionIndicator.style.opacity = '0.8';
					connectionIndicator.textContent = 'SSE Connected';

					// Remove after 3 seconds
					setTimeout(() => {
						if (document.body.contains(connectionIndicator)) {
							document.body.removeChild(connectionIndicator);
						}
					}, 3000);

					document.body.appendChild(connectionIndicator);

				} catch (error) {
					console.error('Error parsing test event data:', error, event.data);
				}
			});

			// Initialize a Set to track displayed tool calls
			if (!window.displayedToolCalls) {
				window.displayedToolCalls = new Set();
			}

			// Handle tool call events
			eventSource.addEventListener('toolCall', (event) => {
				// If no request is in progress, ignore the tool call
				if (!isRequestInProgress) {
					console.log('Tool call received but no request in progress, ignoring');
					return;
				}
				console.log('%c Received tool call event:', 'background: #4CAF50; color: white; padding: 2px 5px; border-radius: 2px;', event);
				try {
					const toolCall = JSON.parse(event.data);
					console.log('%c Tool call data:', 'background: #2196F3; color: white; padding: 2px 5px; border-radius: 2px;', toolCall);

					// Skip events with status "started" - only process "completed" events
					if (toolCall.status === "started") {
						console.log('%c Skipping "started" event, waiting for "completed"', 'background: #FF9800; color: white; padding: 2px 5px; border-radius: 2px;');
						return;
					}

					// Create a unique identifier for this tool call
					const query = toolCall.args.query || toolCall.args.keywords || toolCall.args.pattern || '';
					const path = toolCall.args.path || toolCall.args.folder || '.';

					// Create a simpler fingerprint that doesn't include timestamp
					// This helps catch duplicate events with different timestamps
					const toolCallFingerprint = `${toolCall.name}-${query}-${path}`;

					// Check if we've already displayed this exact tool call
					if (window.displayedToolCalls.has(toolCallFingerprint)) {
						console.log(`%c Skipping duplicate tool call: ${toolCallFingerprint}`, 'background: #FF9800; color: white; padding: 2px 5px; border-radius: 2px;');
						return;
					}

					// Add this tool call to our set of displayed tool calls
					window.displayedToolCalls.add(toolCallFingerprint);
					console.log(`%c Added tool call to displayed set: ${toolCallFingerprint}`, 'background: #9C27B0; color: white; padding: 2px 5px; border-radius: 2px;');

					// Format the tool call description for display
					let toolDescription = '';
					if (toolCall.name === 'searchCode' || toolCall.name === 'search') {
						const language = toolCall.args.language;
						const exact = toolCall.args.exact;

						let locationInfo = path !== '.' ? ` in ${path}` : '';
						let languageInfo = language ? ` (language: ${language})` : '';
						let exactInfo = exact === true ? ` (exact match)` : '';

						toolDescription = `Searching code with "${query}"${locationInfo}${languageInfo}${exactInfo}`;
					} else if (toolCall.name === 'queryCode' || toolCall.name === 'query') {
						toolDescription = `Querying code with pattern "${query}"${path === '.' ? '' : ` in ${path}`}`;
					} else if (toolCall.name === 'extractCode' || toolCall.name === 'extract') {
						const filePath = toolCall.args.file_path || '';
						const line = toolCall.args.line;
						const endLine = toolCall.args.end_line;

						let lineInfo = '';
						if (line && endLine) {
							lineInfo = ` (lines ${line}-${endLine})`;
						} else if (line) {
							lineInfo = ` (from line ${line})`;
						}

						toolDescription = `Extracting code from ${filePath}${lineInfo}`;
					} else {
						toolDescription = `Using ${toolCall.name} tool`;
					}

					// Log the tool call being processed
					console.log(`%c Processing tool call: "${toolDescription}"`, 'background: #9C27B0; color: white; padding: 2px 5px; border-radius: 2px;');

					// Add tool call to the current AI message if it exists
					if (currentAiMessageDiv) {
						addToolCallToMessage(currentAiMessageDiv, toolCall);
					} else {
						console.warn('No current AI message div to add tool call to');
						// Create a temporary div to display the tool call
						const tempDiv = document.createElement('div');
						tempDiv.className = 'ai-message';
						tempDiv.innerHTML = '<div class="tool-call-header">Tool call received but no message context</div>';
						messagesDiv.appendChild(tempDiv);
						addToolCallToMessage(tempDiv, toolCall);
					}
				} catch (error) {
					console.error('Error parsing tool call data:', error, event.data);
				}
			});

			// Handle errors
			eventSource.onerror = (error) => {
				console.error('%c SSE Error:', 'background: #F44336; color: white; padding: 2px 5px; border-radius: 2px;', error);

				// Log detailed readyState information
				const readyStateMap = {
					0: 'CONNECTING',
					1: 'OPEN',
					2: 'CLOSED'
				};
				const readyState = eventSource.readyState;
				console.log(`EventSource readyState: ${readyState} (${readyStateMap[readyState] || 'UNKNOWN'})`);

				// Check if the connection was established before the error
				if (readyState === 2) {
					console.log('Connection was closed. Attempting to reconnect...');
				} else if (readyState === 0) {
					console.log('Connection is still trying to connect. Will retry if it fails.');
				}

				// Try to reconnect after a delay
				console.log('Will attempt to reconnect in 5 seconds...');
				setTimeout(connectToToolEvents, 5000);
			};

			// Add open event handler
			eventSource.onopen = () => {
				console.log('%c SSE connection opened successfully', 'background: #4CAF50; color: white; padding: 2px 5px; border-radius: 2px;');
				console.log('Ready to receive tool call events for session:', sessionId);
			};
		}

		// Add tool call to the AI message
		function addToolCallToMessage(messageDiv, toolCall) {
			console.log('%c Adding tool call to message:', 'background: #4CAF50; color: white; padding: 2px 5px; border-radius: 2px;', toolCall);

			try {
				// Format the tool call description for display
				let toolDescription = '';
				if (toolCall.name === 'searchCode' || toolCall.name === 'search') {
					const query = toolCall.args.query || toolCall.args.keywords || '';
					const path = toolCall.args.path || toolCall.args.folder || '.';
					const language = toolCall.args.language;
					const exact = toolCall.args.exact;

					let locationInfo = path !== '.' ? ` in ${path}` : '';
					let languageInfo = language ? ` (language: ${language})` : '';
					let exactInfo = exact === true ? ` (exact match)` : '';

					toolDescription = `Searching code with "${query}"${locationInfo}${languageInfo}${exactInfo}`;
				} else if (toolCall.name === 'queryCode' || toolCall.name === 'query') {
					const query = toolCall.args.query || toolCall.args.pattern || '';
					const path = toolCall.args.path || toolCall.args.folder || '.';
					toolDescription = `Querying code with pattern "${query}"${path === '.' ? '' : ` in ${path}`}`;
				} else if (toolCall.name === 'extractCode' || toolCall.name === 'extract') {
					const filePath = toolCall.args.file_path || '';
					const line = toolCall.args.line;
					const endLine = toolCall.args.end_line;

					let lineInfo = '';
					if (line && endLine) {
						lineInfo = ` (lines ${line}-${endLine})`;
					} else if (line) {
						lineInfo = ` (from line ${line})`;
					}

					toolDescription = `Extracting code from ${filePath}${lineInfo}`;
				} else {
					toolDescription = `Using ${toolCall.name} tool`;
				}

				// Create a simple paragraph element with the formatted description
				const paragraph = document.createElement('p');
				paragraph.textContent = toolDescription;
				paragraph.style.fontStyle = 'italic';
				paragraph.style.color = '#555';
				paragraph.style.margin = '8px 0';

				// Add the paragraph to the message div
				messageDiv.appendChild(paragraph);

				// Scroll to the bottom
				messagesDiv.scrollTop = messagesDiv.scrollHeight;

				console.log('%c Tool call added successfully', 'background: #4CAF50; color: white; padding: 2px 5px; border-radius: 2px;');
			} catch (error) {
				console.error('Error adding tool call to message:', error);
			}
		}
		// Connect to tool events on page load
		window.addEventListener('DOMContentLoaded', () => {
			// Check if we're in no API keys mode
			const noApiKeys = document.body.getAttribute('data-no-api-keys') === 'true';

			if (!noApiKeys) {
				connectToToolEvents();
			}
		});

		// Handle "New chat" button click
		document.addEventListener('DOMContentLoaded', () => {
			const newChatLink = document.querySelector('.new-chat-link');
			if (newChatLink) {
				newChatLink.addEventListener('click', (e) => {
					e.preventDefault();

					// Cancel any ongoing requests for the current session
					cancelRequest(sessionId).catch(err => console.error('Error cancelling session on new chat:', err));

					// Generate a new session ID
					sessionId = crypto.randomUUID();
					console.log(`New chat started in current window. New session ID: ${sessionId}`);

					// Make session ID available to other scripts
					// We use both direct property assignment and event dispatch for compatibility
					window.sessionId = sessionId;

					// Dispatch an event with the session ID for any external scripts that may be listening
					window.dispatchEvent(new MessageEvent('message', {
						data: { sessionId: sessionId }
					}));

					// Clear the messages
					messagesDiv.innerHTML = '';

					// Reset the UI
					positionInputForm();
					searchSuggestionsDiv.style.display = 'block';

					// Hide and reset token usage display
					const tokenUsageElement = document.getElementById('token-usage');
					if (tokenUsageElement) {
						tokenUsageElement.style.display = 'none';

						// Reset token usage counters
						document.getElementById('current-request').textContent = '0';
						document.getElementById('current-response').textContent = '0';
						document.getElementById('total-request').textContent = '0';
						document.getElementById('total-response').textContent = '0';
					}

					// Close existing SSE connection and reconnect with new session ID
					if (eventSource) {
						eventSource.close();
					}
					connectToToolEvents();

					// Send a request to the server to clear the chat history for this session
					fetch('/chat', {
						method: 'POST',
						headers: { 'Content-Type': 'application/json' },
						body: JSON.stringify({
							message: '__clear_history__',
							sessionId,
							clearHistory: true
						})
					}).catch(err => console.error('Error clearing chat history:', err));
				});
			}
		});

		// Add event listener for page unload to cancel the current session
		window.addEventListener('beforeunload', () => {
			// If we have a sessionId that's about to become invalid, cancel it
			if (sessionId) {
				// Use navigator.sendBeacon for more reliable delivery during page unload
				const data = JSON.stringify({ sessionId });
				if (navigator.sendBeacon) {
					navigator.sendBeacon('/cancel-request', data);
				} else {
					// Fallback to fetch for older browsers
					fetch('/cancel-request', {
						method: 'POST',
						headers: { 'Content-Type': 'application/json' },
						body: data,
						// Use keepalive to ensure the request completes even if the page is unloading
						keepalive: true
					}).catch((err) => console.error('Error cancelling session on unload:', err));
				}
			}
		});

		// Controller for aborting fetch requests
		let currentController = null;
		// Flag to track if a request is in progress
		let isRequestInProgress = false;

		// Function to cancel the current request on the server
		async function cancelRequest(sessionId) {
			try {
				const response = await fetch('/cancel-request', {
					method: 'POST',
					headers: { 'Content-Type': 'application/json' },
					body: JSON.stringify({ sessionId })
				});

				if (response.ok) {
					console.log('Request cancelled successfully on server');
				} else {
					console.error('Failed to cancel request on server');
				}
			} catch (error) {
				console.error('Error cancelling request:', error);
			}
		}

		// Handle form submission
		// Use the button click event instead of form submit to avoid potential form submission issues
		const searchButton = document.getElementById('search-button');
		searchButton.addEventListener('click', async (e) => {
			e.preventDefault();

			// If this is a stop action
			if (searchButton.textContent === 'Stop') {
				// Abort the current fetch request
				if (currentController) {
					currentController.abort();
					currentController = null;
				}

				// Send cancellation request to the server
				if (isRequestInProgress) {
					await cancelRequest(sessionId);
					isRequestInProgress = false;

					// Stop token usage polling when request is cancelled
					stopTokenUsagePolling();
				}

				// Reset the button to "Search" and enable input
				searchButton.textContent = 'Search';
				searchButton.style.backgroundColor = '#44CDF3';
				input.disabled = false;
				return;
			}

			const message = input.value.trim();
			if (!message) return;

			// Check if this is the first message
			const isFirstMessage = messagesDiv.children.length === 0;

			// Display user message
			const userMsgDiv = document.createElement('div');
			userMsgDiv.className = 'user-message markdown-content'; // Add markdown-content class
			userMsgDiv.innerHTML = renderMarkdown(message); // Render as markdown
			messagesDiv.appendChild(userMsgDiv);

			// Apply syntax highlighting to code blocks in user message
			userMsgDiv.querySelectorAll('pre code').forEach((block) => {
				hljs.highlightElement(block);
			});

			// Render Mermaid diagrams in user message
			const userMermaidDivs = userMsgDiv.querySelectorAll('.mermaid');
			if (userMermaidDivs.length > 0) {
				console.log(`Found ${userMermaidDivs.length} mermaid diagrams in user message`);
				try {
					if (typeof mermaid.run === 'function') {
						mermaid.run({ nodes: userMermaidDivs });
					} else if (typeof mermaid.init === 'function') {
						mermaid.init(undefined, userMermaidDivs);
					}
					// Convert rendered SVGs to PNGs
					setTimeout(() => {
						const renderedSvgs = userMsgDiv.querySelectorAll('.mermaid svg');
						if (renderedSvgs.length > 0) {
							renderedSvgs.forEach((svg, index) => {
								convertSvgToPng(svg, userMsgDiv, index);
							});
						}
					}, 100);
				} catch (error) {
					console.error('Error rendering mermaid in user message:', error);
				}
			}
			input.value = '';
			autoResizeTextarea(); // Reset textarea height after clearing content

			// If this is the first message, move the input form to the bottom and hide UI elements
			if (isFirstMessage) {
				positionInputForm();
				searchSuggestionsDiv.style.display = 'none';

				// Ensure footer is hidden when chat starts
				const footer = document.querySelector('.footer');
				if (footer) {
					footer.style.display = 'none';
				}

				// Show token usage display
				document.getElementById('token-usage').style.display = 'block';

				// Show token usage display
				const tokenUsageElement = document.getElementById('token-usage');
				if (tokenUsageElement) {
					tokenUsageElement.style.display = 'block';
				}

				// Keep the allowed folders section visible during chat
				// This is the key change - we don't hide the folder information anymore
			}

			// Create AI message container
			const aiMsgDiv = document.createElement('div');
			aiMsgDiv.className = 'ai-message markdown-content';

			// Store the original message for copying
			aiMsgDiv.setAttribute('data-original-markdown', '');

			// Add the AI message to the DOM
			messagesDiv.appendChild(aiMsgDiv);

			// Set as current AI message for tool calls
			currentAiMessageDiv = aiMsgDiv;

			// Disable input and change button to "Stop"
			input.disabled = true;
			searchButton.textContent = 'Stop';
			searchButton.style.backgroundColor = '#f44336';

			// Set request in progress flag
			isRequestInProgress = true;

			// Start token usage polling for long-running requests
			startTokenUsagePolling();

			// Send message to server
			try {
				// Log the session ID being used
				console.log(`%c Using session ID for chat request: ${sessionId}`, 'background: #FF9800; color: white; padding: 2px 5px; border-radius: 2px;');

				// Get API key from local storage if available
				const storedApiProvider = localStorage.getItem('probeApiProvider');
				const storedApiKey = localStorage.getItem('probeApiKey');
				const storedApiUrl = localStorage.getItem('probeApiUrl');

				const requestData = {
					message,
					sessionId, // Include session ID with the request
					apiProvider: storedApiProvider,
					apiKey: storedApiKey,
					apiUrl: storedApiUrl
				};
				console.log('Sending chat request with data:', requestData);

				// Add a visual indicator that we're using this session ID
				const sessionIndicator = document.createElement('div');
				sessionIndicator.style.position = 'fixed';
				sessionIndicator.style.top = '10px';
				sessionIndicator.style.right = '10px';
				sessionIndicator.style.backgroundColor = '#FF9800';
				sessionIndicator.style.color = 'white';
				sessionIndicator.style.padding = '5px 10px';
				sessionIndicator.style.borderRadius = '4px';
				sessionIndicator.style.fontSize = '12px';
				sessionIndicator.style.zIndex = '1000';
				sessionIndicator.style.opacity = '0.8';
				sessionIndicator.textContent = `Session ID: ${sessionId.substring(0, 8)}...`;

				// Remove after 3 seconds
				setTimeout(() => {
					if (document.body.contains(sessionIndicator)) {
						document.body.removeChild(sessionIndicator);
					}
				}, 3000);

				document.body.appendChild(sessionIndicator);

				// Create a new AbortController for this request
				currentController = new AbortController();
				const signal = currentController.signal;

				const response = await fetch('/chat', {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json',
						'Cache-Control': 'no-cache',
						'Pragma': 'no-cache'
					},
					cache: 'no-store',
					body: JSON.stringify(requestData),
					signal: signal
				}).catch(error => {
					if (error.name === 'AbortError') {
						console.log('Fetch aborted');
						aiMsgDiv.innerHTML += '<p><em>Search was stopped by user.</em></p>';
						return null;
					}
					throw error;
				});

				// If response is null (aborted), reset UI and return
				if (!response) {
					// Reset button to "Search" and enable input
					form.querySelector('button').textContent = 'Search';
					form.querySelector('button').style.backgroundColor = '#44CDF3';
					input.disabled = false;
					return;
				}

				// We'll rely on polling and final fetch for token usage updates
				// No need to extract from headers as it's redundant

				const reader = response.body.getReader();
				const decoder = new TextDecoder();
				let aiResponse = '';

				while (true) {
					const { done, value } = await reader.read();
					if (done) break;
					const chunk = decoder.decode(value, { stream: true });
					aiResponse += chunk;

					try {
						// Parse the JSON response to extract the "response" field
						const jsonResponse = JSON.parse(aiResponse);
						const markdownContent = jsonResponse.response;

						// Update the original markdown attribute with just the markdown content
						aiMsgDiv.setAttribute('data-original-markdown', markdownContent);

						// Render markdown content
						aiMsgDiv.innerHTML = renderMarkdown(markdownContent);

						// Apply syntax highlighting to code blocks
						aiMsgDiv.querySelectorAll('pre code').forEach((block) => {
							hljs.highlightElement(block);
						});

						// Don't render mermaid diagrams during streaming - will render once at the end
						// This prevents premature rendering attempts that might fail

						messagesDiv.scrollTop = messagesDiv.scrollHeight;
					} catch (error) {
						console.error('Error processing response chunk:', error);

						// Check if it's a JSON parsing error or a markdown rendering error
						if (error instanceof SyntaxError) {
							// If it's a JSON parsing error, show a message about incomplete response
							aiMsgDiv.innerHTML = '<p><em>Receiving response...</em></p>';
						} else {
							// If it's a markdown rendering error, try to parse JSON but show raw content
							try {
								const jsonResponse = JSON.parse(aiResponse);
								aiMsgDiv.textContent = jsonResponse.response || aiResponse;
							} catch (jsonError) {
								// If JSON parsing fails, show the raw text
								aiMsgDiv.textContent = aiResponse;
							}
						}
					}
				}

				// Final render after all content is received
				setTimeout(() => {
					try {
						// Parse the complete JSON response
						const jsonResponse = JSON.parse(aiResponse);
						const markdownContent = jsonResponse.response;

						// Update token usage if available
						if (jsonResponse.tokenUsage && window.tokenUsageDisplay) {
							window.tokenUsageDisplay.update(jsonResponse.tokenUsage);
						}

						// Make sure the final content is set correctly
						aiMsgDiv.setAttribute('data-original-markdown', markdownContent);
						aiMsgDiv.innerHTML = renderMarkdown(markdownContent);

						// Apply syntax highlighting to code blocks
						aiMsgDiv.querySelectorAll('pre code').forEach((block) => {
							hljs.highlightElement(block);
						});

						// Specifically target mermaid diagrams in the current message
						const finalMermaidDivs = aiMsgDiv.querySelectorAll('.language-mermaid');

						if (finalMermaidDivs.length > 0) {
							console.log(`Final render: Found ${finalMermaidDivs.length} mermaid diagrams in current message`);

							// Log the content of the first diagram for debugging
							if (finalMermaidDivs[0]) {
								console.log('First diagram content:', finalMermaidDivs[0].textContent.substring(0, 100) + '...');
							}

							// Try direct rendering with specific nodes from current message
							if (typeof mermaid.run === 'function') {
								console.log('Using mermaid.run() for rendering');
								mermaid.run({
									nodes: finalMermaidDivs
								});
							} else if (typeof mermaid.init === 'function') {
								// Fallback to older mermaid versions
								console.log('Using mermaid.init() for rendering');
								mermaid.init(undefined, finalMermaidDivs);
							} else {
								console.error('No suitable mermaid rendering method found');
							}

							// Verify rendering success
							setTimeout(() => {
								// Update selector to find SVGs inside code.language-mermaid elements
								const renderedSvgs = aiMsgDiv.querySelectorAll('.language-mermaid svg, .mermaid svg');
								console.log(`Rendering verification: Found ${renderedSvgs.length} rendered SVGs`);

								// Convert SVGs to PNGs if any were rendered
								if (renderedSvgs.length > 0) {
									console.log('Converting SVGs to PNGs...');
									renderedSvgs.forEach((svg, index) => {
										convertSvgToPng(svg, aiMsgDiv, index);
									});
								}

								// Also add zoom functionality to any existing PNG images
								setTimeout(() => {
									const existingPngs = aiMsgDiv.querySelectorAll('.mermaid-png:not(.zoom-enabled)');
									if (existingPngs.length > 0) {
										console.log(`Adding zoom functionality to ${existingPngs.length} existing PNG images`);
										existingPngs.forEach((png) => {
											if (!png.parentElement.classList.contains('mermaid-container')) {
												const container = document.createElement('div');
												container.className = 'mermaid-container';

												const zoomIcon = document.createElement('div');
												zoomIcon.className = 'zoom-icon';
												zoomIcon.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line><line x1="11" y1="8" x2="11" y2="14"></line><line x1="8" y1="11" x2="14" y2="11"></line></svg>';

												zoomIcon.addEventListener('click', function (e) {
													e.stopPropagation();
													showDiagramDialog(png.src);
												});

												png.parentNode.insertBefore(container, png);
												container.appendChild(png);
												container.appendChild(zoomIcon);
												png.classList.add('zoom-enabled');
											}
										});
									}
								}, 200);
							}, 100);
						} else {
							console.log('No mermaid diagrams found in current message');
						}
					} catch (error) {
						console.warn('Final mermaid rendering error:', error);
						console.error('Error details:', error.message);
					}

					// Add copy button below the message after rendering is complete
					if (!aiMsgDiv.nextElementSibling || !aiMsgDiv.nextElementSibling.classList.contains('copy-button-container')) {
						// Create copy button container
						const copyButtonContainer = document.createElement('div');
						copyButtonContainer.className = 'copy-button-container';

						// Create copy button
						const copyButton = document.createElement('button');
						copyButton.className = 'copy-button';
						copyButton.innerHTML = `<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M7 5C7 3.34315 8.34315 2 10 2H19C20.6569 2 22 3.34315 22 5V14C22 15.6569 20.6569 17 19 17H17V19C17 20.6569 15.6569 22 14 22H5C3.34315 22 2 20.6569 2 19V10C2 8.34315 3.34315 7 5 7H7V5ZM9 7H14C15.6569 7 17 8.34315 17 10V15H19C19.5523 15 20 14.5523 20 14V5C20 4.44772 19.5523 4 19 4H10C9.44772 4 9 4.44772 9 5V7ZM5 9C4.44772 9 4 9.44772 4 10V19C4 19.5523 4.44772 20 5 20H14C14.5523 20 15 19.5523 15 19V10C15 9.44772 14.5523 9 14 9H5Z" fill="#666"></path></svg>Copy`;

						// Add click event to copy button
						copyButton.addEventListener('click', function () {
							const markdown = aiMsgDiv.getAttribute('data-original-markdown');
							if (markdown) {
								// Copy just the markdown content, not the raw JSON
								navigator.clipboard.writeText(markdown).then(() => {
									// Visual feedback
									copyButton.textContent = 'Copied!';

									setTimeout(() => {
										copyButton.innerHTML = `<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M7 5C7 3.34315 8.34315 2 10 2H19C20.6569 2 22 3.34315 22 5V14C22 15.6569 20.6569 17 19 17H17V19C17 20.6569 15.6569 22 14 22H5C3.34315 22 2 20.6569 2 19V10C2 8.34315 3.34315 7 5 7H7V5ZM9 7H14C15.6569 7 17 8.34315 17 10V15H19C19.5523 15 20 14.5523 20 14V5C20 4.44772 19.5523 4 19 4H10C9.44772 4 9 4.44772 9 5V7ZM5 9C4.44772 9 4 9.44772 4 10V19C4 19.5523 4.44772 20 5 20H14C14.5523 20 15 19.5523 15 19V10C15 9.44772 14.5523 9 14 9H5Z" fill="#666"></path></svg>Copy`;
									}, 2000);
								}).catch(err => {
									console.error('Failed to copy text: ', err);
									copyButton.textContent = 'Failed to copy';

									setTimeout(() => {
										copyButton.innerHTML = `<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M7 5C7 3.34315 8.34315 2 10 2H19C20.6569 2 22 3.34315 22 5V14C22 15.6569 20.6569 17 19 17H17V19C17 20.6569 15.6569 22 14 22H5C3.34315 22 2 20.6569 2 19V10C2 8.34315 3.34315 7 5 7H7V5ZM9 7H14C15.6569 7 17 8.34315 17 10V15H19C19.5523 15 20 14.5523 20 14V5C20 4.44772 19.5523 4 19 4H10C9.44772 4 9 4.44772 9 5V7ZM5 9C4.44772 9 4 9.44772 4 10V19C4 19.5523 4.44772 20 5 20H14C14.5523 20 15 19.5523 15 19V10C15 9.44772 14.5523 9 14 9H5Z" fill="#666"></path></svg>Copy`;
									}, 2000);
								});
							}
						});

						// Add elements to the DOM
						copyButtonContainer.appendChild(copyButton);

						// Insert after the AI message
						if (aiMsgDiv.nextSibling) {
							messagesDiv.insertBefore(copyButtonContainer, aiMsgDiv.nextSibling);
						} else {
							messagesDiv.appendChild(copyButtonContainer);
						}
					}
				}, 500); // Increased timeout to ensure DOM is fully updated
			} catch (error) {
				console.error('Error:', error);
				const errorMsg = document.createElement('div');
				errorMsg.className = 'ai-message';
				errorMsg.textContent = 'Error occurred while processing your request.';
				messagesDiv.appendChild(errorMsg);
			} finally {
				// Fetch and update token usage after each chat interaction
				// Only if this is still the current session
				if (window.sessionId === sessionId && window.tokenUsageDisplay && typeof window.tokenUsageDisplay.fetch === 'function') {
					console.log('[TokenUsage] Fetching final token usage after request completion');
					window.tokenUsageDisplay.fetch(sessionId);
				}

				// Reset button to "Search" and enable input
				searchButton.textContent = 'Search';
				searchButton.style.backgroundColor = '#44CDF3';
				input.disabled = false;
				currentController = null;
				isRequestInProgress = false;

				// Stop token usage polling when request is completed
				stopTokenUsagePolling();
			}

			messagesDiv.scrollTop = messagesDiv.scrollHeight;
		});

		// Use the updateTokenUsageDisplay function defined at the beginning of the script

		// Fetch token usage manually only for long-running requests
		// This helps avoid redundant polling for quick responses
		let tokenUsagePollingTimer = null;
		let pollingAttempts = 0;
		const MAX_POLLING_ATTEMPTS = 10;

		// Function to start polling for token usage updates
		function startTokenUsagePolling() {
			// Reset attempts counter
			pollingAttempts = 0;
			// Clear any existing timer
			if (tokenUsagePollingTimer) {
				clearInterval(tokenUsagePollingTimer);
			}

			// Start polling immediately to show token usage as soon as possible
			if (isRequestInProgress && sessionId && window.tokenUsageDisplay) {
				console.log('[TokenUsage] Starting token usage polling for request...');

				// Do an initial fetch right away
				window.tokenUsageDisplay.fetch(sessionId);

				// Poll every 3 seconds (reduced from 5 seconds for more responsive updates)
				tokenUsagePollingTimer = setInterval(() => {
					if (isRequestInProgress && sessionId && window.tokenUsageDisplay) {
						console.log('[TokenUsage] Polling for token usage updates...');
						window.tokenUsageDisplay.fetch(sessionId);

						// Increment attempts counter
						pollingAttempts++;

						// If we've reached the maximum number of attempts, slow down polling
						if (pollingAttempts >= MAX_POLLING_ATTEMPTS) {
							console.log('[TokenUsage] Reached maximum polling attempts, slowing down polling');
							clearInterval(tokenUsagePollingTimer);
							tokenUsagePollingTimer = setInterval(() => {
								if (isRequestInProgress && sessionId && window.tokenUsageDisplay) {
									console.log('[TokenUsage] Slow polling for token usage updates...');
									window.tokenUsageDisplay.fetch(sessionId);
								} else {
									clearInterval(tokenUsagePollingTimer);
									tokenUsagePollingTimer = null;
									console.log('[TokenUsage] Stopped slow polling - request completed');
								}
							}, 10000); // Slow down to every 10 seconds
						}
					} else {
						// Stop polling if request is no longer in progress
						clearInterval(tokenUsagePollingTimer);
						tokenUsagePollingTimer = null;
						console.log('[TokenUsage] Stopped polling - request completed');
					}
				}, 3000);
			}
		}

		// Function to stop polling
		function stopTokenUsagePolling() {
			if (tokenUsagePollingTimer) {
				clearInterval(tokenUsagePollingTimer);
				tokenUsagePollingTimer = null;
				console.log('[TokenUsage] Stopped token usage polling');
			}
		}

		const messageInput = document.getElementById('message-input');

		function autoResizeTextarea() {
			messageInput.style.height = 'auto'; // Reset to natural height
			const scrollHeight = messageInput.scrollHeight;
			messageInput.style.height = Math.min(scrollHeight, 200) + 'px'; // Set height, capped at 200px
		}

		// Initialize height on page load
		window.addEventListener('load', () => {
			autoResizeTextarea(); // Set initial height based on content (empty = min-height)
		});

		// Auto-resize as user types
		messageInput.addEventListener('input', autoResizeTextarea);

		// Handle Shift+Enter for new line and Enter for form submission
		messageInput.addEventListener('keydown', function (e) {
			if (e.key === 'Enter') {
				if (e.shiftKey) {
					// Allow new line with Shift+Enter and resize
					setTimeout(autoResizeTextarea, 0);
				} else {
					// Trigger search button click on Enter without Shift
					e.preventDefault();
					searchButton.click();
				}
			}
		});

		// API Key Form Functionality
		document.addEventListener('DOMContentLoaded', function () {
			// Check if API key is already stored
			const storedApiProvider = localStorage.getItem('probeApiProvider');
			const storedApiKey = localStorage.getItem('probeApiKey');
			const storedApiUrl = localStorage.getItem('probeApiUrl');

			const apiProviderSelect = document.getElementById('api-provider');
			const apiKeyInput = document.getElementById('api-key');
			const apiUrlInput = document.getElementById('api-url');
			const saveButton = document.getElementById('save-api-key');
			const headerResetButton = document.getElementById('header-reset-api-key');
			const statusDiv = document.getElementById('api-key-status');
			const apiKeySetupDiv = document.getElementById('api-key-setup');
			const inputForm = document.getElementById('input-form');

			// If API key is stored, show a success message and show the header reset button
			if (storedApiKey) {
				// Show the reset button in the header
				headerResetButton.style.display = 'inline-block';
				statusDiv.textContent = `API key for ${storedApiProvider} is configured`;
				statusDiv.className = 'api-key-status success';
				statusDiv.style.display = 'block';

				// Fill the form with stored values
				if (storedApiProvider) {
					apiProviderSelect.value = storedApiProvider;
				}
				if (storedApiKey) {
					apiKeyInput.value = '••••••••••••••••••••••••••';
				}
				if (storedApiUrl) {
					apiUrlInput.value = storedApiUrl;
				}

				// If we have an API key in local storage, always enable the chat interface
				// regardless of no API keys mode
				// Hide API key setup and show input form
				apiKeySetupDiv.style.display = 'none';
				inputForm.style.display = 'flex';

				// Remove API setup mode class
				document.body.classList.remove('api-setup-mode');
			}

			// Save API key to local storage
			saveButton.addEventListener('click', function () {
				const provider = apiProviderSelect.value;
				const key = apiKeyInput.value;
				const url = apiUrlInput.value;

				// Don't save if the key is masked
				if (key === '••••••••••••••••••••••••••') {
					statusDiv.textContent = 'No changes made to API key';
					statusDiv.className = 'api-key-status';
					statusDiv.style.display = 'block';
					return;
				}

				// Validate inputs
				if (!key) {
					statusDiv.textContent = 'Please enter an API key';
					statusDiv.className = 'api-key-status error';
					statusDiv.style.display = 'block';
					return;
				}

				// Save to local storage
				localStorage.setItem('probeApiProvider', provider);
				localStorage.setItem('probeApiKey', key);
				if (url) {
					localStorage.setItem('probeApiUrl', url);
				} else {
					localStorage.removeItem('probeApiUrl');
				}

				// Show success message
				statusDiv.textContent = `API key for ${provider} saved successfully`;
				statusDiv.className = 'api-key-status success';
				statusDiv.style.display = 'block';

				// Mask the API key for security
				apiKeyInput.value = '••••••••••••••••••••••••••';

				// If we're in no API keys mode, enable the chat interface
				if (document.body.getAttribute('data-no-api-keys') === 'true') {
					// Hide API key setup and show input form
					apiKeySetupDiv.style.display = 'none';
					inputForm.style.display = 'flex';

					// Refresh the page to apply changes
					setTimeout(() => {
						window.location.reload();
					}, 1000);
				}
			});

			// Reset API key from header button
			headerResetButton.addEventListener('click', function (e) {
				e.preventDefault();

				// Confirm before resetting
				if (confirm('Are you sure you want to reset your API key configuration?')) {
					// Remove from local storage
					localStorage.removeItem('probeApiProvider');
					localStorage.removeItem('probeApiKey');
					localStorage.removeItem('probeApiUrl');

					// Hide the reset button
					headerResetButton.style.display = 'none';

					// Show message
					alert('API key configuration has been reset.');

					// Reload the page
					window.location.reload();
				}
			});
		});
	</script>
</body>

</html>