From 0bc7753fba9b44d4caa5d12bc4075fd402aa689a Mon Sep 17 00:00:00 2001
From: hit-cxf <2024111082@stu.hit.edu.cn>
Date: Sun, 31 May 2026 22:40:38 +0800
Subject: [PATCH] Improve the orchestrator, set up a unified disk storage entry, and maintain global consistency in session state

---
 video-claw/video-claw/backend/api/services/project_helpers.py        |    9 
 video-claw/video-claw/backend/core/agents/storyboard_agent.py        |   91 +-
 video-claw/video-claw/backend/core/agents/video_agent.py             |   65 -
 video-claw/video-claw/backend/models/llm_deepseek.py                 |  107 ++
 video-claw/video-claw/frontend/lib/workflowApi.ts                    |    4 
 video-claw/video-claw/backend/core/agents/editor_agent.py            |   32 
 video-claw/video-claw/backend/core/agents/reference_agent.py         |   23 
 video-claw/video-claw/backend/api/schemas/pipelines.py               |    4 
 video-claw/video-claw/frontend/components/pipelines/PipelinePage.tsx |    2 
 video-claw/video-claw/backend/api/routers/sandbox.py                 |  115 ++-
 video-claw/video-claw/frontend/components/WorkflowPanel.tsx          |   27 
 video-claw/video-claw/backend/api/routers/workflow.py                |  293 +++-----
 video-claw/video-claw/backend/pipelines/storage.py                   |  167 ++--
 video-claw/video-claw/backend/core/agents/base_agent.py              |   65 -
 video-claw/video-claw/backend/core/agents/character_agent.py         |  100 --
 video-claw/video-claw/backend/core/orchestrator.py                   |  724 +++++++++++++---------
 16 files changed, 911 insertions(+), 917 deletions(-)

diff --git a/video-claw/video-claw/backend/api/routers/sandbox.py b/video-claw/video-claw/backend/api/routers/sandbox.py
index b24527f..6a3f0ea 100644
--- a/video-claw/video-claw/backend/api/routers/sandbox.py
+++ b/video-claw/video-claw/backend/api/routers/sandbox.py
@@ -1,6 +1,7 @@
 import json
 import logging
 import os
+import threading
 import uuid
 from datetime import datetime
 from typing import List
@@ -24,6 +25,7 @@
 SANDBOX_DIR = os.path.join(settings.CODE_DIR, "result", "sandbox")
 SANDBOX_HISTORY_FILE = os.path.join(SANDBOX_DIR, "history.json")
 SANDBOX_ACTIVE_TASKS: dict[str, dict] = {}
+SANDBOX_LOCK = threading.RLock()
 
 # 确保目录存在
 os.makedirs(SANDBOX_DIR, exist_ok=True)
@@ -31,20 +33,24 @@
 
 def _load_history() -> List[dict]:
     """加载历史记录"""
-    if os.path.exists(SANDBOX_HISTORY_FILE):
-        try:
-            with open(SANDBOX_HISTORY_FILE, 'r', encoding='utf-8') as f:
-                return json.load(f)
-        except Exception:
-            logger.warning("Failed to load sandbox history: %s", SANDBOX_HISTORY_FILE, exc_info=True)
-            return []
-    return []
+    with SANDBOX_LOCK:
+        if os.path.exists(SANDBOX_HISTORY_FILE):
+            try:
+                with open(SANDBOX_HISTORY_FILE, 'r', encoding='utf-8') as f:
+                    return json.load(f)
+            except Exception:
+                logger.warning("Failed to load sandbox history: %s", SANDBOX_HISTORY_FILE, exc_info=True)
+                return []
+        return []
 
 
 def _save_history(history: List[dict]):
     """保存历史记录"""
-    with open(SANDBOX_HISTORY_FILE, 'w', encoding='utf-8') as f:
-        json.dump(history, f, ensure_ascii=False, indent=2)
+    with SANDBOX_LOCK:
+        tmp_path = f"{SANDBOX_HISTORY_FILE}.{uuid.uuid4().hex}.tmp"
+        with open(tmp_path, 'w', encoding='utf-8') as f:
+            json.dump(history, f, ensure_ascii=False, indent=2)
+        os.replace(tmp_path, SANDBOX_HISTORY_FILE)
 
 
 def _normalize_path(path: str) -> str:
@@ -88,40 +94,43 @@
 
 def _add_record(tool: str, model: str, input_data: dict, output_data: dict, files: List[str] = None, record_id: str | None = None) -> str:
     """添加历史记录"""
-    record_id = record_id or str(uuid.uuid4().hex[:8])
-    # 转换路径为相对路径格式
-    output_data = _convert_output_paths(output_data)
-    record = {
-        "id": record_id,
-        "tool": tool,
-        "model": model,
-        "input": input_data,
-        "output": output_data,
-        "files": files or [],
-        "created_at": datetime.now().isoformat(),
-    }
-    history = _load_history()
-    history.insert(0, record)  # 最新记录放在最前面
-    _save_history(history)
-    return record_id
+    with SANDBOX_LOCK:
+        record_id = record_id or str(uuid.uuid4().hex[:8])
+        # 转换路径为相对路径格式
+        output_data = _convert_output_paths(output_data)
+        record = {
+            "id": record_id,
+            "tool": tool,
+            "model": model,
+            "input": input_data,
+            "output": output_data,
+            "files": files or [],
+            "created_at": datetime.now().isoformat(),
+        }
+        history = _load_history()
+        history.insert(0, record)  # 最新记录放在最前面
+        _save_history(history)
+        return record_id
 
 
 def _start_active_task(tool: str, model: str, input_data: dict) -> str:
-    task_id = str(uuid.uuid4().hex[:8])
-    SANDBOX_ACTIVE_TASKS[task_id] = {
-        "id": task_id,
-        "tool": tool,
-        "model": model,
-        "input": input_data,
-        "status": "running",
-        "progress": 1,
-        "created_at": datetime.now().isoformat(),
-    }
-    return task_id
+    with SANDBOX_LOCK:
+        task_id = str(uuid.uuid4().hex[:8])
+        SANDBOX_ACTIVE_TASKS[task_id] = {
+            "id": task_id,
+            "tool": tool,
+            "model": model,
+            "input": input_data,
+            "status": "running",
+            "progress": 1,
+            "created_at": datetime.now().isoformat(),
+        }
+        return task_id
 
 
 def _finish_active_task(task_id: str) -> None:
-    SANDBOX_ACTIVE_TASKS.pop(task_id, None)
+    with SANDBOX_LOCK:
+        SANDBOX_ACTIVE_TASKS.pop(task_id, None)
 
 
 def _delete_record_files(files: List[str]):
@@ -160,7 +169,9 @@
 @router.get("/api/sandbox/tasks")
 async def sandbox_get_active_tasks():
     """获取临时工作台正在执行的任务"""
-    return {"success": True, "tasks": list(SANDBOX_ACTIVE_TASKS.values())}
+    with SANDBOX_LOCK:
+        tasks = list(SANDBOX_ACTIVE_TASKS.values())
+    return {"success": True, "tasks": tasks}
 
 
 @router.get("/api/sandbox/history/{record_id}")
@@ -176,21 +187,23 @@
 @router.delete("/api/sandbox/history/{record_id}")
 async def sandbox_delete_record(record_id: str):
     """删除历史记录"""
-    history = _load_history()
-    record_to_delete = None
-    new_history = []
-    for r in history:
-        if r["id"] == record_id:
-            record_to_delete = r
-        else:
-            new_history.append(r)
+    with SANDBOX_LOCK:
+        history = _load_history()
+        record_to_delete = None
+        new_history = []
+        for r in history:
+            if r["id"] == record_id:
+                record_to_delete = r
+            else:
+                new_history.append(r)
 
-    if record_to_delete is None:
-        return {"success": False, "error": "记录不存在"}
+        if record_to_delete is None:
+            return {"success": False, "error": "记录不存在"}
 
-    # 删除关联的文件
+        _save_history(new_history)
+
+    # 删除关联文件不需要占用历史锁。
     _delete_record_files(record_to_delete.get("files", []))
-    _save_history(new_history)
     logger.info("Sandbox history deleted: record_id=%s", record_id)
     return {"success": True}
 
diff --git a/video-claw/video-claw/backend/api/routers/workflow.py b/video-claw/video-claw/backend/api/routers/workflow.py
index ac19d33..a1cdddd 100644
--- a/video-claw/video-claw/backend/api/routers/workflow.py
+++ b/video-claw/video-claw/backend/api/routers/workflow.py
@@ -1,7 +1,9 @@
+import copy
 import json
 import os
 import time
 from datetime import datetime
+from types import SimpleNamespace
 
 from fastapi import APIRouter, HTTPException, Request
 from fastapi.responses import StreamingResponse
@@ -37,16 +39,6 @@
         )
 
 
-def _session_file_path(session_id: str) -> str:
-    session_dir = os.path.join(
-        os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
-        'code',
-        'data',
-        'sessions',
-    )
-    return os.path.join(session_dir, f"{session_id}.json")
-
-
 @router.post("/api/project/start")
 async def start_project(req: ProjectStartRequest):
     final_idea = merge_uploaded_file_into_idea(req.idea, req.file_path)
@@ -54,11 +46,6 @@
 
     session_id = str(int(time.time() * 1000))
     state = workflow_engine.get_or_create_state(session_id)
-    state.started_at = datetime.now()
-    if not isinstance(state.status, dict):
-        state.status = {}
-    state.status[state.current_stage.value] = "completed"
-
     meta = {
         "idea": final_idea,
         "user_textbox_input": req.idea,
@@ -75,12 +62,17 @@
         "web_search": req.web_search if req.web_search is not None else False,
         "episodes": req.episodes if req.episodes is not None else 4,
     }
