File size: 62,763 Bytes
7312c42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cbbe5c7
7312c42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import { TooltipProvider } from '@/components/ui/tooltip'
import { LocaleContext } from '@/lib/i18n'
import { TaskSegmentEditor } from '@/components/widgets/multitrack/TaskSegmentEditor'
import { getMediaListStoreRevision } from '@/stores/media-list-store'
import type { MultiTrack, MultiTrackSegment } from '@/types/multitrack'

vi.mock('@/components/widgets/mediaSelector/MediaSelector', () => ({
  MediaSelector: (props: {
    value: string
    allowMultipleSelection?: boolean
    maxSelectionCount?: number
    slotItems?: Array<{ value: string }>
    onChange: (value: string, source: 'input') => void
  }) => (
    <div
      data-testid="media-selector-mock"
      data-value={props.value}
      data-multiple={String(props.allowMultipleSelection)}
      data-limit={String(props.maxSelectionCount)}
      data-slot-items={props.slotItems?.map((item) => item.value).join(',') ?? ''}
    >
      <button type="button" onClick={() => props.onChange('replacement.png', 'input')}>
        choose replacement
      </button>
    </div>
  ),
}))

vi.stubGlobal('ResizeObserver', class {
  observe() {}
  unobserve() {}
  disconnect() {}
})

function activateTab(name: string) {
  const tab = screen.getByRole('tab', { name })
  fireEvent.pointerDown(tab, { button: 0, ctrlKey: false })
  fireEvent.mouseDown(tab, { button: 0, ctrlKey: false })
  fireEvent.click(tab)
}

function inputEditable(element: HTMLElement, value: string) {
  element.textContent = value
  fireEvent.input(element)
}

function taskSegment(): MultiTrackSegment {
  return {
    id: 'task-segment',
    start_frame: 0,
    end_frame: 3,
    color: 'var(--multitrack-task-bg)',
    content: {
      media_type: 'none',
      task_mode: 'default',
      user_prompt: 'Initial prompt',
      images: [
        { id: 'a', source_type: 'input', file_path: 'a.png', file_name: 'a.png' },
        { id: 'b', source_type: 'input', file_path: 'b.png', file_name: 'b.png' },
      ],
    },
  }
}

function secondTaskSegment(): MultiTrackSegment {
  return {
    ...taskSegment(),
    id: 'task-segment-2',
    start_frame: 3,
    end_frame: 6,
    content: {
      media_type: 'none',
      task_mode: 'default',
      user_prompt: 'Second prompt',
      images: [],
    },
  }
}

function videoSegment(
  startFrame: number,
  endFrame: number,
  sourceType: 'input' | 'preset' = 'input',
): MultiTrackSegment {
  return {
    id: `video-${startFrame}-${endFrame}-${sourceType}`,
    start_frame: startFrame,
    end_frame: endFrame,
    color: 'var(--multitrack-video-bg)',
    content: {
      media_type: 'video',
      source_type: sourceType,
      file_path: 'video.mp4',
    },
  }
}

function mediaTrack(type: 'audio' | 'video', segments: MultiTrackSegment[]): MultiTrack {
  return {
    id: `${type}-track`,
    name: type === 'audio' ? 'Voice track' : 'Source video track',
    type,
    color: type === 'audio' ? 'var(--multitrack-audio-bg)' : 'var(--multitrack-video-bg)',
    muted: false,
    locked: false,
    segments,
  }
}

