hit-cxf
2026-06-03 26b9e3c26e28bce3ccb43f4e2b7eb9cf1306ce87
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
'use client';
 
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import {
  startProject,
  executeStage,
  parseStreamEvents,
  getProjectStatus,
  getProjectStatusFromDisk,
  continueWorkflow,
  stopProject,
  intervene,
  getArtifact,
  fetchSessions,
  updateModels,
  deleteSession,
  saveSelections,
} from '@/lib/workflowApi';
import TopBar, { STAGES, type ModelConfig } from './TopBar';
import HomePage, { type ProjectParams } from './HomePage';
import {
  ScriptStage,
  CharacterStage,
  StoryboardStage,
  ReferenceStage,
  VideoStage,
  PostProductionStage,
  type StageState,
  type StageStatus,
} from './stages';
 
const STAGE_ORDER: string[] = STAGES.map(s => s.id);
 
const STAGE_COMPONENTS: Record<string, React.ComponentType<any>> = {
  script_generation: ScriptStage,
  character_design: CharacterStage,
  storyboard: StoryboardStage,
  reference_generation: ReferenceStage,
  video_generation: VideoStage,
  post_production: PostProductionStage,
};
 
interface HistoryItem {
  id: string;
  idea: string;
  style?: string;
  date: string;
  status: string;
  stages?: Record<string, string>; // stageId => status 映射
}
 
function initStageStates(): Record<string, StageState> {
  const states: Record<string, StageState> = {};
  for (const s of STAGE_ORDER) {
    states[s] = {
      status: 'pending',
      progress: 0,
      progressMessage: '',
      artifact: null,
      error: null,
    };
  }
  return states;
}
 
function hasDoneArtifactItems(artifact: any): boolean {
  if (!artifact) return false;
  return ['clips', 'images', 'scenes', 'characters', 'settings'].some(key => {
    const items = artifact?.[key];
    return Array.isArray(items) && items.some((item: any) => item?.status === 'done' || item?.selected);
  });
}
 
function getStageProgressSnapshot(status: any, stageId: string): Partial<StageState> {
  const snapshot = status?.stage_progress?.[stageId];
  if (!snapshot || typeof snapshot !== 'object') return {};
  const progress = typeof snapshot.percent === 'number'
    ? Math.max(0, Math.min(100, Math.round(snapshot.percent)))
    : undefined;
  const progressMessage = typeof snapshot.message === 'string' && snapshot.message.trim()
    ? snapshot.message
    : (typeof snapshot.step === 'string' ? snapshot.step : undefined);
  return {
    ...(typeof progress === 'number' ? { progress } : {}),
    ...(progressMessage ? { progressMessage } : {}),
  };
}
 
