From 8c486e7efa254bc11f7727ae2aa581b366b9ffa8 Mon Sep 17 00:00:00 2001
From: hit-cxf <2024111082@stu.hit.edu.cn>
Date: Sat, 04 Apr 2026 20:28:34 +0800
Subject: [PATCH] aigc-claw-v2

---
 aigc-director/aigc-claw/backend/core/agents/video_agent.py              |  683 ++----
 aigc-director/aigc-claw/backend/prompts/script/act_extract_en.txt       |   77 
 aigc-director/aigc-claw/backend/prompts/script/meta_extract_zh.txt      |   53 
 aigc-director/aigc-claw/backend/prompts/reference/first_frame_zh.txt    |   27 
 aigc-director/aigc-claw/backend/prompts/setting/eval_setting_zh.txt     |    2 
 aigc-director/aigc-claw/backend/api_server.py                           |   73 
 aigc-director/aigc-claw/backend/docs/session_format.md                  |    3 
 aigc-director/aigc-claw/frontend/components/WorkflowPanel.tsx           |   40 
 aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx   |    4 
 aigc-director/aigc-claw/backend/core/agents/script_agent.py             | 1080 +----------
 aigc-director/aigc-claw/backend/tool/image_client.py                    |    2 
 aigc-director/aigc-claw/backend/tool/llm_deepseek.py                    |    3 
 aigc-director/aigc-claw/backend/core/agents/video_agent.py.bak          |  626 ++++++
 aigc-director/aigc-claw/frontend/components/stages/ScriptStage.tsx      |   45 
 aigc-director/aigc-claw/backend/core/agents/base_agent.py               |    7 
 aigc-director/aigc-claw/frontend/components/stages/StoryboardStage.tsx  |  983 +++------
 aigc-director/aigc-claw/backend/config.py                               |    9 
 aigc-director/aigc-claw/backend/prompts/reference/first_frame_en.txt    |   27 
 aigc-director/aigc-claw/backend/core/agents/storyboard_agent.py         |  615 ++----
 aigc-director/aigc-claw/backend/core/orchestrator.py                    |    8 
 aigc-director/aigc-claw/backend/prompts/script/generate_script_zh.txt   |   64 
 aigc-director/aigc-claw/frontend/lib/workflowApi.ts                     |    2 
 aigc-director/aigc-claw/backend/core/agents/character_agent.py          |   89 
 aigc-director/aigc-claw/backend/prompts/storyboard/shot_zh.txt          |   71 
 aigc-director/aigc-claw/backend/prompts/script/generate_script_en.txt   |   46 
 aigc-director/aigc-claw/backend/prompts/setting/eval_select_best_zh.txt |    2 
 /dev/null                                                               |   27 
 aigc-director/aigc-claw/frontend/components/stages/types.ts             |    2 
 aigc-director/aigc-claw/backend/core/agents/editor_agent.py             |  123 +
 aigc-director/aigc-claw/backend/prompts/script/meta_extract_en.txt      |   28 
 aigc-director/aigc-claw/frontend/components/HomePage.tsx                |   27 
 aigc-director/aigc-claw/backend/prompts/script/act_extract_zh.txt       |   91 
 aigc-director/aigc-claw/backend/core/agents/reference_agent.py          |  427 ++--
 aigc-director/aigc-claw/frontend/components/stages/StageActions.tsx     |   60 
 aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx       |   16 
 35 files changed, 2,369 insertions(+), 3,073 deletions(-)

diff --git a/aigc-director/aigc-claw/backend/api_server.py b/aigc-director/aigc-claw/backend/api_server.py
index 85762cc..4ef4a9d 100644
--- a/aigc-director/aigc-claw/backend/api_server.py
+++ b/aigc-director/aigc-claw/backend/api_server.py
@@ -441,21 +441,23 @@
     # 同步到:storyboard.shots[].visual_prompt
     # ══════════════════════════════════════════════════════════════
     elif stage == "reference_generation":
-        if "shots" in body:
+        if "segments" in body:
             # 修改视觉提示词 → 同步到 storyboard
-            # body.shots 是 [{shot_id: "...", visual_prompt: "..."}]
-            shot_id_to_prompt = {s['shot_id']: s.get('visual_prompt', '')
-                                 for s in body['shots'] if 'shot_id' in s}
+            # body.segments 是 [{segment_id: "...", visual_prompt: "..."}]
+            seg_id_to_prompt = {s['segment_id']: s.get('visual_prompt', '')
+                                for s in body['segments'] if 'segment_id' in s}
 
             storyboard_art = state.artifacts.get('storyboard', {})
-            # storyboard 结构: {shots: [...]} (无 payload 包装)
+            # storyboard 结构: {episodes: [{segments: [...]}]}
             if isinstance(storyboard_art, dict):
-                shots = storyboard_art.get('shots', [])
-                for shot in shots:
-                    if isinstance(shot, dict):
-                        shot_id = shot.get('shot_id')
-                        if shot_id in shot_id_to_prompt:
-                            shot['visual_prompt'] = shot_id_to_prompt[shot_id]
+                episodes = storyboard_art.get('episodes', [])
+                for ep in episodes:
+                    if isinstance(ep, dict):
+                        for seg in ep.get('segments', []):
+                            if isinstance(seg, dict):
+                                seg_id = seg.get('segment_id')
+                                if seg_id in seg_id_to_prompt:
+                                    seg['visual_prompt'] = seg_id_to_prompt[seg_id]
 
             # 同步到 reference_generation.scenes 的 description
             ref_art = state.artifacts.get('reference_generation', {})
@@ -464,11 +466,11 @@
                 for scene in scenes:
                     if isinstance(scene, dict):
                         scene_id = scene.get('id')
-                        if scene_id in shot_id_to_prompt:
-                            scene['description'] = shot_id_to_prompt[scene_id]
+                        if scene_id in seg_id_to_prompt:
+                            scene['description'] = seg_id_to_prompt[scene_id]
 
-            # 移除 shots,避免覆盖 reference_generation artifact
-            body = {k: v for k, v in body.items() if k != "shots"}
+            # 移除 segments,避免覆盖 reference_generation artifact
+            body = {k: v for k, v in body.items() if k != "segments"}
 
         # 处理图片版本选择 {sceneId: path}
         ref_art = state.artifacts.get('reference_generation', {})
@@ -505,16 +507,16 @@
         # 同步到 storyboard 和 video_generation.clips
         if clip_id_to_duration or clip_id_to_description:
             storyboard_art = state.artifacts.get('storyboard', {})
-            # storyboard 结构: {shots: [...]} (无 payload 包装)
+            # storyboard 结构: 从 shots 变更为了 episodes -> segments
             if isinstance(storyboard_art, dict):
-                shots = storyboard_art.get('shots', [])
-                for shot in shots:
-                    if isinstance(shot, dict):
-                        shot_id = shot.get('shot_id')
-                        if shot_id in clip_id_to_duration:
-                            shot['duration'] = clip_id_to_duration[shot_id]
-                        if shot_id in clip_id_to_description:
-                            shot['plot'] = clip_id_to_description[shot_id]
+                episodes = storyboard_art.get('episodes', [])
+                for ep in episodes:
+                    if isinstance(ep, dict):
+                        for seg in ep.get('segments', []):
+                            if isinstance(seg, dict):
+                                seg_id = seg.get('segment_id')
+                                if seg_id in clip_id_to_duration:
+                                    seg['total_duration'] = clip_id_to_duration[seg_id]
 
             # 更新 video_generation.clips 的 duration 和 description
             vid_art = state.artifacts.get('video_generation', {})
@@ -710,15 +712,8 @@
 
 
 @app.delete("/api/sessions/{session_id}")
-async def delete_session(session_id: str, request: Request):
-    """删除历史记录(需要管理员密码)"""
-    try:
-        body = await request.json()
-    except Exception:
-        body = {}
-    password = body.get("password", "")
-    if not settings.ADMIN_PASSWORD or password != settings.ADMIN_PASSWORD:
-        raise HTTPException(403, "密码错误")
+async def delete_session(session_id: str):
+    """直接删除历史记录(无密码控制)"""
     deleted = workflow_engine.delete_session(session_id)
     if not deleted:
         raise HTTPException(404, "Session not found")
@@ -726,16 +721,8 @@
 
 
 @app.delete("/api/sessions")
-async def cleanup_orphan_files(request: Request):
-    """清理孤立的结果文件(需要管理员密码)"""
-    try:
-        body = await request.json()
-    except Exception:
-        body = {}
-    password = body.get("password", "")
-    if not settings.ADMIN_PASSWORD or password != settings.ADMIN_PASSWORD:
-        raise HTTPException(403, "密码错误")
-
+async def cleanup_orphan_files():
+    """清理孤立的结果文件(无密码控制)"""
     # 获取所有 session ID
     session_ids = set()
     for f in os.listdir(workflow_engine._session_dir):
diff --git a/aigc-director/aigc-claw/backend/config.py b/aigc-director/aigc-claw/backend/config.py
index a1ce038..909dc91 100644
--- a/aigc-director/aigc-claw/backend/config.py
+++ b/aigc-director/aigc-claw/backend/config.py
@@ -29,6 +29,9 @@
     
     # 临时文件目录
     TEMP_DIR = os.path.join(BASE_DIR, 'temp')
+    
+    # 会话数据目录
+    SESSION_DIR = os.path.join(CODE_DIR, 'data', 'sessions')
 
     # ==========================
     # AI 模型 API 配置
@@ -84,9 +87,11 @@
     @classmethod
     def check_dirs(cls):
         """自动创建必要的目录"""
-        for directory in [cls.CODE_DIR, cls.RESULT_DIR, cls.TEMP_DIR]:
+        # 确保 data 和 sessions 目录存在
+        data_dir = os.path.join(cls.CODE_DIR, 'data')
+        for directory in [cls.CODE_DIR, data_dir, cls.SESSION_DIR, cls.RESULT_DIR, cls.TEMP_DIR]:
             if not os.path.exists(directory):
-                os.makedirs(directory)
+                os.makedirs(directory, exist_ok=True)
                 print(f"Created directory: {directory}")
 
 # 初始化目录结构
diff --git a/aigc-director/aigc-claw/backend/core/agents/base_agent.py b/aigc-director/aigc-claw/backend/core/agents/base_agent.py
index 065ee3e..1db1ee8 100644
--- a/aigc-director/aigc-claw/backend/core/agents/base_agent.py
+++ b/aigc-director/aigc-claw/backend/core/agents/base_agent.py
@@ -42,7 +42,7 @@
             keys_to_merge = [
                 "style", "video_ratio", "llm_model", "vlm_model", 
                 "image_t2i_model", "image_it2i_model", "video_model",
-                "video_style", "expand_idea"
+                "video_style", "expand_idea", "enable_concurrency"
             ]
             
             merged_data = input_data.copy()
@@ -71,10 +71,11 @@
         if self.cancellation_check and self.cancellation_check():
             raise RuntimeError(f"Agent [{self.name}] cancelled by user")
 
-    def _cancellable_query(self, llm, prompt: str, **kwargs):
+    def _cancellable_query(self, llm, prompt: str, image_urls=[], model="gemini-3-flash-preview", safe_content=True, task_id=None, web_search=False):
         """在 LLM 调用前后检查取消状态"""
         self._check_cancel()
-        result = llm.query(prompt, **kwargs)
+        # 将位置参数映射给 llm.query
+        result = llm.query(prompt, image_urls, model, safe_content, task_id, web_search)
         self._check_cancel()
         return result
 
diff --git a/aigc-director/aigc-claw/backend/core/agents/character_agent.py b/aigc-director/aigc-claw/backend/core/agents/character_agent.py
index f836ae8..d3ae3ac 100644
--- a/aigc-director/aigc-claw/backend/core/agents/character_agent.py
+++ b/aigc-director/aigc-claw/backend/core/agents/character_agent.py
@@ -332,30 +332,23 @@
 
     @staticmethod
     def _read_script_data(sid: str) -> dict:
-        """从结果文件的 script_json 字段读取角色和场景数据(含唯一ID)
-
-        Returns:
-            {
-                "characters": { character_id: { "name", "description", "species" } },
-                "settings":   { setting_id:   { "name", "description" } },
-            }
-        """
-        from config import settings
-
-        script_json_path = os.path.join(settings.RESULT_DIR, 'script', f'script_{sid}.json')
-        if not os.path.exists(script_json_path):
+        """从 code/data/sessions/{sid}.json 提取剧本生成的角色和场景数据"""
+        # Session 文件路径
+        session_path = os.path.join('code/data/sessions', f'{sid}.json')
+        
+        if not os.path.exists(session_path):
+            logger.warning(f"Session file not found: {session_path}")
             return {"characters": {}, "settings": {}}
 
-        with open(script_json_path, 'r', encoding='utf-8') as f:
-            data = json.load(f)
-
-        sid_data = data.get(str(sid), {})
-
-        # 优先从 script_json 读取(包含完整ID信息)
-        sj = sid_data.get('script_json')
-        if sj:
+        try:
+            with open(session_path, 'r', encoding='utf-8') as f:
+                data = json.load(f)
+            
+            # 从 artifacts.script_generation 中提取数据
+            script_gen = data.get("artifacts", {}).get("script_generation", {})
+            
             chars = {}
-            for c in sj.get("characters", []):
+            for c in script_gen.get("characters", []):
                 cid = c.get("character_id", "")
                 if cid:
                     chars[cid] = {
@@ -363,17 +356,20 @@
                         "description": c.get("description", ""),
                         "species": c.get("species", ""),
                     }
+                    
             sets = {}
-            for s in sj.get("settings", []):
+            for s in script_gen.get("settings", []):
                 sid_val = s.get("setting_id", "")
                 if sid_val:
                     sets[sid_val] = {
                         "name": s.get("name", ""),
                         "description": s.get("description", ""),
                     }
+            
             return {"characters": chars, "settings": sets}
-
-        return {"characters": {}, "settings": {}}
+        except Exception as e:
+            logger.error(f"Error reading session data for {sid}: {e}")
+            return {"characters": {}, "settings": {}}
 
     # ─── 核心流程 ───
 
@@ -477,17 +473,40 @@
                             # 简单字符串格式:直接更新 description
                             sets_desc[asset_id]["description"] = str(info)
 
-                # 写回剧本数据文件
-                script_file = os.path.join(settings.RESULT_DIR, 'script', f'script_{sid}.json')
-                with open(script_file, 'r', encoding='utf-8') as f:
-                    full_data = json.load(f)
-
-                if str(sid) in full_data:
-                    full_data[str(sid)]["characters"] = chars_desc
-                    full_data[str(sid)]["settings"] = sets_desc
-
-                with open(script_file, 'w', encoding='utf-8') as f:
-                    json.dump(full_data, f, ensure_ascii=False, indent=2)
+                # 写回会话数据文件
+                session_file = os.path.join('code/data/sessions', f'{sid}.json')
+                if os.path.exists(session_file):
+                    with open(session_file, 'r', encoding='utf-8') as f:
+                        session_data = json.load(f)
+                    
+                    # 更新 artifacts.script_generation 中的描述
+                    script_gen = session_data.get("artifacts", {}).get("script_generation", {})
+                    if script_gen:
+                        # 更新角色
+                        for c in script_gen.get("characters", []):
+                            cid = c.get("character_id")
+                            if cid in updated_chars:
+                                info = updated_chars[cid]
+                                if isinstance(info, dict):
+                                    if "name" in info: c["name"] = info["name"]
+                                    if "description" in info: c["description"] = info["description"]
+                                    if "species" in info: c["species"] = info["species"]
+                                else:
+                                    c["description"] = str(info)
+                        
+                        # 更新场景
+                        for s in script_gen.get("settings", []):
+                            sid_val = s.get("setting_id")
+                            if sid_val in updated_sets:
+                                info = updated_sets[sid_val]
+                                if isinstance(info, dict):
+                                    if "name" in info: s["name"] = info["name"]
+                                    if "description" in info: s["description"] = info["description"]
+                                else:
+                                    s["description"] = str(info)
+                                    
+                        with open(session_file, 'w', encoding='utf-8') as f:
+                            json.dump(session_data, f, ensure_ascii=False, indent=2)
 
                 logger.info(f"[CharacterAgent] Updated descriptions for session {sid}")
 
diff --git a/aigc-director/aigc-claw/backend/core/agents/editor_agent.py b/aigc-director/aigc-claw/backend/core/agents/editor_agent.py
index 018db66..123383d 100644
--- a/aigc-director/aigc-claw/backend/core/agents/editor_agent.py
+++ b/aigc-director/aigc-claw/backend/core/agents/editor_agent.py
@@ -6,9 +6,10 @@
 
 import os
 import re
-import subprocess
+import json
 import asyncio
 import logging
+import subprocess
 from typing import Any, Optional, Dict
 
 from .base_agent import AgentInterface
@@ -24,46 +25,100 @@
 
     async def process(self, input_data: Any, intervention: Optional[Dict] = None) -> Dict:
         sid = input_data["session_id"]
-        selected_clips: dict = input_data.get("selected_clips", {})
-
-        if not selected_clips:
-            raise Exception("未收到用户选择的视频片段(selected_clips),请先完成阶段5")
-
+        
+        # 优先从 session.json 的 artifacts 中读取阶段5的数据
+        session_path = os.path.join('code/data/sessions', f'{sid}.json')
+        if not os.path.exists(session_path):
+            raise Exception(f"Session file not found: {session_path}")
+            
+        with open(session_path, 'r', encoding='utf-8') as f:
+            session_data = json.load(f)
+            
+        artifacts = session_data.get("artifacts", {})
+        video_art = artifacts.get("video_generation", {})
+        clips_list = video_art.get("clips", [])
+        
+        if not clips_list:
+            # 兼容旧逻辑:如果 artifacts 里没有,尝试从 input_data 获取
+            selected_clips: dict = input_data.get("selected_clips", {})
+            if not selected_clips:
+                raise Exception("未找到选定的视频片段数据,请先完成阶段5")
+        
         self._report_progress("后期制作", "准备视频片段...", 5)
 
         def run():
             video_dir = os.path.join('code/result/video', str(sid))
-
-            # 按 shot_id 中的数字排序
-            def sort_key(k: str) -> tuple:
-                return tuple(int(n) for n in re.findall(r'\d+', k)) or (999,)
-
+            os.makedirs(video_dir, exist_ok=True)
+            
             clip_paths = []
-            for shot_id in sorted(selected_clips.keys(), key=sort_key):
-                path = selected_clips[shot_id]
-                if os.path.exists(path):
-                    clip_paths.append(path)
-                else:
-                    logger.warning(f"[{sid}] Clip missing: {shot_id} → {path}")
+            
+            # 如果是从新格式读取
+            if clips_list:
+                for clip in clips_list:
+                    path = clip.get("selected")
+                    if path and os.path.exists(path):
+                        clip_paths.append(path)
+                    else:
+                        logger.warning(f"[{sid}] Clip missing: {clip.get('id')} → {path}")
+            else:
+                # 按旧逻辑从 selected_clips (dict) 读取
+                def sort_key(k: str) -> tuple:
+                    return tuple(int(n) for n in re.findall(r'\d+', k)) or (999,)
+                selected_clips = input_data.get("selected_clips", {})
+                for shot_id in sorted(selected_clips.keys(), key=sort_key):
+                    path = selected_clips[shot_id]
+                    if os.path.exists(path):
+                        clip_paths.append(path)
+                    else:
+                        logger.warning(f"[{sid}] Clip missing: {shot_id} → {path}")
 
             if not clip_paths:
-                raise Exception("所有选定的视频片段文件均不存在")
+                raise Exception("没有可用于拼接的视频文件,请检查之前阶段是否生成成功并选中了版本")
 
-            logger.info(f"[{sid}] Concat {len(clip_paths)} clips")
-            self._report_progress("后期制作", f"拼接 {len(clip_paths)} 个片段...", 15)
+            logger.info(f"[{sid}] Concat {len(clip_paths)} clips using fast stream copy")
+            self._report_progress("后期制作", f"准备拼接 {len(clip_paths)} 个片段...", 15)
 
-            list_path = os.path.join(video_dir, 'file_list.txt')
-            with open(list_path, 'w', encoding='utf-8') as f:
+            # 导出成片
+            output_dir = os.path.join(video_dir, 'output')
+            os.makedirs(output_dir, exist_ok=True)
+            output = os.path.join(output_dir, f'{sid}_final.mp4')
+            
+            # 使用列表文件进行 concat
+            list_file = os.path.join(video_dir, 'concat_list.txt')
+            with open(list_file, 'w', encoding='utf-8') as f:
                 for p in clip_paths:
-                    f.write(f"file '{os.path.abspath(p)}'\n")
+                    # 使用绝对路径并处理 Windows 路径转义
+                    abs_p = os.path.abspath(p).replace('\\', '/')
+                    f.write(f"file '{abs_p}'\n")
 
-            self._report_progress("后期制作", "ffmpeg 拼接中...", 30)
-
-            output = os.path.join(video_dir, f'{sid}_final.mp4')
-            cmd = ['ffmpeg', '-f', 'concat', '-safe', '0',
-                   '-i', list_path, '-c', 'copy', '-y', output]
-            subprocess.run(cmd, check=True, capture_output=True)
-            logger.info(f"[{sid}] Concat success: {output}")
+            try:
+                self._report_progress("后期制作", "正在拼接视频 (FFmpeg)...", 50)
+                
+                ffmpeg_exe = 'ffmpeg'
+                
+                # 为了播放兼容性,我们进行轻量级的重新编码 (Fast Preset)
+                # 这样可以处理不同片段间可能存在的微小元数据差异,确保播放时长正常
+                cmd = [
+                    ffmpeg_exe, '-f', 'concat', '-safe', '0',
+                    '-i', list_file, 
+                    '-c:v', 'libx264',    # 重新编码视频以保证兼容性
+                    '-preset', 'fast',    # 快速平衡速度与质量
+                    '-crf', '22',         # 保持高质量
+                    '-c:a', 'aac',        # 确保有标准的音频流
+                    '-pix_fmt', 'yuv420p', # 确保在所有播放器上都能播放
+                    '-movflags', '+faststart',
+                    '-y', output
+                ]
+                
+                logger.info(f"[{sid}] Running ffmpeg concat/re-encode: {' '.join(cmd)}")
+                result = subprocess.run(cmd, capture_output=True, text=True, check=True)
+                logger.info(f"[{sid}] FFmpeg concat success: {output}")
+                
+            except Exception as e:
+                logger.error(f"Fast concat failed: {str(e)}")
+                # 如果是权限或路径问题,最后尝试一次 moviepy (虽然慢但兼容性好)
+                raise Exception(f"视频快速拼接失败: {str(e)}")
+                
             return output
 
         loop = asyncio.get_running_loop()
@@ -71,6 +126,14 @@
 
         self._report_progress("后期制作", "成片完成", 100)
 
