File size: 84,492 Bytes
5255536
 
 
 
 
 
 
 
 
 
 
 
a6f9451
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5255536
 
 
 
 
 
 
 
 
806c397
 
 
5255536
 
 
 
 
 
806c397
 
 
 
 
 
 
 
 
5255536
 
 
 
 
 
 
 
806c397
 
 
5255536
 
806c397
 
 
 
 
5255536
98cf86d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a16e5a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5255536
 
 
 
 
 
 
 
806c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5255536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac40945
 
 
 
 
 
 
5255536
a16e5a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5255536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac40945
 
5255536
 
ac40945
 
 
 
 
5255536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7554553
 
 
 
 
5255536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3abeb82
 
 
 
 
98cf86d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5255536
 
806c397
5255536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
806c397
 
 
 
 
5255536
 
 
 
 
 
 
 
 
 
 
 
806c397
 
5255536
 
 
 
 
806c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5255536
 
806c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5255536
 
806c397
5255536
ac40945
 
98cf86d
a16e5a2
ac40945
5255536
 
3abeb82
 
ac40945
 
a16e5a2
 
 
 
3abeb82
a6f9451
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5255536
 
3abeb82
ac40945
3abeb82
5255536
ac40945
 
5255536
ac40945
5255536
ac40945
5255536
 
 
 
 
ac40945
 
5255536
 
ac40945
5255536
 
 
8af7be8
5255536
 
ac40945
 
5255536
 
ac40945
 
5255536
 
 
 
 
 
 
 
 
 
 
 
ac40945
5255536
 
 
ac40945
5255536
 
 
ac40945
5255536
 
 
 
 
 
 
 
 
ac40945
5255536
 
ac40945
 
 
 
5255536
 
 
 
 
 
 
 
 
ac40945
5255536
 
 
 
ac40945
5255536
 
 
ac40945
5255536
 
 
 
ac40945
 
5255536
 
98cf86d
 
 
a16e5a2
 
 
 
 
98cf86d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5255536
 
 
 
 
 
 
 
 
 
806c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac40945
3abeb82
a16e5a2
 
 
 
98cf86d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8af7be8
 
 
 
98cf86d
5255536
 
3abeb82
5255536
 
 
 
 
 
 
 
 
 
 
ac40945
5255536
 
 
 
 
 
 
 
 
806c397
 
 
5255536
 
 
ac40945
3abeb82
a16e5a2
 
 
5255536
 
 
806c397
 
 
 
 
98cf86d
 
 
 
a16e5a2
 
 
98cf86d
 
 
 
 
 
5255536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3abeb82
5255536
3abeb82
 
5255536
 
8af7be8
ac40945
 
5255536
ac40945
 
 
5255536
 
ac40945
5255536
 
 
 
98cf86d
a16e5a2
 
5255536
 
 
 
 
ac40945
5255536
 
 
3abeb82
ac40945
 
3abeb82
 
 
 
 
 
 
 
ac40945
 
3abeb82
 
 
5255536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac40945
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3abeb82
a6f9451
3abeb82
a6f9451
3abeb82
ac40945
 
3abeb82
ac40945
3abeb82
a6f9451
3abeb82
 
 
 
 
a16e5a2
 
3abeb82
 
ac40945
a16e5a2
 
 
 
 
 
 
3abeb82
 
 
 
 
 
 
 
 
a6f9451
3abeb82
ac40945
3abeb82
a6f9451
a16e5a2
3abeb82
98cf86d
3abeb82
 
a6f9451
a16e5a2
 
 
3abeb82
 
 
ac40945
3abeb82
98cf86d
 
 
a16e5a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3abeb82
 
98cf86d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8af7be8
 
98cf86d
 
 
 
 
 
 
 
 
 
 
 
 
8af7be8
 
 
 
98cf86d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a16e5a2
 
 
98cf86d
 
 
 
 
 
 
 
 
 
 
 
 
8af7be8
 
 
 
98cf86d
 
 
 
 
 
8af7be8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98cf86d
 
 
 
 
 
 
 
 
 
 
 
8af7be8
 
 
98cf86d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8af7be8
98cf86d
 
 
 
 
 
 
 
 
 
8af7be8
98cf86d
 
 
 
 
 
 
 
 
8af7be8
 
 
 
 
98cf86d
 
 
 
 
 
 
 
 
 
 
 
5255536
 
 
 
 
806c397
 
 
 
 
5255536
 
 
 
 
 
 
 
 
 
ac40945
5255536
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ac40945
5255536
 
 
 
 
 
ac40945
5255536
 
 
 
 
 
 
 
 
98cf86d
 
 
 
 
 
 
 
 
 
 
 
 
 
5255536
 
 
ac40945
5255536
 
 
 
 
 
ac40945
5255536
 
 
 
 
 
 
 
ac40945
5255536
 
 
806c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5255536
ac40945
5255536
 
 
 
 
 
 
 
 
 
806c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5255536
 
 
 
 
806c397
5255536
 
 
 
806c397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5255536
 
ac40945
 
 
 
 
 
 
5255536
 
3abeb82
 
 
ac40945
3abeb82
 
5255536
 
 
 
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
import { ControlWavePlugin } from '../plugin-loader.js';

const STYLE_ID = 'stable-signer-plugin-style';
const toInt = (value, fallback) => {
    const parsed = parseInt(value, 10);
    return Number.isNaN(parsed) ? fallback : parsed;
};
const toFloat = (value, fallback) => {
    const parsed = parseFloat(value);
    return Number.isNaN(parsed) ? fallback : parsed;
};

const normalizePromptText = (raw) => {
    if (!raw) return "";
    const text = raw.trim();
    const doubleQuoted = text.match(/"([^"]{2,})"/);
    if (doubleQuoted) {
        return doubleQuoted[1].trim();
    }
    const singleQuoted = text.match(/'([^']{2,})'/);
    if (singleQuoted) {
        return singleQuoted[1].trim();
    }
    const forClause = text.match(/\bfor\s+([^?!.]+)[?!.]?$/i);
    if (forClause && forClause[1].trim().length > 0) {
        return forClause[1].trim();
    }
    return text;
};

