1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
|
const BASE_PATH = (typeof document !== 'undefined') ? document.querySelector('meta[name="base-path"]')?.content ?? '' : '';
const API_BASE = (typeof window !== 'undefined') ? window.location.origin + BASE_PATH : '';
// ── Fetch ─────────────────────────────────────────────────────────────────────
async function fetchTasks(since = null) {
let url = `${API_BASE}/api/tasks`;
if (since) {
url += `?since=${encodeURIComponent(since)}`;
}
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
// Fetches recent executions (last 24h) from /api/executions?since=24h.
// fetchFn defaults to window.fetch; injectable for tests.
async function fetchRecentExecutions(basePath = BASE_PATH, fetchFn = fetch) {
const res = await fetchFn(`${basePath}/api/executions?since=24h`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
// Returns only tasks currently in state RUNNING.
function filterRunningTasks(tasks) {
return tasks.filter(t => t.state === 'RUNNING');
}
// Returns human-readable elapsed time from an ISO timestamp to now.
function formatElapsed(startISO) {
if (startISO == null) return '';
const elapsed = Math.floor((Date.now() - new Date(startISO).getTime()) / 1000);
if (elapsed < 0) return '0s';
const h = Math.floor(elapsed / 3600);
const m = Math.floor((elapsed % 3600) / 60);
const s = elapsed % 60;
if (h > 0) return `${h}h ${m}m`;
if (m > 0) return `${m}m ${s}s`;
return `${s}s`;
}
// Returns human-readable duration between two ISO timestamps.
// If endISO is null, uses now (for in-progress tasks).
// If startISO is null, returns '--'.
function formatDuration(startISO, endISO) {
if (startISO == null) return '--';
const start = new Date(startISO).getTime();
const end = endISO != null ? new Date(endISO).getTime() : Date.now();
const elapsed = Math.max(0, Math.floor((end - start) / 1000));
const h = Math.floor(elapsed / 3600);
const m = Math.floor((elapsed % 3600) / 60);
const s = elapsed % 60;
if (h > 0) return `${h}h ${m}m`;
if (m > 0) return `${m}m ${s}s`;
return `${s}s`;
}
// Returns last max lines from array (for testability).
function extractLogLines(lines, max = 500) {
if (lines.length <= max) return lines;
return lines.slice(lines.length - max);
}
// Returns a new array of executions sorted by started_at descending.
function sortExecutionsDesc(executions) {
return [...executions].sort((a, b) =>
new Date(b.started_at).getTime() - new Date(a.started_at).getTime(),
);
}
// ── Render ────────────────────────────────────────────────────────────────────
function formatDate(iso) {
if (!iso) return '';
return new Date(iso).toLocaleString(undefined, {
month: 'short', day: 'numeric',
hour: '2-digit', minute: '2-digit',
});
}
// Returns formatted string for changestats, e.g. "5 files, +127 -43".
// Returns empty string for null/undefined input.
export function formatChangestats(stats) {
if (stats == null) return '';
return `${stats.files_changed} files, +${stats.lines_added} -${stats.lines_removed}`;
}
// Returns a <span class="changestats-badge"> element for the given stats,
// or null if stats is null/undefined.
// Accepts an optional doc parameter for testability (defaults to document).
export function renderChangestatsBadge(stats, doc = (typeof document !== 'undefined' ? document : null)) {
if (stats == null || doc == null) return null;
const span = doc.createElement('span');
span.className = 'changestats-badge';
span.textContent = formatChangestats(stats);
return span;
}
// Returns a <span class="deployment-badge"> element indicating whether the
// currently-deployed server includes the task's fix commits.
// Returns null if status is null/undefined or doc is null.
// Accepts an optional doc parameter for testability (defaults to document).
export function renderDeploymentBadge(status, doc = (typeof document !== 'undefined' ? document : null)) {
if (status == null || doc == null) return null;
const span = doc.createElement('span');
if (status.includes_fix) {
span.className = 'deployment-badge deployment-badge--deployed';
span.textContent = '✓ Deployed';
} else {
return null;
}
if (status.deployed_commit) {
span.title = `Deployed commit: ${status.deployed_commit.slice(0, 8)}`;
}
return span;
}
function truncateToWordBoundary(text, maxLen = 120) {
if (!text || text.length <= maxLen) return text;
const cut = text.lastIndexOf(' ', maxLen);
return (cut > 0 ? text.slice(0, cut) : text.slice(0, maxLen)) + '…';
}
function createTaskCard(task) {
const card = document.createElement('div');
card.className = 'task-card';
card.dataset.taskId = task.id;
// Header: name + state badge
const header = document.createElement('div');
header.className = 'task-card-header';
const name = document.createElement('span');
name.className = 'task-name';
name.textContent = task.name;
const badge = document.createElement('span');
badge.className = 'state-badge';
badge.dataset.state = task.state;
badge.textContent = task.state.replace(/_/g, ' ');
header.append(name, badge);
card.appendChild(header);
// Meta: priority + created_at
const meta = document.createElement('div');
meta.className = 'task-meta';
if (task.priority) {
const prio = document.createElement('span');
prio.textContent = task.priority;
meta.appendChild(prio);
}
if (task.created_at) {
const when = document.createElement('span');
when.textContent = formatDate(task.created_at);
meta.appendChild(when);
}
if (task.project) {
const proj = document.createElement('span');
proj.className = 'task-project';
proj.textContent = task.project;
meta.appendChild(proj);
}
if (meta.children.length) card.appendChild(meta);
// Description (truncated via CSS)
if (task.description) {
const desc = document.createElement('div');
desc.className = 'task-description';
desc.textContent = task.description;
card.appendChild(desc);
}
// Error message for failed tasks
const FAILED_STATES = new Set(['FAILED', 'BUDGET_EXCEEDED', 'TIMED_OUT']);
if (FAILED_STATES.has(task.state) && task.error_msg) {
const errEl = document.createElement('div');
errEl.className = 'task-error-msg';
errEl.textContent = task.error_msg;
errEl.title = task.error_msg;
card.appendChild(errEl);
}
// Changestats badge for COMPLETED/READY tasks
const CHANGESTATS_STATES = new Set(['COMPLETED', 'READY']);
if (CHANGESTATS_STATES.has(task.state) && task.changestats != null) {
const csBadge = renderChangestatsBadge(task.changestats);
if (csBadge) card.appendChild(csBadge);
}
// Deployment status badge for READY tasks — only when there are tracked commits to check.
if (task.state === 'READY' && task.deployment_status != null &&
task.deployment_status.fix_commits && task.deployment_status.fix_commits.length > 0) {
const depBadge = renderDeploymentBadge(task.deployment_status);
if (depBadge) card.appendChild(depBadge);
}
// Footer: action buttons based on state
// Interrupted states (CANCELLED, FAILED, BUDGET_EXCEEDED) show both Resume and Restart.
// TIMED_OUT shows Resume only. Others show a single action.
const RESUME_STATES = new Set(['TIMED_OUT', 'CANCELLED', 'FAILED', 'BUDGET_EXCEEDED']);
const RESTART_STATES = new Set(['CANCELLED', 'FAILED', 'BUDGET_EXCEEDED']);
if (task.state === 'PENDING' || task.state === 'RUNNING' || task.state === 'READY' || task.state === 'BLOCKED' || RESUME_STATES.has(task.state)) {
const footer = document.createElement('div');
footer.className = 'task-card-footer';
if (task.state === 'PENDING') {
const btn = document.createElement('button');
btn.className = 'btn-run';
btn.textContent = 'Run';
btn.addEventListener('click', (e) => {
e.stopPropagation();
handleRun(task.id, btn, footer);
});
footer.appendChild(btn);
} else if (task.state === 'RUNNING') {
const btn = document.createElement('button');
btn.className = 'btn-cancel';
btn.textContent = 'Cancel';
btn.addEventListener('click', (e) => {
e.stopPropagation();
handleCancel(task.id, btn, footer);
});
footer.appendChild(btn);
} else if (task.state === 'READY') {
renderSubtaskRollup(task, footer);
const acceptBtn = document.createElement('button');
acceptBtn.className = 'btn-accept';
acceptBtn.textContent = 'Accept';
acceptBtn.addEventListener('click', (e) => {
e.stopPropagation();
handleAccept(task.id, acceptBtn, footer);
});
const rejectBtn = document.createElement('button');
rejectBtn.className = 'btn-reject';
rejectBtn.textContent = 'Reject';
rejectBtn.addEventListener('click', (e) => {
e.stopPropagation();
handleReject(task.id, rejectBtn, footer);
});
footer.appendChild(acceptBtn);
footer.appendChild(rejectBtn);
} else if (task.state === 'BLOCKED') {
if (task.question) {
renderQuestionFooter(task, footer);
} else {
renderSubtaskRollup(task, footer);
}
const cancelBtn = document.createElement('button');
cancelBtn.className = 'btn-cancel';
cancelBtn.textContent = 'Cancel';
cancelBtn.addEventListener('click', (e) => {
e.stopPropagation();
handleCancel(task.id, cancelBtn, footer);
});
footer.appendChild(cancelBtn);
} else if (RESUME_STATES.has(task.state)) {
const resumeBtn = document.createElement('button');
resumeBtn.className = 'btn-resume';
resumeBtn.textContent = 'Resume';
resumeBtn.addEventListener('click', (e) => {
e.stopPropagation();
handleResume(task.id, resumeBtn, footer);
});
footer.appendChild(resumeBtn);
if (RESTART_STATES.has(task.state)) {
const restartBtn = document.createElement('button');
restartBtn.className = 'btn-restart';
restartBtn.textContent = 'Restart';
restartBtn.addEventListener('click', (e) => {
e.stopPropagation();
handleRestart(task.id, restartBtn, footer);
});
footer.appendChild(restartBtn);
}
}
card.appendChild(footer);
}
if (!NON_DELETABLE_STATES.has(task.state)) {
const delBtn = document.createElement('button');
delBtn.className = 'btn-delete-task';
delBtn.title = 'Delete task';
delBtn.textContent = '✕';
delBtn.addEventListener('click', (e) => {
e.stopPropagation();
handleDelete(task.id, card);
});
card.appendChild(delBtn);
}
if (EDITABLE_STATES.has(task.state)) {
card.classList.add('task-card--editable');
const editForm = createEditForm(task);
editForm.hidden = true;
card.appendChild(editForm);
card.addEventListener('click', () => { editForm.hidden = !editForm.hidden; });
} else {
card.addEventListener('click', () => openTaskPanel(task.id));
}
return card;
}
/**
* Returns true if the user is currently editing a text field or has a modal open.
* Used to avoid destructive DOM refreshes during polling.
*/
export function isUserEditing(activeEl = (typeof document !== 'undefined' ? document.activeElement : null)) {
if (!activeEl) return false;
const tag = activeEl.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA') return true;
if (activeEl.isContentEditable) return true;
if (activeEl.closest('[role="dialog"]') || activeEl.closest('dialog')) return true;
// Also block re-renders when any modal/panel is open, even without focus.
if (typeof document !== 'undefined') {
if (document.querySelector('dialog[open]')) return true;
if (document.getElementById('task-panel')?.classList.contains('open')) return true;
}
return false;
}
/**
* Partitions tasks into 'running' and 'ready' arrays for the Active tab view.
* Both arrays are sorted by created_at ascending (oldest first).
*/
export function partitionActivePaneTasks(tasks) {
const running = tasks
.filter(t => t.state === 'RUNNING')
.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
const ready = tasks
.filter(t => t.state === 'READY')
.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
return { running, ready };
}
// ── Sort ──────────────────────────────────────────────────────────────────────
function sortTasksByDate(tasks, descend = false) {
return [...tasks].sort((a, b) => {
if (!a.created_at && !b.created_at) return 0;
if (!a.created_at) return 1;
if (!b.created_at) return -1;
const diff = new Date(a.created_at) - new Date(b.created_at);
return descend ? -diff : diff;
});
}
// ── Filter ────────────────────────────────────────────────────────────────────
const HIDE_STATES = new Set(['COMPLETED', 'FAILED']);
const ACTIVE_STATES = new Set(['PENDING', 'QUEUED', 'RUNNING', 'READY']);
const INTERRUPTED_STATES = new Set(['CANCELLED', 'FAILED', 'BUDGET_EXCEEDED', 'BLOCKED']);
const DONE_STATES = new Set(['COMPLETED', 'TIMED_OUT']);
// filterActiveTasks uses its own set (excludes PENDING — tasks "in-flight" only)
const _PANEL_ACTIVE_STATES = new Set(['RUNNING', 'READY', 'QUEUED', 'BLOCKED']);
export function filterTasks(tasks, hideCompletedFailed = false) {
if (!hideCompletedFailed) return tasks;
return tasks.filter(t => !HIDE_STATES.has(t.state));
}
export function filterActiveTasks(tasks) {
return tasks.filter(t => _PANEL_ACTIVE_STATES.has(t.state));
}
// The New Task button is always visible regardless of active tab.
export function newTaskButtonShouldShowOnTab(_tab) { return true; }
export function filterTasksByTab(tasks, tab) {
if (tab === 'active') return tasks.filter(t => ACTIVE_STATES.has(t.state));
if (tab === 'interrupted') return tasks.filter(t => INTERRUPTED_STATES.has(t.state));
if (tab === 'done') {
const now = new Date();
const twentyFourHoursAgo = new Date(now.getTime() - (24 * 60 * 60 * 1000));
return tasks.filter(t => {
if (!DONE_STATES.has(t.state)) return false;
if (!t.created_at) return true; // keep if no date
return new Date(t.created_at) > twentyFourHoursAgo;
});
}
return tasks;
}
// Returns tasks with state QUEUED or PENDING.
export function filterQueueTasks(tasks) {
return tasks.filter(t => t.state === 'QUEUED' || t.state === 'PENDING');
}
// Returns tasks with state READY.
export function filterReadyTasks(tasks) {
return tasks.filter(t => t.state === 'READY');
}
// Returns COMPLETED, TIMED_OUT, BUDGET_EXCEEDED tasks from last 24h.
// Pass since24h=false to disable the time filter.
export function filterAllDoneTasks(tasks, since24h = true) {
const DONE_TAB_STATES = new Set(['COMPLETED', 'TIMED_OUT', 'BUDGET_EXCEEDED']);
return tasks.filter(t => {
if (!DONE_TAB_STATES.has(t.state)) return false;
if (!since24h) return true;
if (!t.created_at) return true; // defensive: keep if no date
const twentyFourHoursAgo = new Date(Date.now() - 24 * 60 * 60 * 1000);
return new Date(t.created_at) > twentyFourHoursAgo;
});
}
export function getTaskFilterTab() {
return localStorage.getItem('taskFilterTab') ?? 'active';
}
export function setTaskFilterTab(tab) {
localStorage.setItem('taskFilterTab', tab);
}
export function getActiveMainTab() {
return localStorage.getItem('activeMainTab') ?? 'queue';
}
export function setActiveMainTab(tab) {
localStorage.setItem('activeMainTab', tab);
}
// ── Tab badge counts ───────────────────────────────────────────────────────────
/**
* Computes badge counts for the 'interrupted', 'ready', and 'running' tabs.
* Returns { interrupted: N, ready: N, running: N }.
*/
export function computeTabBadgeCounts(tasks) {
let interrupted = 0;
let ready = 0;
let running = 0;
let all = 0;
const now = Date.now();
const twentyFourHoursAgo = now - 24 * 60 * 60 * 1000;
for (const t of tasks) {
if (INTERRUPTED_STATES.has(t.state)) interrupted++;
if (t.state === 'READY') ready++;
if (t.state === 'RUNNING') running++;
if (DONE_STATES.has(t.state)) {
if (!t.created_at || new Date(t.created_at).getTime() > twentyFourHoursAgo) {
all++;
}
}
}
return { interrupted, ready, running, all };
}
/**
* Updates the badge count spans inside the tab buttons for
* 'interrupted', 'ready', 'running', and 'all'.
* Badge is hidden (display:none) when count is zero.
*/
export function updateTabBadges(tasks, doc = (typeof document !== 'undefined' ? document : null)) {
if (!doc) return;
const counts = computeTabBadgeCounts(tasks);
for (const [tab, count] of Object.entries(counts)) {
const btn = doc.querySelector(`.tab[data-tab="${tab}"]`);
if (!btn) continue;
let badge = btn.querySelector('.tab-count-badge');
if (!badge) {
badge = doc.createElement('span');
badge.className = 'tab-count-badge';
btn.appendChild(badge);
}
badge.textContent = String(count);
badge.hidden = count === 0;
}
}
// ── Stats computations ─────────────────────────────────────────────────────────
/**
* Computes task state distribution from a task array.
* Returns { byState: { [state]: count } } — only states with tasks are included.
*/
export function computeTaskStats(tasks) {
const byState = {};
for (const t of tasks) {
byState[t.state] = (byState[t.state] || 0) + 1;
}
return { byState };
}
/**
* Computes execution health metrics from a RecentExecution array.
* Returns:
* { total, successRate, totalCostUSD, avgDurationMs, byOutcome }
* where successRate is a fraction (0–1), avgDurationMs is null if no durations.
*/
export function computeExecutionStats(executions) {
if (executions.length === 0) {
return { total: 0, successRate: 0, totalCostUSD: 0, avgDurationMs: null, byOutcome: {} };
}
let completed = 0;
let totalCost = 0;
let durationSum = 0;
let durationCount = 0;
const byOutcome = {};
for (const e of executions) {
const outcome = e.state || 'unknown';
byOutcome[outcome] = (byOutcome[outcome] || 0) + 1;
if (outcome === 'completed') completed++;
totalCost += e.cost_usd || 0;
if (e.duration_ms != null) {
durationSum += e.duration_ms;
durationCount++;
}
}
return {
total: executions.length,
successRate: executions.length > 0 ? completed / executions.length : 0,
totalCostUSD: totalCost,
avgDurationMs: durationCount > 0 ? Math.round(durationSum / durationCount) : null,
byOutcome,
};
}
// ── Stories ───────────────────────────────────────────────────────────────────
const STORY_STATUS_LABELS = {
PENDING: 'Pending',
IN_PROGRESS: 'In Progress',
SHIPPABLE: 'Shippable',
DEPLOYED: 'Deployed',
VALIDATING: 'Validating',
REVIEW_READY: 'Review Ready',
NEEDS_FIX: 'Needs Fix',
};
export function storyStatusLabel(status) {
return STORY_STATUS_LABELS[status] || status;
}
export function renderStoryCard(story, doc = document) {
const card = doc.createElement('div');
card.className = 'story-card';
card.dataset.storyId = story.id;
const header = doc.createElement('div');
header.className = 'story-card-header';
const name = doc.createElement('span');
name.className = 'story-name';
name.textContent = story.name;
header.appendChild(name);
const badge = doc.createElement('span');
badge.className = 'story-status-badge';
badge.dataset.status = story.status;
badge.textContent = storyStatusLabel(story.status);
header.appendChild(badge);
card.appendChild(header);
const meta = doc.createElement('div');
meta.className = 'story-meta';
const project = doc.createElement('span');
project.className = 'story-project';
project.textContent = story.project_id || '—';
meta.appendChild(project);
if (story.branch_name) {
const branch = doc.createElement('span');
branch.className = 'story-branch';
branch.textContent = story.branch_name;
meta.appendChild(branch);
}
card.appendChild(meta);
return card;
}
export function updateFilterTabs() {
const current = getTaskFilterTab();
document.querySelectorAll('.filter-tab[data-filter]').forEach(el => {
el.classList.toggle('active', el.dataset.filter === current);
});
}
function getHideCompletedFailed() {
const stored = localStorage.getItem('hideCompletedFailed');
return stored === null ? true : stored === 'true';
}
function setHideCompletedFailed(val) {
localStorage.setItem('hideCompletedFailed', String(val));
}
function updateToggleButton() {
const btn = document.getElementById('btn-toggle-completed');
if (!btn) return;
btn.textContent = getHideCompletedFailed()
? 'Show completed/failed'
: 'Hide completed/failed';
}
// Shared helper: renders an array of tasks as cards into a container element.
// Now updated to be non-destructive by reusing/updating existing task-card elements.
function renderTasksIntoContainer(tasks, container, emptyMsg) {
if (!tasks || tasks.length === 0) {
container.innerHTML = `<div class="task-empty">${emptyMsg}</div>`;
return;
}
// Remove empty message if it exists
const empty = container.querySelector('.task-empty');
if (empty) empty.remove();
const existingCards = new Map();
container.querySelectorAll('.task-card').forEach(card => {
existingCards.set(card.dataset.taskId, card);
});
const taskIds = new Set(tasks.map(t => t.id));
// Remove cards for tasks no longer in this list
for (const [id, card] of existingCards.entries()) {
if (!taskIds.has(id)) {
card.remove();
existingCards.delete(id);
}
}
// Create or update cards and maintain order
tasks.forEach((task, index) => {
let card = existingCards.get(task.id);
const newCard = createTaskCard(task);
if (card) {
// If the content is exactly the same, we could skip replacing,
// but createTaskCard is fast and ensures we have the latest state.
// We replace the card in-place to preserve its position if possible.
if (card.innerHTML !== newCard.innerHTML) {
// Special case: if user is interacting with THIS card, we might want to skip or merge.
// For now, createTaskCard ensures we don't disrupt if NOT editing.
container.replaceChild(newCard, card);
}
} else {
// Append new card
container.appendChild(newCard);
}
});
// Re-sort cards in DOM to match task list order if they were out of sync
const currentCards = Array.from(container.querySelectorAll('.task-card'));
tasks.forEach((task, index) => {
const card = container.querySelector(`[data-task-id="${task.id}"]`);
if (container.children[index] !== card) {
container.insertBefore(card, container.children[index]);
}
});
}
function renderQueuePanel(tasks) {
const container = document.querySelector('[data-panel="queue"] .panel-task-list');
if (!container) return;
const visible = sortTasksByDate(filterQueueTasks(tasks));
renderTasksIntoContainer(visible, container, 'No tasks queued.');
}
function renderInterruptedPanel(tasks) {
const container = document.querySelector('[data-panel="interrupted"] .panel-task-list');
if (!container) return;
const visible = sortTasksByDate(tasks.filter(t => INTERRUPTED_STATES.has(t.state)), true);
renderTasksIntoContainer(visible, container, 'No interrupted tasks.');
}
function renderReadyPanel(tasks) {
const container = document.querySelector('[data-panel="ready"] .panel-task-list');
if (!container) return;
const visible = sortTasksByDate(filterReadyTasks(tasks));
renderTasksIntoContainer(visible, container, 'No tasks awaiting review.');
}
function renderAllPanel(tasks) {
const container = document.querySelector('[data-panel="all"] .all-history');
if (!container) return;
const visible = sortTasksByDate(filterAllDoneTasks(tasks), true);
renderTasksIntoContainer(visible, container, 'No completed tasks in the last 24h.');
}
// ── Run action ────────────────────────────────────────────────────────────────
async function runTask(taskId, agent) {
const url = agent && agent !== 'auto'
? `${API_BASE}/api/tasks/${taskId}/run?agent=${agent}`
: `${API_BASE}/api/tasks/${taskId}/run`;
const res = await fetch(url, { method: 'POST' });
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try { const body = await res.json(); msg = body.error || body.message || msg; } catch {}
throw new Error(msg);
}
return res.json();
}
async function handleRun(taskId, btn, footer) {
const agentSelector = document.getElementById('select-agent');
const agent = agentSelector ? agentSelector.value : 'auto';
btn.disabled = true;
btn.textContent = 'Queuing…';
// Remove any previous error
const prev = footer.querySelector('.task-error');
if (prev) prev.remove();
try {
await runTask(taskId, agent);
// Refresh active panel so state flips to QUEUED
await poll();
} catch (err) {
btn.disabled = false;
btn.textContent = 'Run';
const errEl = document.createElement('span');
errEl.className = 'task-error';
errEl.textContent = `Failed to queue: ${err.message}`;
footer.appendChild(errEl);
}
}
// ── Cancel / Restart actions ──────────────────────────────────────────────────
async function cancelTask(taskId) {
const res = await fetch(`${API_BASE}/api/tasks/${taskId}/cancel`, { method: 'POST' });
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try { const body = await res.json(); msg = body.error || body.message || msg; } catch {}
throw new Error(msg);
}
return res.json();
}
async function restartTask(taskId) {
const res = await fetch(`${API_BASE}/api/tasks/${taskId}/run`, { method: 'POST' });
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try { const body = await res.json(); msg = body.error || body.message || msg; } catch {}
throw new Error(msg);
}
return res.json();
}
async function resumeTask(taskId) {
const res = await fetch(`${API_BASE}/api/tasks/${taskId}/resume`, { method: 'POST' });
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try { const body = await res.json(); msg = body.error || body.message || msg; } catch {}
throw new Error(msg);
}
return res.json();
}
const NON_DELETABLE_STATES = new Set(['RUNNING', 'QUEUED']);
const EDITABLE_STATES = new Set(['PENDING', 'FAILED', 'CANCELLED', 'TIMED_OUT', 'BUDGET_EXCEEDED']);
// Convert Duration JSON {"Duration": <ns>} to a human string for a text input (e.g. "15m").
function formatDurationForInput(timeout) {
const ns = timeout && timeout.Duration;
if (!ns) return '';
const secs = Math.round(ns / 1e9);
if (secs < 60) return `${secs}s`;
const mins = Math.floor(secs / 60);
const remSecs = secs % 60;
if (mins < 60) return remSecs > 0 ? `${mins}m${remSecs}s` : `${mins}m`;
const hrs = Math.floor(mins / 60);
const remMins = mins % 60;
return remMins > 0 ? `${hrs}h${remMins}m` : `${hrs}h`;
}
async function deleteTask(taskId) {
const res = await fetch(`${API_BASE}/api/tasks/${taskId}`, { method: 'DELETE' });
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try { const body = await res.json(); msg = body.error || body.message || msg; } catch {}
throw new Error(msg);
}
}
async function handleDelete(taskId, card) {
if (!confirm('Delete this task? This cannot be undone.')) return;
try {
await deleteTask(taskId);
card.remove();
} catch (err) {
alert(`Failed to delete: ${err.message}`);
}
}
// ── Inline task editor ────────────────────────────────────────────────────────
async function updateTask(taskId, body) {
const res = await fetch(`${API_BASE}/api/tasks/${taskId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try { const b = await res.json(); msg = b.error || b.message || msg; } catch {}
throw new Error(msg);
}
return res.json();
}
function createEditForm(task) {
const a = task.agent || {};
const form = document.createElement('div');
form.className = 'task-inline-edit';
// Prevent card-level click from toggling this form while user interacts inside it.
form.addEventListener('click', (e) => e.stopPropagation());
function makeField(labelText, tag, attrs) {
const label = document.createElement('label');
label.textContent = labelText;
const el = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (k === 'value') el.value = v;
else el.setAttribute(k, v);
}
label.appendChild(el);
return label;
}
form.appendChild(makeField('Name', 'input', { type: 'text', name: 'name', value: task.name || '' }));
form.appendChild(makeField('Description', 'textarea', { name: 'description', rows: '2', value: task.description || '' }));
form.appendChild(makeField('Instructions', 'textarea', { name: 'instructions', rows: '4', value: a.instructions || '' }));
form.appendChild(makeField('Project Directory', 'input', { type: 'text', name: 'project_dir', value: a.project_dir || a.working_dir || '', placeholder: '/path/to/repo' }));
form.appendChild(makeField('Max Budget (USD)', 'input', { type: 'number', name: 'max_budget_usd', step: '0.01', value: a.max_budget_usd != null ? String(a.max_budget_usd) : '1.00' }));
form.appendChild(makeField('Timeout', 'input', { type: 'text', name: 'timeout', value: formatDurationForInput(task.timeout) || '15m', placeholder: '15m' }));
const prioLabel = document.createElement('label');
prioLabel.textContent = 'Priority';
const prioSel = document.createElement('select');
prioSel.name = 'priority';
for (const val of ['high', 'normal', 'low']) {
const opt = document.createElement('option');
opt.value = val;
opt.textContent = val.charAt(0).toUpperCase() + val.slice(1);
if (val === (task.priority || 'normal')) opt.selected = true;
prioSel.appendChild(opt);
}
prioLabel.appendChild(prioSel);
form.appendChild(prioLabel);
const errEl = document.createElement('div');
errEl.className = 'inline-edit-error';
errEl.hidden = true;
form.appendChild(errEl);
const actions = document.createElement('div');
actions.className = 'inline-edit-actions';
const cancelBtn = document.createElement('button');
cancelBtn.type = 'button';
cancelBtn.textContent = 'Cancel';
cancelBtn.addEventListener('click', () => { form.hidden = true; });
const saveBtn = document.createElement('button');
saveBtn.type = 'button';
saveBtn.className = 'btn-primary btn-sm';
saveBtn.textContent = 'Save';
saveBtn.addEventListener('click', () => handleEditSave(task.id, form, saveBtn));
actions.append(cancelBtn, saveBtn);
form.appendChild(actions);
return form;
}
async function handleEditSave(taskId, form, saveBtn) {
const get = name => form.querySelector(`[name="${name}"]`)?.value ?? '';
const body = {
name: get('name'),
description: get('description'),
agent: {
instructions: get('instructions'),
project_dir: get('project_dir'),
max_budget_usd: parseFloat(get('max_budget_usd')),
},
timeout: get('timeout'),
priority: get('priority'),
};
const errEl = form.querySelector('.inline-edit-error');
errEl.hidden = true;
saveBtn.disabled = true;
saveBtn.textContent = 'Saving…';
try {
await updateTask(taskId, body);
form.hidden = true;
// Brief success flash on the card
const card = form.closest('.task-card');
const flash = document.createElement('div');
flash.className = 'inline-edit-success';
flash.textContent = 'Saved';
card.appendChild(flash);
setTimeout(() => flash.remove(), 2000);
await poll();
} catch (err) {
errEl.textContent = `Failed to save: ${err.message}`;
errEl.hidden = false;
} finally {
saveBtn.disabled = false;
saveBtn.textContent = 'Save';
}
}
function renderQuestionFooter(task, footer) {
// Prevent any tap inside the question footer from opening the detail panel.
footer.addEventListener('click', (e) => e.stopPropagation());
let question = { text: 'Waiting for your input.', options: [] };
if (task.question) {
try { question = JSON.parse(task.question); } catch {}
}
const questionEl = document.createElement('p');
questionEl.className = 'task-question-text';
questionEl.textContent = question.text;
footer.appendChild(questionEl);
if (question.options && question.options.length > 0) {
question.options.forEach(opt => {
const btn = document.createElement('button');
btn.className = 'btn-answer';
btn.textContent = opt;
btn.addEventListener('click', (e) => {
e.stopPropagation();
handleAnswer(task.id, opt, footer);
});
footer.appendChild(btn);
});
} else {
const row = document.createElement('div');
row.className = 'task-answer-row';
const input = document.createElement('input');
input.type = 'text';
input.className = 'task-answer-input';
input.placeholder = 'Your answer…';
const btn = document.createElement('button');
btn.className = 'btn-answer';
btn.textContent = 'Submit';
btn.addEventListener('click', (e) => {
e.stopPropagation();
if (input.value.trim()) handleAnswer(task.id, input.value.trim(), footer);
});
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && input.value.trim()) {
e.stopPropagation();
handleAnswer(task.id, input.value.trim(), footer);
}
});
row.append(input, btn);
footer.appendChild(row);
}
}
const STATE_EMOJI = {
PENDING: '⏳', QUEUED: '🕐', RUNNING: '⚡', COMPLETED: '✅',
FAILED: '❌', CANCELLED: '🚫', TIMED_OUT: '⏱', BUDGET_EXCEEDED: '💸',
READY: '👀', BLOCKED: '⏸',
};
async function renderSubtaskRollup(task, footer) {
footer.addEventListener('click', (e) => e.stopPropagation());
const container = document.createElement('div');
container.className = 'subtask-rollup';
footer.prepend(container);
try {
const res = await fetch(`${API_BASE}/api/tasks/${task.id}/subtasks`);
const subtasks = await res.json();
if (!subtasks || subtasks.length === 0) {
const blurb = task.elaboration_input || task.description || task.name;
container.textContent = blurb ? truncateToWordBoundary(blurb) : 'Waiting for subtasks…';
return;
}
const ul = document.createElement('ul');
ul.className = 'subtask-list';
for (const st of subtasks) {
const li = document.createElement('li');
li.className = `subtask-item subtask-${st.state.toLowerCase()}`;
li.textContent = `${STATE_EMOJI[st.state] || '•'} ${st.name}`;
ul.appendChild(li);
}
container.appendChild(ul);
} catch {
container.textContent = 'Could not load subtasks.';
}
}
async function handleAnswer(taskId, answer, footer) {
const btns = footer.querySelectorAll('button, input');
btns.forEach(el => { el.disabled = true; });
const prev = footer.querySelector('.task-error');
if (prev) prev.remove();
try {
const res = await fetch(`${API_BASE}/api/tasks/${taskId}/answer`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ answer }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error || `HTTP ${res.status}`);
}
await poll();
} catch (err) {
btns.forEach(el => { el.disabled = false; });
const errEl = document.createElement('span');
errEl.className = 'task-error';
errEl.textContent = `Failed: ${err.message}`;
footer.appendChild(errEl);
}
}
async function handleCancel(taskId, btn, footer) {
btn.disabled = true;
btn.textContent = 'Cancelling…';
const prev = footer.querySelector('.task-error');
if (prev) prev.remove();
try {
await cancelTask(taskId);
await poll();
} catch (err) {
btn.disabled = false;
btn.textContent = 'Cancel';
const errEl = document.createElement('span');
errEl.className = 'task-error';
errEl.textContent = `Failed: ${err.message}`;
footer.appendChild(errEl);
}
}
async function handleRestart(taskId, btn, footer) {
btn.disabled = true;
btn.textContent = 'Restarting…';
const prev = footer.querySelector('.task-error');
if (prev) prev.remove();
try {
await restartTask(taskId);
await poll();
} catch (err) {
btn.disabled = false;
btn.textContent = 'Restart';
const errEl = document.createElement('span');
errEl.className = 'task-error';
errEl.textContent = `Failed: ${err.message}`;
footer.appendChild(errEl);
}
}
async function handleResume(taskId, btn, footer) {
btn.disabled = true;
btn.textContent = 'Resuming…';
const prev = footer.querySelector('.task-error');
if (prev) prev.remove();
try {
await resumeTask(taskId);
await poll();
} catch (err) {
btn.disabled = false;
btn.textContent = 'Resume';
const errEl = document.createElement('span');
errEl.className = 'task-error';
errEl.textContent = `Failed: ${err.message}`;
footer.appendChild(errEl);
}
}
// ── Accept / Reject actions ────────────────────────────────────────────────────
async function acceptTask(taskId) {
const res = await fetch(`${API_BASE}/api/tasks/${taskId}/accept`, { method: 'POST' });
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try { const body = await res.json(); msg = body.error || msg; } catch {}
throw new Error(msg);
}
return res.json();
}
async function rejectTask(taskId, comment) {
const res = await fetch(`${API_BASE}/api/tasks/${taskId}/reject`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ comment: comment || '' }),
});
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try { const body = await res.json(); msg = body.error || msg; } catch {}
throw new Error(msg);
}
return res.json();
}
async function handleAccept(taskId, btn, footer) {
btn.disabled = true;
btn.textContent = 'Accepting…';
const prev = footer.querySelector('.task-error');
if (prev) prev.remove();
try {
await acceptTask(taskId);
await poll();
} catch (err) {
btn.disabled = false;
btn.textContent = 'Accept';
const errEl = document.createElement('span');
errEl.className = 'task-error';
errEl.textContent = `Failed: ${err.message}`;
footer.appendChild(errEl);
}
}
async function handleReject(taskId, btn, footer) {
const comment = prompt('Reason for rejection (optional):', '');
if (comment === null) return; // User cancelled prompt
btn.disabled = true;
btn.textContent = 'Rejecting…';
const prev = footer.querySelector('.task-error');
if (prev) prev.remove();
try {
await rejectTask(taskId, comment);
await poll();
} catch (err) {
btn.disabled = false;
btn.textContent = 'Reject';
const errEl = document.createElement('span');
errEl.className = 'task-error';
errEl.textContent = `Failed: ${err.message}`;
footer.appendChild(errEl);
}
}
// ── Start-next-task ─────────────────────────────────────────────────────────────
async function startNextTask(agent) {
const url = agent && agent !== 'auto'
? `${API_BASE}/api/scripts/start-next-task?agent=${agent}`
: `${API_BASE}/api/scripts/start-next-task`;
const res = await fetch(url, { method: 'POST' });
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try { const body = await res.json(); msg = body.error || msg; } catch {}
throw new Error(msg);
}
return res.json();
}
async function handleStartNextTask(btn) {
const agentSelector = document.getElementById('select-agent');
const agent = agentSelector ? agentSelector.value : 'auto';
btn.disabled = true;
btn.textContent = 'Starting…';
try {
const result = await startNextTask(agent);
const output = (result.output || '').trim();
btn.textContent = output || 'No task to start';
setTimeout(() => { btn.textContent = 'Start Next'; btn.disabled = false; }, 3000);
if (output && output !== 'No task to start.') await poll();
} catch (err) {
btn.textContent = `Error: ${err.message}`;
setTimeout(() => { btn.textContent = 'Start Next'; btn.disabled = false; }, 3000);
}
}
// ── Polling ───────────────────────────────────────────────────────────────────
let taskCache = new Map();
let lastServerUpdate = null;
let pollTimeout = null;
let lastUserInteraction = Date.now();
let lastHistoryFetch = 0;
function getActiveTab() {
const active = document.querySelector('.tab.active');
return active ? active.dataset.tab : 'queue';
}
function getRefreshInterval() {
const stored = localStorage.getItem('refreshInterval');
return stored ? parseInt(stored, 10) : 10_000;
}
async function fetchHealth() {
const res = await fetch(`${API_BASE}/api/health`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
function renderActiveTab(allTasks) {
const activeTab = getActiveTab();
switch (activeTab) {
case 'queue':
renderQueuePanel(allTasks);
break;
case 'interrupted':
renderInterruptedPanel(allTasks);
break;
case 'ready':
renderReadyPanel(allTasks);
break;
case 'running':
renderRunningView(allTasks);
if (Date.now() - lastHistoryFetch > 60_000) {
lastHistoryFetch = Date.now();
fetchRecentExecutions(BASE_PATH, fetch)
.then(execs => renderRunningHistory(execs))
.catch(() => {
const histEl = document.querySelector('.running-history');
if (histEl) histEl.innerHTML = '<p class="task-meta">Could not load execution history.</p>';
});
}
break;
case 'all':
renderAllPanel(allTasks);
break;
case 'stats':
Promise.all([
fetchRecentExecutions(BASE_PATH, fetch),
fetch(`${BASE_PATH}/api/agents/status?since=${encodeURIComponent(new Date(Date.now() - 24*60*60*1000).toISOString())}`).then(r => r.ok ? r.json() : { agents: [], events: [] }),
fetch(`${BASE_PATH}/api/stats?window=7d`).then(r => r.ok ? r.json() : { throughput: [], billing: [], failures: [] }),
])
.then(([execs, agentData, dashStats]) => renderStatsPanel(allTasks, execs, agentData, dashStats))
.catch(() => {});
break;
case 'stories':
renderStoriesPanel();
break;
case 'drops':
renderDropsPanel();
break;
case 'settings':
renderSettingsPanel();
break;
}
}
async function poll() {
try {
const health = await fetchHealth();
const serverUpdate = health.last_updated;
// If server says nothing changed, skip fetching but still render (e.g. tab was just switched).
if (lastServerUpdate && serverUpdate <= lastServerUpdate && taskCache.size > 0) {
renderActiveTab(Array.from(taskCache.values()));
return;
}
const tasks = await fetchTasks(lastServerUpdate);
lastServerUpdate = serverUpdate;
// Update cache with new/changed tasks
for (const t of tasks) {
taskCache.set(t.id, t);
}
if (isUserEditing()) return;
const allTasks = Array.from(taskCache.values());
updateTabBadges(allTasks);
renderActiveTab(allTasks);
} catch (err) {
console.error('Polling failed:', err);
const panel = document.querySelector('[data-panel="queue"] .panel-task-list');
if (panel && taskCache.size === 0) {
panel.innerHTML = '<div class="task-empty">Could not reach server.</div>';
}
}
}
function startPolling() {
if (pollTimeout) clearTimeout(pollTimeout);
const runPoll = async () => {
const interval = getRefreshInterval();
if (interval > 0) {
const now = Date.now();
const timeSinceInteraction = now - lastUserInteraction;
// If user is active, we might want to delay polling slightly,
// but for now we just follow the interval if not editing.
if (!isUserEditing()) {
await poll();
}
}
pollTimeout = setTimeout(runPoll, getRefreshInterval() || 10_000);
};
runPoll();
}
// Reset timer on interaction
if (typeof window !== 'undefined') {
['mousedown', 'keydown', 'touchstart', 'mousemove'].forEach(evt => {
window.addEventListener(evt, () => {
lastUserInteraction = Date.now();
}, { passive: true });
});
}
function renderSettingsPanel() {
const panel = document.querySelector('[data-panel="settings"]');
if (!panel) return;
panel.innerHTML = '';
const section = document.createElement('div');
section.className = 'stats-section';
section.style.padding = '1rem';
const heading = document.createElement('h2');
heading.textContent = 'User Settings';
section.appendChild(heading);
const refreshLabel = document.createElement('label');
refreshLabel.style.display = 'block';
refreshLabel.style.marginBottom = '0.5rem';
refreshLabel.textContent = 'Auto-Refresh Interval';
const refreshSelect = document.createElement('select');
refreshSelect.className = 'agent-selector';
refreshSelect.style.width = '100%';
const options = [
{ label: '5 seconds', value: '5000' },
{ label: '10 seconds (default)', value: '10000' },
{ label: '30 seconds', value: '30000' },
{ label: '1 minute', value: '60000' },
{ label: 'Manual only', value: '0' },
];
const current = String(getRefreshInterval());
options.forEach(opt => {
const o = document.createElement('option');
o.value = opt.value;
o.textContent = opt.label;
if (opt.value === current) o.selected = true;
refreshSelect.appendChild(o);
});
refreshSelect.addEventListener('change', () => {
localStorage.setItem('refreshInterval', refreshSelect.value);
startPolling(); // restart with new interval
});
refreshLabel.appendChild(refreshSelect);
section.appendChild(refreshLabel);
panel.appendChild(section);
}
// ── WebSocket (real-time events) ──────────────────────────────────────────────
let ws = null;
let activeLogSource = null;
function connectWebSocket() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const url = `${protocol}//${window.location.host}${BASE_PATH}/api/ws`;
ws = new WebSocket(url);
ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
handleWsEvent(data);
} catch { /* ignore parse errors */ }
};
ws.onclose = () => {
// Reconnect after 3 seconds.
setTimeout(connectWebSocket, 3000);
};
ws.onerror = () => {
ws.close();
};
}
function handleWsEvent(data) {
switch (data.type) {
case 'task_started':
case 'task_completed':
// Force a poll immediately regardless of interval
poll();
break;
case 'task_question':
showQuestionBanner(data);
break;
}
}
// ── Question UI ───────────────────────────────────────────────────────────────
function showQuestionBanner(data) {
const taskId = data.task_id;
const questionId = data.question_id;
const questionData = data.data || {};
const questions = questionData.questions || [];
// Find the task card for this task.
const card = document.querySelector(`.task-card[data-task-id="${taskId}"]`);
if (!card) return;
// Remove any existing question banner on this card.
const existing = card.querySelector('.question-banner');
if (existing) existing.remove();
const banner = document.createElement('div');
banner.className = 'question-banner';
for (const q of questions) {
const qDiv = document.createElement('div');
qDiv.className = 'question-item';
const label = document.createElement('div');
label.className = 'question-text';
label.textContent = q.question || 'The agent has a question';
qDiv.appendChild(label);
const options = q.options || [];
if (options.length > 0) {
const btnGroup = document.createElement('div');
btnGroup.className = 'question-options';
for (const opt of options) {
const btn = document.createElement('button');
btn.className = 'btn-question-option';
btn.textContent = opt.label;
if (opt.description) btn.title = opt.description;
btn.addEventListener('click', () => {
submitAnswer(taskId, questionId, opt.label, banner);
});
btnGroup.appendChild(btn);
}
qDiv.appendChild(btnGroup);
}
// Always show a free-text input as fallback.
const inputRow = document.createElement('div');
inputRow.className = 'question-input-row';
const input = document.createElement('input');
input.type = 'text';
input.className = 'question-input';
input.placeholder = 'Type an answer…';
const sendBtn = document.createElement('button');
sendBtn.className = 'btn-question-send';
sendBtn.textContent = 'Send';
sendBtn.addEventListener('click', () => {
const val = input.value.trim();
if (val) submitAnswer(taskId, questionId, val, banner);
});
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
const val = input.value.trim();
if (val) submitAnswer(taskId, questionId, val, banner);
}
});
inputRow.append(input, sendBtn);
qDiv.appendChild(inputRow);
banner.appendChild(qDiv);
}
card.appendChild(banner);
}
async function submitAnswer(taskId, questionId, answer, banner) {
// Disable all buttons in the banner.
banner.querySelectorAll('button').forEach(b => { b.disabled = true; });
banner.querySelector('.question-input')?.setAttribute('disabled', '');
try {
const res = await fetch(`${API_BASE}/api/tasks/${taskId}/answer`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ question_id: questionId, answer }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error || `HTTP ${res.status}`);
}
banner.remove();
} catch (err) {
const errEl = document.createElement('div');
errEl.className = 'question-error';
errEl.textContent = `Failed: ${err.message}`;
banner.appendChild(errEl);
// Re-enable buttons.
banner.querySelectorAll('button').forEach(b => { b.disabled = false; });
banner.querySelector('.question-input')?.removeAttribute('disabled');
}
}
// ── Elaborate (Draft with AI) ─────────────────────────────────────────────────
async function elaborateTask(prompt, workingDir) {
const res = await fetch(`${API_BASE}/api/tasks/elaborate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt, project_dir: workingDir }),
});
if (!res.ok) {
let msg = `HTTP ${res.status}`;
try { const body = await res.json(); msg = body.error || msg; } catch {}
throw new Error(msg);
}
return res.json();
}
// ── Validate ──────────────────────────────────────────────────────────────────
async function validateTask(payload) {
const res = await fetch(`${API_BASE}/api/tasks/validate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
if (!res.ok) {
let msg = res.statusText;
try { const body = await res.json(); msg = body.error || body.message || msg; } catch {}
throw new Error(msg);
}
return res.json();
}
function buildValidatePayload() {
const f = document.getElementById('task-form');
const name = f.querySelector('[name="name"]').value;
const instructions = f.querySelector('[name="instructions"]').value;
const repository_url = document.getElementById('repository-url').value;
const container_image = document.getElementById('container-image').value;
const allowedToolsEl = f.querySelector('[name="allowed_tools"]');
const allowed_tools = allowedToolsEl
? allowedToolsEl.value.split(',').map(s => s.trim()).filter(Boolean)
: [];
return { name, repository_url, agent: { instructions, container_image, allowed_tools } };
}
function renderValidationResult(result) {
const container = document.getElementById('validate-result');
container.removeAttribute('hidden');
container.dataset.clarity = result.clarity;
let icon;
if (result.ready === true) {
icon = '✓';
} else if (result.clarity === 'ambiguous') {
icon = '⚠';
} else {
icon = '✗';
}
container.innerHTML = '';
const header = document.createElement('div');
header.className = 'validate-header';
const iconSpan = document.createElement('span');
iconSpan.className = 'validate-icon';
iconSpan.textContent = icon;
const summarySpan = document.createElement('span');
summarySpan.textContent = ' ' + (result.summary || '');
header.append(iconSpan, summarySpan);
container.appendChild(header);
if (result.questions && result.questions.length > 0) {
const ul = document.createElement('ul');
ul.className = 'validate-questions';
for (const q of result.questions) {
const li = document.createElement('li');
li.className = q.severity === 'blocking' ? 'validate-blocking' : 'validate-minor';
li.textContent = q.text;
ul.appendChild(li);
}
container.appendChild(ul);
}
if (result.suggestions && result.suggestions.length > 0) {
const ul = document.createElement('ul');
ul.className = 'validate-suggestions';
for (const s of result.suggestions) {
const li = document.createElement('li');
li.className = 'validate-suggestion';
li.textContent = s;
ul.appendChild(li);
}
container.appendChild(ul);
}
}
// ── Task modal ────────────────────────────────────────────────────────────────
async function openTaskModal() {
document.getElementById('task-modal').showModal();
}
function closeTaskModal() {
document.getElementById('task-modal').close();
document.getElementById('task-form').reset();
document.getElementById('elaborate-prompt').value = '';
const validateResult = document.getElementById('validate-result');
validateResult.setAttribute('hidden', '');
validateResult.innerHTML = '';
validateResult.removeAttribute('data-clarity');
}
async function createTask(formData) {
const repository_url = formData.get('repository_url');
const container_image = formData.get('container_image');
const elaboratePromptEl = document.getElementById('elaborate-prompt');
const elaborationInput = elaboratePromptEl ? elaboratePromptEl.value.trim() : '';
const body = {
name: formData.get('name'),
description: '',
elaboration_input: elaborationInput || undefined,
repository_url: repository_url,
agent: {
instructions: formData.get('instructions'),
container_image: container_image,
max_budget_usd: parseFloat(formData.get('max_budget_usd')),
type: 'container',
},
timeout: formData.get('timeout'),
priority: formData.get('priority'),
tags: [],
};
const res = await fetch(`${API_BASE}/api/tasks`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!res.ok) {
const text = await res.text();
throw new Error(text || `HTTP ${res.status}`);
}
closeTaskModal();
await poll();
}
// ── Task side panel ───────────────────────────────────────────────────────────
// Format Go's task.Duration JSON value {"Duration": <nanoseconds>} to human string.
function formatDurationNs(timeout) {
const ns = timeout && timeout.Duration;
if (!ns) return '—';
const secs = ns / 1e9;
if (secs < 60) return `${secs.toFixed(1)}s`;
const mins = Math.floor(secs / 60);
const remSecs = Math.floor(secs % 60);
if (mins < 60) return remSecs > 0 ? `${mins}m ${remSecs}s` : `${mins}m`;
const hrs = Math.floor(mins / 60);
const remMins = mins % 60;
return remMins > 0 ? `${hrs}h ${remMins}m` : `${hrs}h`;
}
function formatDateLong(iso) {
if (!iso) return '—';
return new Date(iso).toLocaleString(undefined, {
year: 'numeric', month: 'short', day: 'numeric',
hour: '2-digit', minute: '2-digit', second: '2-digit',
});
}
function openTaskPanel(taskId) {
const panel = document.getElementById('task-panel');
const backdrop = document.getElementById('task-panel-backdrop');
const content = document.getElementById('task-panel-content');
document.getElementById('task-panel-title').textContent = 'Task Details';
content.innerHTML = '';
const loading = document.createElement('div');
loading.className = 'panel-loading';
loading.textContent = 'Loading…';
content.appendChild(loading);
backdrop.hidden = false;
panel.classList.add('open');
Promise.all([
fetch(`${API_BASE}/api/tasks/${taskId}`).then(r => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json();
}),
fetch(`${API_BASE}/api/tasks/${taskId}/executions`).then(r => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json();
}),
]).then(([task, executions]) => {
renderTaskPanel(task, executions);
}).catch(err => {
content.innerHTML = '';
const errEl = document.createElement('div');
errEl.className = 'panel-fetch-error';
errEl.textContent = `Failed to load: ${err.message}`;
content.appendChild(errEl);
});
}
function closeTaskPanel() {
closeLogViewer();
document.getElementById('task-panel').classList.remove('open');
document.getElementById('task-panel-backdrop').hidden = true;
}
function makeSection(title) {
const section = document.createElement('div');
section.className = 'panel-section';
const hdr = document.createElement('div');
hdr.className = 'panel-section-title';
hdr.textContent = title;
section.appendChild(hdr);
return section;
}
function makeMetaItem(label, valueText, opts = {}) {
const item = document.createElement('div');
item.className = 'meta-item' + (opts.fullWidth ? ' full-width' : '');
const lbl = document.createElement('div');
lbl.className = 'meta-label';
lbl.textContent = label;
item.appendChild(lbl);
if (opts.badge) {
const badge = document.createElement('span');
badge.className = 'state-badge';
badge.dataset.state = valueText;
badge.textContent = valueText.replace(/_/g, ' ');
item.appendChild(badge);
} else if (opts.code) {
const pre = document.createElement('pre');
pre.className = 'panel-code';
pre.textContent = valueText;
item.appendChild(pre);
} else if (opts.tags) {
const wrap = document.createElement('div');
if (opts.tags.length > 0) {
wrap.className = 'panel-tags';
for (const tag of opts.tags) {
const chip = document.createElement('span');
chip.className = 'tag-chip';
chip.textContent = tag;
wrap.appendChild(chip);
}
} else {
wrap.className = 'meta-value muted';
wrap.textContent = '—';
}
item.appendChild(wrap);
} else {
const val = document.createElement('div');
val.className = 'meta-value' + (opts.mono ? ' mono' : '') + (opts.muted ? ' muted' : '');
val.textContent = valueText || '—';
item.appendChild(val);
}
return item;
}
export function renderTaskPanel(task, executions) {
document.getElementById('task-panel-title').textContent = task.name;
const content = document.getElementById('task-panel-content');
content.innerHTML = '';
// ── Summary ──
if (task.summary) {
const summarySection = makeSection('Summary');
const summaryEl = document.createElement('p');
summaryEl.className = 'task-summary';
summaryEl.textContent = task.summary;
summarySection.appendChild(summaryEl);
content.appendChild(summarySection);
}
// ── Q&A History ──
if (task.interactions && task.interactions.length > 0) {
const qaSection = makeSection('Q&A History');
const qaList = document.createElement('div');
qaList.className = 'qa-list';
for (const interaction of task.interactions) {
const qaItem = document.createElement('div');
qaItem.className = 'qa-item';
const qEl = document.createElement('div');
qEl.className = 'qa-question';
qEl.textContent = interaction.question_text || '(question)';
qaItem.appendChild(qEl);
if (interaction.options && interaction.options.length > 0) {
const opts = document.createElement('div');
opts.className = 'qa-options';
opts.textContent = 'Options: ' + interaction.options.join(', ');
qaItem.appendChild(opts);
}
if (interaction.answer) {
const aEl = document.createElement('div');
aEl.className = 'qa-answer';
aEl.textContent = interaction.answer;
qaItem.appendChild(aEl);
}
qaList.appendChild(qaItem);
}
qaSection.appendChild(qaList);
content.appendChild(qaSection);
}
// ── Overview ──
const overview = makeSection('Overview');
const overviewGrid = document.createElement('div');
overviewGrid.className = 'meta-grid';
overviewGrid.append(
makeMetaItem('State', task.state, { badge: true }),
makeMetaItem('Priority', task.priority),
makeMetaItem('Created', formatDateLong(task.created_at)),
makeMetaItem('Updated', formatDateLong(task.updated_at)),
makeMetaItem('ID', task.id, { fullWidth: true, mono: true }),
);
if (task.parent_task_id) {
overviewGrid.append(makeMetaItem('Parent Task', task.parent_task_id, { fullWidth: true, mono: true }));
}
if (task.tags && task.tags.length >= 0) {
overviewGrid.append(makeMetaItem('Tags', '', { fullWidth: true, tags: task.tags || [] }));
}
if (task.project) {
overviewGrid.append(makeMetaItem('Project', task.project));
}
if (task.description) {
overviewGrid.append(makeMetaItem('Description', task.description, { fullWidth: true }));
}
overview.appendChild(overviewGrid);
content.appendChild(overview);
// ── Agent Config ──
const a = task.agent || {};
const agentSection = makeSection('Agent Config');
const agentGrid = document.createElement('div');
agentGrid.className = 'meta-grid';
agentGrid.append(
makeMetaItem('Type', a.type || 'claude'),
makeMetaItem('Model', a.model),
makeMetaItem('Max Budget', a.max_budget_usd != null ? `$${a.max_budget_usd.toFixed(2)}` : '—'),
makeMetaItem('Project Dir', a.project_dir || a.working_dir),
makeMetaItem('Permission Mode', a.permission_mode || 'default'),
);
if (a.allowed_tools && a.allowed_tools.length > 0) {
agentGrid.append(makeMetaItem('Allowed Tools', a.allowed_tools.join(', '), { fullWidth: true }));
}
if (a.disallowed_tools && a.disallowed_tools.length > 0) {
agentGrid.append(makeMetaItem('Disallowed Tools', a.disallowed_tools.join(', '), { fullWidth: true }));
}
if (a.instructions) {
agentGrid.append(makeMetaItem('Instructions', a.instructions, { fullWidth: true, code: true }));
}
if (a.system_prompt_append) {
agentGrid.append(makeMetaItem('System Prompt Append', a.system_prompt_append, { fullWidth: true, code: true }));
}
agentSection.appendChild(agentGrid);
content.appendChild(agentSection);
// ── Q&A History ──
let interactions = [];
if (task.interactions) {
try { interactions = JSON.parse(task.interactions); } catch {}
}
if (interactions.length > 0) {
const qaSection = makeSection("Q&A History");
const timeline = document.createElement("div");
timeline.className = "qa-timeline";
for (const item of interactions) {
const entry = document.createElement("div");
entry.className = `qa-item qa-${item.type}`;
const label = document.createElement("span");
label.className = "qa-label";
label.textContent = item.type === "question" ? "Agent asked:" : "User answered:";
const text = document.createElement("div");
text.className = "qa-content";
text.textContent = item.content;
const ts = document.createElement("span");
ts.className = "qa-timestamp";
ts.textContent = item.timestamp ? formatDate(item.timestamp) : "";
entry.append(label, text, ts);
timeline.appendChild(entry);
}
qaSection.appendChild(timeline);
content.appendChild(qaSection);
}
// ── Execution Settings ──
const settingsSection = makeSection('Execution Settings');
const settingsGrid = document.createElement('div');
settingsGrid.className = 'meta-grid';
settingsGrid.append(
makeMetaItem('Timeout', formatDurationNs(task.timeout)),
makeMetaItem('Retry Attempts', String(task.retry ? task.retry.max_attempts : 1)),
makeMetaItem('Backoff', task.retry ? task.retry.backoff : '—'),
);
if (task.depends_on && task.depends_on.length > 0) {
settingsGrid.append(makeMetaItem('Depends On', task.depends_on.join(', '), { fullWidth: true, mono: true }));
}
settingsSection.appendChild(settingsGrid);
content.appendChild(settingsSection);
// ── Executions ──
const execSection = makeSection('Executions');
if (!executions || executions.length === 0) {
const none = document.createElement('div');
none.className = 'meta-value muted';
none.textContent = 'No executions yet.';
execSection.appendChild(none);
} else {
const list = document.createElement('div');
list.className = 'executions-list';
// Newest first
for (const exec of [...executions].reverse()) {
const row = document.createElement('div');
row.className = 'execution-row';
const shortId = document.createElement('span');
shortId.className = 'execution-id';
shortId.textContent = exec.ID ? exec.ID.slice(0, 8) : '—';
row.appendChild(shortId);
const badge = document.createElement('span');
badge.className = 'state-badge';
badge.dataset.state = exec.Status || '';
badge.textContent = (exec.Status || '—').replace(/_/g, ' ');
row.appendChild(badge);
const times = document.createElement('span');
times.className = 'execution-times';
const start = exec.StartTime ? formatDate(exec.StartTime) : '?';
const end = exec.EndTime && exec.EndTime !== '0001-01-01T00:00:00Z' ? formatDate(exec.EndTime) : '…';
times.textContent = `${start} → ${end}`;
row.appendChild(times);
if (exec.CostUSD != null && exec.CostUSD > 0) {
const cost = document.createElement('span');
cost.className = 'execution-cost';
cost.textContent = `$${exec.CostUSD.toFixed(4)}`;
row.appendChild(cost);
}
const exitEl = document.createElement('span');
exitEl.className = 'execution-exit';
exitEl.textContent = `exit: ${exec.ExitCode ?? '—'}`;
row.appendChild(exitEl);
if (exec.Changestats != null) {
const csBadge = renderChangestatsBadge(exec.Changestats);
if (csBadge) row.appendChild(csBadge);
}
if (exec.Commits && exec.Commits.length > 0) {
const commitList = document.createElement('div');
commitList.className = 'execution-commits';
for (const commit of exec.Commits) {
const item = document.createElement('div');
item.className = 'commit-item';
const hash = document.createElement('span');
hash.className = 'commit-hash';
hash.textContent = commit.hash.slice(0, 7);
item.appendChild(hash);
const msg = document.createElement('span');
msg.className = 'commit-msg';
msg.textContent = commit.message;
item.appendChild(msg);
commitList.appendChild(item);
}
row.appendChild(commitList);
}
const logsBtn = document.createElement('button');
logsBtn.className = 'btn-view-logs';
logsBtn.textContent = 'View Logs';
logsBtn.addEventListener('click', () => {
const panelContent = document.getElementById('task-panel-content');
openLogViewer(exec.ID, panelContent);
});
row.appendChild(logsBtn);
list.appendChild(row);
}
execSection.appendChild(list);
}
content.appendChild(execSection);
}
async function handleViewLogs(execId) {
const modal = document.getElementById('logs-modal');
const body = document.getElementById('logs-modal-body');
document.getElementById('logs-modal-title').textContent = `Execution ${execId.slice(0, 8)}`;
body.innerHTML = '<div class="panel-loading">Loading…</div>';
modal.showModal();
try {
const res = await fetch(`${API_BASE}/api/executions/${execId}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const exec = await res.json();
body.innerHTML = '';
const grid = document.createElement('div');
grid.className = 'meta-grid';
const entries = [
['ID', exec.ID, { fullWidth: true, mono: true }],
['Status', exec.Status, { badge: true }],
['Exit Code', String(exec.ExitCode ?? '—'), {}],
['Cost', exec.CostUSD > 0 ? `$${exec.CostUSD.toFixed(4)}` : '—', {}],
['Start', formatDateLong(exec.StartTime), {}],
['End', exec.EndTime && !exec.EndTime.startsWith('0001-') ? formatDateLong(exec.EndTime) : '—', {}],
['Error', exec.ErrorMsg || '—', { fullWidth: true }],
['Stdout', exec.StdoutPath || '—', { fullWidth: true, mono: true }],
['Stderr', exec.StderrPath || '—', { fullWidth: true, mono: true }],
];
for (const [label, value, opts] of entries) {
grid.appendChild(makeMetaItem(label, value, opts));
}
body.appendChild(grid);
} catch (err) {
body.innerHTML = `<div class="panel-fetch-error">Failed to load: ${err.message}</div>`;
}
}
// ── Log viewer ────────────────────────────────────────────────────────────────
function openLogViewer(execId, containerEl) {
// Save original children so Back can restore them (with event listeners intact)
const originalChildren = [...containerEl.childNodes];
containerEl.innerHTML = '';
const viewer = document.createElement('div');
viewer.className = 'log-viewer';
// Back button
const backBtn = document.createElement('button');
backBtn.className = 'log-back-btn';
backBtn.textContent = '← Back';
backBtn.addEventListener('click', () => {
closeLogViewer();
containerEl.innerHTML = '';
for (const node of originalChildren) containerEl.appendChild(node);
});
viewer.appendChild(backBtn);
// Pulsing status indicator
const statusEl = document.createElement('div');
statusEl.className = 'log-status-indicator';
statusEl.textContent = 'Streaming...';
viewer.appendChild(statusEl);
// Log output area
const logOutput = document.createElement('div');
logOutput.className = 'log-output';
logOutput.style.fontFamily = 'monospace';
logOutput.style.overflowY = 'auto';
logOutput.style.maxHeight = '400px';
viewer.appendChild(logOutput);
containerEl.appendChild(viewer);
let userScrolled = false;
logOutput.addEventListener('scroll', () => {
const nearBottom = logOutput.scrollHeight - logOutput.scrollTop - logOutput.clientHeight < 50;
userScrolled = !nearBottom;
});
const source = new EventSource(`${API_BASE}/api/executions/${execId}/logs/stream`);
activeLogSource = source;
source.onmessage = (event) => {
let data;
try { data = JSON.parse(event.data); } catch { return; }
const line = document.createElement('div');
line.className = 'log-line';
switch (data.type) {
case 'text': {
line.classList.add('log-text');
line.textContent = data.text ?? data.content ?? '';
break;
}
case 'tool_use': {
line.classList.add('log-tool-use');
const toolName = document.createElement('span');
toolName.className = 'tool-name';
toolName.textContent = `[${data.name ?? 'Tool'}]`;
line.appendChild(toolName);
const inputStr = data.input ? JSON.stringify(data.input) : '';
const inputPreview = document.createElement('span');
inputPreview.textContent = ' ' + inputStr.slice(0, 120);
line.appendChild(inputPreview);
break;
}
case 'tool_result': {
line.classList.add('log-tool-result');
line.style.opacity = '0.6';
const content = Array.isArray(data.content)
? data.content.map(c => c.text ?? '').join(' ')
: (data.content ?? '');
line.textContent = String(content).slice(0, 120);
break;
}
case 'cost': {
line.classList.add('log-cost');
const cost = data.total_cost ?? data.cost ?? 0;
line.textContent = `Cost: $${Number(cost).toFixed(3)}`;
break;
}
default:
return;
}
logOutput.appendChild(line);
if (!userScrolled) {
logOutput.scrollTop = logOutput.scrollHeight;
}
};
source.addEventListener('done', () => {
source.close();
activeLogSource = null;
userScrolled = false;
statusEl.classList.remove('log-status-indicator');
statusEl.textContent = 'Stream complete';
});
source.onerror = () => {
source.close();
activeLogSource = null;
statusEl.hidden = true;
const errEl = document.createElement('div');
errEl.className = 'log-line log-error';
errEl.textContent = 'Connection error. Stream closed.';
logOutput.appendChild(errEl);
};
}
function closeLogViewer() {
activeLogSource?.close();
activeLogSource = null;
}
// ── Running view ───────────────────────────────────────────────────────────────
// Map of taskId → EventSource for live log streams in the Running tab.
const runningViewLogSources = {};
function renderRunningView(tasks) {
const currentEl = document.querySelector('.running-current');
if (!currentEl) return;
const running = filterRunningTasks(tasks);
// Close SSE streams for tasks that are no longer RUNNING.
for (const [id, src] of Object.entries(runningViewLogSources)) {
if (!running.find(t => t.id === id)) {
src.close();
delete runningViewLogSources[id];
}
}
// Update elapsed spans in place if the same tasks are still running.
const existingCards = currentEl.querySelectorAll('[data-task-id]');
const existingIds = new Set([...existingCards].map(c => c.dataset.taskId));
const unchanged = running.length > 0 &&
running.length === existingCards.length &&
running.every(t => existingIds.has(t.id));
if (unchanged) {
updateRunningElapsed();
return;
}
// Full re-render.
currentEl.innerHTML = '';
const h2 = document.createElement('h2');
h2.textContent = 'Currently Running';
currentEl.appendChild(h2);
if (running.length === 0) {
const empty = document.createElement('p');
empty.className = 'task-meta';
empty.textContent = 'No tasks are currently running.';
currentEl.appendChild(empty);
return;
}
for (const task of running) {
const card = document.createElement('div');
card.className = 'running-task-card task-card';
card.dataset.taskId = task.id;
const header = document.createElement('div');
header.className = 'task-card-header';
const name = document.createElement('span');
name.className = 'task-name';
name.textContent = task.name;
const badge = document.createElement('span');
badge.className = 'state-badge';
badge.dataset.state = task.state;
badge.textContent = task.state;
const elapsed = document.createElement('span');
elapsed.className = 'running-elapsed';
elapsed.dataset.startedAt = task.updated_at ?? '';
elapsed.textContent = formatElapsed(task.updated_at);
header.append(name, badge, elapsed);
card.appendChild(header);
// Parent context (async fetch)
if (task.parent_task_id) {
const parentEl = document.createElement('div');
parentEl.className = 'task-meta';
parentEl.textContent = 'Subtask of: …';
card.appendChild(parentEl);
fetch(`${API_BASE}/api/tasks/${task.parent_task_id}`)
.then(r => r.ok ? r.json() : null)
.then(parent => {
if (parent) parentEl.textContent = `Subtask of: ${parent.name}`;
})
.catch(() => { parentEl.textContent = ''; });
}
// Meta row: agent type + model + execution ID (exec ID filled in async)
const metaRow = document.createElement('div');
metaRow.className = 'task-meta running-exec-meta';
const agentType = (task.agent && task.agent.type) ? task.agent.type : 'claude';
const agentModel = (task.agent && task.agent.model) ? task.agent.model : '';
const agentSpan = document.createElement('span');
agentSpan.textContent = agentModel ? `${agentType} (${agentModel})` : `Agent: ${agentType}`;
const execIdSpan = document.createElement('span');
execIdSpan.className = 'execution-id running-exec-id';
execIdSpan.textContent = 'exec: …';
metaRow.append(agentSpan, execIdSpan);
card.appendChild(metaRow);
// Log area
const logArea = document.createElement('div');
logArea.className = 'running-log';
logArea.dataset.logTarget = task.id;
card.appendChild(logArea);
// Footer with Cancel button
const footer = document.createElement('div');
footer.className = 'task-card-footer';
const cancelBtn = document.createElement('button');
cancelBtn.className = 'btn-cancel';
cancelBtn.textContent = 'Cancel';
cancelBtn.addEventListener('click', (e) => {
e.stopPropagation();
handleCancel(task.id, cancelBtn, footer);
});
footer.appendChild(cancelBtn);
card.appendChild(footer);
currentEl.appendChild(card);
// Open SSE stream if not already streaming for this task.
if (!runningViewLogSources[task.id]) {
startRunningLogStream(task.id, logArea);
}
}
}
function startRunningLogStream(taskId, logArea) {
fetch(`${API_BASE}/api/executions?task_id=${taskId}&limit=1`)
.then(r => r.ok ? r.json() : [])
.then(execs => {
if (!execs || execs.length === 0) return;
const execId = execs[0].id;
// Update the exec ID shown in the running card.
const card = document.querySelector(`[data-task-id="${taskId}"]`);
if (card) {
const execIdEl = card.querySelector('.running-exec-id');
if (execIdEl) execIdEl.textContent = `exec: ${execId.slice(0, 8)}`;
}
let userScrolled = false;
logArea.addEventListener('scroll', () => {
const nearBottom = logArea.scrollHeight - logArea.scrollTop - logArea.clientHeight < 50;
userScrolled = !nearBottom;
});
const src = new EventSource(`${API_BASE}/api/executions/${execId}/logs/stream`);
runningViewLogSources[taskId] = src;
src.onmessage = (event) => {
let data;
try { data = JSON.parse(event.data); } catch { return; }
const line = document.createElement('div');
line.className = 'log-line';
switch (data.type) {
case 'text': {
line.classList.add('log-text');
line.textContent = data.text ?? data.content ?? '';
break;
}
case 'tool_use': {
line.classList.add('log-tool-use');
const toolName = document.createElement('span');
toolName.className = 'tool-name';
toolName.textContent = `[${data.name ?? 'Tool'}]`;
line.appendChild(toolName);
const inputStr = data.input ? JSON.stringify(data.input) : '';
const inputPreview = document.createElement('span');
inputPreview.textContent = ' ' + inputStr.slice(0, 120);
line.appendChild(inputPreview);
break;
}
case 'cost': {
line.classList.add('log-cost');
const cost = data.total_cost ?? data.cost ?? 0;
line.textContent = `Cost: $${Number(cost).toFixed(3)}`;
break;
}
default:
return;
}
logArea.appendChild(line);
// Trim to last 500 lines.
while (logArea.childElementCount > 500) {
logArea.removeChild(logArea.firstElementChild);
}
if (!userScrolled) logArea.scrollTop = logArea.scrollHeight;
};
src.addEventListener('done', () => {
src.close();
delete runningViewLogSources[taskId];
});
src.onerror = () => {
src.close();
delete runningViewLogSources[taskId];
const errEl = document.createElement('div');
errEl.className = 'log-line log-error';
errEl.textContent = 'Stream closed.';
logArea.appendChild(errEl);
};
})
.catch(() => {});
}
function updateRunningElapsed() {
document.querySelectorAll('.running-elapsed[data-started-at]').forEach(el => {
el.textContent = formatElapsed(el.dataset.startedAt || null);
});
}
function isRunningTabActive() {
const panel = document.querySelector('[data-panel="running"]');
return panel && !panel.hasAttribute('hidden');
}
function sortExecutionsByDate(executions) {
return sortExecutionsDesc(executions);
}
function renderRunningHistory(executions) {
const histEl = document.querySelector('.running-history');
if (!histEl) return;
histEl.innerHTML = '';
const h2 = document.createElement('h2');
h2.textContent = 'Execution History (Last 24h)';
histEl.appendChild(h2);
if (!executions || executions.length === 0) {
const empty = document.createElement('p');
empty.className = 'task-meta';
empty.textContent = 'No executions in the last 24h';
histEl.appendChild(empty);
return;
}
const sorted = sortExecutionsDesc(executions);
const table = document.createElement('table');
table.className = 'history-table';
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');
for (const col of ['Date', 'Task', 'Status', 'Duration', 'Cost', 'Exit', 'Logs']) {
const th = document.createElement('th');
th.textContent = col;
headerRow.appendChild(th);
}
thead.appendChild(headerRow);
table.appendChild(thead);
const tbody = document.createElement('tbody');
for (const exec of sorted) {
const tr = document.createElement('tr');
const tdDate = document.createElement('td');
tdDate.textContent = formatDate(exec.started_at);
tr.appendChild(tdDate);
const tdTask = document.createElement('td');
tdTask.textContent = exec.task_name || exec.task_id || '—';
tr.appendChild(tdTask);
const tdStatus = document.createElement('td');
const stateBadge = document.createElement('span');
stateBadge.className = 'state-badge';
stateBadge.dataset.state = exec.state || '';
stateBadge.textContent = exec.state || '—';
tdStatus.appendChild(stateBadge);
tr.appendChild(tdStatus);
const tdDur = document.createElement('td');
tdDur.textContent = formatDuration(exec.started_at, exec.finished_at ?? null);
tr.appendChild(tdDur);
const tdCost = document.createElement('td');
tdCost.textContent = exec.cost_usd > 0 ? `$${exec.cost_usd.toFixed(4)}` : '—';
tr.appendChild(tdCost);
const tdExit = document.createElement('td');
tdExit.textContent = exec.exit_code != null ? String(exec.exit_code) : '—';
tr.appendChild(tdExit);
const tdLogs = document.createElement('td');
const viewBtn = document.createElement('button');
viewBtn.className = 'btn-sm';
viewBtn.textContent = 'View Logs';
viewBtn.addEventListener('click', () => openLogViewer(exec.id, histEl));
tdLogs.appendChild(viewBtn);
tr.appendChild(tdLogs);
tbody.appendChild(tr);
}
table.appendChild(tbody);
histEl.appendChild(table);
}
// ── Stats rendering ───────────────────────────────────────────────────────────
// State display order for the task overview grid.
const STATS_STATE_ORDER = [
'RUNNING', 'QUEUED', 'READY', 'BLOCKED',
'PENDING', 'COMPLETED', 'FAILED', 'TIMED_OUT', 'CANCELLED', 'BUDGET_EXCEEDED',
];
function formatDurationMs(ms) {
if (ms == null) return '—';
const s = Math.round(ms / 1000);
if (s < 60) return `${s}s`;
const m = Math.floor(s / 60);
const rs = s % 60;
if (m < 60) return rs > 0 ? `${m}m ${rs}s` : `${m}m`;
const h = Math.floor(m / 60);
const rm = m % 60;
return rm > 0 ? `${h}h ${rm}m` : `${h}h`;
}
function renderStatsPanel(tasks, executions, agentData = { agents: [], events: [] }, dashStats = { throughput: [], billing: [], failures: [] }) {
const panel = document.querySelector('[data-panel="stats"]');
if (!panel) return;
const taskStats = computeTaskStats(tasks);
const execStats = computeExecutionStats(executions);
panel.innerHTML = '';
// ── Task Overview ──────────────────────────────────────────────────────────
const taskSection = document.createElement('div');
taskSection.className = 'stats-section';
const taskHeading = document.createElement('h2');
taskHeading.textContent = 'Task Overview';
taskSection.appendChild(taskHeading);
const countsGrid = document.createElement('div');
countsGrid.className = 'stats-counts';
const orderedStates = STATS_STATE_ORDER.filter(s => taskStats.byState[s] > 0);
const otherStates = Object.keys(taskStats.byState).filter(s => !STATS_STATE_ORDER.includes(s));
for (const state of [...orderedStates, ...otherStates]) {
const count = taskStats.byState[state] || 0;
if (count === 0) continue;
const box = document.createElement('div');
box.className = 'stats-count-box';
box.dataset.state = state;
const num = document.createElement('span');
num.className = 'stats-count-number';
num.textContent = String(count);
const label = document.createElement('span');
label.className = 'stats-count-label';
label.textContent = state.replace(/_/g, ' ');
box.appendChild(num);
box.appendChild(label);
countsGrid.appendChild(box);
}
if (orderedStates.length === 0 && otherStates.length === 0) {
const empty = document.createElement('p');
empty.className = 'task-meta';
empty.textContent = 'No tasks yet.';
countsGrid.appendChild(empty);
}
taskSection.appendChild(countsGrid);
panel.appendChild(taskSection);
// ── Execution Health ───────────────────────────────────────────────────────
const execSection = document.createElement('div');
execSection.className = 'stats-section';
const execHeading = document.createElement('h2');
execHeading.textContent = 'Executions (Last 24h)';
execSection.appendChild(execHeading);
const kpisRow = document.createElement('div');
kpisRow.className = 'stats-kpis';
const kpis = [
{ label: 'Total Runs', value: String(execStats.total) },
{ label: 'Success Rate', value: execStats.total > 0 ? `${Math.round(execStats.successRate * 100)}%` : '—' },
{ label: 'Total Cost', value: execStats.totalCostUSD > 0 ? `$${execStats.totalCostUSD.toFixed(2)}` : '$0.00' },
{ label: 'Avg Duration', value: formatDurationMs(execStats.avgDurationMs) },
];
for (const kpi of kpis) {
const box = document.createElement('div');
box.className = 'stats-kpi-box';
const val = document.createElement('span');
val.className = 'stats-kpi-value';
val.textContent = kpi.value;
const lbl = document.createElement('span');
lbl.className = 'stats-kpi-label';
lbl.textContent = kpi.label;
box.appendChild(val);
box.appendChild(lbl);
kpisRow.appendChild(box);
}
execSection.appendChild(kpisRow);
// Bar chart of outcome distribution.
if (execStats.total > 0) {
const chartSection = document.createElement('div');
chartSection.className = 'stats-bar-chart';
const chartLabel = document.createElement('p');
chartLabel.className = 'stats-bar-chart-label';
chartLabel.textContent = 'Outcome breakdown';
chartSection.appendChild(chartLabel);
const bars = document.createElement('div');
bars.className = 'stats-bars';
for (const [outcome, count] of Object.entries(execStats.byOutcome)) {
const pct = (count / execStats.total) * 100;
const row = document.createElement('div');
row.className = 'stats-bar-row';
const barLabel = document.createElement('span');
barLabel.className = 'stats-bar-row-label';
barLabel.textContent = outcome.replace(/_/g, ' ');
const barTrack = document.createElement('div');
barTrack.className = 'stats-bar-track';
const barFill = document.createElement('div');
barFill.className = 'stats-bar-fill';
barFill.dataset.state = outcome.toUpperCase();
barFill.style.width = `${pct.toFixed(1)}%`;
const barCount = document.createElement('span');
barCount.className = 'stats-bar-count';
barCount.textContent = `${count} (${Math.round(pct)}%)`;
barTrack.appendChild(barFill);
row.appendChild(barLabel);
row.appendChild(barTrack);
row.appendChild(barCount);
bars.appendChild(row);
}
chartSection.appendChild(bars);
execSection.appendChild(chartSection);
}
// ── Per-execution detail table ─────────────────────────────────────────────
if (executions.length > 0) {
const tableWrap = document.createElement('div');
tableWrap.className = 'stats-exec-table-wrap';
const tableLabel = document.createElement('p');
tableLabel.className = 'stats-bar-chart-label';
tableLabel.textContent = 'Recent runs';
tableWrap.appendChild(tableLabel);
const table = document.createElement('table');
table.className = 'stats-exec-table';
table.innerHTML = '<thead><tr><th>Task</th><th>Outcome</th><th>Cost</th><th>Duration</th><th>Started</th></tr></thead>';
const tbody = document.createElement('tbody');
for (const ex of executions.slice(0, 20)) {
const tr = document.createElement('tr');
const durationMs = ex.duration_ms != null ? formatDurationMs(ex.duration_ms) : '—';
const cost = ex.cost_usd > 0 ? `$${ex.cost_usd.toFixed(3)}` : '—';
const started = ex.started_at ? new Date(ex.started_at).toLocaleTimeString() : '—';
const state = (ex.state || '').toUpperCase();
tr.innerHTML = `<td class="stats-exec-name">${ex.task_name || ex.task_id}</td><td><span class="state-badge" data-state="${state}">${state.replace(/_/g,' ')}</span></td><td>${cost}</td><td>${durationMs}</td><td>${started}</td>`;
tbody.appendChild(tr);
}
table.appendChild(tbody);
tableWrap.appendChild(table);
execSection.appendChild(tableWrap);
}
panel.appendChild(execSection);
// ── Errors ────────────────────────────────────────────────────────────────
const failures = dashStats.failures || [];
const errSection = document.createElement('div');
errSection.className = 'stats-section';
const errHeading = document.createElement('h2');
errHeading.textContent = 'Errors (Last 7d)';
errSection.appendChild(errHeading);
if (failures.length === 0) {
const none = document.createElement('p');
none.className = 'task-meta';
none.textContent = 'No failures in the last 7 days.';
errSection.appendChild(none);
} else {
// Category summary bar
const cats = {};
for (const f of failures) cats[f.category] = (cats[f.category] || 0) + 1;
const catOrder = ['quota', 'rate_limit', 'timeout', 'git', 'failed'];
const catLabels = { quota: 'Quota', rate_limit: 'Rate limit', timeout: 'Timeout', git: 'Git', failed: 'Failed' };
const catColors = { quota: 'var(--state-budget-exceeded)', rate_limit: 'var(--state-failed)', timeout: 'var(--state-timed-out)', git: 'var(--state-cancelled)', failed: 'var(--state-failed)' };
const catRow = document.createElement('div');
catRow.className = 'stats-kpis';
const allCats = [...catOrder, ...Object.keys(cats).filter(c => !catOrder.includes(c))];
for (const cat of allCats) {
if (!cats[cat]) continue;
const box = document.createElement('div');
box.className = 'stats-kpi-box stats-err-cat';
box.style.setProperty('--cat-color', catColors[cat] || 'var(--state-failed)');
const val = document.createElement('span');
val.className = 'stats-kpi-value';
val.textContent = String(cats[cat]);
const lbl = document.createElement('span');
lbl.className = 'stats-kpi-label';
lbl.textContent = catLabels[cat] || cat;
box.appendChild(val);
box.appendChild(lbl);
catRow.appendChild(box);
}
errSection.appendChild(catRow);
// Failure table
const errTable = document.createElement('table');
errTable.className = 'stats-exec-table';
errTable.style.marginTop = '0.75rem';
errTable.innerHTML = '<thead><tr><th>Task</th><th>Category</th><th>Error</th><th>Time</th></tr></thead>';
const errTbody = document.createElement('tbody');
for (const f of failures.slice(0, 25)) {
const tr = document.createElement('tr');
const ts = new Date(f.started_at).toLocaleString();
const short = f.error_msg.length > 80 ? f.error_msg.slice(0, 80) + '…' : f.error_msg;
const catColor = catColors[f.category] || 'var(--state-failed)';
tr.innerHTML = `<td class="stats-exec-name">${f.task_name}</td><td><span class="stats-err-badge" style="background:${catColor}">${catLabels[f.category] || f.category}</span></td><td class="stats-err-msg" title="${f.error_msg.replace(/"/g,'"')}">${short}</td><td style="white-space:nowrap">${ts}</td>`;
errTbody.appendChild(tr);
}
errTable.appendChild(errTbody);
errSection.appendChild(errTable);
}
panel.appendChild(errSection);
// ── Throughput ────────────────────────────────────────────────────────────
const throughput = dashStats.throughput || [];
const tpSection = document.createElement('div');
tpSection.className = 'stats-section';
const tpHeading = document.createElement('h2');
tpHeading.textContent = 'Throughput (Last 7d)';
tpSection.appendChild(tpHeading);
if (throughput.length === 0) {
const none = document.createElement('p');
none.className = 'task-meta';
none.textContent = 'No execution data yet.';
tpSection.appendChild(none);
} else {
const maxTotal = Math.max(...throughput.map(b => b.completed + b.failed + b.other), 1);
const chart = document.createElement('div');
chart.className = 'stats-tp-chart';
for (const bucket of throughput) {
const total = bucket.completed + bucket.failed + bucket.other;
const col = document.createElement('div');
col.className = 'stats-tp-col';
const heightPct = (total / maxTotal) * 100;
const label = new Date(bucket.hour).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit' });
col.title = `${label}\n✓ ${bucket.completed} ✗ ${bucket.failed} ○ ${bucket.other}`;
if (total > 0) {
const bar = document.createElement('div');
bar.className = 'stats-tp-bar';
bar.style.height = `${heightPct.toFixed(1)}%`;
const cPct = (bucket.completed / total) * 100;
const fPct = (bucket.failed / total) * 100;
const oPct = 100 - cPct - fPct;
bar.style.background = `linear-gradient(to top,
var(--state-failed) 0% ${fPct.toFixed(1)}%,
var(--state-timed-out) ${fPct.toFixed(1)}% ${(fPct+oPct).toFixed(1)}%,
var(--state-completed) ${(fPct+oPct).toFixed(1)}% 100%)`;
col.appendChild(bar);
}
chart.appendChild(col);
}
tpSection.appendChild(chart);
const tpLegend = document.createElement('div');
tpLegend.className = 'stats-tp-legend';
tpLegend.innerHTML = `
<span class="stats-tp-legend-item"><span class="stats-tp-swatch" style="background:var(--state-completed)"></span>Completed</span>
<span class="stats-tp-legend-item"><span class="stats-tp-swatch" style="background:var(--state-failed)"></span>Failed</span>
<span class="stats-tp-legend-item"><span class="stats-tp-swatch" style="background:var(--state-timed-out)"></span>Other</span>
`;
tpSection.appendChild(tpLegend);
}
panel.appendChild(tpSection);
// ── Billing ───────────────────────────────────────────────────────────────
const billing = dashStats.billing || [];
const billSection = document.createElement('div');
billSection.className = 'stats-section';
const billHeading = document.createElement('h2');
billHeading.textContent = 'Cost (Last 7d)';
billSection.appendChild(billHeading);
if (billing.length === 0) {
const none = document.createElement('p');
none.className = 'task-meta';
none.textContent = 'No cost data yet.';
billSection.appendChild(none);
} else {
const totalCost = billing.reduce((s, d) => s + d.cost_usd, 0);
const totalRuns = billing.reduce((s, d) => s + d.runs, 0);
const billKpis = document.createElement('div');
billKpis.className = 'stats-kpis';
for (const kpi of [
{ label: '7d Total', value: `$${totalCost.toFixed(2)}` },
{ label: 'Avg/Day', value: billing.length > 0 ? `$${(totalCost / billing.length).toFixed(2)}` : '—' },
{ label: 'Cost/Run', value: totalRuns > 0 ? `$${(totalCost / totalRuns).toFixed(3)}` : '—' },
{ label: 'Total Runs', value: String(totalRuns) },
]) {
const box = document.createElement('div');
box.className = 'stats-kpi-box';
const val = document.createElement('span');
val.className = 'stats-kpi-value';
val.textContent = kpi.value;
const lbl = document.createElement('span');
lbl.className = 'stats-kpi-label';
lbl.textContent = kpi.label;
box.appendChild(val);
box.appendChild(lbl);
billKpis.appendChild(box);
}
billSection.appendChild(billKpis);
// Daily cost bar chart
const maxCost = Math.max(...billing.map(d => d.cost_usd), 0.001);
const billChart = document.createElement('div');
billChart.className = 'stats-bill-chart';
for (const day of billing) {
const col = document.createElement('div');
col.className = 'stats-bill-col';
col.title = `${day.day}\n$${day.cost_usd.toFixed(3)} (${day.runs} runs)`;
const bar = document.createElement('div');
bar.className = 'stats-bill-bar';
bar.style.height = `${((day.cost_usd / maxCost) * 100).toFixed(1)}%`;
const dayLabel = document.createElement('span');
dayLabel.className = 'stats-bill-day-label';
const d = new Date(day.day + 'T12:00:00Z');
dayLabel.textContent = d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
col.appendChild(bar);
col.appendChild(dayLabel);
billChart.appendChild(col);
}
billSection.appendChild(billChart);
}
panel.appendChild(billSection);
// ── Agent Status ───────────────────────────────────────────────────────────
const agentSection = document.createElement('div');
agentSection.className = 'stats-section';
const agentHeading = document.createElement('h2');
agentHeading.textContent = 'Agent Status';
agentSection.appendChild(agentHeading);
const agents = agentData.agents || [];
const agentEvents = agentData.events || [];
if (agents.length === 0) {
const none = document.createElement('p');
none.className = 'task-meta';
none.textContent = 'No agents registered.';
agentSection.appendChild(none);
} else {
// Status cards row
const cardsRow = document.createElement('div');
cardsRow.className = 'stats-agent-cards';
for (const ag of agents) {
const card = document.createElement('div');
card.className = 'stats-agent-card';
const statusClass = ag.drained ? 'agent-drained' : ag.rate_limited ? 'agent-rate-limited' : 'agent-available';
card.classList.add(statusClass);
const nameEl = document.createElement('span');
nameEl.className = 'stats-agent-name';
nameEl.textContent = ag.agent;
const statusEl = document.createElement('span');
statusEl.className = 'stats-agent-status';
if (ag.drained) {
statusEl.textContent = 'Drain locked — needs manual undrain';
} else if (ag.rate_limited && ag.until) {
const untilDate = new Date(ag.until);
const minsLeft = Math.max(0, Math.round((untilDate - Date.now()) / 60000));
statusEl.textContent = `Rate limited — ${minsLeft}m remaining`;
} else {
statusEl.textContent = ag.active_tasks > 0 ? `Active (${ag.active_tasks} running)` : 'Available';
}
card.appendChild(nameEl);
card.appendChild(statusEl);
cardsRow.appendChild(card);
}
agentSection.appendChild(cardsRow);
// Availability timeline (last 24h)
const now = Date.now();
const windowMs = 24 * 60 * 60 * 1000;
const windowStart = now - windowMs;
const timelineHeading = document.createElement('p');
timelineHeading.className = 'stats-bar-chart-label';
timelineHeading.textContent = 'Availability last 24h';
agentSection.appendChild(timelineHeading);
// Group events by agent
const eventsByAgent = {};
for (const ev of agentEvents) {
if (!eventsByAgent[ev.agent]) eventsByAgent[ev.agent] = [];
eventsByAgent[ev.agent].push(ev);
}
for (const ag of agents) {
const evs = (eventsByAgent[ag.agent] || []).slice().sort((a, b) => new Date(a.timestamp) - new Date(b.timestamp));
const row = document.createElement('div');
row.className = 'stats-timeline-row';
const label = document.createElement('span');
label.className = 'stats-timeline-label';
label.textContent = ag.agent;
row.appendChild(label);
const track = document.createElement('div');
track.className = 'stats-timeline-track';
// Build segments: walk events and produce [start, end, state] intervals
const segments = [];
let cursor = windowStart;
// Reconstruct: before first event, assume available unless currently rate-limited with an until before window
let inRateLimit = false;
for (const ev of evs) {
const evTime = Math.max(windowStart, new Date(ev.timestamp).getTime());
if (evTime > cursor) {
segments.push({ start: cursor, end: evTime, limited: inRateLimit });
}
cursor = evTime;
if (ev.event === 'rate_limited') {
inRateLimit = true;
} else if (ev.event === 'available') {
inRateLimit = false;
}
}
// Tail to now
if (cursor < now) {
// If currently rate limited use current agent state
segments.push({ start: cursor, end: now, limited: ag.rate_limited || inRateLimit });
}
for (const seg of segments) {
const pct = ((seg.end - seg.start) / windowMs) * 100;
if (pct < 0.01) continue;
const span = document.createElement('div');
span.className = 'stats-timeline-seg';
span.classList.add(seg.limited ? 'seg-limited' : 'seg-available');
span.style.width = `${pct.toFixed(2)}%`;
const mins = Math.round((seg.end - seg.start) / 60000);
span.title = `${seg.limited ? 'Rate limited' : 'Available'} — ${mins}m`;
track.appendChild(span);
}
row.appendChild(track);
// Legend labels
const timeLabels = document.createElement('div');
timeLabels.className = 'stats-timeline-timelabels';
timeLabels.innerHTML = '<span>24h ago</span><span>now</span>';
row.appendChild(timeLabels);
agentSection.appendChild(row);
}
// Rate-limit event log
if (agentEvents.length > 0) {
const evLogLabel = document.createElement('p');
evLogLabel.className = 'stats-bar-chart-label';
evLogLabel.textContent = 'Rate-limit events (last 24h)';
agentSection.appendChild(evLogLabel);
const evTable = document.createElement('table');
evTable.className = 'stats-exec-table';
evTable.innerHTML = '<thead><tr><th>Agent</th><th>Event</th><th>Reason</th><th>Until</th><th>Time</th></tr></thead>';
const evTbody = document.createElement('tbody');
for (const ev of agentEvents.slice(0, 30)) {
const tr = document.createElement('tr');
const until = ev.until ? new Date(ev.until).toLocaleTimeString() : '—';
const ts = new Date(ev.timestamp).toLocaleTimeString();
const eventClass = ev.event === 'rate_limited' ? 'state-badge" data-state="FAILED' : 'state-badge" data-state="COMPLETED';
tr.innerHTML = `<td>${ev.agent}</td><td><span class="${eventClass}">${ev.event.replace(/_/g,' ')}</span></td><td>${ev.reason || '—'}</td><td>${until}</td><td>${ts}</td>`;
evTbody.appendChild(tr);
}
evTable.appendChild(evTbody);
agentSection.appendChild(evTable);
}
}
panel.appendChild(agentSection);
}
// ── Web Push Notifications ────────────────────────────────────────────────────
async function registerServiceWorker() {
if (!('serviceWorker' in navigator) || !('PushManager' in window)) return null;
return navigator.serviceWorker.register(BASE_PATH + '/api/push/sw.js', { scope: BASE_PATH + '/' });
}
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
const rawData = window.atob(base64);
return Uint8Array.from([...rawData].map(c => c.charCodeAt(0)));
}
async function enableNotifications(btn) {
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
alert('Push notifications are not supported in this browser.');
return;
}
try {
const permission = await Notification.requestPermission();
if (permission !== 'granted') {
alert('Notification permission denied.');
return;
}
// Fetch VAPID public key.
const keyRes = await fetch(`${API_BASE}/api/push/vapid-key`);
if (!keyRes.ok) throw new Error(`Failed to get VAPID key: HTTP ${keyRes.status}`);
const { public_key: vapidKey } = await keyRes.json();
// Register service worker and wait for it to become active.
await registerServiceWorker();
const registration = await navigator.serviceWorker.ready;
// Unsubscribe any stale subscription (e.g. from a VAPID key rotation).
// PushManager.subscribe() throws "applicationServerKey is not valid" if the
// existing subscription was created with a different key.
const existingSub = await registration.pushManager.getSubscription();
if (existingSub) {
await existingSub.unsubscribe();
}
// Subscribe via PushManager.
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(vapidKey),
});
const subJSON = subscription.toJSON();
// POST subscription to server.
const res = await fetch(`${API_BASE}/api/push/subscribe`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
endpoint: subJSON.endpoint,
keys: { p256dh: subJSON.keys.p256dh, auth: subJSON.keys.auth },
}),
});
if (!res.ok) throw new Error(`Subscribe failed: HTTP ${res.status}`);
if (btn) {
btn.textContent = '🔔';
btn.disabled = true;
}
} catch (err) {
alert(`Notification setup failed: ${err.message}`);
}
}
// ── File Drops ─────────────────────────────────────────────────────────────────
async function fetchDrops() {
const res = await fetch(`${API_BASE}/api/drops`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
// ── Stories panel ─────────────────────────────────────────────────────────────
async function renderStoriesPanel() {
const panel = document.querySelector('[data-panel="stories"]');
if (!panel) return;
let stories;
try {
const res = await fetch(`${BASE_PATH}/api/stories`);
stories = res.ok ? await res.json() : [];
} catch {
panel.innerHTML = '<p class="task-meta" style="padding:1rem">Failed to load stories.</p>';
return;
}
panel.innerHTML = '';
const toolbar = document.createElement('div');
toolbar.className = 'stories-toolbar';
const btnNew = document.createElement('button');
btnNew.className = 'btn-primary';
btnNew.textContent = 'New Story';
btnNew.addEventListener('click', openStoryModal);
toolbar.appendChild(btnNew);
panel.appendChild(toolbar);
if (!stories || stories.length === 0) {
const empty = document.createElement('p');
empty.className = 'task-empty';
empty.textContent = 'No stories yet. Create one to get started.';
panel.appendChild(empty);
return;
}
const list = document.createElement('div');
list.className = 'stories-list';
for (const story of stories) {
const card = renderStoryCard(story);
card.addEventListener('click', () => openStoryDetail(story));
list.appendChild(card);
}
panel.appendChild(list);
}
function openStoryDetail(story) {
const modal = document.getElementById('story-detail-modal');
if (!modal) return;
document.getElementById('story-detail-name').textContent = story.name;
const body = document.getElementById('story-detail-body');
body.innerHTML = '';
function addRow(label, value) {
const row = document.createElement('div');
row.className = 'meta-item';
const lbl = document.createElement('div');
lbl.className = 'meta-label';
lbl.textContent = label;
const val = document.createElement('div');
val.className = 'meta-value';
val.textContent = value || '—';
row.appendChild(lbl);
row.appendChild(val);
body.appendChild(row);
}
const badge = document.createElement('span');
badge.className = 'story-status-badge';
badge.dataset.status = story.status;
badge.textContent = storyStatusLabel(story.status);
const statusRow = document.createElement('div');
statusRow.className = 'meta-item';
const statusLbl = document.createElement('div');
statusLbl.className = 'meta-label';
statusLbl.textContent = 'Status';
statusRow.appendChild(statusLbl);
statusRow.appendChild(badge);
body.appendChild(statusRow);
addRow('Project', story.project_id);
addRow('Branch', story.branch_name);
addRow('Created', story.created_at ? new Date(story.created_at).toLocaleString() : '—');
modal.showModal();
}
function openStoryModal() {
const modal = document.getElementById('story-modal');
if (!modal) return;
// Reset form state
document.getElementById('story-goal').value = '';
const planArea = document.getElementById('story-plan-area');
planArea.innerHTML = '';
planArea.setAttribute('hidden', '');
const btnElaborate = document.getElementById('btn-story-elaborate');
btnElaborate.disabled = false;
btnElaborate.textContent = 'Elaborate with AI ✦';
const btnApprove = document.getElementById('btn-story-approve');
btnApprove.setAttribute('hidden', '');
btnApprove._elaboratedPlan = null;
// Populate project dropdown
fetch(`${BASE_PATH}/api/projects`)
.then(r => r.ok ? r.json() : [])
.then(projects => {
const sel = document.getElementById('story-project');
sel.innerHTML = '';
for (const p of projects) {
const opt = document.createElement('option');
opt.value = p.id;
opt.textContent = p.name;
sel.appendChild(opt);
}
})
.catch(() => {});
modal.showModal();
}
function renderElaboratedPlan(plan) {
const planArea = document.getElementById('story-plan-area');
planArea.innerHTML = '';
planArea.removeAttribute('hidden');
const nameEl = document.createElement('p');
nameEl.className = 'story-plan-name';
nameEl.textContent = `Story: ${plan.name}`;
planArea.appendChild(nameEl);
if (plan.branch_name) {
const branchEl = document.createElement('p');
branchEl.className = 'story-plan-branch';
branchEl.textContent = `Branch: ${plan.branch_name}`;
planArea.appendChild(branchEl);
}
if (plan.tasks && plan.tasks.length > 0) {
const tasksHeader = document.createElement('p');
tasksHeader.className = 'story-plan-section';
tasksHeader.textContent = `Tasks (${plan.tasks.length}):`;
planArea.appendChild(tasksHeader);
const taskList = document.createElement('ol');
taskList.className = 'story-plan-tasks';
for (const t of plan.tasks) {
const li = document.createElement('li');
li.textContent = t.name;
if (t.subtasks && t.subtasks.length > 0) {
const subList = document.createElement('ul');
for (const s of t.subtasks) {
const subLi = document.createElement('li');
subLi.textContent = s.name;
subList.appendChild(subLi);
}
li.appendChild(subList);
}
taskList.appendChild(li);
}
planArea.appendChild(taskList);
}
if (plan.validation && plan.validation.type) {
const valHeader = document.createElement('p');
valHeader.className = 'story-plan-section';
valHeader.textContent = `Validation: ${plan.validation.type}`;
planArea.appendChild(valHeader);
}
}
async function renderDropsPanel() {
const panel = document.querySelector('[data-panel="drops"] .drops-panel');
if (!panel) return;
panel.innerHTML = '<p class="task-meta">Loading drops…</p>';
try {
const files = await fetchDrops();
panel.innerHTML = '';
const heading = document.createElement('h3');
heading.style.padding = '1rem 1rem 0.5rem';
heading.textContent = 'Dropped Files';
panel.appendChild(heading);
if (files.length === 0) {
const empty = document.createElement('p');
empty.className = 'task-meta';
empty.style.padding = '0 1rem';
empty.textContent = 'No files dropped yet. Agents can write files to the drops directory to share them here.';
panel.appendChild(empty);
} else {
const list = document.createElement('ul');
list.style.cssText = 'list-style:none;padding:0 1rem;margin:0';
for (const f of files) {
const li = document.createElement('li');
li.style.cssText = 'padding:0.5rem 0;border-bottom:1px solid var(--border,#e5e7eb)';
const a = document.createElement('a');
a.href = `${API_BASE}/api/drops/${encodeURIComponent(f.name)}`;
a.textContent = f.name;
a.download = f.name;
a.style.cssText = 'color:var(--accent,#2563eb);text-decoration:none';
const meta = document.createElement('span');
meta.className = 'task-meta';
meta.style.cssText = 'margin-left:1rem';
meta.textContent = `${(f.size / 1024).toFixed(1)} KB`;
li.append(a, meta);
list.appendChild(li);
}
panel.appendChild(list);
}
} catch (err) {
panel.innerHTML = `<p class="task-meta" style="padding:1rem">Failed to load drops: ${err.message}</p>`;
}
}
// ── Tab switching ─────────────────────────────────────────────────────────────
function switchTab(name) {
setActiveMainTab(name);
// Update tab button active state
document.querySelectorAll('.tab').forEach(btn => {
btn.classList.toggle('active', btn.dataset.tab === name);
});
// Show/hide panels
document.querySelectorAll('[data-panel]').forEach(panel => {
if (panel.dataset.panel === name) {
panel.removeAttribute('hidden');
} else {
panel.setAttribute('hidden', '');
}
});
// Trigger immediate render for the newly active tab
poll();
}
// ── Version color ─────────────────────────────────────────────────────────────
async function applyVersionColor() {
try {
const res = await fetch(`${BASE_PATH}/api/version`);
if (!res.ok) return;
const { version } = await res.json();
// Use first 6 hex chars of version as hue seed (works for commit hashes and "dev")
const hex = version.replace(/[^0-9a-f]/gi, '').slice(0, 6).padEnd(6, '0');
const hue = Math.round((parseInt(hex, 16) / 0xffffff) * 360);
const h1 = document.querySelector('header h1');
if (h1) h1.style.color = `hsl(${hue}, 70%, 55%)`;
} catch {
// non-fatal — logo stays default color
}
}
// ── Boot ──────────────────────────────────────────────────────────────────────
if (typeof document !== 'undefined') {
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btn-start-next').addEventListener('click', function() {
handleStartNextTask(this);
});
applyVersionColor();
switchTab(getActiveMainTab());
startPolling();
connectWebSocket();
// Side panel close
document.getElementById('btn-close-panel').addEventListener('click', closeTaskPanel);
document.getElementById('task-panel-backdrop').addEventListener('click', closeTaskPanel);
// Execution logs modal close
document.getElementById('btn-close-logs').addEventListener('click', () => {
document.getElementById('logs-modal').close();
});
// Tab bar
document.querySelectorAll('.tab').forEach(btn => {
btn.addEventListener('click', () => switchTab(btn.dataset.tab));
});
// Task modal
document.getElementById('btn-new-task').addEventListener('click', openTaskModal);
document.getElementById('btn-cancel-task').addEventListener('click', closeTaskModal);
// Push notifications button
const btnNotify = document.getElementById('btn-notifications');
if (btnNotify) {
btnNotify.addEventListener('click', () => enableNotifications(btnNotify));
}
// Validate button
document.getElementById('btn-validate').addEventListener('click', async () => {
const btn = document.getElementById('btn-validate');
const resultDiv = document.getElementById('validate-result');
btn.disabled = true;
btn.textContent = 'Checking…';
try {
const payload = buildValidatePayload();
const result = await validateTask(payload);
renderValidationResult(result);
} catch (err) {
resultDiv.removeAttribute('hidden');
resultDiv.textContent = 'Validation failed: ' + err.message;
} finally {
btn.disabled = false;
btn.textContent = 'Validate Instructions';
}
});
// Draft with AI button
const btnElaborate = document.getElementById('btn-elaborate');
btnElaborate.addEventListener('click', async () => {
const prompt = document.getElementById('elaborate-prompt').value.trim();
if (!prompt) {
const form = document.getElementById('task-form');
// Remove previous error
const prev = form.querySelector('.form-error');
if (prev) prev.remove();
const errEl = document.createElement('p');
errEl.className = 'form-error';
errEl.textContent = 'Please enter a description before drafting.';
form.querySelector('.elaborate-section').appendChild(errEl);
return;
}
btnElaborate.disabled = true;
btnElaborate.textContent = 'Drafting…';
// Remove any previous errors or banners
const form = document.getElementById('task-form');
form.querySelectorAll('.form-error, .elaborate-banner').forEach(el => el.remove());
try {
const repoUrl = document.getElementById('repository-url').value.trim();
const result = await elaborateTask(prompt, repoUrl);
// Populate form fields
const f = document.getElementById('task-form');
if (result.name)
f.querySelector('[name="name"]').value = result.name;
if (result.agent && result.agent.instructions)
f.querySelector('[name="instructions"]').value = result.agent.instructions;
if (result.repository_url || result.agent?.repository_url) {
document.getElementById('repository-url').value = result.repository_url || result.agent.repository_url;
}
if (result.agent && result.agent.container_image) {
document.getElementById('container-image').value = result.agent.container_image;
}
if (result.agent && result.agent.max_budget_usd != null)
f.querySelector('[name="max_budget_usd"]').value = result.agent.max_budget_usd;
if (result.timeout)
f.querySelector('[name="timeout"]').value = result.timeout;
if (result.priority) {
const sel = f.querySelector('[name="priority"]');
if ([...sel.options].some(o => o.value === result.priority)) {
sel.value = result.priority;
}
}
// Show success banner
const banner = document.createElement('p');
banner.className = 'elaborate-banner';
banner.textContent = 'AI draft ready — review and submit.';
document.getElementById('task-form').querySelector('.elaborate-section').appendChild(banner);
// Auto-validate after elaboration
try {
const result = await validateTask(buildValidatePayload());
renderValidationResult(result);
} catch (_) {
// silent - elaboration already succeeded, validation is bonus
}
} catch (err) {
const errEl = document.createElement('p');
errEl.className = 'form-error';
errEl.textContent = `Elaboration failed: ${err.message}`;
document.getElementById('task-form').querySelector('.elaborate-section').appendChild(errEl);
} finally {
btnElaborate.disabled = false;
btnElaborate.textContent = 'Draft with AI ✦';
}
});
document.getElementById('task-form').addEventListener('submit', async e => {
e.preventDefault();
// Remove any previous error
const prev = e.target.querySelector('.form-error');
if (prev) prev.remove();
const btn = e.submitter;
btn.disabled = true;
btn.textContent = 'Creating…';
try {
const validateResult = document.getElementById('validate-result');
if (!validateResult.hasAttribute('hidden') && validateResult.dataset.clarity && validateResult.dataset.clarity !== 'clear') {
if (!window.confirm('The validator flagged issues. Create task anyway?')) {
return;
}
}
await createTask(new FormData(e.target));
} catch (err) {
const errEl = document.createElement('p');
errEl.className = 'form-error';
errEl.textContent = err.message;
e.target.appendChild(errEl);
} finally {
btn.disabled = false;
btn.textContent = 'Create & Queue';
}
});
// Story modal
const storyModal = document.getElementById('story-modal');
if (storyModal) {
document.getElementById('btn-close-story-modal').addEventListener('click', () => storyModal.close());
document.getElementById('btn-story-elaborate').addEventListener('click', async () => {
const btn = document.getElementById('btn-story-elaborate');
const goal = document.getElementById('story-goal').value.trim();
const projectId = document.getElementById('story-project').value;
if (!goal) {
const errEl = document.createElement('p');
errEl.className = 'form-error';
errEl.textContent = 'Please enter a goal before elaborating.';
storyModal.querySelector('.story-modal-body').appendChild(errEl);
return;
}
storyModal.querySelectorAll('.form-error').forEach(el => el.remove());
btn.disabled = true;
btn.textContent = 'Elaborating…';
try {
const res = await fetch(`${BASE_PATH}/api/stories/elaborate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ goal, project_id: projectId }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }));
throw new Error(err.error || res.statusText);
}
const plan = await res.json();
renderElaboratedPlan(plan);
const btnApprove = document.getElementById('btn-story-approve');
btnApprove._elaboratedPlan = { ...plan, project_id: projectId };
btnApprove.removeAttribute('hidden');
} catch (err) {
const errEl = document.createElement('p');
errEl.className = 'form-error';
errEl.textContent = `Elaboration failed: ${err.message}`;
storyModal.querySelector('.story-modal-body').appendChild(errEl);
} finally {
btn.disabled = false;
btn.textContent = 'Elaborate with AI ✦';
}
});
document.getElementById('btn-story-approve').addEventListener('click', async () => {
const btn = document.getElementById('btn-story-approve');
const plan = btn._elaboratedPlan;
if (!plan) return;
btn.disabled = true;
btn.textContent = 'Approving…';
try {
const res = await fetch(`${BASE_PATH}/api/stories/approve`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(plan),
});
if (!res.ok) {
const err = await res.json().catch(() => ({ error: res.statusText }));
throw new Error(err.error || res.statusText);
}
storyModal.close();
renderStoriesPanel();
} catch (err) {
const errEl = document.createElement('p');
errEl.className = 'form-error';
errEl.textContent = `Approve failed: ${err.message}`;
storyModal.querySelector('.story-modal-body').appendChild(errEl);
btn.disabled = false;
btn.textContent = 'Approve & Queue';
}
});
}
// Story detail modal
const storyDetailModal = document.getElementById('story-detail-modal');
if (storyDetailModal) {
document.getElementById('btn-close-story-detail').addEventListener('click', () => storyDetailModal.close());
}
});
}
|