-    state.meta = meta
-    workflow_engine.save_session_to_disk(session_id, meta)
+    with workflow_engine._state_lock:
+        state.started_at = datetime.now()
+        if not isinstance(state.status, dict):
+            state.status = {}
+        state.status[state.current_stage.value] = "completed"
+        state.meta = meta
+        workflow_engine.save_session_to_disk(session_id, meta)
 
     return {
         "session_id": session_id,
-        "status": state.status,
+        "status": copy.deepcopy(state.status),
         "params": {
             "idea": final_idea,
             "file_path": req.file_path,
@@ -107,13 +99,17 @@
         body = {}
 
     body["session_id"] = session_id
-    if state.meta:
-        for k, v in state.meta.items():
+    with workflow_engine._state_lock:
+        meta_snapshot = copy.deepcopy(state.meta)
+        artifact_snapshot = copy.deepcopy(state.artifacts)
+    if meta_snapshot:
+        for k, v in meta_snapshot.items():
             if v is not None and (k not in body or not body[k]):
                 body[k] = v
     _require_model_fields(body)
 
-    inject_user_selections(state, stage, body)
+    state_for_input = SimpleNamespace(artifacts=artifact_snapshot)
+    inject_user_selections(state_for_input, stage, body)
     cancellation_check, on_disconnect = make_cancellation(workflow_engine, session_id)
     progress_events, event_trigger, progress_callback = make_progress_channel()
 
@@ -145,16 +141,18 @@
     state = workflow_engine.get_state(session_id)
     if not state:
         raise HTTPException(404, "Session not found")
-    return state.to_dict()
+    with workflow_engine._state_lock:
+        return state.to_dict()
 
 
 @router.get("/api/project/{session_id}/status/from_disk")
 async def get_project_status_from_disk(session_id: str):
-    session_file = _session_file_path(session_id)
-    if not os.path.exists(session_file):
+    # 兼容旧前端路由名;实际读取统一走 WorkflowEngine 的内存状态入口。
+    state = workflow_engine.get_state(session_id)
+    if not state:
         raise HTTPException(404, "Session not found")
-    with open(session_file, 'r', encoding='utf-8') as f:
-        return json.load(f)
+    with workflow_engine._state_lock:
+        return state.to_dict()
 
 
 @router.get("/api/project/{session_id}/artifact/{stage}")
@@ -163,22 +161,12 @@
     if not state:
         raise HTTPException(404, "Session not found")
 
-    session_file = _session_file_path(session_id)
-    if os.path.exists(session_file):
-        try:
-            with open(session_file, 'r', encoding='utf-8') as f:
-                disk_data = json.load(f)
-            disk_artifact = disk_data.get("artifacts", {}).get(stage)
-            if disk_artifact is not None:
-                state.artifacts[stage] = disk_artifact
-                return {"stage": stage, "artifact": disk_artifact}
-        except Exception:
-            pass
+    with workflow_engine._state_lock:
+        artifact = copy.deepcopy(state.artifacts.get(stage))
+    if artifact is not None:
+        return {"stage": stage, "artifact": artifact}
 
-    artifact = state.artifacts.get(stage)
-    if artifact is None:
-        raise HTTPException(404, f"Artifact for stage '{stage}' not found")
-    return {"stage": stage, "artifact": artifact}
+    raise HTTPException(404, f"Artifact for stage '{stage}' not found")
 
 
 @router.patch("/api/project/{session_id}/models")
@@ -188,71 +176,36 @@
         raise HTTPException(404, "Session not found")
     body = await request.json()
     allowed_keys = ("llm_model", "vlm_model", "image_t2i_model", "image_it2i_model", "video_model", "video_ratio", "video_resolution", "style", "enable_concurrency")
-    if not state.meta:
-        state.meta = {}
-    for k in allowed_keys:
-        if k in body:
-            state.meta[k] = body[k]
-    workflow_engine.save_session_to_disk(session_id)
+    with workflow_engine._state_lock:
+        if not state.meta:
+            state.meta = {}
+        for k in allowed_keys:
+            if k in body:
+                state.meta[k] = body[k]
+        workflow_engine.save_session_to_disk(session_id)
     return {"status": "ok"}
 
 
-@router.patch("/api/project/{session_id}/artifact/{stage}")
-async def update_artifact(session_id: str, stage: str, request: Request):
-    """保存用户在某阶段的选择/修改
-
-    数据存储策略:
-    - 用户修改只保存到 sessions json(state.artifacts)
-    - result/script json 只作为 LLM 初始生成,不接受用户修改
-
-    按阶段分类处理:
-    - 第二阶段(character_design): 修改 characters[]/settings[] 的 description
-    - 第三阶段(storyboard): 修改 episodes[]/segments[]/shots[] 的分镜数据
-    - 第四阶段(reference_generation): 修改 scenes[] 的 description(视觉提示词)
-    - 第五阶段(video_generation): 修改 clips[] 的 duration/description
-    """
-    state = workflow_engine.get_state(session_id)
-    if not state:
-        raise HTTPException(404, "Session not found")
-    body = await request.json()
-
-    # ══════════════════════════════════════════════════════════════
-    # 第二阶段:角色/背景描述修改
-    # 修改 characters[].description 或 settings[].description
-    # 不涉及跨阶段同步
-    # ══════════════════════════════════════════════════════════════
-    if stage == "character_design":
-        # 直接更新 body,由后续逻辑合并到 artifact
-        pass
-
-    # ══════════════════════════════════════════════════════════════
-    # 第三阶段:分镜修改
-    # 当前结构为 episodes -> segments -> shots;segments 对应一次视频模型调用
-    # 同步到:video_generation.clips[].duration, video_generation.clips[].description
-    # ══════════════════════════════════════════════════════════════
-    elif stage == "storyboard" and any(k in body for k in ("episodes", "segments", "shots")):
-        # 兼容旧 shots 格式:清除 is_new 标记
+def _apply_artifact_update(state, stage: str, body: dict):
+    """Apply a user edit to in-memory artifacts before the session is persisted."""
+    if stage == "storyboard" and any(k in body for k in ("episodes", "segments", "shots")):
         for shot in body.get('shots', []):
             if isinstance(shot, dict) and 'is_new' in shot:
                 shot['is_new'] = False
 
-        # 从 episodes/segments 提取同步信息
         input_segments = list(body.get('segments', []))
         for ep in body.get('episodes', []):
             if isinstance(ep, dict):
-                for seg in ep.get('segments', []):
-                    if isinstance(seg, dict):
-                        input_segments.append(seg)
+                input_segments.extend(seg for seg in ep.get('segments', []) if isinstance(seg, dict))
 
         seg_info_list = []
         for seg in input_segments:
             seg_id = seg.get('segment_id')
-            if not seg_id: continue
-            
+            if not seg_id:
+                continue
             shots = seg.get('shots', [])
             desc_video = " ".join([sh.get("plot") or sh.get("content") or "" for sh in shots]).strip()
             total_dur = seg.get("total_duration") or sum([sh.get("duration", 0) for sh in shots]) or 10
-            
             seg_info_list.append({
                 "segment_id": seg_id,
                 "desc": desc_video,
@@ -260,96 +213,63 @@
                 "visual_prompt": seg.get("visual_prompt", ""),
             })
 
-        # 同步到 video_generation
         video_art = state.artifacts.get('video_generation', {})
-        if isinstance(video_art, dict) and 'clips' in video_art:
+        if isinstance(video_art, dict) and isinstance(video_art.get('clips'), list):
             for clip in video_art['clips']:
-                c_id = clip.get('id')
-                # 匹配 segment_id
-                target = next((item for item in seg_info_list if item["segment_id"] == c_id), None)
+                target = next((item for item in seg_info_list if item["segment_id"] == clip.get('id')), None)
                 if target:
                     clip['duration'] = target['duration']
                     clip['description'] = target['desc']
 
-        # 同步到 reference_generation
         ref_art = state.artifacts.get('reference_generation', {})
-        if isinstance(ref_art, dict) and 'scenes' in ref_art:
+        if isinstance(ref_art, dict) and isinstance(ref_art.get('scenes'), list):
             for scene in ref_art['scenes']:
-                s_id = scene.get('id')
-                target = next((item for item in seg_info_list if item["segment_id"] == s_id), None)
+                target = next((item for item in seg_info_list if item["segment_id"] == scene.get('id')), None)
                 if target and target.get("visual_prompt"):
                     scene['description'] = target['visual_prompt']
 
-        # 顶层 segments 是局部 patch 结构,不覆盖完整 storyboard artifact
         if "segments" in body and "episodes" not in body:
             body = {k: v for k, v in body.items() if k != "segments"}
+        body.pop('new_shot_ids', None)
 
-        # 清除 new_shot_ids 标记
-        if "new_shot_ids" in body:
-            del body['new_shot_ids']
-
-    # ══════════════════════════════════════════════════════════════
-    # 第四阶段:参考图提示词修改
-    # 修改 scenes[].description(视觉提示词)
-    # 同步到:storyboard.episodes[].segments[].visual_prompt
-    # ══════════════════════════════════════════════════════════════
     elif stage == "reference_generation":
         if "segments" in body:
-            # 修改视觉提示词 → 同步到 storyboard
-            # 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}
+            seg_id_to_prompt = {
+                s['segment_id']: s.get('visual_prompt', '')
+                for s in body['segments']
+                if isinstance(s, dict) and 'segment_id' in s
+            }
 
             storyboard_art = state.artifacts.get('storyboard', {})
-            # storyboard 结构: {episodes: [{segments: [...]}]}
             if isinstance(storyboard_art, dict):
-                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]
+                for ep in storyboard_art.get('episodes', []):
+                    if not isinstance(ep, dict):
+                        continue
+                    for seg in ep.get('segments', []):
+                        if isinstance(seg, dict) and seg.get('segment_id') in seg_id_to_prompt:
+                            seg['visual_prompt'] = seg_id_to_prompt[seg.get('segment_id')]
 
-            # 同步到 reference_generation.scenes 的 description
             ref_art = state.artifacts.get('reference_generation', {})
             if isinstance(ref_art, dict):
-                scenes = ref_art.get('scenes', [])
-                for scene in scenes:
-                    if isinstance(scene, dict):
-                        scene_id = scene.get('id')
-                        if scene_id in seg_id_to_prompt:
-                            scene['description'] = seg_id_to_prompt[scene_id]
+                for scene in ref_art.get('scenes', []):
+                    if isinstance(scene, dict) and scene.get('id') in seg_id_to_prompt:
+                        scene['description'] = seg_id_to_prompt[scene.get('id')]
 
-            # 移除 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', {})
         if isinstance(ref_art, dict):
             scenes = ref_art.get('scenes', [])
-            is_selection_format = any(
-                isinstance(k, str) and not isinstance(v, (list, dict))
-                for k, v in body.items()
-            )
+            is_selection_format = any(isinstance(k, str) and not isinstance(v, (list, dict)) for k, v in body.items())
             if is_selection_format and scenes:
                 for scene in scenes:
-                    scene_id = scene.get('id')
-                    if scene_id and scene_id in body:
-                        scene['selected'] = body[scene_id]
+                    if isinstance(scene, dict) and scene.get('id') in body:
+                        scene['selected'] = body[scene.get('id')]
                 body = {}
 
-    # ══════════════════════════════════════════════════════════════
-    # 第五阶段:视频片段修改
-    # 修改 clips[].duration / clips[].description
-    # 同步到:storyboard.episodes[].segments[].total_duration
-    # ══════════════════════════════════════════════════════════════
     elif stage == "video_generation":
-        # 收集 clips 的修改
         clip_id_to_duration = {}
         clip_id_to_description = {}
-
         for clip_id, value in body.items():
             if isinstance(value, dict):
                 if 'duration' in value:
@@ -357,48 +277,37 @@
                 if 'description' in value:
                     clip_id_to_description[clip_id] = value['description']
 
-        # 同步到 storyboard 和 video_generation.clips
         if clip_id_to_duration or clip_id_to_description:
             storyboard_art = state.artifacts.get('storyboard', {})
-            # storyboard 结构: 从 shots 变更为了 episodes -> segments
             if isinstance(storyboard_art, dict):
-                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]
+                for ep in storyboard_art.get('episodes', []):
+                    if not isinstance(ep, dict):
+                        continue
+                    for seg in ep.get('segments', []):
+                        if isinstance(seg, dict) and seg.get('segment_id') in clip_id_to_duration:
+                            seg['total_duration'] = clip_id_to_duration[seg.get('segment_id')]
 
-            # 更新 video_generation.clips 的 duration 和 description
             vid_art = state.artifacts.get('video_generation', {})
             if isinstance(vid_art, dict):
-                clips = vid_art.get('clips', [])
-                for clip in clips:
-                    if isinstance(clip, dict):
-                        clip_id = clip.get('id')
-                        if clip_id in clip_id_to_duration:
-                            clip['duration'] = clip_id_to_duration[clip_id]
-                        if clip_id in clip_id_to_description:
-                            clip['description'] = clip_id_to_description[clip_id]
+                for clip in vid_art.get('clips', []):
+                    if not isinstance(clip, dict):
+                        continue
+                    clip_id = clip.get('id')
+                    if clip_id in clip_id_to_duration:
+                        clip['duration'] = clip_id_to_duration[clip_id]
+                    if clip_id in clip_id_to_description:
+                        clip['description'] = clip_id_to_description[clip_id]
 
-        # 处理视频版本选择 {clipId: path}
         vid_art = state.artifacts.get('video_generation', {})
         if isinstance(vid_art, dict):
             clips = vid_art.get('clips', [])
-            is_selection_format = any(
-                isinstance(k, str) and not isinstance(v, (list, dict))
-                for k, v in body.items()
-            )
+            is_selection_format = any(isinstance(k, str) and not isinstance(v, (list, dict)) for k, v in body.items())
             if is_selection_format and clips:
                 for clip in clips:
-                    clip_id = clip.get('id')
-                    if clip_id and clip_id in body:
-                        clip['selected'] = body[clip_id]
+                    if isinstance(clip, dict) and clip.get('id') in body:
+                        clip['selected'] = body[clip.get('id')]
                 body = {}
 
-    # 更新 state.artifacts 并保存到 sessions json
     current = state.artifacts.get(stage)
     if current is None:
         state.artifacts[stage] = body
@@ -407,9 +316,23 @@
     else:
         state.artifacts[stage] = body
 
-    workflow_engine.save_session_to_disk(session_id)
 
-    return {"status": "ok"}
+@router.patch("/api/project/{session_id}/artifact/{stage}")
+async def update_artifact(session_id: str, stage: str, request: Request):
+    """保存用户在某阶段的选择/修改,同时更新内存状态和磁盘快照。"""
+    state = workflow_engine.get_state(session_id)
+    if not state:
+        raise HTTPException(404, "Session not found")
+    body = await request.json()
+
+    with workflow_engine._state_lock:
+        _apply_artifact_update(state, stage, body if isinstance(body, dict) else {})
+        workflow_engine._recalculate_all_statuses(state)
+        workflow_engine.save_session_to_disk(session_id)
+        status_snapshot = copy.deepcopy(state.status)
+        artifact_snapshot = copy.deepcopy(state.artifacts.get(stage))
+
+    return {"status": "ok", "status_map": status_snapshot, "artifact": artifact_snapshot}
 
 
 
@@ -423,14 +346,18 @@
     cancellation_check, on_disconnect = make_cancellation(workflow_engine, session_id)
     progress_events, event_trigger, progress_callback = make_progress_channel()
 
-    current_artifact = state.artifacts.get(req.stage, {})
+    with workflow_engine._state_lock:
+        current_artifact = copy.deepcopy(state.artifacts.get(req.stage, {}))
+        meta_snapshot = copy.deepcopy(state.meta)
+        artifact_snapshot = copy.deepcopy(state.artifacts)
     input_data = current_artifact if isinstance(current_artifact, dict) else {}
     input_data["session_id"] = session_id
-    if state.meta:
-        for k, v in state.meta.items():
+    if meta_snapshot:
+        for k, v in meta_snapshot.items():
             if v is not None and k not in input_data:
                 input_data[k] = v
