hit-cxf
2026-05-14 cd6e29c9d3a49e5b0ea2a8dcbfd0253996ae9a6d
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
'use client';
 
import { useEffect, useMemo, useState } from 'react';
import {
  ArrowRight,
  CheckCircle,
  Clapperboard,
  Clock,
  Image as ImageIcon,
  Lightbulb,
  Loader2,
  Play,
  RefreshCw,
  Repeat2,
  Settings2,
  SlidersHorizontal,
  Upload,
  UserRound,
  Video,
  Volume2,
  X,
  XCircle,
} from 'lucide-react';
import clsx from 'clsx';
import {
  fetchApiModels,
  fetchStandardTemplates,
  deletePipelineTask,
  fetchPipelineTask,
  fetchPipelineTasks,
  startActionTransferPipeline,
  startDigitalHumanPipeline,
  startStandardPipeline,
  subscribePipelineTask,
  uploadPipelineMedia,
  type PipelineTask,
  type PipelineTaskEvent,
  type ApiModelOption,
  type StandardTemplateOption,
} from '@/lib/workflowApi';
import {
  I2I_PROVIDERS,
  LLM_PROVIDERS,
  T2I_PROVIDERS,
  VIDEO_PROVIDERS,
  VIDEO_RATIOS,
  type ProviderGroup,
} from '@/config/models';
import BrandHeader from '@/components/BrandHeader';
 
type PipelineId = 'standard' | 'action_transfer' | 'digital_human';
 
interface PipelinePageProps {
  pipeline: PipelineId;
  title: string;
  subtitle: string;
}
 
const DEFAULTS = {
  llm: LLM_PROVIDERS.flatMap(p => p.models).find(m => m.default)?.id || LLM_PROVIDERS[0].models[0].id,
  image: T2I_PROVIDERS.flatMap(p => p.models).find(m => m.default)?.id || T2I_PROVIDERS[0].models[0].id,
  editImage: I2I_PROVIDERS.flatMap(p => p.models).find(m => m.default)?.id || I2I_PROVIDERS[0].models[0].id,
  video: VIDEO_PROVIDERS.flatMap(p => p.models).find(m => m.default)?.id || VIDEO_PROVIDERS[0].models[0].id,
};
 
const STANDARD_STYLE_PRESETS = [
  {
    label: '印象油画',
    prompt:
      'Impressionist painting style, visible broken brushstrokes, pure colors juxtaposed. The scene is bathed in natural, fleeting light with a shimmering, grainy texture in the air. Soft, blurred outlines, emphasizing color contrast over precise lines. Slight oil paint canvas texture, warm and luminous tone.',
  },
  {
    label: '极简线条',
    prompt:
      'Minimalist black-and-white matchstick figure style illustration, clean lines, simple sketch style',
  },
  {
    label: '中国水墨',
    prompt:
      'Traditional Chinese ink wash painting style, visible xuan paper texture. Layered ink tones from deep black to pale gray, with dry brush strokes (feibai) and natural ink bleeding. Expressive and spontaneous brushwork, large negative space (liubai), interplay between solid and void. Wet and dry contrast, calligraphic rhythm in lines. Minimal color palette, a hint of light ochre or floral blue.',
  },
  {
    label: '写实',
    prompt:
      'Photorealistic cinematic style, 8K resolution, physically accurate. Natural or practical lighting with sharp shadow edges. Materials exhibit realistic specular reflection and roughness, subtle surface textures and imperfections visible. Natural depth of field (sharp foreground with blurred background or vice versa). Motion includes inertial easing, mimicking real human eye observation. No stylized filters, true-to-life color reproduction.',
  },
];
 
const DEFAULT_STANDARD_STYLE_CONTROL = STANDARD_STYLE_PRESETS[0].prompt;
 
const TEMPLATE_TEXT_DEFAULTS = {
  title: '山河入梦',
  text: '心之所向,素履而往',
};
 
const TEMPLATE_FIELD_LABELS: Record<string, string> = {
  author: 'author',
  describe: 'describe',
  brand: 'brand',
  signature: 'signature',
  subtitle: 'subtitle',
};
 
const STATUS_STYLE: Record<string, string> = {
  pending: 'bg-gray-100 text-gray-500',
  running: 'bg-blue-50 text-blue-600',
  completed: 'bg-green-50 text-green-600',
  failed: 'bg-red-50 text-red-600',
};
 
const PIPELINE_TITLE_ICONS = {
  standard: Clapperboard,
  action_transfer: Repeat2,
  digital_human: UserRound,
};
 
function SelectField({
  label,
  value,
  onChange,
  groups,
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  groups: ProviderGroup[];
}) {
  return (
    <label className="flex flex-col gap-1.5 min-w-0">
      <span className="text-xs font-medium text-gray-500">{label}</span>
      <select
        value={value}
        onChange={e => onChange(e.target.value)}
        className="h-10 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-700 outline-none focus:border-blue-300"
      >
        {groups.map(group => (
          <optgroup key={group.provider} label={group.label}>
            {group.models.map(model => (
              <option key={model.id} value={model.id}>{model.label}</option>
            ))}
          </optgroup>
        ))}
      </select>
    </label>
  );
}
 
function groupApiModels(models: ApiModelOption[], fallback: ProviderGroup[]): ProviderGroup[] {
  if (!models.length) return fallback;
  const providerLabels: Record<string, string> = {
    dashscope: 'DashScope',
    openai: 'OpenAI',
    seedream: 'Seedream',
    seedance: 'Seedance',
    kling: 'Kling',
  };
  const groups = new Map<string, ProviderGroup>();
  for (const model of models) {
    if (!groups.has(model.provider)) {
      groups.set(model.provider, {
        provider: model.provider,
        label: providerLabels[model.provider] || model.provider,
        models: [],
      });
    }
    groups.get(model.provider)!.models.push({
      id: model.id,
      label: model.label || model.id,
      default: model.api_contract_verified,
    });
  }
  return Array.from(groups.values());
}
 
