hit-cxf
2026-04-05 3abc547ccca33690ab063a6cc6b3a00bb8a0f94a
aigc-claw-v2
11 files modified
433 ■■■■■ changed files
aigc-director/aigc-claw/backend/core/agents/editor_agent.py 112 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/backend/core/agents/reference_agent.py 7 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/backend/core/agents/video_agent.py 14 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/backend/core/orchestrator.py 1 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/backend/tool/video_kling.py 4 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/frontend/components/WorkflowPanel.tsx 15 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/frontend/components/stages/PostProductionStage.tsx 82 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx 117 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/frontend/components/stages/StoryboardStage.tsx 8 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx 71 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/frontend/components/stages/types.ts 2 ●●●●● patch | view | raw | blame | history
aigc-director/aigc-claw/backend/core/agents/editor_agent.py
@@ -38,6 +38,12 @@
        video_art = artifacts.get("video_generation", {})
        clips_list = video_art.get("clips", [])
        
        # 获取剧集标题映射 (从 Storyboard)
        storyboard_art = artifacts.get("storyboard", {})
        episodes_info = storyboard_art.get("episodes", [])
        ep_title_map = {int(ep.get("episode_number", 0)): ep.get("act_title", f"第 {ep.get('episode_number')} 集")
                        for ep in episodes_info if ep.get("episode_number")}
        if not clips_list:
            # 兼容旧逻辑:如果 artifacts 里没有,尝试从 input_data 获取
            selected_clips: dict = input_data.get("selected_clips", {})