-    inject_user_selections(state, req.stage, input_data)
+    state_for_input = SimpleNamespace(artifacts=artifact_snapshot)
+    inject_user_selections(state_for_input, req.stage, input_data)
     input_data.update(req.modifications)
 
     return StreamingResponse(
@@ -473,6 +400,8 @@
 @router.get("/api/project/{session_id}/scene/{scene_number}/assets")
 async def check_scene_assets(session_id: str, scene_number: int):
     state = workflow_engine.get_state(session_id)
+    with workflow_engine._state_lock:
+        artifacts_snapshot = copy.deepcopy(state.artifacts) if state else {}
     result_file = os.path.join(settings.RESULT_DIR, 'script', f'{session_id}.json')
     if not os.path.exists(result_file):
         return {"scene_number": scene_number, "reference_images": 0, "videos": 0}
@@ -494,8 +423,8 @@
     shot_ids = [s.get('shot_id') for s in scene_shots if s.get('shot_id')]
 
     ref_artifact = script_data.get('reference_generation', {})
-    if not ref_artifact and state:
-        ref_artifact = state.artifacts.get('reference_generation', {})
+    if not ref_artifact:
+        ref_artifact = artifacts_snapshot.get('reference_generation', {})
 
     ref_scenes = ref_artifact.get('scenes', []) if isinstance(ref_artifact, dict) else []
     ref_image_count = 0
@@ -510,8 +439,8 @@
                     ref_image_count += 1
 
     video_artifact = script_data.get('video_generation', {})
-    if not video_artifact and state:
-        video_artifact = state.artifacts.get('video_generation', {})
+    if not video_artifact:
+        video_artifact = artifacts_snapshot.get('video_generation', {})
 
     video_clips = video_artifact.get('clips', []) if isinstance(video_artifact, dict) else []
     video_count = 0
diff --git a/video-claw/video-claw/backend/api/schemas/pipelines.py b/video-claw/video-claw/backend/api/schemas/pipelines.py
index 3e6879a..9cc6e32 100644
--- a/video-claw/video-claw/backend/api/schemas/pipelines.py
+++ b/video-claw/video-claw/backend/api/schemas/pipelines.py
@@ -27,7 +27,7 @@
     template_media_kind: Literal["image", "video"] = "image"
     video_duration: int = 5
     tts_voice: str = "zh-CN-YunjianNeural"
-    tts_speed: float = 1.2
+    tts_speed: float = 1.0
     negative_prompt: Optional[str] = None
     watermark: Optional[bool] = None
     generate_audio_native: Optional[bool] = None
@@ -62,7 +62,7 @@
     video_resolution: Optional[str] = None
     resolution: Optional[str] = None
     tts_voice: str = "zh-CN-YunjianNeural"
-    tts_speed: float = 1.2
+    tts_speed: float = 1.0
     negative_prompt: Optional[str] = None
     watermark: Optional[bool] = None
     prompt_extend: Optional[bool] = None
diff --git a/video-claw/video-claw/backend/api/services/project_helpers.py b/video-claw/video-claw/backend/api/services/project_helpers.py
index 518cf10..fb70bef 100644
--- a/video-claw/video-claw/backend/api/services/project_helpers.py
+++ b/video-claw/video-claw/backend/api/services/project_helpers.py
@@ -1,4 +1,5 @@
 import asyncio
+import copy
 import json
 import queue
 import threading
@@ -131,9 +132,7 @@
                     break
 
             if await request.is_disconnected():
-                if on_disconnect:
-                    on_disconnect()
-                yield json.dumps({"type": "error", "content": "Client disconnected"}) + "\n"
+                workflow_engine.track_background_task(task)
                 return
 
         while not progress_events.empty():
@@ -145,11 +144,13 @@
 
         result = task.result()
         workflow_engine.save_session_to_disk(state.session_id)
+        with workflow_engine._state_lock:
+            status_snapshot = copy.deepcopy(state.status)
 
         payload = {
             "type": "stage_complete",
             "stage": stage,
-            "status": state.status,
+            "status": status_snapshot,
             "requires_intervention": result.get("requires_intervention", False),
             "openclaw": build_openclaw_message(stage, result),
         }
diff --git a/video-claw/video-claw/backend/core/agents/base_agent.py b/video-claw/video-claw/backend/core/agents/base_agent.py
index 3e21d2e..ab44dbd 100644
--- a/video-claw/video-claw/backend/core/agents/base_agent.py
+++ b/video-claw/video-claw/backend/core/agents/base_agent.py
@@ -4,13 +4,17 @@
 """
 
 import logging
-import os
-import json
 from abc import ABC, abstractmethod
 from typing import Any, Optional, Dict, Callable
-from config import settings
 
 logger = logging.getLogger(__name__)
+
+SESSION_PARAM_KEYS = [
+    "idea", "user_textbox_input", "style", "video_ratio", "video_resolution",
+    "llm_model", "vlm_model",
+    "image_t2i_model", "image_it2i_model", "video_model",
+    "video_style", "expand_idea", "enable_concurrency", "web_search", "episodes"
+]
 
 
 class AgentInterface(ABC):
@@ -22,48 +26,29 @@
         self.progress_callback: Optional[Callable] = None
 
     def _merge_session_params(self, input_data: Any) -> Dict:
-        """从 session.json 补齐缺失的参数"""
+        """从编排器注入的 session 快照补齐缺失参数。"""
         if not isinstance(input_data, dict):
             return {}
-            
-        sid = input_data.get("session_id")
-        if not sid:
-            return input_data
 
-        session_file = os.path.join(settings.SESSION_DIR, f"{sid}.json")
-        if not os.path.exists(session_file):
-            return input_data
+        session_meta = self._session_meta(input_data)
+        merged_data = input_data.copy()
+        for key in SESSION_PARAM_KEYS:
+            if key not in merged_data or not merged_data[key]:
+                if key in session_meta and session_meta[key] is not None:
+                    merged_data[key] = session_meta[key]
+        return merged_data
 
-        try:
-            with open(session_file, 'r', encoding='utf-8') as f:
-                session_data = json.load(f)
-            
-            session_meta = session_data.get("meta")
-            if not isinstance(session_meta, dict):
-                session_meta = {}
+    def _session_meta(self, input_data: Dict) -> Dict:
+        meta = input_data.get("_session_meta") if isinstance(input_data, dict) else {}
+        return meta if isinstance(meta, dict) else {}
 
-            # 基础参数列表
-            keys_to_merge = [
-                "idea", "user_textbox_input", "style", "video_ratio", "video_resolution",
-                "llm_model", "vlm_model",
-                "image_t2i_model", "image_it2i_model", "video_model",
-                "video_style", "expand_idea", "enable_concurrency", "web_search", "episodes"
-            ]
-            
-            merged_data = input_data.copy()
-            for key in keys_to_merge:
-                # 只有当 input_data 中缺失该参数时,才从 session 中补齐
-                if key not in merged_data or not merged_data[key]:
-                    if key in session_meta and session_meta[key] is not None:
-                        merged_data[key] = session_meta[key]
-                    elif key in session_data and session_data[key] is not None:
-                        # 兼容旧会话:旧版本把生成参数保存在根字段。
-                        merged_data[key] = session_data[key]
-            
-            return merged_data
-        except Exception as e:
-            logger.error(f"Error merging session params: {e}")
-            return input_data
+    def _session_artifacts(self, input_data: Dict) -> Dict:
+        artifacts = input_data.get("_session_artifacts") if isinstance(input_data, dict) else {}
+        return artifacts if isinstance(artifacts, dict) else {}
+
+    def _session_artifact(self, input_data: Dict, stage: str) -> Dict:
+        artifact = self._session_artifacts(input_data).get(stage, {})
+        return artifact if isinstance(artifact, dict) else {}
 
     def set_cancellation_check(self, fn: Callable):
         self.cancellation_check = fn
diff --git a/video-claw/video-claw/backend/core/agents/character_agent.py b/video-claw/video-claw/backend/core/agents/character_agent.py
index 3e1e457..7b857a6 100644
--- a/video-claw/video-claw/backend/core/agents/character_agent.py
+++ b/video-claw/video-claw/backend/core/agents/character_agent.py
@@ -368,46 +368,29 @@
 
     # ─── 从剧本JSON读取角色/场景数据 ───
 
-    @staticmethod
-    def _read_script_data(sid: str) -> dict:
-        """从 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": {}}
+    def _read_script_data(self, input_data: Dict) -> dict:
+        """从编排器注入的 script_generation artifact 提取角色和场景数据。"""
+        script_gen = self._session_artifact(input_data, "script_generation")
+        chars = {}
+        for c in script_gen.get("characters", []):
+            cid = c.get("character_id") or c.get("id") or ""
+            if cid:
+                chars[cid] = {
+                    "name": c.get("name", ""),
+                    "description": c.get("description", ""),
+                    "species": c.get("species", ""),
+                }
 
-        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 script_gen.get("characters", []):
-                cid = c.get("character_id", "")
-                if cid:
-                    chars[cid] = {
-                        "name": c.get("name", ""),
-                        "description": c.get("description", ""),
-                        "species": c.get("species", ""),
-                    }
-                    
-            sets = {}
-            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}
-        except Exception as e:
-            logger.error(f"Error reading session data for {sid}: {e}")
-            return {"characters": {}, "settings": {}}
+        sets = {}
+        for s in script_gen.get("settings", []):
+            sid_val = s.get("setting_id") or s.get("id") or ""
+            if sid_val:
+                sets[sid_val] = {
+                    "name": s.get("name", ""),
+                    "description": s.get("description", ""),
+                }
+
+        return {"characters": chars, "settings": sets}
 
     # ─── 核心流程 ───
 
@@ -475,7 +458,7 @@
 
             # 如果 input_data 为空(比如后端重启后的第一次介入),再读原始文件
             if not chars_desc and not sets_desc:
-                script_data = self._read_script_data(sid)
+                script_data = self._read_script_data(input_data)
                 chars_desc = script_data["characters"]
                 sets_desc = script_data["settings"]
 
@@ -509,41 +492,6 @@
                         else:
                             # 简单字符串格式:直接更新 description
                             sets_desc[asset_id]["description"] = str(info)
-
-                # 写回会话数据文件
-                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}")
 
@@ -608,7 +556,7 @@
                 sets_desc = input_data["settings"]
         
         if not chars_desc and not sets_desc:
-            script_data = self._read_script_data(sid)
+            script_data = self._read_script_data(input_data)
             chars_desc = script_data["characters"]
             sets_desc = script_data["settings"]
 
diff --git a/video-claw/video-claw/backend/core/agents/editor_agent.py b/video-claw/video-claw/backend/core/agents/editor_agent.py
index 54653d5..4f10e36 100644
--- a/video-claw/video-claw/backend/core/agents/editor_agent.py
+++ b/video-claw/video-claw/backend/core/agents/editor_agent.py
@@ -6,7 +6,6 @@
 
 import os
 import re
-import json
 import asyncio
 import logging
 import subprocess
@@ -24,17 +23,11 @@
         super().__init__(name="VideoEditor")
 
     async def process(self, input_data: Any, intervention: Optional[Dict] = None) -> Dict:
+        input_data = self._merge_session_params(input_data)
         sid = input_data["session_id"]
-        
-        # 优先从 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", {})
+
+        # 从编排器注入的统一 session 快照读取阶段5数据。
+        artifacts = self._session_artifacts(input_data)
         video_art = artifacts.get("video_generation", {})
         clips_list = video_art.get("clips", [])
         
@@ -148,16 +141,11 @@
 
         self._report_progress("后期制作", "成片完成", 100)
 
-        # 同样将最终结果写入 artifacts
-        session_data.setdefault("artifacts", {})["post_production"] = {
-            "session_id": sid,
-            "final_videos": final_results,
-            "final_video": final_results[0]["path"] if final_results else "" # 兼容旧字段
-        }
-        with open(session_path, 'w', encoding='utf-8') as f:
-            json.dump(session_data, f, indent=4, ensure_ascii=False)
-
         return {
-            "payload": {"session_id": sid, "final_videos": final_results},
+            "payload": {
+                "session_id": sid,
+                "final_videos": final_results,
+                "final_video": final_results[0]["path"] if final_results else "",
+            },
             "stage_completed": True,
-        }
\ No newline at end of file
+        }
diff --git a/video-claw/video-claw/backend/core/agents/reference_agent.py b/video-claw/video-claw/backend/core/agents/reference_agent.py
index 5802f62..72b3848 100644
--- a/video-claw/video-claw/backend/core/agents/reference_agent.py
+++ b/video-claw/video-claw/backend/core/agents/reference_agent.py
@@ -550,7 +550,7 @@
         from models.image_client import ImageClient
         from models.llm_client import LLM
 
-        # 从 session.json 补齐缺失的参数(关键修复:防止前端漏传导致的默认值回退)
+        # 从编排器注入的 session 快照补齐缺失参数,避免各阶段直接读取 session JSON。
         input_data = self._merge_session_params(input_data)
 
         sid = input_data["session_id"]
@@ -572,15 +572,11 @@
         concurrency = max(max_t2i, max_it2i)
         logger.info(f"[ReferenceAgent] 使用并发数={concurrency}")
 
-        # 读取会话数据
-        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", {})
+        artifacts = self._session_artifacts(input_data)
+        session_data = {
+            "meta": self._session_meta(input_data),
+            "artifacts": artifacts,
+        }
         
         # 提取已经存在于 session 中的 visual_prompts
         session_visual_prompts = {}
@@ -617,7 +613,6 @@
 
         script_json = artifacts.get('script_generation', {})
         character_json = artifacts.get('character_design', {})