export default function WorkflowPanel() {
  const router = useRouter();
  const searchParams = useSearchParams();
 
  const [sessionId, setSessionId] = useState<string | null>(null);
  const [activeStage, setActiveStage] = useState<string | null>(null);
  const [stageStates, setStageStates] = useState<Record<string, StageState>>(initStageStates());
  const [isRunning, setIsRunning] = useState(false);
  const [history, setHistory] = useState<HistoryItem[]>([]);
  const [projectParams, setProjectParams] = useState<ProjectParams | null>(null);
  const [autoMode, setAutoMode] = useState(false);
  const [videoSound, setVideoSound] = useState('on');
  const [videoShotType, setVideoShotType] = useState('multi');
  // 用于顶栏流程图状态判断
  const [currentStageFromSession, setCurrentStageFromSession] = useState<string | null>(null);
  const [completedStagesFromSession, setCompletedStagesFromSession] = useState<string[]>([]);
 
  const abortRef = useRef<AbortController | null>(null);
  const stoppedRef = useRef(false);
  const pollRef = useRef<string | null>(null);
 
  // 清理轮询
  useEffect(() => {
    return () => { pollRef.current = null; };
  }, []);
 
  // 轮询等待后端阶段完成。运行中优先读后端内存,后端重启后再回退到磁盘快照。
  const pollForCompletion = useCallback(async (sid: string, stageId: string) => {
    const key = `${sid}:${stageId}`;
    pollRef.current = key;
    for (let i = 0; i < 300; i++) {  // 增加轮询次数(最多10分钟)
      await new Promise(r => setTimeout(r, 2000));
      if (pollRef.current !== key) return;
      try {
        let status: any;
        try {
          status = await getProjectStatus(sid);
        } catch {
          status = await getProjectStatusFromDisk(sid);
        }
        if (pollRef.current !== key) return;
        setGlobalStatusMap(status.status || {});
        const done = Object.keys(status.status || {}).filter(k => ["completed", "session_completed"].includes(status.status[k]));
        const currentStageStatus = status.status?.[stageId] || 'idle';
        if (done.includes(stageId)) {
          const isWait = currentStageStatus === 'waiting' && status.current_stage === stageId;
          let artifact = null;
          try { artifact = (await getArtifact(sid, stageId)).artifact; } catch {}
          updateStageState(stageId, {
            status: isWait ? 'waiting' : 'completed',
            progress: 100,
            progressMessage: isWait ? '等待确认' : '已完成',
            artifact,
          });
          pollRef.current = null;
          return;
        }
        if (currentStageStatus === 'error') {
          updateStageState(stageId, {
            status: 'error',
            error: status.error || '执行出错',
            progressMessage: '执行失败',
          });
          pollRef.current = null;
          return;
        }
        if (currentStageStatus === 'stopped') {
          updateStageState(stageId, {
            status: 'stopped',
            error: '手动停止',
            progressMessage: '已停止',
          });
          pollRef.current = null;
          return;
        }
        // 如果当前阶段不再是 running,提前停止轮询(比如变成了 waiting_intervention 或已完成)
        if (currentStageStatus !== 'running') {
          pollRef.current = null;
          return;
        }
        // 更新进度信息(优先使用后端持久化的 stage_progress 快照)
        const artifacts = status.artifacts || {};
        const currentArtifact = artifacts[stageId];
        const update: Partial<StageState> = {
          status: 'running',
          ...getStageProgressSnapshot(status, stageId),
        };
 
        // 无论何种状态,只要有数据就更新 artifact
        if (currentArtifact) {
          update.artifact = currentArtifact;
        }
 
        if (!update.progressMessage && currentArtifact) {
          // 检查是否有已生成的参考图/视频/分镜
          const hasProgress = currentArtifact.scenes?.some((s: any) => s.versions?.length > 0) ||
                             currentArtifact.clips?.some((c: any) => c.versions?.length > 0) ||
                             currentArtifact.episodes?.some((e: any) => e.segments?.length > 0) ||
                             currentArtifact.characters?.length > 0 ||
                             currentArtifact.shots?.length > 0;
          if (hasProgress) {
            update.progressMessage = '执行中...(已生成部分资源)';
          } else {
            update.progressMessage = '执行中...';
          }
        } else if (!update.progressMessage) {
          update.progressMessage = '执行中...';
        }
 
        if (Object.keys(update).length > 0) {
          updateStageState(stageId, update);
        }
      } catch { /* retry */ }
    }
  }, []);
 
  // 检查 URL 参数,加载指定的 session 和阶段
  useEffect(() => {
    const sessionParam = searchParams.get('session');
    const stageParam = searchParams.get('stage');
    if (sessionParam) {
      // 保存目标阶段,等会话加载完成后再设置
      const targetStage = stageParam && STAGE_ORDER.includes(stageParam) ? stageParam : null;
      handleResumeProject(sessionParam, targetStage);
    }
  }, [searchParams]);
 
  // 页面加载时从后端获取历史记录
  useEffect(() => {
    fetchSessions()
      .then(sessions => {
        setHistory(
          sessions.map((s: any) => ({
            id: s.id,
            idea: (s.title || s.idea || 'Untitled').slice(0, 60),
            style: s.style || '',
            date: s.date
              ? new Date(s.date * 1000).toLocaleDateString('zh-CN')
              : '',
            status: Object.keys(s.status || {}).length > 0 ? 'partial' : 'new',
            stages: s.status || {},
          }))
        );
      })
      .catch(() => {});
  }, []);
 
  const updateStageState = (stageId: string, update: Partial<StageState>) => {
    setStageStates(prev => {
      const current = prev[stageId];
      const nextUpdate = { ...update };
      if (
        current?.status === 'running' &&
        typeof update.progress === 'number' &&
        update.progress < (current.progress || 0) &&
        update.status !== 'completed' &&
        update.status !== 'waiting'
      ) {
        nextUpdate.progress = current.progress;
      }
      return {
        ...prev,
        [stageId]: { ...current, ...nextUpdate },
      };
    });
  };
 
  // ── 停止执行 ──
  const handleStop = async () => {
    stoppedRef.current = true;
    // 1. 断开前端 SSE 流
    if (abortRef.current) {
      abortRef.current.abort();
      abortRef.current = null;
    }
    // 2. 通知后端停止
    if (sessionId) {
      try { await stopProject(sessionId); } catch { /* ignore */ }
    }
    setIsRunning(false);
    // 3. 将所有 running 阶段标记为 stopped,保留已有的 artifact
    setStageStates(prev => {
      const next = { ...prev };
      for (const s of STAGE_ORDER) {
        if (next[s]?.status === 'running') {
          // 如果已有 artifact 数据(如部分已生成的视频片段),保留为 waiting 状态以便用户操作
          const hasArtifact = hasDoneArtifactItems(next[s]?.artifact);
          if (hasArtifact) {
            next[s] = { ...next[s], status: 'waiting', error: null, progressMessage: '已停止(保留已完成内容)' };
          } else {
            next[s] = { ...next[s], status: 'error', error: '已手动停止', progressMessage: '已停止' };
          }
        }
      }
      return next;
    });
    // 4. 尝试从后端获取最新 artifact(后端可能已保存部分结果)
    if (sessionId) {
      setTimeout(async () => {
        for (const s of STAGE_ORDER) {
          try {
            const artResult = await getArtifact(sessionId, s);
            if (artResult?.artifact) {
              setStageStates(prev => {
                const cur = prev[s];
                if (!cur || cur.status === 'completed') return prev;
                // 检查 artifact 是否含有效内容
                const hasDone = hasDoneArtifactItems(artResult.artifact);
                if (hasDone) {
                  return { ...prev, [s]: { ...cur, status: 'waiting', artifact: artResult.artifact, error: null, progressMessage: '已停止(保留已完成内容)' } };
                }
                return prev;
              });
            }
          } catch { /* 该阶段无 artifact,跳过 */ }
        }
      }, 500);
    }
  };
 
  // ── 执行单个阶段 ──
  const runStage = async (sid: string, stageId: string, inputData: Record<string, any>) => {
    if (stoppedRef.current) throw new Error('Stopped');
    updateStageState(stageId, { status: 'running', progress: 0, progressMessage: '启动中...', error: null });
    setActiveStage(stageId);
 
    const controller = new AbortController();
    abortRef.current = controller;
 
    try {
      const response = await executeStage(sid, stageId, inputData, controller.signal);
 
      for await (const event of parseStreamEvents(response)) {
        if (event.type === 'progress') {
          updateStageState(stageId, {
            progress: event.percent || 0,
            progressMessage: event.message || '',
          });
          // 处理素材预览和逐个完成事件
          if (event.data?.assets_preview) {
            updateStageState(stageId, { artifact: event.data.assets_preview });
          }
          if (event.data?.asset_complete) {
            const assetUpdate = event.data.asset_complete;
            setStageStates(prev => {
              const prevArt = prev[stageId]?.artifact;
              if (!prevArt) return prev;
              const key = assetUpdate.type as string;
              const items = [...(prevArt[key] || [])];
              const idx = items.findIndex((item: any) => item.id === assetUpdate.id);
              if (idx >= 0) {
                items[idx] = {
                  ...items[idx],
                  status: assetUpdate.status,
                  selected: assetUpdate.selected || items[idx].selected,
                  versions: assetUpdate.versions || items[idx].versions,
                };
              }
              return {
                ...prev,
                [stageId]: { ...prev[stageId], artifact: { ...prevArt, [key]: items } },
              };
            });
          }
          // 处理剧本逐幕增量事件
          if (event.data?.beat_sheet) {
            setStageStates(prev => {
              const prevArt = prev[stageId]?.artifact || {};
              return {
                ...prev,
                [stageId]: {
                  ...prev[stageId],
                  artifact: { ...prevArt, phase: 'generating', beat_sheet: event.data.beat_sheet },
                },
              };
            });
          }
          if (event.data?.act_complete) {
            const actData = event.data.act_complete;
            setStageStates(prev => {
              const prevArt = prev[stageId]?.artifact || {};
              const prevActs = prevArt.completed_acts || [];
              return {
                ...prev,
                [stageId]: {
                  ...prev[stageId],
                  artifact: {
                    ...prevArt,
                    phase: 'generating',
                    completed_acts: [...prevActs, actData],
                  },
                },
              };
            });
          }
          // 处理分镜逐场完成事件
          if (event.data?.scene_shots_complete) {
            const sceneData = event.data.scene_shots_complete;
            setStageStates(prev => {
              const prevArt = prev[stageId]?.artifact || {};
              const prevShots = prevArt.shots || [];
              return {
                ...prev,
                [stageId]: {
                  ...prev[stageId],
                  artifact: {
                    ...prevArt,
                    phase: 'generating',
                    shots: [...prevShots, ...sceneData.shots],
                  },
                },
              };
            });
          }
        } else if (event.type === 'stage_complete') {
          const newStatus: StageStatus = event.requires_intervention ? 'waiting' : 'completed';
 
          let artifact = null;
          try {
            const artResult = await getArtifact(sid, stageId);
            artifact = artResult.artifact;
          } catch { /* ignore */ }
 
          // 如果是后处理阶段,即使 artifact 为空也尝试从事件中读取预览数据
          if (stageId === 'post_production' && !artifact && event.data?.assets_preview) {
            artifact = event.data.assets_preview;
          }
 
          updateStageState(stageId, {
            status: newStatus,
            progress: 100,
            progressMessage: newStatus === 'waiting' ? '等待确认' : '已完成',
            artifact,
          });
        } else if (event.type === 'error') {
          // 取消/停止类错误:尝试获取部分结果而不是直接报错
          const isCancelError = /cancel|取消|停止/i.test(event.content || '');
          if (isCancelError) {
            let artifact = null;
            try {
              const artResult = await getArtifact(sid, stageId);
              artifact = artResult?.artifact;
            } catch { /* ignore */ }
            // 如果有已完成的内容,显示为 waiting 状态
            const hasDone = hasDoneArtifactItems(artifact);
            if (hasDone) {
              updateStageState(stageId, {
                status: 'waiting',
                progress: 100,
                progressMessage: '已停止(保留已完成内容)',
                artifact,
                error: null,
              });
              return; // 不抛异常,让工作流正常停下
            }
          }
          updateStageState(stageId, {
            status: 'error',
            error: event.content || 'Unknown error',
            progressMessage: '执行失败',
          });
          throw new Error(event.content);
        }
      }
    } catch (error: any) {
      if (error.name !== 'AbortError') {
        updateStageState(stageId, {
          status: 'error',
          error: error.message,
          progressMessage: '执行失败',
        });
      }
      throw error;
    }
  };
 
  // ── 启动新项目 ──
  const handleStartProject = async (params: ProjectParams, autoOverride?: boolean) => {
    if (isRunning) return;
    stoppedRef.current = false;
    const useAutoMode = autoOverride !== undefined ? autoOverride : autoMode;
    if (autoOverride !== undefined) setAutoMode(autoOverride);
    setIsRunning(true);
    setStageStates(initStageStates());
    setProjectParams(params);
 
    try {
      const result = await startProject({
        idea: params.idea,
        file_path: params.file_path, // 修复:将上传的文件路径传给后端
        style: params.style,
        video_ratio: params.video_ratio,
        video_resolution: params.video_resolution,
        llm_model: params.llm_model,
        vlm_model: params.vlm_model,
        image_t2i_model: params.image_t2i_model,
        image_it2i_model: params.image_it2i_model,
        video_model: params.video_model,
        enable_concurrency: params.enable_concurrency,
        web_search: params.web_search,
        expand_idea: params.expand_idea,
        episodes: params.episodes,
      });
      setSessionId(result.session_id);
 
      // 添加到历史
      setHistory(prev => [
        {
          id: result.session_id,
          idea: params.idea.slice(0, 60),
          style: params.style,
          date: new Date().toLocaleDateString('zh-CN'),
          status: 'running',
          stages: {},
        },
        ...prev,
      ]);
 
      const inputData: Record<string, any> = {
        idea: params.idea,
        session_id: result.session_id,
        style: params.style,
        video_ratio: params.video_ratio,
        video_resolution: params.video_resolution,
        llm_model: params.llm_model,
        vlm_model: params.vlm_model,
        image_t2i_model: params.image_t2i_model,
        image_it2i_model: params.image_it2i_model,
        video_model: params.video_model,
        scene_number: result.params?.scene_number,
        expand_idea: params.expand_idea,
        enable_concurrency: params.enable_concurrency,
        web_search: params.web_search,
        episodes: params.episodes,
        auto_mode: useAutoMode,
      };
 
      for (const stageId of STAGE_ORDER) {
        if (stoppedRef.current) break;
        await runStage(result.session_id, stageId, inputData);
 
        // 剧本生成完成后,用实际场景数更新 scene_number
        if (stageId === 'script_generation') {
          try {
            const artResult = await getArtifact(result.session_id, 'script_generation');
            if (artResult?.artifact?.scenes?.length) {
              inputData.scene_number = artResult.artifact.scenes.length;
            }
          } catch { /* ignore */ }
        }
 
        const status = await getProjectStatus(result.session_id);
        const stageStatus = status?.status?.[stageId];
        setGlobalStatusMap(status.status || {});
        // waiting: 等待用户介入(如选择角色/图片),不能自动 continue
        // completed: 阶段完成,等待确认进入下一阶段
        if (stageStatus === 'completed' || stageStatus === 'session_completed') {
          if (useAutoMode) {
            // 代理模式:自动确认并继续
            await continueWorkflow(result.session_id);
            updateStageState(stageId, { status: 'completed', progressMessage: '已自动确认' });
          } else {
            updateStageState(stageId, { status: 'completed' });
            setActiveStage(stageId);
            setIsRunning(false);
            return;
          }
        } else if (stageStatus === 'waiting') {
          // 用户需要介入,停止自动执行
          updateStageState(stageId, { status: 'waiting' });
          setActiveStage(stageId);
          setIsRunning(false);
          return;
        }
      }
    } catch (error: any) {
      if (!stoppedRef.current) console.error('Workflow error:', error);
    } finally {
      setIsRunning(false);
    }
  };
 
  // ── 确认阶段并继续 ──
  const handleConfirmStage = async (stageId: string) => {
    if (!sessionId || isRunning) return;
    setIsRunning(true);
 
    try {
      const result: any = await continueWorkflow(sessionId);
      updateStageState(stageId, { status: 'completed', progressMessage: '已确认' });
 
      // 更新顶栏状态
      if (result.status_map) {
        setGlobalStatusMap(result.status_map);
      }
      setCompletedStagesFromSession(prev => [...prev, stageId]);
      if (result.next_stage) {
        setCurrentStageFromSession(result.next_stage);
      }
 
      if (result.next_stage) {
        const idx = STAGE_ORDER.indexOf(stageId);
 
        // 构建完整的 inputData
        const inputData: Record<string, any> = {
          session_id: sessionId,
          style: projectParams?.style,
          llm_model: projectParams?.llm_model,
          vlm_model: projectParams?.vlm_model,
          image_t2i_model: projectParams?.image_t2i_model,
          image_it2i_model: projectParams?.image_it2i_model,
          video_model: projectParams?.video_model,
          video_ratio: projectParams?.video_ratio,
          video_resolution: projectParams?.video_resolution,
          video_sound: videoSound,
          video_shot_type: videoShotType,
        };
        // 从剧本产物获取实际场景数
        try {
          const scriptArt = await getArtifact(sessionId, 'script_generation');
          if (scriptArt?.artifact?.scenes?.length) {
            inputData.scene_number = scriptArt.artifact.scenes.length;
          }
        } catch { /* ignore */ }
 
        // 从参考图产物获取用户选择的图片版本,传递给视频生成阶段
        if (stageId === 'reference_generation') {
          const refArt = stageStates['reference_generation']?.artifact;
          if (refArt?.scenes) {
            const selectedImages: Record<string, string> = {};
            refArt.scenes.forEach((s: any) => {
              if (s.id && s.selected) {
                selectedImages[s.id] = s.selected;
              }
            });
            inputData.selected_images = selectedImages;
          }
        }
 
        // 从视频产物获取用户选择的视频版本,传递给后期制作阶段
        if (stageId === 'video_generation') {
          const vidArt = stageStates['video_generation']?.artifact;
          if (vidArt?.clips) {
            const selectedClips: Record<string, string> = {};
            vidArt.clips.forEach((c: any) => {
              if (c.id && c.selected) {
                selectedClips[c.id] = c.selected;
              }
            });
            inputData.selected_clips = selectedClips;
          }
        }
 
        for (let i = idx + 1; i < STAGE_ORDER.length; i++) {
          if (stoppedRef.current) break;
          const nextStage = STAGE_ORDER[i];
          await runStage(sessionId, nextStage, inputData);
 
          const status = await getProjectStatus(sessionId);
          setGlobalStatusMap(status.status || {});
          const nStageStatus = status?.status?.[nextStage];
          // waiting: 等待用户介入(如选择角色/图片),不能自动 continue
          // completed: 阶段完成,等待确认进入下一阶段,可以自动 continue
          if (nStageStatus === 'completed' || nStageStatus === 'session_completed') {
            if (autoMode) {
              await continueWorkflow(sessionId);
              updateStageState(nextStage, { status: 'completed', progressMessage: '已自动确认' });
              setCompletedStagesFromSession(prev => [...prev, nextStage]);
              setCurrentStageFromSession(nextStage);
            } else {
              updateStageState(nextStage, { status: 'completed' });
              setCompletedStagesFromSession(prev => [...prev, nextStage]);
              setCurrentStageFromSession(nextStage);
              setActiveStage(nextStage);
              break;
            }
          } else if (nStageStatus === 'waiting') {
            // 用户需要介入,停止自动执行
            updateStageState(nextStage, { status: 'waiting' });
            setCurrentStageFromSession(nextStage);
            setActiveStage(nextStage);
            break;
          }
        }
      }
    } catch (error: any) {
      console.error('Continue error:', error);
    } finally {
      setIsRunning(false);
    }
  };
 
  // ── 用户介入修改 ──
  const handleIntervene = async (stageId: string, modifications: Record<string, any>) => {
    if (!sessionId) return;
    const isBackgroundItemRegeneration =
      (stageId === 'character_design' && (
        Array.isArray(modifications.regenerate_characters) ||
        Array.isArray(modifications.regenerate_settings)
      )) ||
      (stageId === 'reference_generation' && Array.isArray(modifications.regenerate_scenes)) ||
      (stageId === 'video_generation' && Array.isArray(modifications.regenerate_clips));
    
    // 构建完整的 inputData 传给后端,确保比例等参数能传递
    const inputData: Record<string, any> = {
      ...modifications,
      session_id: sessionId,
      style: projectParams?.style,
      video_ratio: projectParams?.video_ratio,
      video_resolution: projectParams?.video_resolution,
      llm_model: projectParams?.llm_model,
      vlm_model: projectParams?.vlm_model,
      image_t2i_model: projectParams?.image_t2i_model,
      image_it2i_model: projectParams?.image_it2i_model,
      video_model: projectParams?.video_model,
      video_sound: videoSound,
      video_shot_type: videoShotType,
    };
 
    // 设置 running 状态以便显示进度条(如 Logline 选择后生成剧本)
    // 若选择了 Logline,将其保存到 artifact 以便 ScriptStage 在生成期间展示
    // 若选择了模式,保留已选 Logline 并设置 generating 状态
    const artifactPatch = modifications.selected_logline
      ? { phase: 'generating', selected_logline: modifications.selected_logline }
      : modifications.selected_mode
        ? { phase: 'generating', selected_logline: stageStates[stageId]?.artifact?.selected_logline }
        : undefined;
    if (!isBackgroundItemRegeneration) {
      setIsRunning(true);
      updateStageState(stageId, { status: 'running', progress: 0, progressMessage: '处理中...', ...(artifactPatch ? { artifact: artifactPatch } : {}) });
    } else if (artifactPatch) {
      updateStageState(stageId, { artifact: artifactPatch });
    }
    try {
      const response = await intervene(sessionId, stageId, inputData);
      for await (const event of parseStreamEvents(response)) {
        if (event.type === 'progress') {
          if (!isBackgroundItemRegeneration) {
            updateStageState(stageId, {
              progress: event.percent || 0,
              progressMessage: event.message || '',
            });
          }
          // 处理 asset_complete 实时事件
          if (event.data?.asset_complete) {
            const assetUpdate = event.data.asset_complete;
            setStageStates(prev => {
              const prevArt = prev[stageId]?.artifact;
              if (!prevArt) return prev;
              const key = assetUpdate.type as string;
              const items = [...(prevArt[key] || [])];
              const idx = items.findIndex((item: any) => item.id === assetUpdate.id);
              if (idx >= 0) {
                items[idx] = {
                  ...items[idx],
                  status: assetUpdate.status,
                  selected: assetUpdate.selected || items[idx].selected,
                  versions: assetUpdate.versions || items[idx].versions,
                };
              }
              return {
                ...prev,
                [stageId]: { ...prev[stageId], artifact: { ...prevArt, [key]: items } },
              };
            });
          }
          // 处理剧本逐幕增量事件 (介入模式)
          if (event.data?.beat_sheet) {
            setStageStates(prev => {
              const prevArt = prev[stageId]?.artifact || {};
              return {
                ...prev,
                [stageId]: {
                  ...prev[stageId],
                  artifact: { ...prevArt, phase: 'generating', beat_sheet: event.data.beat_sheet },
                },
              };
            });
          }
          if (event.data?.act_complete) {
            const actData = event.data.act_complete;
            setStageStates(prev => {
              const prevArt = prev[stageId]?.artifact || {};
              const prevActs = prevArt.completed_acts || [];
              return {
                ...prev,
                [stageId]: {
                  ...prev[stageId],
                  artifact: {
                    ...prevArt,
                    phase: 'generating',
                    completed_acts: [...prevActs, actData],
                  },
                },
              };
            });
          }
          // 处理分镜逐场完成事件 (介入模式)
          if (event.data?.scene_shots_complete) {
            const sceneData = event.data.scene_shots_complete;
            setStageStates(prev => {
              const prevArt = prev[stageId]?.artifact || {};
              const prevShots = prevArt.shots || [];
              return {
                ...prev,
                [stageId]: {
                  ...prev[stageId],
                  artifact: {
                    ...prevArt,
                    phase: 'generating',
                    shots: [...prevShots, ...sceneData.shots],
                  },
                },
              };
            });
          }
        } else if (event.type === 'stage_complete') {
          const artResult = await getArtifact(sessionId, stageId);
          if (isBackgroundItemRegeneration) {
            updateStageState(stageId, { artifact: artResult.artifact });
          } else {
            updateStageState(stageId, { artifact: artResult.artifact, status: 'waiting' });
          }
        } else if (event.type === 'error') {
          console.error('Intervention error:', event.content);
        }
      }
    } catch (error: any) {
      console.error('Intervention error:', error);
    } finally {
      if (!isBackgroundItemRegeneration) {
        setIsRunning(false);
      }
    }
  };
 
  // ── 本地更新产物(不触发服务端调用) ──
  const handleUpdateArtifact = (stageId: string, patch: Record<string, any>) => {
    setStageStates(prev => ({
      ...prev,
      [stageId]: {
        ...prev[stageId],
        artifact: { ...(prev[stageId]?.artifact || {}), ...patch },
      },
    }));
  };
 
  // ── 保存用户选择到服务端 ──
  const handleSaveSelections = async (stageId: string, selections: Record<string, any>): Promise<void> => {
    if (!sessionId) return;
    try {
      // 构建更新: 把用户选择写回 artifact 中每个 item 的 selected 字段
      const art = stageStates[stageId]?.artifact;
      if (!art) return;
 
      let patch: Record<string, any> = {};
      if (stageId === 'script_generation') {
        // 剧本阶段:直接保存整个 data 覆盖 artifact
        patch = selections;
      } else if (stageId === 'character_design') {
        const chars = (art.characters || []).map((c: any) => ({ ...c, selected: selections[c.id] || c.selected }));
        const sets = (art.settings || []).map((s: any) => ({ ...s, selected: selections[s.id] || s.selected }));
        patch = { characters: chars, settings: sets };
      } else if (stageId === 'storyboard') {
        // 分镜阶段:保存 shots 数据(排除 original_shots,只保留 artifact 需要的字段)
        const { original_shots, ...rest } = selections;
        patch = { ...rest, user_modified: true };
      } else if (stageId === 'reference_generation') {
        const { _editDescs, ...restSelections } = selections;
        const scenes = (art.scenes || []).map((s: any) => ({
          ...s,
          selected: restSelections[s.id] || s.selected,
          description: _editDescs?.[s.id] ?? s.description,
        }));
        patch = { scenes };
      } else if (stageId === 'video_generation') {
        const { _editDescs, ...restSelections } = selections;
        const clips = (art.clips || []).map((c: any) => ({
          ...c,
          selected: restSelections[c.id] || c.selected,
          description: _editDescs?.[c.id] ?? c.description,
        }));
        patch = { clips };
      }
 
      // 本地更新
      handleUpdateArtifact(stageId, patch);
 
      // 服务端持久化
      await saveSelections(sessionId, stageId, patch);
      // 保存成功后标记为已完成,顶栏显示对勾
      updateStageState(stageId, { status: 'completed' });
 
      // 如果是分镜阶段保存,刷���第3和第4阶段的 artifact
      console.log('[handleSaveSelections] stageId:', stageId, 'patch:', patch);
      if (stageId === 'storyboard') {
        // 更新本地 artifact 以清除 is_new 标记
        handleUpdateArtifact(stageId, patch);
 
        // 获取第4阶段当前已有 artifact
        const oldRefArtifact = stageStates['reference_generation']?.artifact;
        const oldScenes = (oldRefArtifact?.scenes || []) as any[];
        const oldScenesMap = new Map(oldScenes.map((s: any) => [s.id, s]));
 
        // 使用 segments 构建第4阶段 scenes 和第5阶段 clips
        const sourceSegments = patch.segments || [];
        console.log('[handleSaveSelections] sourceSegments:', sourceSegments);
        
        const newScenes = sourceSegments.map((seg: any, idx: number) => {
          const seg_id = seg.segment_id;
          const oldScene = oldScenesMap.get(seg_id) as any;
          const isNew = seg.is_new;
          
          const shots = seg.shots || [];
          const desc_ref = shots.map((sh: any) => sh.visual_prompt || sh.plot || sh.content || '').join(' ').trim();
          
          return {
            id: seg_id,
            name: `片段_${seg_id}`,
            index: idx + 1,
            description: desc_ref,
            selected: isNew ? '' : (oldScene?.selected || ''),
            versions: isNew ? [] : (oldScene?.versions || []),
            status: isNew ? 'pending' : 'done',
          };
        });
 
        // 更新第4阶段的 artifact
        updateStageState('reference_generation', {
          artifact: { session_id: sessionId, scenes: newScenes },
          status: 'completed'
        });
 
        // 同步更新第5阶段(video_generation)
        const oldVidArtifact = stageStates['video_generation']?.artifact;
        const oldClips = (oldVidArtifact?.clips || []) as any[];
        const oldClipsMap = new Map(oldClips.map((c: any) => [c.id, c]));
 
        const newClips = sourceSegments.map((seg: any, idx: number) => {
          const seg_id = seg.segment_id;
          const oldClip = oldClipsMap.get(seg_id) as any;
          
          const shots = seg.shots || [];
          const desc_video = shots.map((sh: any) => sh.plot || sh.content || '').join(' ').trim();
          const total_dur = seg.total_duration || shots.reduce((acc: number, sh: any) => acc + (sh.duration || 0), 0) || 10;
 
          return {
            id: seg_id,
            name: `片段_${seg_id}`,
            index: idx + 1,
            description: desc_video,
            duration: total_dur,
            selected: oldClip?.selected || '',
            versions: oldClip?.versions || [],
            status: 'pending',
          };
        });
 
        // 更新第5阶段的 artifact
        updateStageState('video_generation', {
          artifact: { session_id: sessionId, clips: newClips },
          status: 'completed'
        });
        console.log('[handleSaveSelections] 第5阶段已更新');
      }
    } catch (error) {
      console.error('Save selections error:', error);
      throw error; // 抛出让 StageActions 捕获以恢复按钮状态
    }
  };
 
  // ── 重新生成当前阶段 ──
  const handleRegenerate = async (stageId: string) => {
    if (!sessionId || isRunning) return;
    stoppedRef.current = false;
    setIsRunning(true);
 
    // 清空当前阶段状态
    updateStageState(stageId, {
      status: 'running',
      progress: 0,
      progressMessage: '重新生成中...',
      artifact: null,
      error: null,
    });
 
    // 将该阶段之后的所有阶段重置为 pending
    const idx = STAGE_ORDER.indexOf(stageId);
    for (let i = idx + 1; i < STAGE_ORDER.length; i++) {
      updateStageState(STAGE_ORDER[i], {
        status: 'pending',
        progress: 0,
        progressMessage: '',
        artifact: null,
        error: null,
      });
    }
 
    try {
      const inputData: Record<string, any> = {
        session_id: sessionId,
        style: projectParams?.style,
        llm_model: projectParams?.llm_model,
        vlm_model: projectParams?.vlm_model,
        image_t2i_model: projectParams?.image_t2i_model,
        image_it2i_model: projectParams?.image_it2i_model,
        video_model: projectParams?.video_model,
        video_ratio: projectParams?.video_ratio,
        video_resolution: projectParams?.video_resolution,
      };
 
      // 尝试获取场景数
      try {
        const scriptArt = await getArtifact(sessionId, 'script_generation');
        if (scriptArt?.artifact?.scenes?.length) {
          inputData.scene_number = scriptArt.artifact.scenes.length;
        }
      } catch { /* ignore */ }
 
      await runStage(sessionId, stageId, inputData);
 
      const status = await getProjectStatus(sessionId);
      if (status?.status?.[stageId] === 'waiting') {
        updateStageState(stageId, { status: 'waiting' });
        setActiveStage(stageId);
      }
    } catch (error: any) {
      if (!stoppedRef.current) console.error('Regenerate error:', error);
    } finally {
      setIsRunning(false);
    }
  };
 
  // ── 恢复历史项目 ──
  const handleResumeProject = async (sid: string, targetStage: string | null = null) => {
    // 如果正在执行的就是同一个项目,直接恢复视图,不重置状态
    if (sid === sessionId) {
      const runningStage = STAGE_ORDER.find(s => stageStates[s]?.status === 'running');
      const waitingStage = STAGE_ORDER.find(s => stageStates[s]?.status === 'waiting');
      const lastCompleted = [...STAGE_ORDER].reverse().find(s => stageStates[s]?.status === 'completed');
      setActiveStage(targetStage || runningStage || waitingStage || lastCompleted || STAGE_ORDER[0]);
      return;
    }
 
    setSessionId(sid);
    // 更新 URL 参数(包含阶段)
    const stageParam = targetStage ? `&stage=${targetStage}` : '';
    router.push(`/?session=${sid}${stageParam}`);
    try {
      let status: any;
      try {
        status = await getProjectStatus(sid);
      } catch {
        status = await getProjectStatusFromDisk(sid);
      }
      setGlobalStatusMap(status.status || {});
      const newStates = initStageStates();
      const stMap = status.status || {};
      const allStatusStages = Object.keys(stMap);
      const currentStage = status.current_stage;
      
      // 保存到 state 供顶栏流程图使用
      setCurrentStageFromSession(currentStage || null);
      const completedStages = allStatusStages.filter(k => ["completed", "session_completed"].includes(stMap[k]));
      setCompletedStagesFromSession(completedStages);
 
      for (const sName of allStatusStages) {
        const cStatus = stMap[sName];
        if (cStatus === 'pending' || cStatus === 'idle') {
          // 即使是 pending,如果 artifacts 中有数据,也尝试恢复数据(用于初始占位显示)
          if (status.artifacts?.[sName]) {
            newStates[sName].artifact = status.artifacts[sName];
          }
          continue;
        }
 
        const isCompleted = ["completed", "session_completed"].includes(cStatus);
        const isError = cStatus === 'error';
        const isWaiting = cStatus === 'waiting';
        const isStopped = cStatus === 'stopped';
        const isRunningStatus = cStatus === 'running';
        const progressSnapshot = getStageProgressSnapshot(status, sName);
 
        newStates[sName] = {
          status: isError ? 'error' : (isWaiting ? 'waiting' : (isStopped ? 'stopped' : (isCompleted ? 'completed' : 'running'))),
          progress: isCompleted ? 100 : (typeof progressSnapshot.progress === 'number' ? progressSnapshot.progress : 0),
          progressMessage: isError
            ? '执行失败'
            : (isWaiting
              ? '等待确认'
              : (isStopped
                ? '已停止'
                : (isCompleted
                  ? '已完成'
                  : (progressSnapshot.progressMessage || (isRunningStatus ? '执行中...' : '进行中'))))),
          artifact: status.artifacts?.[sName] || null,
          error: isError ? (status.error || '执行出错') : (isStopped ? '手动停止' : null),
        };
        
        // 如果内存中没有,尝试异步拉取
        if (!newStates[sName].artifact) {
          try {
            const artResult = await getArtifact(sid, sName);
            newStates[sName].artifact = artResult.artifact;
          } catch { /* ignore */ }
        }
      }
 
      // 恢复项目参数:会话级生成配置统一从 meta 中读取,兼容少量旧扁平字段。
      const meta = ((status as any).meta || {}) as any;
      const s = Object.keys(meta).length > 0 ? meta : (status as any);
      if (s.idea || s.user_textbox_input) {
        setProjectParams({
          idea: s.idea || s.user_textbox_input || '',
          style: s.style || '',
          video_ratio: s.video_ratio || '16:9',
          video_resolution: s.video_resolution || '720P',
          llm_model: s.llm_model || '',
          vlm_model: s.vlm_model || '',
          image_t2i_model: s.image_t2i_model || '',
          image_it2i_model: s.image_it2i_model || '',
          video_model: s.video_model || '',
          expand_idea: s.expand_idea || false,
          enable_concurrency: s.enable_concurrency || false,
          web_search: s.web_search || false,
        });
      }
 
      // 确定要显示的阶段(优先使用 URL 中的目标阶段)
      let finalStage = targetStage;
      if (!finalStage) {
        finalStage = currentStage || (completedStages.length > 0 ? completedStages[completedStages.length - 1] : STAGE_ORDER[0]);
      }
      setActiveStage(finalStage);
      setStageStates(newStates);
 
      // 轮询当前正在执行的阶段(仅当该阶段有 artifact 数据时)
      if (currentStage && stMap[currentStage] === 'running') {
        pollForCompletion(sid, currentStage);
      }
    } catch {
      setActiveStage(STAGE_ORDER[0]);
    }
  };
 
  // ── 返回首页 ──
  // 处理阶段点击,更新 URL
  const handleStageClick = (stage: string) => {
    setActiveStage(stage);
    if (sessionId) {
      router.push(`/?session=${sessionId}&stage=${stage}`);
    }
  };
 
  const handleGoHome = () => {
    setActiveStage(null);
    router.push('/');
  };
 
  // ── 删除历史记录 ──
  const handleDeleteSession = async (sid: string) => {
    await deleteSession(sid);
    setHistory(prev => prev.filter(h => h.id !== sid));
  };
 
  // ── 模型配置变更处理 ──
  const handleModelConfigChange = (config: ModelConfig) => {
    setProjectParams(prev => prev ? { ...prev, ...config } : null);
    // 同步到后端会话元数据
    if (sessionId) {
      const payload: Record<string, any> = { ...config };
      updateModels(sessionId, payload).catch(console.error);
    }
  };
 
  // 构建 modelConfig for TopBar
  const modelConfig: ModelConfig | undefined = projectParams
    ? {
        llm_model: projectParams.llm_model,
        vlm_model: projectParams.vlm_model,
        image_t2i_model: projectParams.image_t2i_model,
        image_it2i_model: projectParams.image_it2i_model,
        video_model: projectParams.video_model,
        video_ratio: projectParams.video_ratio,
        video_resolution: projectParams.video_resolution || '720P',
        enable_concurrency: projectParams.enable_concurrency || false,
        // web_search: projectParams.web_search || false,
        // expand_idea: projectParams.expand_idea || false,
      }
    : undefined;
 
  // ── 计算 stageStatuses for TopBar ──
  // 直接根据后端返回的 status 数据计算图标状态
  const [globalStatusMap, setGlobalStatusMap] = useState<Record<string, string>>({});
  
  const stageStatuses: Record<string, StageStatus> = {};
 
  for (let i = 0; i < STAGE_ORDER.length; i++) {
    const s = STAGE_ORDER[i];
    const backendStatus = globalStatusMap[s]; // get status from global mapping updated from backend
 
    if (backendStatus === 'completed') {
      stageStatuses[s] = 'completed';
    } else if (backendStatus === 'waiting') {
      stageStatuses[s] = 'waiting';
    } else if (backendStatus === 'running') {
      stageStatuses[s] = 'running';
    } else if (backendStatus === 'error') {
      stageStatuses[s] = 'error';
    } else {
      stageStatuses[s] = 'pending';
    }
  }
 
  // ── 计算项目状态 ──
  // 后端状态: pending, running, waiting, completed, completed, error
  // 前端 StageStatus: pending, running, waiting, completed, error
  const hasRunning = Object.values(stageStates).some(s => s.status === 'running');
  const hasWaiting = Object.values(stageStates).some(s => s.status === 'waiting');
  const hasError = Object.values(stageStates).some(s => s.status === 'error');
  const allCompleted = Object.values(stageStates).every(s => s.status === 'completed' || s.status === 'pending');
  const effectiveIsRunning = isRunning || hasRunning;
 
  let computedStatus: string;
  if (hasRunning) computedStatus = 'running';
  else if (hasWaiting) computedStatus = 'waiting';
  else if (hasError) computedStatus = 'error';
  // Check if stopped in stageStates
  else if (Object.values(stageStates).some(s => s.status === 'stopped')) computedStatus = 'stopped';
  else if (allCompleted && stageStates[STAGE_ORDER[STAGE_ORDER.length - 1]]?.status === 'completed') {
    computedStatus = 'completed';
  } else if (allCompleted) {
    computedStatus = 'completed';
  } else {
    computedStatus = Object.values(stageStates).some(s => s.status === 'stopped') ? 'stopped' : 'pending';
  }
 
  const projectStatus = sessionId ? computedStatus : undefined;
 
  // ── 渲染阶段内容 ──
  const renderStageContent = () => {
    if (!activeStage) return null;
    const Component = STAGE_COMPONENTS[activeStage];
    if (!Component) return null;
 
    const state = stageStates[activeStage];
 
    // 判断后续阶段是否已执行过:如有,则隐藏"确认并继续"
    const idx = STAGE_ORDER.indexOf(activeStage);
    const hasSubsequentExecution = STAGE_ORDER.slice(idx + 1).some(
      s => stageStates[s]?.status && stageStates[s].status !== 'pending'
    );
    const showConfirm = !hasSubsequentExecution;
 
    // 计算是否有待生成的项(阶段2、4、5)
    let hasPendingItems = false;
    if (activeStage === 'character_design') {
      const chars = state?.artifact?.characters || [];
      const sets = state?.artifact?.settings || [];
      hasPendingItems = chars.some((c: any) => !c.selected) || sets.some((s: any) => !s.selected);
    } else if (activeStage === 'reference_generation') {
      const scenes = state?.artifact?.scenes || [];
      hasPendingItems = scenes.some((s: any) => !s.selected);
    } else if (activeStage === 'video_generation') {
      const clips = state?.artifact?.clips || [];
      // 检查是否有未选中的 clips
      const hasUnselected = clips.some((c: any) => !c.selected);
      // 检查参考图阶段的 scenes 数量是否大于 video clips 数量
      // 如果是,说明有新分镜需要生成
      const refScenes = stageStates['reference_generation']?.artifact?.scenes || [];
      const hasNewShots = refScenes.length > clips.length;
      hasPendingItems = hasUnselected || hasNewShots;
    }
 
    // 计算后续阶段是否已开始(阶段1、3)
    const hasNextStageStarted = hasSubsequentExecution;
 
    // 传递第4阶段的 artifact 到第5阶段用于依赖检查
    const referenceArtifact = activeStage === 'video_generation'
      ? stageStates['reference_generation']?.artifact
      : undefined;
 
    // 传递第1阶段的 artifact 到第4、5、6阶段用于获取剧集标题
    const scriptArtifact = (activeStage === 'reference_generation' || activeStage === 'video_generation' || activeStage === 'post_production')
      ? stageStates['script_generation']?.artifact
      : undefined;
 
    return (
      <Component
        state={state}
        sessionId={sessionId || ''}
        onConfirm={() => handleConfirmStage(activeStage)}
        onIntervene={(mods: Record<string, any>) => handleIntervene(activeStage, mods)}
        onRegenerate={() => handleRegenerate(activeStage)}
        onUpdateArtifact={(patch: Record<string, any>) => handleUpdateArtifact(activeStage, patch)}
        onSaveSelections={(selections: Record<string, any>) => handleSaveSelections(activeStage, selections)}
        showConfirm={showConfirm}
        isRunning={effectiveIsRunning}
        hasPendingItems={hasPendingItems}
        hasNextStageStarted={hasNextStageStarted}
        videoSound={videoSound}
        videoShotType={videoShotType}
        onVideoParamsChange={(params: { videoSound?: string; videoShotType?: string }) => {
          if (params.videoSound !== undefined) setVideoSound(params.videoSound);
          if (params.videoShotType !== undefined) setVideoShotType(params.videoShotType);
        }}
        referenceArtifact={referenceArtifact}
        scriptArtifact={scriptArtifact}
        artifacts={Object.keys(stageStates).reduce((acc: any, key) => {
          acc[key] = stageStates[key].artifact;
          return acc;
        }, {})}
      />
    );
  };
 
  const showHome = activeStage === null;
 
  return (
    <div className="flex h-screen w-full min-w-0 flex-col bg-gray-50/50">
      <TopBar
        activeStage={activeStage}
        stageStatuses={stageStatuses}
        onStageClick={handleStageClick}
        onHomeClick={handleGoHome}
        hasSession={sessionId !== null}
        isRunning={effectiveIsRunning}
        onStop={handleStop}
        autoMode={autoMode}
        onAutoModeChange={setAutoMode}
        modelConfig={modelConfig}
        onModelConfigChange={handleModelConfigChange}
        projectStatus={projectStatus}
      />
 
      <main className="flex-1 min-w-0 overflow-hidden">
        {showHome ? (
          <HomePage
            onStartProject={handleStartProject}
            onResumeProject={handleResumeProject}
            onDeleteSession={handleDeleteSession}
            history={history}
          />
        ) : (
          renderStageContent()
        )}
      </main>
    </div>
  );
}