hit-cxf
2026-05-30 9e3ae86b7355984856d9802f3c5ad6bfbb67f917
Optimized WebUI, The progress bar displays normally after a refresh
8 files modified
717 ■■■■■ changed files
video-claw/video-claw/backend/api/routers/workflow.py 26 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/api/services/project_helpers.py 2 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/core/agents/reference_agent.py 36 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/core/agents/storyboard_agent.py 260 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/core/orchestrator.py 95 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/frontend/components/AppShell.tsx 201 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/frontend/components/WorkflowPanel.tsx 88 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/frontend/components/pipelines/PipelinePage.tsx 9 ●●●●● patch | view | raw | blame | history
video-claw/video-claw/backend/api/routers/workflow.py
@@ -37,6 +37,16 @@
        )
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)
@@ -140,8 +150,7 @@
@router.get("/api/project/{session_id}/status/from_disk")
async def get_project_status_from_disk(session_id: str):
    session_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'code', 'data', 'sessions')
    session_file = os.path.join(session_dir, f"{session_id}.json")
    session_file = _session_file_path(session_id)
    if not os.path.exists(session_file):
        raise HTTPException(404, "Session not found")
    with open(session_file, 'r', encoding='utf-8') as f:
@@ -153,6 +162,19 @@
    state = workflow_engine.get_state(session_id)
    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
    artifact = state.artifacts.get(stage)
    if artifact is None:
        raise HTTPException(404, f"Artifact for stage '{stage}' not found")
video-claw/video-claw/backend/api/services/project_helpers.py
@@ -59,6 +59,7 @@
def make_progress_channel():
    progress_events = queue.Queue()
    event_trigger = asyncio.Event()
    loop = asyncio.get_running_loop()
    def progress_callback(phase, step, percent, data=None):
        event = {"phase": phase, "step": step, "percent": percent}
@@ -66,7 +67,6 @@
            event["data"] = data
        progress_events.put(event)
        try:
            loop = asyncio.get_running_loop()
            loop.call_soon_threadsafe(event_trigger.set)
        except RuntimeError:
            pass
video-claw/video-claw/backend/core/agents/reference_agent.py
@@ -662,12 +662,9 @@
                    done = 0
                    nonlocal selected_images
                    nonlocal prompt_map
                    # 每片段5个步骤:准备(1)、生成(3)、完成(1)
                    steps_per_segment = 5
                    total_steps = total * steps_per_segment
                    def calc_pct_regen(step: int) -> int:
                        return min(2 + int(98 * step / total_steps), 100)
                    def calc_pct_regen(completed: int) -> int:
                        return min(95, 5 + int(90 * completed / max(total, 1)))
                    def regen_segment_run(segment_id: str, index: int):
                        seg = fresh_segment_map.get(segment_id, {})
