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
|
import React, { useState, useEffect, useRef } from 'react';
import { useReactFlow } from 'reactflow';
import useFlowStore from '../store/flowStore';
import type { NodeData, Trace, Message, MergedTrace, MergeStrategy } from '../store/flowStore';
import ReactMarkdown from 'react-markdown';
import { Play, Settings, Info, Save, ChevronLeft, ChevronRight, Maximize2, Edit3, X, Check, FileText, MessageCircle, Send, GripVertical, GitMerge, Trash2, AlertCircle, Loader2, Navigation } from 'lucide-react';
interface SidebarProps {
isOpen: boolean;
onToggle: () => void;
onInteract?: () => void;
}
const Sidebar: React.FC<SidebarProps> = ({ isOpen, onToggle, onInteract }) => {
const {
nodes, edges, selectedNodeId, updateNodeData, getActiveContext, addNode, setSelectedNode,
isTraceComplete, createQuickChatNode, theme,
createMergedTrace, updateMergedTrace, deleteMergedTrace, computeMergedMessages
} = useFlowStore();
const { setCenter } = useReactFlow();
const isDark = theme === 'dark';
const [activeTab, setActiveTab] = useState<'interact' | 'settings' | 'debug'>('interact');
const [streamBuffer, setStreamBuffer] = useState('');
const [streamingNodeId, setStreamingNodeId] = useState<string | null>(null); // Track which node is streaming
// Response Modal & Edit states
const [isModalOpen, setIsModalOpen] = useState(false);
const [isEditing, setIsEditing] = useState(false);
const [editedResponse, setEditedResponse] = useState('');
// Summary states
const [showSummaryModal, setShowSummaryModal] = useState(false);
const [summaryModel, setSummaryModel] = useState('gpt-5-nano');
const [isSummarizing, setIsSummarizing] = useState(false);
// Quick Chat states
const [quickChatOpen, setQuickChatOpen] = useState(false);
const [quickChatTrace, setQuickChatTrace] = useState<Trace | null>(null);
const [quickChatLastNodeId, setQuickChatLastNodeId] = useState<string | null>(null); // Track the last node in the chat chain
const [quickChatMessages, setQuickChatMessages] = useState<Message[]>([]);
const [quickChatInput, setQuickChatInput] = useState('');
const [quickChatModel, setQuickChatModel] = useState('gpt-5.1');
const [quickChatLoading, setQuickChatLoading] = useState(false);
const [quickChatTemp, setQuickChatTemp] = useState(0.7);
const [quickChatEffort, setQuickChatEffort] = useState<'low' | 'medium' | 'high'>('medium');
const [quickChatNeedsDuplicate, setQuickChatNeedsDuplicate] = useState(false);
const [quickChatWebSearch, setQuickChatWebSearch] = useState(true);
const quickChatEndRef = useRef<HTMLDivElement>(null);
const quickChatInputRef = useRef<HTMLTextAreaElement>(null);
// Merge Trace states
const [showMergeModal, setShowMergeModal] = useState(false);
const [mergeSelectedIds, setMergeSelectedIds] = useState<string[]>([]);
const [mergeStrategy, setMergeStrategy] = useState<MergeStrategy>('query_time');
const [mergeDraggedId, setMergeDraggedId] = useState<string | null>(null);
const [mergeOrder, setMergeOrder] = useState<string[]>([]);
const [showMergePreview, setShowMergePreview] = useState(false);
const [isSummarizingMerge, setIsSummarizingMerge] = useState(false);
const selectedNode = nodes.find((n) => n.id === selectedNodeId);
// Reset stream buffer and modal states when node changes
useEffect(() => {
setStreamBuffer('');
setIsModalOpen(false);
setIsEditing(false);
setShowMergeModal(false);
setMergeSelectedIds([]);
setShowMergePreview(false);
}, [selectedNodeId]);
// Default select first trace when node changes and no trace is selected
useEffect(() => {
if (selectedNode &&
selectedNode.data.traces &&
selectedNode.data.traces.length > 0 &&
(!selectedNode.data.activeTraceIds || selectedNode.data.activeTraceIds.length === 0)) {
updateNodeData(selectedNode.id, {
activeTraceIds: [selectedNode.data.traces[0].id]
});
}
}, [selectedNodeId, selectedNode?.data.traces?.length]);
// Sync editedResponse when entering edit mode
useEffect(() => {
if (isEditing && selectedNode) {
setEditedResponse(selectedNode.data.response || '');
}
}, [isEditing, selectedNode?.data.response]);
// Scroll to bottom when quick chat messages change
useEffect(() => {
if (quickChatEndRef.current) {
quickChatEndRef.current.scrollIntoView({ behavior: 'smooth' });
}
}, [quickChatMessages]);
if (!isOpen) {
return (
<div className={`border-l h-screen flex flex-col items-center py-4 w-12 z-10 transition-all duration-300 ${
isDark ? 'border-gray-700 bg-gray-800' : 'border-gray-200 bg-white'
}`}>
<button
onClick={onToggle}
className={`p-2 rounded mb-4 ${isDark ? 'hover:bg-gray-700' : 'hover:bg-gray-100'}`}
title="Expand"
>
<ChevronLeft size={20} className={isDark ? 'text-gray-400' : 'text-gray-500'} />
</button>
{selectedNode && (
<div className={`writing-vertical text-xs font-bold uppercase tracking-widest mt-4 ${isDark ? 'text-gray-400' : 'text-gray-500'}`} style={{ writingMode: 'vertical-rl' }}>
{selectedNode.data.label}
</div>
)}
</div>
);
}
if (!selectedNode) {
return (
<div className={`w-96 border-l h-screen flex flex-col shadow-xl z-10 transition-all duration-300 ${
isDark ? 'border-gray-700 bg-gray-800' : 'border-gray-200 bg-white'
}`}>
<div className={`p-3 border-b flex justify-between items-center ${
isDark ? 'border-gray-700 bg-gray-900' : 'border-gray-200 bg-gray-50'
}`}>
<span className={`text-sm font-medium ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>Details</span>
<button onClick={onToggle} className={`p-1 rounded ${isDark ? 'hover:bg-gray-700' : 'hover:bg-gray-200'}`}>
<ChevronRight size={16} className={isDark ? 'text-gray-400' : 'text-gray-500'} />
</button>
</div>
<div className={`flex-1 p-4 text-center flex flex-col justify-center ${
isDark ? 'bg-gray-900 text-gray-400' : 'bg-gray-50 text-gray-500'
}`}>
<p>Select a node to edit</p>
</div>
</div>
);
}
const handleRun = async () => {
if (!selectedNode) return;
// Check if upstream is complete before running
const tracesCheck = checkActiveTracesComplete();
if (!tracesCheck.complete) {
console.warn('Cannot run: upstream context is incomplete');
return;
}
// Capture the node ID at the start of the request
const runningNodeId = selectedNode.id;
const runningPrompt = selectedNode.data.userPrompt;
// Record query sent timestamp
const querySentAt = Date.now();
updateNodeData(runningNodeId, { status: 'loading', response: '', querySentAt });
setStreamBuffer('');
setStreamingNodeId(runningNodeId);
// Use getActiveContext which respects the user's selected traces
const context = getActiveContext(runningNodeId);
try {
const response = await fetch('http://localhost:8000/api/run_node_stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
node_id: runningNodeId,
incoming_contexts: [{ messages: context }],
user_prompt: runningPrompt,
merge_strategy: selectedNode.data.mergeStrategy || 'smart',
config: {
provider: selectedNode.data.model.includes('gpt') || selectedNode.data.model === 'o3' ? 'openai' : 'google',
model_name: selectedNode.data.model,
temperature: selectedNode.data.temperature,
system_prompt: selectedNode.data.systemPrompt,
api_key: selectedNode.data.apiKey,
enable_google_search: selectedNode.data.enableGoogleSearch !== false,
reasoning_effort: selectedNode.data.reasoningEffort || 'medium',
}
})
});
if (!response.body) return;
const reader = response.body.getReader();
const decoder = new TextDecoder();
let fullResponse = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
fullResponse += chunk;
// Only update stream buffer, the display logic will check streamingNodeId
setStreamBuffer(prev => prev + chunk);
}
// Update final state using captured nodeId
const newUserMsg = {
id: `msg_${Date.now()}_u`,
role: 'user',
content: runningPrompt
};
const newAssistantMsg = {
id: `msg_${Date.now()}_a`,
role: 'assistant',
content: fullResponse
};
const responseReceivedAt = Date.now();
updateNodeData(runningNodeId, {
status: 'success',
response: fullResponse,
responseReceivedAt,
messages: [...context, newUserMsg, newAssistantMsg] as any
});
// Auto-generate title
generateTitle(runningNodeId, runningPrompt, fullResponse);
} catch (error) {
console.error(error);
updateNodeData(runningNodeId, { status: 'error' });
} finally {
setStreamingNodeId(prev => prev === runningNodeId ? null : prev);
}
};
const handleChange = (field: keyof NodeData, value: any) => {
updateNodeData(selectedNode.id, { [field]: value });
};
const handleSaveEdit = () => {
if (!selectedNode) return;
updateNodeData(selectedNode.id, { response: editedResponse });
setIsEditing(false);
};
const handleCancelEdit = () => {
setIsEditing(false);
setEditedResponse(selectedNode?.data.response || '');
};
// Summarize response
const handleSummarize = async () => {
if (!selectedNode?.data.response) return;
setIsSummarizing(true);
setShowSummaryModal(false);
try {
const res = await fetch('http://localhost:8000/api/summarize', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
content: selectedNode.data.response,
model: summaryModel
})
});
if (res.ok) {
const data = await res.json();
if (data.summary) {
// Replace response with summary
updateNodeData(selectedNode.id, { response: data.summary });
}
}
} catch (error) {
console.error('Summarization failed:', error);
} finally {
setIsSummarizing(false);
}
};
// Auto-generate title using gpt-5-nano
const generateTitle = async (nodeId: string, userPrompt: string, response: string) => {
try {
const res = await fetch('http://localhost:8000/api/generate_title', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ user_prompt: userPrompt, response })
});
if (res.ok) {
const data = await res.json();
if (data.title) {
updateNodeData(nodeId, { label: data.title });
}
}
} catch (error) {
console.error('Failed to generate title:', error);
// Silently fail - keep the original title
}
};
// Open merge modal
const openMergeModal = () => {
if (!selectedNode?.data.traces) return;
const traceIds = selectedNode.data.traces.map((t: Trace) => t.id);
setMergeOrder(traceIds);
setMergeSelectedIds([]);
setShowMergePreview(false);
setShowMergeModal(true);
};
// Drag-and-drop handlers for merge modal
const handleMergeDragStart = (e: React.DragEvent, traceId: string) => {
setMergeDraggedId(traceId);
e.dataTransfer.effectAllowed = 'move';
};
const handleMergeDragOver = (e: React.DragEvent, overTraceId: string) => {
e.preventDefault();
if (!mergeDraggedId || mergeDraggedId === overTraceId) return;
const newOrder = [...mergeOrder];
const draggedIndex = newOrder.indexOf(mergeDraggedId);
const overIndex = newOrder.indexOf(overTraceId);
if (draggedIndex !== -1 && overIndex !== -1) {
newOrder.splice(draggedIndex, 1);
newOrder.splice(overIndex, 0, mergeDraggedId);
setMergeOrder(newOrder);
}
};
const handleMergeDragEnd = () => {
setMergeDraggedId(null);
};
// Toggle trace selection in merge modal
const toggleMergeSelection = (traceId: string) => {
setMergeSelectedIds(prev => {
if (prev.includes(traceId)) {
return prev.filter(id => id !== traceId);
} else {
return [...prev, traceId];
}
});
};
// Create merged trace
const handleCreateMergedTrace = async () => {
if (!selectedNode || mergeSelectedIds.length < 2) return;
// Get the ordered trace IDs based on mergeOrder
const orderedSelectedIds = mergeOrder.filter(id => mergeSelectedIds.includes(id));
if (mergeStrategy === 'summary') {
setIsSummarizingMerge(true);
try {
const messages = computeMergedMessages(selectedNode.id, orderedSelectedIds, 'trace_order');
const content = messages.map(m => `${m.role}: ${m.content}`).join('\n\n');
const res = await fetch('http://localhost:8000/api/summarize', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
content,
model_name: 'gpt-5-nano',
api_key: selectedNode.data.apiKey
})
});
if (res.ok) {
const data = await res.json();
const mergedId = createMergedTrace(selectedNode.id, orderedSelectedIds, 'summary');
if (mergedId && data.summary) {
updateMergedTrace(selectedNode.id, mergedId, { summarizedContent: data.summary });
}
}
} catch (error) {
console.error('Failed to summarize for merge:', error);
} finally {
setIsSummarizingMerge(false);
}
} else {
createMergedTrace(selectedNode.id, orderedSelectedIds, mergeStrategy);
}
// Close modal and reset
setShowMergeModal(false);
setMergeSelectedIds([]);
setShowMergePreview(false);
};
// Get preview of merged messages
const getMergePreview = () => {
if (!selectedNode || mergeSelectedIds.length < 2) return [];
const orderedSelectedIds = mergeOrder.filter(id => mergeSelectedIds.includes(id));
return computeMergedMessages(selectedNode.id, orderedSelectedIds, mergeStrategy);
};
// Check if a trace has downstream nodes from the current selected node
const traceHasDownstream = (trace: Trace): boolean => {
if (!selectedNode) return false;
// Find edges going out from selectedNode that are part of this trace
const outgoingEdge = edges.find(e =>
e.source === selectedNode.id &&
e.sourceHandle?.startsWith('trace-')
);
return !!outgoingEdge;
};
// Quick Chat functions
const openQuickChat = (trace: Trace | null, isNewTrace: boolean = false) => {
if (!selectedNode) return;
onInteract?.(); // Close context menu when opening quick chat
// Check if current node has a "sent" query (has response) or just unsent draft
const hasResponse = !!selectedNode.data.response;
const hasDraftPrompt = !!selectedNode.data.userPrompt && !hasResponse;
if (isNewTrace || !trace) {
// Start a new trace from current node
const initialMessages: Message[] = [];
// Only include user prompt as message if it was actually sent (has response)
if (selectedNode.data.userPrompt && hasResponse) {
initialMessages.push({ id: `${selectedNode.id}-u`, role: 'user', content: selectedNode.data.userPrompt });
}
if (selectedNode.data.response) {
initialMessages.push({ id: `${selectedNode.id}-a`, role: 'assistant', content: selectedNode.data.response });
}
setQuickChatTrace({
id: `new-trace-${selectedNode.id}`,
sourceNodeId: selectedNode.id,
color: '#888',
messages: initialMessages
});
setQuickChatMessages(initialMessages);
setQuickChatNeedsDuplicate(false);
setQuickChatLastNodeId(selectedNode.id);
} else {
// Use existing trace context
const hasDownstream = traceHasDownstream(trace);
setQuickChatNeedsDuplicate(hasDownstream);
// Build full message history
const fullMessages: Message[] = [...trace.messages];
// Only include current node's content if it was sent
if (selectedNode.data.userPrompt && hasResponse) {
fullMessages.push({ id: `${selectedNode.id}-u`, role: 'user', content: selectedNode.data.userPrompt });
}
if (selectedNode.data.response) {
fullMessages.push({ id: `${selectedNode.id}-a`, role: 'assistant', content: selectedNode.data.response });
}
setQuickChatTrace({
...trace,
sourceNodeId: selectedNode.id,
messages: fullMessages
});
setQuickChatMessages(fullMessages);
// Set last node ID: if current node has response, start from here.
// Otherwise start from trace source (which is the last completed node)
setQuickChatLastNodeId(hasResponse ? selectedNode.id : trace.sourceNodeId);
}
setQuickChatOpen(true);
// If there's an unsent draft, put it in the input box
setQuickChatInput(hasDraftPrompt ? selectedNode.data.userPrompt : '');
};
const closeQuickChat = () => {
setQuickChatOpen(false);
setQuickChatTrace(null);
setQuickChatMessages([]);
};
// Open Quick Chat for a merged trace
const openMergedQuickChat = (merged: MergedTrace) => {
if (!selectedNode) return;
onInteract?.();
// Check if current node has a "sent" query (has response) or just unsent draft
const hasResponse = !!selectedNode.data.response;
const hasDraftPrompt = !!selectedNode.data.userPrompt && !hasResponse;
// Build messages from merged trace
const fullMessages: Message[] = [...merged.messages];
// Only include current node's content if it was sent
if (selectedNode.data.userPrompt && hasResponse) {
fullMessages.push({ id: `${selectedNode.id}-u`, role: 'user', content: selectedNode.data.userPrompt });
}
if (selectedNode.data.response) {
fullMessages.push({ id: `${selectedNode.id}-a`, role: 'assistant', content: selectedNode.data.response });
}
// Create a pseudo-trace for the merged context
setQuickChatTrace({
id: merged.id,
sourceNodeId: selectedNode.id,
color: merged.colors[0] || '#888',
messages: fullMessages
});
setQuickChatMessages(fullMessages);
setQuickChatNeedsDuplicate(false); // Merged traces don't duplicate
setQuickChatOpen(true);
// If there's an unsent draft, put it in the input box
setQuickChatInput(hasDraftPrompt ? selectedNode.data.userPrompt : '');
};
// Check if a trace is complete (all upstream nodes have Q&A)
const canQuickChat = (trace: Trace): boolean => {
return isTraceComplete(trace);
};
// Helper: Check if all upstream nodes have complete Q&A by traversing edges
const checkUpstreamNodesComplete = (nodeId: string, visited: Set<string> = new Set()): boolean => {
if (visited.has(nodeId)) return true; // Avoid cycles
visited.add(nodeId);
const node = nodes.find(n => n.id === nodeId);
if (!node) return true;
// Find all incoming edges to this node
const incomingEdges = edges.filter(e => e.target === nodeId);
for (const edge of incomingEdges) {
const sourceNode = nodes.find(n => n.id === edge.source);
if (!sourceNode) continue;
// Check if source node is disabled - skip disabled nodes
if (sourceNode.data.disabled) continue;
// Check if source node has complete Q&A
if (!sourceNode.data.userPrompt || !sourceNode.data.response) {
return false; // Found an incomplete upstream node
}
// Recursively check further upstream
if (!checkUpstreamNodesComplete(edge.source, visited)) {
return false;
}
}
return true;
};
// Helper: find incoming edge for a given trace ID (with fallbacks)
const findIncomingEdgeForTrace = (nodeId: string, traceId: string): Edge | null => {
// 1) exact match by sourceHandle
let edge = edges.find(e => e.target === nodeId && e.sourceHandle === `trace-${traceId}`);
if (edge) return edge;
// 2) fallback: any incoming edge whose source has this trace in outgoingTraces
edge = edges.find(e => {
if (e.target !== nodeId) return false;
const src = nodes.find(n => n.id === e.source);
return src?.data.outgoingTraces?.some((t: Trace) => t.id === traceId);
});
return edge || null;
};
// Helper: get source trace IDs for a merged trace on a given node (supports propagated merged traces)
const getMergedSourceIds = (nodeId: string, traceId: string): string[] => {
const node = nodes.find(n => n.id === nodeId);
if (!node) return [];
const mergedLocal = node.data.mergedTraces?.find((m: MergedTrace) => m.id === traceId);
if (mergedLocal) return mergedLocal.sourceTraceIds || [];
const incomingMatch = node.data.traces?.find((t: Trace) => t.id === traceId);
if (incomingMatch?.isMerged && incomingMatch.sourceTraceIds) return incomingMatch.sourceTraceIds;
const outgoingMatch = node.data.outgoingTraces?.find((t: Trace) => t.id === traceId);
if (outgoingMatch?.isMerged && outgoingMatch.sourceTraceIds) return outgoingMatch.sourceTraceIds;
return [];
};
// Recursive: Check if specific trace path upstream has complete nodes (supports multi-level merged)
const checkTracePathComplete = (
nodeId: string,
traceId: string,
visited: Set<string> = new Set()
): boolean => {
const visitKey = `${nodeId}-${traceId}`;
if (visited.has(visitKey)) return true;
visited.add(visitKey);
// Determine if this node is the merge owner or just receiving a propagated merged trace
const localMerge = nodes.find(n => n.id === nodeId)?.data.mergedTraces?.some(m => m.id === traceId);
const localParents = getMergedSourceIds(nodeId, traceId);
const incomingEdge = findIncomingEdgeForTrace(nodeId, traceId);
if (!incomingEdge) {
// If no incoming edge and this node owns the merge, check parents from here
if (localMerge && localParents.length > 0) {
for (const pid of localParents) {
if (!checkTracePathComplete(nodeId, pid, visited)) return false;
}
return true;
}
return true; // head
}
const sourceNode = nodes.find(n => n.id === incomingEdge.source);
if (!sourceNode || sourceNode.data.disabled) return true;
// If merged at sourceNode (or propagated merged), recurse into each parent from the merge owner
const parentIds = localMerge ? localParents : getMergedSourceIds(sourceNode.id, traceId);
if (parentIds.length > 0) {
const mergeOwnerId = localMerge ? nodeId : sourceNode.id;
for (const pid of parentIds) {
if (!checkTracePathComplete(mergeOwnerId, pid, visited)) return false;
}
return true;
}
// Regular trace: check node content then continue upstream
if (!sourceNode.data.userPrompt || !sourceNode.data.response) return false;
return checkTracePathComplete(sourceNode.id, traceId, visited);
};
// Recursive: Find the first empty node on a specific trace path (supports multi-level merged)
const findEmptyNodeOnTrace = (
nodeId: string,
traceId: string,
visited: Set<string> = new Set()
): string | null => {
const visitKey = `${nodeId}-${traceId}`;
if (visited.has(visitKey)) return null;
visited.add(visitKey);
// Determine if this node owns the merge or just receives propagated merged trace
const localMerge = nodes.find(n => n.id === nodeId)?.data.mergedTraces?.some(m => m.id === traceId);
const localParents = getMergedSourceIds(nodeId, traceId);
const incomingEdge = findIncomingEdgeForTrace(nodeId, traceId);
if (!incomingEdge) {
if (localMerge && localParents.length > 0) {
for (const pid of localParents) {
const upstreamEmpty = findEmptyNodeOnTrace(nodeId, pid, visited);
if (upstreamEmpty) return upstreamEmpty;
}
}
return null;
}
const sourceNode = nodes.find(n => n.id === incomingEdge.source);
if (!sourceNode || sourceNode.data.disabled) return null;
const parentIds = localMerge ? localParents : getMergedSourceIds(sourceNode.id, traceId);
if (parentIds.length > 0) {
const mergeOwnerId = localMerge ? nodeId : sourceNode.id;
for (const pid of parentIds) {
const upstreamEmpty = findEmptyNodeOnTrace(mergeOwnerId, pid, visited);
if (upstreamEmpty) return upstreamEmpty;
}
}
if (!sourceNode.data.userPrompt || !sourceNode.data.response) {
return sourceNode.id;
}
return findEmptyNodeOnTrace(sourceNode.id, traceId, visited);
};
// Check if all active traces are complete (for main Run Node button)
const checkActiveTracesComplete = (): { complete: boolean; incompleteTraceId?: string } => {
if (!selectedNode) return { complete: true };
const activeTraceIds = selectedNode.data.activeTraceIds || [];
if (activeTraceIds.length === 0) return { complete: true };
// Check upstream nodes ONLY for active traces (supports merged trace recursion)
for (const traceId of activeTraceIds) {
if (!checkTracePathComplete(selectedNode.id, traceId)) {
return { complete: false, incompleteTraceId: 'upstream' };
}
}
// Check incoming traces content (message integrity)
const incomingTraces = selectedNode.data.traces || [];
for (const traceId of activeTraceIds) {
const trace = incomingTraces.find((t: Trace) => t.id === traceId);
if (trace && !isTraceComplete(trace)) {
return { complete: false, incompleteTraceId: traceId };
}
}
// Check merged traces content (including propagated merged traces)
for (const traceId of activeTraceIds) {
const sourceIds = getMergedSourceIds(selectedNode.id, traceId);
if (sourceIds.length > 0) {
for (const sourceId of sourceIds) {
const sourceTrace = incomingTraces.find((t: Trace) => t.id === sourceId);
if (sourceTrace && !isTraceComplete(sourceTrace)) {
return { complete: false, incompleteTraceId: sourceId };
}
}
}
}
return { complete: true };
};
// Navigate to an empty upstream node on the active traces
const navigateToEmptyNode = () => {
if (!selectedNode) return;
const activeTraceIds = selectedNode.data.activeTraceIds || [];
for (const traceId of activeTraceIds) {
const emptyNodeId = findEmptyNodeOnTrace(selectedNode.id, traceId);
if (emptyNodeId) {
const emptyNode = nodes.find(n => n.id === emptyNodeId);
if (emptyNode) {
setCenter(emptyNode.position.x + 100, emptyNode.position.y + 50, { zoom: 1.2, duration: 500 });
setSelectedNode(emptyNodeId);
return; // Found one, navigate and stop
}
}
}
};
const activeTracesCheck = selectedNode ? checkActiveTracesComplete() : { complete: true };
const handleQuickChatSend = async () => {
if (!quickChatInput.trim() || !quickChatTrace || quickChatLoading || !selectedNode) return;
const userInput = quickChatInput;
const userMessage: Message = {
id: `qc_${Date.now()}_u`,
role: 'user',
content: userInput
};
// Add user message to display
const messagesBeforeSend = [...quickChatMessages];
setQuickChatMessages(prev => [...prev, userMessage]);
setQuickChatInput('');
setQuickChatLoading(true);
// Store model at send time to avoid issues with model switching during streaming
const modelAtSend = quickChatModel;
const tempAtSend = quickChatTemp;
const effortAtSend = quickChatEffort;
const webSearchAtSend = quickChatWebSearch;
try {
// Determine provider
const isOpenAI = modelAtSend.includes('gpt') || modelAtSend === 'o3';
const reasoningModels = ['gpt-5', 'gpt-5-chat-latest', 'gpt-5-mini', 'gpt-5-nano', 'gpt-5-pro', 'gpt-5.1', 'gpt-5.1-chat-latest', 'o3'];
const isReasoning = reasoningModels.includes(modelAtSend);
// Call LLM API with current messages as context
const response = await fetch('http://localhost:8000/api/run_node_stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
node_id: 'quick_chat_temp',
incoming_contexts: [{ messages: messagesBeforeSend }],
user_prompt: userInput,
merge_strategy: 'smart',
config: {
provider: isOpenAI ? 'openai' : 'google',
model_name: modelAtSend,
temperature: isReasoning ? 1 : tempAtSend,
enable_google_search: webSearchAtSend,
reasoning_effort: effortAtSend,
}
})
});
if (!response.body) throw new Error('No response body');
const reader = response.body.getReader();
const decoder = new TextDecoder();
let fullResponse = '';
// Stream response
while (true) {
const { value, done } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
fullResponse += chunk;
// Update display in real-time
setQuickChatMessages(prev => {
const newMsgs = [...prev];
const lastMsg = newMsgs[newMsgs.length - 1];
if (lastMsg?.role === 'assistant') {
// Update existing assistant message
return [...newMsgs.slice(0, -1), { ...lastMsg, content: fullResponse }];
} else {
// Add new assistant message
return [...newMsgs, { id: `qc_${Date.now()}_a`, role: 'assistant', content: fullResponse }];
}
});
}
// Determine whether to overwrite current node or create new one
// Use quickChatLastNodeId as the "current" node in the chat flow to ensure continuity
// If not set, fallback to quickChatTrace.sourceNodeId (initial state)
const fromNodeId = quickChatLastNodeId || quickChatTrace.sourceNodeId;
const fromNode = nodes.find(n => n.id === fromNodeId);
const fromNodeHasResponse = fromNode?.data.response && fromNode.data.response.trim() !== '';
if (!fromNodeHasResponse && fromNode) {
// Overwrite the source node (it's empty)
updateNodeData(fromNodeId, {
userPrompt: userInput,
response: fullResponse,
model: modelAtSend,
temperature: isReasoning ? 1 : tempAtSend,
reasoningEffort: effortAtSend,
enableGoogleSearch: webSearchAtSend,
status: 'success',
querySentAt: Date.now(),
responseReceivedAt: Date.now()
});
// Update trace to reflect current node now has content
setQuickChatTrace(prev => prev ? {
...prev,
messages: [...messagesBeforeSend, userMessage, { id: `qc_${Date.now()}_a`, role: 'assistant', content: fullResponse }]
} : null);
// Update last node ID
setQuickChatLastNodeId(fromNodeId);
// Generate title
generateTitle(fromNodeId, userInput, fullResponse);
} else {
// Create new node (source node has response, continue the chain)
const newNodeId = `node_${Date.now()}`;
const sourceNode = fromNode || selectedNode;
const newPos = {
x: sourceNode.position.x + 300,
y: sourceNode.position.y
};
const newNode = {
id: newNodeId,
type: 'llmNode',
position: newPos,
data: {
label: 'Quick Chat',
model: modelAtSend,
temperature: isReasoning ? 1 : tempAtSend,
systemPrompt: '',
userPrompt: userInput,
mergeStrategy: 'smart' as const,
reasoningEffort: effortAtSend,
enableGoogleSearch: webSearchAtSend,
traces: [],
outgoingTraces: [],
forkedTraces: [],
mergedTraces: [],
activeTraceIds: [],
response: fullResponse,
status: 'success' as const,
inputs: 1,
querySentAt: Date.now(),
responseReceivedAt: Date.now()
}
};
addNode(newNode);
// Connect to the source node
setTimeout(() => {
const store = useFlowStore.getState();
const currentEdges = store.edges;
const sourceNodeData = store.nodes.find(n => n.id === fromNodeId);
// Find the right trace handle to use
let sourceHandle = 'new-trace';
// Get the base trace ID (e.g., 'trace-A' from 'trace-A_B_C' or 'new-trace-A' or 'merged-xxx')
const currentTraceId = quickChatTrace?.id || '';
const isNewTrace = currentTraceId.startsWith('new-trace-');
const isMergedTrace = currentTraceId.startsWith('merged-');
if (isMergedTrace) {
// For merged trace: find the merged trace handle on the source node
// The trace ID may have evolved (e.g., 'merged-xxx' -> 'merged-xxx_nodeA' -> 'merged-xxx_nodeA_nodeB')
// We need to find the version that ends with the current source node ID
// First try: exact match with evolved ID (merged-xxx_sourceNodeId)
const evolvedMergedId = `${currentTraceId}_${fromNodeId}`;
let mergedOutgoing = sourceNodeData?.data.outgoingTraces?.find(
t => t.id === evolvedMergedId
);
// Second try: find trace that starts with merged ID and ends with this node
if (!mergedOutgoing) {
mergedOutgoing = sourceNodeData?.data.outgoingTraces?.find(
t => t.id.startsWith(currentTraceId) && t.id.endsWith(`_${fromNodeId}`)
);
}
// Third try: find any trace that contains the merged ID
if (!mergedOutgoing) {
mergedOutgoing = sourceNodeData?.data.outgoingTraces?.find(
t => t.id.startsWith(currentTraceId) || t.id === currentTraceId
);
}
// Fourth try: find any merged trace
if (!mergedOutgoing) {
mergedOutgoing = sourceNodeData?.data.outgoingTraces?.find(
t => t.id.startsWith('merged-')
);
}
if (mergedOutgoing) {
sourceHandle = `trace-${mergedOutgoing.id}`;
} else {
// Last resort: use the merged trace ID directly
sourceHandle = `trace-${currentTraceId}`;
}
} else if (isNewTrace) {
// For "Start New Trace": create a fresh independent trace from the original node
// First, check if this is the original starting node or a continuation node
const originalStartNodeId = currentTraceId.replace('new-trace-', '');
const isOriginalNode = fromNodeId === originalStartNodeId;
if (isOriginalNode) {
// This is the first round - starting from original node
const hasOutgoingEdges = currentEdges.some(e => e.source === fromNodeId);
if (hasOutgoingEdges) {
// Original node already has downstream - create a new fork
sourceHandle = 'new-trace';
} else {
// No downstream yet - use self trace
const selfTrace = sourceNodeData?.data.outgoingTraces?.find(
t => t.id === `trace-${fromNodeId}`
);
if (selfTrace) {
sourceHandle = `trace-${selfTrace.id}`;
}
}
} else {
// This is a continuation - find the trace ID (should be preserved now)
// Look for a trace that was created from the original node's self trace
const matchingTrace = sourceNodeData?.data.outgoingTraces?.find(t => {
return t.id.includes(originalStartNodeId);
});
if (matchingTrace) {
sourceHandle = `trace-${matchingTrace.id}`;
} else {
// Fallback 1: Check INCOMING traces (Connect to Continue Handle)
const incoming = sourceNodeData?.data.traces?.find(t =>
t.id.includes(originalStartNodeId)
);
if (incoming) {
// ID is preserved, so handle ID is just trace-{id}
sourceHandle = `trace-${incoming.id}`;
} else {
// Fallback 2: find any trace that ends with fromNodeId (unlikely if ID preserved)
const anyMatch = sourceNodeData?.data.outgoingTraces?.find(
t => t.id === `trace-${fromNodeId}`
);
if (anyMatch) {
sourceHandle = `trace-${anyMatch.id}`;
}
}
}
}
} else {
// For existing trace: ID is preserved
const baseTraceId = currentTraceId.replace(/^trace-/, '');
// 1. Try OUTGOING traces first (if already connected downstream)
const matchingOutgoing = sourceNodeData?.data.outgoingTraces?.find(t => {
const traceBase = t.id.replace(/^trace-/, '');
return traceBase === baseTraceId; // Exact match now
});
if (matchingOutgoing) {
sourceHandle = `trace-${matchingOutgoing.id}`;
} else {
// 2. Try INCOMING traces (Connect to Continue Handle)
const matchingIncoming = sourceNodeData?.data.traces?.find(t => {
const tId = t.id.replace(/^trace-/, '');
return tId === baseTraceId; // Exact match now
});
if (matchingIncoming) {
// ID is preserved
sourceHandle = `trace-${matchingIncoming.id}`;
}
}
}
// If this is the first message and we need to duplicate (has downstream),
// onConnect will automatically handle the trace duplication
// because the sourceHandle already has an outgoing edge
store.onConnect({
source: fromNodeId,
sourceHandle,
target: newNodeId,
targetHandle: 'input-0'
});
// After first duplication, subsequent messages continue on the new trace
// Reset the duplicate flag since we're now on the new branch
setQuickChatNeedsDuplicate(false);
// Update trace for continued chat - use newNodeId as the new source
// Find the actual trace ID on the new node to ensure continuity
const newNode = store.nodes.find(n => n.id === newNodeId);
const currentId = quickChatTrace?.id || '';
const isMerged = currentId.startsWith('merged-');
const isCurrentNewTrace = currentId.startsWith('new-trace-');
let nextTraceId = currentId;
if (newNode && newNode.data.outgoingTraces) {
// Find the trace that continues the current conversation
// Now trace IDs don't evolve, so it should be simpler
if (isMerged) {
// Merged traces might still need evolution or logic check
// For now assuming linear extension keeps same ID if we changed flowStore
// But merged trace logic in flowStore might still append ID?
// Let's check if evolved version exists
const evolved = newNode.data.outgoingTraces.find(t =>
t.id === `${currentId}_${newNodeId}`
);
if (evolved) nextTraceId = evolved.id;
else nextTraceId = currentId; // Try keeping same ID
} else if (isCurrentNewTrace) {
// For new trace, check if we have an outgoing trace with the start node ID
const startNodeId = currentId.replace('new-trace-', '');
const match = newNode.data.outgoingTraces.find(t =>
t.id.includes(startNodeId)
);
if (match) nextTraceId = match.id;
} else {
// Regular trace: ID should be preserved
nextTraceId = currentId;
}
}
setQuickChatTrace(prev => prev ? {
...prev,
id: nextTraceId,
sourceNodeId: newNodeId,
messages: [...messagesBeforeSend, userMessage, { id: `qc_${Date.now()}_a`, role: 'assistant', content: fullResponse }]
} : null);
// Update last node ID to the new node
setQuickChatLastNodeId(newNodeId);
// Generate title
generateTitle(newNodeId, userInput, fullResponse);
}, 100);
}
} catch (error) {
console.error('Quick chat error:', error);
setQuickChatMessages(prev => [...prev, {
id: `qc_err_${Date.now()}`,
role: 'assistant',
content: `Error: ${error}`
}]);
} finally {
setQuickChatLoading(false);
// Refocus the input after sending
setTimeout(() => {
quickChatInputRef.current?.focus();
}, 50);
}
};
return (
<div
className={`w-96 border-l h-screen flex flex-col shadow-xl z-10 transition-all duration-300 ${
isDark ? 'border-gray-700 bg-gray-800' : 'border-gray-200 bg-white'
}`}
onClick={onInteract}
>
{/* Header */}
<div className={`p-4 border-b flex flex-col gap-2 ${
isDark ? 'border-gray-700 bg-gray-900' : 'border-gray-200 bg-gray-50'
}`}>
<div className="flex justify-between items-center">
<input
type="text"
value={selectedNode.data.label}
onChange={(e) => handleChange('label', e.target.value)}
className={`font-bold text-lg bg-transparent border-none focus:ring-0 focus:outline-none w-full ${
isDark ? 'text-gray-200' : 'text-gray-900'
}`}
/>
<button onClick={onToggle} className={`p-1 rounded shrink-0 ${isDark ? 'hover:bg-gray-700' : 'hover:bg-gray-200'}`}>
<ChevronRight size={16} className={isDark ? 'text-gray-400' : 'text-gray-500'} />
</button>
</div>
<div className="flex items-center justify-between mt-1">
<div className={`text-xs px-2 py-1 rounded uppercase ${
isDark ? 'bg-blue-900 text-blue-300' : 'bg-blue-100 text-blue-700'
}`}>
{selectedNode.data.status}
</div>
<div className={`text-xs ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
ID: {selectedNode.id}
</div>
</div>
</div>
{/* Tabs */}
<div className={`flex border-b ${isDark ? 'border-gray-700' : 'border-gray-200'}`}>
<button
onClick={() => setActiveTab('interact')}
className={`flex-1 p-3 text-sm flex justify-center items-center gap-2 ${activeTab === 'interact' ? 'border-b-2 border-blue-500 text-blue-600 font-medium' : 'text-gray-600 hover:bg-gray-50'}`}
>
<Play size={16} /> Interact
</button>
<button
onClick={() => setActiveTab('settings')}
className={`flex-1 p-3 text-sm flex justify-center items-center gap-2 ${activeTab === 'settings' ? 'border-b-2 border-blue-500 text-blue-600 font-medium' : 'text-gray-600 hover:bg-gray-50'}`}
>
<Settings size={16} /> Settings
</button>
<button
onClick={() => setActiveTab('debug')}
className={`flex-1 p-3 text-sm flex justify-center items-center gap-2 ${activeTab === 'debug' ? 'border-b-2 border-blue-500 text-blue-600 font-medium' : 'text-gray-600 hover:bg-gray-50'}`}
>
<Info size={16} /> Debug
</button>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto p-4">
{activeTab === 'interact' && (
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Model</label>
<select
value={selectedNode.data.model}
onChange={(e) => {
const newModel = e.target.value;
// Auto-set temperature to 1 for reasoning models
const reasoningModels = [
'gpt-5', 'gpt-5-chat-latest', 'gpt-5-mini', 'gpt-5-nano',
'gpt-5-pro', 'gpt-5.1', 'gpt-5.1-chat-latest', 'o3'
];
const isReasoning = reasoningModels.includes(newModel);
if (isReasoning) {
handleChange('temperature', 1);
}
handleChange('model', newModel);
}}
className="w-full border border-gray-300 rounded-md p-2 text-sm"
>
<optgroup label="Gemini">
<option value="gemini-2.5-flash">gemini-2.5-flash</option>
<option value="gemini-2.5-flash-lite">gemini-2.5-flash-lite</option>
<option value="gemini-3-pro-preview">gemini-3-pro-preview</option>
</optgroup>
<optgroup label="OpenAI (Standard)">
<option value="gpt-4.1">gpt-4.1</option>
<option value="gpt-4o">gpt-4o</option>
</optgroup>
<optgroup label="OpenAI (Reasoning)">
<option value="gpt-5">gpt-5</option>
<option value="gpt-5-chat-latest">gpt-5-chat-latest</option>
<option value="gpt-5-mini">gpt-5-mini</option>
<option value="gpt-5-nano">gpt-5-nano</option>
<option value="gpt-5-pro">gpt-5-pro</option>
<option value="gpt-5.1">gpt-5.1</option>
<option value="gpt-5.1-chat-latest">gpt-5.1-chat-latest</option>
<option value="o3">o3</option>
</optgroup>
</select>
</div>
{/* Trace Selector - Single Select */}
<div className={`p-2 rounded border ${isDark ? 'bg-gray-900 border-gray-700' : 'bg-gray-50 border-gray-200'}`}>
<div className="flex items-center justify-between mb-2">
<label className={`block text-xs font-bold uppercase ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
Select Context
</label>
{/* Create Merged Trace Button - only show if 2+ traces */}
{selectedNode.data.traces && selectedNode.data.traces.length >= 2 && (
<button
onClick={openMergeModal}
className={`text-xs px-2 py-1 rounded flex items-center gap-1 ${
isDark
? 'bg-purple-900 hover:bg-purple-800 text-purple-300'
: 'bg-purple-100 hover:bg-purple-200 text-purple-600'
}`}
>
<GitMerge size={12} />
Merge
</button>
)}
</div>
{/* New Trace option */}
<div className={`flex items-center gap-2 text-sm p-1 rounded group mb-1 border-b pb-2 ${
isDark ? 'hover:bg-gray-800 border-gray-700' : 'hover:bg-white border-gray-200'
}`}>
<div className="flex items-center gap-2 flex-1">
<div className="w-2 h-2 rounded-full bg-gray-400"></div>
<span className={`text-xs ${isDark ? 'text-gray-400' : 'text-gray-600'}`}>Start New Trace</span>
</div>
<button
onClick={(e) => {
e.stopPropagation();
openQuickChat(null, true);
}}
className={`p-1 rounded transition-all ${
isDark ? 'hover:bg-blue-900 text-gray-500 hover:text-blue-400' : 'hover:bg-blue-100 text-gray-400 hover:text-blue-600'
}`}
title="Start New Trace Quick Chat"
>
<MessageCircle size={14} />
</button>
</div>
{/* All Available Traces - Incoming + Outgoing that this node originated */}
{(() => {
// 1. Incoming traces (context from upstream)
const incomingTraces = selectedNode.data.traces || [];
// 2. Outgoing traces that this node ORIGINATED (not pass-through, not merged)
// This includes self-started traces, forked traces, and prepend traces
const outgoingTraces = (selectedNode.data.outgoingTraces || []) as Trace[];
const originatedTraces = outgoingTraces.filter(t => {
// Exclude merged traces - they have their own display section
if (t.id.startsWith('merged-')) return false;
// Include if this node is the source (originated here)
// OR if the trace ID matches a forked/prepend trace pattern from this node
const isOriginated = t.sourceNodeId === selectedNode.id;
const isForkedHere = t.id.includes(`fork-${selectedNode.id}`);
const isSelfTrace = t.id === `trace-${selectedNode.id}`;
return isOriginated || isForkedHere || isSelfTrace;
});
// Combine and deduplicate by ID
// Priority: incoming traces (have full context) > originated outgoing traces
const allTracesMap = new Map<string, Trace>();
// Add originated outgoing traces first
originatedTraces.forEach(t => allTracesMap.set(t.id, t));
// Then incoming traces (will overwrite if same ID, as they have fuller context)
incomingTraces.forEach(t => allTracesMap.set(t.id, t));
const allTraces = Array.from(allTracesMap.values());
if (allTraces.length === 0) return null;
return (
<div className="space-y-1 max-h-[150px] overflow-y-auto">
{allTraces.map((trace: Trace) => {
const isActive = selectedNode.data.activeTraceIds?.includes(trace.id);
const isComplete = canQuickChat(trace);
return (
<div
key={trace.id}
onClick={() => handleChange('activeTraceIds', [trace.id])}
className={`flex items-start gap-2 text-sm p-1.5 rounded group cursor-pointer transition-all ${
isActive
? isDark ? 'bg-blue-900/50 border border-blue-700' : 'bg-blue-50 border border-blue-200'
: isDark ? 'hover:bg-gray-800' : 'hover:bg-white'
}`}
>
<input
type="radio"
checked={isActive || false}
readOnly
className="mt-1"
/>
<div className="flex-1">
<div className="flex items-center gap-2">
{trace.isMerged ? (
// Merged Trace Rendering (for propagated merged traces)
<div className="flex -space-x-1 shrink-0">
{(trace.mergedColors || [trace.color]).slice(0, 3).map((color, idx) => (
<div
key={idx}
className="w-2 h-2 rounded-full border-2"
style={{ backgroundColor: color, borderColor: isDark ? '#1f2937' : '#fff' }}
/>
))}
{(trace.mergedColors?.length || 0) > 3 && (
<div className={`w-2 h-2 rounded-full flex items-center justify-center text-[6px] ${
isDark ? 'bg-gray-700 text-gray-400' : 'bg-gray-200 text-gray-500'
}`}>
+
</div>
)}
</div>
) : (
// Regular Trace Rendering
<div className="w-2 h-2 rounded-full" style={{ backgroundColor: trace.color }}></div>
)}
<span className={`font-mono text-xs ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
{trace.isMerged ? 'Merged ' : ''}#{trace.id.slice(-4)}
</span>
{!isComplete && (
<span className="text-[9px] text-orange-500">(incomplete)</span>
)}
</div>
<div className={`text-[10px] ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
{trace.messages.length} msgs
</div>
</div>
{/* Quick Chat Button */}
{(() => {
const hasDownstream = edges.some(e =>
e.source === selectedNode.id &&
e.sourceHandle?.startsWith('trace-')
);
const buttonLabel = hasDownstream ? "Duplicate & Quick Chat" : "Quick Chat";
return (
<button
onClick={(e) => {
e.stopPropagation();
openQuickChat(trace, false);
}}
disabled={!isComplete}
className={`opacity-0 group-hover:opacity-100 p-1 rounded transition-all ${
isComplete
? hasDownstream
? isDark ? 'hover:bg-orange-900 text-gray-500 hover:text-orange-400' : 'hover:bg-orange-100 text-gray-400 hover:text-orange-600'
: isDark ? 'hover:bg-blue-900 text-gray-500 hover:text-blue-400' : 'hover:bg-blue-100 text-gray-400 hover:text-blue-600'
: 'text-gray-500 cursor-not-allowed'
}`}
title={isComplete ? buttonLabel : "Trace incomplete - all nodes need Q&A"}
>
<MessageCircle size={14} />
</button>
);
})()}
</div>
);
})}
</div>
);
})()}
{/* Merged Traces - also single selectable */}
{selectedNode.data.mergedTraces && selectedNode.data.mergedTraces.length > 0 && (
<div className={`mt-2 pt-2 border-t space-y-1 ${isDark ? 'border-gray-700' : 'border-gray-200'}`}>
<label className={`block text-[10px] font-bold uppercase mb-1 ${isDark ? 'text-purple-400' : 'text-purple-600'}`}>
Merged Traces
</label>
{selectedNode.data.mergedTraces.map((merged: MergedTrace) => {
const isActive = selectedNode.data.activeTraceIds?.includes(merged.id);
// Check if merged trace is complete
const isComplete = merged.sourceTraceIds.every(sourceId => {
// Check trace path completeness (upstream empty nodes)
const pathComplete = checkTracePathComplete(selectedNode.id, sourceId);
if (!pathComplete) return false;
// Check message integrity
const incomingTraces = selectedNode.data.traces || [];
const sourceTrace = incomingTraces.find(t => t.id === sourceId);
if (sourceTrace && !isTraceComplete(sourceTrace)) return false;
return true;
});
return (
<div
key={merged.id}
onClick={() => handleChange('activeTraceIds', [merged.id])}
className={`flex items-center gap-2 p-1.5 rounded text-xs cursor-pointer transition-all ${
isActive
? isDark ? 'bg-purple-900/50 border border-purple-600' : 'bg-purple-50 border border-purple-300'
: isDark ? 'bg-gray-800 hover:bg-gray-700' : 'bg-white border border-gray-200 hover:bg-gray-50'
}`}
>
<input
type="radio"
checked={isActive || false}
readOnly
className="shrink-0"
/>
{/* Alternating color indicator */}
<div className="flex -space-x-1 shrink-0">
{merged.colors.slice(0, 3).map((color, idx) => (
<div
key={idx}
className="w-3 h-3 rounded-full border-2"
style={{ backgroundColor: color, borderColor: isDark ? '#1f2937' : '#fff' }}
/>
))}
{merged.colors.length > 3 && (
<div className={`w-3 h-3 rounded-full flex items-center justify-center text-[8px] ${
isDark ? 'bg-gray-700 text-gray-400' : 'bg-gray-200 text-gray-500'
}`}>
+{merged.colors.length - 3}
</div>
)}
</div>
<div className="flex-1 min-w-0">
<div className={`flex items-center gap-1 ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>
<span className="font-mono truncate">Merged #{merged.id.slice(-6)}</span>
{!isComplete && (
<span className="text-[9px] text-orange-500 font-sans">(incomplete)</span>
)}
</div>
<div className={`truncate ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
{merged.strategy} • {merged.messages.length} msgs
</div>
</div>
{/* Quick Chat for Merged Trace */}
<button
onClick={(e) => {
e.stopPropagation();
openMergedQuickChat(merged);
}}
disabled={!isComplete}
className={`p-1 rounded shrink-0 ${
isComplete
? isDark ? 'hover:bg-purple-900 text-gray-500 hover:text-purple-400' : 'hover:bg-purple-100 text-gray-400 hover:text-purple-600'
: 'text-gray-500 cursor-not-allowed opacity-50'
}`}
title={isComplete ? "Quick Chat with merged context" : "Trace incomplete"}
>
<MessageCircle size={12} />
</button>
<button
onClick={(e) => {
e.stopPropagation();
deleteMergedTrace(selectedNode.id, merged.id);
}}
className={`p-1 rounded shrink-0 ${
isDark ? 'hover:bg-red-900 text-gray-500 hover:text-red-400' : 'hover:bg-red-50 text-gray-400 hover:text-red-600'
}`}
title="Delete merged trace"
>
<Trash2 size={12} />
</button>
</div>
);
})}
</div>
)}
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">User Prompt</label>
<textarea
value={selectedNode.data.userPrompt}
onChange={(e) => handleChange('userPrompt', e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (selectedNode.data.status !== 'loading' && activeTracesCheck.complete) {
handleRun();
}
}
// Shift+Enter allows normal newline
}}
className="w-full border border-gray-300 rounded-md p-2 text-sm min-h-[100px]"
placeholder="Type your message here... (Enter to run, Shift+Enter for newline)"
/>
</div>
{/* Warning for incomplete upstream traces */}
{!activeTracesCheck.complete && (
<div className={`mb-2 p-2 rounded-md text-xs flex items-center gap-2 ${
isDark ? 'bg-yellow-900/50 text-yellow-300 border border-yellow-700' : 'bg-yellow-50 text-yellow-700 border border-yellow-200'
}`}>
<AlertCircle size={14} className="flex-shrink-0" />
<span className="flex-1">Upstream node is empty. Complete the context chain before running.</span>
<button
onClick={navigateToEmptyNode}
className={`flex-shrink-0 p-1 rounded hover:bg-yellow-600/30 transition-colors`}
title="Go to empty node"
>
<Navigation size={14} />
</button>
</div>
)}
<button
onClick={handleRun}
disabled={selectedNode.data.status === 'loading' || !activeTracesCheck.complete}
className={`w-full py-2 px-4 rounded-md flex items-center justify-center gap-2 transition-colors ${
selectedNode.data.status === 'loading' || !activeTracesCheck.complete
? 'bg-gray-300 text-gray-500 cursor-not-allowed dark:bg-gray-600 dark:text-gray-400'
: 'bg-blue-600 text-white hover:bg-blue-700'
}`}
>
{selectedNode.data.status === 'loading' ? <Loader2 className="animate-spin" size={16} /> : <Play size={16} />}
Run Node
</button>
<div className="mt-6">
<div className="flex items-center justify-between mb-2">
<label className="block text-sm font-medium text-gray-700">Response</label>
<div className="flex gap-1">
{selectedNode.data.response && (
<>
<button
onClick={() => setShowSummaryModal(true)}
disabled={isSummarizing}
className="p-1 hover:bg-gray-200 rounded text-gray-500 hover:text-gray-700 disabled:opacity-50"
title="Summarize"
>
{isSummarizing ? <Loader2 className="animate-spin" size={14} /> : <FileText size={14} />}
</button>
<button
onClick={() => setIsEditing(true)}
className="p-1 hover:bg-gray-200 rounded text-gray-500 hover:text-gray-700"
title="Edit Response"
>
<Edit3 size={14} />
</button>
<button
onClick={() => setIsModalOpen(true)}
className="p-1 hover:bg-gray-200 rounded text-gray-500 hover:text-gray-700"
title="Expand"
>
<Maximize2 size={14} />
</button>
</>
)}
</div>
</div>
{isEditing ? (
<div className="space-y-2">
<textarea
value={editedResponse}
onChange={(e) => setEditedResponse(e.target.value)}
className={`w-full border rounded-md p-2 text-sm min-h-[200px] font-mono focus:ring-2 focus:ring-blue-500 ${
isDark
? 'bg-gray-800 border-gray-600 text-gray-200 placeholder-gray-500'
: 'bg-white border-blue-300 text-gray-900'
}`}
/>
<div className="flex gap-2 justify-end">
<button
onClick={handleCancelEdit}
className={`px-3 py-1 text-sm rounded flex items-center gap-1 ${
isDark ? 'text-gray-400 hover:bg-gray-800' : 'text-gray-600 hover:bg-gray-100'
}`}
>
<X size={14} /> Cancel
</button>
<button
onClick={handleSaveEdit}
className="px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 flex items-center gap-1"
>
<Check size={14} /> Save
</button>
</div>
</div>
) : (
<div className={`p-3 rounded-md border min-h-[150px] text-sm prose prose-sm max-w-none ${
isDark
? 'bg-gray-900 border-gray-700 prose-invert text-gray-200'
: 'bg-gray-50 border-gray-200 text-gray-900'
}`}>
<ReactMarkdown>{selectedNode.data.response || (streamingNodeId === selectedNode.id ? streamBuffer : '')}</ReactMarkdown>
</div>
)}
</div>
</div>
)}
{activeTab === 'settings' && (
<div className="space-y-4">
<div>
<label className={`block text-sm font-medium mb-1 ${isDark ? 'text-gray-300' : 'text-gray-700'}`}>Merge Strategy</label>
<select
value={selectedNode.data.mergeStrategy || 'smart'}
onChange={(e) => handleChange('mergeStrategy', e.target.value)}
className={`w-full border rounded-md p-2 text-sm ${
isDark ? 'bg-gray-700 border-gray-600 text-gray-200' : 'border-gray-300 bg-white text-gray-900'
}`}
>
<option value="smart">Smart (Auto-merge roles)</option>
<option value="raw">Raw (Concatenate)</option>
</select>
<p className={`text-xs mt-1 ${isDark ? 'text-gray-500' : 'text-gray-500'}`}>
Smart merge combines consecutive messages from the same role to avoid API errors.
</p>
</div>
<div>
<label className={`block text-sm font-medium mb-1 ${isDark ? 'text-gray-300' : 'text-gray-700'}`}>
Temperature ({selectedNode.data.temperature})
{[
'gpt-5', 'gpt-5-chat-latest', 'gpt-5-mini', 'gpt-5-nano',
'gpt-5-pro', 'gpt-5.1', 'gpt-5.1-chat-latest', 'o3'
].includes(selectedNode.data.model) && (
<span className="text-xs text-orange-500 ml-2">(Locked for Reasoning Model)</span>
)}
</label>
<input
type="range"
min="0"
max="2"
step="0.1"
value={selectedNode.data.temperature}
onChange={(e) => handleChange('temperature', parseFloat(e.target.value))}
disabled={[
'gpt-5', 'gpt-5-chat-latest', 'gpt-5-mini', 'gpt-5-nano',
'gpt-5-pro', 'gpt-5.1', 'gpt-5.1-chat-latest', 'o3'
].includes(selectedNode.data.model)}
className="w-full disabled:opacity-50 disabled:cursor-not-allowed"
/>
</div>
{/* Reasoning Effort - Only for OpenAI reasoning models (except chat-latest) */}
{[
'gpt-5', 'gpt-5-mini', 'gpt-5-nano',
'gpt-5-pro', 'gpt-5.1', 'o3'
].includes(selectedNode.data.model) && (
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Reasoning Effort
</label>
<select
value={selectedNode.data.reasoningEffort || 'medium'}
onChange={(e) => handleChange('reasoningEffort', e.target.value)}
className="w-full border border-gray-300 rounded-md p-2 text-sm"
>
<option value="low">Low (Faster, less thorough)</option>
<option value="medium">Medium (Balanced)</option>
<option value="high">High (Slower, more thorough)</option>
</select>
<p className="text-xs text-gray-500 mt-1">
Controls how much reasoning the model performs before responding. Higher = more tokens used.
</p>
</div>
)}
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">API Key (Optional)</label>
<input
type="password"
value={selectedNode.data.apiKey || ''}
onChange={(e) => handleChange('apiKey', e.target.value)}
className="w-full border border-gray-300 rounded-md p-2 text-sm"
placeholder="Leave empty to use backend env var"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">System Prompt Override</label>
<textarea
value={selectedNode.data.systemPrompt}
onChange={(e) => handleChange('systemPrompt', e.target.value)}
className="w-full border border-gray-300 rounded-md p-2 text-sm min-h-[100px] font-mono"
placeholder="Global system prompt will be used if empty..."
/>
</div>
{(selectedNode.data.model.startsWith('gemini') ||
selectedNode.data.model.startsWith('gpt-5') ||
['o3', 'o4-mini', 'gpt-4o'].includes(selectedNode.data.model)) && (
<div className="flex items-center gap-2 mt-4">
<input
type="checkbox"
id="web-search"
checked={selectedNode.data.enableGoogleSearch !== false} // Default to true
onChange={(e) => handleChange('enableGoogleSearch', e.target.checked)}
/>
<label htmlFor="web-search" className="text-sm font-medium text-gray-700 select-none cursor-pointer">
Enable Web Search
</label>
</div>
)}
</div>
)}
{activeTab === 'debug' && (
<div className="space-y-4">
{/* Timestamps */}
<div className="bg-gray-50 p-3 rounded border border-gray-200">
<label className="block text-xs font-bold text-gray-500 mb-2 uppercase">Timestamps</label>
<div className="grid grid-cols-2 gap-2 text-xs">
<div>
<span className="text-gray-500">Query Sent:</span>
<div className="font-mono text-gray-700">
{selectedNode.data.querySentAt
? new Date(selectedNode.data.querySentAt).toLocaleString()
: '-'}
</div>
</div>
<div>
<span className="text-gray-500">Response Received:</span>
<div className="font-mono text-gray-700">
{selectedNode.data.responseReceivedAt
? new Date(selectedNode.data.responseReceivedAt).toLocaleString()
: '-'}
</div>
</div>
</div>
{selectedNode.data.querySentAt && selectedNode.data.responseReceivedAt && (
<div className="mt-2 text-xs text-gray-500">
Duration: {((selectedNode.data.responseReceivedAt - selectedNode.data.querySentAt) / 1000).toFixed(2)}s
</div>
)}
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Active Context (Sent to LLM)</label>
<pre className="bg-gray-900 text-gray-100 p-2 rounded text-xs overflow-x-auto max-h-[200px]">
{JSON.stringify(getActiveContext(selectedNode.id), null, 2)}
</pre>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Node Traces (Incoming)</label>
<pre className="bg-gray-900 text-gray-100 p-2 rounded text-xs overflow-x-auto max-h-[200px]">
{JSON.stringify(selectedNode.data.traces, null, 2)}
</pre>
</div>
</div>
)}
</div>
{/* Response Modal */}
{isModalOpen && selectedNode && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => setIsModalOpen(false)}>
<div
className="bg-white rounded-lg shadow-2xl w-[80vw] max-w-4xl max-h-[80vh] flex flex-col"
onClick={(e) => e.stopPropagation()}
>
{/* Modal Header */}
<div className="flex items-center justify-between p-4 border-b border-gray-200">
<h3 className="font-semibold text-lg">{selectedNode.data.label} - Response</h3>
<div className="flex gap-2">
{!isEditing && (
<button
onClick={() => setIsEditing(true)}
className="px-3 py-1 text-sm text-gray-600 hover:bg-gray-100 rounded flex items-center gap-1"
>
<Edit3 size={14} /> Edit
</button>
)}
<button
onClick={() => { setIsModalOpen(false); setIsEditing(false); }}
className="p-1 hover:bg-gray-200 rounded text-gray-500"
>
<X size={18} />
</button>
</div>
</div>
{/* Modal Content */}
<div className="flex-1 overflow-y-auto p-6">
{isEditing ? (
<textarea
value={editedResponse}
onChange={(e) => setEditedResponse(e.target.value)}
className="w-full h-full min-h-[400px] border border-gray-300 rounded-md p-3 text-sm font-mono focus:ring-2 focus:ring-blue-500 resize-y"
/>
) : (
<div className="prose prose-sm max-w-none">
<ReactMarkdown>{selectedNode.data.response}</ReactMarkdown>
</div>
)}
</div>
{/* Modal Footer (only when editing) */}
{isEditing && (
<div className="flex justify-end gap-2 p-4 border-t border-gray-200">
<button
onClick={handleCancelEdit}
className="px-4 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded flex items-center gap-1"
>
<X size={14} /> Cancel
</button>
<button
onClick={() => { handleSaveEdit(); setIsModalOpen(false); }}
className="px-4 py-2 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 flex items-center gap-1"
>
<Check size={14} /> Save Changes
</button>
</div>
)}
</div>
</div>
)}
{/* Summary Model Selection Modal */}
{showSummaryModal && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50" onClick={() => setShowSummaryModal(false)}>
<div
className="bg-white rounded-lg shadow-2xl w-80 p-4"
onClick={(e) => e.stopPropagation()}
>
<h3 className="font-semibold text-lg mb-4">Summarize Response</h3>
<div className="mb-4">
<label className="block text-sm font-medium text-gray-700 mb-2">Select Model</label>
<select
value={summaryModel}
onChange={(e) => setSummaryModel(e.target.value)}
className="w-full border border-gray-300 rounded-md p-2 text-sm"
>
<optgroup label="Fast (Recommended)">
<option value="gpt-5-nano">gpt-5-nano</option>
<option value="gpt-5-mini">gpt-5-mini</option>
<option value="gemini-2.5-flash-lite">gemini-2.5-flash-lite</option>
<option value="gemini-2.5-flash">gemini-2.5-flash</option>
</optgroup>
<optgroup label="Standard">
<option value="gpt-4o">gpt-4o</option>
<option value="gpt-5">gpt-5</option>
</optgroup>
</select>
</div>
<div className="flex justify-end gap-2">
<button
onClick={() => setShowSummaryModal(false)}
className="px-3 py-2 text-sm text-gray-600 hover:bg-gray-100 rounded"
>
Cancel
</button>
<button
onClick={handleSummarize}
className="px-3 py-2 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 flex items-center gap-1"
>
<FileText size={14} /> Summarize
</button>
</div>
</div>
</div>
)}
{/* Merge Traces Modal */}
{showMergeModal && selectedNode && (
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50" onClick={() => setShowMergeModal(false)}>
<div
className={`rounded-xl shadow-2xl w-[500px] max-h-[80vh] flex flex-col ${
isDark ? 'bg-gray-800' : 'bg-white'
}`}
onClick={(e) => e.stopPropagation()}
>
{/* Header */}
<div className={`flex items-center justify-between p-4 border-b ${isDark ? 'border-gray-700' : 'border-gray-200'}`}>
<div className="flex items-center gap-2">
<GitMerge size={20} className={isDark ? 'text-purple-400' : 'text-purple-600'} />
<h3 className={`font-semibold text-lg ${isDark ? 'text-gray-100' : 'text-gray-900'}`}>
Create Merged Trace
</h3>
</div>
<button
onClick={() => setShowMergeModal(false)}
className={`p-1 rounded ${isDark ? 'hover:bg-gray-700' : 'hover:bg-gray-200'}`}
>
<X size={20} className={isDark ? 'text-gray-400' : 'text-gray-500'} />
</button>
</div>
{/* Trace Selection - draggable */}
<div className={`p-4 flex-1 overflow-y-auto ${isDark ? 'bg-gray-900' : 'bg-gray-50'}`}>
<p className={`text-xs mb-3 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
Select traces to merge. Drag to reorder for "Trace Order" strategy.
</p>
<div className="space-y-1">
{mergeOrder
.map(traceId => selectedNode.data.traces?.find((t: Trace) => t.id === traceId))
.filter((trace): trace is Trace => trace !== undefined)
.map((trace) => {
const isSelected = mergeSelectedIds.includes(trace.id);
const isDragging = mergeDraggedId === trace.id;
const traceColors = trace.isMerged && trace.mergedColors && trace.mergedColors.length > 0
? trace.mergedColors
: [trace.color];
return (
<div
key={trace.id}
draggable
onDragStart={(e) => handleMergeDragStart(e, trace.id)}
onDragOver={(e) => handleMergeDragOver(e, trace.id)}
onDragEnd={handleMergeDragEnd}
className={`flex items-center gap-3 p-2 rounded cursor-move transition-all ${
isDragging ? 'opacity-50' : ''
} ${isSelected
? isDark ? 'bg-purple-900/50 border border-purple-600' : 'bg-purple-50 border border-purple-300'
: isDark ? 'bg-gray-800 hover:bg-gray-700' : 'bg-white border border-gray-200 hover:bg-gray-50'
}`}
>
<GripVertical size={16} className={isDark ? 'text-gray-600' : 'text-gray-300'} />
<input
type="checkbox"
checked={isSelected}
onChange={() => toggleMergeSelection(trace.id)}
/>
<div className="flex -space-x-1">
{traceColors.slice(0, 3).map((c, idx) => (
<div
key={idx}
className="w-3 h-3 rounded-full border-2"
style={{ backgroundColor: c, borderColor: isDark ? '#1f2937' : '#fff' }}
/>
))}
{traceColors.length > 3 && (
<div className={`w-3 h-3 rounded-full flex items-center justify-center text-[8px] ${
isDark ? 'bg-gray-700 text-gray-400' : 'bg-gray-200 text-gray-500'
}`}>
+{traceColors.length - 3}
</div>
)}
</div>
<div className="flex-1">
<span className={`font-mono text-sm ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>
#{trace.id.slice(-6)}
</span>
<span className={`ml-2 text-xs ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
{trace.messages.length} msgs
</span>
</div>
</div>
);
})}
</div>
{mergeSelectedIds.length < 2 && (
<p className={`text-xs mt-3 text-center ${isDark ? 'text-orange-400' : 'text-orange-500'}`}>
Select at least 2 traces to merge
</p>
)}
</div>
{/* Settings */}
<div className={`p-4 border-t ${isDark ? 'border-gray-700' : 'border-gray-200'}`}>
<label className={`block text-xs font-bold mb-2 ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
Merge Strategy
</label>
<select
value={mergeStrategy}
onChange={(e) => setMergeStrategy(e.target.value as MergeStrategy)}
className={`w-full border rounded-md p-2 text-sm mb-3 ${
isDark ? 'bg-gray-700 border-gray-600 text-gray-200' : 'border-gray-300'
}`}
>
<option value="query_time">By Query Time</option>
<option value="response_time">By Response Time</option>
<option value="trace_order">By Trace Order (drag to reorder)</option>
<option value="grouped">Grouped (each trace in full)</option>
<option value="interleaved">Interleaved (true timeline)</option>
<option value="summary">Summary (LLM compressed)</option>
</select>
{/* Preview */}
{mergeSelectedIds.length >= 2 && (
<>
<button
onClick={() => setShowMergePreview(!showMergePreview)}
className={`w-full text-xs py-1.5 rounded mb-2 ${
isDark ? 'bg-gray-700 hover:bg-gray-600 text-gray-300' : 'bg-gray-100 hover:bg-gray-200 text-gray-600'
}`}
>
{showMergePreview ? 'Hide Preview' : 'Show Preview'} ({getMergePreview().length} messages)
</button>
{showMergePreview && (
<div className={`max-h-[100px] overflow-y-auto mb-3 p-2 rounded text-xs ${
isDark ? 'bg-gray-700' : 'bg-white border border-gray-200'
}`}>
{getMergePreview().map((msg, idx) => (
<div key={idx} className={`mb-1 ${msg.role === 'user' ? 'text-blue-400' : isDark ? 'text-gray-300' : 'text-gray-600'}`}>
<span className="font-bold">{msg.role}:</span> {msg.content.slice(0, 40)}...
</div>
))}
</div>
)}
</>
)}
<button
onClick={handleCreateMergedTrace}
disabled={mergeSelectedIds.length < 2 || isSummarizingMerge}
className={`w-full py-2.5 rounded-md text-sm font-medium flex items-center justify-center gap-2 ${
mergeSelectedIds.length >= 2
? isDark
? 'bg-purple-600 hover:bg-purple-500 text-white disabled:bg-purple-900'
: 'bg-purple-600 hover:bg-purple-700 text-white disabled:bg-purple-300'
: isDark ? 'bg-gray-700 text-gray-500' : 'bg-gray-200 text-gray-400'
}`}
>
{isSummarizingMerge ? (
<>
<Loader2 className="animate-spin" size={16} />
Summarizing...
</>
) : (
<>
<GitMerge size={16} />
Create Merged Trace
</>
)}
</button>
</div>
</div>
</div>
)}
{/* Quick Chat Modal */}
{quickChatOpen && quickChatTrace && (
<div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50" onClick={() => { onInteract?.(); closeQuickChat(); }}>
<div
className={`rounded-xl shadow-2xl w-[85vw] max-w-4xl h-[85vh] flex flex-col ${
isDark ? 'bg-gray-800' : 'bg-white'
}`}
onClick={(e) => { e.stopPropagation(); onInteract?.(); }}
>
{/* Header */}
<div className={`flex items-center justify-between p-4 border-b ${
isDark ? 'border-gray-700' : 'border-gray-200'
}`}>
<div className="flex items-center gap-3">
<div className="w-3 h-3 rounded-full" style={{ backgroundColor: quickChatTrace.color }}></div>
<h3 className={`font-semibold text-lg ${isDark ? 'text-gray-100' : 'text-gray-900'}`}>
{quickChatNeedsDuplicate ? 'Duplicate & Quick Chat' : 'Quick Chat'}
</h3>
{quickChatNeedsDuplicate && (
<span className={`text-xs px-2 py-0.5 rounded-full ${
isDark ? 'bg-orange-900/50 text-orange-300' : 'bg-orange-100 text-orange-600'
}`}>
Will create new branch
</span>
)}
<span className={`text-xs font-mono ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>#{quickChatTrace.id.slice(-8)}</span>
</div>
<div className="flex items-center gap-3">
{/* Model Selector */}
<select
value={quickChatModel}
onChange={(e) => setQuickChatModel(e.target.value)}
className={`border rounded-md px-3 py-1.5 text-sm ${
isDark ? 'bg-gray-700 border-gray-600 text-gray-200' : 'border-gray-300 text-gray-900'
}`}
>
<optgroup label="Gemini">
<option value="gemini-2.5-flash">gemini-2.5-flash</option>
<option value="gemini-2.5-flash-lite">gemini-2.5-flash-lite</option>
<option value="gemini-3-pro-preview">gemini-3-pro-preview</option>
</optgroup>
<optgroup label="OpenAI (Standard)">
<option value="gpt-4.1">gpt-4.1</option>
<option value="gpt-4o">gpt-4o</option>
</optgroup>
<optgroup label="OpenAI (Reasoning)">
<option value="gpt-5">gpt-5</option>
<option value="gpt-5-chat-latest">gpt-5-chat-latest</option>
<option value="gpt-5-mini">gpt-5-mini</option>
<option value="gpt-5-nano">gpt-5-nano</option>
<option value="gpt-5-pro">gpt-5-pro</option>
<option value="gpt-5.1">gpt-5.1</option>
<option value="gpt-5.1-chat-latest">gpt-5.1-chat-latest</option>
<option value="o3">o3</option>
</optgroup>
</select>
<button onClick={closeQuickChat} className={`p-1 rounded ${isDark ? 'hover:bg-gray-700' : 'hover:bg-gray-200'}`}>
<X size={20} className={isDark ? 'text-gray-400' : 'text-gray-500'} />
</button>
</div>
</div>
{/* Chat Messages */}
<div className={`flex-1 overflow-y-auto p-4 space-y-4 ${isDark ? 'bg-gray-900' : 'bg-gray-50'}`}>
{quickChatMessages.length === 0 ? (
<div className={`text-center py-8 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
<MessageCircle size={48} className="mx-auto mb-2 opacity-50" />
<p>Start a conversation with this trace's context</p>
</div>
) : (
quickChatMessages.map((msg, idx) => (
<div
key={msg.id || idx}
className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
>
<div className="flex items-start gap-2 max-w-[80%]">
{/* Source trace indicator for merged traces */}
{msg.sourceTraceColor && msg.role !== 'user' && (
<div
className="w-2 h-2 rounded-full mt-3 shrink-0"
style={{ backgroundColor: msg.sourceTraceColor }}
title={`From trace: ${msg.sourceTraceId?.slice(-6) || 'unknown'}`}
/>
)}
<div
className={`rounded-lg px-4 py-2 ${
msg.role === 'user'
? 'bg-blue-600 text-white'
: isDark
? 'bg-gray-800 border border-gray-700 text-gray-200 shadow-sm'
: 'bg-white border border-gray-200 shadow-sm'
}`}
style={msg.sourceTraceColor ? { borderLeftColor: msg.sourceTraceColor, borderLeftWidth: '3px' } : undefined}
>
{/* Source trace label for user messages from merged trace */}
{msg.sourceTraceColor && msg.role === 'user' && (
<div
className="text-[10px] opacity-70 mb-1 flex items-center gap-1"
>
<div
className="w-2 h-2 rounded-full"
style={{ backgroundColor: msg.sourceTraceColor }}
/>
<span>from trace #{msg.sourceTraceId?.slice(-4)}</span>
</div>
)}
{msg.role === 'user' ? (
<p className="whitespace-pre-wrap">{msg.content}</p>
) : (
<div className={`prose prose-sm max-w-none ${isDark ? 'prose-invert' : ''}`}>
<ReactMarkdown>{msg.content}</ReactMarkdown>
</div>
)}
</div>
{/* Source trace indicator for user messages (on the right side) */}
{msg.sourceTraceColor && msg.role === 'user' && (
<div
className="w-2 h-2 rounded-full mt-3 shrink-0"
style={{ backgroundColor: msg.sourceTraceColor }}
title={`From trace: ${msg.sourceTraceId?.slice(-6) || 'unknown'}`}
/>
)}
</div>
</div>
))
)}
{quickChatLoading && (
<div className="flex justify-start">
<div className={`rounded-lg px-4 py-3 shadow-sm ${
isDark ? 'bg-gray-800 border border-gray-700' : 'bg-white border border-gray-200'
}`}>
<Loader2 className="animate-spin text-blue-500" size={20} />
</div>
</div>
)}
<div ref={quickChatEndRef} />
</div>
{/* Settings Row */}
<div className={`px-4 py-2 border-t flex items-center gap-4 text-xs ${
isDark ? 'border-gray-700 bg-gray-800' : 'border-gray-100 bg-white'
}`}>
{/* Temperature (hide for reasoning models) */}
{!['gpt-5', 'gpt-5-chat-latest', 'gpt-5-mini', 'gpt-5-nano', 'gpt-5-pro', 'gpt-5.1', 'gpt-5.1-chat-latest', 'o3'].includes(quickChatModel) && (
<div className="flex items-center gap-2">
<span className={isDark ? 'text-gray-400' : 'text-gray-500'}>Temp:</span>
<input
type="range"
min="0"
max="2"
step="0.1"
value={quickChatTemp}
onChange={(e) => setQuickChatTemp(parseFloat(e.target.value))}
className="w-20"
/>
<span className={`w-8 ${isDark ? 'text-gray-300' : 'text-gray-700'}`}>{quickChatTemp}</span>
</div>
)}
{/* Reasoning Effort (only for reasoning models, except chat-latest) */}
{['gpt-5', 'gpt-5-mini', 'gpt-5-nano', 'gpt-5-pro', 'gpt-5.1', 'o3'].includes(quickChatModel) && (
<div className="flex items-center gap-2">
<span className={isDark ? 'text-gray-400' : 'text-gray-500'}>Effort:</span>
<select
value={quickChatEffort}
onChange={(e) => setQuickChatEffort(e.target.value as 'low' | 'medium' | 'high')}
className={`border rounded px-2 py-0.5 text-xs ${
isDark ? 'bg-gray-700 border-gray-600 text-gray-200' : 'border-gray-300'
}`}
>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
</select>
</div>
)}
{/* Web Search */}
{(quickChatModel.startsWith('gemini') || quickChatModel.startsWith('gpt-5') || ['o3', 'gpt-4o'].includes(quickChatModel)) && (
<label className="flex items-center gap-1 cursor-pointer">
<input
type="checkbox"
checked={quickChatWebSearch}
onChange={(e) => setQuickChatWebSearch(e.target.checked)}
className="form-checkbox h-3 w-3"
/>
<span className={isDark ? 'text-gray-400' : 'text-gray-500'}>Web Search</span>
</label>
)}
</div>
{/* Input Area */}
<div className={`p-4 border-t ${isDark ? 'border-gray-700 bg-gray-800' : 'border-gray-200 bg-white'}`}>
<div className="flex gap-2">
<textarea
ref={quickChatInputRef}
value={quickChatInput}
onChange={(e) => setQuickChatInput(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
// Only send if not loading
if (!quickChatLoading) {
handleQuickChatSend();
}
}
}}
placeholder={quickChatLoading
? "Waiting for response... (you can type here)"
: "Type your message... (Enter to send, Shift+Enter for new line)"
}
className={`flex-1 border rounded-lg px-4 py-3 text-sm resize-y min-h-[50px] max-h-[150px] focus:ring-2 focus:ring-blue-500 focus:border-blue-500 ${
isDark ? 'bg-gray-700 border-gray-600 text-gray-200 placeholder-gray-400' : 'border-gray-300'
}`}
autoFocus
/>
<button
onClick={handleQuickChatSend}
disabled={!quickChatInput.trim() || quickChatLoading}
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-blue-300 disabled:cursor-not-allowed flex items-center gap-2"
>
{quickChatLoading ? <Loader2 className="animate-spin" size={18} /> : <Send size={18} />}
</button>
</div>
<p className={`text-[10px] mt-2 ${isDark ? 'text-gray-500' : 'text-gray-400'}`}>
Each message creates a new node on the canvas, automatically connected to this trace.
</p>
</div>
</div>
</div>
)}
</div>
);
};
export default Sidebar;
|