function ensureStyles() {
    if (document.getElementById(STYLE_ID)) {
        return;
    }

    const style = document.createElement('style');
    style.id = STYLE_ID;
    style.textContent = `
        .stable-signer-root {
            display: grid;
            grid-template-columns: minmax(0, 1.5fr) minmax(0, 1fr);
            align-items: start;
            gap: 20px;
            width: 100%;
            height: 100%;
            padding: 20px;
            box-sizing: border-box;
        }
        .stable-signer-left-col {
            display: flex;
            flex-direction: column;
            gap: 20px;
            min-width: 0;
            width: 100%;
            justify-self: stretch;
        }
        .stable-signer-panel {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 16px rgba(15, 23, 42, 0.08);
            padding: 20px;
            display: flex;
            flex-direction: column;
        }
        .stable-signer-left {
            min-width: 0;
            align-self: start;
            width: 100%;
        }
        .stable-signer-right {
            min-width: 0;
        }
        .stable-signer-bottom {
            min-width: 0;
            width: 100%;
        }
        .stable-text-playground {
            grid-column: 1 / -1;
            min-width: 0;
        }
        .stable-text-playground .stable-reading-area {
            min-height: 180px;
            font-size: 16px;
            line-height: 1.65;
        }
        .stable-text-playground-title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            margin-bottom: 10px;
        }
        .stable-text-playground-title h3 {
            margin: 0;
            font-size: 16px;
            color: #0f172a;
        }
        .stable-playground-actions {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            gap: 10px;
            flex-wrap: wrap;
        }
        .stable-playground-actions label {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            margin: 0;
            font-size: 13px;
            font-weight: 600;
            color: #334155;
        }
        .stable-playground-actions input {
            width: auto;
            margin: 0;
        }
        .stable-playground-actions button {
            padding: 6px 10px;
            white-space: nowrap;
        }
        .stable-video-frame {
            position: relative;
            width: 100%;
            padding-top: 56.25%;
            background: #0f172a;
            border-radius: 10px;
            overflow: hidden;
        }
        .stable-selected-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            margin-bottom: 12px;
            font-size: 13px;
            color: #0f172a;
        }
        .stable-selected-row strong {
            font-weight: 700;
        }
        .stable-selected-row span {
            color: #334155;
        }
        .stable-refine-grid {
            margin-top: 12px;
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        .stable-output-section {
            margin-top: 12px;
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        .stable-output-section h4 {
            margin: 8px 0 0;
            font-size: 14px;
            color: #0f172a;
        }
        .stable-video-frame video {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: contain;
            background: #0f172a;
        }
        .stable-video-placeholder {
            position: absolute;
            inset: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #94a3b8;
            font-size: 15px;
            text-align: center;
            padding: 20px;
        }
        .stable-video-controls {
            margin-top: 15px;
            display: flex;
            gap: 10px;
            align-items: center;
        }
        .stable-video-controls select,
        .stable-video-controls button {
            flex: 1;
        }
        .stable-meta {
            font-family: "JetBrains Mono", "Fira Code", monospace;
            background: #0f172a;
            color: #e2e8f0;
            padding: 12px;
            border-radius: 8px;
            margin-top: 15px;
            min-height: 60px;
            font-size: 13px;
        }
        .stable-control-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            margin-bottom: 15px;
        }
        .stable-control-actions {
            display: flex;
            gap: 10px;
            flex: 1;
        }
        .stable-control-actions button {
            flex: 1;
        }
        .stable-translation-options {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            margin-top: 8px;
            font-size: 13px;
            color: #334155;
        }
        .stable-translation-options label {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            margin: 0;
            font-weight: 600;
        }
        .stable-translation-options input {
            width: auto;
            margin: 0;
        }
        .stable-translation-options button {
            white-space: nowrap;
            padding: 6px 10px;
        }
        .stable-status-chip {
            font-size: 13px;
            padding: 6px 12px;
            border-radius: 999px;
            background: #e2e8f0;
            color: #0f172a;
        }
        .stable-form-row {
            display: flex;
            gap: 12px;
            margin-bottom: 15px;
        }
        .stable-form-row .form-group {
            flex: 1;
        }
        .form-group label {
            font-size: 13px;
            font-weight: 600;
            display: block;
            margin-bottom: 6px;
            color: #0f172a;
        }
        .form-group textarea,
        .form-group input,
        .form-group select {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #cbd5f5;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.2s, box-shadow 0.2s;
        }
        .form-group textarea {
            min-height: 110px;
            resize: vertical;
        }
        .form-group input:focus,
        .form-group textarea:focus,
        .form-group select:focus {
            outline: none;
            border-color: #6366f1;
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
        }
        details.stable-advanced {
            margin-top: 10px;
            border: 1px solid #cbd5f5;
            border-radius: 10px;
            padding: 12px;
        }
        details.stable-advanced summary {
            cursor: pointer;
            font-weight: 600;
            color: #1d4ed8;
        }
        .stable-advanced-grid {
            margin-top: 12px;
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
        }
        .stable-advanced-grid .form-group,
        .stable-advanced-grid .stable-switch {
            flex: 1 1 calc(50% - 12px);
            min-width: 180px;
        }
        .stable-switch {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 13px;
        }
        .stable-switch input {
            width: auto;
        }
        .stable-logs {
            margin-top: 18px;
        }
        .stable-logs pre {
            background: #0f172a;
            color: #cbd5f5;
            border-radius: 8px;
            padding: 14px;
            font-size: 12px;
            max-height: 220px;
            overflow: auto;
            width: 100%;
            max-width: 100%;
            white-space: pre-wrap;
            word-break: break-word;
            overflow-wrap: anywhere;
        }
        .btn.primary {
            background: linear-gradient(120deg, #6366f1, #8b5cf6);
            border: none;
            color: #fff;
            border-radius: 10px;
            padding: 10px 18px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.15s ease, box-shadow 0.2s ease;
        }
        .btn.primary:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            box-shadow: none;
        }
        .btn.primary:not(:disabled):hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(99, 102, 241, 0.2);
        }
        .btn.secondary {
            background: #e2e8f0;
            border: none;
            color: #0f172a;
            border-radius: 8px;
            padding: 8px 14px;
            font-weight: 600;
            cursor: pointer;
        }
        .stable-inline {
            display: flex;
            gap: 10px;
            align-items: center;
        }
        .stable-hint {
            margin-top: 6px;
            font-size: 12px;
            color: #475569;
        }
        .stable-reading-area {
            min-height: 120px;
            border: 1px solid #cbd5f5;
            border-radius: 8px;
            padding: 12px;
            background: #f8fafc;
            color: #0f172a;
            line-height: 1.55;
            font-size: 14px;
            user-select: text;
        }
        .stable-reading-area:focus {
            outline: none;
            border-color: #6366f1;
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
        }

        .stable-dialogue-area {
            min-height: 360px;
            border: 1px solid #d7b98a;
            border-radius: 10px;
            padding: 18px;
            background:
                linear-gradient(135deg, rgba(255, 255, 255, 0.58), rgba(255, 248, 236, 0.2)),
                repeating-linear-gradient(90deg, #f5e3c4 0, #f5e3c4 18px, #efd6ad 19px, #efd6ad 36px);
            color: #2f2417;
            line-height: 1.62;
            font-size: 15px;
            user-select: text;
            box-shadow: inset 0 1px 0 rgba(255,255,255,0.55);
        }
        .stable-dialogue-turn {
            max-width: 82%;
            margin: 12px 0;
            padding: 14px 16px;
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(74, 53, 28, 0.12);
            white-space: normal;
        }
        .stable-dialogue-turn.question {
            margin-left: auto;
            background: rgba(255, 255, 255, 0.82);
            border: 1px solid rgba(185, 139, 73, 0.38);
        }
        .stable-dialogue-turn.answer {
            margin-right: auto;
            background: rgba(255, 250, 240, 0.9);
            border: 1px solid rgba(161, 113, 48, 0.42);
        }
        .stable-dialogue-speaker {
            display: inline-block;
            margin-bottom: 8px;
            padding: 3px 8px;
            border-radius: 999px;
            background: #8b5e2e;
            color: #fff8ed;
            font-size: 12px;
            font-weight: 700;
        }
        .stable-dialogue-turn p {
            margin: 8px 0;
        }
        .stable-dialogue-turn ul {
            margin: 8px 0 8px 20px;
            padding: 0;
        }
        .stable-dialogue-turn li {
            margin: 4px 0;
        }
        .stable-selection-popover {
            position: fixed;
            right: 22px;
            bottom: 22px;
            z-index: 9999;
            display: none;
            width: min(380px, calc(100vw - 44px));
            border-radius: 12px;
            background: #0f172a;
            color: #e2e8f0;
            box-shadow: 0 18px 40px rgba(15, 23, 42, 0.35);
            overflow: hidden;
        }
        .stable-selection-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            padding: 10px 12px;
            border-bottom: 1px solid rgba(148, 163, 184, 0.25);
            font-size: 13px;
            font-weight: 700;
        }
        .stable-selection-header button,
        .stable-selection-actions button {
            border: none;
            border-radius: 8px;
            padding: 7px 10px;
            font-size: 12px;
            font-weight: 700;
            cursor: pointer;
            background: #e2e8f0;
            color: #0f172a;
        }
        .stable-selection-body {
            padding: 12px;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        .stable-selection-text {
            max-height: 66px;
            overflow: auto;
            color: #cbd5e1;
            font-size: 12px;
            line-height: 1.45;
            border-left: 3px solid #6366f1;
            padding-left: 8px;
        }
        .stable-mini-video-frame {
            position: relative;
            width: 100%;
            aspect-ratio: 1 / 1;
            background: #020617;
            border-radius: 8px;
            overflow: hidden;
        }
        .stable-mini-video-frame video,
        .stable-mini-video-frame canvas {
            position: absolute;
            inset: 0;
            width: 100%;
            height: 100%;
            object-fit: contain;
            background: #020617;
        }
        .stable-mini-video-frame canvas {
            display: none;
        }
        .stable-mini-placeholder {
            position: absolute;
            inset: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #94a3b8;
            font-size: 13px;
            text-align: center;
            padding: 16px;
        }
        .stable-selection-status {
            min-height: 18px;
            color: #cbd5e1;
            font-size: 12px;
            overflow-wrap: anywhere;
        }
        .stable-selection-actions {
            display: flex;
            gap: 8px;
        }
        .stable-selection-actions button {
            flex: 1;
        }
        @media (max-width: 1200px) {
            .stable-signer-root {
                grid-template-columns: 1fr;
            }
        }
    `;
    document.head.appendChild(style);
}

export default class StableSignerPlugin extends ControlWavePlugin {
    constructor() {
        super({
            id: 'stable-signer',
            name: 'StableSigner',
            version: '1.0.0',
            author: 'StableSigner',
            description: 'Prompt/Text → Gloss → Pose Video',
            order: 25,
            needsViser: false
        });
        this.state = {
            status: 'Idle',
            lastVideo: null
        };
        this.currentVideoObjectUrl = null;
        this.refineVideoObjectUrl = null;
        this.selectedPosePath = null;
        this.refineJobId = null;
        this.refineLogCursor = 0;
        this.refinePollingTimer = null;
    }

    async render(container) {
        ensureStyles();
        this.container = container;
        container.classList.add('tab-content', 'active');
        container.style.display = 'flex';
        container.innerHTML = this.renderTemplate();
        this.cacheElements(container);
        this.attachEvents();
        this.updateStatus('Idle');
        await this.refreshRecentVideos();
        await this.refreshStage1Videos();
        await this.refreshStage2Videos();
    }