@@ -702,7 +699,12 @@
                                ff_prompt = plot[:200]
                        logger.info(f"[{segment_id}] first-frame prompt: {ff_prompt}...")
                        self._report_progress("参考图", f"准备提示词: {segment_id}", calc_pct_regen(index * steps_per_segment + 1))
                        self._report_progress("参考图", f"正在生成: {segment_id}", 5, data={
                            "asset_complete": {
                                "type": "scenes", "id": segment_id,
                                "status": "running"
                            }
                        })
                        refs = self._collect_refs(seg, asset_map, char_id_map, setting_id_map)
                        char_desc, set_desc = self._get_descriptions(
@@ -720,7 +722,7 @@
                        return result_segment_id, result_path, eval_result, final_prompt
                    # 并发生成提示词与图像
                    self._report_progress("参考图", "生成参考图...", calc_pct_regen(total * 2))
                    self._report_progress("参考图", f"生成参考图... 0/{total}", 5)
                    with ThreadPoolExecutor(max_workers=concurrency) as executor:
                        futs = {}
                        for i, segment_id in enumerate(regen_scenes):
@@ -735,8 +737,7 @@
                                logger.error(f"Regen future error for {segment_id_done}: {e}")
                                result_path = None
                            done += 1
                            step = done * steps_per_segment
                            pct = calc_pct_regen(step)
                            pct = calc_pct_regen(done)
                            if result_path:
                                selected_images[segment_id_done] = result_path
                                versions = self._list_versions(sid, segment_id_done)
@@ -797,18 +798,15 @@
                return
            total = len(pending_segments)
            # 每分镜5个步骤:准备(1)、生成(3)、完成(1)
            steps_per_segment = 5
            total_steps = total * steps_per_segment + 1  # +1 是加载数据步骤
            def calc_pct(step: int) -> int:
                """根据步骤计算进度百分比"""
                return min(2 + int(98 * step / total_steps), 100)
            def calc_pct(completed: int) -> int:
                """并发阶段只按完成数量推进,避免提交任务时进度虚高。"""
                return min(95, 10 + int(85 * completed / max(total, 1)))
            done = 0
            # 步骤2-6(每片段):流式生成提示词并立即开始图像生成
            self._report_progress("参考图", "开始生成...", calc_pct(0))
            self._report_progress("参考图", f"开始生成... 0/{total}", calc_pct(0))
            
            with ThreadPoolExecutor(max_workers=concurrency) as executor:
                futs = {}
@@ -817,7 +815,7 @@
                def segment_run(seg: dict, index: int):
                    segment_id = seg['segment_id']
                    self._report_progress("参考图", f"正在启动: {segment_id}", calc_pct(index * steps_per_segment), data={
                    self._report_progress("参考图", f"正在生成: {segment_id}", calc_pct(done), data={
                        "asset_complete": {
                            "type": "scenes", "id": segment_id,
                            "status": "running"
@@ -873,7 +871,6 @@
                    segment_id = seg['segment_id']
                    fut = executor.submit(segment_run, seg, i)
                    futs[fut] = segment_id
                    self._report_progress("参考图", f"等待生成: {segment_id}", calc_pct(i * steps_per_segment))
                # 4. 等待所有任务完成
                cancelled = False
@@ -887,8 +884,7 @@
                        result_path = None
                    
                    done += 1
                    step = done * steps_per_segment
                    pct = calc_pct(step)
                    pct = calc_pct(done)
                    
                    if result_path:
                        selected_images_map[segment_id_done] = result_path
video-claw/video-claw/backend/core/agents/storyboard_agent.py
@@ -11,7 +11,7 @@
import asyncio
import logging
from datetime import datetime
from typing import Any, Optional, Dict, List, Tuple
from typing import Any, Optional, Callable, Dict, List, Tuple
from .base_agent import AgentInterface
@@ -145,7 +145,7 @@
        return setting_names[0] if setting_names else ""
    @classmethod
    def _parse_scene_header(cls, line: str, setting_names: List[str]) -> Optional[str]:
    def _parse_scene_header_parts(cls, line: str, setting_names: List[str]) -> Optional[dict]:
        clean = cls._strip_markup(line)
        if not clean:
            return None
@@ -154,19 +154,38 @@
        # **第1集-第1场 日 内 高二三班教室**
        # **1-1 夜 内 锐创科技办公室**
        header_patterns = [
            r"^第\d+集\s*[-—]\s*第\d+场\s+(?:日|夜|晨|傍晚|深夜)\s+(?:内|外)\s+(.+)$",
            r"^\d+\s*[-—_]\s*\d+\s+(?:日|夜|晨|傍晚|深夜)\s+(?:内|外)\s+(.+)$",
            r"^第\d+集\s*[-—]\s*第\d+场\s+(日|夜|晨|傍晚|深夜)\s+(内|外)\s+(.+)$",
            r"^\d+\s*[-—_]\s*\d+\s+(日|夜|晨|傍晚|深夜)\s+(内|外)\s+(.+)$",
        ]
        for pattern in header_patterns:
            match = re.match(pattern, clean, flags=re.I)
            if not match:
                continue
            candidate = match.group(1).strip()
            time_of_day = match.group(1).strip()
            scene_space = match.group(2).strip()
            candidate = match.group(3).strip()
            for name in setting_names:
                if cls._setting_matches_text(name, candidate):
                    return name
            return candidate[:40] or clean[:40]
                    return {
                        "location": name,
                        "scene_time": time_of_day,
                        "scene_space": scene_space,
                        "scene_context": clean,
                    }
            return {
                "location": candidate[:40] or clean[:40],
                "scene_time": time_of_day,
                "scene_space": scene_space,
                "scene_context": clean,
            }
        return None
    @classmethod
    def _parse_scene_header(cls, line: str, setting_names: List[str]) -> Optional[str]:
        parts = cls._parse_scene_header_parts(line, setting_names)
        if not parts:
            return None
        return parts.get("location")
    @staticmethod
    def _is_metadata_line(line: str) -> bool:
@@ -227,6 +246,9 @@
        annotated_lines: List[str] = []
        units: List[dict] = []
        current_location = setting_names[0] if setting_names else ""
        current_scene_time = ""
        current_scene_space = ""
        current_scene_context = ""
        scene_characters: List[str] = []
        scene_key = 0
@@ -239,10 +261,13 @@
                annotated_lines.append(line)
                continue
            header_location = cls._parse_scene_header(stripped, setting_names)
            if header_location:
            header_parts = cls._parse_scene_header_parts(stripped, setting_names)
            if header_parts:
                scene_key += 1
                current_location = header_location
                current_location = header_parts.get("location", current_location)
                current_scene_time = header_parts.get("scene_time", "")
                current_scene_space = header_parts.get("scene_space", "")
                current_scene_context = header_parts.get("scene_context", cls._strip_markup(stripped))
                scene_characters = cls._match_characters(line, character_names)
                annotated_lines.append(cls._strip_markup(stripped))
                continue
@@ -283,6 +308,9 @@
                "scene_characters": scene_characters[:],
                "scene_key": scene_key,
                "location": cls._resolve_location(line, current_location, setting_names),
                "scene_time": current_scene_time,
                "scene_space": current_scene_space,
                "scene_context": current_scene_context,
                "is_entry": cls._is_entry_action(line, character_names),
            })
            annotated_lines.append(f"[{duration}秒][{unit_id}] {line}")
@@ -300,6 +328,9 @@
            "episode_number": ep_n,
            "segment_number": segment_number,
            "location": items[0].get("location", "") if items else "",
            "scene_time": items[0].get("scene_time", "") if items else "",
            "scene_space": items[0].get("scene_space", "") if items else "",
            "scene_context": items[0].get("scene_context", "") if items else "",
            "characters": characters,
            "total_duration": sum(int(item.get("duration") or 0) for item in items),
            "items": items,
@@ -395,6 +426,7 @@
                "text": item["text"],
                "characters": item.get("characters", []),
                "is_entry": item.get("is_entry", False),
                "scene_context": item.get("scene_context", ""),
            }
            for item in items
        ]
@@ -447,6 +479,9 @@
            episode_title=ep_t,
            segment_number=plan.get("segment_number"),
            location=plan.get("location", ""),
            scene_time=plan.get("scene_time", ""),
            scene_space=plan.get("scene_space", ""),
            scene_context=plan.get("scene_context", ""),
            characters=json.dumps(plan.get("characters", []), ensure_ascii=False),
            total_duration=output_total,
            items=json.dumps(items_payload, ensure_ascii=False),
@@ -600,6 +635,9 @@
            plan.get("location", ""),
            shots,
            characters,
            plan.get("scene_time", ""),
            plan.get("scene_space", ""),
            plan.get("scene_context", ""),
        )
    @classmethod
@@ -631,7 +669,129 @@
            plan.get("location", ""),
            shots,
            characters,
            plan.get("scene_time", ""),
            plan.get("scene_space", ""),
            plan.get("scene_context", ""),
        )
    @staticmethod
    def _staging_continuity_payload(segments: List[dict]) -> List[dict]:
        payload: List[dict] = []
        for seg in segments:
            payload.append({
                "segment_number": seg.get("segment_number"),
                "location": seg.get("location", ""),
                "scene_context": seg.get("scene_context", ""),
                "scene_space": seg.get("scene_space", ""),
                "characters": seg.get("characters", []),
                "shots": [
                    {
                        "shot_number": shot.get("shot_number"),
                        "shot_type": shot.get("shot_type", ""),
                        "content": shot.get("content", ""),
                    }
                    for shot in seg.get("shots", [])
                    if isinstance(shot, dict)
                ],
            })
        return payload
    @classmethod
    def _build_staging_continuity_prompt(
        cls,
        ep_n: int,
        ep_t: str,
        segments: List[dict],
        retry_error: str = "",
    ) -> str:
        template = _get_storyboard_prompt("staging_continuity", "zh")
        retry_feedback = ""
        if retry_error:
            retry_feedback = f"上一次输出未通过校验,错误原因:{retry_error}\n请根据这个错误修正输出。"
        from prompts.loader import format_prompt
        return format_prompt(
            template,
            episode_number=ep_n,
            episode_title=ep_t,
            segments=json.dumps(cls._staging_continuity_payload(segments), ensure_ascii=False, indent=2),
            retry_feedback=retry_feedback,
        )
    @staticmethod
    def _apply_staging_continuity_patches(segments: List[dict], review: dict) -> int:
        patches = review.get("patches") if isinstance(review, dict) else None
        if not isinstance(patches, list):
            raise ValueError("站位连续性检查输出缺少 patches 数组")
        segment_by_number = {
            int(seg.get("segment_number") or 0): seg
            for seg in segments
            if isinstance(seg, dict)
        }
        updates: List[Tuple[dict, str]] = []
        for patch in patches:
            if not isinstance(patch, dict):
                raise ValueError("站位连续性补丁包含非对象元素")
            try:
                segment_number = int(patch.get("segment_number"))
                shot_number = int(patch.get("shot_number"))
            except (TypeError, ValueError):
                raise ValueError(f"站位连续性补丁编号无效: {patch}")
            content = str(patch.get("content") or "").strip()
            if not content:
                raise ValueError(f"站位连续性补丁 content 为空: {patch}")
            seg = segment_by_number.get(segment_number)
            if not seg:
                raise ValueError(f"站位连续性补丁引用未知片段: {segment_number}")
            shot = next(
                (item for item in seg.get("shots", []) if int(item.get("shot_number") or 0) == shot_number),
                None,
            )
            if not shot:
                raise ValueError(f"站位连续性补丁引用未知分镜: segment={segment_number}, shot={shot_number}")
            updates.append((shot, content))
        for shot, content in updates:
            shot["content"] = content
        return len(updates)
    async def _fix_episode_staging_continuity(
        self,
        ep_n: int,
        ep_t: str,
        segments: List[dict],
        llm_model: str,
        sid: str,
    ) -> List[dict]:
        last_error: Optional[Exception] = None
        for attempt in range(2):
            try:
                prompt = self._build_staging_continuity_prompt(
                    ep_n,
                    ep_t,
                    segments,
                    retry_error=str(last_error) if last_error else "",
                )
                review = await self._query_json_object_with_retries(
                    prompt,
                    llm_model,
                    sid,
                    label=f"第 {ep_n} 集人物站位连续性检查",
                    max_retries=1,
                )
                applied = self._apply_staging_continuity_patches(segments, review)
                issues = review.get("issues") if isinstance(review, dict) else []
                if applied:
                    logger.info("[Storyboard] Episode %s staging continuity fixed %d shots. issues=%s", ep_n, applied, issues)
                else:
                    logger.info("[Storyboard] Episode %s staging continuity passed.", ep_n)
                return segments
            except Exception as exc:
                last_error = exc
                logger.warning("[Storyboard] Episode %s staging continuity attempt %d failed: %s", ep_n, attempt + 1, exc)
        logger.warning("[Storyboard] Episode %s staging continuity check skipped after retries: %s", ep_n, last_error)
        return segments
    async def _plan_episode_segments(
        self,
@@ -725,23 +885,32 @@
        style: str,
        llm_model: str,
        sid: str,
        progress_note: Optional[Callable[[str], None]] = None,
    ) -> List[dict]:
        annotated_script, units = self._annotate_episode_script(ep_c, characters, settings)
        if not units:
            raise Exception(f"第 {ep_n} 集未能识别出动作或台词")
        self._report_progress("分镜", f"第 {ep_n} 集已完成动作/台词时长标注,共 {len(units)} 项", 20)
        logger.info("[Storyboard] Episode %s annotated %d script units", ep_n, len(units))
        if progress_note:
            progress_note(f"第 {ep_n} 集已完成时长标注,正在划分片段")
        plans = await self._plan_episode_segments(ep_n, ep_t, annotated_script, units, characters, settings, llm_model, sid)
        if not plans:
            raise Exception(f"第 {ep_n} 集片段规划失败")
        self._report_progress("分镜", f"第 {ep_n} 集已规划 {len(plans)} 个片段,开始并行设计分镜", 35)
        logger.info("[Storyboard] Episode %s planned %d segments; designing in parallel", ep_n, len(plans))
        if progress_note:
            progress_note(f"第 {ep_n} 集已规划 {len(plans)} 个片段,正在设计分镜")
        tasks = [
            self._design_one_segment(ep_n, ep_t, plan, style, llm_model, sid)
            for plan in plans
        ]
        segments = await asyncio.gather(*tasks)
        segments.sort(key=lambda item: int(item.get("segment_number") or 0))
        logger.info("[Storyboard] Episode %s checking staging continuity", ep_n)
        if progress_note:
            progress_note(f"第 {ep_n} 集正在检查人物站位连续性")
        segments = await self._fix_episode_staging_continuity(ep_n, ep_t, segments, llm_model, sid)
        return segments
    @classmethod