@@ -49,92 +55,104 @@
        def run():
            video_dir = os.path.join('code/result/video', str(sid))
            os.makedirs(video_dir, exist_ok=True)
            output_dir = os.path.join(video_dir, 'output')
            os.makedirs(output_dir, exist_ok=True)
            
            clip_paths = []
            # 按剧集分组片段
            episodes_map = {}  # { episode_index: [clip_paths] }
            
            # 如果是从新格式读取
            if clips_list:
                for clip in clips_list:
                    path = clip.get("selected")
                    if path and os.path.exists(path):
                        clip_paths.append(path)
                    else:
                    if not path or not os.path.exists(path):
                        logger.warning(f"[{sid}] Clip missing: {clip.get('id')} → {path}")
                        continue
                    # 优先使用片段数据中的 episode 字段
                    ep_idx = clip.get("episode")
                    # 如果没有 episode 字段,则尝试通过 ID 解析
                    if ep_idx is None:
                        match = re.search(r'(?:seg_|shot_)?(\d{1,3})_\d{1,3}', clip.get("id", ""))
                        if match:
                            ep_idx = int(match.group(1))
            else:
                # 按旧逻辑从 selected_clips (dict) 读取
                            # 最后的归底方案:从 name 提取或默认为 1
                            name_match = re.search(r'第(\d+)集', clip.get("name", ""))
                            if not name_match:
                                name_match = re.search(r'(\d+)', clip.get("name", ""))
                            ep_idx = int(name_match.group(1)) if name_match else 1
                    episodes_map.setdefault(int(ep_idx), []).append(path)
            else:
                # 兼容旧逻辑
                def sort_key(k: str) -> tuple:
                    return tuple(int(n) for n in re.findall(r'\d+', k)) or (999,)
                selected_clips = input_data.get("selected_clips", {})
                for shot_id in sorted(selected_clips.keys(), key=sort_key):
                    path = selected_clips[shot_id]
                    if os.path.exists(path):
                        clip_paths.append(path)
                        # 旧逻辑默认全部归为第1集
                        episodes_map.setdefault(1, []).append(path)
                    else:
                        logger.warning(f"[{sid}] Clip missing: {shot_id} → {path}")
            if not clip_paths:
                raise Exception("没有可用于拼接的视频文件,请检查之前阶段是否生成成功并选中了版本")
            if not episodes_map:
                raise Exception("没有可用于拼接的视频文件")
            logger.info(f"[{sid}] Concat {len(clip_paths)} clips using fast stream copy")
            self._report_progress("后期制作", f"准备拼接 {len(clip_paths)} 个片段...", 15)
            # 导出成片
            output_dir = os.path.join(video_dir, 'output')
            os.makedirs(output_dir, exist_ok=True)
            output = os.path.join(output_dir, f'{sid}_final.mp4')
            # 使用列表文件进行 concat
            list_file = os.path.join(video_dir, 'concat_list.txt')
            with open(list_file, 'w', encoding='utf-8') as f:
                for p in clip_paths:
                    # 使用绝对路径并处理 Windows 路径转义
                    abs_p = os.path.abspath(p).replace('\\', '/')
                    f.write(f"file '{abs_p}'\n")
            try:
                self._report_progress("后期制作", "正在拼接视频 (FFmpeg)...", 50)
            final_videos = []
            sorted_episodes = sorted(episodes_map.keys())
            total_eps = len(sorted_episodes)
                
                ffmpeg_exe = 'ffmpeg'
                
                # 为了播放兼容性,我们进行轻量级的重新编码 (Fast Preset)
                # 这样可以处理不同片段间可能存在的微小元数据差异,确保播放时长正常
            for i, ep_idx in enumerate(sorted_episodes):
                self._report_progress("后期制作", f"正在拼接第 {ep_idx} 集 ({i+1}/{total_eps})...", int(20 + (i/total_eps)*70))
                clip_paths = episodes_map[ep_idx]
                list_file = os.path.join(video_dir, f'concat_list_ep{ep_idx}.txt')
                output = os.path.join(output_dir, f'{sid}_ep{ep_idx}.mp4')
                with open(list_file, 'w', encoding='utf-8') as f:
                    for p in clip_paths:
                        abs_p = os.path.abspath(p).replace('\\', '/')
                        f.write(f"file '{abs_p}'\n")
                cmd = [
                    ffmpeg_exe, '-f', 'concat', '-safe', '0',
                    '-i', list_file, 
                    '-c:v', 'libx264',    # 重新编码视频以保证兼容性
                    '-preset', 'fast',    # 快速平衡速度与质量
                    '-crf', '22',         # 保持高质量
                    '-c:a', 'aac',        # 确保有标准的音频流
                    '-pix_fmt', 'yuv420p', # 确保在所有播放器上都能播放
                    '-movflags', '+faststart',
                    '-y', output
                    '-c:v', 'libx264', '-preset', 'fast', '-crf', '22',
                    '-c:a', 'aac', '-pix_fmt', 'yuv420p',
                    '-movflags', '+faststart', '-y', output
                ]
                
                logger.info(f"[{sid}] Running ffmpeg concat/re-encode: {' '.join(cmd)}")
                result = subprocess.run(cmd, capture_output=True, text=True, check=True)
                logger.info(f"[{sid}] FFmpeg concat success: {output}")
                logger.info(f"[{sid}] Running ffmpeg for Ep {ep_idx}: {' '.join(cmd)}")
                subprocess.run(cmd, capture_output=True, text=True, check=True)
                
            except Exception as e:
                logger.error(f"Fast concat failed: {str(e)}")
                # 如果是权限或路径问题,最后尝试一次 moviepy (虽然慢但兼容性好)
                raise Exception(f"视频快速拼接失败: {str(e)}")
                ep_title = ep_title_map.get(ep_idx, f"第 {ep_idx} 集")
                final_videos.append({
                    "episode": ep_idx,
                    "path": output,
                    "name": ep_title
                })
                
            return output
            return final_videos
        loop = asyncio.get_running_loop()
        final_path = await loop.run_in_executor(None, run)
        final_results = await loop.run_in_executor(None, run)
        self._report_progress("后期制作", "成片完成", 100)
        # 同样将最终结果写入 artifacts
        session_data.setdefault("artifacts", {})["post_production"] = {
            "session_id": sid,
            "final_video": final_path
            "final_videos": final_results,
            "final_video": final_results[0]["path"] if final_results else "" # 兼容旧字段
        }
        with open(session_path, 'w', encoding='utf-8') as f:
            json.dump(session_data, f, indent=4, ensure_ascii=False)
        return {
            "payload": {"session_id": sid, "final_video": final_path},
            "payload": {"session_id": sid, "final_videos": final_results},
            "stage_completed": True,
        }