    renderTemplate() {
        return `
            <div class="stable-signer-root">
                <div class="stable-signer-left-col">
                    <div class="stable-signer-left stable-signer-panel">
                        <div class="stable-video-frame">
                            <video id="stable-video" controls playsinline loop muted></video>
                            <div id="stable-video-placeholder" class="stable-video-placeholder">
                                Generated pose video will appear here
                            </div>
                        </div>
                        <div class="stable-video-controls">
                            <select id="stable-video-select">
                                <option value="">Select recently generated video</option>
                            </select>
                            <button id="stable-video-refresh" class="btn secondary">Refresh</button>
                        </div>
                        <div class="stable-meta" id="stable-video-meta">
                            Waiting for generated video...
                        </div>
                    </div>
                    <div class="stable-signer-bottom stable-signer-panel">
                        <div class="stable-control-header">
                            <h3 style="margin:0;font-size:16px;">Render / Refine Output</h3>
                            <span class="stable-status-chip">Preview</span>
                        </div>
                        <div class="stable-selected-row">
                            <div>
                                <strong>Chosen Pose Video:</strong>
                                <span id="stable-selected-name">None</span>
                            </div>
                            <button id="stable-generate-refine" class="btn primary">Generate Refine Video</button>
                        </div>
                        <div class="stable-refine-grid">
                            <div class="stable-form-row">
                                <div class="form-group">
                                    <label>Ref image path</label>
                                    <input id="stable-refine-ref-image" type="text" placeholder="ref_img_dict/man.jpg">
                                </div>
                                <div class="form-group">
                                    <label>GPU (optional)</label>
                                    <input id="stable-refine-gpu" type="text" placeholder="auto">
                                </div>
                            </div>
                            <div class="stable-form-row">
                                <div class="form-group">
                                    <label>Ref CFG</label>
                                    <input id="stable-refine-ref-cfg" type="number" step="0.1" value="2.5">
                                </div>
                                <div class="form-group">
                                    <label>Pose CFG</label>
                                    <input id="stable-refine-pose-cfg" type="number" step="0.1" value="1.5">
                                </div>
                            </div>
                            <div class="stable-form-row">
                                <div class="form-group">
                                    <label>Stage1 output dir</label>
                                    <input id="stable-refine-stage1-out" type="text" value="generated_sign_video">
                                </div>
                                <div class="form-group">
                                    <label>Stage2 output dir</label>
                                    <input id="stable-refine-stage2-out" type="text" value="generated_sign_video_refine">
                                </div>
                            </div>
                        </div>
                        <div class="stable-output-section">
                            <h4>Stage 1 Output (generated_sign_video)</h4>
                            <div class="stable-video-controls">
                                <select id="stable-stage1-select">
                                    <option value="">Select stage1 output video</option>
                                </select>
                                <button id="stable-stage1-refresh" class="btn secondary">Refresh</button>
                            </div>
                            <h4>Stage 2 Output (generated_sign_video_refine)</h4>
                            <div class="stable-video-controls">
                                <select id="stable-stage2-select">
                                    <option value="">Select stage2 output video</option>
                                </select>
                                <button id="stable-stage2-refresh" class="btn secondary">Refresh</button>
                            </div>
                            <div class="stable-video-frame" style="padding-top: 56.25%;">
                                <video id="stable-output-video" controls playsinline loop muted></video>
                                <div id="stable-output-placeholder" class="stable-video-placeholder">
                                    Rendered/refined video will appear here
                                </div>
                            </div>
                            <div class="stable-meta" id="stable-output-meta">
                                Waiting for refine output...
                            </div>
                        </div>
                        <div class="stable-logs">
                            <label>Render / Refine logs</label>
                            <pre id="stable-refine-logs">(waiting for refine...)</pre>
                        </div>
                    </div>
                </div>
                <div class="stable-signer-right stable-signer-panel">
                    <div class="stable-control-header">
                        <div class="stable-control-actions">
                            <button id="stable-prewarm" class="btn secondary">Prewarm</button>
                            <button id="stable-translate" class="btn secondary">Text → Available Gloss</button>
                            <button id="stable-semantic-demo" class="btn secondary">Semantic Demo</button>
                        </div>
                        <span class="stable-status-chip" id="stable-status">Idle</span>
                    </div>
                    <div class="form-group">
                        <label>Prompt / Text</label>
                        <textarea id="stable-prompt-text" placeholder="Describe the action or context; the system will translate it to gloss."></textarea>
                        <div class="stable-hint">Input text auto-translates and fills the uppercase gloss field below (still editable).</div>
                        <div class="stable-translation-options">
                            <label><input type="checkbox" id="stable-semantic-gloss"> Semantic constrained gloss</label>
                            <span>Uses conservative synonym fallback; output remains limited to available poses.</span>
                        </div>
                        <div class="form-group" style="margin-top:8px;font-size:13px;color:#475569;">
                            <div>Prompt samples (picked from the latest prompt2gloss eval logs with strongest gloss matches):</div>
                            <div>1. Can you provide instruction on the sign language for &ldquo;You&rsquo;re going to hit it just a little more behind.&rdquo;?</div>
                            <div>2. Can you show me how &ldquo;Then what I like to do is go on with my fiber pliable paste.&rdquo; appears in sign language?</div>
                            <div>3. How is &ldquo;A baby snake might shed every week to an adult snake that might shed once a year so it really varies as to how often they&rsquo;re going to shed their skin because it depends on how much they are growing.&rdquo; signed?</div>
                            <div>4. How would you express &ldquo;You check the pressure of the tires and to change tire pressures every time you come in, depending on track conditions, the track continues to change every single time you go out there.&rdquo; in sign language?</div>
                            <div style="margin-top:6px;">Text samples (same sentences without the meta question):</div>
                            <div>1. You&rsquo;re going to hit it just a little more behind.</div>
                            <div>2. Then what I like to do is go on with my fiber pliable paste.</div>
                            <div>3. A baby snake might shed every week to an adult snake that might shed once a year so it really varies as to how often they&rsquo;re going to shed their skin because it depends on how much they are growing.</div>
                            <div>4. &ldquo;You check the pressure of the tires and to change tire pressures every time you come in, depending on track conditions, the track continues to change every single time you go out there.&rdquo;</div>
                            <div style="margin-top:6px;">Ground-truth gloss samples (for reference):</div>
                            <div>1. <strong>TO HIT A MORE BEHIND</strong></div>
                            <div>2. <strong>THEN WHAT I LIKE TO GO ON WITH MY</strong></div>
                            <div>3. <strong>A BABY SNAKE EVERY WEEK TO ADULT THAT ONCE YEAR REALLY HOW OFTEN THEIR SKIN BECAUSE ON MUCH THEY</strong></div>
                            <div>4. <strong>YOU CHECK PRESSURE AND TO CHANGE EVERY TIME COME IN ON SINGLE GO OUT THERE</strong></div>
                        </div>
                    </div>
                    <div class="form-group" style="margin-top:4px;">
                        <button id="stable-generate" class="btn primary" style="width:100%;">Generate Pose Video</button>
                    </div>
                    <div class="form-group">
                        <label>Gloss sequence (auto generated, editable)</label>
                        <textarea id="stable-gloss" placeholder="Example: I NEED HELP PLEASE"></textarea>
                        <div class="form-group" style="margin-top:8px;font-size:13px;color:#475569;">
                            <div>Examples:</div>
                            <div>1. HELLO WORLD</div>
                            <div>2. I NEED HELP PLEASE</div>
                            <div>3. TODAY WEATHER NICE</div>
                            <div>4. I GO SCHOOL LATER</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Reuse existing video (path or filename, optional)</label>
                        <input id="stable-existing-video" type="text" placeholder="e.g., generated_pose_video/EXAMPLE.mp4">
                    </div>
                    <details class="stable-advanced">
                        <summary>Advanced Settings</summary>
                        <div class="stable-advanced-grid">
                            <div class="form-group">
                                <label>FPS</label>
                                <input id="stable-fps" type="number" min="5" max="60" value="25">
                            </div>
                            <div class="form-group">
                                <label>Width</label>
                                <input id="stable-width" type="number" min="256" max="1024" value="512">
                            </div>
                            <div class="form-group">
                                <label>Height</label>
                                <input id="stable-height" type="number" min="256" max="1024" value="512">
                            </div>
                            <div class="form-group">
                                <label>Smoothing</label>
                                <select id="stable-smoothing">
                                    <option value="none">None</option>
                                    <option value="fade">Fade</option>
                                    <option value="blend">Blend</option>
                                    <option value="pause">Pause</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Smoothing Frames</label>
                                <input id="stable-smoothing-frames" type="number" min="0" max="60" value="0">
                            </div>
                            <div class="form-group">
                                <label>NPZ Interp Frames</label>
                                <input id="stable-npz" type="number" min="0" max="60" value="20">
                            </div>
                            <div class="form-group">
                                <label>Scale X</label>
                                <input id="stable-scale-x" type="number" step="0.1" value="1.4">
                            </div>
                            <div class="form-group">
                                <label>Scale Y</label>
                                <input id="stable-scale-y" type="number" step="0.1" value="1.5">
                            </div>
                            <div class="form-group">
                                <label>Draw Style</label>
                                <select id="stable-draw-style">
                                    <option value="openpose">OpenPose</option>
                                    <option value="controlnext">ControlNeXt</option>
                                </select>
                            </div>
                            <div class="form-group">
                                <label>Draw Confidence Threshold</label>
                                <input id="stable-draw-threshold" type="number" min="0" max="1" step="0.05" value="0.6">
                            </div>
                            <div class="form-group">
                                <label>Max Candidates</label>
                                <input id="stable-max-candidates" type="number" min="0" value="10">
                            </div>
                            <div class="form-group">
                                <label>Max New Tokens</label>
                                <input id="stable-max-new" type="number" min="8" max="256" value="64">
                            </div>
                            <div class="form-group">
                                <label>Reference image path (optional)</label>
                                <input id="stable-ref-image" type="text" placeholder="ref_img_dict/example.png">
                            </div>
                            <label class="stable-switch">
                                <input type="checkbox" id="stable-normalize" checked>
                                Normalize pose
                            </label>
                            <label class="stable-switch">
                                <input type="checkbox" id="stable-hide-torso">
                                Hide torso lines
                            </label>
                        </div>
                    </details>
                    <div class="stable-logs">
                        <label>Log output</label>
                        <pre id="stable-logs">(waiting for task...)</pre>
                    </div>
                </div>
                <div class="stable-text-playground stable-signer-panel">
                    <div class="stable-text-playground-title">
                        <h3>Selection Translation Playground</h3>
                        <div class="stable-playground-actions">
                            <label><input type="checkbox" id="stable-selection-semantic-gloss" checked> Semantic gloss</label>
                            <button id="stable-selection-semantic-demo" type="button" class="btn secondary">Semantic Demo</button>
                            <span class="stable-status-chip">Select text to translate</span>
                        </div>
                    </div>
                    <div id="stable-selection-template" class="stable-reading-area stable-dialogue-area" tabindex="0" contenteditable="true">
                        <div class="stable-dialogue-turn question">
                            <span class="stable-dialogue-speaker">User</span>
                            <p>Do native signers have difficulty reading written text?</p>
                        </div>
                        <div class="stable-dialogue-turn answer">
                            <span class="stable-dialogue-speaker">Assistant</span>
                            <p>Yes. This is a well-studied phenomenon. Deaf people whose first language is a sign language often do face difficulty when reading written language. The reason is not cognitive ability. It is a matter of linguistics and language acquisition. Written language is essentially a visual encoding of spoken language. Hearing children already have years of spoken-language immersion before reading; deaf children whose first language is ASL, CSL, or another sign language often approach English or Chinese as a second language, and one without accessible spoken-language support. Empirical work in the United States, including Gallaudet-related longitudinal research, has often found deaf high-school graduates around a fourth-grade median English reading level. Reports in mainland China similarly show delays in written Chinese, especially with function words, passive constructions, complex clauses, metaphor, idioms, and forms that depend on spoken-language and pragmatic experience. There is large variation: early sign-language exposure and bilingual education, sign language as L1 and written language as L2, generally produce much better reading outcomes. This is a core motivation for SLP and SLT: text-to-sign generation addresses a real accessibility gap in news, public notices, medical instructions, and educational materials.</p>
                        </div>
                        <div class="stable-dialogue-turn question">
                            <span class="stable-dialogue-speaker">User</span>
                            <p>But why do they not just learn text? Their parents usually know English text. In theory, should they not learn text first rather than sign language?</p>
                        </div>
                        <div class="stable-dialogue-turn answer">
                            <span class="stable-dialogue-speaker">Assistant</span>
                            <p>That intuition is natural, but it depends on a false premise. Parents knowing text does not mean a child can acquire text from them. Writing is not acquired directly; it is a second-order system built on top of an already acquired natural language. Hearing children do not learn text first. They acquire spoken language from age zero to five, then school teaches them to map that known language onto symbols. Deaf children often lack full access to that underlying natural language. You cannot skip language and teach writing directly. The critical-period literature, including work by Mayberry and Newport, shows that early complete language input is crucial; language deprivation can permanently harm later language, second-language learning, and reading. Sign language is not a competitor to reading. It is the foundation for reading. Parents also cannot provide rich language immersion through print: writing apple and pointing to an apple is sparse, slow, and abstract compared with real-time language in daily life. History already tried suppressing sign language through oralism, especially after the 1880 Milan Conference, and the results were disastrous. The correct causal chain is this: deaf children do not read poorly because they learned sign language. Deaf children with early access to a full sign language often learn written language better; those deprived of sign language and forced to rely on incomplete speech or print usually have the worst text outcomes. For SLP and SLT, automatic text-to-sign generation is not a lazy compromise. It provides information through an accessible natural-language modality.</p>
                        </div>
                    </div>
                    <div id="stable-selection-popover" class="stable-selection-popover">
                        <div class="stable-selection-header">
                            <span>Sign Translation</span>
                            <button id="stable-selection-close" type="button">Close</button>
                        </div>
                        <div class="stable-selection-body">
                            <div id="stable-selection-text" class="stable-selection-text"></div>
                            <div class="stable-mini-video-frame">
                                <video id="stable-selection-video" controls playsinline loop muted></video>
                                    <canvas id="stable-selection-canvas" width="512" height="512"></canvas>
                                <div id="stable-selection-placeholder" class="stable-mini-placeholder">Select English text to generate a sign pose video.</div>
                            </div>
                            <div id="stable-selection-status" class="stable-selection-status">Waiting for selection...</div>
                            <div class="stable-selection-actions">
                                <button id="stable-selection-translate" type="button">Regenerate</button>
                            </div>
                        </div>
                    </div>
                    <div class="stable-hint">This is the browser-plugin style test area: select any text, then the floating skeleton signer appears at the bottom-right.</div>
                </div>
            </div>
        `;
    }