+        # 同样将最终结果写入 artifacts
+        session_data.setdefault("artifacts", {})["post_production"] = {
+            "session_id": sid,
+            "final_video": final_path
+        }
+        with open(session_path, 'w', encoding='utf-8') as f:
+            json.dump(session_data, f, indent=4, ensure_ascii=False)
+
         return {
             "payload": {"session_id": sid, "final_video": final_path},
             "stage_completed": True,
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 bcb1107..b029fc6 100644
--- a/aigc-director/aigc-claw/backend/core/agents/reference_agent.py
+++ b/aigc-director/aigc-claw/backend/core/agents/reference_agent.py
@@ -99,35 +99,35 @@
                     am[key][base_id] = os.path.join(d, fn)
         return am
 
-    def _collect_refs(self, shot: dict, asset_map: dict,
+    def _collect_refs(self, segment: dict, asset_map: dict,
                       char_id_map: dict, setting_id_map: dict) -> List[str]:
-        """为一个分镜收集参考原图路径(角色 + 场景素材)"""
+        """为一个片段(Segment)收集参考原图路径(角色 + 场景素材)"""
         refs = []
-        for cn in shot.get('characters', []):
+        for cn in segment.get('characters', []):
             cid = char_id_map.get(cn)
             if cid and cid in asset_map['characters']:
                 refs.append(os.path.abspath(asset_map['characters'][cid]))
-                logger.info(f"[{shot.get('shot_id', '')}] 添加角色参考图: {cn} -> {cid}")
-        loc = shot.get('location', '')
+                logger.info(f"[{segment.get('segment_id', '')}] 添加角色参考图: {cn} -> {cid}")
+        loc = segment.get('location', '')
         set_id = setting_id_map.get(loc)
         if set_id and set_id in asset_map['settings']:
             refs.append(os.path.abspath(asset_map['settings'][set_id]))
-            logger.info(f"[{shot.get('shot_id', '')}] 添加场景参考图: {loc} -> {set_id}")
+            logger.info(f"[{segment.get('segment_id', '')}] 添加场景参考图: {loc} -> {set_id}")
         else:
-            logger.warning(f"[{shot.get('shot_id', '')}] 未找到场景参考图: location={loc}, set_id={set_id}, available_settings={list(asset_map['settings'].keys())}")
-        logger.info(f"[{shot.get('shot_id', '')}] 共收集 {len(refs)} 张参考图")
+            logger.warning(f"[{segment.get('segment_id', '')}] 未找到场景参考图: location={loc}, set_id={set_id}, available_settings={list(asset_map['settings'].keys())}")
+        logger.info(f"[{segment.get('segment_id', '')}] 共收集 {len(refs)} 张参考图")
         return refs[:10]
 
-    def _get_descriptions(self, shot: dict, char_id_map: dict, setting_id_map: dict,
+    def _get_descriptions(self, segment: dict, char_id_map: dict, setting_id_map: dict,
                           script_json: dict) -> tuple:
-        """获取分镜中涉及的角色和场景描述
+        """获取片段中涉及的角色和场景描述
 
         Returns:
             (character_description, setting_description)
         """
         # 角色描述
         char_descs = []
-        for cn in shot.get('characters', []):
+        for cn in segment.get('characters', []):
             cid = char_id_map.get(cn, '')
             if cid:
                 for c in script_json.get('characters', []):
@@ -141,7 +141,7 @@
                         break
 
         # 场景描述
-        loc = shot.get('location', '')
+        loc = segment.get('location', '')
         set_id = setting_id_map.get(loc)
         setting_desc = ""
         if set_id:
@@ -156,17 +156,21 @@
 
     # ─── 预览构建 ───
 
-    def _build_preview(self, sid: str, shots: list) -> list:
-        """构建分镜预览列表(含当前状态)"""
+    def _build_preview(self, sid: str, segments: list) -> list:
+        """构建片段预览列表(含当前状态)"""
         preview = []
-        for idx, shot in enumerate(shots, 1):
-            shot_id = shot['shot_id']
-            versions = self._list_versions(sid, shot_id)
+        for idx, seg in enumerate(segments, 1):
+            segment_id = seg.get('segment_id', f'seg_unk_{idx}')
+            versions = self._list_versions(sid, segment_id)
+            
+            # 将该段下所有镜头组合为简要说明
+            shots_summary = " ".join([s.get('content', '') for s in seg.get('shots', [])])
+            
             preview.append({
-                "id": shot_id,
-                "name": f"场景{shot['scene_number']}-镜头{shot['shot_number']}",
+                "id": segment_id,
+                "name": f"第{seg.get('episode_number', 1)}集-片段{seg.get('segment_number', idx)}",
                 "index": idx,
-                "description": shot.get('visual_prompt', ''),
+                "description": shots_summary[:50] + '...' if len(shots_summary) > 50 else shots_summary,
                 "selected": versions[-1] if versions else "",
                 "versions": versions,
                 "status": "done" if versions else "pending",
@@ -175,31 +179,33 @@
 
     # ─── 单张生成 ───
 
-    def _generate_one(self, img_client, sid: str, shot: dict,
+    def _generate_one(self, img_client, sid: str, segment: dict,
                       first_frame_prompt: str, refs: List[str],
                       style: str, it2i_model: str, t2i_model: str,
                       video_ratio: str = "16:9", resolution: str = "1080P", vlm_model: str = "qwen3.5-plus",
                       character_description: str = "", setting_description: str = "",
                       max_versions: int = 3) -> tuple:
-        """生成单个分镜参考图,返回 (shot_id, path_or_None, eval_result)
+        """生成单个片段参考图,返回 (segment_id, path_or_None, eval_result)
 
         最多生成 max_versions 个版本,如果所有版本都没有达到8分,
         使用 VLM 选择最好的一张作为最终参考图。
         """
-        shot_id = shot.get('shot_id', '')
-        plot = shot.get('plot', '')
-        visual_prompt = shot.get('visual_prompt', '')
+        segment_id = segment.get('segment_id', '')
+        
+        # 拼接剧情描述(评估时用)
+        plot = " ".join([s.get('content', '') for s in segment.get('shots', [])])
+        visual_prompt = first_frame_prompt
 
         # 取消时直接跳过,不抛异常,以保留已生成的部分结果
         if self.cancellation_check and self.cancellation_check():
-            logger.info(f"ReferenceGeneratorAgent: {shot_id} 跳过(用户取消)")
-            return shot_id, None, None
+            logger.info(f"ReferenceGeneratorAgent: {segment_id} 跳过(用户取消)")
+            return segment_id, None, None
 
         model = it2i_model if refs else t2i_model
-        logger.info(f"[{shot_id}] 使用模型: {model}, 参考图数量: {len(refs) if refs else 0}")
+        logger.info(f"[{segment_id}] 使用模型: {model}, 参考图数量: {len(refs) if refs else 0}")
         if refs:
             for i, r in enumerate(refs):
-                logger.info(f"[{shot_id}] 参考图[{i}]: {r}")
+                logger.info(f"[{segment_id}] 参考图[{i}]: {r}")
 
         # 收集所有生成的版本
         all_versions = []
@@ -214,7 +220,7 @@
                 f"{first_frame_prompt}"
             )
 
-            save_path = self._next_version_path(sid, shot_id)
+            save_path = self._next_version_path(sid, segment_id)
             save_dir = os.path.dirname(save_path)
 
             try:
@@ -237,7 +243,7 @@
                     os.rename(gen, save_path)
 
                 # VLM 评估
-                eval_result = self._evaluate_with_vlm(save_path, shot,
+                eval_result = self._evaluate_with_vlm(save_path, segment, plot, visual_prompt,
                                                       character_description=character_description,
                                                       setting_description=setting_description,
                                                       vlm_model=vlm_model)
@@ -245,7 +251,7 @@
                 score = eval_result.get('score', 0)
                 is_acceptable = score >= 8
 
-                logger.info(f"[{shot_id}] 版本{version + 1}: 评分 {score}/10, {'✓通过' if is_acceptable else '✗不通过'}")
+                logger.info(f"[{segment_id}] 版本{version + 1}: 评分 {score}/10, {'✓通过' if is_acceptable else '✗不通过'}")
 
                 # 记录版本信息
                 all_versions.append(save_path)
@@ -253,32 +259,32 @@
 
                 # 如果达到8分,立即返回
                 if is_acceptable:
-                    return shot_id, save_path, eval_result
+                    return segment_id, save_path, eval_result
 
                 # 报告进度
                 if version < max_versions - 1:
-                    self._report_progress("参考图", f"重新生成中 ({version + 2}/{max_versions}): {shot_id}", 0)
+                    self._report_progress("参考图", f"重新生成中 ({version + 2}/{max_versions}): {segment_id}", 0)
 
             except Exception as e:
-                logger.error(f"Shot {shot_id} image generation failed: {e}")
+                logger.error(f"Segment {segment_id} image generation failed: {e}")
 
         # 所有版本都没有达到8分,使用 VLM 选择最好的
         if all_versions:
-            logger.warning(f"[{shot_id}] 所有版本都未达到8分,使用VLM选择最佳...")
+            logger.warning(f"[{segment_id}] 所有版本都未达到8分,使用VLM选择最佳...")
             best_path, best_eval = self._select_best_with_vlm(
-                all_versions, shot,
+                all_versions, segment, plot, visual_prompt,
                 character_description=character_description,
                 setting_description=setting_description,
                 vlm_model=vlm_model
             )
             if best_path:
-                return shot_id, best_path, best_eval
+                return segment_id, best_path, best_eval
 
         # 如果没有任何生成成功
-        logger.warning(f"[{shot_id}] 没有成功生成任何图片")
-        return shot_id, None, None
+        logger.warning(f"[{segment_id}] 没有成功生成任何图片")
+        return segment_id, None, None
 
-    def _select_best_with_vlm(self, image_paths: List[str], shot: dict,
+    def _select_best_with_vlm(self, image_paths: List[str], segment: dict, plot: str, visual_prompt: str,
                               character_description: str = "", setting_description: str = "",
                               vlm_model: str = "qwen3.5-plus") -> tuple:
         """使用 VLM 从多个版本中选择最好的一张"""
@@ -287,9 +293,7 @@
         if not image_paths:
             return None, None
 
-        shot_id = shot.get('shot_id', '')
-        plot = shot.get('plot', '')
-        visual_prompt = shot.get('visual_prompt', '')
+        segment_id = segment.get('segment_id', '')
 
         # 加载评估提示词
         select_prompt = load_prompt('reference', 'eval_select_best', 'zh').format(
@@ -305,7 +309,7 @@
         try:
             vlm = VLM()
             result = vlm.query(select_prompt, image_paths=image_paths, model=vlm_model)
-            logger.info(f"[{shot_id}] VLM选择结果: {result}")
+            logger.info(f"[{segment_id}] VLM选择结果: {result}")
 
             # 解析 JSON 结果
             import re
@@ -315,7 +319,7 @@
                 selected_idx = selected.get('selected_index', 0)
                 if 0 <= selected_idx < len(image_paths):
                     best_path = image_paths[selected_idx]
-                    logger.info(f"[{shot_id}] VLM选择第{selected_idx + 1}张作为最佳图片")
+                    logger.info(f"[{segment_id}] VLM选择第{selected_idx + 1}张作为最佳图片")
                     # 构建评估结果
                     best_eval = {
                         "score": selected.get('score', 5),
@@ -327,12 +331,12 @@
                     return best_path, best_eval
 
         except Exception as e:
-            logger.error(f"[{shot_id}] VLM选择最佳图片失败: {e}")
+            logger.error(f"[{segment_id}] VLM选择最佳图片失败: {e}")
 
         # 如果失败,返回第一个版本
         return image_paths[0], {"score": 5, "issues": [], "selected_by_vlm": False}
 
-    def _evaluate_with_vlm(self, image_path: str, shot: dict,
+    def _evaluate_with_vlm(self, image_path: str, segment: dict, plot: str, visual_prompt: str,
                           character_description: str = "", setting_description: str = "",
                           vlm_model: str = "qwen3.5-plus") -> dict:
         """使用 VLM 评估首帧参考图"""
@@ -341,8 +345,8 @@
             vlm = VLM()
 
             eval_prompt = load_prompt('reference', 'eval_first_frame', 'zh').format(
-                plot=shot.get('plot', ''),
-                visual_prompt=shot.get('visual_prompt', ''),
+                plot=plot,
+                visual_prompt=visual_prompt,
                 character_description=character_description,
                 setting_description=setting_description
             )
@@ -378,19 +382,22 @@
 
     # ─── 构建最终 payload ───
 
-    def _build_payload(self, sid: str, shots: list) -> dict:
+    def _build_payload(self, sid: str, segments: list) -> dict:
         """构建最终 payload"""
         scenes = []
-        for idx, shot in enumerate(shots, 1):
-            shot_id = shot['shot_id']
-            versions = self._list_versions(sid, shot_id)
+        for idx, seg in enumerate(segments, 1):
+            segment_id = seg.get('segment_id', f'seg_unk_{idx}')
+            versions = self._list_versions(sid, segment_id)
+            
+            shots_summary = " ".join([s.get('content', '') for s in seg.get('shots', [])])
+
             # status: 有图片=done, 无图片=pending(待生成)
             status = "done" if versions else "pending"
             scenes.append({
-                "id": shot_id,
-                "name": f"场景{shot['scene_number']}-镜头{shot['shot_number']}",
+                "id": segment_id,
+                "name": f"第{seg.get('episode_number', 1)}集-片段{seg.get('segment_number', idx)}",
                 "index": idx,
-                "description": shot.get('visual_prompt', ''),
+                "description": shots_summary[:50] + '...' if len(shots_summary) > 50 else shots_summary,
                 "selected": versions[-1] if versions else "",
                 "versions": versions,
                 "status": status,
@@ -403,15 +410,15 @@
             "stage_completed": True,
         }
 
-    def _update_scene2image(self, sid: str, shots: list, result_file: str,
+    def _update_scene2image(self, sid: str, segments: list, result_file: str,
                             first_frame_prompts: dict, selected_images: dict = None) -> None:
         """写回 scene2image 到结果文件
-        scene2image[shot_id] = {
+        scene2image[segment_id] = {
             local_path: 当前最新版本图片路径,
             prompt: 首帧图像提示词(阶段4生成),
-            plot: 原始分镜剧情描述(阶段3,供阶段5视频使用),
-            video_prompt: 原始分镜视觉描述(阶段3),
-            duration: 分镜时长,
+            plot: 原始分段剧情描述(阶段3拼接,供阶段5视频使用),
+            video_prompt: 原始分段视觉描述提示词(等同首帧提示词),
+            duration: 分段总时长,
         }
         """
         if selected_images is None:
@@ -420,23 +427,27 @@
         with open(result_file, 'r', encoding='utf-8') as f:
             res = json.load(f)
         scene_images = res.get(str(sid), {}).get('scene2image', {})
-        for shot in shots:
-            shot_id = shot['shot_id']
+        for seg in segments:
+            segment_id = seg.get('segment_id', '')
+            if not segment_id: continue
+
             # 优先使用实时传入的选定路径,否则寻找磁盘已有版本
-            selected = selected_images.get(shot_id)
+            selected = selected_images.get(segment_id)
             if not selected:
-                versions = self._list_versions(sid, shot_id)
+                versions = self._list_versions(sid, segment_id)
                 if versions:
                     selected = versions[-1]
             
             if selected:
-                scene_images[shot_id] = {
+                plot = " ".join([s.get('content', '') for s in seg.get('shots', [])])
+                scene_images[segment_id] = {
                     "local_path": selected,
-                    "prompt": first_frame_prompts.get(shot_id, shot.get('visual_prompt', '')),
-                    "plot": shot.get('plot', ''),
-                    "video_prompt": shot.get('visual_prompt', ''),
-                    "duration": shot.get('duration', 10),
+                    "prompt": first_frame_prompts.get(segment_id, plot[:50]),
+                    "plot": plot,
+                    "video_prompt": first_frame_prompts.get(segment_id, plot[:50]),
+                    "duration": seg.get('total_duration', 10),
                 }
+        res[str(sid)] = res.get(str(sid), {})
         res[str(sid)]['scene2image'] = scene_images
         with open(result_file, 'w', encoding='utf-8') as f:
             json.dump(res, f, indent=4, ensure_ascii=False)
@@ -455,7 +466,7 @@
         
         style = input_data.get("style", "anime")
         video_ratio = input_data.get("video_ratio", "16:9")
-        resolution = input_data.get("resolution", "1080P")
+        resolution = input_data.get("resolution", "4K")
         llm_model = input_data.get("llm_model", "") or settings.LLM_MODEL
         t2i = input_data.get("image_t2i_model", "") or settings.IMAGE_T2I_MODEL
         it2i = input_data.get("image_it2i_model", "") or settings.IMAGE_IT2I_MODEL
@@ -470,7 +481,15 @@
         concurrency = max(max_t2i, max_it2i)
         logger.info(f"[ReferenceAgent] 使用并发数={concurrency}")
 
-        result_file = os.path.join(settings.RESULT_DIR, 'script', f'script_{sid}.json')
+        # 读取会话数据
+        session_path = os.path.join('code/data/sessions', f'{sid}.json')
+        if not os.path.exists(session_path):
+            raise Exception(f"Session file not found: {session_path}")
+            
+        with open(session_path, 'r', encoding='utf-8') as f:
+            session_data = json.load(f)
+            
+        artifacts = session_data.get("artifacts", {})
 
         img_client = ImageClient(
             dashscope_api_key=settings.DASHSCOPE_API_KEY,
@@ -483,25 +502,22 @@
             ark_base_url=settings.ARK_BASE_URL,
         )
 
-        # 优先从 input_data (artifacts) 中获取分镜数据,如果没有再读原始文件
-        shots = []
-        if input_data and isinstance(input_data, dict) and "shots" in input_data:
-            shots = input_data["shots"]
-            logger.info(f"[ReferenceAgent] 使用来自 input_data 的 {len(shots)} 个分镜数据")
-        
-        if not shots:
-            # 备选:从结果文件读取
-            with open(result_file, 'r', encoding='utf-8') as f:
-                results = json.load(f)
-            story_data = results[str(sid)]
-            storyboard = story_data.get('storyboard', {})
-            shots = storyboard.get('shots', [])
-            logger.info(f"[ReferenceAgent] 使用来自结果文件的 {len(shots)} 个分镜数据")
+        episodes = artifacts.get('storyboard', {}).get('episodes', [])
+        if not episodes:
+            raise Exception("未找到分镜剧集数据,请先完成阶段3")
 
-        if not shots:
-            raise Exception("未找到分镜数据,请先完成阶段3")
+        segments = []
+        for ep in episodes:
+            for seg in ep.get("segments", []):
+                segments.append(seg)
+                
+        if not segments:
+            raise Exception("未找到分镜片段数据,请先完成阶段3")
 
-        script_json = story_data.get('script_json', {})
+        logger.info(f"[ReferenceAgent] 解析到 {len(segments)} 个拍摄片段")
+
+        script_json = artifacts.get('script_generation', {})
+        result_file = os.path.join('code/data/sessions', f'{sid}.json')
 
         # 判断中英文
         is_zh = any('\u4e00' <= c <= '\u9fff' for c in script_json.get("title", ""))
@@ -517,7 +533,7 @@
 
         asset_map = self._build_asset_map(sid)
 
-        # ═══ 介入:重新生成指定分镜 ═══
+        # ═══ 介入:重新生成指定分段 ═══
         if intervention:
             regen_scenes = intervention.get("regenerate_scenes", [])
 
@@ -525,11 +541,16 @@
                 self._report_progress("参考图", "重新生成中...", 2)
 
                 # 重新从 session JSON 文件读取最新的 storyboard 数据
-                with open(result_file, 'r', encoding='utf-8') as f:
+                with open(session_path, 'r', encoding='utf-8') as f:
                     fresh_data = json.load(f)
-                fresh_storyboard = fresh_data.get(str(sid), {}).get('storyboard', {})
-                fresh_shots = fresh_storyboard.get('shots', [])
-                fresh_shot_map = {s['shot_id']: s for s in fresh_shots}
+                fresh_artifacts = fresh_data.get('artifacts', {})
+                fresh_episodes = fresh_artifacts.get('storyboard', {}).get('episodes', [])
+                
+                fresh_segments = []
+                for ep in fresh_episodes:
+                    fresh_segments.extend(ep.get("segments", []))
+                    
+                fresh_segment_map = {s['segment_id']: s for s in fresh_segments}
 
                 llm = LLM()
 
@@ -539,64 +560,82 @@
                     total = len(regen_scenes)
                     done = 0
                     nonlocal selected_images
-                    # 每分镜5个步骤:准备(1)、生成(3)、完成(1)
-                    steps_per_shot = 5
-                    total_steps = total * steps_per_shot
+                    # 每片段5个步骤:准备(1)、生成(3)、完成(1)
+                    steps_per_segment = 5
+                    total_steps = total * steps_per_segment
 
                     def calc_pct_regen(step: int) -> int:
                         return min(2 + int(98 * step / total_steps), 100)
 
-                    # 从最新读取的 storyboard JSON 中获取 visual_prompt
-                    prompt_map = {}  # shot_id → first_frame_prompt
-                    for i, shot_id in enumerate(regen_scenes):
-                        shot = fresh_shot_map.get(shot_id, {})
-                        ff_prompt = shot.get('visual_prompt', '')
-                        prompt_map[shot_id] = ff_prompt
-                        logger.info(f"[{shot_id}] first-frame prompt (from JSON): {ff_prompt[:80]}...")
-                        self._report_progress("参考图", f"准备提示词: {shot_id}", calc_pct_regen(i * steps_per_shot + 1))
+                    # 根据最新的 Segment 生成对应的 visual_prompt
+                    prompt_map = {}  # segment_id → first_frame_prompt
+                    for i, segment_id in enumerate(regen_scenes):
+                        seg = fresh_segment_map.get(segment_id, {})
+                        
+                        plot = " ".join([s.get('content', '') for s in seg.get('shots', [])])
+                        char_desc, set_desc = self._get_descriptions(seg, char_id_map, setting_id_map, script_json)
+
+                        ff_prompt_tpl = load_prompt('reference', 'first_frame', 'zh' if is_zh else 'en')
+                        ff_prompt_resp = self._cancellable_query(
+                            llm,
+                            prompt=ff_prompt_tpl.format(
+                                plot=plot,
+                                character_description=char_desc,
+                                setting_description=set_desc
+                            ),
+                            model=llm_model
+                        )
+                        if hasattr(ff_prompt_resp, 'content'):
+                            ff_prompt = ff_prompt_resp.content.strip()
+                        else:
+                            ff_prompt = str(ff_prompt_resp).strip()
+                        prompt_map[segment_id] = ff_prompt
+                        
+                        logger.info(f"[{segment_id}] first-frame prompt: {ff_prompt[:80]}...")
+                        self._report_progress("参考图", f"准备提示词: {segment_id}", calc_pct_regen(i * steps_per_segment + 1))
 
                     # 并发生成图像
                     self._report_progress("参考图", "生成参考图...", calc_pct_regen(total * 2))
                     with ThreadPoolExecutor(max_workers=concurrency) as executor:
                         futs = {}
-                        for shot_id in regen_scenes:
-                            shot = fresh_shot_map.get(shot_id, {})
-                            refs = self._collect_refs(shot, asset_map, char_id_map, setting_id_map)
+                        for segment_id in regen_scenes:
+                            seg = fresh_segment_map.get(segment_id, {})
+                            refs = self._collect_refs(seg, asset_map, char_id_map, setting_id_map)
                             char_desc, set_desc = self._get_descriptions(
-                                shot, char_id_map, setting_id_map, script_json
+                                seg, char_id_map, setting_id_map, script_json
                             )
                             fut = executor.submit(
                                 self._generate_one, img_client, sid,
-                                shot, prompt_map[shot_id], refs,
+                                seg, prompt_map[segment_id], refs,
                                 style, it2i, t2i, video_ratio, resolution, vlm_model,
                                 character_description=char_desc, setting_description=set_desc
                             )
-                            futs[fut] = shot_id
+                            futs[fut] = segment_id
                         for fut in as_completed(futs):
-                            shot_id_done = futs[fut]
+                            segment_id_done = futs[fut]
                             try:
                                 _, result_path, eval_result = fut.result()
                             except Exception as e:
-                                logger.error(f"Regen future error for {shot_id_done}: {e}")
+                                logger.error(f"Regen future error for {segment_id_done}: {e}")
                                 result_path = None
                             done += 1
-                            step = done * steps_per_shot
+                            step = done * steps_per_segment
                             pct = calc_pct_regen(step)
                             if result_path:
-                                selected_images[shot_id_done] = result_path
-                                versions = self._list_versions(sid, shot_id_done)
-                                self._report_progress("参考图", f"完成: {shot_id_done}", pct, data={
+                                selected_images[segment_id_done] = result_path
+                                versions = self._list_versions(sid, segment_id_done)
+                                self._report_progress("参考图", f"完成: {segment_id_done}", pct, data={
                                     "asset_complete": {
-                                        "type": "scenes", "id": shot_id_done,
+                                        "type": "scenes", "id": segment_id_done,
                                         "status": "done",
                                         "selected": result_path,
                                         "versions": versions,
                                     }
                                 })
                             else:
-                                self._report_progress("参考图", f"失败: {shot_id_done}", pct, data={
+                                self._report_progress("参考图", f"失败: {segment_id_done}", pct, data={
                                     "asset_complete": {
-                                        "type": "scenes", "id": shot_id_done,
+                                        "type": "scenes", "id": segment_id_done,
                                         "status": "failed",
                                         "selected": "", "versions": [],
                                     }
@@ -613,39 +652,39 @@
                 await loop.run_in_executor(None, regen_run)
 
                 # 重新生成后更新 scene2image(同步最新版本信息)
-                self._update_scene2image(sid, fresh_shots, result_file, {}, selected_images)
+                self._update_scene2image(sid, fresh_segments, result_file, prompt_map, selected_images)
 
                 self._report_progress("参考图", "完成", 100)
-                return self._build_payload(sid, fresh_shots)
+                return self._build_payload(sid, fresh_segments)
 
         # ═══ 正常流程:全量生成 ═══
         self._report_progress("参考图", "加载分镜数据...", 5)
 
         # 发送预览列表
-        preview = self._build_preview(sid, shots)
+        preview = self._build_preview(sid, segments)
         self._report_progress("参考图", "加载分镜列表", 8, data={"assets_preview": {"scenes": preview}})
 
         llm = LLM()
 
         def run():
             # 筛选需要生成的(跳过已有图的)
-            pending_shots = []
+            pending_segments = []
             selected_images = {}
-            for shot in shots:
-                shot_id = shot['shot_id']
-                existing = self._list_versions(sid, shot_id)
+            for seg in segments:
+                segment_id = seg['segment_id']
+                existing = self._list_versions(sid, segment_id)
                 if existing:
                     continue
-                pending_shots.append(shot)
+                pending_segments.append(seg)
 
-            if not pending_shots:
+            if not pending_segments:
                 self._report_progress("参考图", "所有分镜图已存在", 95)
                 return
 
-            total = len(pending_shots)
+            total = len(pending_segments)
             # 每分镜5个步骤:准备(1)、生成(3)、完成(1)
-            steps_per_shot = 5
-            total_steps = total * steps_per_shot + 1  # +1 是加载数据步骤
+            steps_per_segment = 5
+            total_steps = total * steps_per_segment + 1  # +1 是加载数据步骤
 
             def calc_pct(step: int) -> int:
                 """根据步骤计算进度百分比"""
@@ -653,91 +692,91 @@
 
             done = 0
 
-            # 步骤1:加载数据
-            self._report_progress("参考图", "准备生成...", calc_pct(0))
-
-            # 步骤2-6(每分镜):准备提示词
-            first_frame_prompts = {}  # shot_id -> prompt
-            style = input_data.get('video_style', '')
-            for i, shot in enumerate(pending_shots):
-                shot_id = shot['shot_id']
-                visual_prompt = shot.get('visual_prompt', '')
-                
-                # Load the new translation/style prompt template
-                prompt_text = load_prompt('reference', "first_frame", 'zh' if is_zh else 'en').format(
-                    visual_prompt=visual_prompt, 
-                    style=style
-                )
-                
-                # Call LLM to translate and append style tags
-                try:
-                    ff_prompt_resp = llm.query(prompt_text, max_tokens=1000, temperature=0.7)
-                    if hasattr(ff_prompt_resp, 'content'):
-                        ff_prompt = ff_prompt_resp.content.strip()
-                    else:
-                        ff_prompt = str(ff_prompt_resp).strip()
-                except Exception as e:
-                    logger.error(f"Error generating first-frame prompt for {shot_id}: {e}")
-                    ff_prompt = visual_prompt  # Fallback to pure visual prompt
-                
-                first_frame_prompts[shot_id] = ff_prompt
-                logger.info(f"[{shot_id}] first-frame prompt: {ff_prompt[:80]}...")
-                step = i * steps_per_shot + 1
-                self._report_progress("参考图", f"准备提示词: {shot_id}", calc_pct(step))
-
-            # 步骤7+(每分镜3步):并发生成图像
-            self._report_progress("参考图", "生成参考图...", calc_pct(total * 2))
-            tasks = []
-            for shot in pending_shots:
-                shot_id = shot['shot_id']
-                refs = self._collect_refs(shot, asset_map, char_id_map, setting_id_map)
-                char_desc, set_desc = self._get_descriptions(
-                    shot, char_id_map, setting_id_map, script_json
-                )
-                tasks.append((shot, first_frame_prompts[shot_id], refs, char_desc, set_desc))
-
+            # 步骤2-6(每片段):流式生成提示词并立即开始图像生成
+            self._report_progress("参考图", "开始生成...", calc_pct(0))
+            
+            first_frame_prompts = {}  # 用于最后写回结果文件
+            
             with ThreadPoolExecutor(max_workers=concurrency) as executor:
                 futs = {}
-                for shot, ff_prompt, refs, char_desc, set_desc in tasks:
-                    shot_id = shot['shot_id']
+                done = 0
+                
+                for i, seg in enumerate(pending_segments):
+                    segment_id = seg['segment_id']
+                    
+                    # 1. 准备该片段的视觉提示词
+                    plot = " ".join([s.get('content', '') for s in seg.get('shots', [])])
+                    char_desc, set_desc = self._get_descriptions(seg, char_id_map, setting_id_map, script_json)
+                    ff_prompt_tpl = load_prompt('reference', "first_frame", 'zh' if is_zh else 'en')
+                    
+                    try:
+                        ff_prompt_resp = self._cancellable_query(
+                            llm,
+                            prompt=ff_prompt_tpl.format(
+                                plot=plot,
+                                character_description=char_desc,
+                                setting_description=set_desc
+                            ),
+                            model=llm_model
+                        )
+                        if hasattr(ff_prompt_resp, 'content'):
+                            ff_prompt = ff_prompt_resp.content.strip()
+                        else:
+                            ff_prompt = str(ff_prompt_resp).strip()
+                    except Exception as e:
+                        logger.error(f"Error generating first-frame prompt for {segment_id}: {e}")
+                        ff_prompt = plot[:200]
+                    
+                    first_frame_prompts[segment_id] = ff_prompt
+                    logger.info(f"[{segment_id}] Prompt ready, starting image generation...")
+
+                    # 2. 立即提交图像生成任务,不再等待其他片段的提示词
+                    refs = self._collect_refs(seg, asset_map, char_id_map, setting_id_map)
                     fut = executor.submit(
                         self._generate_one, img_client, sid,
-                        shot, ff_prompt, refs,
+                        seg, ff_prompt, refs,
                         style, it2i, t2i, video_ratio, resolution, vlm_model,
                         character_description=char_desc, setting_description=set_desc
                     )
-                    futs[fut] = shot_id
+                    futs[fut] = segment_id
+                    
+                    # 报告进度(提交任务也算一点进度)
+                    self._report_progress("参考图", f"正在生成: {segment_id}", calc_pct(i * steps_per_segment))
+
+                # 3. 等待所有任务完成
                 cancelled = False
                 for fut in as_completed(futs):
-                    shot_id_done = futs[fut]
+                    segment_id_done = futs[fut]
                     try:
                         _, result_path, eval_result = fut.result()
                     except Exception as e:
-                        logger.error(f"Image future error for {shot_id_done}: {e}")
+                        logger.error(f"Image future error for {segment_id_done}: {e}")
                         result_path = None
+                    
                     done += 1
-                    # 每个分镜完成时更新进度
-                    step = done * steps_per_shot
+                    step = done * steps_per_segment
                     pct = calc_pct(step)
+                    
                     if result_path:
-                        selected_images[shot_id_done] = result_path
-                        versions = self._list_versions(sid, shot_id_done)
-                        self._report_progress("参考图", f"完成: {shot_id_done}", pct, data={
+                        selected_images[segment_id_done] = result_path
+                        versions = self._list_versions(sid, segment_id_done)
+                        self._report_progress("参考图", f"完成: {segment_id_done}", pct, data={
                             "asset_complete": {
-                                "type": "scenes", "id": shot_id_done,
+                                "type": "scenes", "id": segment_id_done,
                                 "status": "done",
                                 "selected": result_path,
                                 "versions": versions,
                             }
                         })
                     else:
-                        self._report_progress("参考图", f"失败: {shot_id_done}", pct, data={
+                        self._report_progress("参考图", f"失败: {segment_id_done}", pct, data={
                             "asset_complete": {
-                                "type": "scenes", "id": shot_id_done,
+                                "type": "scenes", "id": segment_id_done,
                                 "status": "failed",
                                 "selected": "", "versions": [],
                             }
                         })
+                    
                     # 检查取消
                     if self.cancellation_check and self.cancellation_check():
                         logger.info("ReferenceGeneratorAgent: 用户取消,停止等待剩余任务")
@@ -753,17 +792,17 @@
                 self._report_progress("参考图", "保存结果...", 96)
 
             # 写回结果文件
-            self._update_scene2image(sid, shots, result_file, first_frame_prompts, selected_images)
+            self._update_scene2image(sid, segments, result_file, first_frame_prompts, selected_images)
 
         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("ReferenceGeneratorAgent: 用户取消,返回已完成���部分结果")
+                logger.info("ReferenceGeneratorAgent: 用户取消,返回已完成部分结果")
                 self._report_progress("参考图", "已取消(保留已完成图片)", 100)
-                return self._build_payload(sid, shots)
+                return self._build_payload(sid, segments)
             raise
 
         self._report_progress("参考图", "完成", 100)
-        return self._build_payload(sid, shots)
+        return self._build_payload(sid, segments)
diff --git a/aigc-director/aigc-claw/backend/core/agents/script_agent.py b/aigc-director/aigc-claw/backend/core/agents/script_agent.py
index ec1fc72..e103bbd 100644
--- a/aigc-director/aigc-claw/backend/core/agents/script_agent.py
+++ b/aigc-director/aigc-claw/backend/core/agents/script_agent.py
@@ -1,7 +1,6 @@
 # -*- coding: utf-8 -*-
 """
-阶段1: 编剧智能体 - 多轮LLM交互生成结构化剧本JSON
-流程: Logline → 节拍表(4幕) → 分场大纲(逐幕) → JSON结构化提取(带校验重试)
+阶段1: 编剧智能体 (直出一遍过版本)
 """
 
 import os
@@ -9,47 +8,32 @@
 import json
 import asyncio
 import logging
-import string
-import random
+from functools import partial
 from datetime import datetime, timezone
 from typing import Any, Optional, Dict
 
 from prompts.loader import load_prompt_with_fallback
+from .base_agent import AgentInterface
+
+logger = logging.getLogger(__name__)
 
 def _get_script_prompt(name: str, lang: str = "zh") -> str:
     return load_prompt_with_fallback("script", name, lang, "zh")
 
-from .base_agent import AgentInterface
-
-# 导入提示词加载器
-from prompts.loader import load_prompt
-
-logger = logging.getLogger(__name__)
-
-ACT_NAMES_ZH = {1: "激励事件", 2: "进入新世界", 3: "灵魂黑夜", 4: "高潮决战"}
-ACT_NAMES_EN = {1: "Inciting Incident", 2: "Break into Two", 3: "Dark Night of the Soul", 4: "Finale"}
-
 class ScriptWriterAgent(AgentInterface):
-    """编剧智能体:多轮LLM交互 → 结构化剧本JSON"""
-
     def __init__(self):
         super().__init__(name="ScriptWriter")
 
-    # ─── JSON 提取 ───
-
     @staticmethod
     def _extract_json_from_text(text: str) -> Optional[dict]:
-        """从LLM输出中提取JSON对象"""
         text = text.strip()
         text = re.sub(r'^```(?:json)?\s*', '', text)
         text = re.sub(r'\s*```$', '', text)
         text = text.strip()
-
         try:
             return json.loads(text)
         except json.JSONDecodeError:
             pass
-
         start = text.find('{')
         end = text.rfind('}')
         if start != -1 and end != -1 and end > start:
@@ -59,150 +43,22 @@
                 pass
         return None
 
-    @staticmethod
-    def _extract_json_array_from_text(text: str) -> Optional[list]:
-        """从LLM输出中提取JSON数组"""
-        text = text.strip()
-        # 去除 markdown 代码块标记(支持多行)
-        text = re.sub(r'```(?:json)?\s*\n?', '', text)
-        text = text.strip()
-
-        try:
-            result = json.loads(text)
-            if isinstance(result, list):
-                return result
-            # LLM 有时返回对象而非数组,尝试包装
-            if isinstance(result, dict):
-                return [result]
-        except json.JSONDecodeError:
-            pass
-
-        start = text.find('[')
-        end = text.rfind(']')
-        if start != -1 and end != -1 and end > start:
-            try:
-                result = json.loads(text[start:end + 1])
-                if isinstance(result, list):
-                    return result
-            except json.JSONDecodeError:
-                pass
-
-        # 尝试匹配多个独立 JSON 对象
-        objects = []
-        for m in re.finditer(r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}', text):
-            try:
-                obj = json.loads(m.group())
-                if isinstance(obj, dict) and 'logline' in obj:
-                    objects.append(obj)
-            except json.JSONDecodeError:
-                continue
-        if objects:
-            return objects
-
-        return None
-
-    @staticmethod
-    def _gen_id(prefix: str = "char") -> str:
-        return f"{prefix}_{''.join(random.choices(string.ascii_lowercase + string.digits, k=8))}"
-
-    # ─── 保存结果 ───
+    def _gen_id(self, prefix: str = "char") -> str:
+        import uuid
+        return f"{prefix}_{uuid.uuid4().hex[:6]}"
 
     def _save_result(self, json_data: dict, sid: str, is_zh: bool):
-        """保存结构化剧本JSON到结果文件"""
-        from config import settings
-        script_dir = os.path.join(settings.RESULT_DIR, 'script')
-        os.makedirs(script_dir, exist_ok=True)
-
-        result_file = os.path.join(script_dir, f'script_{sid}.json')
-        results = {}
-        if os.path.exists(result_file) and os.path.getsize(result_file) > 0:
-            with open(result_file, 'r', encoding='utf-8') as f:
-                results = json.load(f)
-
-        results.setdefault(str(sid), {})['script_json'] = json_data
-        with open(result_file, 'w', encoding='utf-8') as f:
-            json.dump(results, f, indent=4, ensure_ascii=False)
+        from config import settings as app_settings
+        os.makedirs(os.path.join(app_settings.RESULT_DIR, 'script'), exist_ok=True)
+        out_path = os.path.join(app_settings.RESULT_DIR, 'script', f'{sid}.json')
+        with open(out_path, 'w', encoding='utf-8') as f:
+            json.dump(json_data, f, ensure_ascii=False, indent=2)
+        logger.info(f"[ScriptWriter] script saved to {out_path}")
 
     def _save_progress(self, sid: str, phase: str, data: dict):
-        """保存剧本生成的中间进度状态到结果文件"""
-        from config import settings
-        script_dir = os.path.join(settings.RESULT_DIR, 'script')
-        os.makedirs(script_dir, exist_ok=True)
-
-        result_file = os.path.join(script_dir, f'script_{sid}.json')
-        results = {}
-        if os.path.exists(result_file) and os.path.getsize(result_file) > 0:
-            with open(result_file, 'r', encoding='utf-8') as f:
-                results = json.load(f)
-
-        # 初始化 progress 字段
-        results.setdefault(str(sid), {}).setdefault('progress', {})
-
-        # 保存当前阶段信息
-        results[str(sid)]['progress']['current_phase'] = phase
-        results[str(sid)]['progress']['updated_at'] = datetime.now(timezone.utc).isoformat()
-
-        # 根据阶段保存对应的数据
-        if phase == 'logline_check':
-            # 创意检查结果
-            results[str(sid)]['progress']['idea_analyzed'] = data.get('idea_analyzed', False)
-            results[str(sid)]['progress']['logline_extracted'] = data.get('logline_summary')
-        elif phase == 'logline_generation':
-            # 生成的候选 logline
-            results[str(sid)]['progress']['logline_options'] = data.get('logline_options', [])
-        elif phase == 'logline_confirmed':
-            # 用户选择的 logline
-            results[str(sid)]['progress']['selected_logline'] = data.get('selected_logline')
-        elif phase == 'mode_selection':
-            # 用户选择的模式
-            results[str(sid)]['progress']['selected_mode'] = data.get('selected_mode')
-        elif phase == 'script_generation':
-            # 完整剧本已生成
-            results[str(sid)]['progress']['script_generated'] = True
-            results[str(sid)]['progress']['title'] = data.get('title')
-
-        with open(result_file, 'w', encoding='utf-8') as f:
-            json.dump(results, f, indent=4, ensure_ascii=False)
-
-    # ─── 核心流程 ───
+        pass
 
     async def process(self, input_data: Any, intervention: Optional[Dict] = None) -> Dict:
-
-        # 检查当前阶段,避免重复生成 logline
-        current_phase = input_data.get("phase", "")
-        selected_logline = input_data.get("selected_logline")
-        selected_mode = input_data.get("selected_mode")
-
-        # 如果已选择模式,直接生成剧本
-        if selected_mode:
-            # 如果 selected_logline 是索引(数字),需要转换为 logline 对象
-            if isinstance(selected_logline, int):
-                logline_options = input_data.get("logline_options", [])
-                if 0 <= selected_logline < len(logline_options):
-                    logline_data = logline_options[selected_logline]
-                else:
-                    logline_data = {}
-            else:
-                logline_data = selected_logline if isinstance(selected_logline, dict) else {}
-
-            if selected_mode == "micro":
-                return await self._phase_micro_script_gen(input_data, logline_data)
-            else:
-                return await self._phase_script_gen(input_data, logline_data)
-
-        # 如果已选择 logline 但未选择模式,返回模式选择
-        if selected_logline and current_phase == "mode_selection":
-            return {
-                "payload": {
-                    "phase": "mode_selection",
-                    "selected_logline": selected_logline,
-                    "session_id": input_data.get("session_id", ""),
-                },
-                "requires_intervention": True,
-                "openclaw_hint": "用户已选择情节,需要选择拍摄模式(电影模式4幕/微电影模式1幕)。请展示给用户并等待用户选择。",
-            }
-
-        # (A) 用户介入修改最终剧本
         if intervention and "modified_script" in intervention:
             modified = intervention["modified_script"]
             sid = input_data.get("session_id", "")
@@ -213,835 +69,103 @@
             self._save_result(modified, sid, is_zh)
             return {"payload": modified, "requires_intervention": False, "stage_completed": True}
 
-        # (B1) 用户选择了创作模式 → 根据模式生成剧本
-        if intervention and "selected_mode" in intervention:
-            selected = input_data.get("selected_logline", {})
-            mode = intervention["selected_mode"]
+        async def run_logic():
+            idea = input_data.get("idea", "")
             sid = input_data.get("session_id", "")
+            style = input_data.get("style", "anime")
+            llm_model = input_data.get("llm_model", "qwen3.5-plus")
+            web_search = input_data.get("web_search", False)
+            is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
 
-            # 如果 selected_logline 是索引(数字),转换为对应的 logline 对象
-            if isinstance(selected, int):
-                logline_options = input_data.get("logline_options", [])
-                if 0 <= selected < len(logline_options):
-                    logline_data = logline_options[selected]
-                else:
-                    logline_data = {}
-            else:
-                logline_data = selected if isinstance(selected, dict) else {}
-
-            # 保存进度状态
-            self._save_progress(sid, "mode_selection", {
-                "selected_mode": mode
-            })
-
-            if mode == "micro":
-                return await self._phase_micro_script_gen(input_data, logline_data)
-            else:
-                return await self._phase_script_gen(input_data, logline_data)
-
-        # (B2) 用户选择了一个 Logline → 显示模式选择
-        if intervention and "selected_logline" in intervention:
-            selected = intervention["selected_logline"]
-            sid = input_data.get("session_id", "")
-
-            # 如果 selected_logline 是索引(数字),转换为对应的 logline 对象
-            if isinstance(selected, int):
-                logline_options = input_data.get("logline_options", [])
-                if 0 <= selected < len(logline_options):
-                    logline_data = logline_options[selected]
-                else:
-                    logline_data = {}
-            else:
-                logline_data = selected if isinstance(selected, dict) else {}
-
-            # 保存进度状态
-            self._save_progress(sid, "logline_confirmed", {
-                "selected_logline": logline_data
-            })
-
-            return {
-                "payload": {
-                    "phase": "mode_selection",
-                    "selected_logline": logline_data,
-                    "session_id": sid,
-                },
-                "requires_intervention": True,
-                "openclaw_hint": "用户已选择情节,需要选择拍摄模式(电影模式4幕/微电影模式1幕)。请展示给用户并等待用户选择。",
-            }
-
-        # 首次运行:自动判断是直接提取 logline 还是进入扩写
-        auto_mode = input_data.get("auto_mode", False)
-
-        # 代理(自动)模式:跳过 Logline 选择,直接生成剧本
-        if auto_mode:
-            return await self._phase_direct(input_data)
-
-        # 自动判断:创意足够则提取 logline,否则自动扩写生成 3 个选项
-        return await self._phase_logline_check(input_data)
-
-    # ─── Phase 1A: 生成 3 个 Logline 方案 ───
-
-    async def _phase_logline_gen(self, input_data: Dict) -> Dict:
-        idea = input_data.get("idea", "")
-        sid = input_data.get("session_id", "")
-        llm_model = input_data.get("llm_model", "qwen3.5-plus")
-        web_search = input_data.get("web_search", False)
-        is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
-
-        def run():
+            from config import settings as app_settings
             from tool.llm_client import LLM
+            os.makedirs(app_settings.TEMP_DIR, exist_ok=True)
             llm = LLM()
-            self._report_progress("剧本生成", "正在生成 Logline 方案...", 5)
-            prompt = _get_script_prompt("logline_generate", "zh" if is_zh else "en").format(idea=idea)
 
-            for attempt in range(3):
+            def _log_progress(pct, msg):
+                self._report_progress("剧本生成", msg, pct)
+                logger.info(f"[{pct}%] {msg}")
+
+            # 1. Generate full script
+            _log_progress(10, "正在生成完整剧本文本...")
+            prompt_name = "generate_script"
+            prompt = _get_script_prompt(prompt_name, "zh" if is_zh else "en").format(idea=idea, style=style)
+            
+            loop = asyncio.get_running_loop()
+            full_script_text = await loop.run_in_executor(None, self._cancellable_query, llm, prompt, [], llm_model, True, sid, web_search)
+            logger.info(f"[ScriptWriter] Full script generated ({len(full_script_text)} chars)")
+            _log_progress(40, "原稿生成完成,正在提取元数据...")
+
+            # 2. Extract meta data -> total_episodes, characters, settings
+            meta_prompt = _get_script_prompt("meta_extract", "zh" if is_zh else "en").format(script_text=full_script_text, outline=full_script_text)
+            meta_raw = await loop.run_in_executor(None, self._cancellable_query, llm, meta_prompt, [], llm_model, True, sid, web_search)
+            meta_data = self._extract_json_from_text(meta_raw) or {}
+            
+            all_characters = meta_data.get("characters", [])
+            all_settings = meta_data.get("settings", [])
+            for c in all_characters:
+                c["character_id"] = c.get("character_id") or self._gen_id("char")
+            for s in all_settings:
+                s["setting_id"] = s.get("setting_id") or self._gen_id("set")
+
+            asset_chars_str = json.dumps([{"name": c.get("name"), "description": c.get("description"), "role": c.get("role")} for c in all_characters], ensure_ascii=False)
+            asset_sets_str = json.dumps([{"name": s.get("name"), "description": s.get("description")} for s in all_settings], ensure_ascii=False)
+
+            _log_progress(50, "正在解析各集数据...")
+            
+            total_eps = meta_data.get("total_episodes", 4)
+            if not isinstance(total_eps, int) or total_eps < 1:
+                total_eps = 1
+                
+            async def extract_one_episode(ep_num):
                 self._check_cancel()
-                raw = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid, web_search=web_search)
-                logger.info(f"[ScriptWriter] Logline gen attempt {attempt + 1}, raw output ({len(raw)} chars): {raw[:500]}")
-                options = self._extract_json_array_from_text(raw)
-                if options and len(options) > 0:
-                    # 确保每个选项包含必要字段
-                    required = {"logline", "who", "goal", "conflict", "twist", "theme"}
-                    valid = [o for o in options if isinstance(o, dict) and required.issubset(o.keys())]
-                    if valid:
-                        self._report_progress("剧本生成", "Logline 方案已生成", 20)
-                        return valid[:3]
+                
+                extract_prompt = _get_script_prompt("act_extract", "zh" if is_zh else "en").format(
+                    act_number=ep_num, scene_start=1, script_text=full_script_text, outline=full_script_text,
+                    asset_characters=asset_chars_str, asset_settings=asset_sets_str
+                )
+                
+                # 并行调用 LLM(使用异步包装)
+                loop = asyncio.get_running_loop()
+                raw_act = await loop.run_in_executor(None, self._cancellable_query, llm, extract_prompt, [], llm_model, True, sid, web_search)
+                parsed_act = self._extract_json_from_text(raw_act) or {}
 
-                logger.warning(f"[ScriptWriter] Logline gen attempt {attempt + 1}: parse failed")
-                if is_zh:
-                    prompt = (
-                        "上次输出格式不正确,请严格按要求重新输出。"
-                        "必须输出纯JSON数组,不要用```包裹,不要有任何多余文字。\n\n"
-                        + (_get_script_prompt("logline_generate", "zh")).format(idea=idea)
-                    )
-                else:
-                    prompt = (
-                        "Previous output format was incorrect. Please try again. "
-                        "Output ONLY a raw JSON array, no code blocks, no extra text.\n\n"
-                        + (_get_script_prompt("logline_generate", "en")).format(idea=idea)
-                    )
+                return ep_num, {
+                    "episode_number": ep_num,
+                    "act_title": parsed_act.get("episode_title") or parsed_act.get("act_title") or f"第{ep_num}集",
+                    "content": parsed_act.get("episode_content") or parsed_act.get("content", "")
+                }
 
-            raise Exception("Logline 生成失败:多次尝试均无法解析输出")
+            # 创建并发任务
+            tasks = [extract_one_episode(i) for i in range(1, total_eps + 1)]
+            results = await asyncio.gather(*tasks)
 
-        loop = asyncio.get_running_loop()
-        options = await loop.run_in_executor(None, run)
+            # 保持原始顺序
+            results.sort(key=lambda x: x[0])
+            all_episodes = [r[1] for r in results]
 
-        # 保存进度状态
-        self._save_progress(sid, "logline_generation", {
-            "logline_options": options
-        })
-
-        return {
-            "payload": {
-                "phase": "logline_selection",
-                "logline_options": options,
+            final_json = {
+                "project_id": f"proj_{sid}",
                 "session_id": sid,
-            },
-            "requires_intervention": True,
-            "openclaw_hint": "生成了多个情节候选(logline),需要用户选择。请展示给用户并等待用户选择。",
-        }
-
-    # ─── Phase 1B: 检测输入是否可提取 Logline ───
-
-    async def _phase_logline_check(self, input_data: Dict) -> Dict:
-        idea = input_data.get("idea", "")
-        sid = input_data.get("session_id", "")
-        llm_model = input_data.get("llm_model", "qwen3.5-plus")
-        web_search = input_data.get("web_search", False)
-        is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
-
-        def run():
-            from tool.llm_client import LLM
-            llm = LLM()
-            self._report_progress("剧本生成", "分析创意文本...", 5)
-            check_prompt = _get_script_prompt("logline_check", "zh" if is_zh else "en").format(idea=idea)
-            answer = self._cancellable_query(llm, check_prompt, model=llm_model, task_id=sid, web_search=web_search).strip()
-
-            if answer.lower().startswith("yes"):
-                self._report_progress("剧本生成", "提取 Logline...", 10)
-                extract_prompt = _get_script_prompt("logline_extract", "zh" if is_zh else "en").format(idea=idea)
-                raw = self._cancellable_query(llm, extract_prompt, model=llm_model, task_id=sid, web_search=web_search)
-                logger.info(f"[ScriptWriter] Logline extract raw ({len(raw)} chars): {raw[:500]}")
-                logline_data = self._extract_json_from_text(raw)
-                if logline_data and isinstance(logline_data, dict) and 'logline' in logline_data:
-                    self._report_progress("剧本生成", "Logline 提取完成", 20)
-                    return {"phase": "logline_confirm", "logline_summary": logline_data}
-
-            return {"phase": "suggest_expand"}
-
-        loop = asyncio.get_running_loop()
-        result = await loop.run_in_executor(None, run)
-        result["session_id"] = sid
-
-        # 如果创意不够,自动进入扩写阶段,生成 3 个 logline 供选择
-        if result.get("phase") == "suggest_expand":
-            return await self._phase_logline_gen(input_data)
-
-        # 保存进度状态
-        phase = result.get("phase", "logline_check")
-        self._save_progress(sid, "logline_check", {
-            "idea_analyzed": phase == "logline_confirm",
-            "logline_summary": result.get("logline_summary")
-        })
-
-        return {
-            "payload": result,
-            "requires_intervention": True,
-            "openclaw_hint": "已提取情节概要,需要用户确认。请展示给用户并等待用户确认。",
-        }
-
-    # ─── Phase 2: 根据选定 Logline 生成完整剧本 ───
-
-    async def _phase_script_gen(self, input_data: Dict, logline_data: Dict) -> Dict:
-        idea = input_data.get("idea", "")
-        sid = input_data.get("session_id", "")
-        style = input_data.get("style", "anime")
-        llm_model = input_data.get("llm_model", "qwen3.5-plus")
-        web_search = input_data.get("web_search", False)
-        is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
-
-        # 用 Logline 六要素构建丰富的故事概要
-        if is_zh:
-            draft = (
-                f"故事核心 Logline:{logline_data.get('logline', '')}\n"
-                f"主角:{logline_data.get('who', '')}\n"
-                f"目标:{logline_data.get('goal', '')}\n"
-                f"核心障碍:{logline_data.get('conflict', '')}\n"
-                f"反转:{logline_data.get('twist', '')}\n"
-                f"主题:{logline_data.get('theme', '')}\n\n"
-                f"原始灵感:{idea}"
-            )
-        else:
-            draft = (
-                f"Story Logline: {logline_data.get('logline', '')}\n"
-                f"Protagonist: {logline_data.get('who', '')}\n"
-                f"Goal: {logline_data.get('goal', '')}\n"
-                f"Core Conflict: {logline_data.get('conflict', '')}\n"
-                f"Twist: {logline_data.get('twist', '')}\n"
-                f"Theme: {logline_data.get('theme', '')}\n\n"
-                f"Original idea: {idea}"
-            )
-
-        def run():
-            from config import settings as app_settings
-            from tool.llm_client import LLM
-
-            os.makedirs(app_settings.TEMP_DIR, exist_ok=True)
-            os.makedirs(os.path.join(app_settings.RESULT_DIR, 'script'), exist_ok=True)
-
-            llm = LLM()
-
-            # 逐幕生成节拍表 + 分场大纲 + 结构化提取
-            json_data = self._generate_script_incremental(
-                llm, draft, idea, style, llm_model, sid, is_zh, web_search=web_search, pct_start=20
-            )
-
-            # 补充元数据
-            json_data.setdefault("project_id", f"proj_{sid}")
-            json_data.setdefault("version", 1)
-            json_data["created_at"] = datetime.now(timezone.utc).isoformat()
-            json_data["metadata"] = {
-                "generation_model": llm_model,
-                "generation_prompt": idea,
+                "version": 1,
+                "created_at": datetime.now(timezone.utc).isoformat(),
+                "metadata": {
+                    "generation_model": llm_model,
+                    "generation_prompt": idea,
+                    "original_text": full_script_text
+                },
+                "title": meta_data.get("title", "Generated Script"),
+                "logline": meta_data.get("logline", ""),
+                "genre": meta_data.get("genre", []),
+                "mood": meta_data.get("mood", ""),
+                "characters": all_characters,
+                "settings": all_settings,
+                "episodes": all_episodes
             }
-            json_data["session_id"] = sid
-            json_data["logline_data"] = logline_data
+            
+            self._save_result(final_json, sid, is_zh)
+            _log_progress(100, "剧本结构化解析完成!")
+            return final_json
 
-            self._save_result(json_data, sid, is_zh)
-            # 保存进度状态
-            self._save_progress(sid, "script_generation", {
-                "title": json_data.get("title")
-            })
-            self._report_progress("剧本生成", "完成", 100)
-            return json_data
-
-        loop = asyncio.get_running_loop()
-        script_json = await loop.run_in_executor(None, run)
-
-        # 保存进度状态
-        self._save_progress(sid, "script_generation", {
-            "title": script_json.get("title")
-        })
-
-        return {
-            "payload": script_json,
-            "requires_intervention": False,
-            "stage_completed": True,  # 明确标记阶段完成
-            "openclaw_hint": "剧本生成完成。",
-        }
-
-    # ─── Phase 2-Micro: 微电影模式 - 根据选定 Logline 生成紧凑单幕剧本 ───
-
-    async def _phase_micro_script_gen(self, input_data: Dict, logline_data: Dict) -> Dict:
-        idea = input_data.get("idea", "")
-        sid = input_data.get("session_id", "")
-        style = input_data.get("style", "anime")
-        llm_model = input_data.get("llm_model", "qwen3.5-plus")
-        web_search = input_data.get("web_search", False)
-        is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
-
-        # 用 Logline 六要素构建故事概要
-        if is_zh:
-            draft = (
-                f"故事核心 Logline:{logline_data.get('logline', '')}\n"
-                f"主角:{logline_data.get('who', '')}\n"
-                f"目标:{logline_data.get('goal', '')}\n"
-                f"核心障碍:{logline_data.get('conflict', '')}\n"
-                f"反转:{logline_data.get('twist', '')}\n"
-                f"主题:{logline_data.get('theme', '')}\n\n"
-                f"原始灵感:{idea}"
-            )
-        else:
-            draft = (
-                f"Story Logline: {logline_data.get('logline', '')}\n"
-                f"Protagonist: {logline_data.get('who', '')}\n"
-                f"Goal: {logline_data.get('goal', '')}\n"
-                f"Core Conflict: {logline_data.get('conflict', '')}\n"
-                f"Twist: {logline_data.get('twist', '')}\n"
-                f"Theme: {logline_data.get('theme', '')}\n\n"
-                f"Original idea: {idea}"
-            )
-
-        def run():
-            from config import settings as app_settings
-            from tool.llm_client import LLM
-
-            os.makedirs(app_settings.TEMP_DIR, exist_ok=True)
-            os.makedirs(os.path.join(app_settings.RESULT_DIR, 'script'), exist_ok=True)
-
-            llm = LLM()
-
-            # 微电影模式: 单幕生成
-            json_data = self._generate_micro_script_incremental(
-                llm, draft, idea, style, llm_model, sid, is_zh, web_search=web_search, pct_start=20
-            )
-
-            # 补充元数据
-            json_data.setdefault("project_id", f"proj_{sid}")
-            json_data.setdefault("version", 1)
-            json_data["created_at"] = datetime.now(timezone.utc).isoformat()
-            json_data["metadata"] = {
-                "generation_model": llm_model,
-                "generation_prompt": idea,
-                "mode": "micro",
-            }
-            json_data["session_id"] = sid
-            json_data["logline_data"] = logline_data
-
-            self._save_result(json_data, sid, is_zh)
-            # 保存进度状态
-            self._save_progress(sid, "script_generation", {
-                "title": json_data.get("title")
-            })
-            self._report_progress("剧本生成", "完成", 100)
-            return json_data
-
-        loop = asyncio.get_running_loop()
-        script_json = await loop.run_in_executor(None, run)
-
-        # 保存进度状态
-        self._save_progress(sid, "script_generation", {
-            "title": script_json.get("title")
-        })
-
-        return {
-            "payload": script_json,
-            "requires_intervention": False,
-            "stage_completed": True,  # 明确标记阶段完成
-            "openclaw_hint": "剧本生成完成。",
-        }
-
-    # ─── 代理模式(自动生成 Logline 并选择第一个) ───
-
-    async def _phase_direct(self, input_data: Dict) -> Dict:
-        """代理模式:生成 3 个 Logline → 自动选择第一个 → 生成完整剧本"""
-        idea = input_data.get("idea", "")
-        sid = input_data.get("session_id", "")
-        style = input_data.get("style", "anime")
-        llm_model = input_data.get("llm_model", "qwen3.5-plus")
-        web_search = input_data.get("web_search", False)
-        is_zh = any('\u4e00' <= c <= '\u9fff' for c in idea)
-
-        def run():
-            from config import settings as app_settings
-            from tool.llm_client import LLM
-
-            os.makedirs(app_settings.TEMP_DIR, exist_ok=True)
-            os.makedirs(os.path.join(app_settings.RESULT_DIR, 'script'), exist_ok=True)
-
-            llm = LLM()
-
-            # Step 1: 生成 Logline 方案
-            self._report_progress("剧本生成", "正在生成 Logline 方案...", 5)
-            prompt = _get_script_prompt("logline_generate", "zh" if is_zh else "en").format(idea=idea)
-
-            logline_data = None
-            for attempt in range(3):
-                self._check_cancel()
-                raw = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid, web_search=web_search)
-                logger.info(f"[ScriptWriter][auto] Logline gen attempt {attempt + 1}, raw ({len(raw)} chars): {raw[:500]}")
-                options = self._extract_json_array_from_text(raw)
-                if options and len(options) > 0:
-                    required = {"logline", "who", "goal", "conflict", "twist", "theme"}
-                    valid = [o for o in options if isinstance(o, dict) and required.issubset(o.keys())]
-                    if valid:
-                        logline_data = valid[0]  # 自动选择第一个
-                        logger.info(f"[ScriptWriter][auto] Auto-selected logline: {logline_data.get('logline', '')[:80]}")
-                        break
-
-                logger.warning(f"[ScriptWriter][auto] Logline gen attempt {attempt + 1}: parse failed")
-                if is_zh:
-                    prompt = (
-                        "上次输出格式不正确,请严格按要求重新输出。"
-                        "必须输出纯JSON数组,不要用```包裹,不要有任何多余文字。\n\n"
-                        + _get_script_prompt("logline_generate", "zh").format(idea=idea)
-                    )
-                else:
-                    prompt = (
-                        "Previous output format was incorrect. Please try again. "
-                        "Output ONLY a raw JSON array, no code blocks, no extra text.\n\n"
-                        + _get_script_prompt("logline_generate", "en").format(idea=idea)
-                    )
-
-            if logline_data is None:
-                raise Exception("Logline 生成失败:多次尝试均无法解析输出")
-
-            self._report_progress("剧本生成", "已自动选择 Logline,开始创作情节...", 15)
-
-            # Step 2: 用 Logline 六要素构建故事概要
-            if is_zh:
-                draft = (
-                    f"故事核心 Logline:{logline_data.get('logline', '')}\n"
-                    f"主角:{logline_data.get('who', '')}\n"
-                    f"目标:{logline_data.get('goal', '')}\n"
-                    f"核心障碍:{logline_data.get('conflict', '')}\n"
-                    f"反转:{logline_data.get('twist', '')}\n"
-                    f"主题:{logline_data.get('theme', '')}\n\n"
-                    f"原始灵感:{idea}"
-                )
-            else:
-                draft = (
-                    f"Story Logline: {logline_data.get('logline', '')}\n"
-                    f"Protagonist: {logline_data.get('who', '')}\n"
-                    f"Goal: {logline_data.get('goal', '')}\n"
-                    f"Core Conflict: {logline_data.get('conflict', '')}\n"
-                    f"Twist: {logline_data.get('twist', '')}\n"
-                    f"Theme: {logline_data.get('theme', '')}\n\n"
-                    f"Original idea: {idea}"
-                )
-
-            # Step 3: 逐幕生成节拍表 + 分场大纲 + 结构化提取
-            json_data = self._generate_script_incremental(
-                llm, draft, idea, style, llm_model, sid, is_zh, web_search=web_search, pct_start=20
-            )
-
-            # 补充元数据
-            json_data.setdefault("project_id", f"proj_{sid}")
-            json_data.setdefault("version", 1)
-            json_data["created_at"] = datetime.now(timezone.utc).isoformat()
-            json_data["metadata"] = {
-                "generation_model": llm_model,
-                "generation_prompt": idea,
-            }
-            json_data["session_id"] = sid
-            json_data["logline_data"] = logline_data
-
-            self._save_result(json_data, sid, is_zh)
-            # 保存进度状态
-            self._save_progress(sid, "script_generation", {
-                "title": json_data.get("title")
-            })
-            self._report_progress("剧本生成", "完成", 100)
-            return json_data
-
-        loop = asyncio.get_running_loop()
-        script_json = await loop.run_in_executor(None, run)
-
-        # 保存进度状态
-        self._save_progress(sid, "script_generation", {
-            "title": script_json.get("title")
-        })
-
-        return {
-            "payload": script_json,
-            "requires_intervention": False,
-            "stage_completed": True,  # 明确标记阶段完成
-            "openclaw_hint": "剧本生成完成。",
-        }
-
-    # ─── 公共: 逐幕生成节拍表 + 分场大纲 + 结构化提取 ───
-
-    def _generate_script_incremental(self, llm, draft: str, idea: str, style: str,
-                                      llm_model: str, sid: str, is_zh: bool,
-                                      web_search: bool = False,
-                                      pct_start: int = 20) -> dict:
-        """生成 Save the Cat! 节拍表 → 逐幕生成分场大纲 + 结构化提取,返回合并的 JSON"""
-
-        # Step 1: 生成四幕节拍表
-        self._report_progress("剧本生成", "生成节拍表...", pct_start)
-        prompt = _get_script_prompt("beat_sheet", "zh" if is_zh else "en").format(draft=draft, idea=idea, style=style)
-        beat_sheet = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid, web_search=web_search)
-        logger.info(f"[ScriptWriter] Beat sheet generated ({len(beat_sheet)} chars)")
-
-        # 发送节拍表到前端
-        self._report_progress("剧本生成", "节拍表生成完成", pct_start + 5,
-                              data={"beat_sheet": beat_sheet})
-
-        # Step 2: 提取顶层元数据 (title, logline, genre, synopsis, mood)
-        self._report_progress("剧本生成", "提取故事元信息...", pct_start + 7)
-        meta_prompt = _get_script_prompt("meta_extract", "zh" if is_zh else "en").format(beat_sheet=beat_sheet)
-        meta_raw = self._cancellable_query(llm, meta_prompt, model=llm_model, task_id=sid, web_search=web_search)
-        meta_data = self._extract_json_from_text(meta_raw) or {}
-        logger.info(f"[ScriptWriter] Meta extracted: {list(meta_data.keys())}")
-
-        # Step 3: 逐幕生成分场大纲 + 结构化提取
-        act_names = ACT_NAMES_ZH if is_zh else ACT_NAMES_EN
-        all_characters = []  # 累积角色
-        all_settings = []    # 累积场景
-        all_scenes = []      # 累积分场
-        seen_char_names = set()
-        seen_setting_names = set()
-        scene_start = 1
-
-        for act_num in range(1, 5):
-            self._check_cancel()
-            act_name = act_names[act_num]
-
-            # --- 生成分场大纲 ---
-            pct_outline = pct_start + 8 + (act_num - 1) * 15  # 28, 43, 58, 73
-            progress_msg = (f"生成第{act_num}幕分场大纲({act_name})..."
-                            if is_zh else f"Generating Act {act_num} outline ({act_name})...")
-            self._report_progress("剧本生成", progress_msg, pct_outline)
-
-            outline_prompt = _get_script_prompt("step_outline", "zh" if is_zh else "en").format(
-                beat_sheet=beat_sheet,
-                act_number=act_num,
-                act_name=act_name,
-                scene_start=scene_start,
-                style=style,
-            )
-            outline = self._cancellable_query(llm, outline_prompt, model=llm_model, task_id=sid, web_search=web_search)
-            logger.info(f"[ScriptWriter] Act {act_num} outline generated ({len(outline)} chars)")
-
-            # --- 结构化提取本幕 JSON ---
-            pct_extract = pct_outline + 8
-            progress_msg = (f"提取第{act_num}幕结构化数据..."
-                            if is_zh else f"Extracting Act {act_num} structured data...")
-            self._report_progress("剧本生成", progress_msg, pct_extract)
-
-            act_json = self._extract_act_json(
-                llm, outline, act_num, scene_start, style, llm_model, sid, is_zh, web_search
-            )
-
-            # 累积角色(去重)
-            for c in act_json.get("characters", []):
-                if c.get("name") and c["name"] not in seen_char_names:
-                    if not c.get("character_id"):
-                        c["character_id"] = self._gen_id("char")
-                    all_characters.append(c)
-                    seen_char_names.add(c["name"])
-
-            # 累积场景(去重)
-            for s in act_json.get("settings", []):
-                if s.get("name") and s["name"] not in seen_setting_names:
-                    if not s.get("setting_id"):
-                        s["setting_id"] = self._gen_id("set")
-                    all_settings.append(s)
-                    seen_setting_names.add(s["name"])
-
-            # 累积分场
-            act_scenes = act_json.get("scenes", [])
-            all_scenes.extend(act_scenes)
-
-            # 计算下一幕场次起始
-            if act_scenes:
-                scene_start = max(s.get("scene_number", scene_start) for s in act_scenes) + 1
-
-            # 发送本幕结果到前端
-            act_label = f"第{act_num}幕 - {act_name}" if is_zh else f"Act {act_num} - {act_name}"
-            self._report_progress("剧本生成",
-                                  f"{act_label} 完成" if is_zh else f"{act_label} done",
-                                  pct_extract + 2,
-                                  data={"act_complete": {
-                                      "act": act_num,
-                                      "act_name": act_name,
-                                      "characters": act_json.get("characters", []),
-                                      "settings": act_json.get("settings", []),
-                                      "scenes": act_scenes,
-                                  }})
-
-        # Step 4: 合并最终 JSON
-        # 重新编号 scene_number
-        for i, sc in enumerate(all_scenes):
-            sc["scene_number"] = i + 1
-
-        json_data = {
-            "title": meta_data.get("title", ""),
-            "logline": meta_data.get("logline", ""),
-            "genre": meta_data.get("genre", []),
-            "target_duration": 1800,
-            "synopsis": meta_data.get("synopsis", ""),
-            "characters": all_characters,
-            "settings": all_settings,
-            "scenes": all_scenes,
-            "overall_style": style,
-            "mood": meta_data.get("mood", ""),
-        }
-
-        # Step 5: 合并相似场景和角色
-        self._report_progress("剧本生成",
-                              "审查并合并相似场景..." if is_zh else "Consolidating similar settings...",
-                              96)
-        json_data = self._consolidate_script(llm, json_data, llm_model, sid, is_zh, web_search=web_search)
-
-        return json_data
-
-    # ─── 微电影模式: 单幕紧凑生成 ───
-
-    def _generate_micro_script_incremental(self, llm, draft: str, idea: str, style: str,
-                                            llm_model: str, sid: str, is_zh: bool,
-                                            web_search: bool = False,
-                                            pct_start: int = 20) -> dict:
-        """微电影模式:生成紧凑单幕剧情概要 → 分场大纲 → 结构化提取,返回合并的 JSON"""
-
-        # Step 1: 生成单幕剧情概要
-        self._report_progress("剧本生成", "生成微电影剧情概要...", pct_start)
-        prompt = _get_script_prompt("micro_beat_sheet", "zh" if is_zh else "en").format(
-            draft=draft, idea=idea, style=style
-        )
-        beat_sheet = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid, web_search=web_search)
-        logger.info(f"[ScriptWriter][micro] Beat sheet generated ({len(beat_sheet)} chars)")
-
-        # 发送概要到前端
-        self._report_progress("剧本生成", "剧情概要生成完成", pct_start + 10,
-                              data={"beat_sheet": beat_sheet})
-
-        # Step 2: 提取顶层元数据
-        self._report_progress("剧本生成", "提取故事元信息...", pct_start + 15)
-        meta_prompt = _get_script_prompt("micro_meta_extract", "zh" if is_zh else "en").format(
-            beat_sheet=beat_sheet
-        )
-        meta_raw = self._cancellable_query(llm, meta_prompt, model=llm_model, task_id=sid, web_search=web_search)
-        meta_data = self._extract_json_from_text(meta_raw) or {}
-        logger.info(f"[ScriptWriter][micro] Meta extracted: {list(meta_data.keys())}")
-
-        # Step 3: 生成分场大纲
-        self._check_cancel()
-        self._report_progress("剧本生成",
-                              "生成微电影分场大纲..." if is_zh else "Generating micro-film step outline...",
-                              pct_start + 25)
-
-        outline_prompt = _get_script_prompt("micro_step_outline", "zh" if is_zh else "en").format(
-            beat_sheet=beat_sheet, style=style
-        )
-        outline = self._cancellable_query(llm, outline_prompt, model=llm_model, task_id=sid, web_search=web_search)
-        logger.info(f"[ScriptWriter][micro] Outline generated ({len(outline)} chars)")
-
-        # Step 4: 结构化 JSON 提取
-        self._report_progress("剧本生成",
-                              "提取结构化数据..." if is_zh else "Extracting structured data...",
-                              pct_start + 45)
-
-        act_json = self._extract_act_json(
-            llm, outline, act_number=1, scene_start=1,
-            style=style, llm_model=llm_model, sid=sid, is_zh=is_zh,
-            web_search=web_search
-        )
-
-        characters = act_json.get("characters", [])
-        settings = act_json.get("settings", [])
-        scenes = act_json.get("scenes", [])
-
-        # 补全 ID
-        for c in characters:
-            if not c.get("character_id"):
-                c["character_id"] = self._gen_id("char")
-        for s in settings:
-            if not s.get("setting_id"):
-                s["setting_id"] = self._gen_id("set")
-
-        # 重新编号并去掉 act 字段(微电影不分幕)
-        for i, sc in enumerate(scenes):
-            sc["scene_number"] = i + 1
-            sc.pop("act", None)
-
-        # 发送到前端
-        act_label = "微电影" if is_zh else "Micro-film"
-        self._report_progress("剧本生成",
-                              f"{act_label} 分场完成" if is_zh else f"{act_label} scenes done",
-                              pct_start + 60,
-                              data={"act_complete": {
-                                  "act": 1,
-                                  "act_name": act_label,
-                                  "characters": characters,
-                                  "settings": settings,
-                                  "scenes": scenes,
-                              }})
-
-        # Step 5: 合并最终 JSON
-        json_data = {
-            "title": meta_data.get("title", ""),
-            "logline": meta_data.get("logline", ""),
-            "genre": meta_data.get("genre", []),
-            "target_duration": 180,  # 微电影默认 3 分钟
-            "synopsis": meta_data.get("synopsis", ""),
-            "characters": characters,
-            "settings": settings,
-            "scenes": scenes,
-            "overall_style": style,
-            "mood": meta_data.get("mood", ""),
-        }
-
-        # Step 6: 合并相似场景和角色
-        self._report_progress("剧本生成",
-                              "审查并合并相似场景..." if is_zh else "Consolidating similar settings...",
-                              pct_start + 70)
-        json_data = self._consolidate_script(llm, json_data, llm_model, sid, is_zh, web_search=web_search)
-
-        return json_data
-
-    # ─── 公共: 单幕结构化提取 (带校验重试) ───
-
-    def _extract_act_json(self, llm, outline: str, act_number: int,
-                          scene_start: int, style: str,
-                          llm_model: str, sid: str, is_zh: bool,
-                          web_search: bool = False) -> dict:
-        """从单幕分场大纲提取结构化JSON,带校验重试"""
-        extract_prompt = _get_script_prompt("act_extract", "zh" if is_zh else "en").format(
-            act_number=act_number, scene_start=scene_start, outline=outline
-        )
-
-        last_error = ""
-
-        for attempt in range(3):
-            self._check_cancel()
-            raw = self._cancellable_query(llm, extract_prompt, model=llm_model, task_id=sid, web_search=web_search)
-            parsed = self._extract_json_from_text(raw)
-
-            if parsed is None:
-                last_error = "LLM输出无法解析为JSON"
-                logger.warning(f"[ScriptWriter] Act {act_number} extract attempt {attempt + 1}: JSON parse failed")
-                extract_prompt = (
-                    ("上次输出不是合法JSON,请重新输出。" if is_zh
-                     else "Previous output was not valid JSON. Please try again. ")
-                    + extract_prompt
-                )
-                continue
-
-            # 基本校验: 必须有 scenes 列表
-            scenes = parsed.get("scenes")
-            if not isinstance(scenes, list) or len(scenes) == 0:
-                last_error = "scenes 必须是非空列表"
-                logger.warning(f"[ScriptWriter] Act {act_number} extract attempt {attempt + 1}: no scenes")
-                extract_prompt = (
-                    (f"上次输出的JSON缺少scenes。请确保scenes是非空列表。" if is_zh
-                     else "Previous JSON had no scenes. Ensure scenes is a non-empty array. ")
-                    + extract_prompt
-                )
-                continue
-
-            # 校验每个 scene 的必要字段
-            valid = True
-            for i, sc in enumerate(scenes):
-                for key in ["scene_number", "act", "location", "characters", "plot"]:
-                    if key not in sc:
-                        last_error = f"scenes[{i}] 缺少字段: {key}"
-                        valid = False
-                        break
-                if not valid:
-                    break
-
-            if not valid:
-                logger.warning(f"[ScriptWriter] Act {act_number} extract attempt {attempt + 1}: {last_error}")
-                extract_prompt = (
-                    (f"上次输出的JSON存在问题: {last_error}。请修正后重新输出。" if is_zh
-                     else f"Previous JSON issue: {last_error}. Please fix and retry. ")
-                    + extract_prompt
-                )
-                continue
-
-            return parsed
-
-        raise Exception(f"第{act_number}幕JSON提取失败 (已重试3次): {last_error}")
-
-    # ─── 公共: 场景 & 角色合并 ───
-
-    def _consolidate_script(self, llm, json_data: dict,
-                            llm_model: str, sid: str, is_zh: bool,
-                            web_search: bool = False) -> dict:
-        """审查并合并重复/相似的场景和角色"""
-        characters = json_data.get("characters", [])
-        settings = json_data.get("settings", [])
-        scenes = json_data.get("scenes", [])
-
-        if len(settings) <= 1 and len(characters) <= 1:
-            return json_data
-
-        # 构建简洁的列表供 LLM 审查
-        settings_summary = [{"name": s["name"], "description": s.get("description", "")}
-                            for s in settings]
-        chars_summary = [{"name": c["name"], "description": c.get("description", "")}
-                         for c in characters]
-
-        prompt = _get_script_prompt("consolidate", "zh" if is_zh else "en").format(
-            settings_json=json.dumps(settings_summary, ensure_ascii=False, indent=2),
-            characters_json=json.dumps(chars_summary, ensure_ascii=False, indent=2),
-        )
-
-        self._check_cancel()
-        raw = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid, web_search=web_search)
-        result = self._extract_json_from_text(raw)
-
-        if not result or not isinstance(result, dict):
-            logger.warning("[ScriptWriter] Consolidation: failed to parse LLM response, skipping")
-            return json_data
-
-        setting_merges = result.get("setting_merges", {})
-        char_merges = result.get("character_merges", {})
-
-        if not setting_merges and not char_merges:
-            logger.info("[ScriptWriter] Consolidation: nothing to merge")
-            return json_data
-
-        # --- 合并场景 ---
-        if setting_merges:
-            logger.info(f"[ScriptWriter] Merging settings: {setting_merges}")
-            # 移除被合并的 settings
-            merged_names = set(setting_merges.keys())
-            json_data["settings"] = [s for s in settings if s["name"] not in merged_names]
-
-            # 更新 scenes 中的 location 引用
-            for sc in scenes:
-                loc = sc.get("location", "")
-                if loc in setting_merges:
-                    sc["location"] = setting_merges[loc]
-
-        # --- 合并角色 ---
-        if char_merges:
-            logger.info(f"[ScriptWriter] Merging characters: {char_merges}")
-            merged_char_names = set(char_merges.keys())
-            json_data["characters"] = [c for c in characters if c["name"] not in merged_char_names]
-
-            # 更新 scenes 中的 characters 引用
-            for sc in scenes:
-                new_chars = []
-                seen = set()
-                for cn in sc.get("characters", []):
-                    target = char_merges.get(cn, cn)
-                    if target not in seen:
-                        new_chars.append(target)
-                        seen.add(target)
-                sc["characters"] = new_chars
-
-        logger.info(f"[ScriptWriter] After consolidation: "
-                     f"{len(json_data['settings'])} settings, "
-                     f"{len(json_data['characters'])} characters")
-
-        # 验证 scenes 的 location 是否都在 settings 中
-        settings_names = {s["name"] for s in json_data.get("settings", [])}
-        for sc in json_data.get("scenes", []):
-            loc = sc.get("location", "")
-            if loc and loc not in settings_names:
-                logger.error(f"[ScriptWriter] ERROR: Scene location '{loc}' not found in settings! available: {settings_names}")
-
-        return json_data
+        result = await run_logic()
+        return {"payload": result, "requires_intervention": False, "stage_completed": True}
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 9dbe1a7..b9d7e4f 100644
--- a/aigc-director/aigc-claw/backend/core/agents/storyboard_agent.py
+++ b/aigc-director/aigc-claw/backend/core/agents/storyboard_agent.py
@@ -1,7 +1,8 @@
-# -*- coding: utf-8 -*-
+# -*- coding: utf-8 -*-
 """
 阶段3: 分镜智能体
 基于剧本JSON,逐场景拆分为带时长标签的分镜(shots),按幕分组输出。
+支持 Segment -> Shots 嵌套结构。
 """
 
 import os
@@ -9,469 +10,247 @@
 import json
 import asyncio
 import logging
+from datetime import datetime
 from typing import Any, Optional, Dict, List
-from concurrent.futures import ThreadPoolExecutor, as_completed
 
 from .base_agent import AgentInterface
-from prompts.loader import load_prompt
 
 logger = logging.getLogger(__name__)
 
 # ─── 幕名 ───
 ACT_NAMES = {1: "激励事件", 2: "进入新世界", 3: "灵魂黑夜", 4: "高潮决战"}
 
-
-def _get_shot_prompt(lang: str = 'zh') -> str:
-    """获取分镜提取提示词"""
+def _get_shot_prompt(lang: str = "zh") -> str:
     from prompts.loader import load_prompt_with_fallback
-    return load_prompt_with_fallback('storyboard', 'shot', lang, 'zh')
+    return load_prompt_with_fallback("storyboard", "shot", lang, "zh")
 
-
-def _get_expand_prompt(lang: str = 'zh') -> str:
-    """获取剧本扩写提示词"""
+def _get_continue_prompt(lang: str = "zh") -> str:
     from prompts.loader import load_prompt_with_fallback
-    return load_prompt_with_fallback('storyboard', 'expand', 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')
-
+    return load_prompt_with_fallback("storyboard", "continue", lang, "zh")
 
 class StoryboardAgent(AgentInterface):
-    """分镜智能体:逐场景拆分为带时长标签的分镜"""
-
     def __init__(self):
         super().__init__(name="Storyboard")
 
-    # ─── 辅助方法 ───
-
     @staticmethod
     def _read_script_json(sid: str) -> dict:
-        """从结果文件读取 script_json"""
-        from config import settings
-        result_file = os.path.join(settings.RESULT_DIR, 'script', f'script_{sid}.json')
-        if not os.path.exists(result_file):
+        session_path = os.path.join("code/data/sessions", f"{sid}.json")
+        if not os.path.exists(session_path):
             return {}
-        with open(result_file, 'r', encoding='utf-8') as f:
-            data = json.load(f)
-        return data.get(str(sid), {}).get('script_json', {})
+        try:
+            with open(session_path, "r", encoding="utf-8") as f:
+                data = json.load(f)
+            return data.get("artifacts", {}).get("script_generation", {})
+        except Exception:
+            return {}
 
     @staticmethod
     def _extract_json_array(text: str) -> Optional[List[dict]]:
-        """从LLM输出中提取JSON数组"""
         text = text.strip()
-        text = re.sub(r'^```(?:json)?\s*', '', text)
-        text = re.sub(r'\s*```$', '', text)
-        text = text.strip()
+        text = re.sub(r"^```(?:json)?\s*", "", text)
+        text = re.sub(r"\s*```$", "", text)
         try:
             result = json.loads(text)
-            if isinstance(result, list):
-                return result
-        except json.JSONDecodeError:
-            pass
-        # 尝试找到 [ ... ] 部分
-        m = re.search(r'\[.*\]', text, re.DOTALL)
+            if isinstance(result, list): return result
+        except json.JSONDecodeError: pass
+        m = re.search(r"\[.*\]", text, re.DOTALL)
         if m:
             try:
                 result = json.loads(m.group())
-                if isinstance(result, list):
-                    return result
-            except json.JSONDecodeError:
-                pass
+                if isinstance(result, list): return result
+            except json.JSONDecodeError: pass
         return None
 
     @staticmethod
-    def _validate_shots(shots: List[dict]) -> List[dict]:
-        """校验并清洗分镜数据"""
-        valid = []
-        for s in shots:
-            if not isinstance(s, dict):
-                continue
-            dur = s.get("duration", 10)
-            if dur not in (5, 10, 15):
-                dur = 10  # 默认10秒
-            valid.append({
-                "shot_number": s.get("shot_number", len(valid) + 1),
-                "duration": dur,
-                "characters": s.get("characters", []),
-                "location": s.get("location", ""),
-                "plot": s.get("plot", ""),
-                "visual_prompt": s.get("visual_prompt", ""),
+    def _validate_episodes(episodes: List[dict]) -> List[dict]:
+        """验证嵌套的 Episode -> Segment -> Shots 结构"""
+        valid_episodes = []
+        for ep in episodes:
+            if not isinstance(ep, dict): continue
+            
+            segments = ep.get("segments", [])
+            valid_segments = []
+            
+            for seg in segments:
+                if not isinstance(seg, dict): continue
+                
+                shots = seg.get("shots", [])
+                valid_shots = []
+                calc_total_duration = 0
+                
+                for s in shots:
+                    if not isinstance(s, dict): continue
+                    dur = s.get("duration", 5)
+                    calc_total_duration += dur
+                    valid_shots.append({
+                        "shot_number": s.get("shot_number", len(valid_shots) + 1),
+                        "shot_type": s.get("shot_type", "中景"),
+                        "duration": dur,
+                        "content": s.get("content", "")
+                    })
+                
+                valid_segments.append({
+                    "segment_id": seg.get("segment_id", str(uuid.uuid4())[:8]),
+                    "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", []),
+                    "shots": valid_shots
+                })
+            
+            valid_episodes.append({
+                "episode_number": ep.get("episode_number", len(valid_episodes) + 1),
+                "episode_title": ep.get("episode_title", ""),
+                "segments": valid_segments
             })
-        return valid
+        return valid_episodes
 
     async def _continue_story(self, input_data: Dict, continue_info: Dict) -> Dict:
-        """智能续写:根据已有剧情续写新场景"""
-        from config import settings
-        from tool.llm_client import LLM
-
-        sid = input_data["session_id"]
-        style = input_data.get("style", "anime")
-        llm_model = input_data.get("llm_model", "qwen3.5-plus")
-
-        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)
-        existing_shots = results.get(str(sid), {}).get('storyboard', {}).get('shots', [])
-        if not existing_shots:
-            raise Exception("没有已有分镜,无法续写")
-
-        # 读取剧本信息
-        script_json = self._read_script_json(sid)
-        if not script_json:
-            raise Exception("未找到剧本数据")
-
-        title = script_json.get("title", "")
-        characters = script_json.get("characters", [])
-        settings_list = script_json.get("settings", [])
-
-        # 取所有分镜作为上下文
-        last_shots = existing_shots
-
-        # 构建上下文描述
-        char_names = [c.get("name", "") for c in characters]
-        # 只使用现有分镜中实际使用的场景位置
-        used_locations = set(s.get("location", "") for s in existing_shots if s.get("location"))
-        setting_names = [s.get("name", "") for s in settings_list if s.get("name", "") in used_locations]
-
-        # 获取续写提示词
-        is_zh = any('\u4e00' <= c <= '\u9fff' for c in title)
-        prompt_template = _get_continue_prompt('zh' if is_zh else 'en')
-
-        # 格式化已有分镜信息
-        shots_context = ""
-        for shot in last_shots:
-            shots_context += f"- 场景{shot.get('scene_number')} 分镜{shot.get('shot_number')}: {shot.get('plot', '')}\n"
-
-        prompt = prompt_template.format(
-            title=title,
-            style=style,
-            characters=", ".join(char_names),
-            settings=", ".join(setting_names),
-            existing_shots=shots_context,
-        )
-
-        self._report_progress("分镜", "智能续写中...", 10)
-
-        def run():
-            llm = LLM()
-            raw = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid)
-            new_shots = self._extract_json_array(raw)
-            if not new_shots:
-                raise Exception("续写失败,无法解析LLM输出")
-            new_shots = self._validate_shots(new_shots)
-            return new_shots
-
-        loop = asyncio.get_running_loop()
-        new_shots = await loop.run_in_executor(None, run)
-
-        # 为新分镜添加全局标识
-        last_scene = last_shots[-1] if last_shots else None
-        next_scene_num = (last_scene.get("scene_number", 0) + 1) if last_scene else 1
-        next_act = last_scene.get("act", 1) if last_scene else 1
-
-        for i, shot in enumerate(new_shots):
-            shot["shot_id"] = f"shot_{next_scene_num:03d}_{i + 1:02d}"
-            shot["scene_number"] = next_scene_num
-            shot["act"] = next_act
-            shot["is_new"] = True  # 标记为新添加的分镜
-
-        # 追加到已有分镜
-        all_shots = existing_shots + new_shots
-
-        # 保存(带有 is_new 标记,供前端识别)
-        results.setdefault(str(sid), {})['storyboard'] = {
-            'shots': all_shots,
-            'user_modified': True,
-            'new_shot_ids': [s["shot_id"] for s in new_shots],  # 记录新分镜ID
-        }
-        with open(result_file, 'w', encoding='utf-8') as f:
-            json.dump(results, f, indent=4, ensure_ascii=False)
-
-        self._report_progress("分镜", "续写完成", 100)
-
-        return {
-            "payload": {
-                "session_id": sid,
-                "shots": all_shots,
-                "new_shots": new_shots,
-                "new_shot_ids": [s["shot_id"] for s in new_shots],
-                "continued": True,
-            },
-            "requires_intervention": True,
-        }
-
-    # ─── 核心流程 ───
+        # TODO: 适配 Segment 结构的续写逻辑(暂留原始逻辑或抛错)
+        raise NotImplementedError("续写逻辑尚不支持新的嵌套 Segment 结构,请先完成基础生成。")
 
     async def process(self, input_data: Any, intervention: Optional[Dict] = None) -> Dict:
-        from config import settings
         from tool.llm_client import LLM
-
-        sid = input_data["session_id"]
-        style = input_data.get("style", "anime")
-        llm_model = input_data.get("llm_model", "qwen3.5-plus")
-
-        result_file = os.path.join(settings.RESULT_DIR, 'script', f'script_{sid}.json')
-
-        # ── 用户修改了分镜 ──
+        input_data = self._merge_session_params(input_data)
+        sid = input_data.get("session_id")
+        if not sid: raise Exception("Missing session_id")
+             
+        session_file = os.path.join("code/data/sessions", f"{sid}.json")
+        with open(session_file, "r", encoding="utf-8") as f:
+            session_data = json.load(f)
+            
+        llm_model = input_data.get("llm_model") or session_data.get("llm_model") or "qwen-max"
+        style = input_data.get("style") or session_data.get("style") or "anime"
+        
+        # 处理人工干预/修改
         if intervention and "modified_storyboard" in intervention:
-            modified_shots = intervention["modified_storyboard"]
-            if isinstance(modified_shots, str):
-                modified_shots = json.loads(modified_shots)
-
-            with open(result_file, 'r', encoding='utf-8') as f:
-                results = json.load(f)
-
-            # 同步更新 script_json 中的 scenes
-            # 获取修改后的 shots 中包含的场景编号
-            new_scene_numbers = set(s.get("scene_number") for s in modified_shots if s.get("scene_number"))
-
-            # 更新 script_json.scenes
-            script_json = results.get(str(sid), {}).get('script_json', {})
-            if script_json and 'scenes' in script_json:
-                original_scenes = script_json.get('scenes', [])
-                # 保留新分镜中包含的场景,按原始顺序
-                filtered_scenes = [s for s in original_scenes if s.get('scene_number') in new_scene_numbers]
-                # 重新编号(确保 scene_number 连续)
-                for i, scene in enumerate(filtered_scenes, 1):
-                    scene['scene_number'] = i
-                script_json['scenes'] = filtered_scenes
-
-            # 清除 new_shot_ids 标记,同时清除 is_new 标志
-            for shot in modified_shots:
-                if 'is_new' in shot:
-                    shot['is_new'] = False
-            storyboard_data = {
-                'shots': modified_shots,
-                'user_modified': True,
-                'new_shot_ids': [],  # 清除新分镜标记
+            modified_episodes = intervention["modified_storyboard"]
+            if isinstance(modified_episodes, str): modified_episodes = json.loads(modified_episodes)
+            session_data.setdefault("artifacts", {})["storyboard"] = {
+                "session_id": sid,
+                "episodes": modified_episodes,
+                "user_modified": True,
+                "updated_at": datetime.now().isoformat()
             }
+            # 更新顶层状态
+            session_data["updated_at"] = datetime.now().timestamp()
+            with open(session_file, "w", encoding="utf-8") as f: json.dump(session_data, f, indent=2, ensure_ascii=False)
+            return {"payload": {"session_id": sid, "episodes": modified_episodes}, "stage_completed": True}
+        
+        script_data = self._read_script_json(sid)
+        if not script_data: raise Exception("未找到剧本数据")
+        
+        episodes = script_data.get("episodes", [])
+        if not episodes:
+            raise Exception("剧本数据中不包含有效集数列表(episodes)")
+            
+        chars = script_data.get("characters", [])
+        sets = script_data.get("settings", [])
+        is_zh = any("\u4e00" <= c <= "\u9fff" for c in script_data.get("title", ""))
+        shot_prompt_tpl = _get_shot_prompt("zh" if is_zh else "en")
+        
+        self._report_progress("分镜", "解析剧本并生成片段...", 5)
+        
+        async def proc_ep(ep):
+            ep_n = ep.get("episode_number", 1)
+            ep_t = ep.get("act_title", f"第{ep_n}集")
+            ep_c = ep.get("content", "")
+            
+            # 清洗剧本内容:按行拆分,用于提示说明“一行一分镜”
+            lines = [line.strip() for line in ep_c.split('\n') if line.strip()]
+            script_text_with_lines = "\n".join([f"L{idx+1}: {line}" for idx, line in enumerate(lines)])
 
-            results.setdefault(str(sid), {})['storyboard'] = storyboard_data
-            if script_json:
-                results.setdefault(str(sid), {})['script_json'] = script_json
-            with open(result_file, 'w', encoding='utf-8') as f:
-                json.dump(results, f, indent=4, ensure_ascii=False)
-
-            # 返回完整的 payload 包含 user_modified 和 new_shot_ids
-            return {
-                "payload": {
-                    "session_id": sid,
-                    "shots": modified_shots,
-                    "user_modified": True,
-                    "new_shot_ids": [],
-                },
-                "stage_completed": True,
-            }
-
-        # ── 用户点击"智能续写" ──
-        if intervention and "continue_story" in intervention:
-            return await self._continue_story(input_data, intervention["continue_story"])
-
-        # ── 正常流程 ──
-        script_json = self._read_script_json(sid)
-        if not script_json:
-            raise Exception("未找到剧本数据(script_json),请先完成阶段1")
-
-        scenes = script_json.get("scenes", [])
-        characters = {c["name"]: c for c in script_json.get("characters", [])}
-        settings_map = {s["name"]: s for s in script_json.get("settings", [])}
-
-        # 拼接完整剧情以供扩写参考
-        full_plot_text = "\n".join([f"场景{s.get('scene_number', i+1)}: {s.get('plot', '')}" for i, s in enumerate(scenes)])
-
-        is_zh = any('\u4e00' <= c <= '\u9fff' for c in script_json.get("title", ""))
-        lang = 'zh' if is_zh else 'en'
-        shot_prompt_template = _get_shot_prompt(lang)
-        expand_prompt_template = _get_expand_prompt(lang)
-
-        self._report_progress("分镜", "读取剧本数据...", 5)
-
-        # 获取并发数
-        enable_concurrency = input_data.get("enable_concurrency", True)
-        from config_model import get_max_concurrency
-        # LLM 调用的并发数
-        concurrency = get_max_concurrency(llm_model, enable_concurrency)
-        logger.info(f"[StoryboardAgent] enable_concurrency={enable_concurrency}, concurrency={concurrency} for model={llm_model}")
-
-        # 用于按场景顺序存储结果的字典
-        shots_results: Dict[int, List[dict]] = {}
-        done_count = 0
-        total = len(scenes)
-
-        def generate_one_scene(scene_index: int, scene: dict) -> tuple:
-            """生成单个场景的分镜"""
-            llm = LLM()
-            sn = scene.get("scene_number", scene_index + 1)
-            act = scene.get("act", 1)
-
-            location = scene.get("location", "")
-            scene_chars = scene.get("characters", [])
-            original_plot = scene.get("plot", "")
-
-            # 角色外貌描述
-            char_descs = []
-            for cn in scene_chars:
-                c = characters.get(cn)
-                if c:
-                    char_descs.append(f"{cn}: {c.get('description', '')}")
-            char_desc_text = "\n".join(char_descs) if char_descs else "无"
-
-            # 场景环境描述
-            setting_info = settings_map.get(location, {})
-            setting_desc = setting_info.get("description", location)
-
-            # 第一步:扩写剧本
-            logger.info(f"[StoryboardAgent] Expanding scene {sn}...")
-            expand_prompt = expand_prompt_template.format(
-                title=script_json.get("title", ""),
-                style=style,
-                location=location,
-                characters=", ".join(scene_chars),
-                plot=original_plot,
-                char_descriptions=char_desc_text,
-                setting_description=setting_desc,
-                script=full_plot_text
+            prompt = shot_prompt_tpl.format(
+                act_number=ep_n, 
+                act_title=ep_t, 
+                script_text=script_text_with_lines, 
+                asset_characters=json.dumps(chars, ensure_ascii=False), 
+                asset_settings=json.dumps(sets, ensure_ascii=False),
+                style=style
             )
             
-            expanded_plot = original_plot
-            try:
-                expanded_plot = self._cancellable_query(llm, expand_prompt, model=llm_model, task_id=sid)
-                logger.info(f"[StoryboardAgent] Scene {sn} expanded.")
-            except Exception as e:
-                logger.error(f"Scene {sn} expansion failed: {e}")
-
-            # 第二步:生成分镜 (使用扩写后的内容)
-            prompt = shot_prompt_template.format(
-                style=style,
-                scene_number=sn,
-                location=location,
-                characters=", ".join(scene_chars),
-                expanded_plot=expanded_plot,
-                char_descriptions=char_desc_text,
-                setting_description=setting_desc,
-            )
-
-            # 最多重试3次
-            scene_shots = None
-            for attempt in range(3):
-                if hasattr(self, 'cancellation_check') and self.cancellation_check:
-                    if self.cancellation_check():
+            llm = LLM()
+            loop = asyncio.get_running_loop()
+            
+            # 增加重试机制 (Max 3 retries)
+            max_retries = 3
+            extracted = None
+            raw = ""
+            
+            for attempt in range(max_retries):
+                try:
+                    self._report_progress("分镜", f"生成集数 {ep_n} (第 {attempt + 1} 次尝试)...", 5 + attempt * 2)
+                    raw = await loop.run_in_executor(None, self._cancellable_query, llm, prompt, [], llm_model, False, sid, False)
+                    extracted = self._extract_json_array(raw)
+                    if extracted:
                         break
-                raw = self._cancellable_query(llm, prompt, model=llm_model, task_id=sid)
-                parsed = self._extract_json_array(raw)
-                if parsed:
-                    scene_shots = self._validate_shots(parsed)
-                    if scene_shots:
-                        break
-                logger.warning(f"Scene {sn} shot parse attempt {attempt+1} failed")
+                    logger.warning(f"Episode {ep_n} Attempt {attempt + 1}: Failed to extract JSON array. Retrying...")
+                except Exception as e:
+                    logger.error(f"Episode {ep_n} Attempt {attempt + 1}: LLM query error: {str(e)}")
+                    if attempt == max_retries - 1: raise e
+            
+            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": []
+                }
+                
+            # 兼容旧的 _validate_segments 调用(已改名为 _validate_episodes 内部的逻辑)
+            # 我们直接手动处理 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
+                for s in shots:
+                    if not isinstance(s, dict): continue
+                    dur = s.get("duration", 5)
+                    calc_total_duration += dur
+                    valid_shots.append({
+                        "shot_number": s.get("shot_number", len(valid_shots) + 1),
+                        "shot_type": s.get("shot_type", "中景"),
+                        "duration": dur,
+                        "content": s.get("content", "")
+                    })
+                valid_segments.append({
+                    "segment_id": f"seg_{ep_n:02d}_{i:02d}",
+                    "segment_number": i,
+                    "location": seg.get("location", ""),
+                    "characters": seg.get("characters", []),
+                    "total_duration": seg.get("total_duration", calc_total_duration),
+                    "shots": valid_shots,
+                    "episode_number": ep_n
+                })
 
-            if not scene_shots:
-                # 降级: 整个场景作为一个分镜
-                scene_shots = [{
-                    "shot_number": 1,
-                    "duration": 15,
-                    "characters": scene_chars,
-                    "location": location,
-                    "plot": original_plot,
-                    "visual_prompt": original_plot,
-                }]
-
-            # 为每个分镜添加全局标识
-            for shot in scene_shots:
-                shot["shot_id"] = f"shot_{sn:03d}_{shot['shot_number']:02d}"
-                shot["scene_number"] = sn
-                shot["act"] = act
-
-            return scene_index, scene_shots, sn, act
-
-        def run():
-            nonlocal done_count
-            # 检测是否有多幕结构(微电影模式只有一幕或无 act 字段)
-            act_values = {s.get("act") for s in scenes}
-            multi_act = len(act_values - {None}) > 1
-
-            with ThreadPoolExecutor(max_workers=concurrency) as executor:
-                futs = {}
-                for i, scene in enumerate(scenes):
-                    fut = executor.submit(generate_one_scene, i, scene)
-                    futs[fut] = i
-
-                # 按提交顺序收集结果(不是按完成顺序)
-                for scene_index in range(len(scenes)):
-                    # 找到对应的 future
-                    found_future = None
-                    for fut in futs:
-                        if futs[fut] == scene_index:
-                            found_future = fut
-                            break
-
-                    if found_future:
-                        try:
-                            idx, scene_shots, sn, act = found_future.result()
-                            shots_results[idx] = scene_shots
-
-                            # 报告进度
-                            done_count += 1
-                            pct = 5 + int(90 * done_count / max(total, 1))
-                            if multi_act:
-                                act_label = ACT_NAMES.get(act, f"第{act}幕")
-                                self._report_progress("分镜", f"第{act}幕「{act_label}」 场景{sn}/{total}完成", pct)
-                            else:
-                                self._report_progress("分镜", f"场景{sn}完成 ({len(scene_shots)}个分镜)", pct)
-
-                            # 发送逐场完成事件
-                            self._report_progress(
-                                "分镜",
-                                f"场景{sn}完成 ({len(scene_shots)}个分镜)",
-                                pct,
-                                data={"scene_shots_complete": {
-                                    "scene_number": sn,
-                                    "act": act,
-                                    "shots": scene_shots,
-                                }},
-                            )
-                        except Exception as e:
-                            logger.error(f"Scene {scene_index} generation error: {e}")
-                            shots_results[scene_index] = []
-
-            # 按场景顺序拼接所有分镜
-            all_shots = []
-            for i in range(len(scenes)):
-                if i in shots_results:
-                    all_shots.extend(shots_results[i])
-
-            self._report_progress("分镜", "保存结果...", 96)
-
-            # 写入结果文件
-            with open(result_file, 'r', encoding='utf-8') as f:
-                results = json.load(f)
-            results.setdefault(str(sid), {})['storyboard'] = {
-                'shots': all_shots,
-            }
-            with open(result_file, 'w', encoding='utf-8') as f:
-                json.dump(results, f, indent=4, ensure_ascii=False)
-
-            self._report_progress("分镜", "完成", 100)
             return {
-                "payload": {
-                    "session_id": sid,
-                    "shots": all_shots,
-                },
-                "stage_completed": True,
+                "episode_number": ep_n,
+                "episode_title": ep_t,
+                "segments": valid_segments
             }
 
-        loop = asyncio.get_running_loop()
-        all_shots = await loop.run_in_executor(None, run)
-
-        return {
-            "payload": {
-                "session_id": sid,
-                "shots": all_shots,
-            },
-            "stage_completed": True,
+        # 并发处理
+        all_episodes = await asyncio.gather(*(proc_ep(ep) for ep in episodes))
+        all_episodes.sort(key=lambda x: x["episode_number"])
+        
+# 核心:将结果持久化到 artifacts.storyboard
+        # 现在存储的是嵌套的 episodes 结构
+        session_data.setdefault("artifacts", {})["storyboard"] = {
+            "session_id": sid, 
+            "episodes": all_episodes, 
+            "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: 
+            json.dump(session_data, f, indent=2, ensure_ascii=False)
+            
+        self._report_progress("分镜", "完成", 100)
+        return {"payload": {"session_id": sid, "episodes": all_episodes}, "stage_completed": True}
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 9c127a7..ef96a8b 100644
--- a/aigc-director/aigc-claw/backend/core/agents/video_agent.py
+++ b/aigc-director/aigc-claw/backend/core/agents/video_agent.py
@@ -1,10 +1,10 @@
 # -*- coding: utf-8 -*-
 """
-阶段5: 视频生成智能体
-分镜参考图 → 各分镜视频片段
-- 视频提示词使用阶段3的原始分镜剧情描述(plot),而非视觉描述或首帧图像提示词
-- 参考图使用用户在阶段4选择的版本,而非第一版
-- 支持逐项实时预览、重新生成、多版本管理
+阶段5: 视频生成智能体 (适配 Session JSON 格式)
+- 从 session.json 的 artifacts["storyboard"] 读取拍摄片段(Segments)
+- 视频提示词:风格前缀 + 分镜列表(分镜1: [时长] content...)
+- 参考图:从 session.json 的 artifacts["reference_generation"] 或 scene2image 读取
+- 支持逐项并发生成、实时预览、重新生成
 """
 
 import os
@@ -22,7 +22,7 @@
 
 
 class VideoDirectorAgent(AgentInterface):
-    """视频生成:分镜参考图(阶段4用户选择) + 分镜剧情描述(阶段3 plot) → 视频片段"""
+    """视频生成:拍摄片段(Segments) → 组装提示词 → 视频片段"""
 
     def __init__(self):
         super().__init__(name="VideoDirector")
@@ -33,22 +33,22 @@
     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]:
-        """列出某个分镜视频的所有历史版本"""
+    def _list_versions(self, sid: str, segment_id: str) -> List[str]:
+        """列出某个片段视频的所有历史版本"""
         video_dir = self._video_base(sid)
-        pattern = os.path.join(video_dir, f"{shot_id}*.mp4")
+        pattern = os.path.join(video_dir, f"{segment_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:
+    def _next_version_path(self, sid: str, segment_id: str) -> str:
         """获取下一个版本路径"""
         video_dir = self._video_base(sid)
         os.makedirs(video_dir, exist_ok=True)
 
-        existing = self._list_versions(sid, shot_id)
+        existing = self._list_versions(sid, segment_id)
         if not existing:
-            return os.path.join(video_dir, f"{shot_id}.mp4")
+            return os.path.join(video_dir, f"{segment_id}.mp4")
 
         max_v = 1
         for fp in existing:
@@ -57,26 +57,25 @@
             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")
+        return os.path.join(video_dir, f"{segment_id}_v{max_v + 1}.mp4")
 
     # ─── 视频生成 ───
 
-    def _generate_one(self, sid: str, shot_id: str, prompt: str,
+    def _generate_one(self, sid: str, segment_id: str, prompt: str,
                       img_path: str, video_model: str,
-                      duration: int = 5, sound: str = "",
+                      duration: int = 10, sound: str = "",
                       shot_type: str = "multi",
                       video_ratio: str = "16:9") -> tuple:
-        """生成单个分镜视频,返回 (shot_id, path_or_None)"""
-        # 取消时直接跳过,不抛异常,以保留已生成的部分结果
+        """生成单个视频片段,返回 (segment_id, path_or_None)"""
         if self.cancellation_check and self.cancellation_check():
-            logger.info(f"VideoDirectorAgent: {shot_id} 跳过(用户取消)")
-            return shot_id, None
+            logger.info(f"VideoDirectorAgent: {segment_id} 跳过(用户取消)")
+            return segment_id, None
 
         if not os.path.exists(img_path):
-            logger.warning(f"Image missing for {shot_id}: {img_path}")
-            return shot_id, None
+            logger.warning(f"Image missing for {segment_id}: {img_path}")
+            return segment_id, None
 
-        save_path = self._next_version_path(sid, shot_id)
+        save_path = self._next_version_path(sid, segment_id)
         try:
             from tool.video_client import VideoClient
             client = VideoClient()
@@ -90,78 +89,98 @@
                 shot_type=shot_type,
                 video_ratio=video_ratio,
             )
-            return shot_id, save_path
+            return segment_id, save_path
         except Exception as e:
-            logger.error(f"Video gen failed for {shot_id}: {e}")
+            logger.error(f"Video gen failed for {segment_id}: {e}")
             if os.path.exists(save_path):
                 try:
                     os.remove(save_path)
                 except Exception:
                     pass
-        return shot_id, None
+        return segment_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)
+    def _assemble_prompt(self, segment: dict, style: str) -> str:
+        """组装视频提示词
+        格式:
+        风格控制:用户选择的风格, 电影质感
+        分镜列表:分镜1:[时长] content... 分镜2:[时长] content...
+        """
+        prompt = f"风格控制:{style}风格, 电影质感\n"
+        prompt += "分镜列表:"
+        
+        shots = segment.get("shots", [])
+        for i, shot in enumerate(shots, 1):
+            dur = shot.get("duration", 5)
+            content = shot.get("content", "").strip()
+            prompt += f"\n分镜{i}:[{dur}秒] {content}"
+            
+        return prompt
 
-    # ─── 预览 / Payload 构建 ───
+    def _get_style_keywords(self, session_data: dict) -> str:
+        """从会话数据获取风格关键词"""
+        style = session_data.get('style', 'realistic').lower()
+        
+        STYLE_MAP = {
+            "anime": "anime style, vibrant colors, clean lines,",
+            "realistic": "photorealistic, cinematic lighting, high-detail textures,",
+            "cartoon": "cartoon style, thick outlines, bold colors,",
+            "3d-disney": "3D CGI animation, Disney/Pixar style, smooth textures,",
+            "oil-painting": "oil painting, artistic brushstrokes, rich textures,",
+            "chinese-ink": "Chinese ink wash painting, traditional style, soft strokes,"
+        }
+        return STYLE_MAP.get(style, "cinematic, high quality,")
 
-    @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:
-        """构建视频片段预览列表"""
+    def _get_reference_image(self, sid: str, segment_id: str, scene_map: dict) -> str:
+        """获取参考图路径:优先用选中的版本,次之用最新版本"""
+        # 1. 检查 session 中 artifacts.reference_generation.scenes 里的 selected
+        if segment_id in scene_map and scene_map[segment_id].get("selected"):
+            path = scene_map[segment_id]["selected"]
+            if os.path.exists(path):
+                return path
+
+        # 2. 回退:扫描磁盘 Scenes 目录
+        from .reference_agent import ReferenceGeneratorAgent
+        versions = ReferenceGeneratorAgent._list_versions_static(sid, segment_id)
+        if versions:
+            return versions[-1]
+
+        # 3. 默认路径
+        return os.path.abspath(os.path.join('code/result/image', str(sid), 'Scenes', f"{segment_id}.jpg"))
+
+    # ─── 预览 / Payload ───
+
+    def _build_preview(self, sid: str, segments: list, scene_map: dict, style_name: str = "") -> 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', '')
+        for idx, seg in enumerate(segments, 1):
+            segment_id = seg["segment_id"]
+            versions = self._list_versions(sid, segment_id)
             preview.append({
-                "id": shot_id,
-                "name": self._shot_display_name(shot_id),
+                "id": segment_id,
+                "name": f"片段{idx} ({seg.get('location', '')})",
                 "index": idx,
-                "description": desc,
-                "duration": entry.get('duration', 5),
+                "description": self._assemble_prompt(seg, style_name),
+                "duration": seg.get('total_duration', 10),
                 "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: 用户修改的提示词,优先使用
-        """
+    def _build_payload(self, sid: str, segments: list, style_name: str = "") -> dict:
         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', '')
+        for idx, seg in enumerate(segments, 1):
+            segment_id = seg["segment_id"]
+            versions = self._list_versions(sid, segment_id)
             clips.append({
-                "id": shot_id,
-                "name": self._shot_display_name(shot_id),
+                "id": segment_id,
+                "name": f"片段{idx}",
                 "index": idx,
-                "description": desc,
-                "duration": entry.get('duration', 5),
+                "description": self._assemble_prompt(seg, style_name),
+                "duration": seg.get('total_duration', 10),
                 "selected": versions[-1] if versions else "",
                 "versions": versions,
                 "status": "done" if versions else "failed",
@@ -174,453 +193,227 @@
             "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
+    def _update_session_video_data(self, sid: str, segments: list, style_name: str) -> None:
+        """同步视频生成结果到 session.json 的 artifacts 中,适配前端读取"""
+        session_path = os.path.join('code/data/sessions', f'{sid}.json')
+        if not os.path.exists(session_path):
+            return
 
         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
+            with open(session_path, 'r', encoding='utf-8') as f:
+                data = json.load(f)
+            
+            payload = self._build_payload(sid, segments, style_name)
+            data.setdefault("artifacts", {})["video_generation"] = payload["payload"]
+            
+            # 同时保留一份给后端的 scene2video (如果需要)
+            # data[sid]["scene2video"] = ... (可选)
+            
+            with open(session_path, 'w', encoding='utf-8') as f:
+                json.dump(data, f, indent=4, ensure_ascii=False)
         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")
+            logger.error(f"Failed to update session video data: {e}")
 
     # ─── 核心流程 ───
 
     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"]
+        
+        # ═══ 介入:用户选择指定版本 ═══
+        if intervention and "selected_clips" in intervention:
+            selected_clips = intervention["selected_clips"] # Dict[segment_id, path]
+            logger.info(f"[VideoAgent] 用户更新片段选择: {selected_clips}")
+            
+            session_path = os.path.join('code/data/sessions', f'{sid}.json')
+            if os.path.exists(session_path):
+                with open(session_path, 'r', encoding='utf-8') as f:
+                    data = json.load(f)
+                
+                clips = data.get("artifacts", {}).get("video_generation", {}).get("clips", [])
+                for clip in clips:
+                    cid = clip.get("id")
+                    if cid in selected_clips:
+                        clip["selected"] = selected_clips[cid]
+                
+                with open(session_path, 'w', encoding='utf-8') as f:
+                    json.dump(data, f, indent=4, ensure_ascii=False)
+            
+            # 返回当前状态
+            artifacts = data.get("artifacts", {})
+            episodes = artifacts.get('storyboard', {}).get('episodes', [])
+            segments = []
+            for ep in episodes:
+                segments.extend(ep.get("segments", []))
+            return self._build_payload(sid, segments)
+
         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')
+        video_shot_type = input_data.get("video_shot_type", "multi")
+        
+        # 加载会话数据
+        session_path = os.path.join('code/data/sessions', f'{sid}.json')
+        with open(session_path, 'r', encoding='utf-8') as f:
+            session_data = json.load(f)
+            
+        artifacts = session_data.get("artifacts", {})
+        
+        # 1. 获取拍摄片段列表 (从 Storyboard)
+        episodes = artifacts.get('storyboard', {}).get('episodes', [])
+        segments = []
+        for ep in episodes:
+            segments.extend(ep.get("segments", []))
+            
+        if not segments:
+            raise Exception("未找到分镜片段数据,请先完成阶段3")
 
-        # 读取数据
-        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")
+        # 2. 获取参考图路径映射 (从 Reference Generation)
+        ref_art = artifacts.get('reference_generation', {})
+        scene_list = ref_art.get('scenes', [])
+        scene_map = {s['id']: s for s in scene_list if 'id' in s}
+        
+        style_zh = session_data.get('style', 'realistic')
+        # 简单映射为中文显示名
+        style_map_zh = {
+            "anime": "动漫",
+            "realistic": "写实",
+            "cartoon": "卡通",
+            "3d-disney": "3D迪斯尼",
+            "oil-painting": "油画",
+            "chinese-ink": "国画",
+            "comic-book": "美漫",
+            "cyberpunk": "赛博朋克"
+        }
+        style_name = style_map_zh.get(style_zh, style_zh)
 
         # ═══ 介入:重新生成指定片段 ═══
         if intervention:
-            regen_clips = intervention.get("regenerate_clips", [])
-
-            if regen_clips:
-                self._report_progress("视频生成", "重新生成中...", 10)
-
+            regen_ids = intervention.get("regenerate_clips", [])
+            if regen_ids:
+                self._report_progress("视频生成", "重新生成中...", 5)
+                segment_map = {s['segment_id']: s for s in segments}
+                
                 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)
+                        for seg_id in regen_ids:
+                            seg = segment_map.get(seg_id)
+                            if not seg: continue
+                            prompt = self._assemble_prompt(seg, style_name)
+                            img_path = self._get_reference_image(sid, seg_id, scene_map)
+                            duration = seg.get("total_duration", 10)
                             fut = executor.submit(
-                                self._generate_one, sid, shot_id, prompt,
-                                img_path, video_model, shot_duration,
-                                sound_param, video_shot_type, video_ratio
+                                self._generate_one, sid, seg_id, prompt,
+                                img_path, video_model, duration,
+                                "", video_shot_type, video_ratio
                             )
-                            futs[fut] = shot_id
+                            futs[fut] = seg_id
                         for fut in as_completed(futs):
-                            shot_id_done = futs[fut]
+                            sid_done = futs[fut]
                             try:
-                                _, result_path = fut.result()
+                                _, res_path = fut.result()
                             except Exception as e:
-                                logger.error(f"Regen future error for {shot_id_done}: {e}")
-                                result_path = None
+                                logger.error(f"Regen future error for {sid_done}: {e}")
+                                res_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={
+                            pct = 5 + int(90 * done / max(1, len(regen_ids)))
+                            if res_path:
+                                versions = self._list_versions(sid, sid_done)
+                                self._report_progress("视频生成", f"完成: {sid_done}", pct, data={
                                     "asset_complete": {
-                                        "type": "clips", "id": shot_id_done,
+                                        "type": "clips", "id": sid_done,
                                         "status": "done",
-                                        "selected": result_path,
+                                        "selected": res_path,
                                         "versions": versions,
                                     }
                                 })
                             else:
-                                self._report_progress("视频生成", f"失败: {shot_id_done}", pct, data={
+                                self._report_progress("视频生成", f"失败: {sid_done}", pct, data={
                                     "asset_complete": {
-                                        "type": "clips", "id": shot_id_done,
+                                        "type": "clips", "id": sid_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)
+                
+                # 同步到 session artifacts
+                self._update_session_video_data(sid, segments, style_name)
+                
+                return self._build_payload(sid, segments, style_name)
 
         # ═══ 正常流程:全量生成 ═══
-        self._report_progress("视频生成", "加载场景数据...", 5)
-
-        # 发送预览列表
-        preview = self._build_preview(sid, shot_keys, s2i)
-        self._report_progress("视频生成", "加载视频列表", 8, data={"assets_preview": {"clips": preview}})
+        self._report_progress("视频生成", "正在准备数据...", 2)
+        preview = self._build_preview(sid, segments, scene_map, style_name)
+        self._report_progress("视频生成", "加载视频列表", 5, 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))
-
+            for seg in segments:
+                seg_id = seg["segment_id"]
+                existing = self._list_versions(sid, seg_id)
+                if existing: continue
+                prompt = self._assemble_prompt(seg, style_name)
+                img_path = self._get_reference_image(sid, seg_id, scene_map)
+                duration = seg.get("total_duration", 10)
+                tasks.append((seg_id, prompt, img_path, duration))
             if not tasks:
-                self._report_progress("视频生成", "所有视频已存在", 95)
+                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:
+                for seg_id, prompt, img_path, dur 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
+                        self._generate_one, sid, seg_id, prompt,
+                        img_path, video_model, dur,
+                        "", video_shot_type, video_ratio
                     )
-                    futs[fut] = shot_id
+                    futs[fut] = seg_id
                 for fut in as_completed(futs):
-                    shot_id_done = futs[fut]
+                    sid_done = futs[fut]
                     try:
-                        _, result_path = fut.result()
+                        _, res_path = fut.result()
                     except Exception as e:
-                        logger.error(f"Video future error for {shot_id_done}: {e}")
-                        result_path = None
+                        logger.error(f"Video future error for {sid_done}: {e}")
+                        res_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={
+                    pct = 5 + int(90 * done / max(1, len(tasks)))
+                    if res_path:
+                        versions = self._list_versions(sid, sid_done)
+                        self._report_progress("视频生成", f"完成: {sid_done}", pct, data={
                             "asset_complete": {
-                                "type": "clips", "id": shot_id_done,
+                                "type": "clips", "id": sid_done,
                                 "status": "done",
-                                "selected": result_path,
+                                "selected": res_path,
                                 "versions": versions,
                             }
                         })
                     else:
-                        self._report_progress("视频生成", f"失败: {shot_id_done}", pct, data={
+                        self._report_progress("视频生成", f"失败: {sid_done}", pct, data={
                             "asset_complete": {
-                                "type": "clips", "id": shot_id_done,
+                                "type": "clips", "id": sid_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
+                            if not f.done(): f.cancel()
                         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
-
+        await loop.run_in_executor(None, run)
+        
+        # 同步到 session artifacts
+        self._update_session_video_data(sid, segments, style_name)
+        
         self._report_progress("视频生成", "完成", 100)
-        return self._build_payload(sid, shot_keys, s2i, clip_descriptions)
\ No newline at end of file
+        return self._build_payload(sid, segments, style_name)
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
new file mode 100644
index 0000000..9c127a7
--- /dev/null
+++ b/aigc-director/aigc-claw/backend/core/agents/video_agent.py.bak
@@ -0,0 +1,626 @@
+# -*- 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 56fc515..1cd3a9f 100644
--- a/aigc-director/aigc-claw/backend/core/orchestrator.py
+++ b/aigc-director/aigc-claw/backend/core/orchestrator.py
@@ -413,7 +413,13 @@
             if state.meta:
                 for k, v in state.meta.items():
                     if v is not None:
-                        data[k] = v
+                        # 转换并保持原始类型(尤其是布尔值)
+                        if isinstance(v, str) and v.lower() == 'true':
+                            data[k] = True
+                        elif isinstance(v, str) and v.lower() == 'false':
+                            data[k] = False
+                        else:
+                            data[k] = v
 
         # 原子写入:先写临时文件,再重命名
         dir_path = os.path.dirname(path)
diff --git a/aigc-director/aigc-claw/backend/docs/session_format.md b/aigc-director/aigc-claw/backend/docs/session_format.md
index 5a0bc40..9011504 100644
--- a/aigc-director/aigc-claw/backend/docs/session_format.md
+++ b/aigc-director/aigc-claw/backend/docs/session_format.md
@@ -53,10 +53,9 @@
 {
   "session_id": "...",
   "title": "守",
-  "logline": "一句话概括故事",
+  "logline": "详细故事梗概",
   "genre": ["奇幻", "温情"],
   "target_duration": 180,
-  "synopsis": "详细故事梗概",
   "characters": [
     {
       "name": "角色名",
diff --git a/aigc-director/aigc-claw/backend/prompts/reference/first_frame_en.txt b/aigc-director/aigc-claw/backend/prompts/reference/first_frame_en.txt
index 2268e70..e008ba2 100644
--- a/aigc-director/aigc-claw/backend/prompts/reference/first_frame_en.txt
+++ b/aigc-director/aigc-claw/backend/prompts/reference/first_frame_en.txt
@@ -1,15 +1,18 @@
-You are a professional AI prompt translator and optimizer.
-Please translate and optimize the following visual description into a pure English image generation prompt for an AI image model.
+You are an expert AI prompt engineer and cinematic storyboard director. Your task is to generate a purely English "First Frame Visual Description Prompt" for an AI video generation tool, based on the plot of a video segment (which includes shot types, actions, and dialogues), along with the relevant setting and character descriptions.
 
-Visual Description:
-{visual_prompt}
+[Segment Plot]
+{plot}
 
-Selected Style:
-{style}
+[Character Descriptions]
+{character_description}
 
-Requirements:
-1. The main body of the prompt MUST exclusively reflect the [Visual Description] above. Do not invent extraneous plot elements.
-2. Based on the [Selected Style], append appropriate English style descriptors and keywords.
-3. You must add quality-boosting prompt words (e.g., masterpiece, best quality, high resolution, cinematic composition, etc.).
-4. The output must be pure English, with traits ideally separated by commas.
-5. Output ONLY the optimized prompt text. Do NOT include any explanations, prefixes, or extra markers.
+[Setting Description]
+{setting_description}
+
+[Requirements]
+1. The prompt must focus solely on the **first frame** composition of this video segment. Primarily describe the initial action, the relative positions of the characters, the environmental layout, and the lighting/atmosphere.
+2. You must integrate visual details from the Character and Setting Descriptions accurately into the scene.
+3. Do not describe precise texts, lettering, or signs in the prompt, as AI often struggles with accurate text generation.
+4. The prompt must be entirely in English (preferably formatted as comma-separated tags instead of prose).
+5. Append high-quality modifiers (e.g., masterpiece, best quality, high resolution, cinematic composition).
+6. Output **only** the final English prompt text. Do NOT include any explanations, prefaces, or code block markers (```).
diff --git a/aigc-director/aigc-claw/backend/prompts/reference/first_frame_zh.txt b/aigc-director/aigc-claw/backend/prompts/reference/first_frame_zh.txt
index a9db037..236efe6 100644
--- a/aigc-director/aigc-claw/backend/prompts/reference/first_frame_zh.txt
+++ b/aigc-director/aigc-claw/backend/prompts/reference/first_frame_zh.txt
@@ -1,15 +1,18 @@
-你是一位专业的AI提示词翻译与优化专家。
-请将以下分镜视觉描述翻译成纯英文的图像生成提示词(image prompt),用于AI绘图模型。
+你是一位专业的AI提示词工程师与影视分镜导演。你的任务是根据一个拍摄分段的剧情(包含景别、动作、对话等),结合场地背景描述和相关人物描述,为这个拍摄片段生成用于AI视频生成工具的「首帧视觉描述提示词」(用纯英文输出)。
 
-分镜视觉描述:
-{visual_prompt}
+【拍摄片段剧情】
+{plot}
 
-用户选择的风格:
-{style}
+【人物外貌描述】
+{character_description}
 
-要求:
-1. 提示词主体必须紧扣上述的【分镜视觉描述】进行翻译,提炼画面要素,不要自行脑补多余的剧情。
-2. 根据用户选择的【风格】,在提示词前后加上相应的英文风格描述词。
-3. 必须加上提升画面质量的提示词(例如:masterpiece, best quality, high resolution, cinematic composition等)。
-4. 语言必须是纯英文,以逗号分隔特征词。
-5. 只输出合并优化后的提示词文本,不要出现任何解释语、前缀或多余内容。
+【场地背景描述】
+{setting_description}
+
+【要求】
+1. 提示词必须聚焦于这个片段的**视频首帧**画面。主要描述人物的相对位置、起始动作、整体环境结构和光影氛围。
+2. 必须将相关人物的外貌特征和场地的空间细节融入到提示词中。
+3. 不要包含具体的文字或符号描述,因为AI生成文字容易出错。
+4. 语言必须是纯英文(以逗号分隔的标签形式呈现),不要出现任何中文。
+5. 必须加上提升画面质量的提示词(例如:masterpiece, best quality, high resolution, cinematic composition等)。
+6. 只需要输出最终的纯英文提示词文本,不要出现任何解释语、前缀或代码块标记(不要```)。
diff --git a/aigc-director/aigc-claw/backend/prompts/script/act_extract_en.txt b/aigc-director/aigc-claw/backend/prompts/script/act_extract_en.txt
index 2053540..a28ea34 100644
--- a/aigc-director/aigc-claw/backend/prompts/script/act_extract_en.txt
+++ b/aigc-director/aigc-claw/backend/prompts/script/act_extract_en.txt
@@ -1,54 +1,39 @@
-You are a professional script analyst. Read the following Act {act_number} step outline carefully and extract it into a structured JSON format.
+You are a professional script analyst. Please carefully read the following [Full Script Text], and per instructions, extract the entirety of **Episode {act_number}**, reference the [Global Assets], and organize it into standard JSON format.
 
-Step outline:
+---
+
+[Global Assets]
+Character Library:
+{asset_characters}
+
+Setting Library:
+{asset_settings}
+
+---
+
+[Full Script Text]
 {outline}
 
-Output ONLY valid JSON in the following structure (no code block markers, no comments, no other text):
+---
 
+[Important Rules]
 
+1. Extract the entirety of Episode {act_number} from the [Full Script Text].
+2. Provide a one-sentence summary for `episode_title`.
+3. Put the full text of this episode into `episode_content`, preserving all details, dialogue, and actions.
+4. Keep the `scenes` array empty `[]` as scene extraction will be handled in a later stage.
+5. `episode_number` must be {act_number}.
+6. Output ONLY pure JSON. Do NOT generate `characters` and `settings` arrays.
+
+---
+
+[Output Format]
+
+Please strictly output in the following JSON structure (direct pure JSON, no ``` wrappers, no extra text):
 
 {{
-  "characters": [
-    {{
-      "name": "Full name",
-      "character_id": "char_ plus 8 random alphanumeric",
-      "description": "Visual description: hair, eyes, build, clothing details, 50-80 words",
-      "personality": ["trait1", "trait2", "trait3"],
-      "motivation": "Core motivation",
-      "arc_description": "Character growth arc",
-      "role": "protagonist or supporting or background",
-      "age": "age",
-      "species": "human or specific animal"
-    }}
-  ],
-  "settings": [
-    {{
-      "name": "Location name (Indoor) or Location name (Outdoor)",
-      "setting_id": "set_ plus 8 random alphanumeric",
-      "description": "Layout, colors, lighting, atmosphere details, 80-120 words, no people or animals"
-    }}
-  ],
-  "scenes": [
-    {{
-      "scene_number": {scene_start},
-      "act": {act_number},
-      "location": "Must be a name defined in settings",
-      "characters": ["character names matching characters array"],
-      "plot": "Complete detailed scene plot with dialogue, actions and expressions, no word limit"
-    }}
-  ]
+  "episode_number": {act_number},
+  "episode_title": "A one-sentence summary of Episode {act_number}",
+  "episode_content": "The full script text of this episode (containing all details, dialogue)",
+  "scenes": []
 }}
-
-
-
-Important rules:
-1. Character names in scenes must exactly match names in characters array
-2. Scene locations must be names defined in settings array
-3. Setting names must include (Indoor) or (Outdoor)
-4. All scenes' act field must be {act_number}
-5. scene_number starts from {scene_start} and increments
-6. Character descriptions need enough visual detail for AI image generation
-7. Setting descriptions need enough visual detail for AI background generation
-8. No group characters, every character is an individual
-9. Scene 'plot' field must fully express all content, do not truncate
-10. Output ONLY the JSON
diff --git a/aigc-director/aigc-claw/backend/prompts/script/act_extract_zh.txt b/aigc-director/aigc-claw/backend/prompts/script/act_extract_zh.txt
index 2133d87..8f7c2ae 100644
--- a/aigc-director/aigc-claw/backend/prompts/script/act_extract_zh.txt
+++ b/aigc-director/aigc-claw/backend/prompts/script/act_extract_zh.txt
@@ -1,76 +1,35 @@
-你是一个专业的剧本分析师,擅长从一个剧本中提取涉及到的所有背景、人物,并对剧本进行分场。
-请仔细阅读以下第{act_number}幕的【分场大纲】,严格遵循【重要规则】,从剧本中提取并整理为【输出格式】中的标准JSON格式。
+你是一个专业的剧本分析师。你需要将剧本中的全集内容,根据集数标签(如“第1集”、“第2集”等)准确拆分为数组格式。
 
 ---
 
-【分场大纲】
-{outline}
+【剧本输入】
+
+{script_text}
 
 ---
 
-【重要规则】
+【拆分要求】
 
-1. characters中的name必须与scenes中的角色名完全一致
-2. scenes中的location必须是settings中已定义的场景名称之一
-3. settings的name需标注(室内)或(室外)
-4. 所有scene的act字段必须为{act_number}
-5. scene_number从{scene_start}开始递增
-6. 角色描述规范:
-   - 采用“年龄+性别+发型/首饰+服装+体型+面部特征/神态”的概括性写法。
-   - 核心特征:必须包含发型、体型、服装颜色和款式等视觉特征。
-   - 示例:
-     - ”40多岁中年男性,大背头,穿着考究的深色西装,体型微胖,面相精明且神态傲慢。“
-     - ”20多岁男性,短发,戴黑框眼镜,五官清秀且透着坚毅,穿着程序员风格的休闲卫衣。“
-   - 外貌必须正常:严禁描述伤口、血迹、残疾或过于奇特畸形的外形。
-   - 头发颜色必须正常:如黑色、棕色、金色等,严禁描述“发根青黑”、“斑驳色块”等微观细节(模型无法理解)。
-   - 禁止项:不要描述眼睛颜色,面部不要有文字、刺青或特殊几何符号。
-   - 风格要求:30-50字,语言平实直接,禁止使用比喻或文学化修辞。
-7. 场景描述规范:
-   - 采用“场景定位+核心物件+空间感受+色调光影”的概括性写法。
-   - 示例:
-     - ”现代企业办公区,密集的工位,杂乱的桌面,狭窄的走廊。场景呈现压抑的冷蓝灰色调,缺乏自然光。”
-     - ”高端明亮的独立办公室及会议室,宽大的会议桌,通透的落地窗。场景呈现温暖明亮的金色调,充满生机与质感。”
-   - 严禁堆砌琐碎细节,强调视觉印象(例如“现代办公区,杂乱桌面,压抑冷蓝调”)。
-   - 字数要求:30-50字。
-   - 禁止项:严禁在场景描述中包含人物或动物。
-8. 不要生成群体角色(如"邻居们"),每个角色都是独立个体
-9. scene的plot字段必须完整表达该分场的全部内容
-10. 只输出纯JSON
+1. 请将输入的剧本内容按集数归纳到对应的 `episode_number` 下。
+2. `act_title` 请提取该集的标题或前10个字。
+3. `content` 请保留该集的完整剧本正文(包含场景描述、动作说明和角色台词)。
+
+**注意(严格遵守):**
+1. **输出格式**:必须且仅能输出一个纯净的 JSON 数组。严禁包含任何 Markdown 格式(如 ```json 代码块)、解释性文字、分析或结束语。
+2. 确保 JSON 结构完整且合法。
 
 ---
 
-【输出格式】
-
-请严格按照以下JSON结构输出(直接输出纯JSON,不要用```包裹,不要添加注释或任何其他文字):
-
-{{
-  "characters": [
-    {{
-      "name": "角色全名",
-      "character_id": "char_加8位随机字母数字",
-      "description": "外貌描写: 遵循角色描述规范, 30-50字",
-      "personality": ["性格特征1", "性格特征2", "性格特征3"],
-      "motivation": "角色核心动机",
-      "arc_description": "角色成长弧线",
-      "role": "主角 或 配角 或 背景",
-      "age": "年龄",
-      "species": "人类 或 具体动物种类"
-    }}
-  ],
-  "settings": [
-    {{
-      "name": "场景名称(室内) 或 场景名称(室外)",
-      "setting_id": "set_加8位随机字母数字",
-      "description": "概括性场景描述:核心功能区、核心家具/物件、空间感受、色调与光影。30-50字。"
-    }}
-  ],
-  "scenes": [
-    {{
-      "scene_number": {scene_start},
-      "act": {act_number},
-      "location": "必须是settings中已定义的场景名称",
-      "characters": ["出场角色名(必须与characters中的name一致)"],
-      "plot": "该场景完整详细的剧情, 含对话、动作和表情描写, 必须完整表达分场内容, 无字数限制"
-    }}
-  ]
-}}
+【输出格式示例(仅返回此 JSON 数组)】
+[
+  {{
+    "episode_number": 1,
+    "act_title": "激励事件/剧集标题",
+    "content": "具体的剧本正文内容..."
+  }},
+  {{
+    "episode_number": 2,
+    "act_title": "进入新世界/剧集标题",
+    "content": "具体的剧本正文内容..."
+  }}
+]
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/script/beat_sheet_en.txt b/aigc-director/aigc-claw/backend/prompts/script/beat_sheet_en.txt
deleted file mode 100644
index c6b4b0b..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/beat_sheet_en.txt
+++ /dev/null
@@ -1,19 +0,0 @@
-You are a Hollywood screenwriting mentor. Break down the following storyline into a 4-act structure using the Save the Cat! Beat Sheet.
-
-Must include these four key beats:
-Act 1 - Inciting Incident: Establish the world and protagonist's status quo, then a disruptive event
-Act 2 - Break into Two: Protagonist embarks on journey, faces challenges, B-story unfolds
-Act 3 - Dark Night of the Soul: Protagonist suffers the biggest blow, hits rock bottom
-Act 4 - Finale: Protagonist gains epiphany, final confrontation, story resolves
-
-Ensure: tight logic, escalating conflict, and clear turning points in each act. Crucially, you must preserve and integrate key details, specific imagery, or core creative ideas (User Idea) from the original input.
-
-Storyline:
-{draft}
-
-User Core Idea/Specific Requirements:
-{idea}
-
-Story style: {style}
-
-Output the 4-act beat sheet directly. Start each act with '[Act X - Name]' heading. Detail the plot points, character development and key turning points for each act.
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/script/beat_sheet_zh.txt b/aigc-director/aigc-claw/backend/prompts/script/beat_sheet_zh.txt
deleted file mode 100644
index 63f7a02..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/beat_sheet_zh.txt
+++ /dev/null
@@ -1,33 +0,0 @@
-你是好莱坞编剧导师。请根据以下故事线,使用 Save the Cat! 节拍表将故事拆解为四幕结构。
-
-必须包含以下四个关键节拍(起承转合):
-第一幕 - 激励事件(Inciting Incident):建立世界观和主角现状,发生打破平衡的事件
-第二幕 - 进入新世界(Break into Two):主角踏上旅程,面对挑战和考验,副线展开
-第三幕 - 灵魂黑夜(Dark Night of the Soul):主角遭受最大打击,陷入低谷
-第四幕 - 高潮决战(Finale):主角获得顿悟,最终决战,故事收束
-
-确保:逻辑严密、冲突逐步升级、每一幕有清晰的转折点。务必保留并整合用户原始输入中的关键细节、特定意象或核心创意(User Idea)。
-请直接输出四幕节拍表,每一幕用"【第X幕 - 名称】"标记开始,详细描述该幕的情节要点、角色发展和关键转折。
-
----
-
-输入
-
-故事大纲:
-{draft}
-
-用户核心创意/细节要求:
-{idea}
-
-故事风格:{style}
-
----
-
-输出格式
-
-【主角】xxx
-【主要配角】xxx, xxx
-【第一幕 - xxx】 xxx
-【第二幕 - xxx】 xxx
-【第三幕 - xxx】 xxx
-【第四幕 - xxx】 xxx
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/script/consolidate_en.txt b/aigc-director/aigc-claw/backend/prompts/script/consolidate_en.txt
deleted file mode 100644
index 056304b..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/consolidate_en.txt
+++ /dev/null
@@ -1,21 +0,0 @@
-You are a script review expert. Review the following settings and characters lists and identify entries that should be merged.
-
-Merge rules:
-- Settings merge: If two settings are the same physical location (just different camera angles), merge them into one. E.g., 'Train interior', 'Train aisle', 'Train panorama' are all the same car.
-  Different physical spaces should NOT be merged.
-- Character merge: If the same character appears with slightly different descriptions, merge them.
-- Keep the most detailed description after merging.
-
-Current settings:
-{settings_json}
-
-Current characters:
-{characters_json}
-
-Output ONLY valid JSON (no code blocks):
-{{
-  "setting_merges": {{"merged_setting_name": "target_setting_name", ...}},
-  "character_merges": {{"merged_char_name": "target_char_name", ...}}
-}}
-
-If nothing to merge, return empty objects {{}}. Output ONLY the JSON.
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/script/consolidate_zh.txt b/aigc-director/aigc-claw/backend/prompts/script/consolidate_zh.txt
deleted file mode 100644
index 0e3528e..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/consolidate_zh.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-你是剧本审校专家。请审查以下剧本中的场景列表和角色列表,找出可以合并的条目。
-
-合并规则:
-- 场景合并:如果两个场景在物理空间上是同一个地点(只是拍摄角度、景别不同),应合并为一个
-  例如:「车厢内」「车厢过道」「车厢全景」都是同一节车厢 → 合并为「车厢内」
-  例如:「咖啡馆吧台」「咖啡馆角落」→ 合并为「咖啡馆」
-  注意:不同物理空间不能合并(如「车厢内」和「车厢连接处」是不同空间)
-- 角色合并:如果同名角色出现多次(可能描述略有不同),合并为一个
-- 合并后保留最详细的描述
-
-当前场景列表:
-{settings_json}
-
-当前角色列表:
-{characters_json}
-
-请输出纯JSON(不要用```包裹),格式如下:
-{{
-  "setting_merges": {{"被合并的场景名": "合并到的目标场景名", ...}},
-  "character_merges": {{"被合并的角色名": "合并到的目标角色名", ...}}
-}}
-
-如果没有需要合并的条目,对应字段返回空对象 {{}}。
-只输出纯JSON,不要添加任何其他文字。
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/script/generate_script_en.txt b/aigc-director/aigc-claw/backend/prompts/script/generate_script_en.txt
new file mode 100644
index 0000000..a0d39ec
--- /dev/null
+++ b/aigc-director/aigc-claw/backend/prompts/script/generate_script_en.txt
@@ -0,0 +1,46 @@
+You are an expert micro-drama screenwriter. Based on the user's "core idea" and "story style", directly write out the complete micro-drama script.
+
+[Script Format and Writing Methodology]:
+1. **Episodic Structure**: The script must be divided into episodes (e.g., "Episode 1", "Episode 2"...), and each episode must have a fast pace.
+2. **Scene and Layout Format**: You must strictly follow the industrial scene script format.
+   For example: `**x-x Day/Night Int/Ext Scene Name**`
+   The next line specifies `Characters: xxx, xxx`, followed by a blank line.
+3. **Action and Visual Descriptions**: Action descriptions must start with "<action>" (e.g., "<action>Lin Yichen stares at the screen, dark circles under his eyes..."). Never write psychological activities that cannot be filmed.
+4. **Vivid and Concise Dialogue**: Dialogues should fit the character's identity and emotions. Emotion and action hints are written in parentheses after the character's name. Example: `Lin Yichen (sneering): ...`
+5. **Strong Dramatic Satisfaction**: The opening should quickly cut into the core conflict (such as being fired, betrayed, humiliated), and then swiftly enter the counterattack/entrepreneurship/face-slapping phase. The pace must be fast and emotions high.
+6. **Visual Contrast**: Use the contrast between bottom-level dilapidated scenes and top-level luxurious scenes to enhance dramatic tension.
+7. **No Separate Lore/Settings**: Do not write character bios or background outlines. Start the script text directly.
+
+---
+[Script Example (Learn its action, dialogue, and rhythmic structure)]:
+## Episode 1
+
+**1-1 Day Int Tech Company Office**
+
+Characters: Lin Yichen, Boss Wang, Colleague A, Colleague B, HR Sister Li
+
+<action>Inside the office, cubicles are densely packed, programmers are buried in writing code, the atmosphere is oppressive.
+
+<action>Lin Yichen stares at the screen, dark circles under his eyes, his fingers typing quickly on the keyboard.
+
+<action>Boss Wang, with a beer belly, paces behind Lin Yichen.
+
+Boss Wang (sarcastically): Lin Yichen, you haven't finished this module you've been writing for three days? Did I hire you to do nothing?
+
+Lin Yichen (without looking up): Boss Wang, this architecture needs refactoring. The previous technical debt is too heavy...
+
+Boss Wang (slamming the table): Stop making excuses! Little Zhang launched three features in two days, what about you? Low efficiency is an ability problem!
+
+<action>Lin Yichen takes a deep breath and continues typing.
+
+(...End of example...)
+
+---
+[User Core Idea]:
+{idea}
+
+[Story Style]:
+{style}
+
+---
+Take a deep breath and start your creation. Based on the inspiration above, directly output the complete script text (containing the full content of 4-6 episodes). Do not include any filler words or prefaces.
diff --git a/aigc-director/aigc-claw/backend/prompts/script/generate_script_zh.txt b/aigc-director/aigc-claw/backend/prompts/script/generate_script_zh.txt
new file mode 100644
index 0000000..67b1c80
--- /dev/null
+++ b/aigc-director/aigc-claw/backend/prompts/script/generate_script_zh.txt
@@ -0,0 +1,64 @@
+你是顶级微短剧编剧专家。请根据用户提供的“核心灵感”与“故事风格”,直接创作出完整的微短剧剧本。
+
+【剧本格式与创作方法】:
+1. **分集结构**:剧本必须分集(如“等1集”、“第2集”...),每一集起承转合要快。
+2. **场次与排版格式**:必须严格遵循工业场志格式。
+   例如:`**x-x 日/夜 内/外 场景名称**`
+   下一行写明`人物:xxx, xxx`,再下一行空出。
+3. **动作与视觉描述**:动作描述必须以“<action>”开头,描述客观存在的物理动作和镜头画面(如“<action>林逸尘盯着屏幕,眼眶乌青,手指在键盘上飞快敲击。”)。绝不写无法拍出的心理活动。
+4. **生动的对话**:对白要符合人物的身份与情绪,情绪和动作提示写在角色名后的括号里。例如:`林逸尘(冷笑):……`
+5. **强烈的剧作爽感**:开场迅速切入核心冲突(如被开除、被背叛、被羞辱等最低谷),然后迅速进入反击/创业/打脸环节,节奏必须要快,情绪拉满。
+6. **场景与视觉反差**:利用底层破败场景与顶层奢华场景的落差,增强戏剧张力。
+7. **不要单独的设定集**:不需要写人物小传或大纲背景,直接开始写剧本正文。
+8. **用台词推动情节发展**:多使用对白、独白、画外音来表达角色的想法,推动情节发展,制造矛盾冲突。
+
+---
+
+【剧本示例(参考学习其动作、对白与节奏结构)】:
+
+## 第1集
+
+**1-1 日 内 科技公司办公室**
+
+人物:林逸尘,王总,同事甲、乙,HR李姐
+
+<action>办公室内,格子间密密麻麻,程序员们埋头敲代码,气氛压抑。
+
+<action>林逸尘盯着屏幕,眼眶乌青,手指在键盘上飞快敲击。
+
+<action>王总挺着啤酒肚,踱步到林逸尘身后。
+
+王总(冷嘲热讽):林逸尘,你这个模块写了三天了还没搞定?我招你进来是吃干饭的?
+
+林逸尘(头也不抬):王总,这个架构需要重构,之前的技术债太重了……
+
+王总(猛地拍桌):少给我找借口!人家小张两天就上线了三个功能,你呢?效率低下就是能力问题!
+
+<action>林逸尘手指顿了顿,没有说话。
+
+<action>同事甲凑过来,小声嘀咕。
+
+同事甲:逸尘,你就别顶嘴了,上个月老李就是顶嘴被开了。
+
+<action>林逸尘深吸一口气,继续敲代码。
+
+王总(指着屏幕):今晚12点之前,这个模块必须上线。不然这个月绩效全扣!
+
+<action>王总转身离开,走到半路又回头。
+
+王总:对了,周末团建你得来,别又找借口加班。团队凝聚力也是考核指标!
+
+<action>林逸尘攥紧鼠标,指节发白。
+
+(...示例结束...)
+
+---
+【用户核心灵感/故事设定】:
+{idea}
+
+【故事风格】:
+{style}
+
+---
+
+接下来,开始你的创作。根据上述灵感,直接输出完整的剧本正文(包含4-6集的完整内容)。不需要任何废话和前言后语。
diff --git a/aigc-director/aigc-claw/backend/prompts/script/logline_check_en.txt b/aigc-director/aigc-claw/backend/prompts/script/logline_check_en.txt
deleted file mode 100644
index 272eed5..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/logline_check_en.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-Determine if the following text contains enough narrative elements for a complete story Logline.
-(Needs: protagonist, goal, conflict, twist, and theme)
-
-Text: {idea}
-
-Answer only Yes or No.
diff --git a/aigc-director/aigc-claw/backend/prompts/script/logline_check_zh.txt b/aigc-director/aigc-claw/backend/prompts/script/logline_check_zh.txt
deleted file mode 100644
index b271323..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/logline_check_zh.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-请判断以下文本是否包含足够的叙事要素,能够从中总结出一个完整故事的 Logline。
-(完整 Logline 需涵盖:主角、目标、核心障碍、反转和主题)
-
-文本:{idea}
-
-只回答 Yes 或 No,不要添加任何其他内容。
diff --git a/aigc-director/aigc-claw/backend/prompts/script/logline_extract_en.txt b/aigc-director/aigc-claw/backend/prompts/script/logline_extract_en.txt
deleted file mode 100644
index 0a2b96e..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/logline_extract_en.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-You are a senior producer. Extract the Logline and five story elements from the following text.
-The Logline should use 'What if...' format.
-
-Text: {idea}
-
-Output ONLY valid JSON (no code block markers, no other text):
-{{"logline":"What if...","who":"protagonist","goal":"goal","conflict":"conflict","twist":"twist","theme":"theme"}}
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/script/logline_extract_zh.txt b/aigc-director/aigc-claw/backend/prompts/script/logline_extract_zh.txt
deleted file mode 100644
index ab2473a..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/logline_extract_zh.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-你是资深制片人。请从以下文本中总结提取 Logline 及故事五要素。
-Logline 请使用"如果…会怎样"的句式。
-
-文本:{idea}
-
-请严格按如下 JSON 格式输出(直接输出纯JSON,不要用```包裹,不要添加任何其他文字):
-{{"logline":"如果...会怎样","who":"主角描述","goal":"目标","conflict":"核心障碍","twist":"反转","theme":"潜在主题"}}
diff --git a/aigc-director/aigc-claw/backend/prompts/script/logline_generate_en.txt b/aigc-director/aigc-claw/backend/prompts/script/logline_generate_en.txt
deleted file mode 100644
index bbf7f8e..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/logline_generate_en.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-You are a senior producer. Expand the following idea into 3 different Loglines.
-Requirements:
-- Define the protagonist (Who), Goal, core Conflict, and Twist
-- Identify the story's Theme
-- Expand into the following three fixed styles, and prefix the logline with the 【Style】 tag:
-    1. Web Novel (Fast-paced/Gratifying)
-    2. Suspense/Mind-bending
-    3. Philosophical/Contemplative
-- The 3 Loglines should be diverse in style and focus
-
-Input: {idea}
-
-Output ONLY a JSON array with exactly 3 elements (no code block markers, no other text):
-[{{"logline":"【Style Name】Story outline content","who":"protagonist","goal":"goal","conflict":"conflict","twist":"twist","theme":"theme"}}]
diff --git a/aigc-director/aigc-claw/backend/prompts/script/logline_generate_zh.txt b/aigc-director/aigc-claw/backend/prompts/script/logline_generate_zh.txt
deleted file mode 100644
index caf3828..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/logline_generate_zh.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-你是资深制片人。请将以下灵感扩展为 3 个不同的 Logline(故事大纲)。
-要求:
-- 明确主角(Who)、目标(Goal)、核心障碍(Conflict)和反转(Twist)
-- 确定故事的 Theme(潜在主题)
-- 固定扩写以下三个方向,并在 logline 前面增加【风格】标注:
-    1. 网络爽文
-    2. 悬疑烧脑
-    3. 哲理思辨
-- 3 个 Logline 应风格各异、各有侧重
-
-输入内容:{idea}
-
-请严格按如下 JSON 数组格式输出(直接输出纯JSON,不要用```包裹,不要添加任何其他文字):
-[{{"logline":"【风格名】故事大纲内容","who":"主角描述","goal":"目标","conflict":"核心障碍","twist":"反转","theme":"潜在主题"}}]
-输出恰好 3 个元素的 JSON 数组。
diff --git a/aigc-director/aigc-claw/backend/prompts/script/meta_extract_en.txt b/aigc-director/aigc-claw/backend/prompts/script/meta_extract_en.txt
index b4c9ea2..8c9dd85 100644
--- a/aigc-director/aigc-claw/backend/prompts/script/meta_extract_en.txt
+++ b/aigc-director/aigc-claw/backend/prompts/script/meta_extract_en.txt
@@ -1,6 +1,26 @@
-You are a professional script analyst. Here is the complete 4-act beat sheet:
+You are a professional script analyst. Below is the complete full script text:
 
-{beat_sheet}
+{script_text}
 
-Extract the following information as pure JSON (no code blocks):
-{{"title":"Story title (short)","logline":"One sentence summary","genre":["genre1","genre2"],"synopsis":"Complete synopsis (100-200 words)","mood":"Overall mood"}}
\ No newline at end of file
+Please extract the following information, specifically building the [Global Asset Tone (Core Characters and Main Settings)]. Their appearances and layouts will remain unchanged throughout the drama. Additionally, tell me how many total episodes and their titles.
+Output ONLY pure JSON format (direct JSON, no ``` wrappers, no extra text):
+{{
+  "title": "Story Title (2-8 words)",
+  "logline": "Complete story synopsis (100-200 words)",
+  "total_episodes": 4, // Actual total number of episodes present in text
+  "genre": ["genre1", "genre2"],
+  "mood": "Emotional tone",
+  "characters": [
+    {{
+      "name": "Full name of protagonist/major supporting character",
+      "description": "Appearance: age+gender+hairstyle/jewelry+clothing+body type+facial features. Must be objective visual description, no metaphors, 30-50 words.",
+      "species": "Human or specific animal species"
+    }}
+  ],
+  "settings": [
+    {{
+      "name": "Main Setting Name (Int) or (Ext)",
+      "description": "General setting description: core functional areas, main furniture/objects, spatial perception, color palette and lighting. No characters, 30-50 words."
+    }}
+  ]
+}}
\ No newline at end of file
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 c4d3b7c..d7dbb3b 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
@@ -1,6 +1,51 @@
-你是专业的剧本分析师。以下是完整的四幕节拍表:
+你是一个专业的剧本设计师。你需要提取剧本的信息,设计人物形象、场地布置。
 
-{beat_sheet}
+---
 
-请从中提取以下信息,以纯JSON格式输出(不要用```包裹):
-{{"title":"故事标题(2-8字)","logline":"一句话概括故事(30字以内)","genre":["类型1","类型2"],"synopsis":"完整故事梗概(100-200字)","mood":"影片情绪基调"}}
\ No newline at end of file
+【剧本输入】
+
+以下是完整的全集剧本文本:
+
+{script_text}
+
+---
+
+【设计要求】
+
+请从中【剧本输入】中提取以下信息,特别是构建【全局资产基调(核心角色与主场景)】。这些资产的外貌和布局将贯穿全剧保持不变。此外,请告诉我总共有多少集(幕)。
+
+**注意(严格遵守):**
+1. **输出格式**:必须且仅能输出一个纯净的 JSON 对象。严禁包含任何 Markdown 格式(如 ```json 代码块)、解释性文字、开场白或结尾。
+2. 提取所有在剧本中出现的、有台词或重要动作的【角色】(不仅仅是主角)。
+3. 提取所有在剧本中具体描述过的、不同地理位置的【场景】(不仅仅是概括性的)。
+4. 角色描述:
+   - 采用“年龄+性别+发型/首饰+服装+体型+面部特征/神态”的概括性写法。
+   - 核心特征:必须包含发型、体型、服装颜色和款式等视觉特征。
+   - 严禁加入科幻或幻想元素,外貌必须正常。
+   - 风格要求:30-50字,语言平实直接,禁止使用比喻或文学化修辞。
+5. 场地布置:
+   - 采用“空间类型+光效方向与颜色+核心陈设(质感/材质)+环境氛围”的概括性写法。
+   - 示例:“现代简约办公室,清冷的月光从落地窗洒入,办公桌为冷色实木,空气透着宁静与严肃。”
+   - 风格要求:30-50字,描述具体且具备可拍摄感。
+
+---
+
+【输出格式示例(仅返回此 JSON 对象)】
+{{
+  "title": "剧本名称",
+  "num_episodes": 4,
+  "mood": "影片情绪基调",
+  "characters": [
+    {{
+      "name": "主角/重要配角全名",
+      "description": "外貌描写,要求参见【设计要求】",
+      "species": "人类 或 具体动物种类"
+    }}
+  ],
+  "settings": [
+    {{
+      "name": "具体场地名称",
+      "description": "概括性场地描述,要求参见【设计要求】"
+    }}
+  ]
+}}
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/script/micro_beat_sheet_en.txt b/aigc-director/aigc-claw/backend/prompts/script/micro_beat_sheet_en.txt
deleted file mode 100644
index daaabc9..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/micro_beat_sheet_en.txt
+++ /dev/null
@@ -1,18 +0,0 @@
-You are a micro-film screenwriting expert. Compress the following storyline into a compact single-act plot summary.
-
-Requirements:
-- Fast narrative pacing, concise and tight plot
-- All content in a single act, no act divisions
-- Keep core conflict and emotional turns, remove unnecessary setup
-- 3-6 scenes total
-- Suitable for a 1-3 minute short film
-
-Storyline:
-{draft}
-
-User Core Idea/Specific Requirements (Must preserve and integrate):
-{idea}
-
-Story style: {style}
-
-Output a compact plot summary directly, describing scene progression, core actions and emotional shifts.
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/script/micro_beat_sheet_zh.txt b/aigc-director/aigc-claw/backend/prompts/script/micro_beat_sheet_zh.txt
deleted file mode 100644
index 18cff33..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/micro_beat_sheet_zh.txt
+++ /dev/null
@@ -1,31 +0,0 @@
-你是微电影编剧专家。请根据以下故事线,将故事压缩为一个紧凑的单幕剧情概要。
-
-要求:
-- 叙事节奏快,情节紧凑精炼,没有拖沓的铺垫
-- 全部内容在一幕内完成,不分幕
-- 保留核心冲突和情感转折,去掉多余叙事
-- 场景数量控制在 3-6 场
-- 适合 1-3 分钟的微电影
-
-确保:逻辑严密、冲突逐步升级、每一幕有清晰的转折点。务必保留并整合用户原始输入中的关键细节、特定意象或核心创意(User Idea)。
-请直接输出紧凑的剧情概要,描述场景发展、核心动作和情感转折。
-
----
-
-输入
-
-故事大纲:
-{draft}
-
-用户核心创意/细节要求:
-{idea}
-
-故事风格:{style}
-
----
-
-输出格式
-
-【主角】xxx
-【主要配角】xxx, xxx
-【剧情】 xxx
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/script/micro_meta_extract_en.txt b/aigc-director/aigc-claw/backend/prompts/script/micro_meta_extract_en.txt
deleted file mode 100644
index 3dceddf..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/micro_meta_extract_en.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-You are a professional script analyst. Here is the micro-film plot summary:
-
-{beat_sheet}
-
-Extract the following information as pure JSON (no code blocks):
-{{"title":"Story title (short)","logline":"One sentence summary","genre":["genre1","genre2"],"synopsis":"Complete synopsis (50-100 words)","mood":"Overall mood"}}
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/script/micro_meta_extract_zh.txt b/aigc-director/aigc-claw/backend/prompts/script/micro_meta_extract_zh.txt
deleted file mode 100644
index f242133..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/micro_meta_extract_zh.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-你是专业的剧本分析师。以下是微电影剧情概要:
-
-{beat_sheet}
-
-请从中提取以下信息,以纯JSON格式输出(不要用```包裹):
-{{"title":"故事标题(2-8字)","logline":"一句话概括故事(30字以内)","genre":["类型1","类型2"],"synopsis":"完整故事梗概(50-100字)","mood":"影片情绪基调"}}
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/script/micro_step_outline_en.txt b/aigc-director/aigc-claw/backend/prompts/script/micro_step_outline_en.txt
deleted file mode 100644
index 6fa4910..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/micro_step_outline_en.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-You are a scene director. Here is the micro-film plot summary:
-
-{beat_sheet}
-
-Convert it into a detailed step outline.
-
-Format for each scene:
-[Scene number]. [Location (Indoor/Outdoor)] - [Day/Night]
-[Core Action]: Detailed description including dialogue, actions and expressions.
-[Emotional Shift]: Protagonist's emotional change from start to end (+/-).
-[Characters Present]: All characters appearing in this scene.
-
-Requirements:
-- Each character needs detailed physical descriptions (hair, eyes, build, clothing)
-- **IMPORTANT: Physical descriptions must be STATIC and consistent throughout the entire story - do NOT change with plot development**
-  - For example: do NOT write "wearing torn clothes" which changes with the plot
-  - Instead write: "wearing a blue shirt and black pants" which is a fixed clothing description
-- Each scene needs detailed environment, layout, color and atmosphere descriptions
-- 3-6 scenes total, compact and fast-paced
-- Dialogue marked with double quotes, natural and vivid
-- Scene numbers start from 1 and increment
-- Story style: {style}
-
-Output the step outline directly, without extra notes.
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/script/micro_step_outline_zh.txt b/aigc-director/aigc-claw/backend/prompts/script/micro_step_outline_zh.txt
deleted file mode 100644
index 6e12225..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/micro_step_outline_zh.txt
+++ /dev/null
@@ -1,23 +0,0 @@
-你是分场导演。以下是微电影剧情概要:
-
-{beat_sheet}
-
-请将其转化为详细的分场大纲。
-
-格式要求(每场一段):
-[场次]. [地点(室内/室外)] - [日/夜]
-[角色]:列出本场出现的所有角色。
-[情节]:详细描述该场戏发生了什么,包含完整的对话、动作和表情描写。
-
-要求:
-- 每个角色都要有详细的外貌描写(发型、眼睛颜色、体型、服装颜色和款式等视觉特征)
-- **重要:外貌描写必须是静态的、贯穿全剧保持一致的特征,不要随剧情发展而变化**
-  - 例如:不要写"他穿着破碎的衣服"这种随情节变化的描写
-  - 应该写:"他身穿蓝色衬衫,黑色长裤"这种固定的服装描述
-- 每个场景都要有详细的环境、布局、色彩与氛围描写
-- 分场数量 3-6 场,叙事紧凑,依靠台词(对话、内心独白)快速推进情节
-- 对话用双引号标注,对话内容真实生动
-- 场次编号从 1 开始递增
-- 故事风格:{style}
-
-请直接输出分场大纲,不要添加额外说明。
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/script/step_outline_en.txt b/aigc-director/aigc-claw/backend/prompts/script/step_outline_en.txt
deleted file mode 100644
index 2a1a5e1..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/step_outline_en.txt
+++ /dev/null
@@ -1,24 +0,0 @@
-You are a scene director. Here is the complete 4-act beat sheet:
-
-{beat_sheet}
-
-Convert Act {act_number} ({act_name}) into a detailed step outline.
-
-Format for each scene:
-[Scene number]. [Location (Indoor/Outdoor)] - [Day/Night]
-[Core Action]: Detailed description of what happens, including dialogue, actions and expressions.
-[Emotional Shift]: Describe the protagonist's emotional change from start to end (+/-).
-[Characters Present]: List all characters appearing in this scene.
-
-Requirements:
-- Each character needs detailed physical descriptions (hair, eyes, build, clothing details)
-- **IMPORTANT: Physical descriptions must be STATIC and consistent throughout the entire story - do NOT change with plot development**
-  - For example: do NOT write "wearing torn clothes" which changes with the plot
-  - Instead write: "wearing a blue shirt and black pants" which is a fixed clothing description
-- Each scene needs detailed environment, layout, color and atmosphere descriptions
-- Number of scenes based on plot length and pacing
-- Dialogue marked with double quotes, natural and vivid
-- Scene numbers start from {scene_start} and increment
-- Story style: {style}
-
-Output the step outline directly, without act headings or extra notes.
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/script/step_outline_zh.txt b/aigc-director/aigc-claw/backend/prompts/script/step_outline_zh.txt
deleted file mode 100644
index 52af609..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/step_outline_zh.txt
+++ /dev/null
@@ -1,23 +0,0 @@
-你是分场导演。以下是完整的四幕节拍表:
-
-{beat_sheet}
-
-请将第{act_number}幕({act_name})转化为详细的分场大纲。
-
-格式要求(每场一段):
-[场次]. [地点(室内/室外)] - [日/夜]
-[角色]:列出本场出现的所有角色。
-[情节]:详细描述该场戏发生了什么,包含完整的对话、动作和表情描写。
-
-要求:
-- 每个角色都要有详细的外貌描写(发型、眼睛颜色、体型、服装颜色和款式等视觉特征)
-- **重要:外貌描写必须是静态的、贯穿全剧保持一致的特征,不要随剧情发展而变化**
-  - 例如:不要写"他穿着破碎的衣服"这种随情节变化的描写
-  - 应该写:"他身穿蓝色衬衫,黑色长裤"这种固定的服装描述
-- 每个场景都要有详细的环境、布局、色彩与氛围描写
-- 分场数量根据情节长度和节奏自行决定,确保叙事节奏合理
-- 对话用双引号标注,对话内容真实生动
-- 场次编号从 {scene_start} 开始递增
-- 故事风格:{style}
-
-请直接输出分场大纲,不要添加幕次标题或额外说明。
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/prompts/script/validate_characters_zh.txt b/aigc-director/aigc-claw/backend/prompts/script/validate_characters_zh.txt
deleted file mode 100644
index e78e6ac..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/validate_characters_zh.txt
+++ /dev/null
@@ -1,28 +0,0 @@
-你是专业的剧本分析师和AI绘画提示词工程师。请审查以下角色列表,识别需要修改或删除的角色。
-
-角色列表:
-{characters_json}
-
-审查标准:
-1. 群体角色(如"邻居们"、"群众"、"乘客们"、"学生们")应该删除,改为在场景描述中用一句话表示(如"车厢里坐满了乘客")
-2. 角色描述必须包含足够的视觉细节用于AI图像生成:
-   - 外貌:发型、眼睛颜色、面部特征、体型
-   - 服装:颜色、款式、材质配饰:帽子
-   - 、眼镜、珠宝等
-3. 避免抽象比喻(如"看起来很凶"),要具体描述
-
-请输出纯JSON(不要用```包裹),格式如下:
-{{
-  "characters_to_remove": ["需要删除的角色名1", "角色名2", ...],
-  "characters_to_fix": [
-    {{
-      "name": "角色名",
-      "issue": "问题描述",
-      "fix_suggestion": "修改建议"
-    }}
-  ]
-}}
-
-如果没有需要删除的角色,characters_to_remove 返回空数组 []。
-如果没有需要修改的角色,characters_to_fix 返回空数组 []。
-只输出纯JSON,不要添加任何其他文字。
diff --git a/aigc-director/aigc-claw/backend/prompts/script/validate_settings_zh.txt b/aigc-director/aigc-claw/backend/prompts/script/validate_settings_zh.txt
deleted file mode 100644
index 287f0d2..0000000
--- a/aigc-director/aigc-claw/backend/prompts/script/validate_settings_zh.txt
+++ /dev/null
@@ -1,27 +0,0 @@
-你是专业的剧本分析师和AI绘画提示词工程师。请审查以下场景列表,识别需要修改的场景。
-
-场景列表:
-{settings_json}
-
-审查标准:
-1. 场景描述必须包含足够的视觉细节用于AI图像生成:
-   - 空间布局:室内/室外、主要物体位置
-   - 光线:自然光/人工光、光源方向、亮度
-   - 色彩:主色调、氛围
-   - 构图:景别、视角
-2. 场景应该是具体的、可视觉化的地点
-3. 避免过于笼统的描述(如"某个地方")
-
-请输出纯JSON(不要用```包裹),格式如下:
-{{
-  "settings_to_fix": [
-    {{
-      "name": "场景名",
-      "issue": "问题描述",
-      "fix_suggestion": "修改建议"
-    }}
-  ]
-}}
-
-如果没有需要修改的场景,settings_to_fix 返回空数组 []。
-只输出纯JSON,不要添加任何其他文字。
diff --git a/aigc-director/aigc-claw/backend/prompts/setting/eval_select_best_zh.txt b/aigc-director/aigc-claw/backend/prompts/setting/eval_select_best_zh.txt
index 49fa3e9..727a407 100644
--- a/aigc-director/aigc-claw/backend/prompts/setting/eval_select_best_zh.txt
+++ b/aigc-director/aigc-claw/backend/prompts/setting/eval_select_best_zh.txt
@@ -15,7 +15,7 @@
 2. 布局还原(+1/-1):场景布局、物品摆放是否与描述一致
 3. 光线氛围(+1/-1):光线是否与描述一致(日/夜、暖/冷)
 4. 色彩还原(+1/-1):场景色彩是否与描述一致
-5. 风格一致性(+1/-1):整体风格是否符合设定(室内/室外、年代感等)
+5. 风格一致性(+1/-1):整体风格是否符合设定
 6. 细节完整(+1/-1):细节是否丰富,无明显缺失
 7. 空间感(+1/-1):空间透视是否合理
 8. 构图质量(+1/-1):构图是否均衡、美观
diff --git a/aigc-director/aigc-claw/backend/prompts/setting/eval_setting_zh.txt b/aigc-director/aigc-claw/backend/prompts/setting/eval_setting_zh.txt
index f5e9164..2ba6b75 100644
--- a/aigc-director/aigc-claw/backend/prompts/setting/eval_setting_zh.txt
+++ b/aigc-director/aigc-claw/backend/prompts/setting/eval_setting_zh.txt
@@ -12,7 +12,7 @@
 2. 布局还原(+1/-1):场景布局、物品摆放是否与描述一致
 3. 光线氛围(+1/-1):光线是否与描述一致(日/夜、暖/冷)
 4. 色彩还原(+1/-1):场景色彩是否与描述一致
-5. 风格一致性(+1/-1):整体风格是否符合设定(室内/室外、年代感等)
+5. 风格一致性(+1/-1):整体风格是否符合设定
 6. 细节完整(+1/-1):细节是否丰富,无明显缺失
 7. 空间感(+1/-1):空间透视是否合理
 8. 构图质量(+1/-1):构图是否均衡、美观
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 8932e0a..20754b9 100644
--- a/aigc-director/aigc-claw/backend/prompts/storyboard/shot_zh.txt
+++ b/aigc-director/aigc-claw/backend/prompts/storyboard/shot_zh.txt
@@ -1,34 +1,47 @@
-你是一位专业的影视分镜师。你的任务是将以下经过由于编剧润色后的详细剧本场景(Detailed Scene Script),拆分为【3到5个】极具生产力的核心分镜(shot)。
+你是一台专业的 JSON 生成器。请根据输入的集数描述,拆分为一系列极具视觉表现力的“拍摄片段”(Segments),并规划详细的“分镜列表”(Shots)。
 
-要求:
-1. 【数量控制】:每个场景必须且只能拆分为 3 到 5 个分镜。优先保留最具戏剧冲突和视觉张力的瞬间。
-2. 【核心必填:完整台词】:除非是专门的渲染空镜头,否则【每个分镜】的 plot 必须包含剧本中的对话/人物独白。严禁出现只有动作而没有声音叙事的分镜。台词是情节推动的核心,不要浪费镜头素材!
-3. 每个分镜时长为 5、10 或 15 秒(根据内容复杂度选择)。
-4. 每个分镜描述一个独立的画面段落(一个动作/一句对话/一个反应)。
-5. 核心要求:必须包含并保留角色的对话与内心独白。即使是单人镜头,也应通过画外音或自言自言表达内心转折,确保叙事逻辑顺畅。
-6. plot 字段必须严格按时间顺序拆解,包含以下要素:
-   - 完整对话:必须提取剧本中的核心台词,用双引号标注。确保对话应与动作、表情同步描述,体现角色边说边做的真实感。
-   - 动作细节与情感表达:描述该分镜内的身体动作与面部微表情变化过程。
-   - 画面纯净度:禁止在 plot 描述中包含文字信息(如招牌文字、手机屏幕文本等)。
-7. visual_prompt 是用于生成“首帧参考图”的关键。必须满足以下视觉逻辑:
-   - 画面纯净:严禁提及任何具体的文本、字符或文字描述,防止AI生成时出现乱码。
-   - 动作起点:描述分镜开始瞬间的状态,确保后续视频生成动作连贯。
-   - 视觉一致性:相邻分镜要有镜头光影和环境细节的关联,避免拼接突变。
-   - 包含:明确镜头位置(过肩、特写等)、角色站位、姿态、表情、口型、光线色调。
-8. 保持{style}风格,用角色全名。
+### 核心任务
+剧本中每一行描述对应一个分镜。若干分镜组合成一个拍摄片段。
 
-场景编号:{scene_number}
-场景位置:{location}
-出场角色:{characters}
-该场景的剧本:{expanded_plot}
+### 约束要求(严格遵守):
+1. **输出格式**:必须且仅能输出一个纯净的 JSON 数组。严谨包含 ```json 代码块或其他引导性文字。
+2. **片段时长控制**:每个拍摄片段(total_duration)严格限制在 **5~15秒** 之间。
+3. **数学校验**:`total_duration` 必须等于该片段下所有分镜 `duration` 之和。
+4. **景别规范**:仅选:特写、近景、过肩近景、中景、远景。
+5. **内容规范**:
+   - 包含景别、机位、动作、完整台词、详细音色(如:20多岁男性,音质清亮稳健,带自嘲语调)。
+   - 视觉风格:符合 {style}。
 
-角色外貌参考:
-{char_descriptions}
+### 输入上下文
+- **当前集数/名称**:第 {act_number} 集 - {act_title}
+- **角色信息**:{asset_characters}
+- **场景描述**:{asset_settings}
+- **片段风格**:{style}
+- **剧本原文**:
+{script_text}
 
-场景环境参考:
-{setting_description}
+---
 
-请直接输出JSON数组(不要用```包裹),每个元素格式如下:
-[{{"shot_number":1,"duration":5,"characters":["角色名"],"location":"场景位置","plot":"包含台词、动作、表情、音效的描述,80-150字","visual_prompt":"视觉描述,含镜头位、站位、构图、光影,80-150字"}}]
-
-注意:duration只能是5、10、15三个值之一。每个场景分镜数限制在3-5个。
+【输出格式示例(仅返回此 JSON 数组)】
+[
+  {{
+    "segment_number": 1,
+    "total_duration": 12,
+    "location": "具体场景位置",
+    "characters": ["角色名"],
+    "shots": [
+      {{
+        "shot_number": 1,
+        "shot_type": "中景",
+        "duration": 6,
+        "content": "中景,[机位描述]。[动作细节]。[角色名]说:“[台词]”。音色:[详细描述]。"
+      }},
+      {{
+        "shot_number": 2,
+        "shot_type": "近景",
+        "duration": 6,
+        "content": "近景,[机位描述]。[动作细节]。[角色名]说:“[台词]”。音色:[详细描述]。"
+      }}
+    ]
+  }}
+]
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/backend/tool/image_client.py b/aigc-director/aigc-claw/backend/tool/image_client.py
index b2e7d1b..a578f8b 100644
--- a/aigc-director/aigc-claw/backend/tool/image_client.py
+++ b/aigc-director/aigc-claw/backend/tool/image_client.py
@@ -75,7 +75,7 @@
                        save_dir: Optional[str] = None,
                        session_id: Optional[str] = None,
                        video_ratio: Optional[str] = "16:9",
-                       resolution: Optional[str] = "1080P") -> List[str]:
+                       resolution: Optional[str] = "4K") -> List[str]:
         """
         Generate images based on prompt and optional reference images.
 
diff --git a/aigc-director/aigc-claw/backend/tool/llm_deepseek.py b/aigc-director/aigc-claw/backend/tool/llm_deepseek.py
index fb43dae..882b895 100644
--- a/aigc-director/aigc-claw/backend/tool/llm_deepseek.py
+++ b/aigc-director/aigc-claw/backend/tool/llm_deepseek.py
@@ -41,9 +41,6 @@
                     "messages": messages,
                     "stream": False
                 }
-                # Add web search if enabled
-                if web_search:
-                    request_params["enable_web_search"] = True
 
                 response = self.client.chat.completions.create(**request_params)
                 
diff --git a/aigc-director/aigc-claw/frontend/components/HomePage.tsx b/aigc-director/aigc-claw/frontend/components/HomePage.tsx
index ccbeb98..1d8c57e 100644
--- a/aigc-director/aigc-claw/frontend/components/HomePage.tsx
+++ b/aigc-director/aigc-claw/frontend/components/HomePage.tsx
@@ -33,7 +33,7 @@
 interface HomePageProps {
   onStartProject: (params: ProjectParams, autoMode?: boolean) => void;
   onResumeProject: (sessionId: string) => void;
-  onDeleteSession: (sessionId: string, password: string) => Promise<void>;
+  onDeleteSession: (sessionId: string) => Promise<void>;
   history: HistoryItem[];
 }
 
@@ -64,18 +64,16 @@
   // 管理模式状态
   const [manageMode, setManageMode] = useState(false);
   const [deleteTarget, setDeleteTarget] = useState<string | null>(null);
-  const [adminPassword, setAdminPassword] = useState('');
   const [deleteError, setDeleteError] = useState('');
   const [deleting, setDeleting] = useState(false);
 
   const handleDelete = async () => {
-    if (!deleteTarget || !adminPassword) return;
+    if (!deleteTarget) return;
     setDeleting(true);
     setDeleteError('');
     try {
-      await onDeleteSession(deleteTarget, adminPassword);
+      await onDeleteSession(deleteTarget);
       setDeleteTarget(null);
-      setAdminPassword('');
     } catch (e: any) {
       setDeleteError(e.message || '删除失败');
     } finally {
@@ -410,7 +408,7 @@
                     </div>
                     {manageMode ? (
                       <button
-                        onClick={(e) => { e.stopPropagation(); setDeleteTarget(item.id); setDeleteError(''); setAdminPassword(''); }}
+                        onClick={(e) => { e.stopPropagation(); setDeleteTarget(item.id); setDeleteError(''); }}
                         className="w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center hover:bg-red-600 transition-colors flex-shrink-0 mt-0.5"
                         title="删除"
                       >
@@ -440,21 +438,12 @@
               <X className="w-4 h-4" />
             </button>
             <div className="flex items-center gap-2 mb-4">
-              <Lock className="w-4 h-4 text-gray-500" />
+              <Trash2 className="w-4 h-4 text-red-500" />
               <h4 className="text-sm font-semibold text-gray-700">确认删除</h4>
             </div>
-            <p className="text-xs text-gray-500 mb-3">删除后不可恢复,请输入管理员密码确认操作。</p>
-            <input
-              type="password"
-              placeholder="管理员密码"
-              value={adminPassword}
-              onChange={e => { setAdminPassword(e.target.value); setDeleteError(''); }}
-              onKeyDown={e => { if (e.key === 'Enter') handleDelete(); }}
-              className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-300 mb-2"
-              autoFocus
-            />
+            <p className="text-xs text-gray-500 mb-6">删除后不可恢复,确定要删除此项目吗?</p>
             {deleteError && <p className="text-xs text-red-500 mb-2">{deleteError}</p>}
-            <div className="flex gap-2 mt-2">
+            <div className="flex gap-2">
               <button
                 onClick={() => { setDeleteTarget(null); setDeleteError(''); }}
                 className="flex-1 text-sm py-1.5 rounded-lg border border-gray-200 text-gray-600 hover:bg-gray-50"
@@ -463,7 +452,7 @@
               </button>
               <button
                 onClick={handleDelete}
-                disabled={deleting || !adminPassword}
+                disabled={deleting}
                 className="flex-1 text-sm py-1.5 rounded-lg bg-red-500 text-white hover:bg-red-600 disabled:opacity-50"
               >
                 {deleting ? '删除中…' : '确认删除'}
diff --git a/aigc-director/aigc-claw/frontend/components/WorkflowPanel.tsx b/aigc-director/aigc-claw/frontend/components/WorkflowPanel.tsx
index 4b23251..e021c92 100644
--- a/aigc-director/aigc-claw/frontend/components/WorkflowPanel.tsx
+++ b/aigc-director/aigc-claw/frontend/components/WorkflowPanel.tsx
@@ -130,6 +130,15 @@
           pollRef.current = null;
           return;
         }
+        if (status.status === 'stopped') {
+          updateStageState(stageId, {
+            status: 'stopped',
+            error: '手动停止',
+            progressMessage: '已停止',
+          });
+          pollRef.current = null;
+          return;
+        }
         // 如果后端状态不再是 running,提前停止轮询(比如变成了 waiting_intervention 或已完成)
         if (status.status !== 'running') {
           pollRef.current = null;
@@ -977,18 +986,19 @@
         } catch { /* ignore */ }
       }
 
-      // 如果 current_stage 不在 completedStages 中,也需要显示(可能是 stage_completed、running 或 error 状态)
+      // 如果 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' : 'running')),
+          status: isError ? 'error' : (isWaiting ? 'waiting' : (isCompleted ? 'completed' : (isStopped ? 'stopped' : 'running'))),
           progress: 100,
-          progressMessage: isError ? '执行失败' : (isWaiting ? '等待确认' : (isCompleted ? '已完成' : '进行中')),
+          progressMessage: isError ? '执行失败' : (isWaiting ? '等待确认' : (isCompleted ? '已完成' : (isStopped ? '已停止' : '进行中'))),
           artifact: null,
-          error: isError ? (status.error || '执行出错') : null,
+          error: isError ? (status.error || '执行出错') : (isStopped ? '手动停止' : null),
         };
         try {
           const artResult = await getArtifact(sid, currentStage);
@@ -1046,21 +1056,18 @@
   };
 
   // ── 删除历史记录 ──
-  const handleDeleteSession = async (sid: string, password: string) => {
-    await deleteSession(sid, password);
+  const handleDeleteSession = async (sid: string) => {
+    await deleteSession(sid);
     setHistory(prev => prev.filter(h => h.id !== sid));
   };
 
   // ── 模型配置变更处理 ──
   const handleModelConfigChange = (config: ModelConfig) => {
     setProjectParams(prev => prev ? { ...prev, ...config } : null);
-    // 同步到后端会话元数据(需要将 boolean 转为 string)
+    // 同步到后端会话元数据
     if (sessionId) {
-      const stringConfig: Record<string, string> = {};
-      for (const [key, value] of Object.entries(config)) {
-        stringConfig[key] = String(value);
-      }
-      updateModels(sessionId, stringConfig).catch(console.error);
+      const payload: Record<string, any> = { ...config };
+      updateModels(sessionId, payload).catch(console.error);
     }
   };
 
@@ -1074,8 +1081,8 @@
         video_model: projectParams.video_model,
         video_ratio: projectParams.video_ratio,
         enable_concurrency: projectParams.enable_concurrency || false,
-        web_search: projectParams.web_search || false,
-        expand_idea: projectParams.expand_idea || false,
+        // web_search: projectParams.web_search || false,
+        // expand_idea: projectParams.expand_idea || false,
       }
     : undefined;
 
@@ -1102,6 +1109,7 @@
     } else {
       // current_stage 本身:根据 stageStates 判断
       stageStatuses[s] = stageStates[s]?.status || 'pending';
+      if (stageStatuses[s] === 'stopped') stageStatuses[s] = 'stopped';
     }
   }
 
@@ -1117,12 +1125,14 @@
   if (hasRunning) computedStatus = 'running';
   else if (hasWaiting) computedStatus = 'waiting_in_stage';
   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';
   } else if (allCompleted) {
     computedStatus = 'stage_completed';
   } else {
-    computedStatus = 'idle';
+    computedStatus = Object.values(stageStates).some(s => s.status === 'stopped') ? 'stopped' : 'idle';
   }
 
   const projectStatus = sessionId ? computedStatus : undefined;
diff --git a/aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx b/aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx
index 96a5887..23aaf2c 100644
--- a/aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx
+++ b/aigc-director/aigc-claw/frontend/components/stages/ReferenceStage.tsx
@@ -347,8 +347,8 @@
         method: 'PATCH',
         headers: { 'Content-Type': 'application/json' },
         body: JSON.stringify({
-          shots: scenes.map(s => ({
-            shot_id: s.id,
+          segments: scenes.map(s => ({
+            segment_id: s.id,
             visual_prompt: s.id === sceneId ? newPrompt : s.description
           }))
         })
diff --git a/aigc-director/aigc-claw/frontend/components/stages/ScriptStage.tsx b/aigc-director/aigc-claw/frontend/components/stages/ScriptStage.tsx
index 971235a..038a67f 100644
--- a/aigc-director/aigc-claw/frontend/components/stages/ScriptStage.tsx
+++ b/aigc-director/aigc-claw/frontend/components/stages/ScriptStage.tsx
@@ -51,14 +51,20 @@
   scenes: ScriptScene[];
 }
 
+interface ScriptEpisode {
+  act_number: number;
+  act_title: string;
+  content: string;
+}
+
 interface ScriptData {
   title?: string;
   logline?: string;
   genre?: string[];
-  synopsis?: string;
   characters?: ScriptCharacter[];
   settings?: ScriptSetting[];
   scenes?: ScriptScene[];
+  episodes?: ScriptEpisode[];
   overall_style?: string;
   mood?: string;
   session_id?: string;
@@ -392,14 +398,14 @@
             )}
 
             {/* 故事梗概 */}
-            {data.synopsis && (
+            {data.logline && (
               <section>
                 <div className="flex items-center gap-2 mb-3">
                   <BookOpen className="w-4 h-4 text-orange-500" />
                   <h3 className="text-sm font-semibold text-gray-700">故事梗概</h3>
                 </div>
                 <div className="bg-white border border-gray-200 rounded-xl p-5">
-                  <p className="text-sm text-gray-600 leading-relaxed">{data.synopsis}</p>
+                  <p className="text-sm text-gray-600 leading-relaxed">{data.logline}</p>
                 </div>
               </section>
             )}
@@ -456,7 +462,29 @@
             )}
 
             {/* 故事线 */}
-            {data.scenes && data.scenes.length > 0 && (
+            {data.episodes && data.episodes.length > 0 ? (
+          <section className="bg-gray-50 p-4 rounded-xl border border-gray-100">
+            <div className="flex items-center justify-between mb-4">
+              <div className="flex items-center gap-2">
+                <Film className="w-5 h-5 text-purple-500" />
+                <h3 className="text-sm font-bold text-gray-800">分集剧本</h3>
+              </div>
+            </div>
+            <div className="space-y-6">
+              {data.episodes.map((ep, i) => (
+                <div key={i} className="bg-white border border-gray-200 rounded-xl overflow-hidden shadow-sm hover:shadow-md transition-shadow">
+                  <div className="bg-gradient-to-r from-purple-50 to-white px-4 py-3 border-b border-purple-100 flex items-center justify-between">
+                    <h4 className="font-bold text-purple-800">第 {ep.act_number || (i + 1)} 集:{ep.act_title}</h4>
+                    <span className="text-[10px] font-bold text-purple-300 bg-purple-50 px-2 py-0.5 rounded uppercase tracking-wider">Episode {ep.act_number || (i + 1)}</span>
+                  </div>
+                  <div className="p-5 text-gray-700 whitespace-pre-wrap leading-relaxed text-[15px]">
+                    {ep.content}
+                  </div>
+                </div>
+              ))}
+            </div>
+          </section>
+        ) : data.scenes && data.scenes.length > 0 && (
               <section>
                 <div className="flex items-center gap-2 mb-3">
                   <Film className="w-4 h-4 text-purple-500" />
@@ -519,13 +547,8 @@
                 </label>
               </div>
               <label className="flex flex-col gap-1 text-xs">
-                <span className="text-gray-500 font-medium">Logline</span>
-                <input type="text" value={editData.logline || ''} onChange={e => updateField('logline', e.target.value)}
-                  className="border border-gray-200 rounded-lg px-3 py-2 text-sm text-gray-700 focus:ring-2 focus:ring-blue-500/30 outline-none" />
-              </label>
-              <label className="flex flex-col gap-1 text-xs">
-                <span className="text-gray-500 font-medium">故事梗概</span>
-                <textarea value={editData.synopsis || ''} onChange={e => updateField('synopsis', e.target.value)} rows={3}
+                <span className="text-gray-500 font-medium">Logline (故事大纲)</span>
+                <textarea value={editData.logline || ''} onChange={e => updateField('logline', e.target.value)} rows={4}
                   className="border border-gray-200 rounded-lg px-3 py-2 text-sm text-gray-700 focus:ring-2 focus:ring-blue-500/30 outline-none resize-none" />
               </label>
             </section>
diff --git a/aigc-director/aigc-claw/frontend/components/stages/StageActions.tsx b/aigc-director/aigc-claw/frontend/components/stages/StageActions.tsx
index 4f24ace..d7c92d5 100644
--- a/aigc-director/aigc-claw/frontend/components/stages/StageActions.tsx
+++ b/aigc-director/aigc-claw/frontend/components/stages/StageActions.tsx
@@ -47,21 +47,21 @@
   // 是否是"重新生成"阶段(1、3)
   const isRegenStage = STAGES_WITH_NEXT_CHECK.includes(stageId);
 
-  // 重新生成/继续生成按钮:在 waiting / completed / error 状态下显示
-  const showRegen = onRegenerate && (status === 'waiting' || status === 'completed' || status === 'error');
+  // 重新生成/继续生成按钮:在 waiting / completed / error / stopped 状态下显示
+  const showRegen = !!onRegenerate && (status === 'waiting' || status === 'completed' || status === 'error' || status === 'stopped');
+  
+  // 按钮是否禁用逻辑
+  let isButtonDisabled = isRunning;
+  if (!isRunning) {
+    if (isContinueStage && !hasPendingItems && status !== 'error') isButtonDisabled = true;
+    if (isRegenStage && hasNextStageStarted) isButtonDisabled = true;
+  }
 
-  // 判断按钮是否禁用
-  const isButtonDisabled = isRunning || (
-    status !== 'error' && (
-      isContinueStage ? !hasPendingItems : (isRegenStage ? hasNextStageStarted : false)
-    )
-  );
-
-  // 其余按钮在 waiting、running、completed 状态显示
-  const showActions = status === 'waiting' || status === 'running' || status === 'completed';
-  // 保存选项:在 waiting 和 completed 状态下都显示
-  const showSaveSelections = onSaveSelections && (status === 'waiting' || status === 'completed');
-  // "确认并继续"在 showConfirm=true 且 waiting/running/completed 时显示
+  // 其余按钮在 waiting、running、completed、stopped 状态显示
+  const showActions = status === 'waiting' || status === 'running' || status === 'completed' || status === 'stopped';
+  // 保存选项:在 waiting、completed 和 stopped 状态下都显示
+  const showSaveSelections = onSaveSelections && (status === 'waiting' || status === 'completed' || status === 'stopped');
+  // "确认并继续"在 showConfirm=true 且 waiting/running/completed 时显示(stopped 状态不显示确认)
   const showConfirmBtn = showConfirm && (status === 'waiting' || status === 'running' || status === 'completed');
 
   const handleSaveClick = useCallback(async () => {
@@ -79,7 +79,8 @@
   if (!showRegen && !showActions && !showSaveSelections) return null;
 
   return (
-    <div className="border-t border-gray-200 bg-white px-6 py-4 flex items-center justify-between flex-shrink-0">
+    <div className="border-t border-gray-200 bg-white px-6 py-4 flex items-center justify-between gap-3 flex-shrink-0">
+      {/* 左侧:重新生成按钮 */}
       <div>
         {showRegen && (
           <button
@@ -93,6 +94,8 @@
           </button>
         )}
       </div>
+
+      {/* 右侧:操作按钮组 */}
       <div className="flex items-center gap-3">
         {showActions && onEdit && (
           <button
@@ -104,6 +107,7 @@
             修改
           </button>
         )}
+        
         {showActions && onSave && (
           <button
             onClick={onSave}
@@ -111,30 +115,32 @@
             className="flex items-center gap-2 px-4 py-2 bg-white border border-blue-300 text-blue-600 rounded-lg text-sm font-medium hover:bg-blue-50 transition-colors disabled:opacity-50"
           >
             <Save className="w-4 h-4" />
-            保存编辑
+            保存
           </button>
         )}
+
         {showSaveSelections && (
           <button
             onClick={handleSaveClick}
-            disabled={isRunning || saveState !== 'idle'}
-            className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors disabled:opacity-50 ${
-              saveState === 'saved'
-                ? 'bg-green-50 border border-green-300 text-green-600'
-                : 'bg-white border border-indigo-300 text-indigo-600 hover:bg-indigo-50'
-            }`}
+            disabled={saveState !== 'idle' || isRunning}
+            className="flex items-center gap-2 px-4 py-2 bg-white border border-blue-600 text-blue-600 rounded-lg text-sm font-medium hover:bg-blue-50 transition-colors disabled:opacity-50 min-w-[120px] justify-center"
           >
             {saveState === 'saving' ? (
-              <><Loader2 className="w-4 h-4 animate-spin" />正在保存</>           ) : saveState === 'saved' ? (
-              <><Check className="w-4 h-4" />保存成功</>           ) : (
-              <><Save className="w-4 h-4" />保存修改</>           )}
+              <Loader2 className="w-4 h-4 animate-spin" />
+            ) : saveState === 'saved' ? (
+              <Check className="w-4 h-4 text-green-600" />
+            ) : (
+              <Save className="w-4 h-4" />
+            )}
+            {saveState === 'saving' ? '正在保存...' : saveState === 'saved' ? '保存成功' : '保存选择'}
           </button>
         )}
+        
         {showConfirmBtn && (
           <button
             onClick={onConfirm}
             disabled={isRunning}
-            className="flex items-center gap-2 px-5 py-2 bg-green-500 text-white rounded-lg text-sm font-medium hover:bg-green-600 transition-colors disabled:opacity-50"
+            className="flex items-center gap-2 px-6 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:bg-blue-300"
           >
             <CheckCircle className="w-4 h-4" />
             确认并继续
@@ -143,4 +149,4 @@
       </div>
     </div>
   );
-}
+}
\ No newline at end of file
diff --git a/aigc-director/aigc-claw/frontend/components/stages/StoryboardStage.tsx b/aigc-director/aigc-claw/frontend/components/stages/StoryboardStage.tsx
index 1931b5c..16945db 100644
--- a/aigc-director/aigc-claw/frontend/components/stages/StoryboardStage.tsx
+++ b/aigc-director/aigc-claw/frontend/components/stages/StoryboardStage.tsx
@@ -1,682 +1,403 @@
-'use client';
+'use client';
 
-import React, { useState, useMemo, useCallback, useEffect } from 'react';
-import { Save, X, Code, LayoutList, Camera, Clock, MapPin, Users, Plus, Trash2, Sparkles, Check, AlertTriangle } from 'lucide-react';
+import React, { useState, useMemo, useCallback } from 'react';
+import { 
+  Plus, Trash2, Film, Clock, MapPin, Users, Edit3, Save, X, 
+  LayoutList, Camera, ChevronDown, ChevronRight,
+  AlertCircle, Clapperboard
+} from 'lucide-react';
 import type { StageViewProps } from './types';
 import StageActions from './StageActions';
 import StageProgress from './StageProgress';
-import { checkSceneAssets } from '@/lib/workflowApi';
 
-// ─── 类型 ───
+// ─── 类型定义 ───
 
 interface Shot {
-  shot_id: string;
-  scene_number: number;
-  act: number;
   shot_number: number;
-  duration: number; // 5 | 10 | 15
-  location: string;
-  characters: string[];
-  plot: string;
-  visual_prompt: string;
-  is_new?: boolean; // 新添加的分镜标记
+  shot_type: string;
+  duration: number;
+  content: string;
 }
 
-const ACT_NAMES: Record<number, string> = {
-  1: '激励事件', 2: '进入新世界', 3: '灵魂黑夜', 4: '高潮决战',
+interface Segment {
+  segment_id: string;
+  segment_number: number;
+  episode_number: number;
+  location: string;
+  characters: string[];
+  total_duration: number;
+  shots: Shot[];
+}
+
+interface Episode {
+  episode_number: number;
+  episode_title: string;
+  segments: Segment[];
+}
+
+// ─── 样式常量 ───
+
+const SHOT_TYPE_DECOR = {
+  '远景': { bg: 'bg-indigo-50', text: 'text-indigo-600', border: 'border-indigo-100' },
+  '中景': { bg: 'bg-blue-50', text: 'text-blue-600', border: 'border-blue-100' },
+  '近景': { bg: 'bg-cyan-50', text: 'text-cyan-600', border: 'border-cyan-100' },
+  '过肩近景': { bg: 'bg-amber-50', text: 'text-amber-600', border: 'border-amber-100' },
+  '特写': { bg: 'bg-rose-50', text: 'text-rose-600', border: 'border-rose-100' },
 };
 
-const DURATION_COLORS: Record<number, string> = {
-  5:  'bg-green-100 text-green-700',
-  10: 'bg-amber-100 text-amber-700',
-  15: 'bg-red-100 text-red-700',
-};
+// ─── 主组件 ───
 
-// ─── 分镜视图 ───
-
-export default function StoryboardStage({ state, sessionId, onConfirm, onIntervene, onRegenerate, onSaveSelections, showConfirm, isRunning, hasPendingItems, hasNextStageStarted }: StageViewProps) {
-  // 处理嵌套的 shots 结构:可能是数组,也可能是 {payload: {shots: []}, requires_intervention: true}
-  const artifactShots = state.artifact?.shots;
-  let shots: Shot[] = [];
-  if (Array.isArray(artifactShots)) {
-    shots = artifactShots;
-  } else if (artifactShots?.payload?.shots) {
-    shots = artifactShots.payload.shots;
-  }
-  const newShotIds = new Set(state.artifact?.new_shot_ids || state.artifact?.payload?.new_shot_ids || []);
-
-  // 跟踪新添加但未确认的分镜
-  const [pendingNewShots, setPendingNewShots] = useState<string[]>([]);
+export default function StoryboardStage({ 
+  state, 
+  onConfirm, 
+  onIntervene, 
+  onRegenerate, 
+  showConfirm, 
+  isRunning, 
+  hasPendingItems,
+  hasNextStageStarted
+}: StageViewProps) {
+  const artifactData = state.artifact;
+  
+  // 获取剧集数据 (新结构)
+  const episodes: Episode[] = useMemo(() => {
+    if (Array.isArray(artifactData?.episodes)) return artifactData.episodes;
+    if (artifactData?.payload?.episodes) return artifactData.payload.episodes;
+    return [];
+  }, [artifactData]);
 
   const [isEditing, setIsEditing] = useState(false);
   const [editMode, setEditMode] = useState<'structured' | 'raw'>('structured');
-  const [editShots, setEditShots] = useState<Shot[]>([]);
+  const [editEpisodes, setEditEpisodes] = useState<Episode[]>([]);
   const [rawJson, setRawJson] = useState('');
-  const [isContinuing, setIsContinuing] = useState(false);
 
-  // 删除场景时的确认对话框
-  const [deleteConfirm, setDeleteConfirm] = useState<{
-    show: boolean;
-    sceneNumber: number;
-    assetInfo: { reference_images: number; videos: number } | null;
-  }>({ show: false, sceneNumber: 0, assetInfo: null });
-
-  // 检测新添加的分镜 - 使用shots的JSON字符串作为依赖避免无限循环
-  const shotsJson = JSON.stringify(shots || []);
-  useEffect(() => {
-    try {
-      const parsed = JSON.parse(shotsJson);
-      if (Array.isArray(parsed)) {
-        const newIds = parsed.filter((s: Shot) => s.is_new).map((s: Shot) => s.shot_id);
-        setPendingNewShots(newIds);
-      }
-    } catch { /* ignore parse errors */ }
-  }, [shotsJson]);
-
-  // 确认新分镜(清除 is_new 标记)
-  const handleConfirmNewShots = useCallback(async () => {
-    // 保留原始 shots 用于第4阶段(带有 is_new 标记)
-    const originalShots = [...shots];
-
-    // 使用 shots 中已有的 is_new 字段来确认(因为 new_shot_ids 保存后会被清除)
-    const confirmedShots = shots.map(s => {
-      if (s.is_new) {
-        return { ...s, is_new: false };
-      }
-      return s;
-    });
-    // 保存时清除 new_shot_ids 标记,同时传递原始 shots 用于刷新第4阶段
-    await onSaveSelections?.({ shots: confirmedShots, new_shot_ids: [], original_shots: originalShots });
-    setPendingNewShots([]);
-  }, [shots, onSaveSelections]);
-
-  // 取消新分镜(删除)
-  const handleCancelNewShots = useCallback(async () => {
-    // 使用 shots 中已有的 is_new 字段来过滤
-    const filteredShots = shots.filter(s => !s.is_new);
-    await onSaveSelections?.({ shots: filteredShots });
-    setPendingNewShots([]);
-  }, [shots, onSaveSelections]);
-
-  // 生成新的 shot_id
-  const generateShotId = (sceneNum: number, shotNum: number) => {
-    return `shot_${sceneNum.toString().padStart(3, '0')}_${shotNum.toString().padStart(2, '0')}`;
-  };
-
-  // 添加新场景
-  const addScene = useCallback(() => {
-    if (editShots.length === 0) return;
-    const lastShot = editShots[editShots.length - 1];
-    const newSceneNum = (lastShot?.scene_number || 0) + 1;
-    const newAct = lastShot?.act || 1;
-
-    // 添加一个空分镜
-    const newShot: Shot = {
-      shot_id: generateShotId(newSceneNum, 1),
-      scene_number: newSceneNum,
-      act: newAct,
-      shot_number: 1,
-      duration: 10,
-      location: '',
-      characters: [],
-      plot: '',
-      visual_prompt: '',
-    };
-    setEditShots(prev => [...prev, newShot]);
-  }, [editShots]);
-
-  // 删除场景(先检查是否有生成的资产)
-  const deleteScene = useCallback(async (sceneNum: number) => {
-    // 检查该场景是否有生成的参考图或视频
-    try {
-      const assets = await checkSceneAssets(sessionId, sceneNum);
-      if (assets.reference_images > 0 || assets.videos > 0) {
-        // 有资产,显示确认对话框
-        setDeleteConfirm({
-          show: true,
-          sceneNumber: sceneNum,
-          assetInfo: { reference_images: assets.reference_images, videos: assets.videos },
-        });
-        return;
-      }
-    } catch (e) {
-      // API 调用失败,直接删除
-      console.error('Failed to check scene assets:', e);
-    }
-    // 没有资产,直接删除
-    setEditShots(prev => prev.filter(s => s.scene_number !== sceneNum));
-  }, [sessionId]);
-
-  // 确认删除场景
-  const confirmDeleteScene = useCallback(() => {
-    setEditShots(prev => prev.filter(s => s.scene_number !== deleteConfirm.sceneNumber));
-    setDeleteConfirm({ show: false, sceneNumber: 0, assetInfo: null });
-  }, [deleteConfirm.sceneNumber]);
-
-  // 取消删除
-  const cancelDeleteScene = useCallback(() => {
-    setDeleteConfirm({ show: false, sceneNumber: 0, assetInfo: null });
-  }, []);
-
-  // 添加分镜
-  const addShot = useCallback((sceneNum: number) => {
-    setEditShots(prev => {
-      const sceneShots = prev.filter(s => s.scene_number === sceneNum);
-      const lastShot = sceneShots[sceneShots.length - 1];
-      const newShotNum = (lastShot?.shot_number || 0) + 1;
-      const act = lastShot?.act || 1;
-
-      const newShot: Shot = {
-        shot_id: generateShotId(sceneNum, newShotNum),
-        scene_number: sceneNum,
-        act: act,
-        shot_number: newShotNum,
-        duration: 10,
-        location: lastShot?.location || '',
-        characters: lastShot?.characters || [],
-        plot: '',
-        visual_prompt: '',
-      };
-
-      // 插入到该场景的最后
-      const otherShots = prev.filter(s => s.scene_number !== sceneNum);
-      return [...otherShots, ...sceneShots, newShot];
-    });
-  }, []);
-
-  // 删除分镜
-  const deleteShot = useCallback((shotId: string) => {
-    setEditShots(prev => prev.filter(s => s.shot_id !== shotId));
-  }, []);
-
-  // 智能续写
-  const handleContinueStory = useCallback(async () => {
-    setIsContinuing(true);
-    try {
-      await onIntervene({ continue_story: true });
-    } finally {
-      setIsContinuing(false);
-    }
-  }, [onIntervene]);
-
-  // 按幕 → 场景分组
-  const grouped = useMemo(() => {
-    const map = new Map<number, Map<number, Shot[]>>();
-    if (!shots || !Array.isArray(shots)) return map;
-    for (const shot of shots) {
-      const act = shot.act ?? 1;
-      const sceneNum = shot.scene_number ?? 1;
-      if (!map.has(act)) map.set(act, new Map());
-      const actMap = map.get(act)!;
-      if (!actMap.has(sceneNum)) actMap.set(sceneNum, []);
-      actMap.get(sceneNum)!.push(shot);
-    }
-    return map;
-  }, [shots]);
-
-  const hasContent = shots && Array.isArray(shots) && shots.length > 0;
-
-  // 统计
-  const totalDuration = useMemo(() => {
-    if (!shots || !Array.isArray(shots)) return 0;
-    return shots.reduce((s, sh) => s + (sh.duration || 0), 0);
-  }, [shots]);
+  // ─── 编辑逻辑 ───
 
   const startEdit = useCallback(() => {
-    const safeShots = Array.isArray(shots) ? shots : [];
-    setEditShots(JSON.parse(JSON.stringify(safeShots)));
-    setRawJson(JSON.stringify(safeShots, null, 2));
+    setEditEpisodes(JSON.parse(JSON.stringify(episodes)));
+    setRawJson(JSON.stringify(episodes, null, 2));
     setIsEditing(true);
     setEditMode('structured');
-  }, [shots]);
-
-  const switchEditMode = useCallback((mode: 'structured' | 'raw') => {
-    if (mode === 'raw') {
-      setRawJson(JSON.stringify(editShots, null, 2));
-    } else {
-      try { setEditShots(JSON.parse(rawJson)); } catch { /* keep current */ }
-    }
-    setEditMode(mode);
-  }, [editShots, rawJson]);
-
-  const handleSave = useCallback(() => {
-    let finalShots: Shot[];
-    if (editMode === 'raw') {
-      try { finalShots = JSON.parse(rawJson); } catch { finalShots = editShots; }
-    } else {
-      finalShots = editShots;
-    }
-    onIntervene({ modified_storyboard: finalShots });
-    setIsEditing(false);
-  }, [editMode, rawJson, editShots, onIntervene]);
+  }, [episodes]);
 
   const cancelEdit = useCallback(() => setIsEditing(false), []);
 
-  const updateShotField = (idx: number, field: keyof Shot, value: any) => {
-    setEditShots(prev => prev.map((s, i) => i === idx ? { ...s, [field]: value } : s));
+  const handleSave = useCallback(() => {
+    let finalEpisodes: Episode[];
+    if (editMode === 'raw') {
+      try { finalEpisodes = JSON.parse(rawJson); } catch { finalEpisodes = editEpisodes; }
+    } else {
+      finalEpisodes = editEpisodes;
+    }
+    onIntervene({ modified_storyboard: finalEpisodes });
+    setIsEditing(false);
+  }, [editMode, rawJson, editEpisodes, onIntervene]);
+
+  const switchEditMode = (mode: 'structured' | 'raw') => {
+    if (mode === 'raw') {
+      setRawJson(JSON.stringify(editEpisodes, null, 2));
+    } else {
+      try { 
+        const parsed = JSON.parse(rawJson);
+        if (Array.isArray(parsed)) setEditEpisodes(parsed);
+      } catch { /* ignore */ }
+    }
+    setEditMode(mode);
   };
 
-  // 按幕→场景分组(编辑数据)
-  const editGrouped = useMemo(() => {
-    const map = new Map<number, Map<number, { shot: Shot; globalIdx: number }[]>>();
-    editShots.forEach((shot, globalIdx) => {
-      const act = shot.act ?? 1;
-      const sceneNum = shot.scene_number ?? 1;
-      if (!map.has(act)) map.set(act, new Map());
-      const actMap = map.get(act)!;
-      if (!actMap.has(sceneNum)) actMap.set(sceneNum, []);
-      actMap.get(sceneNum)!.push({ shot, globalIdx });
+  const updateSegmentField = (epIdx: number, segIdx: number, field: keyof Segment, value: any) => {
+    setEditEpisodes(prev => prev.map((ep, i) => {
+      if (i !== epIdx) return ep;
+      const newSegments = ep.segments.map((s, j) => j === segIdx ? { ...s, [field]: value } : s);
+      return { ...ep, segments: newSegments };
+    }));
+  };
+
+  const updateShotField = (epIdx: number, segIdx: number, shotIdx: number, field: keyof Shot, value: any) => {
+    setEditEpisodes(prev => prev.map((ep, i) => {
+      if (i !== epIdx) return ep;
+      const newSegments = ep.segments.map((seg, j) => {
+        if (j !== segIdx) return seg;
+        const newShots = seg.shots.map((shot, k) => k === shotIdx ? { ...shot, [field]: value } : shot);
+        const newTotal = newShots.reduce((sum, s) => sum + (Number(s.duration) || 0), 0);
+        return { ...seg, shots: newShots, total_duration: newTotal };
+      });
+      return { ...ep, segments: newSegments };
+    }));
+  };
+
+  const addShot = (epIdx: number, segIdx: number) => {
+    setEditEpisodes(prev => prev.map((ep, i) => {
+      if (i !== epIdx) return ep;
+      const newSegments = ep.segments.map((seg, j) => {
+        if (j !== segIdx) return seg;
+        const newShot: Shot = { shot_number: seg.shots.length + 1, shot_type: '近景', duration: 5, content: '' };
+        return { ...seg, shots: [...seg.shots, newShot], total_duration: seg.total_duration + 5 };
+      });
+      return { ...ep, segments: newSegments };
+    }));
+  };
+
+  const deleteShot = (epIdx: number, segIdx: number, shotIdx: number) => {
+    setEditEpisodes(prev => prev.map((ep, i) => {
+      if (i !== epIdx) return ep;
+      const newSegments = ep.segments.map((seg, j) => {
+        if (j !== segIdx) return seg;
+        const newShots = seg.shots.filter((_, k) => k !== shotIdx);
+        const newTotal = newShots.reduce((sum, s) => sum + (Number(s.duration) || 0), 0);
+        return { ...seg, shots: newShots.map((s, idx) => ({...s, shot_number: idx + 1})), total_duration: newTotal };
+      });
+      return { ...ep, segments: newSegments };
+    }));
+  };
+
+  // ─── 渲染部分 ───
+
+  const episodesToRender = isEditing ? editEpisodes : episodes;
+  const hasEpisodes = episodes.length > 0;
+
+  // 计算统计数据
+  const stats = useMemo(() => {
+    if (!episodesToRender.length) return { episodes: 0, segments: 0, duration: 0 };
+    let totalSegments = 0;
+    let totalDuration = 0;
+    episodesToRender.forEach(ep => {
+      totalSegments += ep.segments.length;
+      ep.segments.forEach(seg => {
+        totalDuration += (seg.total_duration || 0);
+      });
     });
-    return map;
-  }, [editShots]);
+    return {
+      episodes: episodesToRender.length,
+      segments: totalSegments,
+      duration: totalDuration
+    };
+  }, [episodesToRender]);
 
   return (
-    <div className="flex flex-col h-full">
-      <div className="flex-1 overflow-y-auto p-6">
-        {/* 标题 + 编辑模式切换 */}
-        <div className="flex items-center justify-between mb-1">
-          <h2 className="text-lg font-semibold text-gray-800">分镜设计</h2>
-          {isEditing && (
-            <div className="flex gap-1 bg-gray-100 rounded-lg p-1 text-xs">
-              <button
-                onClick={() => switchEditMode('structured')}
-                className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md transition-colors ${editMode === 'structured' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}
-              >
-                <LayoutList className="w-3.5 h-3.5" />
-                结构编辑
-              </button>
-              <button
-                onClick={() => switchEditMode('raw')}
-                className={`flex items-center gap-1.5 px-3 py-1.5 rounded-md transition-colors ${editMode === 'raw' ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500 hover:text-gray-700'}`}
-              >
-                <Code className="w-3.5 h-3.5" />
-                JSON编辑
-              </button>
-            </div>
-          )}
-        </div>
-        <p className="text-sm text-gray-500 mb-6">
-          按场景拆分分镜,每个分镜带时长标签
-          {hasContent && (
-            <span className="ml-2 text-gray-400">
-              共 {shots.length} 个分镜 · 总时长 {totalDuration}s
-            </span>
-          )}
-        </p>
+    <div className="flex flex-col h-full bg-white">
+      <div className="flex-1 overflow-y-auto p-6 custom-scrollbar">
+        {/* 标题栏 */}
+        <div className="flex items-start justify-between mb-6">
+          <div className="flex flex-col">
+            <h2 className="text-lg font-semibold text-gray-800">分镜设计</h2>
+            <p className="text-sm text-gray-500">
+              生成分段分镜脚本 (景别·时长·叙事内容) 以及指导性的视觉流转设计
+            </p>
+          </div>
 
-        {/* 运行中 */}
-        {state.status === 'running' && (
-          <>
-            <StageProgress message={state.progressMessage} fallback="正在拆分分镜..." progress={state.progress} color="amber" />
-            {/* 增量显示已完成的分镜 */}
-            {hasContent && (
-              <div className="mt-4 space-y-4">
-                {renderShotGroups(grouped)}
+          <div className="flex items-center gap-3">
+            {hasEpisodes && !isEditing && (
+              <div className="flex items-center h-12 gap-5 px-5 py-2 bg-violet-50 rounded-xl border border-violet-100 shadow-sm">
+                <div className="flex items-center gap-2">
+                  <Film className="w-3.5 h-3.5 text-violet-500" />
+                  <span className="text-sm text-violet-700 font-bold whitespace-nowrap">总计 {stats.episodes} 集</span>
+                </div>
+                <div className="w-px h-6 bg-violet-200" />
+                <div className="flex items-center gap-2">
+                  <Clapperboard className="w-3.5 h-3.5 text-violet-500" />
+                  <span className="text-sm text-violet-700 font-bold whitespace-nowrap">{stats.segments} 段分镜</span>
+                </div>
+                <div className="w-px h-6 bg-violet-200" />
+                <div className="flex items-center gap-2 px-1">
+                  <Clock className="w-3.5 h-3.5 text-violet-500" />
+                  <span className="text-sm text-violet-700 font-black whitespace-nowrap">预计时长 {stats.duration}s</span>
+                </div>
               </div>
             )}
-          </>
-        )}
-
-        {state.error && (
-          <div className="text-sm text-red-600 bg-red-50 border border-red-200 p-4 rounded-xl mb-4">{state.error}</div>
-        )}
-
-        {/* ===== 查看模式 ===== */}
-        {hasContent && !isEditing && state.status !== 'running' && (
-          <div className="space-y-4">
-            {renderShotGroups(grouped)}
+            
+            {isEditing && (
+              <div className="flex items-center gap-2">
+                <div className="bg-gray-100 p-1 rounded-lg flex items-center mr-2">
+                  <button onClick={() => switchEditMode('structured')} className={`px-2 py-1 text-[10px] font-medium rounded-md transition-all ${editMode === 'structured' ? 'bg-white text-violet-600 shadow-sm' : 'text-gray-500'}`}>可视化</button>
+                  <button onClick={() => switchEditMode('raw')} className={`px-2 py-1 text-[10px] font-medium rounded-md transition-all ${editMode === 'raw' ? 'bg-white text-violet-600 shadow-sm' : 'text-gray-500'}`}>JSON</button>
+                </div>
+                <button onClick={cancelEdit} className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium text-gray-500 hover:bg-gray-100">
+                  <X className="w-3.5 h-3.5" />取消
+                </button>
+                <button onClick={handleSave} className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-violet-500 hover:bg-violet-600">
+                  <Save className="w-3.5 h-3.5" />保存
+                </button>
+              </div>
+            )}
           </div>
+        </div>
+
+        {/* 进度提示 */}
+        {isRunning && state.progress < 100 && (
+          <StageProgress message={state.progressMessage} progress={state.progress} color="violet" />
         )}
 
-        {/* ===== 结构编辑模式 ===== */}
-        {isEditing && editMode === 'structured' && (
-          <div className="space-y-4">
-            {Array.from(editGrouped.entries()).sort(([a], [b]) => a - b).map(([act, sceneMap]) => (
-              <React.Fragment key={act}>
-                {/* 幕分隔线:仅多幕时显示 */}
-                {editGrouped.size > 1 && (
-                  <div className="flex items-center gap-3 pt-2">
-                    <div className="flex-1 h-px bg-gradient-to-r from-amber-200 to-transparent" />
-                    <span className="px-3 py-1 bg-amber-50 text-amber-600 text-xs font-semibold rounded-full whitespace-nowrap">
-                      第{act}幕 — {ACT_NAMES[act] || ''}
-                    </span>
-                    <div className="flex-1 h-px bg-gradient-to-l from-amber-200 to-transparent" />
-                  </div>
-                )}
-
-                {Array.from(sceneMap.entries()).sort(([a], [b]) => a - b).map(([sceneNum, items]) => (
-                  <div key={sceneNum} className="bg-white border border-gray-200 rounded-xl overflow-hidden">
-                    <div className="bg-gray-50 px-4 py-2 border-b border-gray-100 flex items-center gap-2">
-                      <Camera className="w-3.5 h-3.5 text-amber-500" />
-                      <span className="text-sm font-medium text-gray-700">场景 {sceneNum}</span>
-                      <span className="text-xs text-gray-400">{items.length} 个分镜</span>
-                      <div className="ml-auto flex items-center gap-1">
-                        <button
-                          onClick={() => addShot(sceneNum)}
-                          className="p-1 text-blue-500 hover:bg-blue-50 rounded"
-                          title="添加分镜"
-                        >
-                          <Plus className="w-4 h-4" />
-                        </button>
-                        <button
-                          onClick={() => deleteScene(sceneNum)}
-                          className="p-1 text-red-500 hover:bg-red-50 rounded"
-                          title="删除场景"
-                        >
-                          <Trash2 className="w-4 h-4" />
-                        </button>
-                      </div>
-                    </div>
-                    <div className="divide-y divide-gray-100">
-                      {items.map(({ shot, globalIdx }) => (
-                        <div key={shot.shot_id} className="p-4 space-y-2">
-                          <div className="flex items-center gap-2">
-                            <span className="flex items-center justify-center w-6 h-6 rounded-full bg-amber-100 text-amber-700 text-xs font-bold flex-shrink-0">
-                              {shot.shot_number}
-                            </span>
-                            <select
-                              value={shot.duration}
-                              onChange={e => updateShotField(globalIdx, 'duration', Number(e.target.value))}
-                              className="text-xs border border-gray-200 rounded px-2 py-1 text-gray-700"
-                            >
-                              <option value={5}>5s</option>
-                              <option value={10}>10s</option>
-                              <option value={15}>15s</option>
-                            </select>
-                            <div className="flex flex-wrap gap-1 ml-2">
-                              {shot.characters.map((c, ci) => (
-                                <span key={ci} className="px-2 py-0.5 bg-blue-50 text-blue-600 text-xs rounded-full">{c}</span>
-                              ))}
-                              <span className="px-2 py-0.5 bg-green-50 text-green-600 text-xs rounded-full">{shot.location}</span>
-                            </div>
-                          </div>
-                          <div>
-                            <label className="block text-xs text-gray-500 mb-1">剧情</label>
-                            <textarea
-                              value={shot.plot}
-                              onChange={e => updateShotField(globalIdx, 'plot', e.target.value)}
-                              rows={2}
-                              className="w-full border border-gray-200 rounded-lg px-3 py-2 text-sm text-gray-700 focus:ring-2 focus:ring-blue-500/30 outline-none resize-none"
-                            />
-                          </div>
-                          <div>
-                            <label className="block text-xs text-gray-500 mb-1">视觉提示词</label>
-                            <div className="flex gap-2">
-                              <textarea
-                                value={shot.visual_prompt}
-                                onChange={e => updateShotField(globalIdx, 'visual_prompt', e.target.value)}
-                                rows={2}
-                                className="flex-1 border border-gray-200 rounded-lg px-3 py-2 text-sm text-gray-700 focus:ring-2 focus:ring-blue-500/30 outline-none resize-none"
-                              />
-                              <button
-                                onClick={() => deleteShot(shot.shot_id)}
-                                className="p-2 text-red-400 hover:bg-red-50 rounded self-start"
-                                title="删除分镜"
-                              >
-                                <Trash2 className="w-4 h-4" />
-                              </button>
-                            </div>
-                          </div>
-                        </div>
-                      ))}
-                    </div>
-                    {/* 场景底部添加分镜按钮 */}
-                    <div className="px-4 py-2 bg-gray-50 border-t border-gray-100">
-                      <button
-                        onClick={() => addShot(sceneNum)}
-                        className="flex items-center gap-1 text-xs text-blue-500 hover:text-blue-600"
-                      >
-                        <Plus className="w-3.5 h-3.5" />
-                        添加分镜
-                      </button>
-                    </div>
-                  </div>
-                ))}
-              </React.Fragment>
-            ))}
-
-            {/* 添加场景按钮 */}
-            <button
-              onClick={addScene}
-              className="w-full flex items-center justify-center gap-2 py-3 border-2 border-dashed border-gray-300 rounded-xl text-gray-500 hover:border-blue-400 hover:text-blue-500 transition-colors"
-            >
-              <Plus className="w-5 h-5" />
-              添加场景
-            </button>
-
-            <div className="flex gap-2 pt-2">
-              <button onClick={handleSave} className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg text-sm font-medium hover:bg-blue-600 transition-colors">
-                <Save className="w-4 h-4" />
-                保存修改
-              </button>
-              <button onClick={cancelEdit} className="flex items-center gap-2 px-4 py-2 bg-gray-100 text-gray-600 rounded-lg text-sm hover:bg-gray-200 transition-colors">
-                <X className="w-4 h-4" />
-                取消
-              </button>
-            </div>
+        {/* 主体内容 */}
+        {!hasEpisodes && !isRunning && !isEditing ? (
+          <div className="flex flex-col items-center justify-center py-20 text-gray-400">
+            <Film className="w-12 h-12 text-gray-200 mb-4" />
+            <p className="text-xs">等待生成分镜剧本...</p>
           </div>
-        )}
-
-        {/* ===== JSON编辑模式 ===== */}
-        {isEditing && editMode === 'raw' && (
-          <div className="space-y-3">
+        ) : isEditing && editMode === 'raw' ? (
+          <div className="h-[500px] bg-gray-950 rounded-xl overflow-hidden border border-gray-800">
             <textarea
+              className="w-full h-full bg-transparent text-gray-300 p-6 font-mono text-sm resize-none focus:outline-none"
               value={rawJson}
-              onChange={e => setRawJson(e.target.value)}
-              className="w-full bg-white border border-gray-200 rounded-xl p-4 text-sm text-gray-700 font-mono leading-relaxed resize-none outline-none min-h-[400px] focus:ring-2 focus:ring-blue-500/30"
+              onChange={(e) => setRawJson(e.target.value)}
+              spellCheck={false}
             />
-            <div className="flex gap-2">
-              <button onClick={handleSave} className="flex items-center gap-2 px-4 py-2 bg-blue-500 text-white rounded-lg text-sm font-medium hover:bg-blue-600 transition-colors">
-                <Save className="w-4 h-4" />
-                保存修改
-              </button>
-              <button onClick={cancelEdit} className="flex items-center gap-2 px-4 py-2 bg-gray-100 text-gray-600 rounded-lg text-sm hover:bg-gray-200 transition-colors">
-                <X className="w-4 h-4" />
-                取消
-              </button>
-            </div>
           </div>
-        )}
+        ) : (
+          <div className="space-y-12">
+            {episodesToRender.map((episode, epIdx) => {
+              const epTotalTime = episode.segments.reduce((sum, s) => sum + (s.total_duration || 0), 0);
+              return (
+                <div key={epIdx} className="space-y-4">
+                  {/* 一级:剧集抬头 (参考第一阶段) */}
+                  <div className="flex items-center justify-between border-b pb-2 border-gray-100">
+                    <div className="flex items-center gap-3">
+                      <span className="text-xs font-black text-white bg-violet-500 px-2 py-0.5 rounded leading-tight shadow-sm">第 {String(episode.episode_number)} 集</span>
+                      <h3 className="text-base font-bold text-gray-800">{episode.episode_title}</h3>
+                    </div>
+                    <span className="text-[11px] font-bold text-violet-600 bg-violet-50 px-2 py-0.5 rounded-full flex items-center gap-1">
+                      <Clock className="w-3 h-3" /> 总计 {epTotalTime}s
+                    </span>
+                  </div>
 
-        {state.status === 'pending' && (
-          <div className="text-center text-gray-400 text-sm py-20">等待上一阶段完成...</div>
-        )}
+                  {/* 二级:拍摄分段 */}
+                  <div className="space-y-8 pl-1">
+                    {episode.segments.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">
+                            <span className="text-xs font-black text-gray-400">#{segment.segment_number}</span>
+                            <div className="flex items-center gap-1.5">
+                              <MapPin className="w-3.5 h-3.5 text-gray-400" />
+                              <span className="text-sm font-bold text-gray-800">
+                                {isEditing ? (
+                                  <input 
+                                    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}
+                              </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) => (
+                                  <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>
+                            </div>
+                          </div>
+                          <span className="text-xs font-black text-violet-600 bg-violet-50 px-2.5 py-1 rounded-full">{segment.total_duration}s</span>
+                        </div>
 
-        {/* 智能续写按钮 - 仅在分镜完成后显示(pending/running 时不显示) */}
-        {hasContent && !isEditing && !['pending', 'running'].includes(state.status) && (
-          <div className="mt-6 pt-6 border-t border-gray-200">
-            <button
-              onClick={handleContinueStory}
-              disabled={isContinuing}
-              className="w-full flex items-center justify-center gap-2 px-4 py-3 bg-gradient-to-r from-purple-500 to-indigo-500 text-white rounded-xl text-sm font-medium hover:from-purple-600 hover:to-indigo-600 transition-colors disabled:opacity-50"
-            >
-              {isContinuing ? (
-                <>
-                  <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
-                  智能续写中...
-                </>
-              ) : (
-                <>
-                  <Sparkles className="w-4 h-4" />
-                  智能续写
-                </>
-              )}
-            </button>
-            <p className="text-xs text-gray-400 text-center mt-2">根据已有剧情,自动续写新的分镜</p>
-          </div>
-        )}
-
-        {/* 新分镜确认/取消按钮 */}
-        {pendingNewShots.length > 0 && !isEditing && (
-          <div className="mt-4 p-4 bg-purple-50 border border-purple-200 rounded-xl">
-            <div className="flex items-center gap-2 mb-3">
-              <Sparkles className="w-4 h-4 text-purple-500" />
-              <span className="text-sm font-medium text-purple-700">检测到 {pendingNewShots.length} 个新分镜</span>
-            </div>
-            <div className="flex gap-3">
-              <button
-                onClick={handleConfirmNewShots}
-                disabled={isContinuing}
-                className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-purple-500 text-white rounded-lg text-sm font-medium hover:bg-purple-600 transition-colors disabled:opacity-50"
-              >
-                <Check className="w-4 h-4" />
-                保存
-              </button>
-              <button
-                onClick={handleCancelNewShots}
-                disabled={isContinuing}
-                className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-white border border-gray-300 text-gray-700 rounded-lg text-sm font-medium hover:bg-gray-50 transition-colors disabled:opacity-50"
-              >
-                <X className="w-4 h-4" />
-                取消
-              </button>
-            </div>
+                        {/* 三级:分镜表格 */}
+                        <div className="ml-8 border border-gray-100 rounded-xl overflow-hidden shadow-sm bg-white">
+                          <table className="w-full text-left">
+                            <thead className="bg-gray-50/50 border-b border-gray-100">
+                              <tr className="text-[12px] font-bold text-gray-500 uppercase tracking-wider">
+                                <th className="px-4 py-2 w-10 text-center">#</th>
+                                <th className="px-4 py-2 w-24 text-center">景别</th>
+                                <th className="px-4 py-2 w-20 text-center">时长</th>
+                                <th className="px-4 py-2">分镜内容描述</th>
+                                {isEditing && <th className="px-4 py-2 w-10"></th>}
+                              </tr>
+                            </thead>
+                            <tbody className="divide-y divide-gray-50">
+                              {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">
+                                    <td className="px-4 py-3 text-center text-xs font-mono text-gray-400">{shot.shot_number}</td>
+                                    <td className="px-4 py-3 text-center">
+                                      {isEditing ? (
+                                        <select 
+                                          value={shot.shot_type} 
+                                          onChange={e => updateShotField(epIdx, segIdx, sIdx, 'shot_type', e.target.value)} 
+                                          className="w-full bg-white border border-gray-200 rounded text-xs font-bold py-1 px-1 outline-none focus:ring-1 focus:ring-violet-300"
+                                        >
+                                          {Object.keys(SHOT_TYPE_DECOR).map(t => <option key={t} value={t}>{t}</option>)}
+                                        </select>
+                                      ) : (
+                                        <span className={`px-2 py-0.5 rounded text-xs font-black ${decor.bg} ${decor.text}`}>{shot.shot_type}</span>
+                                      )}
+                                    </td>
+                                    <td className="px-4 py-3 text-center">
+                                      {isEditing ? (
+                                        <input 
+                                          type="number" 
+                                          value={shot.duration} 
+                                          onChange={e => updateShotField(epIdx, segIdx, sIdx, 'duration', Number(e.target.value))} 
+                                          className="w-12 bg-white border border-gray-200 rounded text-xs font-mono py-1 px-1 text-center focus:ring-1 focus:ring-violet-300 outline-none" 
+                                        />
+                                      ) : (
+                                        <span className="text-xs font-mono text-gray-500">{shot.duration}s</span>
+                                      )}
+                                    </td>
+                                    <td className="px-4 py-3">
+                                      {isEditing ? (
+                                        <textarea 
+                                          value={shot.content} 
+                                          onChange={e => updateShotField(epIdx, segIdx, sIdx, 'content', e.target.value)} 
+                                          rows={1} 
+                                          className="w-full bg-gray-50 border border-transparent rounded px-2 py-1 text-sm text-gray-700 focus:bg-white focus:border-violet-100 outline-none resize-none" 
+                                        />
+                                      ) : (
+                                        <p className="text-sm text-gray-700 leading-relaxed font-semibold">{shot.content}</p>
+                                      )}
+                                    </td>
+                                    {isEditing && (
+                                      <td className="px-2 py-3">
+                                        <button onClick={() => deleteShot(epIdx, segIdx, sIdx)} className="p-1 text-gray-300 hover:text-red-500 transition-colors opacity-0 group-hover:opacity-100">
+                                          <Trash2 className="w-3.5 h-3.5" />
+                                        </button>
+                                      </td>
+                                    )}
+                                  </tr>
+                                );
+                              })}
+                              {isEditing && (
+                                <tr>
+                                  <td colSpan={5} className="p-2">
+                                    <button onClick={() => addShot(epIdx, segIdx)} className="w-full py-1.5 border border-dashed border-gray-100 rounded-lg text-gray-400 text-[10px] font-bold hover:bg-violet-50 hover:text-violet-500 transition-all flex items-center justify-center gap-1">
+                                      <Plus className="w-3 h-3" /> 插入新分镜点
+                                    </button>
+                                  </td>
+                                </tr>
+                              )}
+                            </tbody>
+                          </table>
+                        </div>
+                      </div>
+                    ))}
+                  </div>
+                </div>
+              );
+            })}
           </div>
         )}
       </div>
 
-      {/* 删除场景确认对话框 */}
-      {deleteConfirm.show && (
-        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
-          <div className="bg-white rounded-xl p-6 max-w-sm w-full mx-4 shadow-xl">
-            <div className="flex items-center gap-3 mb-4">
-              <div className="w-10 h-10 rounded-full bg-red-100 flex items-center justify-center">
-                <AlertTriangle className="w-5 h-5 text-red-500" />
-              </div>
-              <h3 className="text-lg font-semibold text-gray-800">确认删除场景</h3>
-            </div>
-            <p className="text-gray-600 mb-4">
-              场景 {deleteConfirm.sceneNumber} 中包含已生成的资产:
-            </p>
-            <div className="bg-gray-50 rounded-lg p-3 mb-4 space-y-1 text-sm">
-              <div className="flex justify-between">
-                <span className="text-gray-500">参考图:</span>
-                <span className="font-medium text-gray-800">{deleteConfirm.assetInfo?.reference_images || 0} 张</span>
-              </div>
-              <div className="flex justify-between">
-                <span className="text-gray-500">视频片段:</span>
-                <span className="font-medium text-gray-800">{deleteConfirm.assetInfo?.videos || 0} 个</span>
-              </div>
-            </div>
-            <p className="text-amber-600 text-sm mb-4">
-              删除后这些资产将无法恢复!
-            </p>
-            <div className="flex gap-3">
-              <button
-                onClick={cancelDeleteScene}
-                className="flex-1 px-4 py-2 border border-gray-200 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
-              >
-                取消
-              </button>
-              <button
-                onClick={confirmDeleteScene}
-                className="flex-1 px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
-              >
-                确认删除
-              </button>
-            </div>
-          </div>
-        </div>
-      )}
+      {/* 底部确认操作 (参考第二阶段 StageActions 放在底部) */}
+      <StageActions 
+        status={state.status}
+        onConfirm={onConfirm} 
+        onEdit={!isEditing ? startEdit : undefined}
+        onSave={isEditing ? handleSave : undefined}
+        onRegenerate={onRegenerate} 
+        showConfirm={showConfirm} 
+        isRunning={isRunning} 
+        hasPendingItems={hasPendingItems} 
+        hasNextStageStarted={hasNextStageStarted}
+        stageId="storyboard"
+      />
 
-      {!isEditing && (
-        <StageActions
-          status={state.status}
-          onConfirm={onConfirm}
-          showConfirm={showConfirm}
-          onEdit={startEdit}
-          onRegenerate={onRegenerate}
-          stageId="storyboard"
-          hasPendingItems={hasPendingItems}
-          hasNextStageStarted={hasNextStageStarted}
-          isRunning={isRunning}
-        />
-      )}
-      {isEditing && (
-        <StageActions
-          status={state.status}
-          onConfirm={onConfirm}
-          showConfirm={showConfirm}
-          onSave={handleSave}
-          onRegenerate={onRegenerate}
-          stageId="storyboard"
-          hasPendingItems={hasPendingItems}
-          hasNextStageStarted={hasNextStageStarted}
-          isRunning={isRunning}
-        />
-      )}
+      <style jsx global>{`
+        .custom-scrollbar::-webkit-scrollbar { width: 5px; }
+        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
+        .custom-scrollbar::-webkit-scrollbar-thumb { background: #F1F1F1; border-radius: 10px; }
+        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: #E5E7EB; }
+      `}</style>
     </div>
   );
-}
-
-// ─── 分镜分组渲染 ───
-
-function renderShotGroups(grouped: Map<number, Map<number, Shot[]>>) {
-  const multiAct = grouped.size > 1;
-  return Array.from(grouped.entries()).sort(([a], [b]) => a - b).map(([act, sceneMap]) => (
-    <React.Fragment key={act}>
-      {/* 幕分隔线:仅多幕时显示 */}
-      {multiAct && (
-        <div className="flex items-center gap-3 pt-2">
-          <div className="flex-1 h-px bg-gradient-to-r from-amber-200 to-transparent" />
-          <span className="px-3 py-1 bg-amber-50 text-amber-600 text-xs font-semibold rounded-full whitespace-nowrap">
-            第{act}幕 — {ACT_NAMES[act] || ''}
-          </span>
-          <div className="flex-1 h-px bg-gradient-to-l from-amber-200 to-transparent" />
-        </div>
-      )}
-
-      {Array.from(sceneMap.entries()).sort(([a], [b]) => a - b).map(([sceneNum, sceneShots]) => (
-        <React.Fragment key={sceneNum}>
-        <div className="bg-white border border-gray-200 rounded-xl overflow-hidden">
-          {/* 场景标题栏 */}
-          <div className="bg-gray-50 px-4 py-2 border-b border-gray-100 flex items-center gap-2">
-            <Camera className="w-3.5 h-3.5 text-amber-500" />
-            <span className="text-sm font-medium text-gray-700">场景 {sceneNum}</span>
-            <span className="text-xs text-gray-400">
-              {sceneShots.length} 个分镜 · {sceneShots.reduce((s, sh) => s + sh.duration, 0)}s
-            </span>
-            {sceneShots[0]?.location && (
-              <span className="ml-auto px-2 py-0.5 bg-green-50 text-green-600 text-xs rounded-full flex items-center gap-1">
-                <MapPin className="w-3 h-3" />
-                {sceneShots[0].location}
-              </span>
-            )}
-          </div>
-          {/* 分镜列表 */}
-          <div className="divide-y divide-gray-100">
-            {sceneShots.map(shot => (
-              <div key={shot.shot_id} className={`px-4 py-3 hover:bg-gray-50/50 transition-colors ${shot.is_new ? 'bg-purple-50 border-l-4 border-l-purple-400' : ''}`}>
-                <div className="flex items-start gap-3">
-                  {/* 编号 */}
-                  <span className="flex items-center justify-center w-6 h-6 rounded-full bg-amber-100 text-amber-700 text-xs font-bold flex-shrink-0 mt-0.5">
-                    {shot.shot_number}
-                  </span>
-                  <div className="flex-1 min-w-0">
-                    {/* 标签行 */}
-                    <div className="flex items-center gap-2 mb-1.5">
-                      <span className={`inline-flex items-center gap-1 px-2 py-0.5 text-xs font-medium rounded-full ${DURATION_COLORS[shot.duration] || 'bg-gray-100 text-gray-600'}`}>
-                        <Clock className="w-3 h-3" />
-                        {shot.duration}s
-                      </span>
-                      {(shot.characters || []).map((c, ci) => (
-                        <span key={ci} className="px-2 py-0.5 bg-blue-50 text-blue-600 text-xs rounded-full">{c}</span>
-                      ))}
-                    </div>
-                    {/* 剧情 */}
-                    <p className="text-sm text-gray-700 leading-relaxed">{shot.plot}</p>
-                    {/* 视觉提示词 */}
-                    {shot.visual_prompt && (
-                      <p className="text-xs text-gray-400 leading-relaxed mt-1 italic">{shot.visual_prompt}</p>
-                    )}
-                  </div>
-                </div>
-              </div>
-            ))}
-          </div>
-        </div>
-        </React.Fragment>
-      ))}
-    </React.Fragment>
-  ));
 }
diff --git a/aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx b/aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx
index 3fc85f2..3f82391 100644
--- a/aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx
+++ b/aigc-director/aigc-claw/frontend/components/stages/VideoStage.tsx
@@ -81,20 +81,20 @@
                   : 'ring-1 ring-gray-200 hover:ring-gray-300 hover:shadow-md'
               }`}
             >
-              <div className="relative bg-black">
+              <div className="relative bg-black flex items-center justify-center h-32 aspect-video overflow-hidden">
                 <video
                   src={assetUrl(path)}
                   controls={isSelected}
                   preload="metadata"
-                  className="h-32 aspect-video object-cover"
+                  className="h-full w-full object-contain"
                 />
                 {!isSelected && (
-                  <div className="absolute inset-0 flex items-center justify-center bg-black/10">
-                    <Play className="w-6 h-6 text-white/70" />
+                  <div className="absolute inset-0 flex items-center justify-center bg-black/20 group-hover:bg-black/10 transition-colors">
+                    <Play className="w-8 h-8 text-white filter drop-shadow-lg" />
                   </div>
                 )}
               </div>
-              <div className={`text-center text-[10px] py-0.5 ${
+              <div className={`text-center text-[10px] py-1 ${
                 isSelected ? 'bg-rose-500 text-white font-medium' : 'bg-gray-50 text-gray-400'
               }`}>
                 v{i + 1}
@@ -103,7 +103,7 @@
           );
         })}
         {showPlaceholder && (
-          <div className="flex-shrink-0 flex items-center justify-center h-32 aspect-video bg-gray-50 rounded-lg border border-dashed border-gray-200">
+          <div className="flex-shrink-0 flex items-center justify-center h-32 aspect-video bg-gray-50 rounded-lg border border-dashed border-gray-200 px-4">
             <div className="flex items-center gap-2 text-gray-400 text-xs">
               <Loader className="w-4 h-4 animate-spin" />
               <span>生成中...</span>
@@ -232,7 +232,7 @@
       <div className="flex-1 min-w-0 p-3 flex items-center">
         {isPending && !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">
+            <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>
@@ -242,7 +242,7 @@
             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"
             onClick={onRegenerate}
           >
-            <div className="flex flex-col items-center gap-1 text-red-400 text-xs">
+            <div className="flex flex-col items-center gap-1 text-red-400 text-xs px-4">
               <AlertCircle className="w-4 h-4" />
               <span>生成失败,点击重试</span>
             </div>
diff --git a/aigc-director/aigc-claw/frontend/components/stages/types.ts b/aigc-director/aigc-claw/frontend/components/stages/types.ts
index 98d26b9..d431b65 100644
--- a/aigc-director/aigc-claw/frontend/components/stages/types.ts
+++ b/aigc-director/aigc-claw/frontend/components/stages/types.ts
@@ -1,4 +1,4 @@
-export type StageStatus = 'pending' | 'running' | 'waiting' | 'completed' | 'error';
+export type StageStatus = 'pending' | 'running' | 'waiting' | 'completed' | 'error' | 'stopped';
 
 export interface StageState {
   status: StageStatus;
diff --git a/aigc-director/aigc-claw/frontend/lib/workflowApi.ts b/aigc-director/aigc-claw/frontend/lib/workflowApi.ts
index 01937e2..ab5bba4 100644
--- a/aigc-director/aigc-claw/frontend/lib/workflowApi.ts
+++ b/aigc-director/aigc-claw/frontend/lib/workflowApi.ts
@@ -151,12 +151,10 @@
 
 export async function deleteSession(
   sessionId: string,
-  password: string,
 ): Promise<{ status: string }> {
   const resp = await fetch(`/api/sessions/${sessionId}`, {
     method: 'DELETE',
     headers: { 'Content-Type': 'application/json' },
-    body: JSON.stringify({ password }),
   });
   if (!resp.ok) {
     const err = await resp.json().catch(() => ({ detail: '删除失败' }));

--
Gitblit v1.8.0