-        result_file = os.path.join('code/data/sessions', f'{sid}.json')
 
         # 判断中英文
         is_zh = any('\u4e00' <= c <= '\u9fff' for c in script_json.get("title", ""))
@@ -642,11 +637,7 @@
             if regen_scenes:
                 self._report_progress("参考图", "重新生成中...", 2)
 
-                # 重新从 session JSON 文件读取最新的 storyboard 数据
-                with open(session_path, 'r', encoding='utf-8') as f:
-                    fresh_data = json.load(f)
-                fresh_artifacts = fresh_data.get('artifacts', {})
-                fresh_episodes = fresh_artifacts.get('storyboard', {}).get('episodes', [])
+                fresh_episodes = artifacts.get('storyboard', {}).get('episodes', [])
                 
                 fresh_segments = []
                 for ep in fresh_episodes:
diff --git a/video-claw/video-claw/backend/core/agents/storyboard_agent.py b/video-claw/video-claw/backend/core/agents/storyboard_agent.py
index 4203597..feb5d34 100644
--- a/video-claw/video-claw/backend/core/agents/storyboard_agent.py
+++ b/video-claw/video-claw/backend/core/agents/storyboard_agent.py
@@ -31,18 +31,6 @@
     OPENING_SHOT_TYPES = {"中景", "全景"}
 
     @staticmethod
-    def _read_script_json(sid: str) -> dict:
-        session_path = os.path.join("code/data/sessions", f"{sid}.json")
-        if not os.path.exists(session_path):
-            return {}
-        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]]:
         text = text.strip()
         text = re.sub(r"^```(?:json)?\s*", "", text)
@@ -1265,11 +1253,8 @@
         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)
-        session_meta = session_data.get("meta") if isinstance(session_data.get("meta"), dict) else {}
+        artifacts = self._session_artifacts(input_data)
+        session_meta = self._session_meta(input_data)
             
         llm_model = input_data.get("llm_model") or session_meta.get("llm_model")
         if not llm_model:
@@ -1280,18 +1265,17 @@
         if intervention and "modified_storyboard" in intervention:
             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()
+            return {
+                "payload": {
+                    "session_id": sid,
+                    "episodes": modified_episodes,
+                    "user_modified": True,
+                    "updated_at": datetime.now().isoformat(),
+                },
+                "stage_completed": True,
             }
-            # 更新顶层状态
-            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)
+        script_data = artifacts.get("script_generation", {})
         if not script_data: raise Exception("未找到剧本数据")
         
         episodes = script_data.get("episodes", [])
@@ -1299,7 +1283,7 @@
             raise Exception("剧本数据中不包含有效集数列表(episodes)")
 
         # 检查是否有已存在的分镜数据,识别需要生成的集数
-        existing_storyboard = session_data.get("artifacts", {}).get("storyboard", {})
+        existing_storyboard = artifacts.get("storyboard", {})
         existing_story_eps = existing_storyboard.get("episodes", [])
         
         # 建立已生成的 segments 索引
@@ -1348,19 +1332,18 @@
                 "segments": segments
             }
 
-        # 核心:支持流式保存增量产物,让前端能看到实时进度
+        # 核心:支持流式推送增量产物,让前端能看到实时进度
         updated_ep_map = {e["episode_number"]: e for e in existing_story_eps}
         
-        # 立即先保存一次,确保已有的 episodes 在进入 running 状态后依然可见
-        session_data.setdefault("artifacts", {})["storyboard"] = {
-            "session_id": sid, 
-            "episodes": sorted(updated_ep_map.values(), key=lambda x: x["episode_number"]),
-            "created_at": datetime.now().isoformat()
-        }
-        with open(session_file, "w", encoding="utf-8") as f:
-            json.dump(session_data, f, indent=2, ensure_ascii=False)
-        # 报告一次进度,带上 asset_complete 强制前端从磁盘刷新一次初步数据
-        report_storyboard_note("准备生成分镜...", 10, {"asset_complete": True})
+        # 报告一次进度,带上 assets_preview 让编排器更新内存中的初步数据
+        report_storyboard_note("准备生成分镜...", 10, {
+            "assets_preview": {
+                "session_id": sid,
+                "episodes": sorted(updated_ep_map.values(), key=lambda x: x["episode_number"]),
+                "created_at": datetime.now().isoformat(),
+            },
+            "persist": True,
+        })
 
         results_queue = [asyncio.create_task(proc_ep(ep)) for ep in episodes_to_proc]
 
@@ -1369,37 +1352,25 @@
             completed_count += 1
             updated_ep_map[res["episode_number"]] = res
             
-            # 每完成一集分镜,立即持久化并触发增量同步
+            # 每完成一集分镜,通过编排器更新内存并受控持久化
             temp_eps = sorted(updated_ep_map.values(), key=lambda x: x["episode_number"])
-            session_data.setdefault("artifacts", {})["storyboard"] = {
-                "session_id": sid, 
-                "episodes": temp_eps, 
-                "created_at": datetime.now().isoformat()
-            }
-            with open(session_file, "w", encoding="utf-8") as f:
-                json.dump(session_data, f, indent=2, ensure_ascii=False)
             
             # 并发多集时只按已完成集数推进全局进度,避免各集内部进度互相覆盖。
             pct = min(95, 10 + int(85 * completed_count / max(total_to_process, 1)))
             report_storyboard_note(
                 f"已完成 {completed_count}/{total_to_process} 集分镜:第 {res['episode_number']} 集",
                 pct,
-                {"asset_complete": True},
+                {
+                    "assets_preview": {
+                        "session_id": sid,
+                        "episodes": temp_eps,
+                        "created_at": datetime.now().isoformat(),
+                    },
+                    "persist": True,
+                },
             )
 
         final_all_episodes = sorted(updated_ep_map.values(), key=lambda x: x["episode_number"])
         