    cacheElements(container) {
        this.videoEl = container.querySelector('#stable-video');
        this.videoPlaceholder = container.querySelector('#stable-video-placeholder');
        this.videoSelect = container.querySelector('#stable-video-select');
        this.videoRefreshBtn = container.querySelector('#stable-video-refresh');
        this.videoMeta = container.querySelector('#stable-video-meta');
        this.selectedName = container.querySelector('#stable-selected-name');
        this.generateRefineBtn = container.querySelector('#stable-generate-refine');
        this.refineRefImageInput = container.querySelector('#stable-refine-ref-image');
        this.refineGpuInput = container.querySelector('#stable-refine-gpu');
        this.refineRefCfgInput = container.querySelector('#stable-refine-ref-cfg');
        this.refinePoseCfgInput = container.querySelector('#stable-refine-pose-cfg');
        this.refineStage1OutInput = container.querySelector('#stable-refine-stage1-out');
        this.refineStage2OutInput = container.querySelector('#stable-refine-stage2-out');
        this.stage1Select = container.querySelector('#stable-stage1-select');
        this.stage1RefreshBtn = container.querySelector('#stable-stage1-refresh');
        this.stage2Select = container.querySelector('#stable-stage2-select');
        this.stage2RefreshBtn = container.querySelector('#stable-stage2-refresh');
        this.outputVideoEl = container.querySelector('#stable-output-video');
        this.outputPlaceholder = container.querySelector('#stable-output-placeholder');
        this.outputMeta = container.querySelector('#stable-output-meta');
        this.refineLogsPre = container.querySelector('#stable-refine-logs');
        this.prewarmBtn = container.querySelector('#stable-prewarm');
        this.translateBtn = container.querySelector('#stable-translate');
        this.semanticDemoBtn = container.querySelector('#stable-semantic-demo');
        this.semanticGlossCheckbox = container.querySelector('#stable-semantic-gloss');
        this.selectionSemanticCheckbox = container.querySelector('#stable-selection-semantic-gloss');
        this.selectionSemanticDemoBtn = container.querySelector('#stable-selection-semantic-demo');
        this.selectionTemplate = container.querySelector('#stable-selection-template');
        this.selectionPopover = container.querySelector('#stable-selection-popover');
        this.selectionTranslateBtn = container.querySelector('#stable-selection-translate');
        this.selectionCloseBtn = container.querySelector('#stable-selection-close');
        this.selectionTextEl = container.querySelector('#stable-selection-text');
        this.selectionVideoEl = container.querySelector('#stable-selection-video');
        this.selectionCanvas = container.querySelector('#stable-selection-canvas');
        this.selectionCanvasCtx = this.selectionCanvas ? this.selectionCanvas.getContext('2d') : null;
        this.selectionHasFrame = false;
        this.selectionPlaceholder = container.querySelector('#stable-selection-placeholder');
        this.selectionStatus = container.querySelector('#stable-selection-status');
        this.selectedTemplateText = '';
        this.selectionGenerationTimer = null;
        this.selectionGenerationInFlight = false;
        this.selectionStreamPollingTimer = null;
        this.selectionStreamCursor = 0;
        this.selectionStreamFrameQueue = [];
        this.selectionStreamPlaybackTimer = null;
        this.selectionStreamPlaybackFps = 25;
        this.selectionPendingFinalVideoUrl = null;
        this.lastGeneratedSelection = '';
        this.generateBtn = container.querySelector('#stable-generate');
        this.statusChip = container.querySelector('#stable-status');
        this.promptTextInput = container.querySelector('#stable-prompt-text');
        this.glossInput = container.querySelector('#stable-gloss');
        this.existingInput = container.querySelector('#stable-existing-video');
        this.fpsInput = container.querySelector('#stable-fps');
        this.widthInput = container.querySelector('#stable-width');
        this.heightInput = container.querySelector('#stable-height');
        this.smoothingSelect = container.querySelector('#stable-smoothing');
        this.smoothingFramesInput = container.querySelector('#stable-smoothing-frames');
        this.npzInput = container.querySelector('#stable-npz');
        this.scaleXInput = container.querySelector('#stable-scale-x');
        this.scaleYInput = container.querySelector('#stable-scale-y');
        this.drawStyleSelect = container.querySelector('#stable-draw-style');
        this.drawThresholdInput = container.querySelector('#stable-draw-threshold');
        this.maxCandidatesInput = container.querySelector('#stable-max-candidates');
        this.maxNewTokensInput = container.querySelector('#stable-max-new');
        this.refImageInput = container.querySelector('#stable-ref-image');
        this.normalizeCheckbox = container.querySelector('#stable-normalize');
        this.hideTorsoCheckbox = container.querySelector('#stable-hide-torso');
        this.logsPre = container.querySelector('#stable-logs');
        if (this.videoEl) {
            this.videoEl.style.display = 'none';
        }
        if (this.outputVideoEl) {
            this.outputVideoEl.style.display = 'none';
        }
    }