@@ -806,6 +975,9 @@
        location: str,
        shots: List[dict],
        characters: List[str],
        scene_time: str = "",
        scene_space: str = "",
        scene_context: str = "",
    ) -> dict:
        for idx, shot in enumerate(shots, 1):
            shot["shot_number"] = idx
@@ -815,7 +987,7 @@
            )
        cls._normalize_first_shot_type(shots)
        total_duration = cls._ensure_segment_duration(shots)
        return {
        segment = {
            "segment_id": f"seg_{ep_n:02d}_{segment_number:02d}",
            "segment_number": segment_number,
            "total_duration": total_duration,
@@ -824,6 +996,13 @@
            "shots": shots,
            "episode_number": ep_n,
        }
        if scene_time:
            segment["scene_time"] = scene_time
        if scene_space:
            segment["scene_space"] = scene_space
        if scene_context:
            segment["scene_context"] = scene_context
        return segment
    @classmethod
    def _build_segments_by_regex(
@@ -845,6 +1024,9 @@
        atomic_shots: List[dict] = []
        current_location = setting_names[0] if setting_names else ""
        current_scene_time = ""
        current_scene_space = ""
        current_scene_context = ""
        scene_characters: List[str] = []
        scene_key = 0
        found_scene_header = False
@@ -856,11 +1038,14 @@
            if re.match(r"^第?\d+集$", line):
                continue
            header_location = cls._parse_scene_header(line, setting_names)
            if header_location:
            header_parts = cls._parse_scene_header_parts(line, setting_names)
            if header_parts:
                found_scene_header = True
                scene_key += 1
                current_location = header_location
                current_location = header_parts.get("location", current_location)
                current_scene_time = header_parts.get("scene_time", "")
                current_scene_space = header_parts.get("scene_space", "")
                current_scene_context = header_parts.get("scene_context", line)
                matched = cls._match_characters(line, character_names)
                if matched:
                    scene_characters = matched
@@ -892,6 +1077,9 @@
            atomic_shots.append({
                "scene_key": scene_key,
                "location": location,
                "scene_time": current_scene_time,
                "scene_space": current_scene_space,
                "scene_context": current_scene_context,
                "characters": shot_chars,
                "shot": {
                    "shot_number": 0,
@@ -915,10 +1103,14 @@
        current_items: List[dict] = []
        current_scene_key: Optional[int] = None
        current_location = ""
        current_scene_time = ""
        current_scene_space = ""
        current_scene_context = ""
        current_chars: List[str] = []
        def flush_current():
            nonlocal current_items, current_scene_key, current_location, current_chars
            nonlocal current_items, current_scene_key, current_location
            nonlocal current_scene_time, current_scene_space, current_scene_context, current_chars
            if not current_items:
                return
            shots = [item["shot"] for item in current_items]
@@ -935,10 +1127,16 @@
                current_location,
                shots,
                chars,
                current_scene_time,
                current_scene_space,
                current_scene_context,
            ))
            current_items = []
            current_scene_key = None
            current_location = ""
            current_scene_time = ""
            current_scene_space = ""
            current_scene_context = ""
            current_chars = []
        for item in atomic_shots:
@@ -957,6 +1155,9 @@
            current_items.append(item)
            current_scene_key = item["scene_key"]
            current_location = item["location"]
            current_scene_time = item.get("scene_time", "")
            current_scene_space = item.get("scene_space", "")
            current_scene_context = item.get("scene_context", "")
            for name in item["characters"]:
                if name not in current_chars:
                    current_chars.append(name)
@@ -1046,6 +1247,9 @@
                    "segment_number": seg.get("segment_number", len(valid_segments) + 1),
                    "total_duration": seg.get("total_duration", calc_total_duration),
                    "location": seg.get("location", ""),
                    "scene_time": seg.get("scene_time", ""),
                    "scene_space": seg.get("scene_space", ""),
                    "scene_context": seg.get("scene_context", ""),
                    "characters": seg.get("characters", []),
                    "shots": valid_shots
                })
@@ -1112,11 +1316,20 @@
        sets = script_data.get("settings", [])
        
        self._report_progress("分镜", f"开始生成 {len(episodes_to_proc)} 集缺失的分镜...", 5)
        total_to_process = len(episodes_to_proc)
        completed_count = 0
        progress_state = {"percent": 10}
        def report_storyboard_note(message: str, percent: Optional[int] = None, data: Optional[dict] = None):
            if percent is not None:
                progress_state["percent"] = max(progress_state["percent"], percent)
            self._report_progress("分镜设计", message, progress_state["percent"], data)
        
        async def proc_ep(ep):
            ep_n = ep.get("episode_number", 1)
            ep_t = ep.get("act_title", f"第{ep_n}集")
            ep_c = ep.get("content", "")
            report_storyboard_note(f"正在处理第 {ep_n} 集分镜")
            segments = await self._design_episode_storyboard(
                ep_n,
                ep_t,
@@ -1126,6 +1339,7 @@
                style,
                llm_model,
                sid,
                progress_note=report_storyboard_note,
            )
            return {
@@ -1146,12 +1360,13 @@
        with open(session_file, "w", encoding="utf-8") as f:
            json.dump(session_data, f, indent=2, ensure_ascii=False)
        # 报告一次进度,带上 asset_complete 强制前端从磁盘刷新一次初步数据
        self._report_progress("分镜设计", "准备生成分镜...", 10, {"asset_complete": True})
        report_storyboard_note("准备生成分镜...", 10, {"asset_complete": True})
        results_queue = [asyncio.create_task(proc_ep(ep)) for ep in episodes_to_proc]
        for coro in asyncio.as_completed(results_queue):
            res = await coro
            completed_count += 1
            updated_ep_map[res["episode_number"]] = res
            
            # 每完成一集分镜,立即持久化并触发增量同步
@@ -1164,8 +1379,13 @@
            with open(session_file, "w", encoding="utf-8") as f:
                json.dump(session_data, f, indent=2, ensure_ascii=False)
            
            # 报告带有 asset_complete 的进度,强制编排器刷新前端数据
            self._report_progress("分镜设计", f"集数 {res['episode_number']} 分镜已生成", 50, {"asset_complete": True})
            # 并发多集时只按已完成集数推进全局进度,避免各集内部进度互相覆盖。
            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},
            )
        final_all_episodes = sorted(updated_ep_map.values(), key=lambda x: x["episode_number"])
        