function firstModelId(groups: ProviderGroup[], preferred?: string) {
  const models = groups.flatMap(group => group.models);
  if (preferred && models.some(model => model.id === preferred)) return preferred;
  return models.find(model => model.default)?.id || models[0]?.id || '';
}
 
function TextInput({
  label,
  value,
  onChange,
  placeholder,
  required,
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  required?: boolean;
}) {
  return (
    <label className="flex flex-col gap-1.5 min-w-0">
      <span className="text-xs font-medium text-gray-500">{label}{required ? ' *' : ''}</span>
      <input
        value={value}
        onChange={e => onChange(e.target.value)}
        placeholder={placeholder}
        className="h-10 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-700 outline-none focus:border-blue-300"
      />
    </label>
  );
}
 
function MediaUploadField({
  label,
  value,
  onChange,
  accept,
  placeholder,
  required,
}: {
  label: string;
  value: string;
  onChange: (value: string) => void;
  accept: string;
  placeholder: string;
  required?: boolean;
}) {
  const [uploading, setUploading] = useState(false);
  const [filename, setFilename] = useState('');
  const [error, setError] = useState('');
 
  const handleUpload = async (file?: File) => {
    if (!file) return;
    setUploading(true);
    setError('');
    try {
      const result = await uploadPipelineMedia(file);
      setFilename(result.filename);
      onChange(result.file_path);
    } catch (e: any) {
      setError(e.message || '上传失败');
    } finally {
      setUploading(false);
    }
  };
 
  return (
    <label className="flex flex-col gap-1.5 min-w-0">
      <span className="text-xs font-medium text-gray-500">{label}{required ? ' *' : ''}</span>
      <div className="flex gap-2">
        <input
          value={value}
          onChange={e => {
            setFilename('');
            onChange(e.target.value);
          }}
          placeholder={placeholder}
          className="h-10 min-w-0 flex-1 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-700 outline-none focus:border-blue-300"
        />
        <div className="relative flex-shrink-0">
          <input
            type="file"
            accept={accept}
            onChange={e => handleUpload(e.target.files?.[0])}
            className="absolute inset-0 opacity-0 cursor-pointer"
            disabled={uploading}
          />
          <button
            type="button"
            className={clsx(
              'h-10 w-10 rounded-lg border flex items-center justify-center transition-colors',
              uploading
                ? 'border-gray-100 bg-gray-50 text-gray-300'
                : 'border-gray-200 bg-white text-gray-500 hover:border-blue-200 hover:bg-blue-50 hover:text-blue-600'
            )}
            title="上传媒体"
          >
            {uploading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Upload className="w-4 h-4" />}
          </button>
        </div>
        {value && (
          <button
            type="button"
            onClick={() => {
              setFilename('');
              onChange('');
            }}
            className="h-10 w-10 rounded-lg border border-gray-200 bg-white text-gray-400 hover:bg-gray-50 hover:text-red-500 flex items-center justify-center flex-shrink-0"
            title="清除"
          >
            <X className="w-4 h-4" />
          </button>
        )}
      </div>
      {(filename || error) && (
        <span className={clsx('text-[10px] truncate', error ? 'text-red-500' : 'text-gray-400')}>
          {error || filename}
        </span>
      )}
    </label>
  );
}
 
function NumberField({
  label,
  value,
  onChange,
  min,
  max,
}: {
  label: string;
  value: number;
  onChange: (value: number) => void;
  min: number;
  max: number;
}) {
  return (
    <label className="flex flex-col gap-1.5 min-w-0">
      <span className="text-xs font-medium text-gray-500">{label}</span>
      <input
        type="number"
        min={min}
        max={max}
        value={value}
        onChange={e => onChange(Number(e.target.value))}
        className="h-10 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-700 outline-none focus:border-blue-300"
      />
    </label>
  );
}
 
function assetHref(path?: string) {
  if (!path) return '';
  if (/^(https?:|data:|file:)/.test(path)) return path;
  const marker = '/code/';
  const idx = path.indexOf(marker);
  if (idx >= 0) return `/code/${path.slice(idx + marker.length)}`;
  return path;
}
 
function statusText(status?: string) {
  if (status === 'pending') return '等待中';
  if (status === 'running') return '生成中';
  if (status === 'completed') return '已完成';
  if (status === 'failed') return '失败';
  return status || '未知';
}
 
function taskTitle(task: PipelineTask) {
  const input = task.input || {};
  return input.title || input.goods_title || input.text || input.prompt_text || input.goods_text || task.task_id;
}
 
type PipelineArtifact = NonNullable<PipelineTask['artifacts']>[number];
 
function isFinalVideoArtifact(item: PipelineArtifact) {
  if (item.kind !== 'video') return false;
  const name = (item.name || '').toLowerCase();
  const path = (item.path || '').toLowerCase();
  return name === 'final' || path.endsWith('/final.mp4') || path.endsWith('\\final.mp4');
}
 
function FinalVideoResult({ item }: { item?: PipelineArtifact }) {
  return (
    <section className="mb-4 rounded-xl border border-blue-100 bg-blue-50/40 p-3">
      <div className="mb-2 flex items-center gap-2">
        <Video className="w-4 h-4 text-blue-600" />
        <h3 className="text-sm font-semibold text-gray-800">最终视频</h3>
      </div>
      {item ? (
        <div className="overflow-hidden rounded-lg border border-gray-200 bg-black">
          <video src={assetHref(item.path)} controls className="w-full max-h-72 object-contain" />
        </div>
      ) : (
        <div className="h-36 rounded-lg border border-dashed border-blue-200 bg-white/60 flex items-center justify-center text-sm text-gray-400">
          最终视频生成后显示
        </div>
      )}
    </section>
  );
}
 