describe('TaskSegmentEditor', () => {
  it('updates task mode and prompt text', () => {
    const onContentChange = vi.fn()
    render(<TaskSegmentEditor segment={taskSegment()} onContentChange={onContentChange} />)

    fireEvent.click(screen.getByRole('combobox', { name: 'Task mode' }))
    fireEvent.click(screen.getByRole('option', { name: 'R2V' }))
    inputEditable(screen.getByRole('textbox', { name: 'Prompt' }), 'New prompt')

    expect(onContentChange).toHaveBeenCalledWith({ task_mode: 'ref' })
    expect(onContentChange).toHaveBeenCalledWith({ user_prompt: 'New prompt' })
  })

  it('shows and stores MiniMax continuity mode from the second task onward', () => {
    const onContentChange = vi.fn()
    const first = taskSegment()
    const second = secondTaskSegment()
    const { rerender } = render(
      <TaskSegmentEditor
        segment={second}
        trackSegments={[first, second]}
        format="MiniMax"
        onContentChange={onContentChange}
      />,
    )

    const continuitySelect = screen.getByRole('combobox', { name: 'Continuity mode' })
    expect(continuitySelect.className).toContain('w-28')
    expect(screen.getByRole('combobox', { name: 'Task mode' }).className).toContain('w-24')
    fireEvent.click(continuitySelect)
    fireEvent.click(screen.getByRole('option', { name: 'Context' }))
    expect(onContentChange).toHaveBeenCalledWith({ continuity_mode: 'context' })
    fireEvent.click(continuitySelect)
    fireEvent.click(screen.getByRole('option', { name: 'Swap Context' }))
    expect(onContentChange).toHaveBeenCalledWith({ continuity_mode: 'context_swap' })

    rerender(
      <TaskSegmentEditor
        segment={first}
        trackSegments={[first, second]}
        format="MiniMax"
        onContentChange={onContentChange}
      />,
    )
    expect(screen.queryByRole('combobox', { name: 'Continuity mode' })).toBeNull()

    rerender(
      <TaskSegmentEditor
        segment={second}
        trackSegments={[first, second]}
        format="Seedance"
        onContentChange={onContentChange}
      />,
    )
    expect(screen.queryByRole('combobox', { name: 'Continuity mode' })).toBeNull()
  })

  it('shows and stores reference image size only for reference tasks', () => {
    const onContentChange = vi.fn()
    const referenceSegment = taskSegment()
    referenceSegment.content.task_mode = 'ref'
    referenceSegment.content.ref_image_size = 'max'
    const { rerender } = render(
      <TaskSegmentEditor
        segment={referenceSegment}
        format="MiniMax"
        onContentChange={onContentChange}
      />,
    )

    const sizeSelect = screen.getByRole('combobox', { name: 'Reference image size' })
    expect(sizeSelect.textContent).toContain('Max')
    fireEvent.click(sizeSelect)
    fireEvent.click(screen.getByRole('option', { name: 'Match' }))
    expect(onContentChange).toHaveBeenCalledWith({ ref_image_size: 'match' })

    rerender(
      <TaskSegmentEditor
        segment={taskSegment()}
        format="MiniMax"
        onContentChange={onContentChange}
      />,
    )
    expect(screen.queryByRole('combobox', { name: 'Reference image size' })).toBeNull()
  })

  it('synchronizes dropdown changes across selected tasks while keeping the first continuity mode as shot', () => {
    const onContentChange = vi.fn()
    const onTrackSegmentsContentChange = vi.fn()
    const first = taskSegment()
    first.content.task_mode = 'ref'
    first.content.continuity_mode = 'shot'
    const second = secondTaskSegment()
    second.content.task_mode = 'ref'
    second.content.continuity_mode = 'shot'

    render(
      <TaskSegmentEditor
        segment={first}
        trackSegments={[first, second]}
        selectedSegments={[first, second]}
        format="MiniMax"
        onContentChange={onContentChange}
        onTrackSegmentsContentChange={onTrackSegmentsContentChange}
      />,
    )

    fireEvent.click(screen.getByRole('combobox', { name: 'Continuity mode' }))
    fireEvent.click(screen.getByRole('option', { name: 'Context' }))
    expect(onTrackSegmentsContentChange).toHaveBeenLastCalledWith([
      { segmentId: first.id, patch: { continuity_mode: 'shot' } },
      { segmentId: second.id, patch: { continuity_mode: 'context' } },
    ])

    fireEvent.click(screen.getByRole('combobox', { name: 'Reference image size' }))
    fireEvent.click(screen.getByRole('option', { name: 'Max' }))
    expect(onTrackSegmentsContentChange).toHaveBeenLastCalledWith([
      { segmentId: first.id, patch: { ref_image_size: 'max' } },
      { segmentId: second.id, patch: { ref_image_size: 'max' } },
    ])

    fireEvent.click(screen.getByRole('combobox', { name: 'Task mode' }))
    fireEvent.click(screen.getByRole('option', { name: 'VI2V' }))
    expect(onTrackSegmentsContentChange).toHaveBeenLastCalledWith([
      { segmentId: first.id, patch: { task_mode: 'edit' } },
      { segmentId: second.id, patch: { task_mode: 'edit' } },
    ])
    expect(onContentChange).not.toHaveBeenCalled()
  })

  it('stores the A/B prompt selection, edits B independently, and shows its tooltip on hover', async () => {
    const onContentChange = vi.fn()
    const initialSegment = taskSegment()
    const { rerender } = render(
      <TooltipProvider delayDuration={0}>
        <TaskSegmentEditor segment={initialSegment} onContentChange={onContentChange} />
      </TooltipProvider>,
    )

    const tooltipText = 'New: The user prompt output follows your A/B selection (select A to output A, select B to output B). Use A/B to compare prompts, or to preserve both the original and reverse-engineered prompts.'
    const tooltipTrigger = screen.getByLabelText(tooltipText)
    fireEvent.pointerMove(tooltipTrigger, { pointerType: 'mouse' })
    expect((await screen.findByRole('tooltip')).textContent).toBe(tooltipText)
    fireEvent.pointerLeave(tooltipTrigger, { pointerType: 'mouse' })
    await waitFor(() => expect(screen.queryByRole('tooltip')).toBeNull())

    activateTab('B')
    expect(onContentChange).toHaveBeenCalledWith({ user_prompt_variant: 'b' })

    const bSegment = taskSegment()
    bSegment.content.user_prompt_b = 'Reverse-engineered prompt'
    bSegment.content.user_prompt_variant = 'b'
    rerender(
      <TooltipProvider delayDuration={0}>
        <TaskSegmentEditor segment={bSegment} onContentChange={onContentChange} />
      </TooltipProvider>,
    )

    const prompt = screen.getByRole('textbox', { name: 'Prompt' }) as HTMLElement
    expect(prompt.textContent).toBe('Reverse-engineered prompt')
    inputEditable(prompt, 'Updated B prompt')
    expect(onContentChange).toHaveBeenCalledWith({ user_prompt_b: 'Updated B prompt' })
    expect(bSegment.content.user_prompt).toBe('Initial prompt')
  })

  it('offers last-frame mode after edit', () => {
    const onContentChange = vi.fn()
    render(<TaskSegmentEditor segment={taskSegment()} onContentChange={onContentChange} />)

    fireEvent.click(screen.getByRole('combobox'))
    const options = screen.getAllByRole('option').map((option) => option.textContent)

    expect(options).toEqual([
      'FL2V',
      'R2V',
      'VI2V',
      'L2V',
    ])
    fireEvent.click(screen.getByRole('option', { name: 'L2V' }))
    expect(onContentChange).toHaveBeenCalledWith({ task_mode: 'l2v' })
  })

  it.each([
    [0, 'T2V'],
    [1, 'I2V'],
    [2, 'FL2V'],
    [3, 'FMLF2V'],
  ])('shows the default task type for %i task images', (imageCount, expectedLabel) => {
    const segment = taskSegment()
    segment.content.images = Array.from({ length: imageCount }, (_, index) => ({
      id: `image-${index}`,
      source_type: 'input' as const,
      file_path: `image-${index}.png`,
    }))

    render(<TaskSegmentEditor segment={segment} onContentChange={vi.fn()} />)

    expect(screen.getByRole('combobox', { name: 'Task mode' }).textContent).toContain(expectedLabel)
  })

  it('keeps task prompt wheel scrolling inside the editor', () => {
    const onCanvasWheel = vi.fn()
    render(
      <div
        onWheelCapture={(event) => {
          const target = event.target as HTMLElement
          const captureElement = target.closest('[data-capture-wheel="true"]')
          if (!captureElement?.contains(document.activeElement)) onCanvasWheel()
        }}
      >
        <TaskSegmentEditor segment={taskSegment()} onContentChange={vi.fn()} />
      </div>,
    )

    const prompt = screen.getByRole('textbox', { name: 'Prompt' })
    prompt.focus()
    const keepsNativeScroll = fireEvent.wheel(prompt, { deltaY: 100 })

    expect(keepsNativeScroll).toBe(true)
    expect(onCanvasWheel).not.toHaveBeenCalled()
  })

  it('uses rv2v for reference mode when a non-preset video overlaps the task range', () => {
    render(
      <TaskSegmentEditor
        segment={taskSegment()}
        videoSegments={[videoSegment(2, 5)]}
        onContentChange={vi.fn()}
      />,
    )

    fireEvent.click(screen.getByRole('combobox'))

    expect(screen.getByRole('option', { name: 'RV2V' })).not.toBeNull()
  })

  it('uses rv2v for reference mode with preset video', () => {
    render(
      <TaskSegmentEditor
        segment={taskSegment()}
        videoSegments={[videoSegment(2, 5, 'preset')]}
        onContentChange={vi.fn()}
      />,
    )

    fireEvent.click(screen.getByRole('combobox'))

    expect(screen.getByRole('option', { name: 'RV2V' })).not.toBeNull()
  })

  it.each([
    ['video ending at the task start', videoSegment(-2, 0)],
    ['video starting at the task end', videoSegment(3, 5)],
  ])('uses r2v for reference mode with %s', (_caseName, video) => {
    render(
      <TaskSegmentEditor
        segment={taskSegment()}
        videoSegments={[video]}
        onContentChange={vi.fn()}
      />,
    )

    fireEvent.click(screen.getByRole('combobox'))

    expect(screen.getByRole('option', { name: 'R2V' })).not.toBeNull()
  })

  it('uploads dropped image files and appends them to task images', async () => {
    const onContentChange = vi.fn()
    const initialCacheRevision = getMediaListStoreRevision()
    const fetchMock = vi.fn()
      .mockResolvedValueOnce({ ok: true, json: async () => ({ name: 'first.png', subfolder: 'uploads' }) })
      .mockResolvedValueOnce({ ok: true, json: async () => ({ name: 'second.png', subfolder: '' }) })
    vi.stubGlobal('fetch', fetchMock)
    render(<TaskSegmentEditor segment={taskSegment()} onContentChange={onContentChange} />)

    fireEvent.drop(screen.getByTestId('task-image-drop-zone'), {
      dataTransfer: {
        files: [
          new File(['first'], 'first.png', { type: 'image/png' }),
          new File(['second'], 'second.png', { type: 'image/png' }),
        ],
        types: ['Files'],
      },
    })

    await waitFor(() => {
      expect(onContentChange).toHaveBeenLastCalledWith({
        images: [
          expect.objectContaining({ file_name: 'a.png' }),
          expect.objectContaining({ file_name: 'b.png' }),
          expect.objectContaining({ file_path: 'uploads/first.png', file_name: 'first.png' }),
          expect.objectContaining({ file_path: 'second.png', file_name: 'second.png' }),
        ],
      })
    })
    expect(getMediaListStoreRevision()).toBe(initialCacheRevision + 1)
  })

  it('highlights the image picker while image files are dragged over it', () => {
    render(<TaskSegmentEditor segment={taskSegment()} onContentChange={vi.fn()} />)

    const dropZone = screen.getByTestId('task-image-drop-zone')
    fireEvent.dragEnter(dropZone, {
      dataTransfer: {
        files: [new File(['first'], 'first.png', { type: 'image/png' })],
        types: ['Files'],
      },
    })

    expect(dropZone.className).toContain('border-primary')

    fireEvent.dragLeave(dropZone, { relatedTarget: document.body })

    expect(dropZone.className).not.toContain('border-primary')
  })

  it('previews and deletes images from the image grid actions', () => {
    const onContentChange = vi.fn()
    const onOpenImagePreview = vi.fn()
    render(
      <TaskSegmentEditor
        segment={taskSegment()}
        onContentChange={onContentChange}
        onOpenImagePreview={onOpenImagePreview}
      />,
    )

    expect(screen.getByTestId('task-image-a').className).toContain('bg-black')
    expect(screen.getByTestId('task-image-a').className).toContain('group/task-image')
    const firstImage = screen.getByAltText('a.png')
    expect(firstImage.className).toContain('absolute')
    expect(firstImage.className).toContain('inset-0')
    expect(firstImage.className).toContain('h-full')
    expect(firstImage.className).toContain('w-full')
    expect(firstImage.className).toContain('object-contain')
    expect(screen.getByTestId('task-image-actions-a').className).toContain('opacity-0')
    expect(screen.getByTestId('task-image-actions-a').className).toContain('group-hover/task-image:opacity-100')
    expect(screen.getByTestId('task-image-actions-a').className).toContain('flex')
    expect(screen.getByTestId('task-image-actions-a').className).toContain('right-0')
    expect(screen.getByTestId('task-image-actions-a').className).toContain('top-1')
    expect(screen.getByTestId('task-image-overlay-a').className).toContain('bg-black/30')
    expect(screen.getByTestId('task-image-index-a').textContent).toBe('0')
    expect(screen.getByTestId('task-image-index-a').className).toContain('bottom-0')
    expect(screen.getByTestId('task-image-index-b').textContent).toBe('1')
    expect(screen.getAllByRole('button', { name: 'Preview image' })[0].className).toContain('cursor-pointer')
    expect(screen.getAllByRole('button', { name: 'Preview image' })).toHaveLength(2)
    expect(screen.queryByRole('button', { name: '720° panorama preview' })).toBeNull()
    expect(screen.getAllByRole('button', { name: 'Delete image' })[0].className).toContain('cursor-pointer')
    expect(screen.getAllByRole('button', { name: 'Delete image' })[0].className).toContain('text-destructive')
    const previewButton = screen.getAllByRole('button', { name: 'Preview image' })[0]
    expect(previewButton.querySelector('.lucide-eye')).not.toBeNull()

    fireEvent.click(previewButton)
    expect(onOpenImagePreview).toHaveBeenCalledWith('a')
    expect(screen.queryByTestId('media-selector-mock')).toBeNull()

    fireEvent.click(screen.getAllByRole('button', { name: 'Delete image' })[0])
    expect(onContentChange).toHaveBeenCalledWith({
      images: [expect.objectContaining({ id: 'b' })],
    })
    expect(screen.queryByTestId('media-selector-mock')).toBeNull()
  })

  it('labels slot image placeholders with their slot number', () => {
    const segment = taskSegment()
    segment.content.images = [{
      id: 'slot-image',
      source_type: 'slot',
      slot_name: 'image2',
      file_name: 'image2',
    }]

    render(<TaskSegmentEditor segment={segment} onContentChange={vi.fn()} />)

    expect(screen.getByTestId('task-image-slot-image').textContent).toContain('Image 2')
  })

  it('shares an image across tasks before each task local images', () => {
    const first = taskSegment()
    first.content.images = [
      { id: 'local-a', source_type: 'input', file_path: 'local-a.png' },
      { id: 'shared', source_type: 'input', file_path: 'shared.png' },
    ]
    const second = secondTaskSegment()
    second.content.images = [
      { id: 'same-path', source_type: 'input', file_path: 'shared.png' },
      { id: 'local-b', source_type: 'input', file_path: 'local-b.png' },
    ]
    const onTrackSegmentsContentChange = vi.fn()

    render(
      <TaskSegmentEditor
        segment={first}
        trackSegments={[first, second]}
        onContentChange={vi.fn()}
        onTrackSegmentsContentChange={onTrackSegmentsContentChange}
      />,
    )
    fireEvent.click(screen.getByTestId('task-image-shared-shared'))

    expect(onTrackSegmentsContentChange).toHaveBeenCalledWith([
      {
        segmentId: first.id,
        patch: { images: [
          expect.objectContaining({ id: 'shared', shared_reference: true }),
          expect.objectContaining({ id: 'local-a' }),
        ] },
      },
      {
        segmentId: second.id,
        patch: { images: [
          expect.objectContaining({ id: 'same-path', shared_reference: true }),
          expect.objectContaining({ id: 'local-b' }),
        ] },
      },
    ])
  })

  it('reselects an image in place and opens the chosen image first without batch controls', () => {
    const onContentChange = vi.fn()
    render(<TaskSegmentEditor segment={taskSegment()} onContentChange={onContentChange} />)

    fireEvent.click(screen.getByTestId('task-image-a'))

    const selector = screen.getByTestId('media-selector-mock')
    expect(selector.dataset.value).toBe('a.png')
    expect(selector.dataset.multiple).toBe('false')
    expect(selector.dataset.limit).toBe('1')

    fireEvent.click(screen.getByRole('button', { name: 'choose replacement' }))
    expect(onContentChange).toHaveBeenLastCalledWith({
      images: [
        expect.objectContaining({ id: 'a', file_path: 'replacement.png' }),
        expect.objectContaining({ id: 'b', file_path: 'b.png' }),
      ],
    })
  })

  it('passes the remaining image capacity to the add-image selector', () => {
    render(<TaskSegmentEditor segment={taskSegment()} onContentChange={vi.fn()} />)

    fireEvent.click(screen.getByRole('button', { name: 'Select image' }))

    const selector = screen.getByTestId('media-selector-mock')
    expect(selector.dataset.value).toBe('')
    expect(selector.dataset.multiple).toBe('true')
    expect(selector.dataset.limit).toBe('7')
  })

  it('supports one-based image item numbering', () => {
    render(
      <TaskSegmentEditor
        segment={taskSegment()}
        imageIndexOffset={1}
        onContentChange={vi.fn()}
      />,
    )

    expect(screen.getByTestId('task-image-index-a').textContent).toBe('1')
    expect(screen.getByTestId('task-image-index-b').textContent).toBe('2')
  })

  it('confirms before applying the selected prompt to both variants of every task segment', () => {
    const first = taskSegment()
    first.content.user_prompt = 'Prompt A'
    first.content.user_prompt_b = 'Selected prompt B'
    first.content.user_prompt_variant = 'b'
    const second = secondTaskSegment()
    second.content.user_prompt = 'Existing A'
    second.content.user_prompt_b = 'Existing B'
    const onTrackSegmentsContentChange = vi.fn()

    render(
      <TaskSegmentEditor
        segment={first}
        trackSegments={[first, second]}
        onContentChange={vi.fn()}
        onTrackSegmentsContentChange={onTrackSegmentsContentChange}
      />,
    )

    const applyButton = screen.getByRole('button', { name: 'Apply to all' })
    expect(applyButton.className).toContain('text-highlight')
    expect(applyButton.className).toContain('hover:bg-highlight/10')
    fireEvent.click(applyButton)

    expect(screen.getByRole('heading', { name: 'Apply this prompt to every segment?' })).not.toBeNull()
    expect(screen.getByText(/replace both prompt A and prompt B/)).not.toBeNull()
    expect(onTrackSegmentsContentChange).not.toHaveBeenCalled()

    fireEvent.click(screen.getByRole('button', { name: 'Replace all' }))
    expect(onTrackSegmentsContentChange).toHaveBeenCalledWith([
      {
        segmentId: first.id,
        patch: { user_prompt: 'Selected prompt B', user_prompt_b: 'Selected prompt B' },
      },
      {
        segmentId: second.id,
        patch: { user_prompt: 'Selected prompt B', user_prompt_b: 'Selected prompt B' },
      },
    ])
  })

  it('bypasses an image, removes its sequence number, and renumbers active images', () => {
    const onContentChange = vi.fn()
    const segment = taskSegment()
    segment.content.images![0].muted = true
    render(
      <TooltipProvider>
        <TaskSegmentEditor
          segment={segment}
          imageIndexOffset={1}
          onContentChange={onContentChange}
        />
      </TooltipProvider>,
    )

    expect(screen.queryByTestId('task-image-index-a')).toBeNull()
    expect(screen.getByTestId('task-image-index-b').textContent).toBe('1')
    expect(screen.getAllByRole('button', { name: 'Preview image' })).toHaveLength(2)
    expect(screen.getAllByRole('button', { name: 'Delete image' })).toHaveLength(2)

    fireEvent.click(screen.getByTestId('task-image-muted-a'))
    expect(onContentChange).toHaveBeenCalledWith({
      images: [
        expect.objectContaining({ id: 'a', muted: false }),
        expect.objectContaining({ id: 'b' }),
      ],
    })
  })

  it('keeps the image grid responsive inside resizable image and prompt panels', () => {
    const nodePointerDown = vi.fn()
    document.body.addEventListener('pointerdown', nodePointerDown)
    render(<TaskSegmentEditor segment={taskSegment()} onContentChange={vi.fn()} />)

    const dropZone = screen.getByTestId('task-image-drop-zone')
    const grid = screen.getByTestId('task-image-grid')
    expect(dropZone.closest('.task-segment-editor')).not.toBeNull()
    expect(dropZone.className).toContain('w-full')
    expect(grid.className).toContain('grid-cols-2')
    expect(screen.getByTestId('task-image-a').className).toContain('w-full')
    expect(screen.getByTestId('task-image-a').className).toContain('self-start')
    expect(screen.getByRole('button', { name: 'Select image' }).className).toContain('w-full')
    expect(screen.getByRole('button', { name: 'Select image' }).className).toContain('self-start')
    expect(screen.getByTestId('task-prompt-panel').className).toContain('min-w-0')
    const separator = screen.getByRole('separator', { name: 'Resize image and prompt panels' })
    fireEvent.pointerDown(separator, { button: 0, clientX: 320 })
    expect(nodePointerDown).not.toHaveBeenCalled()
    document.body.removeEventListener('pointerdown', nodePointerDown)
    expect(screen.getByTestId('task-images-resizable-panel')).not.toBeNull()
    expect(screen.getByTestId('task-prompt-resizable-panel')).not.toBeNull()
  })

  it('resizes panels through the local pointer-capture path used by Nodes 2.0', async () => {
    const offsetWidth = vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get').mockReturnValue(400)
    render(<TaskSegmentEditor segment={taskSegment()} onContentChange={vi.fn()} />)

    const separator = screen.getByRole('separator', { name: 'Resize image and prompt panels' })
    const group = separator.parentElement
    if (!group) throw new Error('Expected resizable panel group')
    vi.spyOn(group, 'getBoundingClientRect').mockReturnValue({
      x: 0,
      y: 0,
      top: 0,
      right: 800,
      bottom: 400,
      left: 0,
      width: 800,
      height: 400,
      toJSON: () => ({}),
    })

    const dispatchPointer = (type: string, clientX: number, buttons: number) => {
      const event = new Event(type, { bubbles: true, cancelable: true })
      Object.defineProperties(event, {
        button: { value: 0 },
        buttons: { value: buttons },
        clientX: { value: clientX },
        pointerId: { value: 7 },
      })
      fireEvent(separator, event)
    }
    const initialSize = separator.getAttribute('aria-valuenow')
    dispatchPointer('pointerdown', 320, 1)
    dispatchPointer('pointermove', 400, 1)

    await waitFor(() => {
      expect(separator.getAttribute('aria-valuenow')).not.toBe(initialSize)
    })
    dispatchPointer('pointerup', 400, 0)
    offsetWidth.mockRestore()
  })

  it('renders saved panorama framing without showing a panorama action icon', () => {
    const segment = taskSegment()
    segment.content.images![0].panorama_view = {
      version: 1,
      projection: 'equirectangular',
      yaw: 20,
      pitch: 5,
      hfov: 75,
      aspect_ratio: 1.5,
    }
    render(<TaskSegmentEditor segment={segment} onContentChange={vi.fn()} />)

    expect(screen.queryByRole('button', { name: '720° panorama preview' })).toBeNull()
    expect(screen.getAllByRole('button', { name: 'Preview image' })).toHaveLength(2)
    expect(screen.getByTestId('task-image-grid').className).toContain('w-full')
    expect(screen.getByTestId('panorama-image-preview-a').className).toContain('absolute')
  })

  it('reorders images by dragging one image onto another', () => {
    const onContentChange = vi.fn()
    render(<TaskSegmentEditor segment={taskSegment()} onContentChange={onContentChange} />)

    fireEvent.dragStart(screen.getByTestId('task-image-a'))
    fireEvent.drop(screen.getByTestId('task-image-b'))

    expect(onContentChange).toHaveBeenCalledWith({
      images: [
        expect.objectContaining({ id: 'b' }),
        expect.objectContaining({ id: 'a' }),
      ],
    })
  })

  it('keeps the image grid stable without opening a hover focus preview', () => {
    render(<TaskSegmentEditor segment={taskSegment()} onContentChange={vi.fn()} />)

    const grid = screen.getByTestId('task-image-grid')
    const firstImage = screen.getByTestId('task-image-a')
    const secondImage = screen.getByTestId('task-image-b')

    expect(grid.className).toContain('grid-cols-2')
    expect(screen.queryByTestId('task-image-focus-preview')).toBeNull()
    fireEvent.mouseEnter(secondImage)
    expect(grid.className).toContain('grid-cols-2')
    expect(screen.queryByTestId('task-image-focus-preview')).toBeNull()
    expect(secondImage.className).toContain('relative')
    expect(secondImage.className).toContain('cursor-pointer')
    expect(secondImage.className).not.toContain('opacity-0')
    expect(firstImage.className).not.toContain('opacity-0')

    fireEvent.mouseLeave(grid)
    expect(grid.className).toContain('grid-cols-2')
    expect(screen.queryByTestId('task-image-focus-preview')).toBeNull()
    expect(secondImage.className).toContain('relative')
    expect(secondImage.className).not.toContain('opacity-0')
  })

  it('uses a three-column image grid once four or more task images are present', () => {
    const segment = taskSegment()
    segment.content.images = [
      ...(segment.content.images ?? []),
      { id: 'c', source_type: 'input', file_path: 'c.png', file_name: 'c.png' },
      { id: 'd', source_type: 'input', file_path: 'd.png', file_name: 'd.png' },
    ]

    render(<TaskSegmentEditor segment={segment} onContentChange={vi.fn()} />)

    expect(screen.getByTestId('task-image-grid').className).toContain('grid-cols-3')
  })

  it('uses locale messages for task mode and prompt labels', () => {
    render(
      <LocaleContext.Provider value="zh">
        <TaskSegmentEditor segment={taskSegment()} onContentChange={vi.fn()} />
      </LocaleContext.Provider>,
    )

    expect(screen.getByRole('combobox').textContent).toContain('首尾生视频')
    expect(screen.getByRole('textbox', { name: '提示词' })).not.toBeNull()
    expect(screen.getByLabelText('任务图片拖放区域')).not.toBeNull()
  })

  it('opens an @ resource menu with task images and populated media tracks', () => {
    const onContentChange = vi.fn()
    const audio = videoSegment(0, 3)
    audio.id = 'audio-segment'
    audio.content = { media_type: 'audio', file_path: 'voice.wav' }
    render(
      <TaskSegmentEditor
        segment={taskSegment()}
        mediaTracks={[
          mediaTrack('audio', [audio]),
          mediaTrack('video', [videoSegment(0, 3)]),
          { ...mediaTrack('video', []), id: 'empty-video-track', name: 'Empty video track' },
        ]}
        onContentChange={onContentChange}
      />,
    )

    const prompt = screen.getByRole('textbox', { name: 'Prompt' })
    inputEditable(prompt, '@')

    const menu = screen.getByRole('listbox', { name: 'Reference resources' })
    expect(menu.parentElement?.classList.contains('comfyui-easy-media')).toBe(true)
    expect(menu.className).toContain('bg-popover')
    expect(menu.textContent).toContain('Picture 1')
    expect(menu.textContent).toContain('Picture 2')
    expect(menu.textContent).toContain('Audio 1')
    expect(menu.textContent).toContain('Audio 2')
    expect(menu.textContent).toContain('Video 1')
    expect(menu.textContent).not.toContain('Empty video track')
    expect(screen.getByRole('option', { name: /Audio 1 Source video track/ })).not.toBeNull()
    expect(screen.getByRole('option', { name: /Audio 2 Voice track/ })).not.toBeNull()

    expect(screen.getByRole('option', { name: /Picture 1/ }).getAttribute('aria-selected')).toBe('true')
    fireEvent.keyDown(prompt, { key: 'Enter' })

    expect(onContentChange).toHaveBeenLastCalledWith({ user_prompt: '@Picture 1' })
    expect(screen.queryByRole('listbox', { name: 'Reference resources' })).toBeNull()
    const chip = prompt.querySelector('[data-prompt-reference-token="@Picture 1"]')
    expect(chip?.querySelector('img')?.getAttribute('src')).toContain('a.png')
    expect((chip as HTMLElement | null)?.style.color).toBe('var(--multitrack-task-bg)')
  })

  it('shows the interactive MiniMax placeholder only for an empty prompt', () => {
    const onContentChange = vi.fn()
    const segment = taskSegment()
    segment.content.user_prompt = ''
    const { rerender } = render(
      <LocaleContext.Provider value="zh">
        <TaskSegmentEditor segment={segment} format="MiniMax" onContentChange={onContentChange} />
      </LocaleContext.Provider>,
    )

    const prompt = screen.getByRole('textbox', { name: '提示词' })
    expect(prompt.getAttribute('data-placeholder')).toBe('参考模式下最多支持9张图片,3个音频,3个视频, 输入文字或 @ 参考内容, 自由组合图、文、音,视频多元素,定义精彩互动。例如 @图片1 模仿 @视频1 的动作,音色参考 @音频1。')
    expect(prompt.textContent).toBe('')

    const placeholderTrigger = screen.getByRole('button', { name: '打开引用资源' })
    expect(placeholderTrigger.className).toContain('prompt-reference-chip')
    fireEvent.click(placeholderTrigger)
    fireEvent.click(screen.getByRole('option', { name: /图片1/ }))
    expect(onContentChange).toHaveBeenLastCalledWith({ user_prompt: '@图片1' })

    rerender(
      <LocaleContext.Provider value="zh">
        <TaskSegmentEditor segment={segment} format="Seedance" onContentChange={onContentChange} />
      </LocaleContext.Provider>,
    )
    expect(screen.getByRole('textbox', { name: '提示词' }).getAttribute('data-placeholder')).toBe('双击描述您想要生成的内容...')
    expect(screen.queryByRole('button', { name: '打开引用资源' })).toBeNull()
  })

  it('restores the MiniMax placeholder immediately after deleting back to empty', () => {
    const onContentChange = vi.fn()
    render(<TaskSegmentEditor segment={taskSegment()} format="MiniMax" onContentChange={onContentChange} />)

    const prompt = screen.getByRole('textbox', { name: 'Prompt' })
    prompt.innerHTML = '<br>'
    fireEvent.input(prompt)

    expect(onContentChange).toHaveBeenLastCalledWith({ user_prompt: '' })
    expect(prompt.textContent).toBe('')
    expect(screen.getByRole('button', { name: 'Open reference resources' })).not.toBeNull()
  })

  it('does not open the resource menu when clicking prompt text that already contains @', () => {
    const segment = taskSegment()
    segment.content.user_prompt = 'Keep this @ character'
    render(<TaskSegmentEditor segment={segment} onContentChange={vi.fn()} />)

    const prompt = screen.getByRole('textbox', { name: 'Prompt' })
    fireEvent.focus(prompt)
    fireEvent.click(prompt)

    expect(screen.queryByRole('listbox', { name: 'Reference resources' })).toBeNull()
  })

  it('centers the empty reference state below its header', () => {
    const segment = taskSegment()
    segment.content.images = []
    render(<TaskSegmentEditor segment={segment} mediaTracks={[]} onContentChange={vi.fn()} />)

    const prompt = screen.getByRole('textbox', { name: 'Prompt' })
    inputEditable(prompt, '@')

    const menu = screen.getByRole('listbox', { name: 'Reference resources' })
    const emptyState = screen.getByTestId('reference-resources-empty')
    expect(menu.className).toContain('h-64')
    expect(emptyState.className).toContain('flex-1')
    expect(emptyState.className).toContain('items-center')
    expect(emptyState.className).toContain('justify-center')
    expect(emptyState.className).toContain('text-center')
    expect(emptyState.textContent).toContain('Add task images or media clips to a track first.')
  })

  it('highlights official media tags with thumbnails, Lucide icons, and track colors', () => {
    const segment = taskSegment()
    segment.content.user_prompt = '<Picture 1> <Audio 1> <Audio 2> <Video 1>'
    const audio = videoSegment(0, 3)
    audio.id = 'audio-segment'
    audio.content = { media_type: 'audio', file_path: 'voice.wav' }
    render(
      <TaskSegmentEditor
        segment={segment}
        mediaTracks={[
          mediaTrack('audio', [audio]),
          mediaTrack('video', [videoSegment(0, 3)]),
        ]}
        onContentChange={vi.fn()}
      />,
    )

    const prompt = screen.getByRole('textbox', { name: 'Prompt' })
    const chips = prompt.querySelectorAll('[data-prompt-reference-token]')
    expect(chips).toHaveLength(4)
    expect(chips[0].querySelector('img')?.getAttribute('src')).toContain('a.png')
    expect(chips[1].querySelector('[data-reference-icon="audio"] svg.lucide')).not.toBeNull()
    expect(chips[2].querySelector('[data-reference-icon="audio"] svg.lucide')).not.toBeNull()
    expect(chips[3].querySelector('[data-reference-icon="video"] svg.lucide')).not.toBeNull()
    expect((chips[0] as HTMLElement).className).toContain('align-middle')
    expect((chips[0] as HTMLElement).className).toContain('items-center')
    expect((chips[0] as HTMLElement).className).toContain('leading-none')
    expect((chips[0] as HTMLElement).className).toContain('rounded-md')
    expect((chips[0] as HTMLElement).className).toContain('cursor-pointer')
    expect(chips[0].querySelector('span:last-child')?.className).toContain('items-center')
    expect((chips[0] as HTMLElement).style.borderColor).toBe('var(--multitrack-task-bg)')
    expect((chips[0] as HTMLElement).style.backgroundColor).toContain('color-mix')
    expect((chips[1] as HTMLElement).style.color).toBe('var(--multitrack-video-waveform)')
    expect((chips[1] as HTMLElement).style.borderColor).toBe('var(--multitrack-video-waveform)')
    expect((chips[2] as HTMLElement).style.color).toBe('var(--multitrack-audio-waveform)')
    expect((chips[2] as HTMLElement).style.borderColor).toBe('var(--multitrack-audio-waveform)')
    expect((chips[3] as HTMLElement).style.color).toBe('var(--multitrack-video-waveform)')
    expect((chips[3] as HTMLElement).style.borderColor).toBe('var(--multitrack-video-waveform)')
  })

  it('renders H3 tags as typed chips and emphasizes dialogue text and section headings', () => {
    const segment = taskSegment()
    segment.content.user_prompt = '<Subject 12> (S1,S2) says <d>[Chinese] 你好</d> [English] [Shot 3] <scenetrans> <cutoff> subject_definitions: subject summary: overview retention_analysis: retention detailed_description: detail overall_soundscape: sound non_diegetic_music: music 主体定义:主体 留存分析:结果 详细描述:细节 整体声景:声音 非叙事性音乐:安静 [reference generation]'
    render(<TaskSegmentEditor segment={segment} onContentChange={vi.fn()} />)

    const prompt = screen.getByRole('textbox', { name: 'Prompt' })
    const semantics = prompt.querySelectorAll('[data-prompt-semantic-token]')
    expect(Array.from(semantics, (item) => item.textContent)).toEqual([
      '<Subject 12>',
      '(S1,S2)',
      '<d>',
      '[Chinese]',
      '</d>',
      '[English]',
      '[Shot 3]',
      '<scenetrans>',
      '<cutoff>',
    ])
    expect(Array.from(semantics).every((item) => item.className.includes('prompt-reference-chip'))).toBe(true)
    expect((semantics[0] as HTMLElement).style.color).toBe('var(--highlight)')
    expect(semantics[0].querySelector('[data-semantic-icon="subject"] svg.lucide')).not.toBeNull()
    expect((semantics[1] as HTMLElement).style.color).toBe('var(--prompt-semantic)')
    expect((semantics[2] as HTMLElement).style.color).toBe('var(--prompt-dialogue)')
    expect(semantics[2].querySelector('[data-semantic-icon="dialogue"] svg.lucide')).not.toBeNull()
    expect((semantics[3] as HTMLElement).style.color).toBe('')
    expect(semantics[3].className).toContain('border-border')
    expect(semantics[3].className).toContain('bg-background')
    expect(semantics[3].className).toContain('text-foreground')
    expect((semantics[3] as HTMLElement).style.borderColor).toBe('')
    expect((semantics[5] as HTMLElement).style.color).toBe('')
    expect(semantics[5].className).toContain('border-border')
    expect(semantics[5].className).toContain('bg-background')
    expect((semantics[4] as HTMLElement).style.color).toBe('var(--prompt-dialogue)')
    expect((semantics[6] as HTMLElement).style.color).toBe('')
    expect(semantics[6].className).toContain('border-border')
    expect(semantics[6].className).toContain('bg-background')
    expect(semantics[6].className).toContain('text-foreground')
    expect((semantics[6] as HTMLElement).style.borderColor).toBe('')
    const dialogue = prompt.querySelector('[data-prompt-dialogue-content]')
    expect(dialogue?.className).toContain('font-semibold')
    expect(dialogue?.className).toContain('text-muted-foreground')
    expect(dialogue?.textContent).toBe(' 你好')
    const emphasis = prompt.querySelectorAll('[data-prompt-emphasis-text]')
    expect(Array.from(emphasis, (item) => item.textContent)).toEqual([
      'subject_definitions: ',
      'summary: ',
      'retention_analysis: ',
      'detailed_description: ',
      'overall_soundscape: ',
      'non_diegetic_music: ',
      '主体定义:',
      '留存分析:',
      '详细描述:',
      '整体声景:',
      '非叙事性音乐:',
    ])
    expect(Array.from(emphasis).every((item) => (
      item.className.includes('font-semibold') && item.className.includes('text-muted-foreground')
    ))).toBe(true)
    expect(prompt.textContent).toContain('[reference generation]')
  })

  it('inserts a plain line break after an H3 section heading without duplicating it', () => {
    const onContentChange = vi.fn()
    const segment = taskSegment()
    segment.content.user_prompt = 'non_diegetic_music:'
    render(<TaskSegmentEditor segment={segment} onContentChange={onContentChange} />)

    const prompt = screen.getByRole('textbox', { name: 'Prompt' })
    const heading = prompt.querySelector('[data-prompt-emphasis-text]')
    expect(heading?.textContent).toBe('non_diegetic_music:')

    prompt.focus()
    const selection = window.getSelection()
    const range = document.createRange()
    range.setStartAfter(heading as Node)
    range.collapse(true)
    selection?.removeAllRanges()
    selection?.addRange(range)
    fireEvent.keyDown(prompt, { key: 'Enter' })

    expect(onContentChange).toHaveBeenLastCalledWith({
      user_prompt: 'non_diegetic_music:\n',
    })
    expect(prompt.querySelectorAll('[data-prompt-emphasis-text]')).toHaveLength(1)
    expect(prompt.textContent?.match(/non_diegetic_music:/g)).toHaveLength(1)
  })

  it('does not restore a stale H3 heading after replacing the full prompt', () => {
    const onContentChange = vi.fn()
    const segment = taskSegment()
    segment.content.user_prompt = 'subject_definitions: old subject'
    render(<TaskSegmentEditor segment={segment} onContentChange={onContentChange} />)

    const prompt = screen.getByRole('textbox', { name: 'Prompt' })
    const staleHeading = prompt.querySelector('[data-prompt-emphasis-text]') as HTMLElement
    staleHeading.textContent = ''
    while (staleHeading.nextSibling) staleHeading.nextSibling.remove()
    prompt.append(document.createTextNode('subject_definitions: new subject'))
    fireEvent.input(prompt)

    expect(onContentChange).toHaveBeenLastCalledWith({
      user_prompt: 'subject_definitions: new subject',
    })
    expect(prompt.textContent?.match(/subject_definitions:/g)).toHaveLength(1)
  })

  it('opens the reference picker from media chips and preserves their token syntax when replacing them', () => {
    const onContentChange = vi.fn()
    const segment = taskSegment()
    segment.content.user_prompt = '@Picture 1 then <Picture 2>'
    const audio = videoSegment(0, 3)
    audio.id = 'audio-segment'
    audio.content = { media_type: 'audio', file_path: 'voice.wav' }
    render(
      <TaskSegmentEditor
        segment={segment}
        mediaTracks={[
          mediaTrack('audio', [audio]),
          mediaTrack('video', [videoSegment(0, 3)]),
        ]}
        onContentChange={onContentChange}
      />,
    )

    const prompt = screen.getByRole('textbox', { name: 'Prompt' })
    fireEvent.click(prompt.querySelector('[data-prompt-reference-token="@Picture 1"]') as HTMLElement)
    fireEvent.click(screen.getByRole('option', { name: /Video 1 Source video track/ }))
    expect(onContentChange).toHaveBeenLastCalledWith({ user_prompt: '@Video 1 then <Picture 2>' })

    fireEvent.click(prompt.querySelector('[data-prompt-reference-token="<Picture 2>"]') as HTMLElement)
    fireEvent.click(screen.getByRole('option', { name: /Audio 2 Voice track/ }))
    expect(onContentChange).toHaveBeenLastCalledWith({ user_prompt: '@Video 1 then <Audio 2>' })
  })

  it('keeps reference tokens stable when typing adjacent text', () => {
    const onContentChange = vi.fn()
    const segment = taskSegment()
    segment.content.user_prompt = '@Picture 1'
    render(<TaskSegmentEditor segment={segment} onContentChange={onContentChange} />)

    const prompt = screen.getByRole('textbox', { name: 'Prompt' })
    const chip = prompt.querySelector('[data-prompt-reference-token="@Picture 1"]')
    expect(chip).not.toBeNull()
    chip?.after(document.createTextNode(' moves forward'))
    fireEvent.input(prompt)

    expect(onContentChange).toHaveBeenLastCalledWith({ user_prompt: '@Picture 1 moves forward' })
    expect(prompt.querySelector('[data-prompt-reference-token="@Picture 1"]')).toBe(chip)
  })

  it('pastes plain text into the prompt without bubbling to the ComfyUI canvas', () => {
    const onContentChange = vi.fn()
    const onCanvasPaste = vi.fn()
    const segment = taskSegment()
    segment.content.user_prompt = ''
    render(
      <div onPaste={onCanvasPaste}>
        <TaskSegmentEditor segment={segment} onContentChange={onContentChange} />
      </div>,
    )

    const prompt = screen.getByRole('textbox', { name: 'Prompt' })
    prompt.focus()
    const range = document.createRange()
    range.selectNodeContents(prompt)
    range.collapse(false)
    const selection = window.getSelection()
    selection?.removeAllRanges()
    selection?.addRange(range)
    fireEvent.paste(prompt, {
      clipboardData: {
        getData: (type: string) => type === 'text/plain' ? '<Picture 1> moves' : '',
      },
    })

    expect(onCanvasPaste).not.toHaveBeenCalled()
    expect(onContentChange).toHaveBeenLastCalledWith({ user_prompt: '<Picture 1> moves' })
    expect(prompt.querySelector('[data-prompt-reference-token="<Picture 1>"]')).not.toBeNull()
  })

  it('copies newly inserted reference chips as their prompt tag text', () => {
    render(<TaskSegmentEditor segment={taskSegment()} onContentChange={vi.fn()} />)

    const prompt = screen.getByRole('textbox', { name: 'Prompt' })
    inputEditable(prompt, '@')
    fireEvent.keyDown(prompt, { key: 'Enter' })
    expect(prompt.querySelector('[data-prompt-reference-token="@Picture 1"]')).not.toBeNull()

    const selection = window.getSelection()
    const selectAll = document.createRange()
    selectAll.selectNodeContents(prompt)
    selection?.removeAllRanges()
    selection?.addRange(selectAll)
    const setData = vi.fn()
    fireEvent.copy(prompt, {
      clipboardData: { setData },
    })

    expect(setData).toHaveBeenCalledWith('text/plain', '@Picture 1')
  })

  it('deletes a reference chip as one atomic value with Backspace', () => {
    const onContentChange = vi.fn()
    const segment = taskSegment()
    segment.content.user_prompt = 'Before <Picture 1> after'
    render(<TaskSegmentEditor segment={segment} onContentChange={onContentChange} />)

    const prompt = screen.getByRole('textbox', { name: 'Prompt' })
    const chip = prompt.querySelector('[data-prompt-reference-token="<Picture 1>"]')
    expect(chip).not.toBeNull()
    prompt.focus()
    const selection = window.getSelection()
    const range = document.createRange()
    range.setStartAfter(chip!)
    range.collapse(true)
    selection?.removeAllRanges()
    selection?.addRange(range)

    fireEvent.keyDown(prompt, { key: 'Backspace' })

    expect(onContentChange).toHaveBeenLastCalledWith({ user_prompt: 'Before  after' })
    expect(prompt.querySelector('[data-prompt-reference-token]')).toBeNull()
  })

  it('loads system prompt options once and matches the current task state locally', async () => {
    const onContentChange = vi.fn()
    const fetchMock = vi.fn().mockResolvedValue({
      ok: true,
      json: async () => ({
        items: [
          { task_type: 't2v', system_prompt: 'Default text-to-video template' },
          { task_type: 'i2v', system_prompt: 'Default image-to-video template' },
          { task_type: 'r2v', system_prompt: 'Default reference-to-video template' },
          { task_type: 'rv2v', system_prompt: 'Default reference-edit template' },
          { modes: ['default', 'l2v'], format: 'MiniMax', system_prompt: 'MiniMax base template' },
          { modes: ['ref', 'edit'], format: 'MiniMax', system_prompt: 'MiniMax reference template' },
        ],
      }),
    })
    vi.stubGlobal('fetch', fetchMock)

    const { rerender, unmount } = render(<TaskSegmentEditor segment={taskSegment()} onContentChange={onContentChange} />)

    fireEvent.click(screen.getByRole('button', { name: 'System Prompt' }))
    const systemPrompt = await screen.findByRole('textbox', { name: 'System Prompt' }) as HTMLElement
    await waitFor(() => {
      expect(systemPrompt.textContent).toBe('Default image-to-video template')
    })

    const resetSegment = {
      ...taskSegment(),
      content: {
        ...taskSegment().content,
        system_prompt: '',
      },
    }
    rerender(<TaskSegmentEditor segment={resetSegment} onContentChange={onContentChange} />)
    expect(systemPrompt.textContent).toBe('Default image-to-video template')

    const refSegment = {
      ...taskSegment(),
      content: {
        ...taskSegment().content,
        task_mode: 'ref' as const,
      },
    }
    rerender(<TaskSegmentEditor segment={refSegment} onContentChange={onContentChange} />)
    await waitFor(() => {
      expect(systemPrompt.textContent).toBe('Default reference-to-video template')
    })

    rerender(
      <TaskSegmentEditor
        segment={refSegment}
        videoSegments={[videoSegment(2, 5)]}
        onContentChange={onContentChange}
      />,
    )
    await waitFor(() => {
      expect(systemPrompt.textContent).toBe('Default reference-edit template')
    })

    rerender(<TaskSegmentEditor segment={resetSegment} format="MiniMax" onContentChange={onContentChange} />)
    await waitFor(() => {
      expect(systemPrompt.textContent).toBe('MiniMax base template')
    })

    rerender(<TaskSegmentEditor segment={refSegment} format="MiniMax" onContentChange={onContentChange} />)
    await waitFor(() => {
      expect(systemPrompt.textContent).toBe('MiniMax reference template')
    })
    expect(fetchMock).toHaveBeenCalledTimes(1)
    expect(fetchMock).toHaveBeenCalledWith('/easy-media/prompt/system-prompts')

    unmount()
    render(<TaskSegmentEditor segment={refSegment} onContentChange={onContentChange} />)
    fireEvent.click(screen.getByRole('button', { name: 'System Prompt' }))
    const remountedSystemPrompt = await screen.findByRole('textbox', { name: 'System Prompt' }) as HTMLElement
    expect(remountedSystemPrompt.textContent).toBe('Default reference-to-video template')
    expect(fetchMock).toHaveBeenCalledTimes(1)
  })

  it('edits a customized system prompt and highlights complete placeholders', () => {
    const onContentChange = vi.fn()
    const customizedSegment = {
      ...taskSegment(),
      content: {
        ...taskSegment().content,
        system_prompt: 'Create {subject} in <style> with <Picture 1> and @图片1',
      },
    }
    const { container } = render(
      <TooltipProvider>
        <TaskSegmentEditor segment={customizedSegment} onContentChange={onContentChange} />
      </TooltipProvider>,
    )

    fireEvent.click(screen.getByRole('button', { name: 'System Prompt' }))
    const textarea = screen.getByRole('textbox', { name: 'System Prompt' }) as HTMLElement
    const highlightedVariables = container.querySelectorAll('[data-system-prompt-variable="true"]')

    expect(textarea.getAttribute('contenteditable')).toBe('true')
    expect(textarea.classList.contains('text-transparent')).toBe(false)
    expect(textarea.classList.contains('caret-foreground')).toBe(true)
    expect(Array.from(highlightedVariables, (item) => item.textContent)).toEqual(['{subject}', '<style>', '<Picture 1>'])
    expect(textarea.querySelectorAll('[data-prompt-reference-token]')).toHaveLength(0)
    expect(textarea.textContent).toBe('Create {subject} in <style> with <Picture 1> and @图片1')

    inputEditable(textarea, 'Create {character} in <location>')

    expect(onContentChange).toHaveBeenCalledWith({ system_prompt: 'Create {character} in <location>' })
  })

  it('keeps the caret position when completing a highlighted tag after a line break', () => {
    const onContentChange = vi.fn()
    const segment = taskSegment()
    segment.content.system_prompt = 'first\n<style'
    render(
      <TooltipProvider>
        <TaskSegmentEditor segment={segment} onContentChange={onContentChange} />
      </TooltipProvider>,
    )

    fireEvent.click(screen.getByRole('button', { name: 'System Prompt' }))
    const editor = screen.getByRole('textbox', { name: 'System Prompt' })
    const secondLine = editor.childNodes[2]
    expect(secondLine.nodeType).toBe(Node.TEXT_NODE)
    const textNode = secondLine as Text
    textNode.insertData(textNode.length, '>')
    const range = document.createRange()
    range.setStart(textNode, textNode.length)
    range.collapse(true)
    const selection = window.getSelection()
    selection?.removeAllRanges()
    selection?.addRange(range)
    fireEvent.input(editor)

    expect(onContentChange).toHaveBeenLastCalledWith({ system_prompt: 'first\n<style>' })
    const highlighted = editor.querySelector('[data-system-prompt-variable="true"]')
    expect(highlighted?.textContent).toBe('<style>')
    expect(selection?.anchorNode).toBe(highlighted?.firstChild)
    expect(selection?.anchorOffset).toBe('<style>'.length)
  })

  it('resets a customized system prompt with an icon button and tooltip', async () => {
    const onContentChange = vi.fn()
    const customizedSegment = {
      ...taskSegment(),
      content: {
        ...taskSegment().content,
        system_prompt: 'Customized system prompt',
      },
    }
    render(
      <TooltipProvider>
        <TaskSegmentEditor segment={customizedSegment} onContentChange={onContentChange} />
      </TooltipProvider>,
    )

    fireEvent.click(screen.getByRole('button', { name: 'System Prompt' }))
    const resetButton = screen.getByRole('button', { name: 'Reset system prompt' })

    expect(resetButton.textContent).toBe('')
    expect(resetButton.querySelector('svg.lucide-rotate-ccw')).not.toBeNull()

    fireEvent.focus(resetButton)
    const tooltip = await screen.findByRole('tooltip')
    expect(tooltip.textContent).toBe('Reset system prompt')

    fireEvent.click(resetButton)

    expect(onContentChange).toHaveBeenCalledWith({ system_prompt: '' })
  })

  it('does not show the system prompt reset button for a default system prompt', () => {
    render(<TaskSegmentEditor segment={taskSegment()} onContentChange={vi.fn()} />)

    fireEvent.click(screen.getByRole('button', { name: 'System Prompt' }))

    expect(screen.queryByRole('button', { name: 'Reset system prompt' })).toBeNull()
  })

  it('edits all task prompts in combined mode and hides image selection', () => {
    const onTrackSegmentsContentChange = vi.fn()
    render(
      <TaskSegmentEditor
        segment={taskSegment()}
        trackSegments={[taskSegment(), secondTaskSegment()]}
        onContentChange={vi.fn()}
        onTrackSegmentsContentChange={onTrackSegmentsContentChange}
      />,
    )

    activateTab('Combined')

    expect(screen.queryByLabelText('Task image drop zone')).toBeNull()
    expect(screen.queryByRole('button', { name: 'User Prompt' })).toBeNull()
    expect(screen.queryByRole('button', { name: 'System Prompt' })).toBeNull()
    expect(screen.getByText('Use | to separate segments. Changes apply in real-time.')).not.toBeNull()
    inputEditable(screen.getByRole('textbox', { name: 'Prompt' }), 'First rewritten|Second rewritten')

    expect(onTrackSegmentsContentChange).toHaveBeenCalledWith([
      { segmentId: 'task-segment', patch: { user_prompt: 'First rewritten' } },
      { segmentId: 'task-segment-2', patch: { user_prompt: 'Second rewritten' } },
    ])
  })

  it('reads and writes each task selected A/B prompt in combined mode', () => {
    const onTrackSegmentsContentChange = vi.fn()
    const first = taskSegment()
    const second = secondTaskSegment()
    second.content.user_prompt_b = 'Selected B prompt'
    second.content.user_prompt_variant = 'b'
    render(
      <TaskSegmentEditor
        segment={first}
        trackSegments={[first, second]}
        onContentChange={vi.fn()}
        onTrackSegmentsContentChange={onTrackSegmentsContentChange}
      />,
    )

    activateTab('Combined')
    const prompt = screen.getByRole('textbox', { name: 'Prompt' })
    expect(prompt.textContent).toBe('Initial prompt|Selected B prompt')

    inputEditable(prompt, 'Updated A|Updated B')

    expect(onTrackSegmentsContentChange).toHaveBeenCalledWith([
      { segmentId: 'task-segment', patch: { user_prompt: 'Updated A' } },
      { segmentId: 'task-segment-2', patch: { user_prompt_b: 'Updated B' } },
    ])
  })

  it('creates and evenly distributes task segments when combined pasted text has more parts', () => {
    const onTrackSegmentsChange = vi.fn()
    render(
      <TaskSegmentEditor
        segment={taskSegment()}
        trackSegments={[taskSegment(), secondTaskSegment()]}
        totalFrames={10}
        onContentChange={vi.fn()}
        onTrackSegmentsChange={onTrackSegmentsChange}
      />,
    )

    activateTab('Combined')
    const prompt = screen.getByRole('textbox', { name: 'Prompt' }) as HTMLElement
    inputEditable(prompt, 'First pasted|Second pasted|Third pasted')

    expect(prompt.textContent).toBe('First pasted|Second pasted|Third pasted')
    const highlight = screen.getByTestId('combined-prompt-highlight')
    expect(highlight.querySelectorAll('[data-pipe="true"]')).toHaveLength(2)
    expect(highlight.querySelector('[data-pipe="true"]')?.className).toContain('text-highlight')
    const updated = onTrackSegmentsChange.mock.lastCall?.[0] as MultiTrackSegment[]
    expect(updated).toHaveLength(3)
    expect(updated.map(({ start_frame, end_frame, content }) => ({
      start_frame,
      end_frame,
      user_prompt: content.user_prompt,
    }))).toEqual([
      { start_frame: 0, end_frame: 4, user_prompt: 'First pasted' },
      { start_frame: 4, end_frame: 7, user_prompt: 'Second pasted' },
      { start_frame: 7, end_frame: 10, user_prompt: 'Third pasted' },
    ])
    expect(updated[0].id).toBe('task-segment')
    expect(updated[1].id).toBe('task-segment-2')
    expect(updated[2]).toMatchObject({
      content: { media_type: 'none', task_mode: 'default', images: [] },
    })

    inputEditable(prompt, '')
    const cleared = onTrackSegmentsChange.mock.lastCall?.[0] as MultiTrackSegment[]
    expect(cleared).toHaveLength(1)
    expect(cleared[0]).toMatchObject({
      id: 'task-segment',
      start_frame: 0,
      end_frame: 10,
      content: { user_prompt: '' },
    })
  })

  it('shows and edits the selected task duration in the center of the footer', () => {
    const onDurationChange = vi.fn()
    const { rerender } = render(
      <TaskSegmentEditor
        segment={secondTaskSegment()}
        trackSegments={[taskSegment(), secondTaskSegment()]}
        frameRate={24}
        onContentChange={vi.fn()}
        onDurationChange={onDurationChange}
      />,
    )

    expect(screen.getByText('Segment 2').className).toContain('text-[10px]')
    expect(screen.getByText('Segment 2').className).toContain('text-primary')
    expect(screen.getByText('00:00:03').className).toContain('text-[10px]')

    fireEvent.click(screen.getByRole('button', { name: 'Edit task duration' }))
    expect(screen.queryByText('Segment 2')).toBeNull()
    expect(screen.queryByText('00:00:03')).toBeNull()
    const durationInput = screen.getByRole('textbox', { name: 'Duration' })
    expect(durationInput.className).toContain('tabular-nums')
    expect(durationInput.getAttribute('placeholder')).toBe('00:00:00')
    fireEvent.change(durationInput, { target: { value: '00:01:12' } })
    fireEvent.keyDown(durationInput, { key: 'Enter' })
    expect(onDurationChange).toHaveBeenCalledWith(1.5)

    const updatedSegment = { ...secondTaskSegment(), end_frame: 39 }
    rerender(
      <TaskSegmentEditor
        segment={updatedSegment}
        trackSegments={[taskSegment(), updatedSegment]}
        frameRate={24}
        onContentChange={vi.fn()}
        onDurationChange={onDurationChange}
      />,
    )
    expect(screen.getByText('00:01:12')).not.toBeNull()

    fireEvent.click(screen.getByRole('button', { name: 'Edit task duration' }))
    const invalidDurationInput = screen.getByRole('textbox', { name: 'Duration' })
    fireEvent.change(invalidDurationInput, { target: { value: '00:61:00' } })
    fireEvent.blur(invalidDurationInput)
    expect(screen.getByText('00:01:12')).not.toBeNull()
    expect(onDurationChange).toHaveBeenCalledTimes(1)
  })

  it('uses responsive preview editor sizing without rendering the empty image picker as a button element', () => {
    const emptyImageSegment = {
      ...taskSegment(),
      content: {
        ...taskSegment().content,
        images: [],
      },
    }
    render(<TaskSegmentEditor segment={emptyImageSegment} onContentChange={vi.fn()} />)

    expect(screen.getByTestId('task-image-drop-zone').className).toContain('w-full')
    expect(screen.getByRole('button', { name: 'Task image drop zone' }).tagName).not.toBe('BUTTON')
    expect(screen.getByRole('textbox', { name: 'Prompt' }).className).toContain('text-[10px]')
  })

  it('shows connected image inputs in the media selector slot list', () => {
    const emptyImageSegment = {
      ...taskSegment(),
      content: {
        ...taskSegment().content,
        images: [],
      },
    }
    const sourceNode = {
      outputs: [{ shape: 0 }],
      imgs: [{ currentSrc: '/view?filename=reference.png&type=input' }],
    }
    const node = {
      inputs: [{ name: 'image', type: 'IMAGE', link: 7 }],
    }
    const app = {
      graph: {
        links: { 7: { origin_id: 3, origin_slot: 0 } },
        getNodeById: (id: number) => id === 3 ? sourceNode : null,
      },
    }

    render(
      <TaskSegmentEditor
        segment={emptyImageSegment}
        node={node}
        app={app}
        onContentChange={vi.fn()}
      />,
    )

    fireEvent.click(screen.getByRole('button', { name: 'Task image drop zone' }))
    expect(screen.getByTestId('media-selector-mock').getAttribute('data-slot-items'))
      .toBe('__slot__:image')
  })
})