aigc-director/aigc-claw/backend/core/agents/reference_agent.py
@@ -165,11 +165,14 @@
            
            # 将该段下所有镜头组合为简要说明
            shots_summary = " ".join([s.get('content', '') for s in seg.get('shots', [])])
            ep_n = seg.get('episode_number', 1)
            seg_n = seg.get('segment_number', idx)
            
            preview.append({
                "id": segment_id,
                "name": f"第{seg.get('episode_number', 1)}集-片段{seg.get('segment_number', idx)}",
                "index": idx,
                "name": f"第{ep_n}集-片段{seg_n}",
                "episode": ep_n,
                "index": seg_n,
                "description": shots_summary[:50] + '...' if len(shots_summary) > 50 else shots_summary,
                "selected": versions[-1] if versions else "",
                "versions": versions,
aigc-director/aigc-claw/backend/core/agents/video_agent.py
@@ -158,10 +158,13 @@
        for idx, seg in enumerate(segments, 1):
            segment_id = seg["segment_id"]
            versions = self._list_versions(sid, segment_id)
            ep_n = seg.get('episode_number', 1)
            seg_n = seg.get('segment_number', idx)
            preview.append({
                "id": segment_id,
                "name": f"片段{idx} ({seg.get('location', '')})",
                "index": idx,
                "name": f"第{ep_n}集-片段{seg_n}",
                "episode": ep_n,
                "index": seg_n,
                "description": self._assemble_prompt(seg, style_name),
                "duration": seg.get('total_duration', 10),
                "selected": versions[-1] if versions else "",
@@ -175,10 +178,13 @@
        for idx, seg in enumerate(segments, 1):
            segment_id = seg["segment_id"]
            versions = self._list_versions(sid, segment_id)
            ep_n = seg.get('episode_number', 1)
            seg_n = seg.get('segment_number', idx)
            clips.append({
                "id": segment_id,
                "name": f"片段{idx}",
                "index": idx,
                "name": f"第{ep_n}集-片段{seg_n}",
                "episode": ep_n,
                "index": seg_n,
                "description": self._assemble_prompt(seg, style_name),
                "duration": seg.get('total_duration', 10),
                "selected": versions[-1] if versions else "",
aigc-director/aigc-claw/backend/core/orchestrator.py
@@ -205,7 +205,6 @@
                return
            # 如果有 progress 回调(纯文字阶段),也定期保存
            # 这样前端可以实时看到文字生成进度
            current_time = time.time()
            if current_time - last_save_time["time"] >= SAVE_INTERVAL:
                last_save_time["time"] = current_time
aigc-director/aigc-claw/backend/tool/video_kling.py
@@ -322,7 +322,7 @@
        save_path: str,
        model: str = "kling-v3",
        duration: int = 5,
        mode: str = "std",
        mode: str = "pro",
        cfg_scale: float = 0.5,
        negative_prompt: str = "",
        sound: str = "",
@@ -387,7 +387,7 @@
    PROMPT = ""
    MODEL = "kling-v3"         # kling-v3 / kling-v2-6 / kling-v2-5-turbo
    DURATION = 5               # v3: 3~15, v2: 5 或 10
    MODE = "std"               # std 或 pro
    MODE = "pro"               # std 或 pro
    SOUND = ""                 # "" = 自动开启, "on", "off"
    print("=== 可灵 (Kling) 图生视频测试 ===")
aigc-director/aigc-claw/frontend/components/WorkflowPanel.tsx
@@ -378,6 +378,11 @@
            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,
@@ -1180,6 +1185,11 @@
      ? 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}
@@ -1200,6 +1210,11 @@
          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;
        }, {})}
      />
    );
  };