function TaskResult({ task }: { task: PipelineTask | null }) {
  const progress = Math.max(0, Math.min(100, task?.progress || 0));
 
  if (!task) {
    return (
      <div className="bg-white rounded-2xl border border-gray-200 p-5 shadow-sm h-full">
        <div className="flex items-center justify-between gap-3 mb-3">
          <div className="flex items-center gap-2 min-w-0">
            <SlidersHorizontal className="w-4 h-4 text-gray-400" />
            <h2 className="text-sm font-semibold text-gray-700">任务状态</h2>
          </div>
          <span className="text-xs font-medium text-gray-400">0%</span>
        </div>
        <div className="mb-4 h-1.5 rounded-full bg-gray-100 overflow-hidden">
          <div className="h-full w-0 rounded-full bg-blue-500" />
        </div>
        <div className="h-48 rounded-xl border border-dashed border-gray-200 bg-gray-50 flex items-center justify-center text-sm text-gray-400">
          等待启动
        </div>
      </div>
    );
  }
 
  const artifacts = task.artifacts || [];
  const finalVideoArtifact = artifacts.find(isFinalVideoArtifact);
  const mediaArtifacts = artifacts
    .map((item, index) => ({ ...item, orderIndex: index }))
    .filter(item => ['audio', 'image', 'video'].includes(item.kind))
    .filter(item => !isFinalVideoArtifact(item))
    .sort((a, b) => {
      const aTime = a.created_at ? Date.parse(a.created_at) : Number.NaN;
      const bTime = b.created_at ? Date.parse(b.created_at) : Number.NaN;
      if (!Number.isNaN(aTime) && !Number.isNaN(bTime) && aTime !== bTime) return aTime - bTime;
      if (!Number.isNaN(aTime) && Number.isNaN(bTime)) return -1;
      if (Number.isNaN(aTime) && !Number.isNaN(bTime)) return 1;
      return a.orderIndex - b.orderIndex;
    });
 
  return (
    <div className="bg-white rounded-2xl border border-gray-200 p-5 shadow-sm h-full">
      <div className="flex items-center justify-between gap-3 mb-3">
        <div className="flex items-center gap-2 min-w-0">
          {task.status === 'running' ? (
            <Loader2 className="w-4 h-4 text-blue-500 animate-spin flex-shrink-0" />
          ) : task.status === 'completed' ? (
            <CheckCircle className="w-4 h-4 text-green-500 flex-shrink-0" />
          ) : task.status === 'failed' ? (
            <XCircle className="w-4 h-4 text-red-500 flex-shrink-0" />
          ) : (
            <Clock className="w-4 h-4 text-gray-400 flex-shrink-0" />
          )}
          <h2 className="text-sm font-semibold text-gray-700">任务状态</h2>
        </div>
        <div className="flex items-center gap-2 flex-shrink-0">
          <span className={clsx('px-2 py-1 rounded-full text-xs font-medium', STATUS_STYLE[task.status] || STATUS_STYLE.pending)}>
            {statusText(task.status)}
          </span>
          <span className="text-xs font-semibold text-gray-500">{progress}%</span>
        </div>
      </div>
 
      <div className="mb-4 h-1.5 rounded-full bg-gray-100 overflow-hidden">
        <div
          className={clsx('h-full rounded-full transition-all', task.status === 'failed' ? 'bg-red-500' : 'bg-blue-500')}
          style={{ width: `${progress}%` }}
        />
      </div>
 
      <FinalVideoResult item={finalVideoArtifact} />
 
      {mediaArtifacts.length > 0 ? (
        <div className="max-h-[28rem] overflow-y-auto pr-1">
          <div className="mb-2 flex items-center gap-2">
            <SlidersHorizontal className="w-4 h-4 text-gray-400" />
            <h3 className="text-sm font-semibold text-gray-700">中间产物</h3>
          </div>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {mediaArtifacts.map((item, index) => (
              <div
                key={`${item.kind}-${item.name || index}-${item.path}`}
                className="h-44 rounded-xl border border-gray-200 bg-gray-50 overflow-hidden min-w-0"
              >
                <div className="h-8 px-3 border-b border-gray-200 bg-white flex items-center gap-2">
                  {item.kind === 'video' && <Video className="w-3.5 h-3.5 text-blue-500" />}
                  {item.kind === 'image' && <ImageIcon className="w-3.5 h-3.5 text-emerald-500" />}
                  {item.kind === 'audio' && <Volume2 className="w-3.5 h-3.5 text-amber-500" />}
                  <span className="text-xs font-medium text-gray-500 truncate">{item.name || item.kind}</span>
                </div>
                {item.kind === 'video' && (
                  <video src={assetHref(item.path)} controls className="w-full h-36 bg-black object-contain" />
                )}
                {item.kind === 'image' && (
                  <img src={assetHref(item.path)} alt={item.name || 'image'} className="w-full h-36 object-contain" />
                )}
                {item.kind === 'audio' && (
                  <div className="h-36 px-3 flex items-center">
                    <audio src={assetHref(item.path)} controls className="w-full" />
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div className="h-48 rounded-xl bg-gray-50 border border-dashed border-gray-200 flex items-center justify-center text-sm text-gray-400">
          结果生成后显示
        </div>
      )}
    </div>
  );
}
 
function TemplatePreviewCard({
  template,
  selected,
  onClick,
}: {
  template: StandardTemplateOption;
  selected?: boolean;
  onClick?: () => void;
}) {
  const ratioClass = template.ratio === '16:9'
    ? 'aspect-[16/9] w-36'
    : template.ratio === '1:1'
      ? 'aspect-square w-28'
      : 'aspect-[9/16] w-24';
  const scale = template.ratio === '16:9'
    ? 0.075
    : template.ratio === '1:1'
      ? 0.105
      : 0.089;
 
  return (
    <button
      type="button"
      onClick={onClick}
      className={clsx(
        'group flex-shrink-0 rounded-lg border bg-white p-1.5 text-left transition-all',
        selected ? 'border-blue-400 ring-2 ring-blue-100' : 'border-gray-200 hover:border-blue-300 hover:shadow-sm'
      )}
      title={template.label}
    >
      <div className={clsx('relative overflow-hidden rounded-md bg-gray-100', ratioClass)}>
        <iframe
          src={template.preview_url}
          title={template.label}
          className="pointer-events-none absolute left-0 top-0 border-0 bg-white"
          style={{
            width: template.width,
            height: template.height,
            transform: `scale(${scale})`,
            transformOrigin: 'top left',
          }}
        />
      </div>
      <div className="mt-1 max-w-36 truncate text-[10px] font-medium text-gray-500 group-hover:text-blue-600">
        {template.label}
      </div>
    </button>
  );
}
 
function PipelineHistory({
  pipeline,
  activeTaskId,
  onSelect,
  onDeleted,
}: {
  pipeline: PipelineId;
  activeTaskId?: string;
  onSelect: (task: PipelineTask) => void;
  onDeleted?: (taskId: string) => void;
}) {
  const [tasks, setTasks] = useState<PipelineTask[]>([]);
  const [loading, setLoading] = useState(false);
  const [manageMode, setManageMode] = useState(false);
  const [deleting, setDeleting] = useState<string | null>(null);
 
  const load = async () => {
    setLoading(true);
    try {
      const records = await fetchPipelineTasks(100);
      setTasks(records.filter(task => task.pipeline === pipeline));
    } finally {
      setLoading(false);
    }
  };
 
  useEffect(() => {
    load().catch(() => {});
  }, [pipeline]);
 
  if (!tasks.length) return null;
 
  const remove = async (taskId: string) => {
    setDeleting(taskId);
    try {
      await deletePipelineTask(taskId);
      setTasks(prev => prev.filter(task => task.task_id !== taskId));
      onDeleted?.(taskId);
    } finally {
      setDeleting(null);
    }
  };
 
  return (
    <section className="w-full max-w-6xl mx-auto px-6 pb-12">
      <div className="flex items-center gap-2 mb-4">
        <Clock className="w-4 h-4 text-gray-400" />
        <h3 className="text-sm font-medium text-gray-600">历史记录</h3>
        <button
          onClick={() => setManageMode(value => !value)}
          className={clsx(
            'ml-auto px-2.5 h-8 rounded-lg text-xs font-medium transition-colors',
            manageMode ? 'bg-red-50 text-red-600 hover:bg-red-100' : 'bg-gray-100 text-gray-500 hover:bg-gray-200'
          )}
        >
          {manageMode ? '完成' : '管理'}
        </button>
        <button
          onClick={() => load().catch(() => {})}
          className="w-8 h-8 rounded-lg bg-gray-100 text-gray-500 hover:bg-gray-200 flex items-center justify-center"
          title="刷新历史"
        >
          <RefreshCw className={clsx('w-3.5 h-3.5', loading && 'animate-spin')} />
        </button>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
        {tasks.map(task => (
          <div
            key={task.task_id}
            onClick={() => !manageMode && onSelect(task)}
            className={clsx(
              'group text-left p-4 bg-white rounded-xl border hover:border-blue-300 hover:shadow-sm transition-all',
              manageMode ? 'cursor-default' : 'cursor-pointer',
              activeTaskId === task.task_id ? 'border-blue-300 ring-2 ring-blue-50' : 'border-gray-200'
            )}
          >
            <div className="flex items-start justify-between gap-3">
              <div className="min-w-0">
                <div className="text-sm font-medium text-gray-700 group-hover:text-blue-600 transition-colors truncate">
                  {String(taskTitle(task)).slice(0, 48)}
                </div>
                <div className="mt-1.5 flex flex-wrap items-center gap-2">
                  <span className={clsx('text-[10px] px-1.5 py-0.5 rounded', STATUS_STYLE[task.status] || STATUS_STYLE.pending)}>
                    {statusText(task.status)}
                  </span>
                  <span className="text-[10px] text-gray-400">
                    {task.created_at ? new Date(task.created_at).toLocaleString('zh-CN') : task.task_id}
                  </span>
                </div>
                <div className="mt-2 h-1 rounded-full bg-gray-100 overflow-hidden">
                  <div className="h-full bg-blue-500 rounded-full" style={{ width: `${task.progress || 0}%` }} />
                </div>
              </div>
              {manageMode ? (
                <button
                  onClick={event => {
                    event.stopPropagation();
                    remove(task.task_id).catch(() => {});
                  }}
                  disabled={deleting === task.task_id}
                  className="w-8 h-8 rounded-lg text-red-500 bg-red-50 hover:bg-red-100 flex items-center justify-center flex-shrink-0"
                  title="删除任务"
                >
                  {deleting === task.task_id ? <Loader2 className="w-4 h-4 animate-spin" /> : <X className="w-4 h-4" />}
                </button>
              ) : (
                <ArrowRight className="w-4 h-4 text-gray-300 group-hover:text-blue-400 flex-shrink-0 mt-0.5" />
              )}
            </div>
          </div>
        ))}
      </div>
    </section>
  );
}
 
export default function PipelinePage({ pipeline, title, subtitle }: PipelinePageProps) {
  const TitleIcon = PIPELINE_TITLE_ICONS[pipeline];
  const [showSettings, setShowSettings] = useState(false);
  const [running, setRunning] = useState(false);
  const [error, setError] = useState('');
  const [task, setTask] = useState<PipelineTask | null>(null);
  const [imageModelGroups, setImageModelGroups] = useState<ProviderGroup[]>(pipeline === 'digital_human' ? I2I_PROVIDERS : T2I_PROVIDERS);
  const [videoModelGroups, setVideoModelGroups] = useState<ProviderGroup[]>(VIDEO_PROVIDERS);
 
  const [text, setText] = useState('');
  const [standardMode, setStandardMode] = useState<'inspiration' | 'copy'>('inspiration');
  const [standardVideoMode, setStandardVideoMode] = useState<'image_concat' | 'dynamic_video'>('image_concat');
  const [templateMode, setTemplateMode] = useState(false);
  const [templates, setTemplates] = useState<StandardTemplateOption[]>([]);
  const [selectedTemplateId, setSelectedTemplateId] = useState('');
  const [templateFieldValues, setTemplateFieldValues] = useState<Record<string, string>>({});
  const [titleValue, setTitleValue] = useState('');
  const [standardSegmentCount, setStandardSegmentCount] = useState(6);
  const [enableSubtitles, setEnableSubtitles] = useState(false);
  const [subtitleRenderMode, setSubtitleRenderMode] = useState<'postprocess' | 'image_model'>('postprocess');
  const [promptText, setPromptText] = useState('');
  const [imagePath, setImagePath] = useState('');
  const [videoPath, setVideoPath] = useState('');
  const [characterImage, setCharacterImage] = useState('');
  const [goodsImage, setGoodsImage] = useState('');
  const [goodsTitle, setGoodsTitle] = useState('');
  const [goodsText, setGoodsText] = useState('');
 
  const [llmModel, setLlmModel] = useState(DEFAULTS.llm);
  const [imageModel, setImageModel] = useState(DEFAULTS.image);
  const [videoModel, setVideoModel] = useState(
    pipeline === 'action_transfer' ? 'wan2.7-videoedit' : pipeline === 'digital_human' ? 'wan2.7-r2v' : DEFAULTS.video
  );
  const [ratio, setRatio] = useState('9:16');
  const [duration, setDuration] = useState(5);
  const [ttsVoice, setTtsVoice] = useState('zh-CN-YunjianNeural');
  const [ttsSpeed, setTtsSpeed] = useState(1.2);
  const [negativePrompt, setNegativePrompt] = useState(pipeline === 'standard' ? DEFAULT_STANDARD_STYLE_CONTROL : '');
 
  useEffect(() => {
    const imageAbility = pipeline === 'digital_human' ? 'reference_image' : 'text_to_image';
    const videoAbility = pipeline === 'standard'
      ? 'first_frame_i2v'
      : pipeline === 'action_transfer'
        ? 'action_transfer'
        : 'digital_human';
 
    if (pipeline === 'standard') {
      setNegativePrompt(current => current || DEFAULT_STANDARD_STYLE_CONTROL);
    }
 
    fetchApiModels({ mediaType: 'image', ability: imageAbility, verifiedOnly: true })
      .then(models => {
        const groups = groupApiModels(models, pipeline === 'digital_human' ? I2I_PROVIDERS : T2I_PROVIDERS);
        setImageModelGroups(groups);
        setImageModel(current => firstModelId(groups, current || DEFAULTS.image));
      })
      .catch(() => {});
 
    if (pipeline !== 'standard' || standardVideoMode === 'dynamic_video') {
      fetchApiModels({ mediaType: 'video', ability: videoAbility, verifiedOnly: true })
        .then(models => {
          const groups = groupApiModels(models, VIDEO_PROVIDERS);
          setVideoModelGroups(groups);
          const preferred = pipeline === 'standard'
            ? DEFAULTS.video
            : pipeline === 'action_transfer'
              ? 'wan2.7-videoedit'
              : 'wan2.7-r2v';
          setVideoModel(current => firstModelId(groups, current || preferred));
        })
        .catch(() => {});
    }
  }, [pipeline, standardVideoMode]);
 
  useEffect(() => {
    if (pipeline !== 'standard') return;
    fetchStandardTemplates()
      .then(items => {
        setTemplates(items);
        setSelectedTemplateId(current => current || items.find(item => item.ratio === ratio)?.id || items[0]?.id || '');
      })
      .catch(() => {});
  }, [pipeline, ratio]);
 
  useEffect(() => {
    if (!templateMode) return;
    setEnableSubtitles(true);
    setStandardVideoMode('image_concat');
    setText(current => current || TEMPLATE_TEXT_DEFAULTS.text);
    setTitleValue(current => current || TEMPLATE_TEXT_DEFAULTS.title);
    setSelectedTemplateId(current => {
      if (current && templates.some(item => item.id === current && item.ratio === ratio)) return current;
      return templates.find(item => item.ratio === ratio)?.id || current;
    });
  }, [templateMode, ratio, templates]);
 
  const portraitTemplates = useMemo(
    () => templates.filter(item => item.size === '1080x1920'),
    [templates]
  );
  const ratioTemplates = useMemo(
    () => templates.filter(item => item.ratio === ratio),
    [templates, ratio]
  );
  const selectedTemplate = useMemo(
    () => templates.find(item => item.id === selectedTemplateId) || null,
    [templates, selectedTemplateId]
  );
  const selectedTemplateFields = useMemo(
    () => selectedTemplate?.fields || [],
    [selectedTemplate]
  );
 
  useEffect(() => {
    if (!templateMode) return;
    if (!selectedTemplateFields.length) {
      setTemplateFieldValues({});
      return;
    }
    setTemplateFieldValues(current => {
      const next: Record<string, string> = {};
      for (const field of selectedTemplateFields) {
        next[field.key] = current[field.key] ?? field.default ?? '';
      }
      return next;
    });
  }, [templateMode, selectedTemplateFields]);
 
  const enterTemplateMode = () => {
    setTemplateMode(true);
    setEnableSubtitles(true);
    setStandardVideoMode('image_concat');
    setText(current => current || TEMPLATE_TEXT_DEFAULTS.text);
    setTitleValue(current => current || TEMPLATE_TEXT_DEFAULTS.title);
  };
 
  const canSubmit = useMemo(() => {
    if (pipeline === 'standard') return text.trim().length > 0 && (!templateMode || Boolean(selectedTemplate));
    if (pipeline === 'action_transfer') return promptText.trim() && imagePath.trim() && videoPath.trim();
    return characterImage.trim() && goodsText.trim();
  }, [pipeline, text, templateMode, selectedTemplate, promptText, imagePath, videoPath, characterImage, goodsText]);
 
  useEffect(() => {
    if (!task || !['pending', 'running'].includes(task.status)) return;
 
    const refreshTask = async () => {
      const fresh = await fetchPipelineTask(task.task_id);
      setTask(fresh);
      if (!['pending', 'running'].includes(fresh.status)) {
        setRunning(false);
      }
    };
 
    const handleEvent = (event: PipelineTaskEvent) => {
      if (event.type === 'snapshot' || event.type === 'progress') {
        setTask(prev => prev && prev.task_id === event.task_id
          ? {
              ...prev,
              status: event.status || prev.status,
              progress: event.progress ?? prev.progress,
            }
          : prev
        );
        return;
      }
 
      if (event.type === 'artifact' || event.type === 'completed' || event.type === 'failed') {
        refreshTask().catch(() => setRunning(false));
      }
    };
 
    return subscribePipelineTask(
      task.task_id,
      handleEvent,
      () => {
        if (task.status === 'pending' || task.status === 'running') {
          setRunning(false);
        }
      },
    );
  }, [task?.task_id, task?.status]);
 
  const submit = async () => {
    if (!canSubmit || running) return;
    setRunning(true);
    setError('');
    try {
      const common = {
        video_model: videoModel,
        video_ratio: ratio,
        duration,
        negative_prompt: negativePrompt || undefined,
      };
      const started = pipeline === 'standard'
        ? await startStandardPipeline({
            text,
            mode: standardMode,
            title: titleValue || undefined,
            llm_model: llmModel,
            image_model: imageModel,
            video_ratio: ratio,
            enable_subtitles: templateMode ? true : enableSubtitles,
            subtitle_render_mode: !templateMode && enableSubtitles ? subtitleRenderMode : undefined,
            subtitle_template: templateMode ? selectedTemplate?.id : undefined,
            subtitle_template_fields: templateMode ? templateFieldValues : undefined,
            tts_voice: ttsVoice,
            tts_speed: ttsSpeed,
            style_control: negativePrompt || undefined,
            segment_count: standardMode === 'inspiration' ? standardSegmentCount : undefined,
            video_mode: templateMode ? 'image_concat' : standardVideoMode,
            video_model: !templateMode && standardVideoMode === 'dynamic_video' ? videoModel : undefined,
            video_duration: !templateMode && standardVideoMode === 'dynamic_video' ? duration : undefined,
          })
        : pipeline === 'action_transfer'
          ? await startActionTransferPipeline({
              prompt_text: promptText,
              image_path: imagePath,
              video_path: videoPath,
              ...common,
            })
          : await startDigitalHumanPipeline({
              mode: 'customize',
              character_image_path: characterImage,
              goods_image_path: goodsImage || undefined,
              goods_title: goodsTitle || undefined,
              goods_text: goodsText || undefined,
              llm_model: llmModel,
              image_model: imageModel,
              video_model: videoModel,
              video_ratio: ratio,
              tts_voice: ttsVoice,
              tts_speed: ttsSpeed,
              negative_prompt: negativePrompt || undefined,
            });
      const fresh = await fetchPipelineTask(started.task_id);
      setTask(fresh);
    } catch (e: any) {
      setError(e.message || '启动失败');
      setRunning(false);
    }
  };
 
  return (
    <div className="min-h-screen bg-gray-50/50 overflow-y-auto">
      <BrandHeader />
 
      <div className="w-full max-w-6xl mx-auto px-6 pt-10 pb-8">
        <div className="text-center mb-10">
          <div className="inline-flex items-center gap-2 mb-3">
            <TitleIcon className="w-7 h-7 text-blue-500" />
            <h1 className="text-2xl font-bold text-gray-800">{title}</h1>
          </div>
          <p className="text-sm text-gray-500">{subtitle}</p>
        </div>
 
        {pipeline === 'standard' && (
          <section className="mb-5 rounded-2xl border border-gray-200 bg-white p-4 shadow-sm">
            <div className="flex flex-col gap-3 md:flex-row md:items-center">
              <button
                type="button"
                onClick={() => {
                  if (templateMode) setTemplateMode(false);
                  else enterTemplateMode();
                }}
                className={clsx(
                  'h-10 flex-shrink-0 rounded-xl px-4 text-sm font-medium transition-colors',
                  templateMode
                    ? 'bg-gray-900 text-white hover:bg-gray-800'
                    : 'bg-blue-500 text-white hover:bg-blue-600'
                )}
              >
                {templateMode ? '返回自定义生成模式' : '使用精品模版'}
              </button>
              <div className="min-w-0 flex-1 overflow-x-auto">
                <div className="flex gap-3 pb-1">
                  {portraitTemplates.length ? (
                    portraitTemplates.map(item => (
                      <TemplatePreviewCard
                        key={item.id}
                        template={item}
                        selected={templateMode && selectedTemplateId === item.id}
                        onClick={() => {
                          enterTemplateMode();
                          setRatio(item.ratio);
                          setSelectedTemplateId(item.id);
                        }}
                      />
                    ))
                  ) : (
                    <div className="flex h-28 min-w-0 flex-1 items-center justify-center rounded-xl border border-dashed border-gray-200 bg-gray-50 text-xs text-gray-400">
                      暂无 1080x1920 模版
                    </div>
                  )}
                </div>
              </div>
            </div>
          </section>
        )}
 
        <div className="grid grid-cols-1 lg:grid-cols-[minmax(0,1.1fr)_minmax(340px,0.9fr)] gap-5 items-start">
          <section className="bg-white rounded-2xl shadow-sm border border-gray-200 p-5">
            {pipeline === 'standard' && (
              <div className="space-y-4">
                {templateMode ? (
                  <div className="space-y-3">
                    <div className="grid h-10 max-w-sm grid-cols-3 rounded-lg bg-gray-100 p-1 text-sm">
                      {['9:16', '1:1', '16:9'].map(item => (
                        <button
                          key={item}
                          onClick={() => setRatio(item)}
                          className={clsx('rounded-md transition-colors', ratio === item ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500')}
                        >
                          {item}
                        </button>
                      ))}
                    </div>
                    <div className="rounded-xl border border-gray-200 bg-gray-50 p-3">
                      <div className="mb-2 text-xs font-medium text-gray-500">选择模版</div>
                      <div className="overflow-x-auto">
                        <div className="flex gap-3 pb-1">
                          {ratioTemplates.length ? (
                            ratioTemplates.map(item => (
                              <TemplatePreviewCard
                                key={item.id}
                                template={item}
                                selected={selectedTemplateId === item.id}
                                onClick={() => setSelectedTemplateId(item.id)}
                              />
                            ))
                          ) : (
                            <div className="flex h-28 min-w-0 flex-1 items-center justify-center rounded-xl border border-dashed border-gray-200 bg-white text-xs text-gray-400">
                              当前比例暂无模版
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                ) : (
                  <div className="grid grid-cols-2 h-10 rounded-lg bg-gray-100 p-1 text-sm max-w-sm">
                    {[
                      { id: 'image_concat', label: '图片拼接' },
                      { id: 'dynamic_video', label: '动态视频' },
                    ].map(item => (
                      <button
                        key={item.id}
                        onClick={() => setStandardVideoMode(item.id as 'image_concat' | 'dynamic_video')}
                        className={clsx('rounded-md transition-colors', standardVideoMode === item.id ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500')}
                      >
                        {item.label}
                      </button>
                    ))}
                  </div>
                )}
                <div className="rounded-xl border border-yellow-300 bg-yellow-100 px-4 py-3">
                  <div className="mb-1 flex items-center gap-1.5 text-xs font-semibold text-yellow-900">
                    <Lightbulb className="w-3.5 h-3.5" />
                    <span>说明</span>
                  </div>
                  <p className="text-sm leading-6 text-yellow-950">
                    {standardVideoMode === 'image_concat'
                      ? '图片拼接会为每个旁白片段生成一张图片,并配合 TTS 音频合成为静态图文短视频。等待时间主要取决于图片生成速度,通常生成每张图片需 10-20 秒。'
                      : '动态视频会先为每个旁白片段生成图片,再调用视频模型把图片扩展为动态片段,最后合成为完整短片。等待时间更长,通常生成每个视频片段需 1-2 分钟。'}
                  </p>
                </div>
                <div className="grid grid-cols-2 h-10 rounded-lg bg-gray-100 p-1 text-sm max-w-sm">
                  {[
                    { id: 'inspiration', label: '创作灵感' },
                    { id: 'copy', label: '完整文案' },
                  ].map(item => (
                    <button
                      key={item.id}
                      onClick={() => setStandardMode(item.id as 'inspiration' | 'copy')}
                      className={clsx('rounded-md transition-colors', standardMode === item.id ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500')}
                    >
                      {item.label}
                    </button>
                  ))}
                </div>
                <textarea
                  value={text}
                  onChange={e => setText(e.target.value)}
                  placeholder={standardMode === 'inspiration' ? '输入主题、观点或故事灵感,系统会先构思成完整旁白...' : '输入完整旁白文案,系统会按句号切分片段并直接进入 TTS...'}
                  className="w-full min-h-[150px] resize-none rounded-xl border border-gray-200 bg-white px-3 py-3 text-sm text-gray-800 outline-none focus:border-blue-300"
                />
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <TextInput label="标题" value={titleValue} onChange={setTitleValue} placeholder="可选,留空时由llm生成" />
                  {standardMode === 'inspiration' && (
                    <NumberField label="片段数量" value={standardSegmentCount} onChange={setStandardSegmentCount} min={1} max={20} />
                  )}
                </div>
                {templateMode && selectedTemplateFields.length > 0 && (
                  <div className="rounded-xl border border-gray-200 bg-gray-50 p-3">
                    <div className="mb-3 text-xs font-medium text-gray-500">自定义字段</div>
                    <div className="space-y-2">
                      {selectedTemplateFields.map(field => (
                        <label key={field.key} className="grid grid-cols-[92px_minmax(0,1fr)] items-center gap-2">
                          <span className="text-xs font-medium text-gray-500">{TEMPLATE_FIELD_LABELS[field.key] || field.key}</span>
                          <input
                            value={templateFieldValues[field.key] ?? field.default ?? ''}
                            onChange={event => {
                              const value = event.target.value;
                              setTemplateFieldValues(current => ({ ...current, [field.key]: value }));
                            }}
                            className="h-9 min-w-0 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-700 outline-none focus:border-blue-300"
                          />
                        </label>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}
 
            {pipeline === 'action_transfer' && (
              <div className="space-y-4">
                <textarea
                  value={promptText}
                  onChange={e => setPromptText(e.target.value)}
                  placeholder="描述希望迁移到人物或角色上的动作效果..."
                  className="w-full min-h-[130px] resize-none rounded-xl border border-gray-200 bg-white px-3 py-3 text-sm text-gray-800 outline-none focus:border-blue-300"
                />
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <MediaUploadField label="参考图片" value={imagePath} onChange={setImagePath} accept="image/*" placeholder="/path/to/image.png" required />
                  <MediaUploadField label="动作视频" value={videoPath} onChange={setVideoPath} accept="video/*" placeholder="/path/to/video.mp4" required />
                </div>
              </div>
            )}
 
            {pipeline === 'digital_human' && (
              <div className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  <MediaUploadField label="人物图片" value={characterImage} onChange={setCharacterImage} accept="image/*" placeholder="/path/to/person.png" required />
                  <MediaUploadField label="商品图片" value={goodsImage} onChange={setGoodsImage} accept="image/*" placeholder="/path/to/product.png" />
                </div>
                <TextInput label="商品标题" value={goodsTitle} onChange={setGoodsTitle} placeholder="可选,留空时由llm生成" />
                <textarea
                  value={goodsText}
                  onChange={e => setGoodsText(e.target.value)}
                  placeholder="输入口播文案..."
                  className="w-full min-h-[130px] resize-none rounded-xl border border-gray-200 bg-white px-3 py-3 text-sm text-gray-800 outline-none focus:border-blue-300"
                />
              </div>
            )}
 
            <div className="mt-4 pt-4 border-t border-gray-100 flex flex-wrap items-center gap-2">
              <button
                onClick={() => setShowSettings(!showSettings)}
                className={clsx(
                  'flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-medium transition-colors',
                  showSettings ? 'bg-blue-50 text-blue-600' : 'text-gray-400 hover:text-gray-600 hover:bg-gray-50'
                )}
              >
                <Settings2 className="w-3.5 h-3.5" />
                生成配置
              </button>
              {pipeline === 'standard' && (
                <>
                  <label className="flex items-center gap-2 h-9 rounded-lg border border-gray-200 bg-white px-3 text-xs font-medium text-gray-600">
                    <input
                      type="checkbox"
                      checked={templateMode || enableSubtitles}
                      onChange={e => setEnableSubtitles(e.target.checked)}
                      disabled={templateMode}
                      className="w-4 h-4 rounded border-gray-300"
                    />
                    添加标题和字幕
                  </label>
                  {!templateMode && enableSubtitles && (
                    <div className="grid h-9 grid-cols-2 rounded-lg bg-gray-100 p-1 text-xs">
                      {[
                        { id: 'postprocess', label: 'PIL 后期叠字' },
                        { id: 'image_model', label: '模型直接生成字幕' },
                      ].map(item => (
                        <button
                          key={item.id}
                          type="button"
                          onClick={() => setSubtitleRenderMode(item.id as 'postprocess' | 'image_model')}
                          className={clsx(
                            'rounded-md px-3 font-medium transition-colors',
                            subtitleRenderMode === item.id
                              ? 'bg-white text-blue-600 shadow-sm'
                              : 'text-gray-500 hover:text-gray-700'
                          )}
                        >
                          {item.label}
                        </button>
                      ))}
                    </div>
                  )}
                </>
              )}
              {error && <span className="text-xs text-red-500 truncate">{error}</span>}
              <button
                onClick={submit}
                disabled={!canSubmit || running}
                className={clsx(
                  'ml-auto flex items-center gap-2 px-5 py-2 rounded-xl text-sm font-medium transition-colors',
                  canSubmit && !running ? 'bg-blue-500 text-white hover:bg-blue-600 shadow-sm' : 'bg-gray-100 text-gray-400 cursor-not-allowed'
                )}
              >
                {running ? <Loader2 className="w-4 h-4 animate-spin" /> : <Play className="w-4 h-4" />}
                启动任务
              </button>
            </div>
 
            {showSettings && (
              <div className="mt-4 p-4 bg-gray-50 rounded-xl space-y-3">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                  {(pipeline === 'digital_human' || pipeline === 'standard') && (
                    <SelectField label="LLM 模型" value={llmModel} onChange={setLlmModel} groups={LLM_PROVIDERS} />
                  )}
                  {pipeline !== 'action_transfer' && (
                    <SelectField label="图片模型" value={imageModel} onChange={setImageModel} groups={imageModelGroups} />
                  )}
                  {(pipeline !== 'standard' || standardVideoMode === 'dynamic_video') && (
                    <SelectField label="视频模型" value={videoModel} onChange={setVideoModel} groups={videoModelGroups} />
                  )}
                  <label className="flex flex-col gap-1.5">
                    <span className="text-xs font-medium text-gray-500">视频比例</span>
                    <select value={ratio} onChange={e => setRatio(e.target.value)} className="h-10 rounded-lg border border-gray-200 bg-white px-3 text-sm text-gray-700 outline-none">
                      {VIDEO_RATIOS.map(item => <option key={item.id} value={item.id}>{item.label}</option>)}
                    </select>
                  </label>
                  {(pipeline === 'action_transfer' || (pipeline === 'standard' && standardVideoMode === 'dynamic_video')) && (
                    <NumberField label="视频时长" value={duration} onChange={setDuration} min={1} max={10} />
                  )}
                  {pipeline !== 'action_transfer' && (
                    <>
                      <TextInput label="TTS 声音" value={ttsVoice} onChange={setTtsVoice} />
                      <NumberField label="TTS 速度" value={ttsSpeed} onChange={setTtsSpeed} min={0.5} max={2} />
                    </>
                  )}
                </div>
                <label className="flex flex-col gap-1.5">
                  <span className="text-xs font-medium text-gray-500">{pipeline === 'standard' ? '风格控制' : '负向提示词'}</span>
                  <textarea
                    value={negativePrompt}
                    onChange={e => setNegativePrompt(e.target.value)}
                    placeholder={pipeline === 'standard' ? '会作为所有图像提示词的前缀...' : '负向提示词...'}
                    className="w-full min-h-[70px] resize-none rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm text-gray-700 outline-none focus:border-blue-300"
                  />
                </label>
                {pipeline === 'standard' && (
                  <div className="flex flex-wrap gap-2">
                    {STANDARD_STYLE_PRESETS.map(preset => (
                      <button
                        key={preset.label}
                        type="button"
                        onClick={() => setNegativePrompt(preset.prompt)}
                        className={clsx(
                          'h-8 rounded-lg border px-3 text-xs font-medium transition-colors',
                          negativePrompt === preset.prompt
                            ? 'border-blue-300 bg-blue-50 text-blue-600'
                            : 'border-gray-200 bg-white text-gray-500 hover:border-blue-200 hover:bg-blue-50 hover:text-blue-600'
                        )}
                      >
                        {preset.label}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            )}
          </section>
 
          <TaskResult task={task} />
        </div>
      </div>
 
      <PipelineHistory
        pipeline={pipeline}
        activeTaskId={task?.task_id}
        onSelect={selected => setTask(selected)}
        onDeleted={taskId => {
          if (task?.task_id === taskId) setTask(null);
        }}
      />
    </div>
  );
}