From 9558cb63d47ecf231b55ecf8ce09481bcd63e3cd Mon Sep 17 00:00:00 2001
From: hit-cxf <2024111082@stu.hit.edu.cn>
Date: Thu, 09 Apr 2026 12:01:51 +0800
Subject: [PATCH] 添加了续写功能

---
 aigc-director/aigc-claw/backend/core/agents/video_agent.py             |    7 
 aigc-director/references/workflow/create_project.md                    |    6 
 aigc-director/aigc-claw/backend/prompts/script/meta_extract_zh.txt     |    2 
 aigc-director/aigc-claw/backend/prompts/storyboard/shot_zh.txt         |    7 
 aigc-director/aigc-claw/backend/api_server.py                          |   40 +
 aigc-director/aigc-claw/frontend/components/WorkflowPanel.tsx          |  211 +++++++------
 aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx  |   14 
 aigc-director/SKILL.md                                                 |   16 
 aigc-director/CLAUDE.md                                                |    8 
 /dev/null                                                              |   41 --
 aigc-director/aigc-claw/frontend/components/TopBar.tsx                 |   19 
 aigc-director/aigc-claw/frontend/components/stages/StoryboardStage.tsx |   18 
 aigc-director/aigc-claw/frontend/components/HomePage.tsx               |   21 
 aigc-director/aigc-claw/backend/core/agents/reference_agent.py         |   14 
 aigc-director/aigc-claw/backend/core/agents/storyboard_agent.py        |   59 ++-
 aigc-director/aigc-claw/backend/core/orchestrator.py                   |  365 ++++++++++++++++--------
 aigc-director/aigc-claw/frontend/components/stages/StageActions.tsx    |   12 
 aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx      |   14 
 aigc-director/aigc-claw/frontend/lib/workflowApi.ts                    |    3 
 19 files changed, 523 insertions(+), 354 deletions(-)

diff --git a/aigc-director/CLAUDE.md b/aigc-director/CLAUDE.md
index ba2d065..fc67296 100644
--- a/aigc-director/CLAUDE.md
+++ b/aigc-director/CLAUDE.md
@@ -1,4 +1,4 @@
-# CLAUDE.md
+# CLAUDE.md
 
 This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
 
@@ -38,9 +38,9 @@
 ## Architecture
 
 ### Backend Core
-- **[orchestrator.py](aigc-claw/backend/core/orchestrator.py)**: Workflow engine managing the 6-stage state machine. Controls session state (idle/running/waiting_in_stage/stage_completed/session_completed), persists to `aigc-claw/backend/code/data/sessions/`, and coordinates agent execution.
+- **[orchestrator.py](aigc-claw/backend/core/orchestrator.py)**: Workflow engine managing the 6-stage state machine. Controls session state (pending/running/waiting/completed/completed), persists to `aigc-claw/backend/code/data/sessions/`, and coordinates agent execution.
 
-- **[base_agent.py](aigc-claw/backend/core/agents/base_agent.py)**: Abstract base class for all stage agents. Defines `process(input_data, intervention)` interface that returns `{"payload": ..., "requires_intervention": bool, "stage_completed": bool}`.
+- **[base_agent.py](aigc-claw/backend/core/agents/base_agent.py)**: Abstract base class for all stage agents. Defines `process(input_data, intervention)` interface that returns `{"payload": ..., "requires_intervention": bool, "completed": bool}`.
 
 ### 6 Stage Agents
 Each agent handles one workflow stage:
@@ -94,4 +94,4 @@
 
 Important files:
 - [SKILL.md](SKILL.md) - Contains the complete workflow rules for OpenClaw agent execution
-- [README.md](README.md) - Full project documentation including model configuration
\ No newline at end of file
+- [README.md](README.md) - Full project documentation including model configuration
diff --git a/aigc-director/SKILL.md b/aigc-director/SKILL.md
index e34503e..2657202 100644
--- a/aigc-director/SKILL.md
+++ b/aigc-director/SKILL.md
@@ -1,4 +1,4 @@
----
+---
 name: aigc-director
 description: AI 视频生成全流程:通过 6 个阶段(剧本→角色/场景设计→分镜→参考图→视频生成→后期剪辑)将用户想法转化为完整视频。支持临时工作台(单独调用 LLM、VLM、文生图、图生图、视频生成)。触发词:视频生成、AI视频、AIGC、创作视频、制作视频、AI画图。
 license: MIT License
@@ -137,7 +137,7 @@
 
 ## 🚨 停点处理(强制规则)
 
-**当查询状态为 `stage_completed` 或 `waiting_in_stage` 时,必须按以下步骤执行:**
+**当查询状态为 `completed` 或 `waiting` 时,必须按以下步骤执行:**
 
 ### 步骤1:获取产物
 ```bash
@@ -169,14 +169,14 @@
 ### ✅ 正确示例
 ```
 1. 阶段中间遇到不确定内容
-收到 waiting_in_stage 停点
+收到 waiting 停点
 → 获取 artifact 查看内容
 → 展示给用户选项
 → 询问:"是否同意修改?"
 → 用户回复"同意" → 调用 intervene
 
 2. 阶段完成停点触发
-收到 stage_completed 停点
+收到 completed 停点
 → 获取 artifact 查看产物内容
 → 展示给用户:"第一阶段已完成,生成了剧本内容(x集)..."
 → 询问:"是否继续下一阶段?"
@@ -194,11 +194,11 @@
 
 | status | 含义 | 操作 |
 |--------|------|------|
-| idle | 新建会话 | 启动项目 |
+| pending | 新建会话 | 启动项目 |
 | running | 执行中 | 轮询等待 |
-| waiting_in_stage | 等待用户介入 | 调用 `intervene` |
-| stage_completed | 阶段完成 | 调用 `continue` |
-| session_completed | 全部完成 | 结束 |
+| waiting | 等待用户介入 | 调用 `intervene` |
+| completed | 阶段完成 | 调用 `continue` |
+| completed | 全部完成 | 结束 |
 
 > **注意**:只有 status 变化时才需要干预,不要反复调用 artifact API 去"确认"!
 
diff --git a/aigc-director/aigc-claw/backend/api_server.py b/aigc-director/aigc-claw/backend/api_server.py
index dc72485..8fcd732 100644
--- a/aigc-director/aigc-claw/backend/api_server.py
+++ b/aigc-director/aigc-claw/backend/api_server.py
@@ -114,7 +114,9 @@
     session_id = str(int(time.time() * 1000))
     state = workflow_engine.get_or_create_state(session_id)
     state.started_at = __import__('datetime').datetime.now()
-    state.status = "stage_completed"
+    if not isinstance(state.status, dict):
+        state.status = {}
+    state.status[state.current_stage.value] = "completed"
 
     # 保存会话元数据(未传参数时使用 config.py 中的默认值)
     meta = {
@@ -418,24 +420,38 @@
             if 'is_new' in shot:
                 shot['is_new'] = False
 
-        # 同步到 video_generation
-        shot_id_to_duration = {s['shot_id']: s.get('duration', 10) for s in body['shots'] if 'shot_id' in s}
-        shot_id_to_plot = {s['shot_id']: s.get('plot', '') for s in body['shots'] if 'shot_id' in s}
+        # 从 body['segments'] 提取同步信息(修改后的逻辑按 segment 同步)
+        seg_info_list = []
+        for seg in body.get('segments', []):
+            seg_id = seg.get('segment_id')
+            if not seg_id: continue
+            
+            shots = seg.get('shots', [])
+            desc_video = " ".join([sh.get("plot") or sh.get("content") or "" for sh in shots]).strip()
+            total_dur = seg.get("total_duration") or sum([sh.get("duration", 0) for sh in shots]) or 10
+            
+            seg_info_list.append({
+                "segment_id": seg_id,
+                "desc": desc_video,
+                "duration": total_dur
+            })
 
+        # 同步到 video_generation
         video_art = state.artifacts.get('video_generation', {})
         if isinstance(video_art, dict) and 'clips' in video_art:
             for clip in video_art['clips']:
-                shot_id = clip.get('id')
-                if shot_id in shot_id_to_duration:
-                    clip['duration'] = shot_id_to_duration[shot_id]
-                if shot_id in shot_id_to_plot:
-                    clip['description'] = shot_id_to_plot[shot_id]
+                c_id = clip.get('id')
+                # 匹配 segment_id
+                target = next((item for item in seg_info_list if item["segment_id"] == c_id), None)
+                if target:
+                    clip['duration'] = target['duration']
+                    clip['description'] = target['desc']
 
-        # 移除 shots,避免覆盖 storyboard artifact
-        body = {k: v for k, v in body.items() if k != "shots"}
+        # 移除 segments,避免覆盖 storyboard artifact
+        body = {k: v for k, v in body.items() if k != "segments"}
 
         # 清除 new_shot_ids 标记
-        if "new_shot_ids" in body and body.get('new_shot_ids') == []:
+        if "new_shot_ids" in body:
             del body['new_shot_ids']
 
     # ══════════════════════════════════════════════════════════════
diff --git a/aigc-director/aigc-claw/backend/core/agents/reference_agent.py b/aigc-director/aigc-claw/backend/core/agents/reference_agent.py
index 4ca757f..c9c1bfd 100644
--- a/aigc-director/aigc-claw/backend/core/agents/reference_agent.py
+++ b/aigc-director/aigc-claw/backend/core/agents/reference_agent.py
@@ -734,7 +734,15 @@
                     first_frame_prompts[segment_id] = ff_prompt
                     logger.info(f"[{segment_id}] Prompt ready, starting image generation...")
 
-                    # 2. 立即提交图像生成任务,不再等待其他片段的提示词
+                    # 2. 发送任务开始状态 (Running),以便前端 UI 立即显示加载状态
+                    self._report_progress("参考图", f"正在启动: {segment_id}", calc_pct(i * steps_per_segment), data={
+                        "asset_complete": {
+                            "type": "scenes", "id": segment_id,
+                            "status": "running"
+                        }
+                    })
+
+                    # 3. 立即提交图像生成任务,不再等待其他片段的提示词
                     refs = self._collect_refs(seg, asset_map, char_id_map, setting_id_map)
                     fut = executor.submit(
                         self._generate_one, img_client, sid,
@@ -745,9 +753,9 @@
                     futs[fut] = segment_id
                     
                     # 报告进度(提交任务也算一点进度)
-                    self._report_progress("参考图", f"正在生成: {segment_id}", calc_pct(i * steps_per_segment))
+                    self._report_progress("参考图", f"等待生成: {segment_id}", calc_pct(i * steps_per_segment))
 
-                # 3. 等待所有任务完成
+                # 4. 等待所有任务完成
                 cancelled = False
                 for fut in as_completed(futs):
                     segment_id_done = futs[fut]
diff --git a/aigc-director/aigc-claw/backend/core/agents/storyboard_agent.py b/aigc-director/aigc-claw/backend/core/agents/storyboard_agent.py
index 3522201..0d4519f 100644
--- a/aigc-director/aigc-claw/backend/core/agents/storyboard_agent.py
+++ b/aigc-director/aigc-claw/backend/core/agents/storyboard_agent.py
@@ -24,10 +24,6 @@
     from prompts.loader import load_prompt_with_fallback
     return load_prompt_with_fallback("storyboard", "shot", lang, "zh")
 
-def _get_continue_prompt(lang: str = "zh") -> str:
-    from prompts.loader import load_prompt_with_fallback
-    return load_prompt_with_fallback("storyboard", "continue", lang, "zh")
-
 class StoryboardAgent(AgentInterface):
     def __init__(self):
         super().__init__(name="Storyboard")
@@ -202,16 +198,13 @@
             
             if not extracted:
                 logger.error(f"LLM output failed to parse as JSON for Episode {ep_n} after {max_retries} attempts. Raw: {raw}")
-                return {
-                    "episode_number": ep_n,
-                    "episode_title": ep_t,
-                    "segments": []
-                }
+                # 抛出异常以触发 orchestrator 的错误状态处理逻辑
+                raise Exception(f"第 {ep_n} 集分镜生成失败:模型输出无法解析")
                 
-            # 我们直接手动处理 segments
             valid_segments = []
             for i, seg in enumerate(extracted, 1):
                 if not isinstance(seg, dict): continue
+                
                 shots = seg.get("shots", [])
                 valid_shots = []
                 calc_total_duration = 0
@@ -225,12 +218,13 @@
                         "duration": dur,
                         "content": s.get("content", "")
                     })
+                
                 valid_segments.append({
-                    "segment_id": f"seg_{ep_n:02d}_{i:02d}",
-                    "segment_number": i,
+                    "segment_id": seg.get("segment_id", f"seg_{ep_n:02d}_{i:02d}"),
+                    "segment_number": seg.get("segment_number", len(valid_segments) + 1),
+                    "total_duration": seg.get("total_duration", calc_total_duration),
                     "location": seg.get("location", ""),
                     "characters": seg.get("characters", []),
-                    "total_duration": seg.get("total_duration", calc_total_duration),
                     "shots": valid_shots,
                     "episode_number": ep_n
                 })