video-claw/video-claw/backend/core/orchestrator.py
@@ -111,6 +111,7 @@
        self.started_at: Optional[datetime] = None
        self.updated_at: datetime = datetime.now()
        self.meta: Dict[str, Any] = {}
        self.stage_progress: Dict[str, Dict[str, Any]] = {}
    def to_dict(self) -> Dict:
        return {
@@ -120,6 +121,7 @@
            "error": self.error,
            "artifacts": self.artifacts,
            "meta": self.meta,
            "stage_progress": self.stage_progress,
            "updated_at": self.updated_at,
        }
@@ -186,6 +188,7 @@
                    state.status = loaded_status
                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)
@@ -211,6 +214,13 @@
            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")
@@ -464,9 +474,68 @@
        # 包装 progress_callback,定期保存状态到 sessions json
        last_save_time = {"time": 0}
        SAVE_INTERVAL = 10  # 每10秒保存一次
        SAVE_INTERVAL = 2  # 进度快照最多每2秒落盘一次,刷新页面后可恢复进度条
        def persist_stage_progress(phase: str, step: str, percent: float):
            stage_key = stage.value
            try:
                safe_percent = max(0, min(100, int(round(float(percent)))))
            except (TypeError, ValueError):
                safe_percent = 0
            message = f"{phase}: {step}" if phase and step else (step or phase or "")
            state.stage_progress[stage_key] = {
                "phase": phase,
                "step": step,
                "message": message,
                "percent": safe_percent,
                "updated_at": time.time(),
            }
            state.updated_at = datetime.now()
        def merge_progress_artifact(data: dict):
            if not isinstance(data, dict):
                return
            stage_key = stage.value
            if data.get("assets_preview"):
                state.artifacts[stage_key] = copy.deepcopy(data["assets_preview"])
            asset_update = data.get("asset_complete")
            if not isinstance(asset_update, dict):
                return
            artifact = state.artifacts.setdefault(stage_key, {})
            item_type = asset_update.get("type")
            item_id = asset_update.get("id")
            if not item_type or not item_id:
                return
            items = artifact.setdefault(item_type, [])
            if not isinstance(items, list):
                items = []
                artifact[item_type] = items
            for item in items:
                if isinstance(item, dict) and item.get("id") == item_id:
                    item["status"] = asset_update.get("status", item.get("status"))
                    if "selected" in asset_update:
                        item["selected"] = asset_update.get("selected") or item.get("selected", "")
                    if "versions" in asset_update:
                        item["versions"] = asset_update.get("versions") or item.get("versions", [])
                    return
            items.append({
                "id": item_id,
                "status": asset_update.get("status", "done"),
                "selected": asset_update.get("selected", ""),
                "versions": asset_update.get("versions", []),
            })
        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)
            # 调用原始 callback
            if progress_callback:
                progress_callback(phase, step, percent, data)