    attachEvents() {
        this.prewarmBtn.addEventListener('click', () => this.handlePrewarm());
        this.translateBtn.addEventListener('click', () => this.handleTranslate());
        if (this.semanticDemoBtn) {
            this.semanticDemoBtn.addEventListener('click', () => this.handleSemanticDemo());
        }
        this.generateBtn.addEventListener('click', () => this.handleGenerate());
        this.videoRefreshBtn.addEventListener('click', () => this.refreshRecentVideos());
        this.videoSelect.addEventListener('change', () => this.handleRecentSelection());
        this.generateRefineBtn.addEventListener('click', () => this.handleGenerateRefine());
        this.stage1RefreshBtn.addEventListener('click', () => this.refreshStage1Videos());
        this.stage2RefreshBtn.addEventListener('click', () => this.refreshStage2Videos());
        this.stage1Select.addEventListener('change', () => this.handleStage1Selection());
        this.stage2Select.addEventListener('change', () => this.handleStage2Selection());
        if (this.selectionTemplate) {
            this.selectionTemplate.addEventListener('mouseup', () => this.handleTemplateSelection());
            this.selectionTemplate.addEventListener('keyup', () => this.handleTemplateSelection());
        }
        if (this.selectionSemanticDemoBtn) {
            this.selectionSemanticDemoBtn.addEventListener('click', () => this.handleSelectionSemanticDemo());
        }
        if (this.selectionTranslateBtn) {
            this.selectionTranslateBtn.addEventListener('click', () => this.handleSelectedTextGenerate(true));
        }
        if (this.selectionCloseBtn) {
            this.selectionCloseBtn.addEventListener('click', () => this.hideSelectionPopover());
        }

        window.addEventListener('websocket-connected', () => {
            this.updateStatus('WebSocket connected');
        });

        this.glossInput.addEventListener('input', () => {
            const { selectionStart, selectionEnd, value } = this.glossInput;
            const upper = value.toUpperCase();
            if (upper !== value) {
                this.glossInput.value = upper;
                this.glossInput.setSelectionRange(selectionStart, selectionEnd);
            }
        });
    }

    collectPayload() {
        const glossValue = (this.glossInput.value || '').toUpperCase().replace(/\s+/g, ' ').trim();
        const promptText = (this.promptTextInput.value || '').trim();
        return {
            prompt: promptText,
            text: promptText,
            gloss: glossValue,
            existingVideo: this.existingInput.value,
            fps: toInt(this.fpsInput.value, 25),
            width: toInt(this.widthInput.value, 512),
            height: toInt(this.heightInput.value, 512),
            smoothing: this.smoothingSelect.value,
            smoothingFrames: toInt(this.smoothingFramesInput.value, 0),
            npzInterpolation: toInt(this.npzInput.value, 20),
            scaleX: toFloat(this.scaleXInput.value, 1.4),
            scaleY: toFloat(this.scaleYInput.value, 1.5),
            drawStyle: this.drawStyleSelect.value,
            drawConfidenceThreshold: toFloat(this.drawThresholdInput.value, 0.6),
            maxCandidates: toInt(this.maxCandidatesInput.value, 10),
            maxNewTokens: toInt(this.maxNewTokensInput.value, 64),
            refImagePath: this.refImageInput.value,
            normalizePose: this.normalizeCheckbox.checked,
            hideTorsoLines: this.hideTorsoCheckbox.checked,
            translationMode: this.semanticGlossCheckbox && this.semanticGlossCheckbox.checked ? 'semantic' : 'text2gloss',
            useSemantic: !!(this.semanticGlossCheckbox && this.semanticGlossCheckbox.checked)
        };
    }