aigc-director/aigc-claw/frontend/components/stages/PostProductionStage.tsx
@@ -7,46 +7,92 @@
import StageProgress from './StageProgress';
import StageActions from './StageActions';
export default function PostProductionStage({ state, onConfirm, onRegenerate, showConfirm, isRunning, hasPendingItems, hasNextStageStarted }: StageViewProps) {
  // payload: { session_id, final_video: "code/result/video/{sid}/{sid}_final.mp4" }
  const finalVideoPath: string = state.artifact?.final_video || '';
  const finalVideoUrl = assetUrl(finalVideoPath);
export default function PostProductionStage({ state, onConfirm, onRegenerate, showConfirm, isRunning, hasPendingItems, hasNextStageStarted, artifacts, scriptArtifact }: StageViewProps) {
  // 提取最终视频列表
  const finalVideos: any[] = state.artifact?.final_videos || [];
  // 兼容旧格式及其变形
  const legacyVideo = state.artifact?.final_video;
  // 从剧本或分镜数据中提取剧集名称映射
  const episodeTitleMap = React.useMemo(() => {
    // 优先从 scriptArtifact 获取
    const episodes = scriptArtifact?.episodes || artifacts?.storyboard?.episodes || artifacts?.script?.episodes || [];
    const map: Record<number, string> = {};
    episodes.forEach((ep: any) => {
      const epNum = ep.episode_number || ep.episode;
      if (epNum) {
        map[Number(epNum)] = ep.act_title || ep.title || '';
      }
    });
    return map;
  }, [artifacts, scriptArtifact]);
  // 确保能拿到展示数据
  const videosToDisplay = React.useMemo(() => {
    if (finalVideos && finalVideos.length > 0) return finalVideos;
    if (legacyVideo) return [{ name: '最终成片', path: legacyVideo, episode: 1 }];
    return [];
  }, [finalVideos, legacyVideo]);
  return (
    <div className="flex flex-col h-full">
      <div className="flex-1 overflow-y-auto p-6">
        <h2 className="text-lg font-semibold text-gray-800 mb-1">后期剪辑</h2>
        <p className="text-sm text-gray-500 mb-6">拼接所有视频片段,合成最终成片</p>
        <p className="text-sm text-gray-500 mb-6">按剧集拼接视频,生成各集独立成片</p>
        {/* 运行中 */}
        {state.status === 'running' && (
          <StageProgress message={state.progressMessage} fallback="正在合成最终视频..." progress={state.progress} color="cyan" />
          <StageProgress message={state.progressMessage} fallback="正在合成视频..." progress={state.progress} color="cyan" />
        )}
        {state.error && (
          <div className="text-sm text-red-600 bg-red-50 border border-red-200 p-4 rounded-xl mb-4">{state.error}</div>
        )}
        {/* 最终视频 */}
        {finalVideoUrl && (
          <div className="space-y-4">
            <div className="bg-black rounded-xl overflow-hidden shadow-lg">
              <video src={finalVideoUrl} controls className="w-full max-h-[65vh]" />
        {/* 最终视频列表 */}
        {videosToDisplay.length > 0 && (
          <div className="space-y-10 pb-10">
            {videosToDisplay.map((video, idx) => {
              const epNum = video.episode || (idx + 1);
              const scriptTitle = episodeTitleMap[epNum];
              const epTitle = scriptTitle ? `第 ${epNum} 集:${scriptTitle}` : (video.name || `第 ${epNum} 集`);
              return (
                <div key={idx} className="space-y-4">
                  {/* 剧集分割行 - 完全同步 S4/S5 格式 */}
                  <div className="flex items-center justify-between py-2 px-1 border-b border-gray-100">
                    <div className="flex items-center gap-3">
                      <div className="w-1.5 h-6 bg-cyan-500 rounded-full" />
                      <h3 className="text-base font-bold text-gray-800">{epTitle}</h3>
            </div>
            <div className="flex items-center justify-center gap-3">
                  </div>
                  <div className="bg-black rounded-xl overflow-hidden shadow-lg border border-gray-800">
                    <video
                      src={assetUrl(video.path)}
                      controls
                      className="w-full max-h-[60vh] object-contain"
                    />
                  </div>
                  <div className="flex items-center justify-end">
              <a
                href={finalVideoUrl}
                download
                className="flex items-center gap-2 px-5 py-2.5 bg-blue-500 text-white rounded-xl text-sm font-medium hover:bg-blue-600 transition-colors"
                      href={assetUrl(video.path)}
                      download={`${epTitle}.mp4`}
                      className="flex items-center gap-2 px-4 py-2 bg-gray-800 text-white rounded-lg text-xs font-medium hover:bg-black transition-colors"
              >
                <Download className="w-4 h-4" />
                下载成片
                      <Download className="w-3.5 h-3.5" />
                      下载本集
              </a>
            </div>
          </div>
              );
            })}
          </div>
        )}
        {state.status === 'completed' && !finalVideoUrl && (
        {state.status === 'completed' && videosToDisplay.length === 0 && (
          <div className="flex flex-col items-center justify-center py-20 text-gray-400">
            <Film className="w-12 h-12 mb-3" />
            <div className="text-sm">视频合成完成</div>
aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx
@@ -138,6 +138,7 @@
  isRegenerating,
  isEditing,
  onToggleEdit,
  getSelected,
}: {
  scene: SceneItem;
  canEdit: boolean;
@@ -150,6 +151,7 @@
  isRegenerating?: boolean;
  isEditing?: boolean;
  onToggleEdit?: () => void;
  getSelected: (scene: SceneItem) => string;
}) {
  const isPending = scene.status === 'pending' || isRegenerating;
  const isFailed = scene.status === 'failed' && !isRegenerating;
@@ -163,10 +165,10 @@
      {/* 左侧: 提示词 */}
      <div className="w-[360px] flex-shrink-0 p-4 border-r border-gray-100 flex flex-col">
        <div className="flex items-center gap-2 mb-2">
          <span className="flex items-center justify-center w-6 h-6 rounded-full bg-emerald-100 text-emerald-700 text-xs font-bold flex-shrink-0">
          <span className="flex items-center justify-center h-6 px-1.5 rounded-full bg-emerald-100 text-emerald-700 text-[10px] font-bold flex-shrink-0 whitespace-nowrap">
            {scene.index ?? scene.id.replace('Scene_', '')}
          </span>
          <span className="text-sm font-semibold text-gray-800 truncate">{scene.name}</span>
          <span className="text-sm font-semibold text-gray-800 truncate">{scene.name || (scene as any).title || `片段 ${scene.index}`}</span>
          {isPending && (
            <span className="inline-flex items-center gap-1 text-[10px] bg-amber-50 text-amber-600 px-1.5 py-0.5 rounded">
              <Loader className="w-2.5 h-2.5 animate-spin" />生成中
@@ -206,10 +208,12 @@
            value={editDesc}
            onChange={e => onDescChange(e.target.value)}
            rows={6}
            className="flex-1 text-xs text-gray-600 bg-gray-50 border border-gray-200 rounded-lg p-2 resize-none focus:outline-none focus:ring-1 focus:ring-emerald-300"
            className="h-[180px] text-xs text-gray-600 bg-gray-50 border border-gray-200 rounded-lg p-2 resize-none focus:outline-none focus:ring-1 focus:ring-emerald-300"
          />
        ) : (
          <p className="flex-1 text-xs text-gray-600 leading-relaxed line-clamp-6">{scene.description}</p>
          <div className="h-[180px] overflow-y-auto pr-1 custom-scrollbar">
            <p className="text-xs text-gray-600 leading-relaxed whitespace-pre-wrap">{scene.description}</p>
          </div>
        )}
        {/* 重新生成按钮 */}
        {!isStageRunning && (
@@ -263,7 +267,7 @@
          <div className="relative w-full">
            <ImageGallery
              versions={scene.versions}
              selected={scene.selected}
              selected={getSelected(scene)}
              onSelect={onSelectVersion}
              showPlaceholder={isRegenerating}
            />
@@ -284,7 +288,31 @@
}
/* ─── 主组件 ─── */
export default function ReferenceStage({ state, sessionId, onConfirm, onIntervene, onRegenerate, onUpdateArtifact, onSaveSelections, showConfirm, isRunning, hasPendingItems, hasNextStageStarted }: StageViewProps) {
export default function ReferenceStage({ state, sessionId, onConfirm, onIntervene, onRegenerate, onUpdateArtifact, onSaveSelections, showConfirm, isRunning, hasPendingItems, hasNextStageStarted, scriptArtifact }: StageViewProps) {
  const [editDescs, setEditDescs] = useState<Record<string, string>>({});
  const [selectedVersions, setSelectedVersions] = useState<Record<string, string>>({});
  const [regeneratingIds, setRegeneratingIds] = useState<Set<string>>(new Set());
  const [editingIds, setEditingIds] = useState<Set<string>>(new Set());
  const [savingIds, setSavingIds] = useState<Set<string>>(new Set());
  // 提取剧集标题映射
  const episodeTitleMap = React.useMemo(() => {
    const map: Record<number, string> = {};
    if (scriptArtifact?.episodes) {
      scriptArtifact.episodes.forEach((ep: any) => {
        // 关键修复:这里的字段名应该是 episode_number 和 act_title
        const epNum = ep.episode_number || ep.episode;
        const epTitle = ep.act_title || ep.title;
        if (epNum) {
          map[Number(epNum)] = epTitle || '';
        }
      });
    }
    return map;
  }, [scriptArtifact]);
  const getSelected = (scene: SceneItem) => selectedVersions[scene.id] || scene.selected;
  // 兼容旧格式: scene_images: {Scene_1: "path"} → scenes: [{id, ...}]
  const scenes: SceneItem[] = (() => {
    if (state.artifact?.scenes?.length) return state.artifact.scenes;
@@ -307,12 +335,6 @@
    }
    return [];
  })();
  const [editDescs, setEditDescs] = useState<Record<string, string>>({});
  const [selectedVersions, setSelectedVersions] = useState<Record<string, string>>({});
  const [regeneratingIds, setRegeneratingIds] = useState<Set<string>>(new Set());
  const [editingIds, setEditingIds] = useState<Set<string>>(new Set());
  const [savingIds, setSavingIds] = useState<Set<string>>(new Set());
  const canEdit = state.status === 'waiting' || state.status === 'completed';
@@ -395,7 +417,11 @@
  };
  const handleRegenerate = (sceneId: string) => {
    setRegeneratingIds(prev => new Set(prev).add(sceneId));
    setRegeneratingIds(prev => {
      const next = new Set(prev);
      next.add(sceneId);
      return next;
    });
    onIntervene({ regenerate_scenes: [sceneId] });
  };
@@ -416,8 +442,6 @@
      await onSaveSelections(selections);
    }
  };
  const getSelected = (scene: SceneItem) => selectedVersions[scene.id] || scene.selected;
  return (
    <div className="flex flex-col h-full">
@@ -441,34 +465,63 @@
        {/* ═══ 场景列表 ═══ */}
        {hasScenes && (
          <section>
            <div className="flex items-center gap-2 mb-3">
              <ImageIcon className="w-4 h-4 text-emerald-500" />
              <h3 className="text-sm font-semibold text-gray-700">场景参考图 ({scenes.length})</h3>
          <div className="space-y-10">
            {(() => {
              // 按剧集分组
              const episodes: Record<number, SceneItem[]> = {};
              scenes.forEach(s => {
                const ep = (s as any).episode || 1;
                if (!episodes[ep]) episodes[ep] = [];
                episodes[ep].push(s);
              });
              return Object.keys(episodes).sort((a, b) => Number(a) - Number(b)).map(epNum => {
                const epScenes = episodes[Number(epNum)];
                const fallbackTitle = (epScenes[0] as any).episode_title || `第 ${epNum} 集`;
                const scriptTitle = episodeTitleMap[Number(epNum)];
                const episodeTitle = scriptTitle ? `第 ${epNum} 集:${scriptTitle}` : fallbackTitle;
                return (
                  <div key={epNum} className="space-y-4">
                    <div className="flex items-center justify-between py-2 px-1 border-b border-gray-100">
                      <div className="flex items-center gap-3">
                        <div className="w-1.5 h-6 bg-emerald-500 rounded-full" />
                        <h3 className="text-base font-bold text-gray-800">{episodeTitle}</h3>
            </div>
            <div className="space-y-3">
              {scenes.map(scene => (
                      <span className="text-[11px] text-emerald-600 font-medium bg-emerald-50 px-2.5 py-1 rounded-full border border-emerald-100 italic">
                        {epScenes.length} 个片段
                      </span>
                    </div>
                    <div className="space-y-4">
                      {epScenes.map(scene => (
                        <div key={scene.id} className="relative">
                <SceneRow
                  key={scene.id}
                  scene={{ ...scene, selected: getSelected(scene) }}
                  canEdit={canEdit}
                  editDesc={editDescs[scene.id] || scene.description}
                  onDescChange={val => setEditDescs(prev => ({ ...prev, [scene.id]: val }))}
                  onRegenerate={() => handleRegenerate(scene.id)}
                  onSelectVersion={path => handleSelectVersion(scene.id, path)}
                            scene={scene}
                            editDesc={editDescs[scene.id] ?? scene.description}
                            onDescChange={(val) => setEditDescs(prev => ({ ...prev, [scene.id]: val }))}
                  onSavePrompt={() => handleSavePrompt(scene.id)}
                            onRegenerate={() => handleRegenerate(scene.id)}
                            onSelectVersion={(path) => handleSelectVersion(scene.id, path)}
                  isStageRunning={state.status === 'running'}
                  isRegenerating={regeneratingIds.has(scene.id) || savingIds.has(scene.id)}
                            isRegenerating={regeneratingIds.has(scene.id)}
                  isEditing={editingIds.has(scene.id)}
                  onToggleEdit={() => handleToggleEdit(scene.id)}
                            canEdit={canEdit}
                            getSelected={getSelected}
                />
                        </div>
              ))}
            </div>
          </section>
                  </div>
                );
              });
            })()}
          </div>
        )}
        {/* 如果有 artifact 数据(即使 status 是 pending),也显示内容 */}
        {state.status === 'pending' && !hasScenes && (
        {!hasScenes && state.status === 'pending' && (
          <div className="text-center text-gray-400 text-sm py-20">等待上一阶段完成...</div>
        )}
      </div>
@@ -478,7 +531,6 @@
        status={state.status}
        onConfirm={onConfirm}
        showConfirm={showConfirm}
        onSave={undefined}
        onRegenerate={onRegenerate}
        stageId="reference_generation"
        hasPendingItems={hasPendingItems}
@@ -488,3 +540,4 @@
    </div>
  );
}
aigc-director/aigc-claw/frontend/components/stages/StoryboardStage.tsx
@@ -250,12 +250,12 @@
              return (
                <div key={epIdx} className="space-y-4">
                  {/* 一级:剧集抬头 (参考第一阶段) */}
                  <div className="flex items-center justify-between border-b pb-2 border-gray-100">
                  <div className="flex items-center justify-between py-2 px-1 border-b border-gray-100">
                    <div className="flex items-center gap-3">
                      <span className="text-xs font-black text-white bg-violet-500 px-2 py-0.5 rounded leading-tight shadow-sm">第 {String(episode.episode_number)} 集</span>
                      <h3 className="text-base font-bold text-gray-800">{episode.episode_title}</h3>
                      <div className="w-1.5 h-6 bg-violet-500 rounded-full" />
                      <h3 className="text-base font-bold text-gray-800">第 {String(episode.episode_number)} 集:{episode.episode_title}</h3>
                    </div>
                    <span className="text-[11px] font-bold text-violet-600 bg-violet-50 px-2 py-0.5 rounded-full flex items-center gap-1">
                    <span className="text-[11px] text-violet-600 font-medium bg-violet-50 px-2.5 py-1 rounded-full border border-violet-100 flex items-center gap-1 italic">
                      <Clock className="w-3 h-3" /> 总计 {epTotalTime}s
                    </span>
                  </div>
aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx
@@ -156,7 +156,7 @@
      {/* 左侧: 描述信息 */}
      <div className="w-[280px] flex-shrink-0 p-4 border-r border-gray-100 flex flex-col">
        <div className="flex items-center gap-2 mb-2">
          <span className="flex items-center justify-center w-6 h-6 rounded-full bg-rose-100 text-rose-700 text-xs font-bold flex-shrink-0">
          <span className="flex items-center justify-center h-6 px-1.5 rounded-full bg-rose-100 text-rose-700 text-[10px] font-bold flex-shrink-0 whitespace-nowrap">
            {clip.index ?? clip.id.replace('Scene_', '')}
          </span>
          <span className="text-sm font-semibold text-gray-800 truncate">{clip.name}</span>
@@ -202,12 +202,16 @@
            value={editDesc ?? clip.description}
            onChange={e => onDescChange?.(e.target.value)}
            rows={4}
            className="flex-1 text-xs text-gray-600 bg-gray-50 border border-gray-200 rounded-lg p-2 resize-none focus:outline-none focus:ring-1 focus:ring-rose-300"
            className="h-[120px] text-xs text-gray-600 bg-gray-50 border border-gray-200 rounded-lg p-2 resize-none focus:outline-none focus:ring-1 focus:ring-rose-300"
          />
        ) : clip.description ? (
          <p className="flex-1 text-xs text-gray-600 leading-relaxed line-clamp-4">{clip.description}</p>
          <div className="h-[120px] overflow-y-auto pr-1 custom-scrollbar">
             <p className="text-xs text-gray-600 leading-relaxed whitespace-pre-wrap">{clip.description}</p>
          </div>
        ) : (
          <p className="flex-1 text-xs text-gray-400 italic">无提示词</p>
          <div className="h-[120px] flex items-center justify-center">
            <p className="text-xs text-gray-400 italic">无提示词</p>
          </div>
        )}
        {/* 重新生成按钮 */}
        {!isStageRunning && (
@@ -272,7 +276,23 @@
}
/* ─── 主组件 ─── */
export default function VideoStage({ state, sessionId, onConfirm, onIntervene, onRegenerate, onUpdateArtifact, onSaveSelections, showConfirm, isRunning, videoSound = 'on', videoShotType = 'multi', onVideoParamsChange, referenceArtifact, hasPendingItems, hasNextStageStarted }: StageViewProps) {
export default function VideoStage({ state, sessionId, onConfirm, onIntervene, onRegenerate, onUpdateArtifact, onSaveSelections, showConfirm, isRunning, videoSound = 'on', videoShotType = 'multi', onVideoParamsChange, referenceArtifact, hasPendingItems, hasNextStageStarted, scriptArtifact }: StageViewProps) {
  // 提取剧集标题映射
  const episodeTitleMap = React.useMemo(() => {
    const map: Record<number, string> = {};
    if (scriptArtifact?.episodes) {
      scriptArtifact.episodes.forEach((ep: any) => {
        // 关键修复:兼容剧本阶段的字段名
        const epNum = ep.episode_number || ep.episode;
        const epTitle = ep.act_title || ep.title;
        if (epNum) {
          map[Number(epNum)] = epTitle || '';
        }
      });
    }
    return map;
  }, [scriptArtifact]);
  // 检查每个 clip 是否有对应的参考图
  const hasReferenceImage = useCallback((clipId: string): boolean => {
    if (!referenceArtifact?.scenes) return false;
@@ -484,13 +504,36 @@
        {/* ═══ 视频列表 ═══ */}
        {hasClips && (
          <section>
            <div className="flex items-center gap-2 mb-3">
              <Film className="w-4 h-4 text-rose-500" />
              <h3 className="text-sm font-semibold text-gray-700">视频片段 ({clips.length})</h3>
          <div className="space-y-10">
            {(() => {
              // 按剧集分组
              const episodes: Record<number, ClipItem[]> = {};
              clips.forEach(c => {
                const ep = (c as any).episode || 1;
                if (!episodes[ep]) episodes[ep] = [];
                episodes[ep].push(c);
              });
              return Object.keys(episodes).sort((a, b) => Number(a) - Number(b)).map(epNum => {
                const epClips = episodes[Number(epNum)];
                const fallbackTitle = (epClips[0] as any).episode_title || `第 ${epNum} 集`;
                const scriptTitle = episodeTitleMap[Number(epNum)];
                const episodeTitle = scriptTitle ? `第 ${epNum} 集:${scriptTitle}` : fallbackTitle;
                return (
                  <div key={epNum} className="space-y-6">
                    <div className="flex items-center justify-between py-2 px-1 border-b border-gray-100">
                      <div className="flex items-center gap-3">
                        <div className="w-1.5 h-6 bg-blue-500 rounded-full" />
                        <h3 className="text-base font-bold text-gray-800">{episodeTitle}</h3>
            </div>
            <div className="space-y-3">
              {clips.map(clip => {
                      <span className="text-[11px] text-blue-600 font-medium bg-blue-50 px-2.5 py-1 rounded-full border border-blue-100 italic">
                        {epClips.length} 个片段
                      </span>
                    </div>
                    <div className="space-y-4">
                      {epClips.map(clip => {
                // 检查是否有参考图
                const hasRef = hasReferenceImage(clip.id);
                return (
@@ -520,7 +563,11 @@
                );
              })}
            </div>
          </section>
                  </div>
                );
              });
            })()}
          </div>
        )}
        {/* 如果有 artifact 数据(即使 status 是 pending),也显示内容 */}
aigc-director/aigc-claw/frontend/components/stages/types.ts
@@ -29,4 +29,6 @@
  onVideoParamsChange?: (params: { videoSound?: string; videoShotType?: string }) => void;
  /** 参考图阶段的 artifact(仅 VideoStage 使用,用于检查依赖) */
  referenceArtifact?: any;
  /** 剧本阶段的 artifact(用于获取剧集标题) */
  scriptArtifact?: any;
}