@@ -241,14 +235,39 @@
                 "segments": valid_segments
             }
 
-        # 并发处理新增集数
-        new_story_results = await asyncio.gather(*(proc_ep(ep) for ep in episodes_to_proc))
-        
-        # 合并旧数据和新数据
+        # 核心:支持流式保存增量产物,让前端能看到实时进度
         updated_ep_map = {e["episode_number"]: e for e in existing_story_eps}
-        for res in new_story_results:
+        
+        # 立即先保存一次,确保已有的 episodes 在进入 running 状态后依然可见
+        session_data.setdefault("artifacts", {})["storyboard"] = {
+            "session_id": sid, 
+            "episodes": sorted(updated_ep_map.values(), key=lambda x: x["episode_number"]),
+            "created_at": datetime.now().isoformat()
+        }
+        with open(session_file, "w", encoding="utf-8") as f:
+            json.dump(session_data, f, indent=2, ensure_ascii=False)
+        # 报告一次进度,带上 asset_complete 强制前端从磁盘刷新一次初步数据
+        self._report_progress("分镜设计", "准备生成分镜...", 10, {"asset_complete": True})
+
+        results_queue = [proc_ep(ep) for ep in episodes_to_proc]
+
+        for coro in asyncio.as_completed(results_queue):
+            res = await coro
             updated_ep_map[res["episode_number"]] = res
             
+            # 每完成一集分镜,立即持久化并触发增量同步
+            temp_eps = sorted(updated_ep_map.values(), key=lambda x: x["episode_number"])
+            session_data.setdefault("artifacts", {})["storyboard"] = {
+                "session_id": sid, 
+                "episodes": temp_eps, 
+                "created_at": datetime.now().isoformat()
+            }
+            with open(session_file, "w", encoding="utf-8") as f:
+                json.dump(session_data, f, indent=2, ensure_ascii=False)
+            
+            # 报告带有 asset_complete 的进度,强制编排器刷新前端数据
+            self._report_progress("分镜设计", f"集数 {res['episode_number']} 分镜已生成", 50, {"asset_complete": True})
+
         final_all_episodes = sorted(updated_ep_map.values(), key=lambda x: x["episode_number"])
         
         # 核心:将结果持久化到 artifacts.storyboard
@@ -258,10 +277,6 @@
             "created_at": datetime.now().isoformat()
         }
         
-        # 更新会话状态
-        if "storyboard" not in session_data.get("stages_completed", []):
-            session_data.setdefault("stages_completed", []).append("storyboard")
-        session_data["status"] = "stage_completed"
         session_data["updated_at"] = datetime.now().timestamp()
 
         with open(session_file, "w", encoding="utf-8") as f: 
diff --git a/aigc-director/aigc-claw/backend/core/agents/video_agent.py b/aigc-director/aigc-claw/backend/core/agents/video_agent.py
index af9b10e..33b453e 100644
--- a/aigc-director/aigc-claw/backend/core/agents/video_agent.py
+++ b/aigc-director/aigc-claw/backend/core/agents/video_agent.py
@@ -378,6 +378,13 @@
             with ThreadPoolExecutor(max_workers=concurrency) as executor:
                 futs = {}
                 for seg_id, prompt, img_path, dur in tasks:
+                    # 提交前立即发送正在运行的状态,让前端 UI 更新
+                    self._report_progress("视频生成", f"启动生成: {seg_id}", 5, data={
+                        "asset_complete": {
+                            "type": "clips", "id": seg_id,
+                            "status": "running"
+                        }
+                    })
                     fut = executor.submit(
                         self._generate_one, sid, seg_id, prompt,
                         img_path, video_model, dur,
diff --git a/aigc-director/aigc-claw/backend/core/agents/video_agent.py.bak b/aigc-director/aigc-claw/backend/core/agents/video_agent.py.bak
deleted file mode 100644
index 9c127a7..0000000
--- a/aigc-director/aigc-claw/backend/core/agents/video_agent.py.bak
+++ /dev/null
@@ -1,626 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-阶段5: 视频生成智能体
-分镜参考图 → 各分镜视频片段
-- 视频提示词使用阶段3的原始分镜剧情描述(plot),而非视觉描述或首帧图像提示词
-- 参考图使用用户在阶段4选择的版本,而非第一版
-- 支持逐项实时预览、重新生成、多版本管理
-"""
-
-import os
-import re
-import glob
-import json
-import asyncio
-import logging
-from typing import Any, Optional, Dict, List
-from concurrent.futures import ThreadPoolExecutor, as_completed
-
-from .base_agent import AgentInterface
-
-logger = logging.getLogger(__name__)
-
-
-class VideoDirectorAgent(AgentInterface):
-    """视频生成:分镜参考图(阶段4用户选择) + 分镜剧情描述(阶段3 plot) → 视频片段"""
-
-    def __init__(self):
-        super().__init__(name="VideoDirector")
-
-    # ─── 版本管理 ───
-
-    @staticmethod
-    def _video_base(sid: str) -> str:
-        return os.path.join('code/result/video', str(sid))
-
-    def _list_versions(self, sid: str, shot_id: str) -> List[str]:
-        """列出某个分镜视频的所有历史版本"""
-        video_dir = self._video_base(sid)
-        pattern = os.path.join(video_dir, f"{shot_id}*.mp4")
-        files = [f for f in sorted(glob.glob(pattern), key=os.path.getmtime)
-                 if not f.endswith('_final.mp4')]
-        return files
-
-    def _next_version_path(self, sid: str, shot_id: str) -> str:
-        """获取下一个版本路径"""
-        video_dir = self._video_base(sid)
-        os.makedirs(video_dir, exist_ok=True)
-
-        existing = self._list_versions(sid, shot_id)
-        if not existing:
-            return os.path.join(video_dir, f"{shot_id}.mp4")
-
-        max_v = 1
-        for fp in existing:
-            bn = os.path.splitext(os.path.basename(fp))[0]
-            m = re.search(r'_v(\d+)$', bn)
-            if m:
-                max_v = max(max_v, int(m.group(1)))
-
-        return os.path.join(video_dir, f"{shot_id}_v{max_v + 1}.mp4")
-
-    # ─── 视频生成 ───
-
-    def _generate_one(self, sid: str, shot_id: str, prompt: str,
-                      img_path: str, video_model: str,
-                      duration: int = 5, sound: str = "",
-                      shot_type: str = "multi",
-                      video_ratio: str = "16:9") -> tuple:
-        """生成单个分镜视频,返回 (shot_id, path_or_None)"""
-        # 取消时直接跳过,不抛异常,以保留已生成的部分结果
-        if self.cancellation_check and self.cancellation_check():
-            logger.info(f"VideoDirectorAgent: {shot_id} 跳过(用户取消)")
-            return shot_id, None
-
-        if not os.path.exists(img_path):
-            logger.warning(f"Image missing for {shot_id}: {img_path}")
-            return shot_id, None
-
-        save_path = self._next_version_path(sid, shot_id)
-        try:
-            from tool.video_client import VideoClient
-            client = VideoClient()
-            client.generate_video(
-                prompt=prompt,
-                image_path=img_path,
-                save_path=save_path,
-                model=video_model,
-                duration=duration,
-                sound=sound,
-                shot_type=shot_type,
-                video_ratio=video_ratio,
-            )
-            return shot_id, save_path
-        except Exception as e:
-            logger.error(f"Video gen failed for {shot_id}: {e}")
-            if os.path.exists(save_path):
-                try:
-                    os.remove(save_path)
-                except Exception:
-                    pass
-        return shot_id, None
-
-    # ─── 排序 ───
-
-    @staticmethod
-    def _sort_shot_keys(keys: list) -> list:
-        """对 shot_id 排序: shot_001_01, shot_001_02, shot_002_01, ..."""
-        def sort_key(k):
-            nums = re.findall(r'(\d+)', k)
-            return tuple(int(n) for n in nums) if nums else (0,)
-        return sorted(keys, key=sort_key)
-
-    # ─── 预览 / Payload 构建 ───
-
-    @staticmethod
-    def _shot_display_name(shot_id: str) -> str:
-        """shot_001_02 → 场景1-镜头2"""
-        nums = re.findall(r'(\d+)', shot_id)
-        if len(nums) >= 2:
-            return f"场景{int(nums[0])}-镜头{int(nums[1])}"
-        elif len(nums) == 1:
-            return f"场景{int(nums[0])}"
-        return shot_id
-
-    def _build_preview(self, sid: str, shot_keys: list, s2i: dict) -> list:
-        """构建视频片段预览列表"""
-        preview = []
-        for idx, shot_id in enumerate(shot_keys, 1):
-            versions = self._list_versions(sid, shot_id)
-            entry = s2i.get(shot_id, {})
-            desc = entry.get('plot', '') or entry.get('video_prompt', '') or entry.get('prompt', '')
-            preview.append({
-                "id": shot_id,
-                "name": self._shot_display_name(shot_id),
-                "index": idx,
-                "description": desc,
-                "duration": entry.get('duration', 5),
-                "selected": versions[-1] if versions else "",
-                "versions": versions,
-                "status": "done" if versions else "pending",
-            })
-        return preview
-
-    def _build_payload(self, sid: str, shot_keys: list, s2i: dict, clip_descriptions: dict = None) -> dict:
-        """构建最终 payload
-
-        Args:
-            clip_descriptions: 用户修改的提示词,优先使用
-        """
-        clips = []
-        for idx, shot_id in enumerate(shot_keys, 1):
-            versions = self._list_versions(sid, shot_id)
-            entry = s2i.get(shot_id, {})
-            # 优先使用用户修改的描述,否则用 scene2image 中的原始描述
-            if clip_descriptions and shot_id in clip_descriptions:
-                desc = clip_descriptions[shot_id]
-            else:
-                desc = entry.get('plot', '') or entry.get('video_prompt', '') or entry.get('prompt', '')
-            clips.append({
-                "id": shot_id,
-                "name": self._shot_display_name(shot_id),
-                "index": idx,
-                "description": desc,
-                "duration": entry.get('duration', 5),
-                "selected": versions[-1] if versions else "",
-                "versions": versions,
-                "status": "done" if versions else "failed",
-            })
-        return {
-            "payload": {
-                "session_id": sid,
-                "clips": clips,
-            },
-            "stage_completed": True,
-        }
-
-    # ─── 视频提示词前缀/后缀配置 ───
-
-    # 尝试从模板文件加载前缀/后缀,失败则使用默认值
-    _VIDEO_PROMPT_PREFIX = None
-    _VIDEO_PROMPT_SUFFIX = None
-
-    @classmethod
-    def _load_video_enhance_prompt(cls) -> tuple:
-        """加载视频提示词优化模板"""
-        if cls._VIDEO_PROMPT_PREFIX is not None:
-            return cls._VIDEO_PROMPT_PREFIX, cls._VIDEO_PROMPT_SUFFIX
-
-        try:
-            from prompts.loader import PROMPTS_DIR
-            import os
-            enhance_file = os.path.join(PROMPTS_DIR, 'video', 'enhance.txt')
-            if os.path.exists(enhance_file):
-                with open(enhance_file, 'r', encoding='utf-8') as f:
-                    content = f.read()
-
-                prefix = ""
-                suffix = ""
-                current_section = None
-
-                for line in content.split('\n'):
-                    line = line.strip()
-                    if not line or line.startswith('#'):
-                        continue
-                    if line == '[prefix]':
-                        current_section = 'prefix'
-                    elif line == '[suffix]':
-                        current_section = 'suffix'
-                    elif line.startswith('[') and line.endswith(']'):
-                        # 遇到新的 section(如 [style_keywords]),停止解析
-                        current_section = None
-                    elif current_section == 'prefix':
-                        prefix += line + " "
-                    elif current_section == 'suffix':
-                        suffix += " " + line
-
-                cls._VIDEO_PROMPT_PREFIX = prefix.strip()
-                cls._VIDEO_PROMPT_SUFFIX = suffix.strip()
-                logger.info(f"Loaded video enhance prompt from file: prefix={len(cls._VIDEO_PROMPT_PREFIX)} chars, suffix={len(cls._VIDEO_PROMPT_SUFFIX)} chars")
-                return cls._VIDEO_PROMPT_PREFIX, cls._VIDEO_PROMPT_SUFFIX
-        except Exception as e:
-            logger.warning(f"Failed to load video enhance prompt: {e}")
-
-        # 默认值
-        cls._VIDEO_PROMPT_PREFIX = (
-            "high quality, detailed, cinematic footage, smooth motion, natural movement, "
-        )
-        cls._VIDEO_PROMPT_SUFFIX = (
-            ", realistic, no blur, no distortion, professional lighting, film grain"
-        )
-        return cls._VIDEO_PROMPT_PREFIX, cls._VIDEO_PROMPT_SUFFIX
-
-    # 视频API字符限制(可灵2500,万象也类似)
-    MAX_PROMPT_LENGTH = 2500
-
-    # ─── 风格关键词映射 ───
-    # 根据项目风格添加对应的视觉描述词
-
-    STYLE_VIDEO_KEYWORDS = {
-        # 动漫/动画风格
-        "anime": "anime style, animated, cel-shaded, vibrant colors, manga aesthetic, ",
-        "cartoon": "cartoon style, animated, colorful, fun, children's book illustration, ",
-        # 写实风格
-        "realistic": "photorealistic, realistic, natural lighting, detailed textures, cinema photography, ",
-        "photorealistic": "photorealistic, realistic, natural lighting, detailed textures, cinema photography, ",
-        # 3D 迪士尼风格
-        "3d-disney": "3D animation, Disney style, pixar, CGI, smooth textures, computer generated, ",
-        "3d": "3D animation, CGI, computer generated, smooth textures, digital cinema, ",
-        # 油画风格
-        "oil-painting": "oil painting style, impasto, classical art, painterly, rich brushstrokes, ",
-        "watercolor": "watercolor style, delicate, soft colors, artistic, flowing, ",
-        # 漫画风格
-        "comic-book": "comic book style, vibrant, bold outlines, pop art, graphic novel, ",
-        # 赛博朋克
-        "cyberpunk": "cyberpunk, neon lights, futuristic, dark atmosphere, sci-fi, ",
-        # 中国风
-        "chinese-ink": "Chinese ink painting style, traditional, minimalist, brush strokes, oriental art, ",
-        "ink": "Chinese ink painting style, traditional, minimalist, brush strokes, oriental art, ",
-    }
-
-    def _get_style_keywords(self, sid: str) -> str:
-        """获取项目风格对应的视频关键词"""
-        try:
-            from config import settings
-            result_file = os.path.join(settings.RESULT_DIR, 'script', f'script_{sid}.json')
-            if os.path.exists(result_file):
-                with open(result_file, 'r', encoding='utf-8') as f:
-                    data = json.load(f)
-                session_data = data.get(str(sid), {})
-                style = session_data.get('overall_style', '').lower().strip()
-                if style and style in self.STYLE_VIDEO_KEYWORDS:
-                    logger.info(f"Using style keywords for video: {style}")
-                    return self.STYLE_VIDEO_KEYWORDS[style]
-        except Exception as e:
-            logger.debug(f"Could not get style for video prompt: {e}")
-        return ""
-
-    # ─── 辅助:获取分镜的视频提示词和参考图路径 ───
-
-    def _enhance_video_prompt(self, base_prompt: str, sid: str = None) -> str:
-        """
-        增强视频提示词:添加前缀后缀优化生成效果
-        不截断,发送完整提示词给API
-        """
-        if not base_prompt:
-            return base_prompt
-
-        prefix, suffix = self._load_video_enhance_prompt()
-        base_lower = base_prompt.lower().strip()
-
-        # 获取风格关键词
-        style_keywords = ""
-        if sid:
-            style_keywords = self._get_style_keywords(sid)
-
-        # 获取对话语言要求
-        dialog_language = ""
-        if sid:
-            from config import settings
-            import os
-            script_file = os.path.join(settings.RESULT_DIR, 'script', f'script_{sid}.json')
-            if os.path.exists(script_file):
-                import json
-                with open(script_file, 'r', encoding='utf-8') as f:
-                    data = json.load(f)
-                    script_data = data.get(str(sid), {})
-                    # title 可能在 script_json 子对象中
-                    title = script_data.get('title') or script_data.get('script_json', {}).get('title', '')
-                    # 判断语言:检查标题是否包含中文字符
-                    is_zh = any('\u4e00' <= c <= '\u9fff' for c in title)
-                    if is_zh:
-                        dialog_language = "注意:人物对话必须使用中文,不要使用英文。"
-                    else:
-                        dialog_language = "Note: Character dialogues must be in English."
-
-        # 构建增强后的提示词
-        # 检查是否已包含前缀关键词
-        has_prefix = any(kw in base_lower for kw in ["high quality", "cinematic", "smooth motion", "anime", "photorealistic"])
-        # 检查是否已包含后缀关键词
-        has_suffix = any(kw in base_lower for kw in ["film grain", "realistic", "professional lighting", "masterpiece"])
-
-        enhanced = base_prompt.strip()
-
-        # 添加对话语言要求
-        if dialog_language:
-            enhanced = enhanced + " " + dialog_language
-
-        # 添加风格关键词(前缀之前)
-        if style_keywords:
-            enhanced = style_keywords + enhanced
-
-        if prefix and not has_prefix:
-            enhanced = prefix + enhanced
-
-        if suffix and not has_suffix:
-            enhanced = enhanced + suffix
-
-        logger.info(f"Video prompt enhanced: {len(base_prompt)} -> {len(enhanced)} chars")
-        # 不截断,发送完整提示词
-        return enhanced
-
-    def _get_shot_prompt(self, entry: dict, enhance: bool = True, sid: str = None, shot_id: str = None, clip_descriptions: dict = None) -> str:
-        """获取视频提示词:优先用用户修改的提示词,其次用 plot(剧情描述),兼容旧数据回退到 video_prompt"""
-        # 优先使用用户修改的提示词
-        if not shot_id:
-            shot_id = entry.get('shot_id') or entry.get('id', '')
-        if clip_descriptions and shot_id and clip_descriptions.get(shot_id):
-            base_prompt = clip_descriptions[shot_id]
-        else:
-            base_prompt = entry.get('plot', '') or entry.get('video_prompt', '') or entry.get('prompt', '')
-        if enhance:
-            return self._enhance_video_prompt(base_prompt, sid)
-        return base_prompt
-
-    def _get_shot_image(self, sid: str, shot_id: str, entry: dict,
-                        selected_images: dict) -> str:
-        """获取参考图路径:优先用前端传入的用户选择,再用 scene2image 的 local_path,
-        最后回退到扫描磁盘最新版本"""
-        # 1. 前端传入的用户选择(stage 4 确认时携带)
-        if selected_images.get(shot_id):
-            path = selected_images[shot_id]
-            if os.path.exists(path):
-                return path
-            logger.warning(f"selected_images path missing for {shot_id}: {path}")
-
-        # 2. scene2image 中的 local_path
-        local_path = entry.get('local_path', '')
-        if local_path and os.path.exists(local_path):
-            return local_path
-
-        # 3. 回退:扫描磁盘,使用最新版本
-        from core.agents.reference_agent import ReferenceGeneratorAgent
-        versions = ReferenceGeneratorAgent._list_versions_static(sid, shot_id)
-        if versions:
-            logger.info(f"Fallback to latest version for {shot_id}: {versions[-1]}")
-            return versions[-1]
-
-        # 4. 最终回退:默认路径
-        return os.path.join('code/result/image', str(sid), 'Scenes', f"{shot_id}.jpg")
-
-    # ─── 核心流程 ───
-
-    async def process(self, input_data: Any, intervention: Optional[Dict] = None) -> Dict:
-        from config import settings
-        
-        # 从 session.json 补齐缺失的参数(关键修复:防止前端漏传导致的默认值回退)
-        input_data = self._merge_session_params(input_data)
-
-        sid = input_data["session_id"]
-        video_model = input_data.get("video_model", "") or settings.VIDEO_MODEL
-        # 根据 enable_concurrency 决定并发数
-        enable_concurrency = input_data.get("enable_concurrency", True)
-        from config_model import get_max_concurrency
-        concurrency = get_max_concurrency(video_model, enable_concurrency)
-        selected_images = input_data.get("selected_images", {})
-        # 优先使用 input_data 中已有的 clips(包含用户修改的 description)
-        existing_clips = input_data.get("clips", [])
-        clip_descriptions = {c['id']: c['description'] for c in existing_clips if c.get('id') and c.get('description')}
-        clip_durations = {c['id']: c.get('duration', 10) for c in existing_clips if c.get('id')}
-        
-        video_sound = input_data.get("video_sound", "on")
-        video_shot_type = input_data.get("video_shot_type", "multi")
-        video_ratio = input_data.get("video_ratio", "16:9")
-        result_file = os.path.join(settings.RESULT_DIR, 'script', f'script_{sid}.json')
-
-        # 读取数据
-        with open(result_file, 'r', encoding='utf-8') as f:
-            results = json.load(f)
-        story_data = results[str(sid)]
-
-        s2i = story_data.get('scene2image', {})
-
-        # 1. 如果 input_data 传了 clips,则优先使用 input_data 中的结构
-        # 即使 scene2image 还没写回,也能根据 input_data 生成
-        if existing_clips:
-            logger.info(f"Using clips from input_data, count: {len(existing_clips)}")
-            # 补全 s2i 中可能缺失的项(例如新分镜)
-            for clip in existing_clips:
-                cid = clip['id']
-                if cid not in s2i:
-                    s2i[cid] = {
-                        "plot": clip.get('description', ''),
-                        "duration": clip.get('duration', 10),
-                    }
-                else:
-                    # 更新已有项的时长和描述(以 input_data 为准)
-                    if cid in clip_descriptions:
-                        s2i[cid]['plot'] = clip_descriptions[cid]
-                    if cid in clip_durations:
-                        s2i[cid]['duration'] = clip_durations[cid]
-
-        # 从 storyboard 获取时长数据(用于兜底更新)
-        storyboard = story_data.get('storyboard', {})
-        storyboard_shots_list = storyboard.get('shots', [])
-        shot_duration_map = {s.get('shot_id'): s.get('duration', 10) for s in storyboard_shots_list if s.get('shot_id')}
-
-        # 同步 scene2image 中的时长
-        for shot_id in s2i:
-            if shot_id in shot_duration_map:
-                s2i[shot_id]['duration'] = shot_duration_map[shot_id]
-
-        logger.info(f"VideoDirectorAgent: duration sync from storyboard: {list(shot_duration_map.keys())}")
-
-        # 兼容 shot_xxx_xx 和旧 Scene_x 格式
-        shot_keys = self._sort_shot_keys(list(s2i.keys()))
-        total = len(shot_keys)
-
-        logger.info(f"VideoDirectorAgent: total shots in scene2image = {total}, shot_keys = {shot_keys}")
-
-        if not shot_keys:
-            raise Exception("未找到场景图数据(scene2image),请先完成阶段4")
-
-        # ═══ 介入:重新生成指定片段 ═══
-        if intervention:
-            regen_clips = intervention.get("regenerate_clips", [])
-
-            if regen_clips:
-                self._report_progress("视频生成", "重新生成中...", 10)
-
-                def regen_run():
-                    regen_total = len(regen_clips)
-                    done = 0
-                    with ThreadPoolExecutor(max_workers=concurrency) as executor:
-                        futs = {}
-                        for shot_id in regen_clips:
-                            entry = s2i.get(shot_id, {})
-                            prompt = self._get_shot_prompt(entry, sid=sid, shot_id=shot_id, clip_descriptions=clip_descriptions)
-                            img_path = self._get_shot_image(sid, shot_id, entry, selected_images)
-                            shot_duration = entry.get('duration', 5)
-                            fut = executor.submit(
-                                self._generate_one, sid, shot_id, prompt,
-                                img_path, video_model, shot_duration,
-                                sound_param, video_shot_type, video_ratio
-                            )
-                            futs[fut] = shot_id
-                        for fut in as_completed(futs):
-                            shot_id_done = futs[fut]
-                            try:
-                                _, result_path = fut.result()
-                            except Exception as e:
-                                logger.error(f"Regen future error for {shot_id_done}: {e}")
-                                result_path = None
-                            done += 1
-                            pct = 10 + int(85 * done / max(regen_total, 1))
-                            if result_path:
-                                versions = self._list_versions(sid, shot_id_done)
-                                self._report_progress("视频生成", f"完成: {shot_id_done}", pct, data={
-                                    "asset_complete": {
-                                        "type": "clips", "id": shot_id_done,
-                                        "status": "done",
-                                        "selected": result_path,
-                                        "versions": versions,
-                                    }
-                                })
-                            else:
-                                self._report_progress("视频生成", f"失败: {shot_id_done}", pct, data={
-                                    "asset_complete": {
-                                        "type": "clips", "id": shot_id_done,
-                                        "status": "failed",
-                                        "selected": "", "versions": [],
-                                    }
-                                })
-                            # 检查取消:停止等待剩余任务
-                            if self.cancellation_check and self.cancellation_check():
-                                logger.info("VideoDirectorAgent: 用户取消重新生成,停止等待剩余任务")
-                                for f in futs:
-                                    if not f.done():
-                                        f.cancel()
-                                break
-
-                loop = asyncio.get_running_loop()
-                await loop.run_in_executor(None, regen_run)
-
-            self._report_progress("视频生成", "完成", 100)
-            return self._build_payload(sid, shot_keys, s2i, clip_descriptions)
-
-        # ═══ 正常流程:全量生成 ═══
-        self._report_progress("视频生成", "加载场景数据...", 5)
-
-        # 发送预览列表
-        preview = self._build_preview(sid, shot_keys, s2i)
-        self._report_progress("视频生成", "加载视频列表", 8, data={"assets_preview": {"clips": preview}})
-
-        def run():
-            # 筛选需要生成的(跳过已有的)
-            tasks = []
-            for shot_id in shot_keys:
-                existing = self._list_versions(sid, shot_id)
-                if existing:
-                    continue
-                entry = s2i.get(shot_id, {})
-                prompt = self._get_shot_prompt(entry, sid=sid, shot_id=shot_id, clip_descriptions=clip_descriptions)
-                img_path = self._get_shot_image(sid, shot_id, entry, selected_images)
-                shot_duration = entry.get('duration', 5)
-                tasks.append((shot_id, prompt, img_path, shot_duration))
-
-            if not tasks:
-                self._report_progress("视频生成", "所有视频已存在", 95)
-                return
-
-            gen_total = len(tasks)
-            done = 0
-
-            cancelled = False
-            with ThreadPoolExecutor(max_workers=concurrency) as executor:
-                futs = {}
-                for shot_id, prompt, img_path, shot_duration in tasks:
-                    fut = executor.submit(
-                        self._generate_one, sid, shot_id, prompt,
-                        img_path, video_model, shot_duration,
-                        sound_param, video_shot_type, video_ratio
-                    )
-                    futs[fut] = shot_id
-                for fut in as_completed(futs):
-                    shot_id_done = futs[fut]
-                    try:
-                        _, result_path = fut.result()
-                    except Exception as e:
-                        logger.error(f"Video future error for {shot_id_done}: {e}")
-                        result_path = None
-                    done += 1
-                    pct = 10 + int(85 * done / max(gen_total, 1))
-                    if result_path:
-                        versions = self._list_versions(sid, shot_id_done)
-                        self._report_progress("视频生成", f"完成: {shot_id_done}", pct, data={
-                            "asset_complete": {
-                                "type": "clips", "id": shot_id_done,
-                                "status": "done",
-                                "selected": result_path,
-                                "versions": versions,
-                            }
-                        })
-                    else:
-                        self._report_progress("视频生成", f"失败: {shot_id_done}", pct, data={
-                            "asset_complete": {
-                                "type": "clips", "id": shot_id_done,
-                                "status": "failed",
-                                "selected": "", "versions": [],
-                            }
-                        })
-                    # 检查取消:停止等待剩余任务
-                    if self.cancellation_check and self.cancellation_check():
-                        logger.info("VideoDirectorAgent: 用户取消,停止等待剩余任务")
-                        for f in futs:
-                            if not f.done():
-                                f.cancel()
-                        cancelled = True
-                        break
-
-            if cancelled:
-                self._report_progress("视频生成", "已取消(保留已完成片段)", 96)
-            else:
-                self._report_progress("视频生成", "保存结果...", 96)
-
-            # 写回结果文件
-            with open(result_file, 'r', encoding='utf-8') as f:
-                res = json.load(f)
-            i2v_data = {}
-            for shot_id in shot_keys:
-                versions = self._list_versions(sid, shot_id)
-                entry = s2i.get(shot_id, {})
-                if versions:
-                    i2v_data[shot_id] = {
-                        "video_prompt": self._get_shot_prompt(entry, sid=sid, shot_id=shot_id, clip_descriptions=clip_descriptions),
-                        "input_path": self._get_shot_image(sid, shot_id, entry, selected_images),
-                        "output_path": versions[-1],
-                        "duration": entry.get('duration', 10),
-                        "status": "done",
-                    }
-            res[str(sid)]['image2video'] = i2v_data
-            with open(result_file, 'w', encoding='utf-8') as f:
-                json.dump(res, f, indent=4, ensure_ascii=False)
-
-        loop = asyncio.get_running_loop()
-        try:
-            await loop.run_in_executor(None, run)
-        except Exception as e:
-            # 即使异常也保留已完成的部分结果
-            if "cancel" in str(e).lower():
-                logger.info("VideoDirectorAgent: 用户取消,返回已完成的部分结果")
-                self._report_progress("视频生成", "已取消(保留已完成片段)", 100)
-                return self._build_payload(sid, shot_keys, s2i, clip_descriptions)
-            raise
-
-        self._report_progress("视频生成", "完成", 100)
-        return self._build_payload(sid, shot_keys, s2i, clip_descriptions)
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/core/orchestrator.py b/aigc-director/aigc-claw/backend/core/orchestrator.py
index 111d815..0d36aeb 100644
--- a/aigc-director/aigc-claw/backend/core/orchestrator.py
+++ b/aigc-director/aigc-claw/backend/core/orchestrator.py
@@ -1,4 +1,4 @@
-# -*- coding: utf-8 -*-
+# -*- coding: utf-8 -*-
 """
 核心编排器 / 工作流引擎
 管理六阶段状态机,协调各智能体执行,支持用户在任意阶段介入
@@ -35,7 +35,7 @@
     REFERENCE_GENERATION = "reference_generation"
     VIDEO_GENERATION = "video_generation"
     POST_PRODUCTION = "post_production"
-    COMPLETED = "session_completed"
+    COMPLETED = "completed"
 
 
 STAGE_ORDER = [
@@ -52,19 +52,20 @@
     """工作流状态"""
 
     # 状态说明:
-    # - idle: 新建会话,还没有任何数据,也没有在运行
+    # - pending: 新建会话,还没有任何数据,也没有在运行
     # - running: 会话正在运行
-    # - waiting_in_stage: 会话在某一阶段内等待用户介入(如选择角色、选择图片等)
-    # - stage_completed: 会话完成了某一阶段,等待用户确定开始下一阶段
-    # - session_completed: 会话全部完成
+    # - waiting: 会话在某一阶段内等待用户介入(如选择角色、选择图片等)
+    # - completed: 会话完成了某一阶段,等待用户确定开始下一阶段
+    # - completed: 会话全部完成
     # - stopped: 用户手动停止
     # - error: 执行中遇到错误
 
     def __init__(self, session_id: str):
         self.session_id = session_id
         self.current_stage: WorkflowStage = WorkflowStage.INIT
-        self.status: str = "idle"
-        self.stages_completed: List[str] = []  # 已完成的阶段列表
+        self.status: Dict[str, str] = {
+            stage.value: "pending" for stage in WorkflowStage if stage != WorkflowStage.INIT and stage != WorkflowStage.COMPLETED
+        }
         self.artifacts: Dict[str, Any] = {}
         self.error: Optional[str] = None
         self.started_at: Optional[datetime] = None
@@ -77,7 +78,6 @@
             "current_stage": self.current_stage.value,
             "status": self.status,
             "error": self.error,
-            "stages_completed": self.stages_completed,
             "artifacts": self.artifacts,
             "meta": self.meta,
             "updated_at": self.updated_at,
@@ -125,10 +125,24 @@
 
                 # 从磁盘数据恢复 WorkflowState
                 state = WorkflowState(session_id=session_id)
-                state.status = data.get('status', 'idle')
+                
                 stage_str = data.get('current_stage')
                 state.current_stage = WorkflowStage(stage_str) if stage_str else WorkflowStage.INIT
-                state.stages_completed = data.get('stages_completed', [])
+                
+                loaded_status = data.get('status')
+                if isinstance(loaded_status, str):
+                    stages_completed = data.get('stages_completed', [])
+                    for stage in WorkflowStage:
+                        if stage != WorkflowStage.INIT and stage != WorkflowStage.COMPLETED:
+                            if stage.value in stages_completed:
+                                state.status[stage.value] = "completed"
+                            elif stage.value == state.current_stage.value:
+                                state.status[stage.value] = loaded_status
+                            else:
+                                state.status[stage.value] = "pending"
+                elif isinstance(loaded_status, dict):
+                    state.status = loaded_status
+
                 state.artifacts = data.get('artifacts', {})
                 state.meta = data.get('meta', {})
                 state.updated_at = data.get('updated_at', 0)
@@ -151,8 +165,8 @@
     def stop_session(self, session_id: str):
         self.get_stop_event(session_id).set()
         state = self.get_state(session_id)
-        if state and state.status == "running":
-            state.status = "stopped"
+        if state and state.status.get(state.current_stage.value) == "running":
+            state.status[state.current_stage.value] = "stopped"
             state.error = None  # 清除错误,因为是主动停止
             state.updated_at = datetime.now()
             self.save_session_to_disk(session_id)
@@ -237,6 +251,157 @@
                 story_art["episodes"] = existing_eps
                 state.artifacts[story_stage_key] = story_art
 
+        # 案例 2: 分镜生成或修改同步到第四、第五阶段 (Storyboard -> Ref/Video)
+        if stage == WorkflowStage.STORYBOARD:
+            episodes = payload.get("episodes", []) if isinstance(payload, dict) else payload
+            if not isinstance(episodes, list):
+                return
+                
+            all_sync_clips = []
+            for ep in episodes:
+                if not isinstance(ep, dict): continue
+                ep_n = ep.get("episode_number", 0)
+                for s_i, seg in enumerate(ep.get("segments", []), 1):
+                    if not isinstance(seg, dict): continue
+                    seg_id = seg.get("segment_id", f"seg_{ep_n:02d}_{s_i:02d}")
+                    
+                    # 汇总 segment 级别的描述和时长
+                    shots = seg.get("shots", [])
+                    desc_video = " ".join([sh.get("plot") or sh.get("content") or "" for sh in shots]).strip()
+                    desc_ref = " ".join([sh.get("visual_prompt") or sh.get("plot") or sh.get("content") or "" for sh in shots]).strip()
+                    total_dur = seg.get("total_duration") or sum([sh.get("duration", 0) for sh in shots]) or 10
+                    
+                    all_sync_clips.append({
+                        "segment_id": seg_id,
+                        "desc_video": desc_video,
+                        "desc_ref": desc_ref,
+                        "duration": total_dur,
+                        "episode": ep_n,
+                        "index": s_i,
+                        "name": f"第{ep_n}集-片段{s_i}"
+                    })
+            
+            if not all_sync_clips:
+                return
+
+            # (A) 同步到第四阶段 (参考图生成)
+            ref_stage_key = WorkflowStage.REFERENCE_GENERATION.value
+            ref_art = state.artifacts.get(ref_stage_key)
+            if not isinstance(ref_art, dict):
+                ref_art = {"scenes": [], "version": 1}
+            
+            existing_scenes = ref_art.get("scenes", [])
+            for c_info in all_sync_clips:
+                id = c_info["segment_id"]
+                idx = next((i for i, s in enumerate(existing_scenes) if s.get("id") == id), -1)
+                if idx == -1:
+                    existing_scenes.append({
+                        "id": id,
+                        "name": c_info["name"],
+                        "index": c_info["index"],
+                        "description": c_info["desc_ref"],
+                        "selected": "",
+                        "versions": [],
+                        "status": "pending",
+                        "episode": c_info["episode"]
+                    })
+                else:
+                    # 更新已有记录
+                    existing_scenes[idx]["description"] = c_info["desc_ref"]
+                    existing_scenes[idx]["episode"] = c_info["episode"]
+                    existing_scenes[idx]["index"] = c_info["index"]
+                    existing_scenes[idx]["name"] = c_info["name"]
+            
+            # 排序:确保片段显示顺序正确 (按 id 排序,例如 seg_01_01 < seg_07_01)
+            existing_scenes.sort(key=lambda x: x.get("id", ""))
+            ref_art["scenes"] = existing_scenes
+            state.artifacts[ref_stage_key] = ref_art
+
+            # (B) 同步到第五阶段 (视频生成)
+            video_stage_key = WorkflowStage.VIDEO_GENERATION.value
+            video_art = state.artifacts.get(video_stage_key)
+            if not isinstance(video_art, dict):
+                video_art = {"clips": [], "version": 1}
+            
+            existing_clips = video_art.get("clips", [])
+            for c_info in all_sync_clips:
+                id = c_info["segment_id"]
+                idx = next((i for i, c in enumerate(existing_clips) if c.get("id") == id), -1)
+                if idx == -1:
+                    existing_clips.append({
+                        "id": id,
+                        "name": c_info["name"],
+                        "index": c_info["index"],
+                        "description": c_info["desc_video"],
+                        "duration": c_info["duration"],
+                        "selected": "",
+                        "versions": [],
+                        "status": "pending",
+                        "episode": c_info["episode"]
+                    })
+                else:
+                    existing_clips[idx]["description"] = c_info["desc_video"]
+                    existing_clips[idx]["duration"] = c_info["duration"]
+                    existing_clips[idx]["episode"] = c_info["episode"]
+                    existing_clips[idx]["index"] = c_info["index"]
+                    existing_clips[idx]["name"] = c_info["name"]
+            
+            # 排序:确保片段显示顺序正确
+            existing_clips.sort(key=lambda x: x.get("id", ""))
+            video_art["clips"] = existing_clips
+            state.artifacts[video_stage_key] = video_art
+
+    def _recalculate_all_statuses(self, state: WorkflowState):
+        """
+        根据各阶段 artifacts 的数据完整性重新计算 status 字典。
+        逻辑:
+        - 如果 artifacts[stage] 不存在: pending
+        - 如果存在且包含核心列表(characters/scenes/clips等):
+            - 如果列表项存在 selected 为空的情况: waiting
+            - 如果列表项全部已选择(或不需要选择): completed
+        """
+        for stage in WorkflowStage:
+            if stage in [WorkflowStage.INIT, WorkflowStage.COMPLETED]:
+                continue
+            s_val = stage.value
+            # 如果当前阶段正在运行,不自动覆盖其为 completed/waiting (除非它目前是空)
+            current_s_status = state.status.get(s_val, "pending")
+            if current_s_status == "running" or current_s_status == "error":
+                continue
+
+            art = state.artifacts.get(s_val)
+            if not art or not isinstance(art, dict):
+                state.status[s_val] = "pending"
+                continue
+            
+            # 检查是否有待处理的“空数据占位”
+            has_pending = False
+            
+            if s_val == "character_design":
+                chars = art.get("characters", [])
+                sets = art.get("settings", [])
+                if any(not c.get("selected") for c in chars) or any(not s.get("selected") for s in sets):
+                    has_pending = True
+            elif s_val == "storyboard":
+                # 检查分镜阶段:如果存在剧集(episode)但其 segments 为空,视为 waiting
+                episodes = art.get("episodes", [])
+                if not episodes or any(not ep.get("segments") for ep in episodes):
+                    has_pending = True
+            elif s_val == "reference_generation":
+                scenes = art.get("scenes", [])
+                if not scenes or any(not s.get("selected") for s in scenes):
+                    has_pending = True
+            elif s_val == "video_generation":
+                clips = art.get("clips", [])
+                if not clips or any(not c.get("selected") for c in clips):
+                    has_pending = True
+            
+            if has_pending:
+                state.status[s_val] = "waiting"
+            else:
+                # 已经有数据且没有 pending 项,标记为完成
+                state.status[s_val] = "completed"
+
     async def execute_stage(self,
                             state: WorkflowState,
                             stage: WorkflowStage,
@@ -280,7 +445,7 @@
             agent.set_progress_callback(wrapped_progress_callback)
 
         state.current_stage = stage
-        state.status = "running"
+        state.status[stage.value] = "running"
         state.updated_at = datetime.now()
 
         try:
@@ -312,91 +477,19 @@
                 self._sync_artifacts_cross_stages(state, stage, payload)
                 state.artifacts[stage.value] = payload
 
-            # 只有在 storyboard 阶段明确有修改时才执行同步
-            if stage.value == "storyboard" and isinstance(intervention, dict) and "modified_storyboard" in intervention:
-                modified_shots = intervention["modified_storyboard"]
-                if isinstance(modified_shots, list):
-                    shot_durations = {s.get('shot_id'): s.get('duration', 10)
-                                    for s in modified_shots if s.get('shot_id')}
-                    shot_visual_prompts = {s.get('shot_id'): s.get('visual_prompt', '')
-                                         for s in modified_shots if s.get('shot_id')}
-                    shot_plots = {s.get('shot_id'): s.get('plot', '')
-                                for s in modified_shots if s.get('shot_id')}
-
-                    # 1. 同步 duration 到第五阶段 clips
-                    video_art = state.artifacts.get('video_generation', {})
-                    if isinstance(video_art, dict) and 'clips' in video_art:
-                        for clip in video_art['clips']:
-                            shot_id = clip.get('id')
-                            if shot_id in shot_durations:
-                                clip['duration'] = shot_durations[shot_id]
-                            if shot_id in shot_plots:
-                                clip['description'] = shot_plots[shot_id]
-
-                    # 2. 同步 visual_prompt 到第四阶段 scenes (description)
-                    ref_art = state.artifacts.get('reference_generation', {})
-                    if isinstance(ref_art, dict) and 'scenes' in ref_art:
-                        for scene in ref_art['scenes']:
-                            shot_id = scene.get('id')
-                            if shot_id in shot_visual_prompts:
-                                scene['description'] = shot_visual_prompts[shot_id]
-
-                    # 3. 新增分镜:同步到第四、第五阶段
-                    existing_shot_ids = {clip.get('id') for clip in video_art.get('clips', [])} if isinstance(video_art, dict) else set()
-                    existing_scene_ids = {scene.get('id') for scene in ref_art.get('scenes', [])} if isinstance(ref_art, dict) else set()
-
-                    for shot in modified_shots:
-                        shot_id = shot.get('shot_id')
-                        if not shot_id:
-                            continue
-                        # 新增到第五阶段
-                        if shot_id not in existing_shot_ids:
-                            if isinstance(video_art, dict):
-                                video_art.setdefault('clips', []).append({
-                                    'id': shot_id,
-                                    'name': f"镜头{shot_id.split('_')[-1]}",
-                                    'description': shot.get('plot', ''),
-                                    'duration': shot.get('duration', 10),
-                                    'selected': '',
-                                    'versions': [],
-                                    'status': 'pending'
-                                })
-                        # 新增到第四阶段
-                        if shot_id not in existing_scene_ids:
-                            if isinstance(ref_art, dict):
-                                ref_art.setdefault('scenes', []).append({
-                                    'id': shot_id,
-                                    'name': f"场景{shot_id.split('_')[-2]}",
-                                    'description': shot.get('visual_prompt', ''),
-                                    'selected': '',
-                                    'versions': [],
-                                    'status': 'pending'
-                                })
-
-                    logger.info(f"Synced stage 3 modifications: {len(shot_durations)} durations, {len(shot_visual_prompts)} prompts")
-
             # 调试日志
             logger.info(f"[execute_stage] stage={stage.value}, intervention={intervention is not None}, requires_intervention={result.get('requires_intervention')}, stage_completed={result.get('stage_completed')}")
 
-            # 状态转换逻辑:
-            # - stage_completed=True: 阶段已完成,等待用户确认进入下一阶段
-            # - requires_intervention=True: 阶段内需要用户介入(如选择图片等)
-            # - 其他(running):阶段正在执行中
-            if result.get("stage_completed"):
-                # 阶段真正完成,标记到已完成的列表
-                if stage.value not in state.stages_completed:
-                    state.stages_completed.append(stage.value)
-                # 如果是最后一个阶段,设置为 session_completed
-                if stage == WorkflowStage.POST_PRODUCTION:
-                    state.status = "session_completed"
-                else:
-                    state.status = "stage_completed"
+            # 重新计算所有阶段的状态(基于 artifacts 里的数据完整性)
+            self._recalculate_all_statuses(state)
+
+            # 如果 result 明确标记了完成且不是干预,则可能需要覆盖为 completed (除非 recalculate 认为是 waiting)
+            if result.get("stage_completed") and not result.get("requires_intervention"):
+                # 如果 recalculate 没把它设为 waiting,就设为 completed
+                if state.status.get(stage.value) != "waiting":
+                    state.status[stage.value] = "completed"
             elif result.get("requires_intervention"):
-                # 阶段内需要用户介入,等待用户选择
-                state.status = "waiting_in_stage"
-            else:
-                # 阶段正在执行中(中间步骤),保持 running
-                state.status = "running"
+                state.status[stage.value] = "waiting"
 
             state.updated_at = datetime.now()
             # 立即保存状态到磁盘,确保前端能获取到最新状态
@@ -404,9 +497,11 @@
             return result
 
         except Exception as e:
-            state.status = "error"
+            state.status[stage.value] = "error"
             state.error = str(e)
             state.updated_at = datetime.now()
+            # 确保保存错误状态
+            self.save_session_to_disk(state.session_id)
             raise
 
     async def handle_intervention(self,
@@ -420,51 +515,61 @@
         input_data = current_artifact if isinstance(current_artifact, dict) else {}
         input_data.update(modifications)
 
-        return await self.execute_stage(state, stage_enum, input_data, intervention=modifications)
+        res = await self.execute_stage(state, stage_enum, input_data, intervention=modifications)
+        # 处理完干预后再次校验状态
+        self._recalculate_all_statuses(state)
+        self.save_session_to_disk(session_id)
+        return res
 
     async def continue_workflow(self, session_id: str) -> Dict:
         state = self.sessions[session_id]
         logger.info(f"[continue_workflow] session={session_id}, current_stage={state.current_stage}, status={state.status}")
 
-        # 检查当前阶段是否已完成
-        current_stage_str = state.current_stage.value if hasattr(state.current_stage, 'value') else str(state.current_stage)
+        # 检查当前状态是否已完成
+        current_stage_str = state.current_stage.value if hasattr(state.current_stage, "value") else str(state.current_stage)
+
+        # 在继续之前,先重新扫描一次状态,确保最新的选择已被计入
+        self._recalculate_all_statuses(state)
 
         # 如果当前状态是 running,说明阶段还在执行中,不能继续
-        if state.status == "running":
+        if state.status.get(current_stage_str) == "running":
             return {
                 "status": "waiting",
                 "openclaw": f"当前阶段({current_stage_str})还在执行中,请等待完成后再调用 /continue。",
                 "message": f"当前阶段({current_stage_str})还在执行中,请等待完成后再调用 /continue。",
-                "current_status": state.status,
+                "current_status": "running",
             }
 
         # 状态转换逻辑:
-        # - waiting_in_stage 或 stage_completed: 用户确认后直接进入下一阶段
-        # 注意:只有当阶段真正完成(waiting_in_stage 或 stage_completed)时才允许继续
+        # - waiting 或 completed: 用户确认后直接进入下一阶段
+        # 如果是 waiting,可能需要阻止进入下一阶段,除非业务允许强制通过
+        # 这里我们遵循用户逻辑:如果有空数据,显示为 waiting,用户需要解决它才能真正 completed。
+        if state.status.get(current_stage_str) == "waiting":
+            # 如果是 waiting 状态,通常不应该自动跳到下一阶段
+            # 但如果用户点击了“继续”,可能是想补全或者强制进入
+            pass
+        # 注意:只有当阶段真正完成(waiting 或 completed)时才允许继续
 
-        if state.status == "waiting_in_stage" or state.status == "stage_completed":
-            # 用户确认后标记阶段完成
-            if current_stage_str not in state.stages_completed:
-                state.stages_completed.append(current_stage_str)
-
+        current_status = state.status.get(current_stage_str)
+        if current_status == "waiting" or current_status == "completed":
             # 直接进入下一阶段
-            state.status = "running"
+            state.status[current_stage_str] = "completed"
             next_stage = self._get_next_stage(state.current_stage)
 
             if not next_stage:
-                state.status = "session_completed"
+                state.status[current_stage_str] = "completed"
                 self.save_session_to_disk(state.session_id)
-                return {"status": "session_completed"}
+                return {"status": "completed", "session_id": state.session_id, "status_map": state.status}
 
             self.save_session_to_disk(state.session_id)
-            return {"status": "ready", "next_stage": next_stage.value}
+            return {"status": "ready", "next_stage": next_stage.value, "session_id": state.session_id, "status_map": state.status}
 
-        # 其他状态(如 idle, stopped, error, session_completed)不允许继续
+        # 其他状态(如 pending, stopped, error, completed)不允许继续
         return {
             "status": "error",
-            "openclaw": f"当前状态 {state.status} 不允许继续,请检查会话状态。",
+            "openclaw": f"当前状态 {current_status} 不允许继续,请检查会话状态。",
             "message": f"当前状态不允许继续",
-            "current_status": state.status,
+            "current_status": current_status,
         }
 
     # ──────────── 会话持久化 ────────────
@@ -497,7 +602,6 @@
         if state:
             data["current_stage"] = state.current_stage.value
             data["status"] = state.status
-            data["stages_completed"] = state.stages_completed
             # 这里的 state.artifacts 应该是已经经过 _sync_artifacts_cross_stages 处理的最新的内存对象
             data["artifacts"] = state.artifacts
             data["error"] = state.error
@@ -547,16 +651,27 @@
                     state.current_stage = WorkflowStage(data.get("current_stage", "init"))
                 except ValueError:
                     state.current_stage = WorkflowStage.INIT
-                # 旧版本兼容:状态名称转换
-                old_status = data.get("status", "idle")
-                if old_status == "waiting_intervention":
-                    state.status = "waiting_in_stage"
-                elif old_status == "completed":
-                    state.status = "session_completed"
-                else:
+                
+                # 旧版本兼容:状态名称转换及迁移
+                old_status = data.get("status", "pending")
+                if isinstance(old_status, str):
+                    if old_status == "waiting_intervention":
+                        old_status = "waiting"
+                    elif old_status == "completed":
+                        old_status = "completed"
+                    
+                    stages_completed = data.get("stages_completed", [])
+                    for stage in WorkflowStage:
+                        if stage != WorkflowStage.INIT and stage != WorkflowStage.COMPLETED:
+                            if stage.value in stages_completed:
+                                state.status[stage.value] = "completed"
+                            elif stage.value == state.current_stage.value:
+                                state.status[stage.value] = old_status
+                            else:
+                                state.status[stage.value] = "pending"
+                elif isinstance(old_status, dict):
                     state.status = old_status
 
-                state.stages_completed = data.get("stages_completed", [])
                 state.artifacts = data.get("artifacts", {})
                 state.error = data.get("error")
                 state.updated_at = data.get("updated_at", 0)
@@ -623,7 +738,7 @@
                     "idea": data.get("idea", ""),
                     "style": data.get("style", ""),
                     "date": data.get("updated_at", 0),
-                    "stages": data.get("stages_completed", []),
+                    "status": data.get("status", {}),
                 })
             except Exception:
                 continue
diff --git a/aigc-director/aigc-claw/backend/prompts/script/meta_extract_zh.txt b/aigc-director/aigc-claw/backend/prompts/script/meta_extract_zh.txt
index a1e5da2..138b27d 100644
--- a/aigc-director/aigc-claw/backend/prompts/script/meta_extract_zh.txt
+++ b/aigc-director/aigc-claw/backend/prompts/script/meta_extract_zh.txt
@@ -16,7 +16,7 @@
 
 **注意(严格遵守):**
 1. **输出格式**:必须且仅能输出一个纯净的 JSON 对象。严禁包含任何 Markdown 格式(如 ```json 代码块)、解释性文字、开场白或结尾。
-2. 提取所有在剧本中出现的、有台词或重要动作的【角色】(不仅仅是主角)。
+2. 提取所有在剧本中出现的、有台词或重要动作的【角色】(不仅仅是主角),但是注意不要提取群体角色(如:若干员工、一些顾客)。
 3. 提取所有在剧本中具体描述过的、不同地理位置的【场景】(不仅仅是概括性的)。
 4. 角色描述:
    - 采用“年龄+性别+发型/首饰+服装+体型+面部特征/神态”的概括性写法。
diff --git a/aigc-director/aigc-claw/backend/prompts/storyboard/continue_zh.txt b/aigc-director/aigc-claw/backend/prompts/storyboard/continue_zh.txt
deleted file mode 100644
index 74e44ab..0000000
--- a/aigc-director/aigc-claw/backend/prompts/storyboard/continue_zh.txt
+++ /dev/null
@@ -1,32 +0,0 @@
-你是一位专业的影视编剧。根据已有的剧情内容,续写接下来的故事情节。
-
-已有剧情信息:
-- 标题:{title}
-- 风格:{style}
-- 角色:{characters}
-- 场景位置:{settings}
-
-当前分镜列表:
-{existing_shots}
-
-请根据以上信息,续写1个新场景(包含多个分镜,总时长40-60秒)。
-
-要求:
-1. 新场景要承接上文剧情自然发展
-2. 分镜时长为 5、10 或 15 秒
-3. 包含4-8个分镜,总时长控制在40-60秒
-4. 每个分镜描述一个独立的画面段落
-5. plot 字段必须按时间顺序描述:角色动作、表情、对话(用引号标注)、背景音效
-6. visual_prompt 字段是适合AI图像生成的视觉描述,包含角色站位、姿态、表情、环境光线,色调、构图
-7. 保持{style}风格
-8. 用角色全名,不要用代词
-9. location 字段必须从上面给出的"场景位置"中选择一个,名称必须完全一致,不能有任何修改或添加
-
-请直接输出JSON数组(不要用```包裹),每个元素格式如下:
-[{{"shot_number":1,"duration":5,"characters":["角色名"],"location":"场景位置","plot":"按时间顺序描述: 角色动作、表情、对话、背景音效,50-100字","visual_prompt":"AI图像生成用的视觉描述,含站位、姿态、表情,光线、构图,80-120字"}}]
-
-注意:
-- duration只能是5、10、15三个值之一
-- 新场景的 scene_number 应该延续上一个场景的编号
-- 新场景应该延续当前幕(act)的内容,或者开启新一幕(如果故事需要)
-- 新场景中出现的人物、场景位置必须与上面给出的完全一致,禁止添加额外的人物或场景位置
diff --git a/aigc-director/aigc-claw/backend/prompts/storyboard/expand_zh.txt b/aigc-director/aigc-claw/backend/prompts/storyboard/expand_zh.txt
deleted file mode 100644
index c71735d..0000000
--- a/aigc-director/aigc-claw/backend/prompts/storyboard/expand_zh.txt
+++ /dev/null
@@ -1,41 +0,0 @@
-你是一位天才电影编剧。请注意,你当前处理的仅仅是【完整剧本】中的【一个独立场景】。
-你的任务是将这个初版的场景大纲,“扩写”为一段极具画面感、戏剧冲突和完整对话的详细剧本素材(Detailed Scene Script),不要越界去创作后续剧情。
-
----
-
-【要求】
-
-1. 扩写后的内容必须保持与原剧本《{title}》的整体风格《{style}》一致,目标只是丰富这一个特定场景。
-2. 戏剧性增强:通过具体的动作、神态、环境变化来体现角色的内心冲突。
-3. 角色完整性:必须使用角色全名。确保每个角色的对话都符合其性格设定。
-4. 本场景补充核心要素:
-   - 动作:描述角色在此次场景内的具体物理行为(如:他颤抖着手点燃了烟,火光映照出他深陷的眼窝)。
-   - 对话:为这一个场景构思符合该大纲发展的精彩台词。对话必须用引号标注。
-   - 内心独白:如果是单人镜头,务必通过自言自语或极度细腻的动作描写来展现其内心戏。
-   - 环境细节:描述当前环境中的光影、声音、氛围对剧情的影响。
-5. 长度要求:不少于 1000 字,确保内容足以支撑拆分为多个分镜。
-6. 禁止产出 JSON:请直接输出一段纯文本的、流式的剧本叙述。
-
----
-
-【完整剧本】
-
-{script}
-
-你只需要参考这个剧本,了解完整情节,然后用于接下来的【场景扩写】
-
----
-
-【场景扩写】
-
-本场景的内容是【完整剧本】中的一部分,你只需要专注于扩写这个场景的内容即可,不要越界去创作这个场景前后的剧情。
-
-出场角色:{characters}
-角色设定:{char_descriptions}
-
-背景位置:{location}
-背景设定:{setting_description}
-
-场景大纲:{plot}
-
-请扩写这个场景,注意输出的情节必须是发生在这个场景中的,只给出续写后的纯文本内容,不要包含其他文字。
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/storyboard/shot_zh.txt b/aigc-director/aigc-claw/backend/prompts/storyboard/shot_zh.txt
index 20754b9..344ba06 100644
--- a/aigc-director/aigc-claw/backend/prompts/storyboard/shot_zh.txt
+++ b/aigc-director/aigc-claw/backend/prompts/storyboard/shot_zh.txt
@@ -1,4 +1,4 @@
-你是一台专业的 JSON 生成器。请根据输入的集数描述,拆分为一系列极具视觉表现力的“拍摄片段”(Segments),并规划详细的“分镜列表”(Shots)。
+你是一台专业的拍摄片段设计师。请根据输入的集数描述,拆分为一系列极具视觉表现力的“拍摄片段”(Segments),并规划详细的“分镜列表”(Shots)。
 
 ### 核心任务
 剧本中每一行描述对应一个分镜。若干分镜组合成一个拍摄片段。
@@ -23,6 +23,7 @@
 ---
 
 【输出格式示例(仅返回此 JSON 数组)】
+
 [
   {{
     "segment_number": 1,
@@ -44,4 +45,6 @@
       }}
     ]
   }}