    async handleGenerate() {
        if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
            this.updateStatus('WebSocket not ready');
            return;
        }
        const payload = this.collectPayload();
        if (!payload.gloss && !payload.text) {
            this.updateStatus('Enter Prompt/Text or Gloss');
            this.logsPre.textContent = 'Prompt/Text or Gloss cannot be empty';
            return;
        }
        if (!payload.gloss && payload.text) {
            try {
                await this.handleTranslate(true);
                payload.gloss = (this.glossInput.value || '').trim();
            } catch (error) {
                console.error('[StableSigner] auto translation failed', error);
                this.updateStatus('Gloss translation failed');
                this.logsPre.textContent = (error && error.message) ? error.message : 'Prompt → Gloss translation failed';
                return;
            }
        }
        this.setLoading(true);
        this.updateStatus('Running...');
        try {
            const response = await window.controlWaveWebSocket.sendRequest(this.id, {
                action: 'generate_pose',
                data: payload
            });
            console.log('[StableSigner] generation payload', response);
            const normalizedStatus = typeof response.status === 'string' ? response.status.toLowerCase() : '';
            const inferredSuccess = normalizedStatus === 'success' || (!!response.video_url && response.generated !== undefined);
            if (inferredSuccess) {
                if (response.gloss) {
                    this.glossInput.value = response.gloss;
                }
                if (response.video_url) {
                    await this.updateVideo(response.video_url, response.video_path);
                }
                if (response.logs) {
                    this.logsPre.textContent = response.logs;
                }
                this.updateStatus(response.generated ? 'Generation completed' : 'Reused existing video');
                try {
                    await this.refreshRecentVideos();
                } catch (err) {
                    console.warn('[StableSigner] refresh failed', err);
                }
            } else {
                console.error('[StableSigner] backend returned error', response);
                this.updateStatus('Error');
                this.logsPre.textContent = response.logs 
                    || response.message 
                    || response.error 
                    || normalizedStatus 
                    || 'Unknown error';
            }
        } catch (error) {
            this.updateStatus('Error');
            console.error('[StableSigner] request failure', error);
            this.logsPre.textContent = (error && error.message) ? error.message : 'Request failed';
        } finally {
            this.setLoading(false);
        }
    }

    async handlePrewarm() {
        if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
            this.updateStatus('WebSocket not ready');
            return;
        }
        this.updateStatus('Prewarming...');
        this.setPrewarmLoading(true);
        try {
            const response = await window.controlWaveWebSocket.sendRequest(this.id, {
                action: 'prewarm',
                data: {}
            });
            const message = response.message || 'Prewarm completed';
            const logs = response.logs || response.details || message;
            this.logsPre.textContent = logs;
            this.updateStatus('Prewarm completed');
        } catch (error) {
            console.error('[StableSigner] prewarm failed', error);
            this.logsPre.textContent = (error && error.message) ? error.message : 'Prewarm failed';
            this.updateStatus('Prewarm failed');
        } finally {
            this.setPrewarmLoading(false);
        }
    }

    async handleTranslate(isAuto = false) {
        const promptTextRaw = (this.promptTextInput.value || '').trim();
        const maxTokens = toInt(this.maxNewTokensInput.value, 64);
        if (!promptTextRaw) {
            if (!isAuto) {
                this.updateStatus('Prompt/Text is empty');
                this.logsPre.textContent = 'Please enter a Prompt or Text to translate';
            }
            throw new Error('Prompt/Text is empty');
        }
        const normalizedPrompt = normalizePromptText(promptTextRaw);
        if (!isAuto) {
            this.updateStatus('Translating...');
            this.setTranslateLoading(true);
        }
        try {
            const result = await this.translatePromptToGloss(normalizedPrompt, maxTokens, promptTextRaw);
            const gloss = typeof result === 'string' ? result : result.gloss;
            this.glossInput.value = gloss;
            if (!isAuto) {
                this.updateStatus('Gloss translation completed');
                const semantic = result.semantic && result.semantic.length > 0
                    ? `\nSemantic fallback: ${result.semantic.map(([src, dst]) => `${src}→${dst}`).join(', ')}`
                    : '';
                const dropped = result.dropped && result.dropped.length > 0
                    ? `\nDropped: ${result.dropped.join(', ')}`
                    : '';
                this.logsPre.textContent = `Translation result: ${gloss}\nMode: ${result.mode || 'rule'}${semantic}${dropped}`;
            }
            return gloss;
        } finally {
            if (!isAuto) {
                this.setTranslateLoading(false);
            }
        }
    }

    async translatePromptToGloss(promptText, maxNewTokens, originalPrompt = null) {
        if (!promptText) {
            throw new Error('Prompt/Text is empty');
        }
        const payloadPrompt = originalPrompt || promptText;
        const useSemantic = !!(this.semanticGlossCheckbox && this.semanticGlossCheckbox.checked);
        const response = await window.controlWaveWebSocket.sendRequest(this.id, {
            action: 'text_to_gloss',
            data: {
                text: promptText,
                prompt: payloadPrompt,
                maxNewTokens,
                mode: useSemantic ? 'semantic' : 'rule',
                useSemantic
            }
        });
        if (!response || response.status !== 'success' || !response.gloss) {
            throw new Error(response?.message || 'Gloss translation failed');
        }
        if (response.dropped && response.dropped.length > 0) {
            console.info('[StableSigner] dropped non-renderable text tokens', response.dropped);
        }
        return response;
    }

    handleSemanticDemo() {
        if (this.semanticGlossCheckbox) {
            this.semanticGlossCheckbox.checked = true;
        }
        this.promptTextInput.value = 'Could you aid me? I bought a mobile and go home later.';
        this.handleTranslate(false).catch((error) => {
            this.updateStatus('Semantic demo failed');
            this.logsPre.textContent = (error && error.message) ? error.message : 'Semantic demo failed';
        });
    }

    handleSelectionSemanticDemo() {
        if (this.selectionSemanticCheckbox) {
            this.selectionSemanticCheckbox.checked = true;
        }
        const demoText = 'Could you aid me? I bought a mobile and go home later.';
        if (this.selectionTemplate) {
            this.selectionTemplate.innerHTML = `<div class="stable-dialogue-turn question"><span class="stable-dialogue-speaker">User</span><p>${demoText}</p></div>`;
        }
        this.selectedTemplateText = demoText;
        this.lastGeneratedSelection = '';
        if (this.selectionTextEl) {
            this.selectionTextEl.textContent = demoText;
        }
        if (this.selectionPopover) {
            this.selectionPopover.style.display = 'block';
        }
        this.handleSelectedTextGenerate(true);
    }

    handleTemplateSelection() {
        if (!this.selectionTemplate || !this.selectionPopover) return;
        const selection = window.getSelection();
        const selectedText = selection ? selection.toString().replace(/\s+/g, ' ').trim() : '';
        if (!selectedText || selectedText.length < 2) {
            return;
        }
        const range = selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
        if (!range || !this.selectionTemplate.contains(range.commonAncestorContainer)) {
            return;
        }
        this.selectedTemplateText = selectedText;
        if (this.selectionTextEl) {
            this.selectionTextEl.textContent = selectedText;
        }
        if (this.selectionStatus) {
            this.selectionStatus.textContent = 'Preparing translation...';
        }
        if (this.selectionPopover) {
            this.selectionPopover.style.display = 'block';
        }
        if (this.selectionGenerationTimer) {
            clearTimeout(this.selectionGenerationTimer);
        }
        this.selectionGenerationTimer = setTimeout(() => this.handleSelectedTextGenerate(false), 450);
    }

    hideSelectionPopover() {
        if (this.selectionGenerationTimer) {
            clearTimeout(this.selectionGenerationTimer);
            this.selectionGenerationTimer = null;
        }
        this.stopSelectionStreamPlayback();
        this.selectionPendingFinalVideoUrl = null;
        if (this.selectionPopover) {
            this.selectionPopover.style.display = 'none';
        }
    }

    async handleSelectedTextGenerate(force = false) {
        const text = (this.selectedTemplateText || '').trim();
        if (!text || this.selectionGenerationInFlight) return;
        if (!force && text === this.lastGeneratedSelection) return;
        this.selectionGenerationInFlight = true;
        this.lastGeneratedSelection = text;
        this.promptTextInput.value = text;
        this.glossInput.value = '';
        this.stopSelectionStreamPlayback();
        this.selectionStreamFrameQueue = [];
        this.selectionStreamCursor = 0;
        this.selectionPendingFinalVideoUrl = null;
        this.logsPre.textContent = 'Selected text:\n' + text + '\n\nStreaming pose preview...';
        if (this.selectionStatus) {
            this.selectionStatus.textContent = 'Preparing pose preview...';
        }
        if (this.selectionPlaceholder && !this.selectionHasFrame) {
            this.selectionPlaceholder.style.display = 'none';
        }
        if (this.selectionVideoEl) {
            this.selectionVideoEl.style.display = 'none';
            this.selectionVideoEl.removeAttribute('src');
            this.selectionVideoEl.load();
        }
        try {
            await this.handleGenerateStream();
        } catch (error) {
            if (this.selectionStatus) {
                this.selectionStatus.textContent = (error && error.message) ? error.message : 'Stream failed';
            }
            this.selectionGenerationInFlight = false;
        }
    }

    async handleGenerateStream() {
        if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
            throw new Error('WebSocket not ready');
        }
        const payload = this.collectPayload();
        const selectionUseSemantic = !!(this.selectionSemanticCheckbox && this.selectionSemanticCheckbox.checked);
        payload.translationMode = selectionUseSemantic ? 'semantic' : 'text2gloss';
        payload.useSemantic = selectionUseSemantic;
        payload.maxNewTokens = Math.min(toInt(this.maxNewTokensInput.value, 64), 18);
        payload.maxCandidates = Math.min(toInt(this.maxCandidatesInput.value, 10), 3);
        const response = await window.controlWaveWebSocket.sendRequest(this.id, {
            action: 'generate_pose_stream',
            data: payload
        });
        if (!response || response.status !== 'running' || !response.job_id) {
            throw new Error(response?.message || 'Stream generation failed');
        }
        if (response.gloss) {
            this.glossInput.value = response.gloss;
        }
        this.selectionStreamCursor = 0;
        this.selectionStreamFrameQueue = [];
        this.selectionPendingFinalVideoUrl = null;
        this.selectionStreamPlaybackFps = toInt(response.fps, toInt(this.fpsInput.value, 25));
        this.startSelectionStreamPlayback();
        if (this.selectionStreamPollingTimer) {
            clearTimeout(this.selectionStreamPollingTimer);
        }
        this.pollPoseStream(response.job_id);
    }

    startSelectionStreamPlayback() {
        this.stopSelectionStreamPlayback();
        const fps = Math.max(5, Math.min(60, this.selectionStreamPlaybackFps || 30));
        const intervalMs = Math.max(16, Math.round(1000 / fps));
        this.selectionStreamPlaybackTimer = setInterval(() => {
            if (this.selectionStreamFrameQueue && this.selectionStreamFrameQueue.length > 0) {
                const next = this.selectionStreamFrameQueue.shift();
                if (next && next.image) {
                    this.drawStreamFrameToCanvas(next.image);
                }
                return;
            }
            if (this.selectionPendingFinalVideoUrl) {
                const finalUrl = this.selectionPendingFinalVideoUrl;
                this.selectionPendingFinalVideoUrl = null;
                this.showSelectionFinalVideo(finalUrl);
            }
        }, intervalMs);
    }

    stopSelectionStreamPlayback() {
        if (this.selectionStreamPlaybackTimer) {
            clearInterval(this.selectionStreamPlaybackTimer);
            this.selectionStreamPlaybackTimer = null;
        }
    }

    async showSelectionFinalVideo(url) {
        if (!url || !this.selectionVideoEl) return;
        const absoluteUrl = url.startsWith('http') ? url : `${window.location.origin}${url}`;
        const hasQuery = absoluteUrl.includes('?');
        const fetchUrl = `${absoluteUrl}${hasQuery ? '&' : '?'}t=${Date.now()}`;
        this.stopSelectionStreamPlayback();
        this.selectionStreamFrameQueue = [];
        this.selectionPendingFinalVideoUrl = null;
        this.selectionVideoEl.pause();
        this.selectionVideoEl.src = fetchUrl;
        this.selectionVideoEl.style.display = 'block';
        this.selectionVideoEl.load();
        try {
            await this.selectionVideoEl.play();
        } catch (error) {
            // Keep controls available even if autoplay is blocked.
        }
        if (this.selectionCanvas) {
            this.selectionCanvas.style.display = 'none';
        }
        if (this.selectionPlaceholder) {
            this.selectionPlaceholder.style.display = 'none';
        }
    }

    drawStreamFrameToCanvas(dataUrl) {
        const image = new Image();
        image.onload = () => {
            if (!this.selectionCanvas || !this.selectionCanvasCtx) return;
            if (this.selectionCanvas.width !== image.naturalWidth) {
                this.selectionCanvas.width = image.naturalWidth;
            }
            if (this.selectionCanvas.height !== image.naturalHeight) {
                this.selectionCanvas.height = image.naturalHeight;
            }
            this.selectionCanvasCtx.drawImage(image, 0, 0, this.selectionCanvas.width, this.selectionCanvas.height);
            this.selectionCanvas.style.display = 'block';
            if (this.selectionVideoEl) {
                this.selectionVideoEl.style.display = 'none';
            }
            this.selectionHasFrame = true;
            if (this.selectionPlaceholder) {
                this.selectionPlaceholder.style.display = 'none';
            }
        };
        image.src = dataUrl;
    }

    async pollPoseStream(jobId) {
        try {
            const response = await window.controlWaveWebSocket.sendRequest(this.id, {
                action: 'get_pose_stream_status',
                data: {
                    jobId,
                    cursor: this.selectionStreamCursor
                }
            });
            if (!response || response.status === 'error') {
                throw new Error(response?.message || 'Stream polling failed');
            }
            const frames = response.frames || [];
            if (frames.length > 0) {
                this.selectionStreamFrameQueue.push(...frames.filter(frame => frame && frame.image));
                if (this.selectionPlaceholder) {
                    this.selectionPlaceholder.style.display = 'none';
                }
                this.selectionStreamCursor = response.cursor || (this.selectionStreamCursor + frames.length);
            }
            if (this.selectionStatus) {
                const total = response.total_frames ? ` / ${response.total_frames}` : '';
                this.selectionStatus.textContent = `Gloss: ${(response.gloss || this.glossInput.value || '').trim()} · ${response.frame_count || this.selectionStreamCursor}${total} frames`;
            }
            if (response.status === 'running') {
                this.selectionStreamPollingTimer = setTimeout(() => this.pollPoseStream(jobId), 120);
                return;
            }
            this.selectionGenerationInFlight = false;
            if (response.logs) {
                this.logsPre.textContent = response.logs;
            }
            if (response.video_url) {
                await this.updateVideo(response.video_url, response.video_path);
                await this.refreshRecentVideos();
                if (this.selectionStreamFrameQueue.length > 0) {
                    this.selectionPendingFinalVideoUrl = response.video_url;
                } else {
                    await this.showSelectionFinalVideo(response.video_url);
                }
            }
            if (this.selectionStatus && response.status === 'success') {
                this.selectionStatus.textContent = `Gloss: ${(response.gloss || this.glossInput.value || '').trim()} · completed`;
            }
        } catch (error) {
            // Keep the last displayed frame. Short polling gaps should not be visible to users.
            if (this.selectionGenerationInFlight) {
                this.selectionStreamPollingTimer = setTimeout(() => this.pollPoseStream(jobId), 500);
            }
        }
    }

    async updateVideo(url, path) {
        if (!url || !this.videoEl) return;
        const absoluteUrl = url.startsWith('http') ? url : `${window.location.origin}${url}`;
        const hasQuery = absoluteUrl.includes('?');
        const fetchUrl = `${absoluteUrl}${hasQuery ? '&' : '?'}t=${Date.now()}`;
        if (path) {
            this.setSelectedPose(path);
        } else {
            this.updateSelectedLabel(absoluteUrl);
        }

        const resetVideoEl = () => {
            this.videoEl.onloadeddata = null;
            this.videoEl.onerror = null;
            this.videoEl.pause();
            this.videoEl.removeAttribute('src');
            this.videoEl.load();
        };

        this.videoPlaceholder.style.display = 'flex';
        this.videoPlaceholder.textContent = 'Loading video…';
        this.videoEl.style.display = 'none';
        resetVideoEl();

        if (this.currentVideoObjectUrl) {
            URL.revokeObjectURL(this.currentVideoObjectUrl);
            this.currentVideoObjectUrl = null;
        }

        try {
            const response = await fetch(fetchUrl, { cache: 'no-store' });
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}`);
            }

            const blob = await response.blob();
            const objectUrl = URL.createObjectURL(blob);
            this.currentVideoObjectUrl = objectUrl;

            this.videoEl.onloadeddata = () => {
                this.videoEl.onloadeddata = null;
                this.videoEl.onerror = null;
                this.videoPlaceholder.style.display = 'none';
                this.videoEl.style.display = 'block';
                const playPromise = this.videoEl.play();
                if (playPromise && typeof playPromise.catch === 'function') {
                    playPromise.catch(() => {});
                }
                this.videoMeta.textContent = `Video: ${path || absoluteUrl}`;
            };

            this.videoEl.onerror = () => {
                this.videoEl.onloadeddata = null;
                this.videoEl.onerror = null;
                this.videoPlaceholder.style.display = 'flex';
                this.videoPlaceholder.textContent = 'Video load failed';
                const mediaError = this.videoEl.error;
                console.error('[StableSigner] video load error', mediaError ? {
                    code: mediaError.code,
                    message: mediaError.message
                } : 'unknown');
            };

            this.videoEl.src = objectUrl;
            this.videoEl.load();

            if (this.selectionVideoEl && this.selectionPopover && this.selectionPopover.style.display !== 'none') {
                this.selectionVideoEl.pause();
                this.selectionVideoEl.src = objectUrl;
                this.selectionVideoEl.style.display = 'block';
                this.selectionVideoEl.load();
                if (this.selectionPlaceholder) {
                    this.selectionPlaceholder.style.display = 'none';
                }
                const miniPlayPromise = this.selectionVideoEl.play();
                if (miniPlayPromise && typeof miniPlayPromise.catch === 'function') {
                    miniPlayPromise.catch(() => {});
                }
            }
        } catch (error) {
            resetVideoEl();
            this.videoPlaceholder.style.display = 'flex';
            this.videoPlaceholder.textContent = 'Video load failed';
            console.error('[StableSigner] video fetch failed', error);
        }
    }

    async refreshRecentVideos() {
        if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
            this.updateStatus('Waiting for WebSocket...');
            return;
        }
        try {
            const response = await window.controlWaveWebSocket.sendRequest(this.id, {
                action: 'list_recent_videos'
            });
            this.populateRecentVideos(response.videos || []);
        } catch (error) {
            this.videoMeta.textContent = `Failed to refresh video list: ${error.message}`;
        }
    }

    async refreshStage1Videos() {
        if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
            this.updateStatus('Waiting for WebSocket...');
            return;
        }
        try {
            const response = await window.controlWaveWebSocket.sendRequest(this.id, {
                action: 'list_sign_videos'
            });
            this.populateStage1Videos(response.videos || []);
        } catch (error) {
            this.outputMeta.textContent = `Failed to refresh stage1 list: ${error.message}`;
        }
    }

    async refreshStage2Videos() {
        if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
            this.updateStatus('Waiting for WebSocket...');
            return;
        }
        try {
            const response = await window.controlWaveWebSocket.sendRequest(this.id, {
                action: 'list_refine_videos'
            });
            this.populateStage2Videos(response.videos || []);
        } catch (error) {
            this.outputMeta.textContent = `Failed to refresh stage2 list: ${error.message}`;
        }
    }

    populateRecentVideos(videos) {
        this.videoSelect.innerHTML = '<option value="">Select recently generated video</option>';
        videos.forEach(video => {
            const option = document.createElement('option');
            option.value = video.url;
            option.dataset.path = video.path;
            option.dataset.size = video.size_mb;
            option.textContent = `${video.name} (${video.size_mb} MB)`;
            this.videoSelect.appendChild(option);
        });
    }

    populateStage1Videos(videos) {
        this.stage1Select.innerHTML = '<option value="">Select stage1 output video</option>';
        videos.forEach(video => {
            const option = document.createElement('option');
            option.value = video.url;
            option.dataset.path = video.path;
            option.dataset.size = video.size_mb;
            option.textContent = `${video.name} (${video.size_mb} MB)`;
            this.stage1Select.appendChild(option);
        });
    }

    populateStage2Videos(videos) {
        this.stage2Select.innerHTML = '<option value="">Select stage2 output video</option>';
        videos.forEach(video => {
            const option = document.createElement('option');
            option.value = video.url;
            option.dataset.path = video.path;
            option.dataset.size = video.size_mb;
            option.textContent = `${video.name} (${video.size_mb} MB)`;
            this.stage2Select.appendChild(option);
        });
    }

    async handleRecentSelection() {
        const option = this.videoSelect.selectedOptions[0];
        if (!option || !option.value) {
            return;
        }
        this.setSelectedPose(option.dataset.path || option.value);
        this.videoMeta.textContent = `${option.dataset.path} • ${option.dataset.size} MB`;
        await this.updateVideo(option.value, option.dataset.path);
    }

    async handleStage1Selection() {
        const option = this.stage1Select.selectedOptions[0];
        if (!option || !option.value) {
            return;
        }
        this.outputMeta.textContent = `${option.dataset.path} • ${option.dataset.size} MB`;
        await this.updateOutputVideo(option.value, option.dataset.path);
    }

    async handleStage2Selection() {
        const option = this.stage2Select.selectedOptions[0];
        if (!option || !option.value) {
            return;
        }
        this.outputMeta.textContent = `${option.dataset.path} • ${option.dataset.size} MB`;
        await this.updateOutputVideo(option.value, option.dataset.path);
    }

    updateSelectedLabel(pathOrUrl) {
        if (!this.selectedName) return;
        if (!pathOrUrl) {
            this.selectedName.textContent = 'None';
            return;
        }
        const clean = String(pathOrUrl).split('?')[0];
        const parts = clean.split('/');
        this.selectedName.textContent = parts[parts.length - 1] || clean;
    }

    setSelectedPose(pathOrUrl) {
        this.selectedPosePath = pathOrUrl;
        this.updateSelectedLabel(pathOrUrl);
    }

    collectRefinePayload() {
        return {
            poseVideoPath: this.selectedPosePath,
            refImagePath: (this.refineRefImageInput.value || this.refImageInput.value || '').trim(),
            refCfg: toFloat(this.refineRefCfgInput.value, 2.5),
            poseCfg: toFloat(this.refinePoseCfgInput.value, 1.5),
            stage1Out: (this.refineStage1OutInput.value || '').trim(),
            stage2Out: (this.refineStage2OutInput.value || '').trim(),
            gpu: (this.refineGpuInput.value || '').trim(),
        };
    }

    async handleGenerateRefine() {
        if (!window.controlWaveWebSocket || !window.controlWaveWebSocket.sendRequest) {
            this.updateStatus('WebSocket not ready');
            return;
        }
        const payload = this.collectRefinePayload();
        if (!payload.poseVideoPath) {
            this.updateStatus('Choose a pose video first');
            this.refineLogsPre.textContent = 'Please select a pose video from the list above.';
            return;
        }
        if (this.refineJobId) {
            this.updateStatus('Refine already running');
            return;
        }
        this.setRefineLoading(true);
        this.updateStatus('Refine running...');
        this.refineLogsPre.textContent = 'Starting refine...\n';
        try {
            const response = await window.controlWaveWebSocket.sendRequest(this.id, {
                action: 'generate_refine',
                data: payload
            });
            const status = typeof response.status === 'string' ? response.status.toLowerCase() : '';
            if (status === 'running' && response.job_id) {
                this.refineJobId = response.job_id;
                this.refineLogCursor = 0;
                this.startRefineLogPolling();
                return;
            }
            if (status === 'success') {
                if (response.logs) {
                    this.refineLogsPre.textContent = response.logs;
                }
                if (response.stage2_video_url) {
                    await this.updateOutputVideo(response.stage2_video_url, response.stage2_video_path);
                } else if (response.stage1_video_url) {
                    await this.updateOutputVideo(response.stage1_video_url, response.stage1_video_path);
                }
                await Promise.all([this.refreshStage1Videos(), this.refreshStage2Videos()]);
                this.updateStatus('Refine completed');
            } else {
                this.updateStatus('Refine failed');
                this.refineLogsPre.textContent = response.message || response.error || response.logs || 'Refine failed';
            }
        } catch (error) {
            this.updateStatus('Refine failed');
            this.refineLogsPre.textContent = (error && error.message) ? error.message : 'Refine request failed';
        }
        this.setRefineLoading(false);
    }

    startRefineLogPolling() {
        this.stopRefineLogPolling();
        this.pollRefineStatus();
        this.refinePollingTimer = setInterval(() => {
            this.pollRefineStatus();
        }, 1200);
    }

    stopRefineLogPolling() {
        if (this.refinePollingTimer) {
            clearInterval(this.refinePollingTimer);
            this.refinePollingTimer = null;
        }
    }

    async pollRefineStatus() {
        if (!this.refineJobId) {
            return;
        }
        try {
            const response = await window.controlWaveWebSocket.sendRequest(this.id, {
                action: 'get_refine_status',
                data: {
                    job_id: this.refineJobId,
                    last_index: this.refineLogCursor
                }
            });
            if (response.status !== 'success') {
                throw new Error(response.message || 'Failed to fetch refine status');
            }
            if (Array.isArray(response.logs) && response.logs.length > 0) {
                this.appendRefineLogs(response.logs);
            }
            if (typeof response.next_index === 'number') {
                this.refineLogCursor = response.next_index;
            } else if (response.logs) {
                this.refineLogCursor += response.logs.length;
            }

            const jobStatus = response.job_status;
            if (jobStatus === 'success' && response.result) {
                const result = response.result;
                if (result.stage2_video_url) {
                    await this.updateOutputVideo(result.stage2_video_url, result.stage2_video_path);
                } else if (result.stage1_video_url) {
                    await this.updateOutputVideo(result.stage1_video_url, result.stage1_video_path);
                }
                await Promise.all([this.refreshStage1Videos(), this.refreshStage2Videos()]);
                this.updateStatus('Refine completed');
                this.finishRefineJob();
            } else if (jobStatus === 'error') {
                const errMsg = response.error_message || 'Refine failed';
                this.updateStatus(`Refine failed: ${errMsg}`);
                this.finishRefineJob();
            } else if (jobStatus === 'running') {
                this.updateStatus('Refine running...');
            }
        } catch (error) {
            this.updateStatus(`Refine polling failed: ${error.message}`);
            this.finishRefineJob();
        }
    }

    appendRefineLogs(newLines) {
        if (!this.refineLogsPre || !newLines) {
            return;
        }
        const text = Array.isArray(newLines) ? newLines.join('\n') : newLines;
        if (!text) {
            return;
        }
        if (!this.refineLogsPre.textContent || this.refineLogsPre.textContent === '(waiting for refine...)') {
            this.refineLogsPre.textContent = '';
        }
        if (this.refineLogsPre.textContent && !this.refineLogsPre.textContent.endsWith('\n')) {
            this.refineLogsPre.textContent += '\n';
        }
        this.refineLogsPre.textContent += text + '\n';
        this.refineLogsPre.scrollTop = this.refineLogsPre.scrollHeight;
    }

    finishRefineJob() {
        this.stopRefineLogPolling();
        this.refineJobId = null;
        this.setRefineLoading(false);
    }

    async updateOutputVideo(url, path) {
        if (!url || !this.outputVideoEl) return;
        const absoluteUrl = url.startsWith('http') ? url : `${window.location.origin}${url}`;
        const hasQuery = absoluteUrl.includes('?');
        const fetchUrl = `${absoluteUrl}${hasQuery ? '&' : '?'}t=${Date.now()}`;

        const resetVideoEl = () => {
            this.outputVideoEl.onloadeddata = null;
            this.outputVideoEl.onerror = null;
            this.outputVideoEl.pause();
            this.outputVideoEl.removeAttribute('src');
            this.outputVideoEl.load();
        };

        this.outputPlaceholder.style.display = 'flex';
        this.outputPlaceholder.textContent = 'Loading video…';
        this.outputVideoEl.style.display = 'none';
        resetVideoEl();

        if (this.refineVideoObjectUrl) {
            URL.revokeObjectURL(this.refineVideoObjectUrl);
            this.refineVideoObjectUrl = null;
        }

        try {
            const response = await fetch(fetchUrl, { cache: 'no-store' });
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}`);
            }

            const blob = await response.blob();
            const objectUrl = URL.createObjectURL(blob);
            this.refineVideoObjectUrl = objectUrl;

            this.outputVideoEl.onloadeddata = () => {
                this.outputVideoEl.onloadeddata = null;
                this.outputVideoEl.onerror = null;
                this.outputPlaceholder.style.display = 'none';
                this.outputVideoEl.style.display = 'block';
                const playPromise = this.outputVideoEl.play();
                if (playPromise && typeof playPromise.catch === 'function') {
                    playPromise.catch(() => {});
                }
                this.outputMeta.textContent = `Video: ${path || absoluteUrl}`;
            };

            this.outputVideoEl.onerror = () => {
                this.outputVideoEl.onloadeddata = null;
                this.outputVideoEl.onerror = null;
                this.outputPlaceholder.style.display = 'flex';
                this.outputPlaceholder.textContent = 'Video load failed';
                const mediaError = this.outputVideoEl.error;
                console.error('[StableSigner] output video load error', mediaError ? {
                    code: mediaError.code,
                    message: mediaError.message
                } : 'unknown');
            };

            this.outputVideoEl.src = objectUrl;
            this.outputVideoEl.load();
        } catch (error) {
            resetVideoEl();
            this.outputPlaceholder.style.display = 'flex';
            this.outputPlaceholder.textContent = 'Video load failed';
            console.error('[StableSigner] output video fetch failed', error);
        }
    }

    setRefineLoading(isLoading) {
        if (!this.generateRefineBtn) return;
        this.generateRefineBtn.disabled = isLoading;
        this.generateRefineBtn.textContent = isLoading ? 'Generating...' : 'Generate Refine Video';
    }

    setLoading(isLoading) {
        this.generateBtn.disabled = isLoading;
        this.generateBtn.textContent = isLoading ? 'Generating...' : 'Generate Pose Video';
    }

    setPrewarmLoading(isLoading) {
        if (!this.prewarmBtn) return;
        this.prewarmBtn.disabled = isLoading;
        this.prewarmBtn.textContent = isLoading ? 'Prewarming...' : 'Prewarm';
    }

    setTranslateLoading(isLoading) {
        if (!this.translateBtn) return;
        this.translateBtn.disabled = isLoading;
        this.translateBtn.textContent = isLoading ? 'Translating...' : 'Translate Prompt → Gloss';
    }

    updateStatus(text) {
        this.statusChip.textContent = text;
    }
}