@@ -489,6 +558,14 @@
        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)
        try:
            result = await agent.process(input_data, intervention=intervention)
@@ -534,6 +611,13 @@
                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)
            return result
@@ -542,6 +626,13 @@
            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
@@ -651,6 +742,7 @@
            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()
            
@@ -715,6 +807,7 @@
                    state.status = old_status
                state.artifacts = data.get("artifacts", {})
                state.stage_progress = data.get("stage_progress", {})
                state.error = data.get("error")
                state.updated_at = data.get("updated_at", 0)
                state.meta = _extract_session_meta(data)
video-claw/video-claw/frontend/components/AppShell.tsx
@@ -2,7 +2,7 @@
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
import { ChevronLeft, ChevronRight, Clapperboard, Clock, Hexagon, Home, Loader2, PanelLeftOpen, Repeat2, Settings, Trash2, UserRound } from 'lucide-react';
import { CheckCircle2, ChevronLeft, ChevronRight, Clapperboard, Clock, Hexagon, Home, Loader2, PanelLeftOpen, Repeat2, Settings, Trash2, UserRound } from 'lucide-react';
import clsx from 'clsx';
import { useEffect, useState, type CSSProperties } from 'react';
import { clearTempCache, fetchPipelineTasks, fetchSandboxTasks, fetchSessions, type PipelineTask, type SandboxTask } from '@/lib/workflowApi';
@@ -26,6 +26,7 @@
const TASK_STATUS_STYLE: Record<string, string> = {
  pending: 'bg-gray-100 text-gray-500',
  running: 'bg-blue-50 text-blue-600',
  waiting: 'bg-amber-50 text-amber-600',
  completed: 'bg-green-50 text-green-600',
  failed: 'bg-red-50 text-red-600',
};
@@ -33,6 +34,7 @@
function statusText(status?: string) {
  if (status === 'pending') return '等待中';
  if (status === 'running') return '生成中';
  if (status === 'waiting') return '待确认';
  if (status === 'completed') return '已完成';
  if (status === 'failed') return '失败';
  return status || '未知';
@@ -40,7 +42,8 @@
function taskTitle(task: PipelineTask) {
  const input = task.input || {};
  return input.title || input.goods_title || input.text || input.prompt_text || input.goods_text || task.task_id;
  const output = task.output || {};
  return output.title || input.title || input.goods_title || input.text || input.prompt_text || input.goods_text || task.task_id;
}
type RunningTaskItem = {
@@ -53,6 +56,8 @@
};
const WORKFLOW_STAGE_COUNT = 7;
const COMPLETED_TASK_DISMISS_KEY = 'video-claw.dismissed-completed-tasks';
const SIDEBAR_OPEN_KEY = 'video-claw.sidebar-open';
function projectTaskFromSession(session: any): RunningTaskItem | null {
  const statusMap = session.status || {};
@@ -70,6 +75,23 @@
  };
}
function projectReviewTaskFromSession(session: any): RunningTaskItem | null {
  const statusMap = session.status || {};
  const waitingStage = Object.keys(statusMap).find(key => statusMap[key] === 'waiting');
  const completed = Object.values(statusMap).filter(value => ['completed', 'session_completed'].includes(String(value))).length;
  const allDone = completed >= WORKFLOW_STAGE_COUNT || statusMap.completed === 'completed';
  if (!waitingStage && !allDone) return null;
  const targetStage = waitingStage || Object.keys(statusMap).reverse().find(key => ['completed', 'session_completed'].includes(String(statusMap[key]))) || '';
  return {
    id: `project-review-${session.id}-${waitingStage || 'completed'}`,
    href: `/?session=${encodeURIComponent(session.id)}${targetStage ? `&stage=${encodeURIComponent(targetStage)}` : ''}`,
    title: session.idea || session.title || session.id,
    scope: waitingStage ? `主流程 · ${waitingStage}` : '主流程',
    status: waitingStage ? 'waiting' : 'completed',
    progress: waitingStage ? Math.round((completed / WORKFLOW_STAGE_COUNT) * 100) : 100,
  };
}
function pipelineTaskItem(task: PipelineTask): RunningTaskItem | null {
  const route = PIPELINE_ROUTES[task.pipeline];
  if (!route || !['pending', 'running'].includes(task.status)) return null;
@@ -80,6 +102,19 @@
    scope: route.label,
    status: task.status,
    progress: task.progress || 0,
  };
}
function pipelineCompletedTaskItem(task: PipelineTask): RunningTaskItem | null {
  const route = PIPELINE_ROUTES[task.pipeline];
  if (!route || task.status !== 'completed') return null;
  return {
    id: `pipeline-completed-${task.task_id}`,
    href: `${route.href}?task=${encodeURIComponent(task.task_id)}`,
    title: String(taskTitle(task)),
    scope: route.label,
    status: 'completed',
    progress: 100,
  };
}
@@ -103,40 +138,54 @@
  };
}
function RunningTaskList({ currentPath }: { currentPath: string }) {
  const router = useRouter();
  const [tasks, setTasks] = useState<RunningTaskItem[]>([]);
  const [loading, setLoading] = useState(false);
  const load = async () => {
    setLoading(true);
function loadDismissedCompletedTasks(): Set<string> {
  if (typeof window === 'undefined') return new Set();
    try {
      const [pipelineRecords, sessions, sandboxRecords] = await Promise.all([
        fetchPipelineTasks(100).catch(() => []),
        fetchSessions().catch(() => []),
        fetchSandboxTasks().catch(() => []),
      ]);
      setTasks([
        ...sandboxRecords.map(sandboxTaskItem),
        ...pipelineRecords.map(pipelineTaskItem).filter((task): task is RunningTaskItem => Boolean(task)),
        ...sessions.map(projectTaskFromSession).filter((task): task is RunningTaskItem => Boolean(task)),
      ]);
    } finally {
      setLoading(false);
    const raw = window.localStorage.getItem(COMPLETED_TASK_DISMISS_KEY);
    const parsed = raw ? JSON.parse(raw) : [];
    return new Set(Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === 'string') : []);
  } catch {
    return new Set();
    }
  };
}
  useEffect(() => {
    load().catch(() => {});
    const timer = window.setInterval(() => load().catch(() => {}), 3000);
    return () => window.clearInterval(timer);
  }, []);