-        # 核心:将结果持久化到 artifacts.storyboard
-        session_data.setdefault("artifacts", {})["storyboard"] = {
-            "session_id": sid, 
-            "episodes": final_all_episodes, 
-            "created_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)
-            
         self._report_progress("分镜", "完成", 100)
         return {"payload": {"session_id": sid, "episodes": final_all_episodes}, "stage_completed": True}
diff --git a/video-claw/video-claw/backend/core/agents/video_agent.py b/video-claw/video-claw/backend/core/agents/video_agent.py
index d3589ae..2de1c12 100644
--- a/video-claw/video-claw/backend/core/agents/video_agent.py
+++ b/video-claw/video-claw/backend/core/agents/video_agent.py
@@ -1,16 +1,15 @@
 # -*- coding: utf-8 -*-
 """
-阶段5: 视频生成智能体 (适配 Session JSON 格式)
-- 从 session.json 的 artifacts["storyboard"] 读取拍摄片段(Segments)
+阶段5: 视频生成智能体
+- 从编排器注入的 artifacts["storyboard"] 读取拍摄片段(Segments)
 - 视频提示词:风格前缀 + 分镜列表(分镜1: [时长] content...)
-- 参考图:从 session.json 的 artifacts["reference_generation"] 读取
+- 参考图:从 artifacts["reference_generation"] 读取
 - 支持逐项并发生成、实时预览、重新生成
 """
 
 import os
 import re
 import glob
-import json
 import asyncio
 import logging
 from typing import Any, Optional, Dict, List
@@ -210,25 +209,8 @@
         }
 
     def _update_session_video_data(self, sid: str, segments: list, style_prompt: 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:
-            with open(session_path, 'r', encoding='utf-8') as f:
-                data = json.load(f)
-            
-            payload = self._build_payload(sid, segments, style_prompt)
-            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.error(f"Failed to update session video data: {e}")
+        """保留兼容入口;session 状态统一由 WorkflowEngine 持久化。"""
+        return
 
     # ─── 核心流程 ───
 
@@ -242,28 +224,19 @@
         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", {})
+            artifacts = self._session_artifacts(input_data)
             episodes = artifacts.get('storyboard', {}).get('episodes', [])
             segments = []
             for ep in episodes:
                 segments.extend(ep.get("segments", []))
-            return self._build_payload(sid, segments)
+            payload = self._build_payload(sid, segments)
+            for clip in payload.get("payload", {}).get("clips", []):
+                clip_id = clip.get("id")
+                if clip_id in selected_clips:
+                    clip["selected"] = selected_clips[clip_id]
+            return payload
 
         video_model = self._require_input(input_data, "video_model")
         enable_concurrency = input_data.get("enable_concurrency", True)
@@ -273,13 +246,9 @@
         video_ratio = input_data.get("video_ratio", "16:9")
         video_resolution = input_data.get("video_resolution", "720P")
         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", {})
+
+        artifacts = self._session_artifacts(input_data)
+        session_meta = self._session_meta(input_data)
         
         # 1. 获取拍摄片段列表 (从 Storyboard)
         episodes = artifacts.get('storyboard', {}).get('episodes', [])
@@ -296,7 +265,7 @@
         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_zh = input_data.get('style') or session_meta.get('style') or 'realistic'
         # 简单映射为中文显示名
         style_map_zh = {
             "anime": "动漫",
diff --git a/video-claw/video-claw/backend/core/orchestrator.py b/video-claw/video-claw/backend/core/orchestrator.py
index 7d8237a..2ff96ea 100644
--- a/video-claw/video-claw/backend/core/orchestrator.py
+++ b/video-claw/video-claw/backend/core/orchestrator.py
@@ -10,9 +10,10 @@
 import threading
 import time
 import copy
+import asyncio
 from datetime import datetime
 from enum import Enum
-from typing import Any, Callable, Dict, List, Optional
+from typing import Any, Callable, Dict, List, Optional, Set
 
 from core.agents import (
     ScriptWriterAgent,
@@ -117,11 +118,11 @@
         return {
             "session_id": self.session_id,
             "current_stage": self.current_stage.value,
-            "status": self.status,
+            "status": copy.deepcopy(self.status),
             "error": self.error,
-            "artifacts": self.artifacts,
-            "meta": self.meta,
-            "stage_progress": self.stage_progress,
+            "artifacts": copy.deepcopy(self.artifacts),
+            "meta": copy.deepcopy(self.meta),
+            "stage_progress": copy.deepcopy(self.stage_progress),
             "updated_at": self.updated_at,
         }
 
@@ -130,16 +131,19 @@
     """工作流引擎 - 管理六阶段状态机"""
 
     def __init__(self):
-        self.agents = {
-            WorkflowStage.SCRIPT_GENERATION: ScriptWriterAgent(),
-            WorkflowStage.CHARACTER_DESIGN: CharacterDesignerAgent(),
-            WorkflowStage.STORYBOARD: StoryboardAgent(),
-            WorkflowStage.REFERENCE_GENERATION: ReferenceGeneratorAgent(),
-            WorkflowStage.VIDEO_GENERATION: VideoDirectorAgent(),
-            WorkflowStage.POST_PRODUCTION: VideoEditorAgent(),
+        self.agent_factories = {
+            WorkflowStage.SCRIPT_GENERATION: ScriptWriterAgent,
+            WorkflowStage.CHARACTER_DESIGN: CharacterDesignerAgent,
+            WorkflowStage.STORYBOARD: StoryboardAgent,
+            WorkflowStage.REFERENCE_GENERATION: ReferenceGeneratorAgent,
+            WorkflowStage.VIDEO_GENERATION: VideoDirectorAgent,
+            WorkflowStage.POST_PRODUCTION: VideoEditorAgent,
         }
         self.sessions: Dict[str, WorkflowState] = {}
         self._stop_events: Dict[str, threading.Event] = {}
+        self._active_sessions: Set[str] = set()
+        self._background_tasks: Set[Any] = set()
+        self._state_lock = threading.RLock()
         self._session_dir = os.path.join(
             os.path.dirname(os.path.abspath(__file__)), '..', 'code', 'data', 'sessions'
         )
@@ -147,86 +151,108 @@
         self._load_sessions_from_disk()
 
     def get_or_create_state(self, session_id: str) -> WorkflowState:
-        if session_id not in self.sessions:
-            loaded_state = self.get_state(session_id)
-            if loaded_state is None:
-                self.sessions[session_id] = WorkflowState(session_id=session_id)
-        if session_id not in self._stop_events:
-            self._stop_events[session_id] = threading.Event()
-        return self.sessions[session_id]
-
-    def get_state(self, session_id: str) -> Optional[WorkflowState]:
-        # 先从内存中获取
-        if session_id in self.sessions:
+        with self._state_lock:
+            if session_id not in self.sessions:
+                loaded_state = self.get_state(session_id)
+                if loaded_state is None:
+                    self.sessions[session_id] = WorkflowState(session_id=session_id)
+            if session_id not in self._stop_events:
+                self._stop_events[session_id] = threading.Event()
             return self.sessions[session_id]
 
-        # 内存中没有,从磁盘加载
-        path = os.path.join(self._session_dir, f"{session_id}.json")
-        if os.path.exists(path):
-            try:
-                with open(path, 'r', encoding='utf-8') as f:
-                    data = json.load(f)
+    def get_state(self, session_id: str) -> Optional[WorkflowState]:
+        with self._state_lock:
+            # 先从内存中获取
+            if session_id in self.sessions:
+                return self.sessions[session_id]
 
-                # 从磁盘数据恢复 WorkflowState
-                state = WorkflowState(session_id=session_id)
-                
-                stage_str = data.get('current_stage')
-                state.current_stage = WorkflowStage(stage_str) if stage_str else WorkflowStage.INIT
-                
-                loaded_status = data.get('status')
-                if isinstance(loaded_status, str):
-                    stages_completed = data.get('stages_completed', [])
-                    for stage in WorkflowStage:
-                        if stage != WorkflowStage.INIT and stage != WorkflowStage.COMPLETED:
-                            if stage.value in stages_completed:
-                                state.status[stage.value] = "completed"
-                            elif stage.value == state.current_stage.value:
-                                state.status[stage.value] = loaded_status
-                            else:
-                                state.status[stage.value] = "pending"
-                elif isinstance(loaded_status, dict):
-                    state.status = loaded_status
+            # 内存中没有,从磁盘加载
+            path = os.path.join(self._session_dir, f"{session_id}.json")
+            if os.path.exists(path):
+                try:
+                    with open(path, 'r', encoding='utf-8') as f:
+                        data = json.load(f)
 
-                state.artifacts = data.get('artifacts', {})
-                state.stage_progress = data.get('stage_progress', {})
-                state.meta = _extract_session_meta(data)
-                state.updated_at = data.get('updated_at', 0)
+                    # 从磁盘数据恢复 WorkflowState
+                    state = WorkflowState(session_id=session_id)
+                    
+                    stage_str = data.get('current_stage')
+                    state.current_stage = WorkflowStage(stage_str) if stage_str else WorkflowStage.INIT
+                    
+                    loaded_status = data.get('status')
+                    if isinstance(loaded_status, str):
+                        stages_completed = data.get('stages_completed', [])
+                        for stage in WorkflowStage:
+                            if stage != WorkflowStage.INIT and stage != WorkflowStage.COMPLETED:
+                                if stage.value in stages_completed:
+                                    state.status[stage.value] = "completed"
+                                elif stage.value == state.current_stage.value:
+                                    state.status[stage.value] = loaded_status
+                                else:
+                                    state.status[stage.value] = "pending"
+                    elif isinstance(loaded_status, dict):
+                        state.status = loaded_status
 
-                # 缓存到内存
-                self.sessions[session_id] = state
-                return state
-            except json.JSONDecodeError as e:
-                logger.warning(f"Session file {session_id} is corrupted, ignoring: {e}")
-            except Exception as e:
-                logger.warning(f"Failed to load session {session_id} from disk: {e}")
+                    state.artifacts = data.get('artifacts', {})
+                    state.stage_progress = data.get('stage_progress', {})
+                    state.meta = _extract_session_meta(data)
+                    state.updated_at = data.get('updated_at', 0)
+
+                    # 缓存到内存
+                    self.sessions[session_id] = state
+                    return state
+                except json.JSONDecodeError as e:
+                    logger.warning(f"Session file {session_id} is corrupted, ignoring: {e}")
+                except Exception as e:
+                    logger.warning(f"Failed to load session {session_id} from disk: {e}")
 
         return None
 
     def get_stop_event(self, session_id: str) -> threading.Event:
-        if session_id not in self._stop_events:
-            self._stop_events[session_id] = threading.Event()
-        return self._stop_events[session_id]
+        with self._state_lock:
+            if session_id not in self._stop_events:
+                self._stop_events[session_id] = threading.Event()
+            return self._stop_events[session_id]
 
     def stop_session(self, session_id: str):
         self.get_stop_event(session_id).set()
-        state = self.get_state(session_id)
-        if state and state.status.get(state.current_stage.value) == "running":
-            state.status[state.current_stage.value] = "stopped"
-            state.error = None  # 清除错误,因为是主动停止
-            state.updated_at = datetime.now()
-            current_progress = state.stage_progress.get(state.current_stage.value, {})
-            state.stage_progress[state.current_stage.value] = {
-                **current_progress,
-                "step": "已停止",
-                "message": "已停止",
-                "updated_at": time.time(),
-            }
-            self.save_session_to_disk(session_id)
+        with self._state_lock:
+            state = self.get_state(session_id)
+            if state and state.status.get(state.current_stage.value) == "running":
+                state.status[state.current_stage.value] = "stopped"
+                state.error = None  # 清除错误,因为是主动停止
+                state.updated_at = datetime.now()
+                current_progress = state.stage_progress.get(state.current_stage.value, {})
+                state.stage_progress[state.current_stage.value] = {
+                    **current_progress,
+                    "step": "已停止",
+                    "message": "已停止",
+                    "updated_at": time.time(),
+                }
+                self.save_session_to_disk(session_id)
         logger.info(f"Session {session_id} stop signal sent")
 
     def reset_stop_event(self, session_id: str):
-        if session_id in self._stop_events:
-            self._stop_events[session_id].clear()
+        with self._state_lock:
+            if session_id in self._stop_events:
+                self._stop_events[session_id].clear()
+
+    def track_background_task(self, task: Any):
+        """Keep detached workflow tasks alive after an SSE client disconnects."""
+        with self._state_lock:
+            self._background_tasks.add(task)
+
+        def _cleanup(done_task: Any):
+            with self._state_lock:
+                self._background_tasks.discard(done_task)
+            try:
+                done_task.exception()
+            except asyncio.CancelledError:
+                pass
+            except Exception:
+                logger.exception("Detached workflow task failed")
+
+        task.add_done_callback(_cleanup)
 
     def _get_next_stage(self, current: WorkflowStage) -> Optional[WorkflowStage]:
         try:
@@ -403,6 +429,39 @@
             video_art["clips"] = existing_clips
             state.artifacts[video_stage_key] = video_art
 
+        # 案例 3: 角色/场景描述修改同步回剧本元数据,保证后续阶段读到用户最新描述。
+        if stage == WorkflowStage.CHARACTER_DESIGN:
+            script_art = state.artifacts.get(WorkflowStage.SCRIPT_GENERATION.value)
+            if not isinstance(script_art, dict):
+                return
+
+            char_by_id = {
+                c.get("id"): c for c in payload.get("characters", [])
+                if isinstance(c, dict) and c.get("id")
+            }
+            setting_by_id = {
+                s.get("id"): s for s in payload.get("settings", [])
+                if isinstance(s, dict) and s.get("id")
+            }
+
+            for char in script_art.get("characters", []):
+                if not isinstance(char, dict):
+                    continue
+                source = char_by_id.get(char.get("character_id") or char.get("id"))
+                if source:
+                    for key in ("name", "description", "species"):
+                        if source.get(key):
+                            char[key] = source[key]
+
+            for setting in script_art.get("settings", []):
+                if not isinstance(setting, dict):
+                    continue
+                source = setting_by_id.get(setting.get("setting_id") or setting.get("id"))
+                if source:
+                    for key in ("name", "description"):
+                        if source.get(key):
+                            setting[key] = source[key]
+
     def _recalculate_all_statuses(self, state: WorkflowState):
         """
         根据各阶段 artifacts 的数据完整性重新计算 status 字典。
@@ -463,7 +522,17 @@
                             intervention: Optional[Dict] = None) -> Dict:
         import time
 
-        agent = self.agents[stage]
+        if not isinstance(input_data, dict):
+            input_data = {}
+        else:
+            input_data = copy.deepcopy(input_data)
+
+        with self._state_lock:
+            input_data["_session_meta"] = copy.deepcopy(state.meta)
+            input_data["_session_artifacts"] = copy.deepcopy(state.artifacts)
+
+        agent = self.agent_factories[stage]()
+        active_registered = False
 
         # 合并会话级停止信号与请求级取消检查
         session_stop = self.get_stop_event(state.session_id)
@@ -472,10 +541,7 @@
 
         agent.set_cancellation_check(combined_cancel_check)
 
-        # 包装 progress_callback,定期保存状态到 sessions json
-        last_save_time = {"time": 0}
-        SAVE_INTERVAL = 2  # 进度快照最多每2秒落盘一次,刷新页面后可恢复进度条
-
+        # 包装 progress_callback:运行中进度只写入全局内存实例,避免并发阶段频繁抢写 session JSON。
         def persist_stage_progress(phase: str, step: str, percent: float):
             stage_key = stage.value
             try:
@@ -531,41 +597,49 @@
             })
 
         def wrapped_progress_callback(phase: str, step: str, percent: float, data: dict = None):
-            persist_stage_progress(phase, step, percent)
-
-            if data:
-                merge_progress_artifact(data)
+            with self._state_lock:
+                persist_stage_progress(phase, step, percent)
+                if data:
+                    merge_progress_artifact(data)
 
             # 调用原始 callback
             if progress_callback:
                 progress_callback(phase, step, percent, data)
 
-            # 如果有 asset_complete 数据,说明有新生成的图片/视频,立即保存到磁盘
-            if data and data.get("asset_complete"):
-                self.save_session_to_disk(state.session_id)
-                last_save_time["time"] = time.time()
-                return
-
-            # 如果有 progress 回调(纯文字阶段),也定期保存
-            current_time = time.time()
-            if current_time - last_save_time["time"] >= SAVE_INTERVAL:
-                last_save_time["time"] = current_time
+            should_persist = False
+            if isinstance(data, dict):
+                asset_update = data.get("asset_complete")
+                should_persist = bool(data.get("persist")) or (
+                    isinstance(asset_update, dict)
+                    and asset_update.get("status") in {"done", "failed"}
+                )
+            if should_persist:
                 self.save_session_to_disk(state.session_id)
 
         if progress_callback:
             agent.set_progress_callback(wrapped_progress_callback)
 
-        state.current_stage = stage
-        state.status[stage.value] = "running"
-        state.updated_at = datetime.now()
-        state.stage_progress[stage.value] = {
-            "phase": stage.value,
-            "step": "启动中...",
-            "message": "启动中...",
-            "percent": 0,
-            "updated_at": time.time(),
-        }
-        self.save_session_to_disk(state.session_id)
+        with self._state_lock:
+            if state.session_id in self._active_sessions:
+                raise RuntimeError(f"Session {state.session_id} is already running a stage.")
+            self._active_sessions.add(state.session_id)
+            active_registered = True
+            state.current_stage = stage
+            state.status[stage.value] = "running"
+            state.updated_at = datetime.now()
+            state.stage_progress[stage.value] = {
+                "phase": stage.value,
+                "step": "启动中...",
+                "message": "启动中...",
+                "percent": 0,
+                "updated_at": time.time(),
+            }
+            try:
+                self.save_session_to_disk(state.session_id)
+            except Exception:
+                self._active_sessions.discard(state.session_id)
+                active_registered = False
+                raise
 
         try:
             result = await agent.process(input_data, intervention=intervention)
@@ -576,126 +650,159 @@
             payload = result.get("payload", {})
             requires_intervention = result.get("requires_intervention", False)
 
-            # 根据阶段类型处理数据持久化和同步逻辑
-            if stage == WorkflowStage.SCRIPT_GENERATION:
-                if requires_intervention:
-                    # 【续写预览状态】直接保存 payload 以保留 new_episodes 供前端显示。
-                    # 此时千万不要跨阶段同步(避免向第二、三阶段注入用户未确认的数据)。
-                    state.artifacts[stage.value] = copy.deepcopy(payload)
+            with self._state_lock:
+                # 根据阶段类型处理数据持久化和同步逻辑
+                if stage == WorkflowStage.SCRIPT_GENERATION:
+                    if requires_intervention:
+                        # 【续写预览状态】直接保存 payload 以保留 new_episodes 供前端显示。
+                        # 此时千万不要跨阶段同步(避免向第二、三阶段注入用户未确认的数据)。
+                        state.artifacts[stage.value] = copy.deepcopy(payload)
+                    else:
+                        # 【确定续写 / 正常生成状态】
+                        # 先同步增量数据到第二、三阶段
+                        self._sync_artifacts_cross_stages(state, stage, payload)
+                        # 然后清理第一阶段内部的临时增量字段并保存
+                        clean_art = copy.deepcopy(payload)
+                        for key in ["new_episodes", "new_characters", "new_settings", "sequel_idea"]:
+                            clean_art.pop(key, None)
+                        state.artifacts[stage.value] = clean_art
                 else:
-                    # 【确定续写 / 正常生成状态】
-                    # 先同步增量数据到第二、三阶段
+                    # 其他阶段正常执行跨阶段同步和赋值
                     self._sync_artifacts_cross_stages(state, stage, payload)
-                    # 然后清理第一阶段内部的临时增量字段并保存
-                    clean_art = copy.deepcopy(payload)
-                    for key in ["new_episodes", "new_characters", "new_settings", "sequel_idea"]:
-                        clean_art.pop(key, None)
-                    state.artifacts[stage.value] = clean_art
-            else:
-                # 其他阶段正常执行跨阶段同步和赋值
-                self._sync_artifacts_cross_stages(state, stage, payload)
-                state.artifacts[stage.value] = payload
+                    state.artifacts[stage.value] = payload
 
-            # 调试日志
-            logger.info(f"[execute_stage] stage={stage.value}, intervention={intervention is not None}, requires_intervention={result.get('requires_intervention')}, stage_completed={result.get('stage_completed')}")
+                # 调试日志
+                logger.info(f"[execute_stage] stage={stage.value}, intervention={intervention is not None}, requires_intervention={result.get('requires_intervention')}, stage_completed={result.get('stage_completed')}")
 
-            # 重新计算所有阶段的状态(基于 artifacts 里的数据完整性)
-            self._recalculate_all_statuses(state)
+                # 重新计算所有阶段的状态(基于 artifacts 里的数据完整性)
+                self._recalculate_all_statuses(state)
 
-            # 如果 result 明确标记了完成且不是干预,则可能需要覆盖为 completed (除非 recalculate 认为是 waiting)
-            if result.get("stage_completed") and not result.get("requires_intervention"):
-                # 如果 recalculate 没把它设为 waiting,就设为 completed
-                if state.status.get(stage.value) != "waiting":
-                    state.status[stage.value] = "completed"
-            elif result.get("requires_intervention"):
-                state.status[stage.value] = "waiting"
+                # 如果 result 明确标记了完成且不是干预,则可能需要覆盖为 completed (除非 recalculate 认为是 waiting)
+                if result.get("stage_completed") and not result.get("requires_intervention"):
+                    # 如果 recalculate 没把它设为 waiting,就设为 completed
+                    if state.status.get(stage.value) != "waiting":
+                        state.status[stage.value] = "completed"
+                elif result.get("requires_intervention"):
+                    state.status[stage.value] = "waiting"
 
-            state.updated_at = datetime.now()
-            state.stage_progress[stage.value] = {
-                "phase": stage.value,
-                "step": "等待确认" if state.status.get(stage.value) == "waiting" else "已完成",
-                "message": "等待确认" if state.status.get(stage.value) == "waiting" else "已完成",
-                "percent": 100,
-                "updated_at": time.time(),
-            }
-            # 立即保存状态到磁盘,确保前端能获取到最新状态
-            self.save_session_to_disk(state.session_id)
+                state.updated_at = datetime.now()
+                state.stage_progress[stage.value] = {
+                    "phase": stage.value,
+                    "step": "等待确认" if state.status.get(stage.value) == "waiting" else "已完成",
+                    "message": "等待确认" if state.status.get(stage.value) == "waiting" else "已完成",
+                    "percent": 100,
+                    "updated_at": time.time(),
+                }
+                # 立即保存状态到磁盘,确保前端能获取到最新状态
+                self.save_session_to_disk(state.session_id)
             return result
 
-        except Exception as e:
-            state.status[stage.value] = "error"
-            state.error = str(e)
-            state.updated_at = datetime.now()
-            state.stage_progress[stage.value] = {
-                "phase": stage.value,
-                "step": "执行失败",
-                "message": "执行失败",
-                "percent": state.stage_progress.get(stage.value, {}).get("percent", 0),
-                "updated_at": time.time(),
-            }
-            # 确保保存错误状态
-            self.save_session_to_disk(state.session_id)
+        except asyncio.CancelledError:
+            with self._state_lock:
+                state.status[stage.value] = "stopped"
+                state.error = None
+                state.updated_at = datetime.now()
+                state.stage_progress[stage.value] = {
+                    "phase": stage.value,
+                    "step": "已取消",
+                    "message": "已取消",
+                    "percent": state.stage_progress.get(stage.value, {}).get("percent", 0),
+                    "updated_at": time.time(),
+                }
+                self.save_session_to_disk(state.session_id)
             raise
+
+        except Exception as e:
+            with self._state_lock:
+                state.status[stage.value] = "error"
+                state.error = str(e)
+                state.updated_at = datetime.now()
+                state.stage_progress[stage.value] = {
+                    "phase": stage.value,
+                    "step": "执行失败",
+                    "message": "执行失败",
+                    "percent": state.stage_progress.get(stage.value, {}).get("percent", 0),
+                    "updated_at": time.time(),
+                }
+                # 确保保存错误状态
+                self.save_session_to_disk(state.session_id)
+            raise
+        finally:
+            if active_registered:
+                with self._state_lock:
+                    self._active_sessions.discard(state.session_id)
 
     async def handle_intervention(self,
                                   session_id: str,
                                   stage: str,
                                   modifications: Dict[str, Any]) -> Dict:
-        state = self.sessions[session_id]
+        with self._state_lock:
+            state = self.get_state(session_id)
+            if not state:
+                raise KeyError(f"Session not found: {session_id}")
+            current_artifact = copy.deepcopy(state.artifacts.get(stage, {}))
         stage_enum = WorkflowStage(stage)
-        current_artifact = state.artifacts.get(stage, {})
 
         input_data = current_artifact if isinstance(current_artifact, dict) else {}
         input_data.update(modifications)
 
         res = await self.execute_stage(state, stage_enum, input_data, intervention=modifications)
-        # 处理完干预后再次校验状态
-        self._recalculate_all_statuses(state)
-        self.save_session_to_disk(session_id)
+        with self._state_lock:
+            # 处理完干预后再次校验状态
+            self._recalculate_all_statuses(state)
+            self.save_session_to_disk(session_id)
         return res
 
     async def continue_workflow(self, session_id: str) -> Dict:
-        state = self.sessions[session_id]
-        logger.info(f"[continue_workflow] session={session_id}, current_stage={state.current_stage}, status={state.status}")
+        with self._state_lock:
+            state = self.get_state(session_id)
+            if not state:
+                return {
+                    "status": "error",
+                    "openclaw": "会话不存在,请刷新后重试。",
+                    "message": "会话不存在",
+                    "current_status": "missing",
+                }
+            logger.info(f"[continue_workflow] session={session_id}, current_stage={state.current_stage}, status={state.status}")
 
-        # 检查当前状态是否已完成
-        current_stage_str = state.current_stage.value if hasattr(state.current_stage, "value") else str(state.current_stage)
+            # 检查当前状态是否已完成
+            current_stage_str = state.current_stage.value if hasattr(state.current_stage, "value") else str(state.current_stage)
 
-        # 在继续之前,先重新扫描一次状态,确保最新的选择已被计入
-        self._recalculate_all_statuses(state)
+            # 在继续之前,先重新扫描一次状态,确保最新的选择已被计入
+            self._recalculate_all_statuses(state)
 
-        # 如果当前状态是 running,说明阶段还在执行中,不能继续
-        if state.status.get(current_stage_str) == "running":
-            return {
-                "status": "waiting",
-                "openclaw": f"当前阶段({current_stage_str})还在执行中,请等待完成后再调用 /continue。",
-                "message": f"当前阶段({current_stage_str})还在执行中,请等待完成后再调用 /continue。",
-                "current_status": "running",
-            }
+            # 如果当前状态是 running,说明阶段还在执行中,不能继续
+            if state.status.get(current_stage_str) == "running":
+                return {
+                    "status": "waiting",
+                    "openclaw": f"当前阶段({current_stage_str})还在执行中,请等待完成后再调用 /continue。",
+                    "message": f"当前阶段({current_stage_str})还在执行中,请等待完成后再调用 /continue。",
+                    "current_status": "running",
+                }
 
-        # 状态转换逻辑:
-        # - waiting 或 completed: 用户确认后直接进入下一阶段
-        # 如果是 waiting,可能需要阻止进入下一阶段,除非业务允许强制通过
-        # 这里我们遵循用户逻辑:如果有空数据,显示为 waiting,用户需要解决它才能真正 completed。
-        if state.status.get(current_stage_str) == "waiting":
-            # 如果是 waiting 状态,通常不应该自动跳到下一阶段
-            # 但如果用户点击了“继续”,可能是想补全或者强制进入
-            pass
-        # 注意:只有当阶段真正完成(waiting 或 completed)时才允许继续
+            # 状态转换逻辑:
+            # - waiting 或 completed: 用户确认后直接进入下一阶段
+            # 如果是 waiting,可能需要阻止进入下一阶段,除非业务允许强制通过
+            # 这里我们遵循用户逻辑:如果有空数据,显示为 waiting,用户需要解决它才能真正 completed。
+            if state.status.get(current_stage_str) == "waiting":
+                # 如果是 waiting 状态,通常不应该自动跳到下一阶段
+                # 但如果用户点击了“继续”,可能是想补全或者强制进入
+                pass
+            # 注意:只有当阶段真正完成(waiting 或 completed)时才允许继续
 
-        current_status = state.status.get(current_stage_str)
-        if current_status == "waiting" or current_status == "completed":
-            # 直接进入下一阶段
-            state.status[current_stage_str] = "completed"
-            next_stage = self._get_next_stage(state.current_stage)
-
-            if not next_stage:
+            current_status = state.status.get(current_stage_str)
+            if current_status == "waiting" or current_status == "completed":
+                # 直接进入下一阶段
                 state.status[current_stage_str] = "completed"
-                self.save_session_to_disk(state.session_id)
-                return {"status": "completed", "session_id": state.session_id, "status_map": state.status}
+                next_stage = self._get_next_stage(state.current_stage)
 
-            self.save_session_to_disk(state.session_id)
-            return {"status": "ready", "next_stage": next_stage.value, "session_id": state.session_id, "status_map": state.status}
+                if not next_stage:
+                    state.status[current_stage_str] = "completed"
+                    self.save_session_to_disk(state.session_id)
+                    return {"status": "completed", "session_id": state.session_id, "status_map": copy.deepcopy(state.status)}
+
+                self.save_session_to_disk(state.session_id)
+                return {"status": "ready", "next_stage": next_stage.value, "session_id": state.session_id, "status_map": copy.deepcopy(state.status)}
 
         # 其他状态(如 pending, stopped, error, completed)不允许继续
         return {
@@ -712,61 +819,62 @@
         import tempfile
         import shutil
 
-        path = os.path.join(self._session_dir, f"{session_id}.json")
-        data: Dict[str, Any] = {}
-        state = self.sessions.get(session_id)
-        
-        # 1. 准备基础数据
-        if os.path.exists(path):
-            try:
-                with open(path, 'r', encoding='utf-8') as f:
-                    data = json.load(f)
-            except (json.JSONDecodeError, Exception):
-                pass
-
-        data["session_id"] = session_id
-        if meta:
-            normalized_meta = {k: _normalize_meta_value(v) for k, v in meta.items() if v is not None}
-            if state:
-                state.meta.update(normalized_meta)
-        if "created_at" not in data:
-            data["created_at"] = time.time()
-
-        # 会话级生成参数统一保存在 meta 中;清理旧版本遗留的根字段。
-        for key in SESSION_META_KEYS:
-            data.pop(key, None)
-        
-        # 2. 将内存中的最新 state 合并到 data 中
-        if state:
-            data["current_stage"] = state.current_stage.value
-            data["status"] = state.status
-            # 这里的 state.artifacts 应该是已经经过 _sync_artifacts_cross_stages 处理的最新的内存对象
-            data["artifacts"] = state.artifacts
-            data["stage_progress"] = state.stage_progress
-            data["error"] = state.error
-            data["updated_at"] = state.updated_at.timestamp() if isinstance(state.updated_at, datetime) else time.time()
+        with self._state_lock:
+            path = os.path.join(self._session_dir, f"{session_id}.json")
+            data: Dict[str, Any] = {}
+            state = self.sessions.get(session_id)
             
-            # 保存元数据:meta 是唯一的会话级生成参数存储位置。
-            if state.meta:
-                data["meta"] = copy.deepcopy(state.meta)
-            else:
-                data.pop("meta", None)
-        else:
-            data["updated_at"] = time.time()
+            # 1. 准备基础数据
+            if os.path.exists(path):
+                try:
+                    with open(path, 'r', encoding='utf-8') as f:
+                        data = json.load(f)
+                except (json.JSONDecodeError, Exception):
+                    pass
 
-        # 3. 原子写入:先写临时文件,再重命名
-        dir_path = os.path.dirname(path)
-        fd, tmp_path = tempfile.mkstemp(dir=dir_path, suffix='.json')
-        try:
-            with os.fdopen(fd, 'w', encoding='utf-8') as f:
-                json.dump(data, f, ensure_ascii=False, indent=2)
-            shutil.move(tmp_path, path)
-            logger.info(f"[Orchestrator] Session {session_id} saved successfully.")
-        except Exception as e:
-            if os.path.exists(tmp_path):
-                os.remove(tmp_path)
-            logger.error(f"[Orchestrator] Failed to save session {session_id}: {e}")
-            raise
+            data["session_id"] = session_id
+            if meta:
+                normalized_meta = {k: _normalize_meta_value(v) for k, v in meta.items() if v is not None}
+                if state:
+                    state.meta.update(normalized_meta)
+            if "created_at" not in data:
+                data["created_at"] = time.time()
+
+            # 会话级生成参数统一保存在 meta 中;清理旧版本遗留的根字段。
+            for key in SESSION_META_KEYS:
+                data.pop(key, None)
+            
+            # 2. 将内存中的最新 state 合并到 data 中
+            if state:
+                data["current_stage"] = state.current_stage.value
+                data["status"] = state.status
+                # 这里的 state.artifacts 应该是已经经过 _sync_artifacts_cross_stages 处理的最新的内存对象
+                data["artifacts"] = state.artifacts
+                data["stage_progress"] = state.stage_progress
+                data["error"] = state.error
+                data["updated_at"] = state.updated_at.timestamp() if isinstance(state.updated_at, datetime) else time.time()
+                
+                # 保存元数据:meta 是唯一的会话级生成参数存储位置。
+                if state.meta:
+                    data["meta"] = copy.deepcopy(state.meta)
+                else:
+                    data.pop("meta", None)
+            else:
+                data["updated_at"] = time.time()
+
+            # 3. 原子写入:先写临时文件,再重命名
+            dir_path = os.path.dirname(path)
+            fd, tmp_path = tempfile.mkstemp(dir=dir_path, suffix='.json')
+            try:
+                with os.fdopen(fd, 'w', encoding='utf-8') as f:
+                    json.dump(data, f, ensure_ascii=False, indent=2)
+                shutil.move(tmp_path, path)
+                logger.info(f"[Orchestrator] Session {session_id} saved successfully.")
+            except Exception as e:
+                if os.path.exists(tmp_path):
+                    os.remove(tmp_path)
+                logger.error(f"[Orchestrator] Failed to save session {session_id}: {e}")
+                raise
 
     def _load_sessions_from_disk(self):
         """启动时从磁盘加载所有已保存的会话"""
@@ -820,68 +928,80 @@
     def delete_session(self, session_id: str) -> bool:
         """删除指定会话(内存 + 磁盘 + 结果文件)"""
         from config import settings
+        import shutil
 
-        # 从内存中移除
-        self.sessions.pop(session_id, None)
-        self._stop_events.pop(session_id, None)
+        with self._state_lock:
+            if session_id in self._active_sessions:
+                self.get_stop_event(session_id).set()
+                logger.warning(f"Refusing to delete active session: {session_id}")
+                return False
 
-        # 1. 删除会话元数据文件
-        path = os.path.join(self._session_dir, f"{session_id}.json")
-        if os.path.exists(path):
-            os.remove(path)
+            path = os.path.join(self._session_dir, f"{session_id}.json")
+            exists = session_id in self.sessions or os.path.exists(path)
+            if not exists:
+                return False
 
-        # 2. 删除结果文件(剧本、图片、视频)
-        result_base = settings.RESULT_DIR
+            # 从内存中移除
+            self.sessions.pop(session_id, None)
+            self._stop_events.pop(session_id, None)
 
-        # 删除剧本文件
-        script_file = os.path.join(result_base, 'script', f'{session_id}.json')
-        if os.path.exists(script_file):
-            os.remove(script_file)
+            # 1. 删除会话元数据文件
+            if os.path.exists(path):
+                os.remove(path)
 
-        # 删除图片目录
-        image_dir = os.path.join(result_base, 'image', session_id)
-        if os.path.exists(image_dir):
-            import shutil
-            shutil.rmtree(image_dir)
+            # 2. 删除结果文件(剧本、图片、视频)
+            result_base = settings.RESULT_DIR
 
-        # 删除视频目录
-        video_dir = os.path.join(result_base, 'video', session_id)
-        if os.path.exists(video_dir):
-            import shutil
-            shutil.rmtree(video_dir)
+            # 删除剧本文件
+            script_file = os.path.join(result_base, 'script', f'{session_id}.json')
+            if os.path.exists(script_file):
+                os.remove(script_file)
+
+            # 删除图片目录
+            image_dir = os.path.join(result_base, 'image', session_id)
+            if os.path.exists(image_dir):
+                shutil.rmtree(image_dir)
+
+            # 删除视频目录
+            video_dir = os.path.join(result_base, 'video', session_id)
+            if os.path.exists(video_dir):
+                shutil.rmtree(video_dir)
 
         logger.info(f"Session and results deleted: {session_id}")
         return True
 
     def list_saved_sessions(self) -> List[Dict]:
         """列出所有已保存的会话概要"""
-        sessions: List[Dict] = []
-        if not os.path.exists(self._session_dir):
+        with self._state_lock:
+            sessions: List[Dict] = []
+            for sid, state in self.sessions.items():
+                try:
+                    meta = copy.deepcopy(state.meta)
+                    artifacts = copy.deepcopy(state.artifacts)
+                    script_artifact = artifacts.get("script_generation", {})
+                    title = (
+                        script_artifact.get("title")
+                        or meta.get("idea")
+                        or meta.get("user_textbox_input")
+                        or ""
+                    )
+                    updated_at = state.updated_at
+                    if isinstance(updated_at, datetime):
+                        date_value = updated_at.timestamp()
+                    else:
+                        date_value = updated_at or 0
+                    sessions.append({
+                        "id": sid,
+                        "title": title,
+                        "idea": meta.get("idea") or meta.get("user_textbox_input") or "",
+                        "style": meta.get("style") or "",
+                        "date": date_value,
+                        "status": copy.deepcopy(state.status),
+                        "current_stage": state.current_stage.value,
+                        "meta": meta,
+                        "stage_progress": copy.deepcopy(state.stage_progress),
+                    })
+                except Exception:
+                    continue
+            sessions.sort(key=lambda x: x.get("date", 0), reverse=True)
             return sessions
-        for filename in os.listdir(self._session_dir):
-            if not filename.endswith('.json'):
-                continue
-            try:
-                fpath = os.path.join(self._session_dir, filename)
-                with open(fpath, 'r', encoding='utf-8') as f:
-                    data = json.load(f)
-                meta = _extract_session_meta(data)
-                script_artifact = data.get("artifacts", {}).get("script_generation", {})
-                title = (
-                    script_artifact.get("title")
-                    or meta.get("idea")
-                    or meta.get("user_textbox_input")
-                    or data.get("idea", "")
-                )
-                sessions.append({
-                    "id": data["session_id"],
-                    "title": title,
-                    "idea": meta.get("idea") or meta.get("user_textbox_input") or data.get("idea", ""),
-                    "style": meta.get("style") or data.get("style", ""),
-                    "date": data.get("updated_at", 0),
-                    "status": data.get("status", {}),
-                })
-            except Exception:
-                continue
-        sessions.sort(key=lambda x: x.get("date", 0), reverse=True)
-        return sessions
diff --git a/video-claw/video-claw/backend/models/llm_deepseek.py b/video-claw/video-claw/backend/models/llm_deepseek.py
index 9916ebd..0508882 100644
--- a/video-claw/video-claw/backend/models/llm_deepseek.py
+++ b/video-claw/video-claw/backend/models/llm_deepseek.py
@@ -13,6 +13,10 @@
 
 logger = logging.getLogger(__name__)
 
+DEFAULT_DEEPSEEK_TIMEOUT = 300
+DEFAULT_DEEPSEEK_MAX_ATTEMPTS = 5
+DEFAULT_DEEPSEEK_MAX_TOKENS = 20000
+
 
 class DeepSeek:
     """
@@ -21,11 +25,12 @@
     deepseek-v4-flash: DeepSeek-V4 Flash
     deepseek-v4-pro: DeepSeek-V4 Pro
     """
-    def __init__(self, base_url="", api_key="", timeout=120):
+    def __init__(self, base_url="", api_key="", timeout=None, max_attempts=None):
         import httpx
         self.base_url = base_url or Config.DEEPSEEK_BASE_URL or "https://api.deepseek.com/v1"
         self.api_key = api_key or Config.DEEPSEEK_API_KEY
-        self.timeout = timeout
+        self.timeout = self._as_int(timeout, DEFAULT_DEEPSEEK_TIMEOUT)
+        self.max_attempts = self._as_int(max_attempts, DEFAULT_DEEPSEEK_MAX_ATTEMPTS)
         
         if not self.api_key:
             logger.warning("DEEPSEEK_API_KEY is not set")
@@ -35,8 +40,79 @@
         if proxy:
             kwargs["http_client"] = httpx.Client(proxy=proxy, timeout=self.timeout)
         self.client = OpenAI(**kwargs)
-        self.max_attempts = 2
-        self.max_tokens = 8000
+        self.max_tokens = DEFAULT_DEEPSEEK_MAX_TOKENS
+
+    @staticmethod
+    def _as_int(value, default: int) -> int:
+        try:
+            return int(value)
+        except (TypeError, ValueError):
+            return default
+
+    @staticmethod
+    def _usage_value(usage, key: str, default=0):
+        if usage is None:
+            return default
+        value = getattr(usage, key, None)
+        if value is None and isinstance(usage, dict):
+            value = usage.get(key)
+        return value if value is not None else default
+
+    @classmethod
+    def _completion_detail_value(cls, usage, key: str, default=0):
+        details = cls._usage_value(usage, "completion_tokens_details", None)
+        if details is None:
+            return default
+        value = getattr(details, key, None)
+        if value is None and isinstance(details, dict):
+            value = details.get(key)
+        return value if value is not None else default
+
+    def _log_empty_response(self, model: str, attempt: int, response):
+        choice = response.choices[0] if response.choices else None
+        message = getattr(choice, "message", None) if choice else None
+        finish_reason = getattr(choice, "finish_reason", None) if choice else None
+        usage = getattr(response, "usage", None)
+        completion_tokens = self._usage_value(usage, "completion_tokens")
+        prompt_tokens = self._usage_value(usage, "prompt_tokens")
+        total_tokens = self._usage_value(usage, "total_tokens")
+        reasoning_tokens = self._completion_detail_value(usage, "reasoning_tokens")
+
+        reasoning_content = getattr(message, "reasoning_content", "") if message else ""
+        reasoning_chars = len(reasoning_content or "")
+        token_budget_exhausted = finish_reason == "length" or completion_tokens >= max(self.max_tokens - 8, 1)
+        reasoning_used_output = reasoning_tokens and completion_tokens and reasoning_tokens >= completion_tokens * 0.9
+
+        if token_budget_exhausted and reasoning_used_output:
+            reason = "output_token_budget_exhausted_by_reasoning"
+            suggestion = "increase max_tokens, reduce prompt/output length, or use a non-reasoning/flash model"
+        elif token_budget_exhausted:
+            reason = "output_token_budget_exhausted"
+            suggestion = "increase max_tokens or reduce requested output length"
+        elif reasoning_content and not getattr(message, "content", None):
+            reason = "reasoning_only_no_final_content"
+            suggestion = "retry may succeed; consider reducing reasoning-heavy model usage for long generation"
+        else:
+            reason = "empty_final_content"
+            suggestion = "retrying"
+
+        logger.warning(
+            "DeepSeek empty final content; retrying. reason=%s suggestion=%s model=%s attempt=%s/%s "
+            "finish_reason=%s max_tokens=%s prompt_tokens=%s completion_tokens=%s reasoning_tokens=%s "
+            "total_tokens=%s reasoning_chars=%s",
+            reason,
+            suggestion,
+            model,
+            attempt,
+            self.max_attempts,
+            finish_reason,
+            self.max_tokens,
+            prompt_tokens,
+            completion_tokens,
+            reasoning_tokens,
+            total_tokens,
+            reasoning_chars,
+        )
 
     def query(self, prompt, image_urls=[], model="deepseek-chat", web_search=False):
         """
@@ -68,22 +144,17 @@
                 if response.choices and response.choices[0].message.content:
                     return response.choices[0].message.content
                 else:
-                    choice = response.choices[0] if response.choices else None
-                    message = getattr(choice, "message", None) if choice else None
-                    try:
-                        message_payload = message.model_dump(exclude_none=True) if message else None
-                    except Exception:
-                        message_payload = str(message) if message else None
-                    logger.warning(
-                        "DeepSeek returned an empty response; retrying. model=%s finish_reason=%s usage=%s message=%s",
-                        model,
-                        getattr(choice, "finish_reason", None) if choice else None,
-                        getattr(response, "usage", None),
-                        message_payload,
-                    )
+                    self._log_empty_response(model, attempts + 1, response)
                     time.sleep(2)
             except Exception as e:
-                logger.warning("DeepSeek request failed; retrying. model=%s timeout=%ss error=%s", model, self.timeout, e)
+                logger.warning(
+                    "DeepSeek request failed; retrying. model=%s attempt=%s/%s timeout=%ss error=%s",
+                    model,
+                    attempts + 1,
+                    self.max_attempts,
+                    self.timeout,
+                    e,
+                )
                 time.sleep(5)
             attempts += 1
                 
diff --git a/video-claw/video-claw/backend/pipelines/storage.py b/video-claw/video-claw/backend/pipelines/storage.py
index 5ed0e8e..70c4263 100644
--- a/video-claw/video-claw/backend/pipelines/storage.py
+++ b/video-claw/video-claw/backend/pipelines/storage.py
@@ -2,6 +2,7 @@
 import logging
 import os
 import shutil
+import threading
 import time
 import uuid
 from datetime import datetime
@@ -11,6 +12,7 @@
 from .events import publish_task_event
 
 logger = logging.getLogger(__name__)
+_task_store_lock = threading.RLock()
 
 TASK_DATA_DIR = os.path.join(settings.CODE_DIR, "data", "tasks")
 TASK_RESULT_DIR = os.path.join(settings.RESULT_DIR, "task")
@@ -38,86 +40,92 @@
 
 
 def save_task(metadata: Dict[str, Any]) -> None:
-    ensure_task_dirs()
-    path = task_metadata_path(metadata["task_id"])
-    tmp_path = f"{path}.tmp"
-    with open(tmp_path, "w", encoding="utf-8") as f:
-        json.dump(metadata, f, ensure_ascii=False, indent=2)
-    os.replace(tmp_path, path)
+    with _task_store_lock:
+        ensure_task_dirs()
+        path = task_metadata_path(metadata["task_id"])
+        tmp_path = f"{path}.{uuid.uuid4().hex}.tmp"
+        with open(tmp_path, "w", encoding="utf-8") as f:
+            json.dump(metadata, f, ensure_ascii=False, indent=2)
+        os.replace(tmp_path, path)
 
 
 def load_task(task_id: str) -> Optional[Dict[str, Any]]:
-    path = task_metadata_path(task_id)
-    if not os.path.exists(path):
-        return None
-    with open(path, "r", encoding="utf-8") as f:
-        return json.load(f)
+    with _task_store_lock:
+        path = task_metadata_path(task_id)
+        if not os.path.exists(path):
+            return None
+        with open(path, "r", encoding="utf-8") as f:
+            return json.load(f)
 
 
 def delete_task(task_id: str) -> bool:
-    metadata = load_task(task_id)
-    if not metadata:
-        return False
+    with _task_store_lock:
+        metadata = load_task(task_id)
+        if not metadata:
+            return False
 
-    metadata_path = task_metadata_path(task_id)
-    output_dir = metadata.get("output_dir") or task_output_dir(task_id)
-    if os.path.exists(metadata_path):
-        os.remove(metadata_path)
-    if output_dir and os.path.exists(output_dir):
-        shutil.rmtree(output_dir)
+        metadata_path = task_metadata_path(task_id)
+        output_dir = metadata.get("output_dir") or task_output_dir(task_id)
+        if os.path.exists(metadata_path):
+            os.remove(metadata_path)
+        if output_dir and os.path.exists(output_dir):
+            shutil.rmtree(output_dir)
     logger.info("Deleted pipeline task: task_id=%s output_dir=%s", task_id, output_dir)
     return True
 
 
 def list_tasks(limit: int = 100) -> list[Dict[str, Any]]:
-    ensure_task_dirs()
-    records = []
-    for filename in os.listdir(TASK_DATA_DIR):
-        if not filename.endswith(".json"):
-            continue
-        try:
-            with open(os.path.join(TASK_DATA_DIR, filename), "r", encoding="utf-8") as f:
-                records.append(json.load(f))
-        except Exception:
-            continue
-    records.sort(key=lambda item: item.get("created_at", ""), reverse=True)
-    return records[:limit]
+    with _task_store_lock:
+        ensure_task_dirs()
+        records = []
+        for filename in os.listdir(TASK_DATA_DIR):
+            if not filename.endswith(".json"):
+                continue
+            try:
+                with open(os.path.join(TASK_DATA_DIR, filename), "r", encoding="utf-8") as f:
+                    records.append(json.load(f))
+            except Exception:
+                continue
+        records.sort(key=lambda item: item.get("created_at", ""), reverse=True)
+        return records[:limit]
 
 
 def create_task(pipeline: str, input_params: Dict[str, Any]) -> Dict[str, Any]:
-    ensure_task_dirs()
-    task_id = new_task_id()
-    output_dir = task_output_dir(task_id)
-    os.makedirs(output_dir, exist_ok=True)
-    metadata = {
-        "task_id": task_id,
-        "pipeline": pipeline,
-        "status": "pending",
-        "progress": 0,
-        "message": "Task created",
-        "input": input_params,
-        "output": {},
-        "artifacts": [],
-        "error": None,
-        "created_at": now_iso(),
-        "updated_at": now_iso(),
-        "started_at": None,
-        "completed_at": None,
-        "duration_seconds": None,
-        "output_dir": output_dir,
-    }
-    save_task(metadata)
+    with _task_store_lock:
+        ensure_task_dirs()
+        task_id = new_task_id()
+        output_dir = task_output_dir(task_id)
+        os.makedirs(output_dir, exist_ok=True)
+        metadata = {
+            "task_id": task_id,
+            "pipeline": pipeline,
+            "status": "pending",
+            "progress": 0,
+            "message": "Task created",
+            "input": input_params,
+            "output": {},
+            "artifacts": [],
+            "error": None,
+            "created_at": now_iso(),
+            "updated_at": now_iso(),
+            "started_at": None,
+            "completed_at": None,
+            "duration_seconds": None,
+            "output_dir": output_dir,
+        }
+        save_task(metadata)
     logger.info("Created pipeline task: task_id=%s pipeline=%s output_dir=%s", task_id, pipeline, output_dir)
     return metadata
 
 
 def update_task(task_id: str, **updates: Any) -> Dict[str, Any]:
-    metadata = load_task(task_id)
-    if not metadata:
-        raise FileNotFoundError(f"Task not found: {task_id}")
-    metadata.update(updates)
-    metadata["updated_at"] = now_iso()
-    save_task(metadata)
+    with _task_store_lock:
+        metadata = load_task(task_id)
+        if not metadata:
+            raise FileNotFoundError(f"Task not found: {task_id}")
+        metadata.update(updates)
+        metadata["updated_at"] = now_iso()
+        save_task(metadata)
     if "progress" in updates or "status" in updates:
         logger.info(
             "Task update: task_id=%s status=%s progress=%s message=%s",
@@ -135,27 +143,28 @@
 
 
 def append_artifact(task_id: str, new_artifact: Dict[str, Any]) -> Dict[str, Any]:
-    metadata = load_task(task_id)
-    if not metadata:
-        raise FileNotFoundError(f"Task not found: {task_id}")
+    with _task_store_lock:
+        metadata = load_task(task_id)
+        if not metadata:
+            raise FileNotFoundError(f"Task not found: {task_id}")
 
-    if not new_artifact.get("created_at"):
-        new_artifact = {**new_artifact, "created_at": now_iso()}
+        if not new_artifact.get("created_at"):
+            new_artifact = {**new_artifact, "created_at": now_iso()}
 
-    artifacts = list(metadata.get("artifacts") or [])
-    key = (new_artifact.get("kind"), new_artifact.get("name"), new_artifact.get("path"))
-    if not any((item.get("kind"), item.get("name"), item.get("path")) == key for item in artifacts):
-        artifacts.append(new_artifact)
-        logger.info(
-            "Task artifact: task_id=%s kind=%s name=%s path=%s",
-            task_id,
-            new_artifact.get("kind"),
-            new_artifact.get("name"),
-            new_artifact.get("path"),
-        )
-    metadata["artifacts"] = artifacts
-    metadata["updated_at"] = now_iso()
-    save_task(metadata)
+        artifacts = list(metadata.get("artifacts") or [])
+        key = (new_artifact.get("kind"), new_artifact.get("name"), new_artifact.get("path"))
+        if not any((item.get("kind"), item.get("name"), item.get("path")) == key for item in artifacts):
+            artifacts.append(new_artifact)
+            logger.info(
+                "Task artifact: task_id=%s kind=%s name=%s path=%s",
+                task_id,
+                new_artifact.get("kind"),
+                new_artifact.get("name"),
+                new_artifact.get("path"),
+            )
+        metadata["artifacts"] = artifacts
+        metadata["updated_at"] = now_iso()
+        save_task(metadata)
     publish_task_event(task_id, {
         "type": "artifact",
         "status": metadata.get("status"),
diff --git a/video-claw/video-claw/frontend/components/WorkflowPanel.tsx b/video-claw/video-claw/frontend/components/WorkflowPanel.tsx
index fb9f222..d61b6e7 100644
--- a/video-claw/video-claw/frontend/components/WorkflowPanel.tsx
+++ b/video-claw/video-claw/frontend/components/WorkflowPanel.tsx
@@ -113,7 +113,7 @@
     return () => { pollRef.current = null; };
   }, []);
 
-  // 轮询等待后端阶段完成(从 sessions json 读取,支持后端重启后恢复)
+  // 轮询等待后端阶段完成。运行中优先读后端内存,后端重启后再回退到磁盘快照。
   const pollForCompletion = useCallback(async (sid: string, stageId: string) => {
     const key = `${sid}:${stageId}`;
     pollRef.current = key;
@@ -121,13 +121,11 @@
       await new Promise(r => setTimeout(r, 2000));
       if (pollRef.current !== key) return;
       try {
-        // 优先从 sessions json 读取(支持后端重启后恢复)
         let status: any;
         try {
-          status = await getProjectStatusFromDisk(sid);
-        } catch {
-          // 如果从磁盘读取失败,回退到内存状态
           status = await getProjectStatus(sid);
+        } catch {
+          status = await getProjectStatusFromDisk(sid);
         }
         if (pollRef.current !== key) return;
         setGlobalStatusMap(status.status || {});
@@ -1017,12 +1015,11 @@
     const stageParam = targetStage ? `&stage=${targetStage}` : '';
     router.push(`/?session=${sid}${stageParam}`);
     try {
-      // 优先从 sessions json 读取(支持后端重启后恢复)
       let status: any;
       try {
-        status = await getProjectStatusFromDisk(sid);
-      } catch {
         status = await getProjectStatus(sid);
+      } catch {
+        status = await getProjectStatusFromDisk(sid);
       }
       setGlobalStatusMap(status.status || {});
       const newStates = initStageStates();
@@ -1077,11 +1074,12 @@
         }
       }
 
-      // 恢复项目参数(从顶层字段读取,sessions json 中模型参数是顶层字段)
-      if ((status as any).idea) {
-        const s = status as any;
+      // 恢复项目参数:会话级生成配置统一从 meta 中读取,兼容少量旧扁平字段。
+      const meta = ((status as any).meta || {}) as any;
+      const s = Object.keys(meta).length > 0 ? meta : (status as any);
+      if (s.idea || s.user_textbox_input) {
         setProjectParams({
-          idea: s.idea || '',
+          idea: s.idea || s.user_textbox_input || '',
           style: s.style || '',
           video_ratio: s.video_ratio || '16:9',
           video_resolution: s.video_resolution || '720P',
@@ -1189,6 +1187,7 @@
   const hasWaiting = Object.values(stageStates).some(s => s.status === 'waiting');
   const hasError = Object.values(stageStates).some(s => s.status === 'error');
   const allCompleted = Object.values(stageStates).every(s => s.status === 'completed' || s.status === 'pending');
+  const effectiveIsRunning = isRunning || hasRunning;
 
   let computedStatus: string;
   if (hasRunning) computedStatus = 'running';
@@ -1264,7 +1263,7 @@
         onUpdateArtifact={(patch: Record<string, any>) => handleUpdateArtifact(activeStage, patch)}
         onSaveSelections={(selections: Record<string, any>) => handleSaveSelections(activeStage, selections)}
         showConfirm={showConfirm}
-        isRunning={isRunning}
+        isRunning={effectiveIsRunning}
         hasPendingItems={hasPendingItems}
         hasNextStageStarted={hasNextStageStarted}
         videoSound={videoSound}
@@ -1293,7 +1292,7 @@
         onStageClick={handleStageClick}
         onHomeClick={handleGoHome}
         hasSession={sessionId !== null}
-        isRunning={isRunning}
+        isRunning={effectiveIsRunning}
         onStop={handleStop}
         autoMode={autoMode}
         onAutoModeChange={setAutoMode}
diff --git a/video-claw/video-claw/frontend/components/pipelines/PipelinePage.tsx b/video-claw/video-claw/frontend/components/pipelines/PipelinePage.tsx
index f2bbdad..6e7bde2 100644
--- a/video-claw/video-claw/frontend/components/pipelines/PipelinePage.tsx
+++ b/video-claw/video-claw/frontend/components/pipelines/PipelinePage.tsx
@@ -734,7 +734,7 @@
   const [videoResolution, setVideoResolution] = useState('720P');
   const [duration, setDuration] = useState(5);
   const [ttsVoice, setTtsVoice] = useState('zh-CN-YunjianNeural');
-  const [ttsSpeed, setTtsSpeed] = useState(1.2);
+  const [ttsSpeed, setTtsSpeed] = useState(1);
   const [negativePrompt, setNegativePrompt] = useState(pipeline === 'standard' ? DEFAULT_STANDARD_STYLE_CONTROL : '');
 
   useEffect(() => {
diff --git a/video-claw/video-claw/frontend/lib/workflowApi.ts b/video-claw/video-claw/frontend/lib/workflowApi.ts
index d8feeb0..57128d3 100644
--- a/video-claw/video-claw/frontend/lib/workflowApi.ts
+++ b/video-claw/video-claw/frontend/lib/workflowApi.ts
@@ -272,10 +272,10 @@
   return resp.json();
 }
 
-// 从 sessions json 文件读取状态(供前端轮询使用,即使后端重启也能获取状态)
+// 兼容旧路由名;后端实际会通过统一的 workflow state 入口返回状态。
 export async function getProjectStatusFromDisk(sessionId: string): Promise<any> {
   const resp = await fetch(`/api/project/${sessionId}/status/from_disk`);
-  if (!resp.ok) throw new Error('Failed to get project status from disk');
+  if (!resp.ok) throw new Error('Failed to get project status snapshot');
   return resp.json();
 }
 

--
Gitblit v1.8.0