-]
\ No newline at end of file
+]
+
+注意,返回的json数组不要用 “```json” 包裹
diff --git a/aigc-director/aigc-claw/frontend/components/HomePage.tsx b/aigc-director/aigc-claw/frontend/components/HomePage.tsx
index 0682a18..a3f34c5 100644
--- a/aigc-director/aigc-claw/frontend/components/HomePage.tsx
+++ b/aigc-director/aigc-claw/frontend/components/HomePage.tsx
@@ -28,7 +28,7 @@
   style?: string;
   date: string;
   status: string;
-  stages?: string[];
+  stages?: Record<string, string>;
 }
 
 interface HomePageProps {
@@ -38,15 +38,18 @@
   history: HistoryItem[];
 }
 
-/* 根据 stages_completed 生成进度文本 */
-function stageProgressLabel(stages?: string[]): { text: string; color: string } {
-  if (!stages || stages.length === 0) return { text: '未开始', color: 'text-gray-400' };
-  if (stages.length >= STAGES.length) return { text: '已完成', color: 'text-green-600' };
-  // 显示最后完成的阶段名称
-  const lastStageId = stages[stages.length - 1];
+/* 根据 status 映射生成进度文本 */
+function stageProgressLabel(statusMap?: Record<string, string>): { text: string; color: string } {
+  const map = statusMap || {};
+  const completed = Object.keys(map).filter(k => ["completed", "session_completed"].includes(map[k]));
+  if (completed.length === 0) return { text: '未开始', color: 'text-gray-400' };
+  if (completed.length >= STAGES.length) return { text: '已完成', color: 'text-green-600' };
+  
+  // 对比 STAGES 获取最后一个已完成的
+  const lastStageId = STAGES.filter(s => completed.includes(s.id)).pop()?.id || completed[completed.length - 1];
   const stageDef = STAGES.find(s => s.id === lastStageId);
   const name = stageDef?.shortName || lastStageId;
-  return { text: `已完成: ${name} (${stages.length}/${STAGES.length})`, color: 'text-blue-600' };
+  return { text: `已完成: ${name} (${completed.length}/${STAGES.length})`, color: 'text-blue-600' };
 }
 
 export default function HomePage({ onStartProject, onResumeProject, onDeleteSession, history }: HomePageProps) {
@@ -468,7 +471,7 @@
                         <span className="text-[10px] text-gray-400">{item.date}</span>
                       </div>
                       <div className={`flex items-center gap-1 mt-1.5 text-[10px] font-medium ${progress.color}`}>
-                        {item.stages && item.stages.length >= STAGES.length ? (
+                        {item.stages && Object.keys(item.stages).filter(k => ["completed", "session_completed"].includes(item.stages![k])).length >= STAGES.length ? (
                           <CheckCircle className="w-3 h-3" />
                         ) : (
                           <span className="w-1.5 h-1.5 rounded-full bg-current flex-shrink-0" />
diff --git a/aigc-director/aigc-claw/frontend/components/TopBar.tsx b/aigc-director/aigc-claw/frontend/components/TopBar.tsx
index 39cb7bf..af270c2 100644
--- a/aigc-director/aigc-claw/frontend/components/TopBar.tsx
+++ b/aigc-director/aigc-claw/frontend/components/TopBar.tsx
@@ -1,4 +1,4 @@
-'use client';
+'use client';
 
 import React, { useState, useRef, useEffect } from 'react';
 import { CheckCircle, Circle, Loader, Edit3, AlertCircle, Square, Zap, Settings2, ChevronDown, Hexagon } from 'lucide-react';
@@ -48,7 +48,7 @@
   modelConfig?: ModelConfig;
   /** 模型配置变更 */
   onModelConfigChange?: (config: ModelConfig) => void;
-  /** 项目状态(如 running, waiting_in_stage, stage_completed, session_completed, idle, error 等) */
+  /** 项目状态(如 running, waiting, completed, completed, idle, error 等) */
   projectStatus?: string;
 }
 
@@ -330,23 +330,22 @@
             className={clsx(
               'px-2 py-1 rounded-lg text-xs font-medium flex items-center gap-1',
               projectStatus === 'running' && 'bg-blue-50 text-blue-700',
-              projectStatus === 'waiting_in_stage' && 'bg-amber-50 text-amber-700',
-              projectStatus === 'stage_completed' && 'bg-green-50 text-green-700',
-              projectStatus === 'idle' && 'bg-gray-50 text-gray-600',
+              projectStatus === 'waiting' && 'bg-amber-50 text-amber-700',
+              projectStatus === 'completed' && 'bg-green-50 text-green-700',
+              projectStatus === 'pending' && 'bg-gray-50 text-gray-600',
               projectStatus === 'error' && 'bg-red-50 text-red-700',
               projectStatus === 'stopped' && 'bg-orange-50 text-orange-700'
             )}
             title="项目状态"
           >
             {projectStatus === 'running' && <Loader className="w-3 h-3 animate-spin" />}
-            {projectStatus === 'waiting_in_stage' && <Edit3 className="w-3 h-3" />}
+            {projectStatus === 'waiting' && <Edit3 className="w-3 h-3" />}
             {projectStatus === 'error' && <AlertCircle className="w-3 h-3" />}
             <span>
               {projectStatus === 'running' ? '执行中' :
-               projectStatus === 'waiting_in_stage' ? '等待确认' :
-               projectStatus === 'stage_completed' ? '阶段完成' :
-               projectStatus === 'session_completed' ? '已完成' :
-               projectStatus === 'idle' ? '空闲' :
+               projectStatus === 'waiting' ? '等待确认' :
+               projectStatus === 'completed' ? '已完成' :
+               projectStatus === 'pending' ? '空闲' :
                projectStatus === 'stopped' ? '已停止' :
                projectStatus === 'error' ? '出错' : projectStatus}
             </span>
diff --git a/aigc-director/aigc-claw/frontend/components/WorkflowPanel.tsx b/aigc-director/aigc-claw/frontend/components/WorkflowPanel.tsx
index d393ce8..71362a0 100644
--- a/aigc-director/aigc-claw/frontend/components/WorkflowPanel.tsx
+++ b/aigc-director/aigc-claw/frontend/components/WorkflowPanel.tsx
@@ -1,4 +1,4 @@
-'use client';
+'use client';
 
 import React, { useState, useRef, useEffect, useCallback } from 'react';
 import { useRouter, useSearchParams } from 'next/navigation';
@@ -47,7 +47,7 @@
   style?: string;
   date: string;
   status: string;
-  stages?: string[];  // stages_completed 列表
+  stages?: Record<string, string>; // stageId => status 映射
 }
 
 function initStageStates(): Record<string, StageState> {
@@ -107,9 +107,11 @@
           status = await getProjectStatus(sid);
         }
         if (pollRef.current !== key) return;
-        const done = status.stages_completed || [];
+        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 = status.status === 'waiting_in_stage' && status.current_stage === stageId;
+          const isWait = currentStageStatus === 'waiting' && status.current_stage === stageId;
           let artifact = null;
           try { artifact = (await getArtifact(sid, stageId)).artifact; } catch {}
           updateStageState(stageId, {
@@ -121,7 +123,7 @@
           pollRef.current = null;
           return;
         }
-        if (status.status === 'error') {
+        if (currentStageStatus === 'error') {
           updateStageState(stageId, {
             status: 'error',
             error: status.error || '执行出错',
@@ -130,7 +132,7 @@
           pollRef.current = null;
           return;
         }
-        if (status.status === 'stopped') {
+        if (currentStageStatus === 'stopped') {
           updateStageState(stageId, {
             status: 'stopped',
             error: '手动停止',
@@ -139,8 +141,8 @@
           pollRef.current = null;
           return;
         }
-        // 如果后端状态不再是 running,提前停止轮询(比如变成了 waiting_intervention 或已完成)
-        if (status.status !== 'running') {
+        // 如果当前阶段不再是 running,提前停止轮询(比如变成了 waiting_intervention 或已完成)
+        if (currentStageStatus !== 'running') {
           pollRef.current = null;
           return;
         }
@@ -148,6 +150,11 @@
         const artifacts = status.artifacts || {};
         const currentArtifact = artifacts[stageId];
         const update: Partial<StageState> = {};
+
+        // 无论何种状态,只要有数据就更新 artifact
+        if (currentArtifact) {
+          update.artifact = currentArtifact;
+        }
 
         // 始终设置状态为 running(如果尚未设置)
         const currentState = stageStates[stageId];
@@ -157,9 +164,10 @@
         }
 
         if (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) {
@@ -201,8 +209,8 @@
             date: s.date
               ? new Date(s.date * 1000).toLocaleDateString('zh-CN')
               : '',
-            status: (s.stages?.length || 0) > 0 ? 'partial' : 'new',
-            stages: s.stages || [],
+            status: Object.keys(s.status || {}).length > 0 ? 'partial' : 'new',
+            stages: s.status || {},
           }))
         );
       })
@@ -469,7 +477,7 @@
           style: params.style,
           date: new Date().toLocaleDateString('zh-CN'),
           status: 'running',
-          stages: [],
+          stages: {},
         },
         ...prev,
       ]);
@@ -504,9 +512,11 @@
         }
 
         const status = await getProjectStatus(result.session_id);
-        // waiting_in_stage: 等待用户介入(如选择角色/图片),不能自动 continue
-        // stage_completed: 阶段完成,等待确认进入下一阶段
-        if (status.status === 'stage_completed') {
+        const stageStatus = status?.status?.[stageId];
+        setGlobalStatusMap(status.status || {});
+        // waiting: 等待用户介入(如选择角色/图片),不能自动 continue
+        // completed: 阶段完成,等待确认进入下一阶段
+        if (stageStatus === 'completed' || stageStatus === 'session_completed') {
           if (useAutoMode) {
             // 代理模式:自动确认并继续
             await continueWorkflow(result.session_id);
@@ -517,7 +527,7 @@
             setIsRunning(false);
             return;
           }
-        } else if (status.status === 'waiting_in_stage') {
+        } else if (stageStatus === 'waiting') {
           // 用户需要介入,停止自动执行
           updateStageState(stageId, { status: 'waiting' });
           setActiveStage(stageId);
@@ -538,10 +548,13 @@
     setIsRunning(true);
 
     try {
-      const result = await continueWorkflow(sessionId);
+      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);
@@ -605,9 +618,11 @@
           await runStage(sessionId, nextStage, inputData);
 
           const status = await getProjectStatus(sessionId);
-          // waiting_in_stage: 等待用户介入(如选择角色/图片),不能自动 continue
-          // stage_completed: 阶段完成,等待确认进入下一阶段,可以自动 continue
-          if (status.status === 'stage_completed') {
+          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: '已自动确认' });
@@ -620,7 +635,7 @@
               setActiveStage(nextStage);
               break;
             }
-          } else if (status.status === 'waiting_in_stage') {
+          } else if (nStageStatus === 'waiting') {
             // 用户需要介入,停止自动执行
             updateStageState(nextStage, { status: 'waiting' });
             setCurrentStageFromSession(nextStage);
@@ -826,46 +841,54 @@
         const oldScenes = (oldRefArtifact?.scenes || []) as any[];
         const oldScenesMap = new Map(oldScenes.map((s: any) => [s.id, s]));
 
-        // 使用 original_shots(保留 is_new 标记)构建第4阶段 scenes
-        const sourceShots = patch.original_shots || patch.shots || [];
-        console.log('[handleSaveSelections] sourceShots:', sourceShots);
-        const newScenes = sourceShots.map((shot: any, idx: number) => {
-          const oldScene = oldScenesMap.get(shot.shot_id) as any;
-          const isNew = shot.is_new;
-          // 如果是新分镜,使用空值;否则保留原有的 selected/versions
+        // 使用 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: shot.shot_id,
-            name: `场景${shot.scene_number}-镜头${shot.shot_number}`,
+            id: seg_id,
+            name: `片段_${seg_id}`,
             index: idx + 1,
-            description: shot.visual_prompt || '',
-            duration: shot.duration || 10,
+            description: desc_ref,
             selected: isNew ? '' : (oldScene?.selected || ''),
             versions: isNew ? [] : (oldScene?.versions || []),
             status: isNew ? 'pending' : 'done',
           };
         });
-        console.log('[handleSaveSelections] newScenes:', newScenes);
 
         // 更新第4阶段的 artifact
         updateStageState('reference_generation', {
           artifact: { session_id: sessionId, scenes: newScenes },
           status: 'completed'
         });
-        console.log('[handleSaveSelections] 第4阶段已更新');
 
         // 同步更新第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 = sourceShots.map((shot: any, idx: number) => {
-          const oldClip = oldClipsMap.get(shot.shot_id) as any;
+        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: shot.shot_id,
-            name: `场景${shot.scene_number}-镜头${shot.shot_number}`,
+            id: seg_id,
+            name: `片段_${seg_id}`,
             index: idx + 1,
-            description: shot.visual_prompt || '',
-            duration: shot.duration || 10,
+            description: desc_video,
+            duration: total_dur,
             selected: oldClip?.selected || '',
             versions: oldClip?.versions || [],
             status: 'pending',
@@ -935,7 +958,7 @@
       await runStage(sessionId, stageId, inputData);
 
       const status = await getProjectStatus(sessionId);
-      if (status.status === 'waiting_in_stage') {
+      if (status?.status?.[stageId] === 'waiting') {
         updateStageState(stageId, { status: 'waiting' });
         setActiveStage(stageId);
       }
@@ -969,47 +992,48 @@
       } catch {
         status = await getProjectStatus(sid);
       }
+      setGlobalStatusMap(status.status || {});
       const newStates = initStageStates();
-      const completedStages = status.stages_completed || [];
+      const stMap = status.status || {};
+      const allStatusStages = Object.keys(stMap);
       const currentStage = status.current_stage;
-      const isWaiting = status.status === 'waiting_in_stage';
+      
       // 保存到 state 供顶栏流程图使用
       setCurrentStageFromSession(currentStage || null);
+      const completedStages = allStatusStages.filter(k => ["completed", "session_completed"].includes(stMap[k]));
       setCompletedStagesFromSession(completedStages);
 
-      for (const cs of completedStages) {
-        const isCurrentWaiting = cs === currentStage && isWaiting;
-        newStates[cs] = {
-          status: isCurrentWaiting ? 'waiting' : 'completed',
-          progress: 100,
-          progressMessage: isCurrentWaiting ? '等待确认' : '已完成',
-          artifact: null,
-          error: null,
-        };
-        try {
-          const artResult = await getArtifact(sid, cs);
-          newStates[cs].artifact = artResult.artifact;
-        } catch { /* ignore */ }
-      }
+      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;
+        }
 
-      // 如果 current_stage 不在 completedStages 中,也需要显示(可能是 stage_completed、running, stopped, 或 error 状态)
-      if (currentStage && !completedStages.includes(currentStage)) {
-        const isError = status.status === 'error';
-        const isWaiting = status.status === 'waiting_in_stage';
-        const isCompleted = status.status === 'stage_completed';
-        const isStopped = status.status === 'stopped';
-        
-        newStates[currentStage] = {
-          status: isError ? 'error' : (isWaiting ? 'waiting' : (isCompleted ? 'completed' : (isStopped ? 'stopped' : 'running'))),
-          progress: 100,
-          progressMessage: isError ? '执行失败' : (isWaiting ? '等待确认' : (isCompleted ? '已完成' : (isStopped ? '已停止' : '进行中'))),
-          artifact: null,
+        const isCompleted = ["completed", "session_completed"].includes(cStatus);
+        const isError = cStatus === 'error';
+        const isWaiting = cStatus === 'waiting';
+        const isStopped = cStatus === 'stopped';
+        const isRunningStatus = cStatus === 'running';
+
+        newStates[sName] = {
+          status: isError ? 'error' : (isWaiting ? 'waiting' : (isStopped ? 'stopped' : (isCompleted ? 'completed' : 'running'))),
+          progress: isCompleted ? 100 : 0,
+          progressMessage: isError ? '执行失败' : (isWaiting ? '等待确认' : (isStopped ? '已停止' : (isCompleted ? '已完成' : (isRunningStatus ? '执行中...' : '进行中')))),
+          artifact: status.artifacts?.[sName] || null,
           error: isError ? (status.error || '执行出错') : (isStopped ? '手动停止' : null),
         };
-        try {
-          const artResult = await getArtifact(sid, currentStage);
-          newStates[currentStage].artifact = artResult.artifact;
-        } catch { /* ignore */ }
+        
+        // 如果内存中没有,尝试异步拉取
+        if (!newStates[sName].artifact) {
+          try {
+            const artResult = await getArtifact(sid, sName);
+            newStates[sName].artifact = artResult.artifact;
+          } catch { /* ignore */ }
+        }
       }
 
       // 恢复项目参数(从顶层字段读取,sessions json 中模型参数是顶层字段)
@@ -1039,7 +1063,7 @@
       setStageStates(newStates);
 
       // 轮询当前正在执行的阶段(仅当该阶段有 artifact 数据时)
-      if (status.status === 'running' && currentStage && !completedStages.includes(currentStage)) {
+      if (currentStage && stMap[currentStage] === 'running') {
         pollForCompletion(sid, currentStage);
       }
     } catch {
@@ -1093,34 +1117,30 @@
     : undefined;
 
   // ── 计算 stageStatuses for TopBar ──
-  // 根据 session 的 current_stage 和 stages_completed 判断图标状态
+  // 直接根据后端返回的 status 数据计算图标状态
+  const [globalStatusMap, setGlobalStatusMap] = useState<Record<string, string>>({});
+  
   const stageStatuses: Record<string, StageStatus> = {};
-  const currentIdx = STAGE_ORDER.indexOf(currentStageFromSession || '');
 
   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 (i < currentIdx) {
-      // current_stage 之前的阶段:已完成(绿色对勾)
+    if (backendStatus === 'completed') {
       stageStatuses[s] = 'completed';
-    } else if (i > currentIdx) {
-      // current_stage 之后的阶段
-      if (completedStagesFromSession.includes(s)) {
-        // 在 stages_completed 中(黄色图案)
-        stageStatuses[s] = 'waiting';
-      } else {
-        // 不在 stages_completed 中:pending
-        stageStatuses[s] = 'pending';
-      }
+    } else if (backendStatus === 'waiting') {
+      stageStatuses[s] = 'waiting';
+    } else if (backendStatus === 'running') {
+      stageStatuses[s] = 'running';
+    } else if (backendStatus === 'error') {
+      stageStatuses[s] = 'error';
     } else {
-      // current_stage 本身:根据 stageStates 判断
-      stageStatuses[s] = stageStates[s]?.status || 'pending';
-      if (stageStatuses[s] === 'stopped') stageStatuses[s] = 'stopped';
+      stageStatuses[s] = 'pending';
     }
   }
 
   // ── 计算项目状态 ──
-  // 后端状态: idle, running, waiting_in_stage, stage_completed, session_completed, error
+  // 后端状态: 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');
@@ -1129,16 +1149,16 @@
 
   let computedStatus: string;
   if (hasRunning) computedStatus = 'running';
-  else if (hasWaiting) computedStatus = 'waiting_in_stage';
+  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 = 'session_completed';
+    computedStatus = 'completed';
   } else if (allCompleted) {
-    computedStatus = 'stage_completed';
+    computedStatus = 'completed';
   } else {
-    computedStatus = Object.values(stageStates).some(s => s.status === 'stopped') ? 'stopped' : 'idle';
+    computedStatus = Object.values(stageStates).some(s => s.status === 'stopped') ? 'stopped' : 'pending';
   }
 
   const projectStatus = sessionId ? computedStatus : undefined;
@@ -1254,3 +1274,4 @@
     </div>
   );
 }
+
diff --git a/aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx b/aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx
index 31596ab..deb0bbf 100644
--- a/aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx
+++ b/aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx
@@ -153,7 +153,8 @@
   onToggleEdit?: () => void;
   getSelected: (scene: SceneItem) => string;
 }) {
-  const isPending = scene.status === 'pending' || isRegenerating;
+  const isRunning = scene.status === 'running' || isRegenerating;
+  const isPending = scene.status === 'pending';
   const isFailed = scene.status === 'failed' && !isRegenerating;
   const isPendingEmpty = scene.status === 'pending' && !scene.versions.length && !isRegenerating;
   const hasChanges = editDesc !== scene.description;
@@ -170,6 +171,9 @@
           </span>
           <span className="text-sm font-semibold text-gray-800 truncate">{scene.name || (scene as any).title || `片段 ${scene.index}`}</span>
           {isPending && (
+            <span className="text-[10px] bg-gray-50 text-gray-500 px-1.5 py-0.5 rounded">等待中</span>
+          )}
+          {isRunning && (
             <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" />生成中
             </span>
@@ -246,13 +250,19 @@
               <span>生成首帧参考图</span>
             </div>
           </div>
-        ) : isPending && !scene.versions.length ? (
+        ) : isRunning && !scene.versions.length ? (
           <div className="flex items-center justify-center h-28 aspect-video bg-gray-50 rounded-lg border border-dashed border-gray-200">
             <div className="flex items-center gap-2 text-gray-400 text-xs">
               <Loader className="w-4 h-4 animate-spin" />
               <span>正在生成...</span>
             </div>
           </div>
+        ) : isPending && !scene.versions.length ? (
+          <div className="flex items-center justify-center h-28 aspect-video bg-gray-50/30 rounded-lg border border-dashed border-gray-200">
+            <div className="flex items-center gap-2 text-gray-400 text-xs text-center px-4">
+              <span>等待生成...</span>
+            </div>
+          </div>
         ) : isFailed && !scene.versions.length ? (
           <div
             className="flex items-center justify-center h-28 aspect-video bg-red-50/50 rounded-lg border border-dashed border-red-200 cursor-pointer hover:bg-red-100/50 transition-colors"
diff --git a/aigc-director/aigc-claw/frontend/components/stages/StageActions.tsx b/aigc-director/aigc-claw/frontend/components/stages/StageActions.tsx
index 7617576..828dd38 100644
--- a/aigc-director/aigc-claw/frontend/components/stages/StageActions.tsx
+++ b/aigc-director/aigc-claw/frontend/components/stages/StageActions.tsx
@@ -47,14 +47,16 @@
   // 是否是"重新生成"阶段(1)
   const isRegenStage = STAGES_WITH_NEXT_CHECK.includes(stageId);
 
-  // 重新生成/继续生成按钮:在 waiting / completed / error / stopped 状态下显示
-  const showRegen = !!onRegenerate && (status === 'waiting' || status === 'completed' || status === 'error' || status === 'stopped');
+  // 重新生成/继续生成按钮:在 != 'running' 状态下显示 (pending时也不会到这个组件)
+  const showRegen = !!onRegenerate && status !== 'running';
   
   // 按钮是否禁用逻辑
   let isButtonDisabled = isRunning;
-  if (!isRunning) {
-    if (isContinueStage && !hasPendingItems && status !== 'error') isButtonDisabled = true;
-    if (isRegenStage && hasNextStageStarted) isButtonDisabled = true;
+  if (!isRunning && stageId) {
+    // 除了第一阶段和第六阶段外,completed 状态下禁用继续生成
+    if (stageId !== 'script_generation' && stageId !== 'post_production' && status === 'completed') {
+      isButtonDisabled = true;
+    }
   }
 
   // 其余按钮在 waiting、running、completed、stopped 状态显示
diff --git a/aigc-director/aigc-claw/frontend/components/stages/StoryboardStage.tsx b/aigc-director/aigc-claw/frontend/components/stages/StoryboardStage.tsx
index 1b38c41..82da41e 100644
--- a/aigc-director/aigc-claw/frontend/components/stages/StoryboardStage.tsx
+++ b/aigc-director/aigc-claw/frontend/components/stages/StoryboardStage.tsx
@@ -162,8 +162,9 @@
     let totalSegments = 0;
     let totalDuration = 0;
     episodesToRender.forEach(ep => {
-      totalSegments += ep.segments.length;
-      ep.segments.forEach(seg => {
+      const segs = ep.segments || [];
+      totalSegments += segs.length;
+      segs.forEach(seg => {
         totalDuration += (seg.total_duration || 0);
       });
     });
@@ -246,7 +247,8 @@
         ) : (
           <div className="space-y-12">
             {episodesToRender.map((episode, epIdx) => {
-              const epTotalTime = episode.segments.reduce((sum, s) => sum + (s.total_duration || 0), 0);
+              const segs = episode.segments || [];
+              const epTotalTime = segs.reduce((sum, s) => sum + (s.total_duration || 0), 0);
               return (
                 <div key={epIdx} className="space-y-4">
                   {/* 一级:剧集抬头 (参考第一阶段) */}
@@ -262,7 +264,7 @@
 
                   {/* 二级:拍摄分段 */}
                   <div className="space-y-8 pl-1">
-                    {episode.segments.map((segment, segIdx) => (
+                    {segs.map((segment, segIdx) => (
                       <div key={segment.segment_id} className="space-y-3">
                         <div className="flex items-center justify-between bg-gray-50/50 rounded-lg px-4 py-2 border border-gray-100">
                           <div className="flex items-center gap-6">
@@ -272,17 +274,17 @@
                               <span className="text-sm font-bold text-gray-800">
                                 {isEditing ? (
                                   <input 
-                                    value={segment.location} 
+                                    value={segment.location || ''} 
                                     onChange={e => updateSegmentField(epIdx, segIdx, 'location', e.target.value)} 
                                     className="bg-transparent border-b border-gray-200 focus:border-violet-400 outline-none px-1" 
                                   />
-                                ) : segment.location}
+                                ) : (segment.location || '未知地点')}
                               </span>
                             </div>
                             <div className="flex items-center gap-1.5">
                               <Users className="w-3.5 h-3.5 text-gray-400" />
                               <div className="flex gap-1.5">
-                                {segment.characters.map((c, i) => (
+                                {(segment.characters || []).map((c, i) => (
                                   <span key={i} className="px-2 py-0.5 bg-white border border-gray-200 text-xs text-gray-600 rounded font-bold">{c}</span>
                                 ))}
                               </div>
@@ -304,7 +306,7 @@
                               </tr>
                             </thead>
                             <tbody className="divide-y divide-gray-50">
-                              {segment.shots.map((shot, sIdx) => {
+                              {(segment.shots || []).map((shot, sIdx) => {
                                 const decor = SHOT_TYPE_DECOR[shot.shot_type as keyof typeof SHOT_TYPE_DECOR] || SHOT_TYPE_DECOR['近景'];
                                 return (
                                   <tr key={sIdx} className="group hover:bg-gray-50/30 transition-colors">
diff --git a/aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx b/aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx
index 9d0dab9..fc030af 100644
--- a/aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx
+++ b/aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx
@@ -145,7 +145,8 @@
   disabled?: boolean;
   isSaving?: boolean;
 }) {
-  const isPending = clip.status === 'pending' || isRegenerating;
+  const isRunning = clip.status === 'running' || isRegenerating;
+  const isPending = clip.status === 'pending';
   const isFailed = clip.status === 'failed' && !isRegenerating;
   const hasChanges = editDesc !== clip.description;
 
@@ -164,6 +165,9 @@
             <span className="text-[10px] bg-gray-100 text-gray-500 px-1.5 py-0.5 rounded">{clip.duration}s</span>
           )}
           {isPending && (
+            <span className="text-[10px] bg-gray-100 text-gray-500 px-1.5 py-0.5 rounded">等待中</span>
+          )}
+          {isRunning && (
             <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" />生成中
             </span>
@@ -234,13 +238,19 @@
 
       {/* 右侧: 视频画廊 / 占位 */}
       <div className="flex-1 min-w-0 p-3 flex items-center">
-        {isPending && !clip.versions.length ? (
+        {isRunning && !clip.versions.length ? (
           <div className="flex items-center justify-center h-32 aspect-video bg-gray-50 rounded-lg border border-dashed border-gray-200">
             <div className="flex items-center gap-2 text-gray-400 text-xs px-4">
               <Loader className="w-4 h-4 animate-spin" />
               <span>正在生成视频...</span>
             </div>
           </div>
+        ) : isPending && !clip.versions.length ? (
+          <div className="flex items-center justify-center h-32 aspect-video bg-gray-50/30 rounded-lg border border-dashed border-gray-200">
+            <div className="flex items-center gap-2 text-gray-400 text-xs px-4">
+              <span>等待生成视频...</span>
+            </div>
+          </div>
         ) : isFailed && !clip.versions.length ? (
           <div
             className="flex items-center justify-center h-32 aspect-video bg-red-50/50 rounded-lg border border-dashed border-red-200 cursor-pointer hover:bg-red-100/50 transition-colors"
diff --git a/aigc-director/aigc-claw/frontend/lib/workflowApi.ts b/aigc-director/aigc-claw/frontend/lib/workflowApi.ts
index 09c0b31..ae182da 100644
--- a/aigc-director/aigc-claw/frontend/lib/workflowApi.ts
+++ b/aigc-director/aigc-claw/frontend/lib/workflowApi.ts
@@ -19,9 +19,8 @@
 export interface ProjectStatus {
   session_id: string;
   current_stage: string;
-  status: string;
+  status: Record<string, string>;
   error: string | null;
-  stages_completed: string[];
 }
 
 export interface StreamEvent {
diff --git a/aigc-director/references/workflow/create_project.md b/aigc-director/references/workflow/create_project.md
index 686c875..eeb1e20 100644
--- a/aigc-director/references/workflow/create_project.md
+++ b/aigc-director/references/workflow/create_project.md
@@ -1,4 +1,4 @@
-# 创建项目
+# 创建项目
 
 创建一个新的视频生成项目。
 
@@ -29,7 +29,7 @@
 ```json
 {
   "session_id": "xxx",
-  "status": "stage_completed",
+  "status": "completed",
   "params": {
     "idea": "故事内容",
     "style": "anime",
@@ -187,4 +187,4 @@
 |------|------|----------|
 | `curl: (7) Failed to connect` | 后端未运行 | 启动后端服务 |
 | `500 Internal Server Error` | API Key 缺失或配置错误 | 检查 `backend/.env` 文件 |
-| `404 Not Found` | API 路径错误 | 确认 URL 为 `http://localhost:8000/api/project/start` |
\ No newline at end of file
+| `404 Not Found` | API 路径错误 | 确认 URL 为 `http://localhost:8000/api/project/start` |

--
Gitblit v1.8.0