function saveDismissedCompletedTasks(ids: Set<string>) {
  if (typeof window === 'undefined') return;
  window.localStorage.setItem(COMPLETED_TASK_DISMISS_KEY, JSON.stringify(Array.from(ids)));
}
function loadSidebarOpen(): boolean {
  if (typeof window === 'undefined') return false;
  return window.localStorage.getItem(SIDEBAR_OPEN_KEY) === 'true';
}
function saveSidebarOpen(open: boolean) {
  if (typeof window === 'undefined') return;
  window.localStorage.setItem(SIDEBAR_OPEN_KEY, open ? 'true' : 'false');
}
function TaskPanel({
  title,
  icon,
  loading,
  tasks,
  currentPath,
  emptyText,
  onTaskClick,
}: {
  title: string;
  icon: React.ReactNode;
  loading?: boolean;
  tasks: RunningTaskItem[];
  currentPath: string;
  emptyText: string;
  onTaskClick: (task: RunningTaskItem) => void;
}) {
  return (
    <section className="h-[30vh] min-h-44 border-t border-gray-100 p-3">
    <section className="h-[20vh] min-h-32 border-t border-gray-100 p-3">
      <div className="mb-2 flex items-center gap-2 px-1">
        <Clock className="h-3.5 w-3.5 text-gray-400" />
        <span className="text-xs font-medium text-gray-500">进行中任务</span>
        {icon}
        <span className="text-xs font-medium text-gray-500">{title}</span>
        {loading && <Loader2 className="ml-auto h-3 w-3 animate-spin text-gray-300" />}
      </div>
      <div className="h-[calc(100%-26px)] overflow-y-auto pr-1">
@@ -148,7 +197,7 @@
                <button
                  key={task.id}
                  type="button"
                  onClick={() => router.push(task.href)}
                  onClick={() => onTaskClick(task)}
                  className={clsx(
                    'w-full rounded-lg border px-2.5 py-2 text-left transition-colors',
                    active ? 'border-blue-100 bg-blue-50/60' : 'border-gray-100 bg-white hover:border-blue-200 hover:bg-blue-50/40'
@@ -173,12 +222,83 @@
            })}
          </div>
        ) : (
          <div className="flex h-full items-center justify-center rounded-lg border border-dashed border-gray-100 text-xs text-gray-300">
            暂无进行中任务
          <div className="flex h-full items-center justify-center rounded-lg border border-dashed border-gray-100 px-2 text-center text-xs text-gray-300">
            {emptyText}
          </div>
        )}
      </div>
    </section>
  );
}
function SidebarTaskPanels({ currentPath }: { currentPath: string }) {
  const router = useRouter();
  const [runningTasks, setRunningTasks] = useState<RunningTaskItem[]>([]);
  const [completedTasks, setCompletedTasks] = useState<RunningTaskItem[]>([]);
  const [dismissedCompleted, setDismissedCompleted] = useState<Set<string>>(() => loadDismissedCompletedTasks());
  const [loading, setLoading] = useState(false);
  const load = async () => {
    setLoading(true);
    try {
      const [pipelineRecords, sessions, sandboxRecords] = await Promise.all([
        fetchPipelineTasks(100).catch(() => []),
        fetchSessions().catch(() => []),
        fetchSandboxTasks().catch(() => []),
      ]);
      setRunningTasks([
        ...sandboxRecords.map(sandboxTaskItem),
        ...pipelineRecords.map(pipelineTaskItem).filter((task): task is RunningTaskItem => Boolean(task)),
        ...sessions.map(projectTaskFromSession).filter((task): task is RunningTaskItem => Boolean(task)),
      ]);
      setCompletedTasks([
        ...pipelineRecords.map(pipelineCompletedTaskItem).filter((task): task is RunningTaskItem => Boolean(task)),
        ...sessions.map(projectReviewTaskFromSession).filter((task): task is RunningTaskItem => Boolean(task)),
      ].filter(task => !dismissedCompleted.has(task.id)));
    } finally {
      setLoading(false);
    }
  };
  useEffect(() => {
    load().catch(() => {});
    const timer = window.setInterval(() => load().catch(() => {}), 3000);
    return () => window.clearInterval(timer);
  }, [dismissedCompleted]);
  const handleRunningClick = (task: RunningTaskItem) => {
    router.push(task.href);
  };
  const handleCompletedClick = (task: RunningTaskItem) => {
    const next = new Set(dismissedCompleted);
    next.add(task.id);
    saveDismissedCompletedTasks(next);
    setDismissedCompleted(next);
    setCompletedTasks(current => current.filter(item => item.id !== task.id));
    router.push(task.href);
  };
  return (
    <>
      <TaskPanel
        title="进行中任务"
        icon={<Clock className="h-3.5 w-3.5 text-gray-400" />}
        loading={loading}
        tasks={runningTasks}
        currentPath={currentPath}
        emptyText="暂无进行中任务"
        onTaskClick={handleRunningClick}
      />
      <TaskPanel
        title="已完成/等待确认"
        icon={<CheckCircle2 className="h-3.5 w-3.5 text-gray-400" />}
        tasks={completedTasks}
        currentPath={currentPath}
        emptyText="暂无已完成或待确认任务"
        onTaskClick={handleCompletedClick}
      />
    </>
  );
}
@@ -188,6 +308,15 @@
  const [open, setOpen] = useState(false);
  const [settingsMenuOpen, setSettingsMenuOpen] = useState(false);
  const [clearingCache, setClearingCache] = useState(false);
  useEffect(() => {
    setOpen(loadSidebarOpen());
  }, []);
  const setSidebarOpen = (nextOpen: boolean) => {
    setOpen(nextOpen);
    saveSidebarOpen(nextOpen);
  };
  const handleClearCache = async () => {
    setClearingCache(true);
@@ -241,7 +370,7 @@
              );
            })}
          </nav>
          <RunningTaskList currentPath={pathname} />
          <SidebarTaskPanels currentPath={pathname} />
          <div className="relative border-t border-gray-100 p-3">
            {(() => {
              const Icon = SETTINGS_ITEM.icon;
@@ -294,7 +423,7 @@
      {open && (
        <button
          onClick={() => setOpen(false)}
          onClick={() => setSidebarOpen(false)}
          className="fixed left-60 top-1/2 z-50 h-14 w-7 -translate-y-1/2 rounded-r-xl border border-l-0 border-gray-200 bg-white text-gray-400 shadow-sm hover:w-9 hover:text-blue-600 hover:border-blue-200 hover:bg-blue-50 flex items-center justify-center transition-all"
          title="收起侧边栏"
        >
@@ -304,7 +433,7 @@
      {!open && (
        <button
          onClick={() => setOpen(true)}
          onClick={() => setSidebarOpen(true)}
          className="fixed left-0 top-1/2 z-50 h-14 w-7 -translate-y-1/2 rounded-r-xl border border-l-0 border-gray-200 bg-white text-gray-400 shadow-sm hover:w-9 hover:text-blue-600 hover:border-blue-200 hover:bg-blue-50 flex items-center justify-center transition-all"
          title="打开侧边栏"
        >
video-claw/video-claw/frontend/components/WorkflowPanel.tsx
@@ -64,6 +64,29 @@
  return states;
}
function hasDoneArtifactItems(artifact: any): boolean {
  if (!artifact) return false;
  return ['clips', 'images', 'scenes', 'characters', 'settings'].some(key => {
    const items = artifact?.[key];
    return Array.isArray(items) && items.some((item: any) => item?.status === 'done' || item?.selected);
  });
}
function getStageProgressSnapshot(status: any, stageId: string): Partial<StageState> {
  const snapshot = status?.stage_progress?.[stageId];
  if (!snapshot || typeof snapshot !== 'object') return {};
  const progress = typeof snapshot.percent === 'number'
    ? Math.max(0, Math.min(100, Math.round(snapshot.percent)))
    : undefined;
  const progressMessage = typeof snapshot.message === 'string' && snapshot.message.trim()
    ? snapshot.message
    : (typeof snapshot.step === 'string' ? snapshot.step : undefined);
  return {
    ...(typeof progress === 'number' ? { progress } : {}),
    ...(progressMessage ? { progressMessage } : {}),
  };
}
export default function WorkflowPanel() {
  const router = useRouter();
  const searchParams = useSearchParams();
@@ -146,24 +169,20 @@
          pollRef.current = null;
          return;
        }
        // 更新进度信息(从 artifacts 中读取)
        // 更新进度信息(优先使用后端持久化的 stage_progress 快照)
        const artifacts = status.artifacts || {};
        const currentArtifact = artifacts[stageId];
        const update: Partial<StageState> = {};
        const update: Partial<StageState> = {
          status: 'running',
          ...getStageProgressSnapshot(status, stageId),
        };
        // 无论何种状态,只要有数据就更新 artifact
        if (currentArtifact) {
          update.artifact = currentArtifact;
        }
        // 始终设置状态为 running(如果尚未设置)
        const currentState = stageStates[stageId];
        if (!currentState || currentState.status === 'pending') {
          update.status = 'running';
          update.progress = 0;
        }
        if (currentArtifact) {
        if (!update.progressMessage && currentArtifact) {
          // 检查是否有已生成的参考图/视频/分镜
          const hasProgress = currentArtifact.scenes?.some((s: any) => s.versions?.length > 0) ||
                             currentArtifact.clips?.some((c: any) => c.versions?.length > 0) ||
@@ -175,7 +194,7 @@
          } else {
            update.progressMessage = '执行中...';
          }
        } else {
        } else if (!update.progressMessage) {
          update.progressMessage = '执行中...';
        }
@@ -218,10 +237,23 @@
  }, []);
  const updateStageState = (stageId: string, update: Partial<StageState>) => {
    setStageStates(prev => ({
    setStageStates(prev => {
      const current = prev[stageId];
      const nextUpdate = { ...update };
      if (
        current?.status === 'running' &&
        typeof update.progress === 'number' &&
        update.progress < (current.progress || 0) &&
        update.status !== 'completed' &&
        update.status !== 'waiting'
      ) {
        nextUpdate.progress = current.progress;
      }
      return {
      ...prev,
      [stageId]: { ...prev[stageId], ...update },
    }));
        [stageId]: { ...current, ...nextUpdate },
      };
    });
  };
  // ── 停止执行 ──
@@ -243,10 +275,7 @@
      for (const s of STAGE_ORDER) {
        if (next[s]?.status === 'running') {
          // 如果已有 artifact 数据(如部分已生成的视频片段),保留为 waiting 状态以便用户操作
          const hasArtifact = next[s]?.artifact &&
            (Array.isArray(next[s].artifact?.clips) ? next[s].artifact.clips.some((c: any) => c.status === 'done') :
             Array.isArray(next[s].artifact?.images) ? next[s].artifact.images.some((c: any) => c.status === 'done') :
             false);
          const hasArtifact = hasDoneArtifactItems(next[s]?.artifact);
          if (hasArtifact) {
            next[s] = { ...next[s], status: 'waiting', error: null, progressMessage: '已停止(保留已完成内容)' };
          } else {
@@ -267,10 +296,7 @@
                const cur = prev[s];
                if (!cur || cur.status === 'completed') return prev;
                // 检查 artifact 是否含有效内容
                const clips = artResult.artifact?.clips;
                const images = artResult.artifact?.images;
                const hasDone = (Array.isArray(clips) && clips.some((c: any) => c.status === 'done'))
                    || (Array.isArray(images) && images.some((c: any) => c.status === 'done'));
                const hasDone = hasDoneArtifactItems(artResult.artifact);
                if (hasDone) {
                  return { ...prev, [s]: { ...cur, status: 'waiting', artifact: artResult.artifact, error: null, progressMessage: '已停止(保留已完成内容)' } };
                }
@@ -407,10 +433,7 @@
              artifact = artResult?.artifact;
            } catch { /* ignore */ }
            // 如果有已完成的内容,显示为 waiting 状态
            const clips = artifact?.clips;
            const images = artifact?.images;
            const hasDone = (Array.isArray(clips) && clips.some((c: any) => c.status === 'done'))
                || (Array.isArray(images) && images.some((c: any) => c.status === 'done'));
            const hasDone = hasDoneArtifactItems(artifact);
            if (hasDone) {
              updateStageState(stageId, {
                status: 'waiting',
@@ -1027,11 +1050,20 @@
        const isWaiting = cStatus === 'waiting';
        const isStopped = cStatus === 'stopped';
        const isRunningStatus = cStatus === 'running';
        const progressSnapshot = getStageProgressSnapshot(status, sName);
        newStates[sName] = {
          status: isError ? 'error' : (isWaiting ? 'waiting' : (isStopped ? 'stopped' : (isCompleted ? 'completed' : 'running'))),
          progress: isCompleted ? 100 : 0,
          progressMessage: isError ? '执行失败' : (isWaiting ? '等待确认' : (isStopped ? '已停止' : (isCompleted ? '已完成' : (isRunningStatus ? '执行中...' : '进行中')))),
          progress: isCompleted ? 100 : (typeof progressSnapshot.progress === 'number' ? progressSnapshot.progress : 0),
          progressMessage: isError
            ? '执行失败'
            : (isWaiting
              ? '等待确认'
              : (isStopped
                ? '已停止'
                : (isCompleted
                  ? '已完成'
                  : (progressSnapshot.progressMessage || (isRunningStatus ? '执行中...' : '进行中'))))),
          artifact: status.artifacts?.[sName] || null,
          error: isError ? (status.error || '执行出错') : (isStopped ? '手动停止' : null),
        };
video-claw/video-claw/frontend/components/pipelines/PipelinePage.tsx
@@ -91,7 +91,6 @@
const DEFAULT_STANDARD_STYLE_CONTROL = STANDARD_STYLE_PRESETS[0].prompt;
const TEMPLATE_TEXT_DEFAULTS = {
  title: '山河入梦',
  text: '心之所向,素履而往',
};
@@ -385,7 +384,8 @@
function taskTitle(task: PipelineTask) {
  const input = task.input || {};
  return input.title || input.goods_title || input.text || input.prompt_text || input.goods_text || task.task_id;
  const output = task.output || {};
  return output.title || input.title || input.goods_title || input.text || input.prompt_text || input.goods_text || task.task_id;
}
type PipelineArtifact = NonNullable<PipelineTask['artifacts']>[number];
@@ -788,7 +788,6 @@
    setEnableSubtitles(true);
    setStandardVideoMode('image_concat');
    setText(current => current || TEMPLATE_TEXT_DEFAULTS.text);
    setTitleValue(current => current || TEMPLATE_TEXT_DEFAULTS.title);
    setSelectedTemplateId(current => {
      if (current && templates.some(item => item.id === current && item.ratio === ratio)) return current;
      return templates.find(item => item.ratio === ratio)?.id || current;
@@ -840,7 +839,6 @@
    setEnableSubtitles(true);
    setStandardVideoMode('image_concat');
    setText(current => current || TEMPLATE_TEXT_DEFAULTS.text);
    setTitleValue(current => current || TEMPLATE_TEXT_DEFAULTS.title);
  };
  const canSubmit = useMemo(() => {
@@ -911,6 +909,7 @@
    setRunning(true);
    setError('');
    try {
      const submittedTitle = titleValue.trim();
      const common = {
        video_model: videoModel,
        video_ratio: ratio,
@@ -922,7 +921,7 @@
        ? await startStandardPipeline({
            text,
            mode: standardMode,
            title: titleValue || undefined,
            title: submittedTitle || undefined,
            llm_model: llmModel,
            image_model: imageModel,
            video_ratio: ratio,