From 8fe160b38659aa2577b165d3884737c236e94a53 Mon Sep 17 00:00:00 2001
From: hit-cxf <2024111082@stu.hit.edu.cn>
Date: Sun, 07 Jun 2026 17:17:29 +0800
Subject: [PATCH] Added a feature for users to upload images

---
 video-claw/video-claw/frontend/components/stages/ReferenceStage.tsx |  107 ++++++-
 video-claw/video-claw/frontend/lib/workflowApi.ts                   |   22 +
 video-claw/video-claw/backend/api/routers/workflow.py               |  171 ++----------
 video-claw/video-claw/frontend/components/stages/utils.ts           |    9 
 video-claw/video-claw/frontend/components/stages/CharacterStage.tsx |  161 +++++++++---
 video-claw/video-claw/frontend/components/stages/VideoStage.tsx     |   49 ++-
 video-claw/video-claw/backend/core/orchestrator.py                  |  240 ++++++++++++++++++
 7 files changed, 545 insertions(+), 214 deletions(-)

diff --git a/video-claw/video-claw/backend/api/routers/workflow.py b/video-claw/video-claw/backend/api/routers/workflow.py
index a1cdddd..3d37017 100644
--- a/video-claw/video-claw/backend/api/routers/workflow.py
+++ b/video-claw/video-claw/backend/api/routers/workflow.py
@@ -5,7 +5,7 @@
 from datetime import datetime
 from types import SimpleNamespace
 
-from fastapi import APIRouter, HTTPException, Request
+from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
 from fastapi.responses import StreamingResponse
 
 from api.dependencies import workflow_engine
@@ -186,153 +186,40 @@
     return {"status": "ok"}
 
 
-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
-
-        input_segments = list(body.get('segments', []))
-        for ep in body.get('episodes', []):
-            if isinstance(ep, dict):
-                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
-            shots = seg.get('shots', [])
-            desc_video = " ".join([sh.get("plot") or sh.get("content") or "" for sh in shots]).strip()
-            total_dur = seg.get("total_duration") or sum([sh.get("duration", 0) for sh in shots]) or 10
-            seg_info_list.append({
-                "segment_id": seg_id,
-                "desc": desc_video,
-                "duration": total_dur,
-                "visual_prompt": seg.get("visual_prompt", ""),
-            })
-
-        video_art = state.artifacts.get('video_generation', {})
-        if isinstance(video_art, dict) and isinstance(video_art.get('clips'), list):
-            for clip in video_art['clips']:
-                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']
-
-        ref_art = state.artifacts.get('reference_generation', {})
-        if isinstance(ref_art, dict) and isinstance(ref_art.get('scenes'), list):
-            for scene in ref_art['scenes']:
-                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']
-
-        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)
-
-    elif stage == "reference_generation":
-        if "segments" in body:
-            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', {})
-            if isinstance(storyboard_art, dict):
-                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')]
-
-            ref_art = state.artifacts.get('reference_generation', {})
-            if isinstance(ref_art, dict):
-                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')]
-
-            body = {k: v for k, v in body.items() if k != "segments"}
-
-        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())
-            if is_selection_format and scenes:
-                for scene in scenes:
-                    if isinstance(scene, dict) and scene.get('id') in body:
-                        scene['selected'] = body[scene.get('id')]
-                body = {}
-
-    elif stage == "video_generation":
-        clip_id_to_duration = {}
-        clip_id_to_description = {}
-        for clip_id, value in body.items():
-            if isinstance(value, dict):
-                if 'duration' in value:
-                    clip_id_to_duration[clip_id] = value['duration']
-                if 'description' in value:
-                    clip_id_to_description[clip_id] = value['description']
-
-        if clip_id_to_duration or clip_id_to_description:
-            storyboard_art = state.artifacts.get('storyboard', {})
-            if isinstance(storyboard_art, dict):
-                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')]
-
-            vid_art = state.artifacts.get('video_generation', {})
-            if isinstance(vid_art, dict):
-                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]
-
-        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())
-            if is_selection_format and clips:
-                for clip in clips:
-                    if isinstance(clip, dict) and clip.get('id') in body:
-                        clip['selected'] = body[clip.get('id')]
-                body = {}
-
-    current = state.artifacts.get(stage)
-    if current is None:
-        state.artifacts[stage] = body
-    elif isinstance(current, dict):
-        current.update(body)
-    else:
-        state.artifacts[stage] = body
+@router.post("/api/project/{session_id}/artifact/{stage}/upload_image")
+async def upload_artifact_image(
+    session_id: str,
+    stage: str,
+    item_type: str = Form(...),
+    item_id: str = Form(...),
+    file: UploadFile = File(...),
+):
+    """Upload a user-provided image into a stage artifact and persist the session."""
+    try:
+        return workflow_engine.upload_artifact_image(
+            session_id=session_id,
+            stage=stage,
+            item_type=item_type,
+            item_id=item_id,
+            file_obj=file.file,
+            filename=file.filename or "",
+        )
+    except KeyError:
+        raise HTTPException(404, "Session not found")
+    except ValueError as exc:
+        raise HTTPException(400, detail=str(exc)) from exc
+    except RuntimeError as exc:
+        raise HTTPException(500, detail=str(exc)) from exc
 
 
 @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}
+    try:
+        return workflow_engine.update_artifact(session_id, stage, body if isinstance(body, dict) else {})
+    except KeyError:
+        raise HTTPException(404, "Session not found")
 
 
 
diff --git a/video-claw/video-claw/backend/core/orchestrator.py b/video-claw/video-claw/backend/core/orchestrator.py
index 31ce383..f25c893 100644
--- a/video-claw/video-claw/backend/core/orchestrator.py
+++ b/video-claw/video-claw/backend/core/orchestrator.py
@@ -7,6 +7,8 @@
 import json
 import logging
 import os
+import re
+import shutil
 import threading
 import time
 import copy
@@ -922,6 +924,244 @@
             "current_status": current_status,
         }
 
+    # ──────────── Artifact 统一管理 ────────────
+
+    def update_artifact(self, session_id: str, stage: str, body: Dict[str, Any]) -> Dict[str, Any]:
+        """Apply a user edit to an artifact, then recalculate and persist state."""
+        with self._state_lock:
+            state = self.get_state(session_id)
+            if not state:
+                raise KeyError(f"Session not found: {session_id}")
+
+            self._apply_artifact_update(state, stage, body if isinstance(body, dict) else {})
+            self._recalculate_all_statuses(state)
+            self.save_session_to_disk(session_id)
+            return {
+                "status": "ok",
+                "status_map": copy.deepcopy(state.status),
+                "artifact": copy.deepcopy(state.artifacts.get(stage)),
+            }
+
+    def _apply_artifact_update(self, state: WorkflowState, stage: str, body: Dict[str, Any]):
+        """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
+
+            input_segments = list(body.get('segments', []))
+            for ep in body.get('episodes', []):
+                if isinstance(ep, dict):
+                    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
+                shots = seg.get('shots', [])
+                desc_video = " ".join([sh.get("plot") or sh.get("content") or "" for sh in shots]).strip()
+                total_dur = seg.get("total_duration") or sum([sh.get("duration", 0) for sh in shots]) or 10
+                seg_info_list.append({
+                    "segment_id": seg_id,
+                    "desc": desc_video,
+                    "duration": total_dur,
+                    "visual_prompt": seg.get("visual_prompt", ""),
+                })
+
+            video_art = state.artifacts.get('video_generation', {})
+            if isinstance(video_art, dict) and isinstance(video_art.get('clips'), list):
+                for clip in video_art['clips']:
+                    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']
+
+            ref_art = state.artifacts.get('reference_generation', {})
+            if isinstance(ref_art, dict) and isinstance(ref_art.get('scenes'), list):
+                for scene in ref_art['scenes']:
+                    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']
+
+            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)
+
+        elif stage == "reference_generation":
+            if "segments" in body:
+                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', {})
+                if isinstance(storyboard_art, dict):
+                    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')]
+
+                ref_art = state.artifacts.get('reference_generation', {})
+                if isinstance(ref_art, dict):
+                    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')]
+
+                body = {k: v for k, v in body.items() if k != "segments"}
+
+            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())
+                if is_selection_format and scenes:
+                    for scene in scenes:
+                        if isinstance(scene, dict) and scene.get('id') in body:
+                            scene['selected'] = body[scene.get('id')]
+                    body = {}
+
+        elif stage == "video_generation":
+            clip_id_to_duration = {}
+            clip_id_to_description = {}
+            for clip_id, value in body.items():
+                if isinstance(value, dict):
+                    if 'duration' in value:
+                        clip_id_to_duration[clip_id] = value['duration']
+                    if 'description' in value:
+                        clip_id_to_description[clip_id] = value['description']
+
+            if clip_id_to_duration or clip_id_to_description:
+                storyboard_art = state.artifacts.get('storyboard', {})
+                if isinstance(storyboard_art, dict):
+                    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')]
+
+                vid_art = state.artifacts.get('video_generation', {})
+                if isinstance(vid_art, dict):
+                    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]
+
+            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())
+                if is_selection_format and clips:
+                    for clip in clips:
+                        if isinstance(clip, dict) and clip.get('id') in body:
+                            clip['selected'] = body[clip.get('id')]
+                    body = {}
+
+        current = state.artifacts.get(stage)
+        if current is None:
+            state.artifacts[stage] = body
+        elif isinstance(current, dict):
+            current.update(body)
+        else:
+            state.artifacts[stage] = body
+
+    def upload_artifact_image(
+        self,
+        session_id: str,
+        stage: str,
+        item_type: str,
+        item_id: str,
+        file_obj: Any,
+        filename: str = "",
+    ) -> Dict[str, Any]:
+        """Save a user-provided image and attach it to the target artifact item."""
+        allowed_exts = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}
+        ext = os.path.splitext(filename or "")[1].lower() or ".png"
+        if ext not in allowed_exts:
+            raise ValueError(f"仅支持 {', '.join(sorted(allowed_exts))} 格式的图片")
+
+        with self._state_lock:
+            state = self.get_state(session_id)
+            if not state:
+                raise KeyError(f"Session not found: {session_id}")
+
+            cfg = self._upload_item_config(stage, item_type, item_id)
+            absolute_path, relative_path = self._next_upload_path(session_id, cfg, ext)
+            try:
+                with open(absolute_path, "wb") as buffer:
+                    shutil.copyfileobj(file_obj, buffer)
+            except Exception as exc:
+                raise RuntimeError(f"图片保存失败: {exc}") from exc
+
+            artifact = state.artifacts.setdefault(stage, {})
+            items = artifact.setdefault(cfg["list_key"], [])
+            if not isinstance(items, list):
+                items = []
+                artifact[cfg["list_key"]] = items
+
+            target = next((item for item in items if isinstance(item, dict) and item.get("id") == item_id), None)
+            if target is None:
+                target = {"id": item_id, "name": item_id, "description": "", "versions": []}
+                items.append(target)
+
+            versions = target.get("versions")
+            if not isinstance(versions, list):
+                versions = []
+            if relative_path not in versions:
+                versions.append(relative_path)
+            target["versions"] = versions
+            target["selected"] = relative_path
+            target["status"] = "done"
+
+            self._recalculate_all_statuses(state)
+            self.save_session_to_disk(session_id)
+            return {
+                "status": "ok",
+                "path": relative_path,
+                "item_id": item_id,
+                "item_type": item_type,
+                "artifact": copy.deepcopy(state.artifacts.get(stage)),
+                "status_map": copy.deepcopy(state.status),
+            }
+
+    @staticmethod
+    def _upload_item_config(stage: str, item_type: str, item_id: str) -> Dict[str, str]:
+        if stage == "character_design" and item_type == "characters":
+            base = item_id if item_id.startswith("char_") else f"char_{item_id}"
+            return {"list_key": "characters", "dir": os.path.join("Assets", "characters"), "base": base}
+        if stage == "character_design" and item_type == "settings":
+            base = item_id if item_id.startswith("set_") else f"set_{item_id}"
+            return {"list_key": "settings", "dir": os.path.join("Assets", "settings"), "base": base}
+        if stage == "reference_generation" and item_type == "scenes":
+            return {"list_key": "scenes", "dir": "Scenes", "base": item_id}
+        raise ValueError("Unsupported upload target")
+
+    @staticmethod
+    def _next_upload_path(session_id: str, cfg: Dict[str, str], ext: str) -> tuple[str, str]:
+        from config import settings
+
+        save_dir = os.path.join(settings.RESULT_DIR, "image", str(session_id), cfg["dir"])
+        os.makedirs(save_dir, exist_ok=True)
+
+        pattern = re.compile(rf"^{re.escape(cfg['base'])}_upload_v(\d+)\.", re.IGNORECASE)
+        max_version = 0
+        for name in os.listdir(save_dir):
+            match = pattern.match(name)
+            if match:
+                max_version = max(max_version, int(match.group(1)))
+        version = f"v{max_version + 1}"
+        upload_filename = f"{cfg['base']}_upload_{version}{ext}"
+        absolute_path = os.path.join(save_dir, upload_filename)
+        relative_path = os.path.relpath(absolute_path, settings.BASE_DIR)
+        return absolute_path, relative_path
+
     # ──────────── 会话持久化 ────────────
 
     def save_session_to_disk(self, session_id: str, meta: Dict = None):
diff --git a/video-claw/video-claw/frontend/components/stages/CharacterStage.tsx b/video-claw/video-claw/frontend/components/stages/CharacterStage.tsx
index a31db47..ddaeb1f 100644
--- a/video-claw/video-claw/frontend/components/stages/CharacterStage.tsx
+++ b/video-claw/video-claw/frontend/components/stages/CharacterStage.tsx
@@ -1,9 +1,10 @@
 'use client';
 
 import React, { useState, useRef, useCallback, useEffect } from 'react';
-import { Users, MapPin, RefreshCw, Save, X, ChevronLeft, ChevronRight, Loader, AlertCircle, ZoomIn, ImagePlus } from 'lucide-react';
+import { Users, MapPin, RefreshCw, Save, X, ChevronLeft, ChevronRight, Loader, AlertCircle, ZoomIn, ImagePlus, Edit2, Upload } from 'lucide-react';
 import type { StageViewProps } from './types';
-import { assetUrl } from './utils';
+import { assetUrl, assetVersionLabel } from './utils';
+import { uploadArtifactImage } from '@/lib/workflowApi';
 import StageActions from './StageActions';
 import StageProgress from './StageProgress';
 import ImageLightbox from './ImageLightbox';
@@ -100,7 +101,7 @@
               <div className={`text-center text-[10px] py-0.5 ${
                 isSelected ? 'bg-violet-500 text-white font-medium' : 'bg-gray-50 text-gray-400'
               }`}>
-                v{i + 1}
+                {assetVersionLabel(path, i)}
               </div>
             </div>
           );
@@ -134,8 +135,13 @@
   onDescChange,
   onRegenerate,
   onSelectVersion,
+  onSaveEdit,
+  onCancelEdit,
+  onToggleEdit,
+  onUploadImage,
   isStageRunning,
   isRegenerating,
+  isUploading,
 }: {
   asset: AssetVersion;
   type: 'character' | 'setting';
@@ -144,8 +150,13 @@
   onDescChange: (val: string) => void;
   onRegenerate: () => void;
   onSelectVersion: (path: string) => void;
+  onSaveEdit: () => void;
+  onCancelEdit: () => void;
+  onToggleEdit: () => void;
+  onUploadImage: (file: File) => void;
   isStageRunning?: boolean;
   isRegenerating?: boolean;
+  isUploading?: boolean;
 }) {
   const isPending = asset.status === 'pending' || isRegenerating;
   const isFailed = asset.status === 'failed' && !isRegenerating;
@@ -172,16 +183,43 @@
           {isFailed && (
             <span className="text-[10px] bg-red-50 text-red-500 px-1.5 py-0.5 rounded">失败</span>
           )}
+          {!isStageRunning && (
+            isEditing ? (
+              <div className="ml-auto flex gap-1">
+                <button
+                  onClick={onCancelEdit}
+                  className="flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium text-gray-500 hover:bg-gray-100"
+                >
+                  <X className="w-3 h-3" />取消
+                </button>
+                <button
+                  onClick={onSaveEdit}
+                  className="flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium text-white bg-violet-500 hover:bg-violet-600"
+                >
+                  <Save className="w-3 h-3" />保存
+                </button>
+              </div>
+            ) : (
+              <button
+                onClick={onToggleEdit}
+                className="ml-auto flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium text-blue-600 bg-blue-50 hover:bg-blue-100 transition-colors"
+              >
+                <Edit2 className="w-3 h-3" />修改
+              </button>
+            )
+          )}
         </div>
         {isEditing ? (
           <textarea
             value={editDesc}
             onChange={e => onDescChange(e.target.value)}
             rows={5}
-            className="flex-1 text-xs text-gray-600 bg-gray-50 border border-gray-200 rounded-lg p-2 resize-none focus:outline-none focus:ring-1 focus:ring-violet-300"
+            className="h-[120px] text-xs text-gray-600 bg-gray-50 border border-gray-200 rounded-lg p-2 resize-none focus:outline-none focus:ring-1 focus:ring-violet-300"
           />
         ) : (
-          <p className="flex-1 text-xs text-gray-600 leading-relaxed">{asset.description}</p>
+          <div className="h-[120px] overflow-y-auto pr-1 custom-scrollbar">
+            <p className="text-xs text-gray-600 leading-relaxed">{asset.description}</p>
+          </div>
         )}
         {/* 已有图片显示重新生成;失败/旧数据空资源允许补生成。 */}
         {!isStageRunning && (hasImage || isFailed || canGenerateMissing) && (
@@ -199,6 +237,27 @@
             <RefreshCw className={`w-3 h-3 ${isRegenerating ? 'animate-spin' : ''}`} />
             {isRegenerating ? '生成中...' : isFailed ? '点击重试' : hasImage ? '重新生成' : '生成'}
           </button>
+        )}
+        {!isStageRunning && (
+          <label className={`mt-2 ml-auto inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
+            isUploading
+              ? 'text-gray-400 bg-gray-100 cursor-wait'
+              : 'text-gray-600 bg-gray-100 hover:bg-gray-200 cursor-pointer'
+          }`}>
+            {isUploading ? <Loader className="w-3 h-3 animate-spin" /> : <Upload className="w-3 h-3" />}
+            {isUploading ? '上传中...' : '上传图片'}
+            <input
+              type="file"
+              accept="image/*"
+              className="hidden"
+              disabled={isUploading}
+              onChange={e => {
+                const file = e.target.files?.[0];
+                e.currentTarget.value = '';
+                if (file) onUploadImage(file);
+              }}
+            />
+          </label>
         )}
       </div>
 
@@ -272,11 +331,10 @@
 }
 
 /* ─── 主组件 ─── */
-export default function CharacterStage({ state, sessionId, onConfirm, onIntervene, onRegenerate, onSaveSelections, showConfirm, isRunning, hasPendingItems, hasNextStageStarted }: StageViewProps) {
+export default function CharacterStage({ state, sessionId, onConfirm, onIntervene, onRegenerate, onUpdateArtifact, onSaveSelections, showConfirm, isRunning, hasPendingItems, hasNextStageStarted }: StageViewProps) {
   const characters: AssetVersion[] = state.artifact?.characters || [];
   const settingsData: AssetVersion[] = state.artifact?.settings || [];
 
-  const [isEditing, setIsEditing] = useState(false);
   const [editChars, setEditChars] = useState<Record<string, string>>({});
   const [editSets, setEditSets] = useState<Record<string, string>>({});
   // 跟踪前端选择的版本(覆盖后端返回的 selected)
@@ -284,6 +342,8 @@
   const [selectedSets, setSelectedSets] = useState<Record<string, string>>({});
   const [regeneratingIds, setRegeneratingIds] = useState<Set<string>>(new Set());
   const regenerationStartCounts = useRef<Record<string, number>>({});
+  const [editingIds, setEditingIds] = useState<Set<string>>(new Set());
+  const [uploadingIds, setUploadingIds] = useState<Set<string>>(new Set());
 
   const allAssets = React.useMemo(() => [...characters, ...settingsData], [characters, settingsData]);
 
@@ -309,29 +369,64 @@
 
   const hasChars = characters.length > 0;
   const hasSets = settingsData.length > 0;
-  const hasAssets = hasChars || hasSets;
 
-  const startEdit = useCallback(() => {
+  const startEdit = useCallback((id: string) => {
     const cd: Record<string, string> = {};
     characters.forEach(c => { cd[c.id] = c.description; });
     setEditChars(cd);
     const sd: Record<string, string> = {};
     settingsData.forEach(s => { sd[s.id] = s.description; });
     setEditSets(sd);
-    setIsEditing(true);
+    setEditingIds(prev => new Set(prev).add(id));
   }, [characters, settingsData]);
 
-  const cancelEdit = () => setIsEditing(false);
+  const cancelEdit = (id: string) => {
+    setEditingIds(prev => {
+      const next = new Set(prev);
+      next.delete(id);
+      return next;
+    });
+  };
 
-  const saveEdit = () => {
+  const saveEdit = (id: string) => {
     // 发送修改后的描述,后端可以用于下次生成
     onIntervene({
       update_descriptions: {
-        characters: editChars,
-        settings: editSets,
+        characters: id in editChars ? { [id]: editChars[id] } : {},
+        settings: id in editSets ? { [id]: editSets[id] } : {},
       },
     });
-    setIsEditing(false);
+    cancelEdit(id);
+  };
+
+  const handleUploadImage = async (type: 'characters' | 'settings', id: string, file: File) => {
+    setUploadingIds(prev => new Set(prev).add(id));
+    try {
+      const result = await uploadArtifactImage(sessionId, 'character_design', type, id, file);
+      const artifact = result.artifact;
+      if (artifact) {
+        onUpdateArtifact?.({
+          characters: artifact.characters || [],
+          settings: artifact.settings || [],
+        });
+      }
+      if (artifact?.characters) {
+        const char = artifact.characters.find((item: AssetVersion) => item.id === id);
+        if (char?.selected) setSelectedChars(prev => ({ ...prev, [id]: char.selected }));
+      }
+      if (artifact?.settings) {
+        const setting = artifact.settings.find((item: AssetVersion) => item.id === id);
+        if (setting?.selected) setSelectedSets(prev => ({ ...prev, [id]: setting.selected }));
+      }
+    } catch (error) {
+      console.error('上传图片失败:', error);
+    } finally {
+      setUploadingIds(prev => {
+        const next = new Set(prev);
+        next.delete(id);
+        return next;
+      });
+    }
   };
 
   const handleRegenerate = (type: 'characters' | 'settings', id: string) => {
@@ -379,26 +474,6 @@
         {/* 标题栏 */}
         <div className="flex items-center justify-between mb-1">
           <h2 className="text-lg font-semibold text-gray-800">角色 / 场景设计</h2>
-          {hasAssets && state.status === 'waiting' && !isEditing && (
-            <button
-              onClick={startEdit}
-              className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-gray-600 bg-gray-100 hover:bg-gray-200 transition-colors"
-            >
-              修改描述
-            </button>
-          )}
-          {isEditing && (
-            <div className="flex gap-2">
-              <button onClick={cancelEdit}
-                className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium text-gray-500 hover:bg-gray-100">
-                <X className="w-3.5 h-3.5" />取消
-              </button>
-              <button onClick={saveEdit}
-                className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-violet-500 hover:bg-violet-600">
-                <Save className="w-3.5 h-3.5" />保存
-              </button>
-            </div>
-          )}
         </div>
         <p className="text-sm text-gray-500 mb-6">
           生成角色4视图 (正面特写·正面全身·侧面全身·背面全身) 和场景全景图
@@ -426,13 +501,18 @@
                   key={asset.id}
                   asset={{ ...asset, selected: getCharSelected(asset) }}
                   type="character"
-                  isEditing={isEditing}
+                  isEditing={editingIds.has(asset.id)}
                   editDesc={editChars[asset.id] || asset.description}
                   onDescChange={val => setEditChars(prev => ({ ...prev, [asset.id]: val }))}
                   onRegenerate={() => handleRegenerate('characters', asset.id)}
                   onSelectVersion={path => handleSelectCharVersion(asset.id, path)}
+                  onToggleEdit={() => startEdit(asset.id)}
+                  onSaveEdit={() => saveEdit(asset.id)}
+                  onCancelEdit={() => cancelEdit(asset.id)}
+                  onUploadImage={file => handleUploadImage('characters', asset.id, file)}
                   isStageRunning={state.status === 'running'}
                   isRegenerating={regeneratingIds.has(asset.id)}
+                  isUploading={uploadingIds.has(asset.id)}
                 />
               ))}
             </div>
@@ -452,13 +532,18 @@
                   key={asset.id}
                   asset={{ ...asset, selected: getSetSelected(asset) }}
                   type="setting"
-                  isEditing={isEditing}
+                  isEditing={editingIds.has(asset.id)}
                   editDesc={editSets[asset.id] || asset.description}
                   onDescChange={val => setEditSets(prev => ({ ...prev, [asset.id]: val }))}
                   onRegenerate={() => handleRegenerate('settings', asset.id)}
                   onSelectVersion={path => handleSelectSetVersion(asset.id, path)}
+                  onToggleEdit={() => startEdit(asset.id)}
+                  onSaveEdit={() => saveEdit(asset.id)}
+                  onCancelEdit={() => cancelEdit(asset.id)}
+                  onUploadImage={file => handleUploadImage('settings', asset.id, file)}
                   isStageRunning={state.status === 'running'}
                   isRegenerating={regeneratingIds.has(asset.id)}
+                  isUploading={uploadingIds.has(asset.id)}
                 />
               ))}
             </div>
@@ -475,8 +560,6 @@
         status={state.status}
         onConfirm={onConfirm}
         showConfirm={showConfirm}
-        onEdit={startEdit}
-        onSave={isEditing ? saveEdit : undefined}
         onRegenerate={onRegenerate}
         stageId="character_design"
         hasPendingItems={hasPendingItems}
diff --git a/video-claw/video-claw/frontend/components/stages/ReferenceStage.tsx b/video-claw/video-claw/frontend/components/stages/ReferenceStage.tsx
index 82e9f34..3422b31 100644
--- a/video-claw/video-claw/frontend/components/stages/ReferenceStage.tsx
+++ b/video-claw/video-claw/frontend/components/stages/ReferenceStage.tsx
@@ -1,9 +1,10 @@
 'use client';
 
 import React, { useState, useRef, useEffect } from 'react';
-import { Image as ImageIcon, RefreshCw, ChevronLeft, ChevronRight, Loader, AlertCircle, ZoomIn, ImagePlus, Edit2, Save } from 'lucide-react';
+import { Image as ImageIcon, RefreshCw, ChevronLeft, ChevronRight, Loader, AlertCircle, ZoomIn, ImagePlus, Edit2, Save, X, Upload } from 'lucide-react';
 import type { StageViewProps } from './types';
-import { assetUrl } from './utils';
+import { assetUrl, assetVersionLabel } from './utils';
+import { uploadArtifactImage } from '@/lib/workflowApi';
 import StageActions from './StageActions';
 import StageProgress from './StageProgress';
 import ImageLightbox from './ImageLightbox';
@@ -100,7 +101,7 @@
               <div className={`text-center text-[10px] py-0.5 ${
                 isSelected ? 'bg-emerald-500 text-white font-medium' : 'bg-gray-50 text-gray-400'
               }`}>
-                v{i + 1}
+                {assetVersionLabel(path, i)}
               </div>
             </div>
           );
@@ -140,6 +141,9 @@
   onToggleEdit,
   getSelected,
   allowMissingGenerate,
+  onCancelEdit,
+  onUploadImage,
+  isUploading,
 }: {
   scene: SceneItem;
   canEdit: boolean;
@@ -154,6 +158,9 @@
   onToggleEdit?: () => void;
   getSelected: (scene: SceneItem) => string;
   allowMissingGenerate?: boolean;
+  onCancelEdit?: () => void;
+  onUploadImage: (file: File) => void;
+  isUploading?: boolean;
 }) {
   const isRunning = scene.status === 'running' || isRegenerating;
   const isPending = scene.status === 'pending';
@@ -167,7 +174,7 @@
       isFailed ? 'border-red-200' : 'border-gray-200'
     }`}>
       {/* 左侧: 提示词 */}
-      <div className="w-full xl:w-[360px] xl:flex-shrink-0 p-4 border-b xl:border-b-0 xl:border-r border-gray-100 flex flex-col">
+      <div className="w-full xl:w-80 xl:flex-shrink-0 p-4 border-b xl:border-b-0 xl:border-r border-gray-100 flex flex-col">
         <div className="flex items-center gap-2 mb-2">
           <span className="flex items-center justify-center h-6 px-1.5 rounded-full bg-emerald-100 text-emerald-700 text-[10px] font-bold flex-shrink-0 whitespace-nowrap">
             {scene.index ?? scene.id.replace('Scene_', '')}
@@ -187,18 +194,26 @@
           {/* 编辑/保存按钮 */}
           {canEdit && !isStageRunning && (
             isEditing ? (
-              <button
-                onClick={onSavePrompt}
-                disabled={!hasChanges}
-                className={`ml-auto flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium transition-colors ${
-                  hasChanges
-                    ? 'text-white bg-emerald-500 hover:bg-emerald-600'
-                    : 'text-gray-400 bg-gray-100 cursor-not-allowed'
-                }`}
-              >
-                <Save className="w-3 h-3" />
-                保存
-              </button>
+              <div className="ml-auto flex gap-1">
+                <button
+                  onClick={onCancelEdit}
+                  className="flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium text-gray-500 hover:bg-gray-100"
+                >
+                  <X className="w-3 h-3" />取消
+                </button>
+                <button
+                  onClick={onSavePrompt}
+                  disabled={!hasChanges}
+                  className={`flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium transition-colors ${
+                    hasChanges
+                      ? 'text-white bg-emerald-500 hover:bg-emerald-600'
+                      : 'text-gray-400 bg-gray-100 cursor-not-allowed'
+                  }`}
+                >
+                  <Save className="w-3 h-3" />
+                  保存
+                </button>
+              </div>
             ) : (
               <button
                 onClick={onToggleEdit}
@@ -214,11 +229,11 @@
           <textarea
             value={editDesc}
             onChange={e => onDescChange(e.target.value)}
-            rows={6}
-            className="h-[180px] text-xs text-gray-600 bg-gray-50 border border-gray-200 rounded-lg p-2 resize-none focus:outline-none focus:ring-1 focus:ring-emerald-300"
+            rows={5}
+            className="h-[120px] text-xs text-gray-600 bg-gray-50 border border-gray-200 rounded-lg p-2 resize-none focus:outline-none focus:ring-1 focus:ring-emerald-300"
           />
         ) : (
-          <div className="h-[180px] overflow-y-auto pr-1 custom-scrollbar">
+          <div className="h-[120px] overflow-y-auto pr-1 custom-scrollbar">
             <p className="text-xs text-gray-600 leading-relaxed whitespace-pre-wrap">{scene.description}</p>
           </div>
         )}
@@ -238,6 +253,27 @@
             <RefreshCw className={`w-3 h-3 ${isRegenerating ? 'animate-spin' : ''}`} />
             {isRegenerating ? '生成中...' : isFailed ? '点击重试' : hasImage ? '重新生成' : '生成'}
           </button>
+        )}
+        {!isStageRunning && (
+          <label className={`mt-2 ml-auto inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
+            isUploading
+              ? 'text-gray-400 bg-gray-100 cursor-wait'
+              : 'text-gray-600 bg-gray-100 hover:bg-gray-200 cursor-pointer'
+          }`}>
+            {isUploading ? <Loader className="w-3 h-3 animate-spin" /> : <Upload className="w-3 h-3" />}
+            {isUploading ? '上传中...' : '上传图片'}
+            <input
+              type="file"
+              accept="image/*"
+              className="hidden"
+              disabled={isUploading}
+              onChange={e => {
+                const file = e.target.files?.[0];
+                e.currentTarget.value = '';
+                if (file) onUploadImage(file);
+              }}
+            />
+          </label>
         )}
       </div>
 
@@ -318,6 +354,7 @@
   const regenerationStartCounts = useRef<Record<string, number>>({});
   const [editingIds, setEditingIds] = useState<Set<string>>(new Set());
   const [savingIds, setSavingIds] = useState<Set<string>>(new Set());
+  const [uploadingIds, setUploadingIds] = useState<Set<string>>(new Set());
 
   // 提取剧集标题映射
   const episodeTitleMap = React.useMemo(() => {
@@ -454,6 +491,35 @@
     });
   };
 
+  const handleCancelEdit = (sceneId: string) => {
+    const scene = scenes.find(item => item.id === sceneId);
+    setEditDescs(prev => ({ ...prev, [sceneId]: scene?.description || '' }));
+    setEditingIds(prev => {
+      const next = new Set(prev);
+      next.delete(sceneId);
+      return next;
+    });
+  };
+
+  const handleUploadImage = async (sceneId: string, file: File) => {
+    setUploadingIds(prev => new Set(prev).add(sceneId));
+    try {
+      const result = await uploadArtifactImage(sessionId, 'reference_generation', 'scenes', sceneId, file);
+      if (result.artifact?.scenes) {
+        onUpdateArtifact?.({ scenes: result.artifact.scenes });
+      }
+      setSelectedVersions(prev => ({ ...prev, [sceneId]: result.path }));
+    } catch (error) {
+      console.error('上传图片失败:', error);
+    } finally {
+      setUploadingIds(prev => {
+        const next = new Set(prev);
+        next.delete(sceneId);
+        return next;
+      });
+    }
+  };
+
   const handleRegenerate = (sceneId: string) => {
     const scene = scenes.find(item => item.id === sceneId);
     regenerationStartCounts.current[sceneId] = scene?.versions?.length || 0;
@@ -547,9 +613,12 @@
                             isRegenerating={regeneratingIds.has(scene.id)}
                             isEditing={editingIds.has(scene.id)}
                             onToggleEdit={() => handleToggleEdit(scene.id)}
+                            onCancelEdit={() => handleCancelEdit(scene.id)}
                             canEdit={canEdit}
                             getSelected={getSelected}
                             allowMissingGenerate={state.status !== 'pending'}
+                            onUploadImage={file => handleUploadImage(scene.id, file)}
+                            isUploading={uploadingIds.has(scene.id)}
                           />
                         </div>
                       ))}
diff --git a/video-claw/video-claw/frontend/components/stages/VideoStage.tsx b/video-claw/video-claw/frontend/components/stages/VideoStage.tsx
index 2e1c8fa..bf5e475 100644
--- a/video-claw/video-claw/frontend/components/stages/VideoStage.tsx
+++ b/video-claw/video-claw/frontend/components/stages/VideoStage.tsx
@@ -1,7 +1,7 @@
 'use client';
 
 import React, { useState, useRef, useCallback, useEffect } from 'react';
-import { Film, RefreshCw, ChevronLeft, ChevronRight, Loader, AlertCircle, AlertTriangle, Play, Volume2, VolumeX, Clapperboard, Edit2, Save } from 'lucide-react';
+import { Film, RefreshCw, ChevronLeft, ChevronRight, Loader, AlertCircle, AlertTriangle, Play, Volume2, VolumeX, Clapperboard, Edit2, Save, X } from 'lucide-react';
 import type { StageViewProps } from './types';
 import { assetUrl } from './utils';
 import StageActions from './StageActions';
@@ -124,6 +124,7 @@
   onRegenerate,
   onSelectVersion,
   onToggleEdit,
+  onCancelEdit,
   isStageRunning,
   isRegenerating,
   isEditing,
@@ -139,6 +140,7 @@
   onRegenerate: () => void;
   onSelectVersion: (path: string) => void;
   onToggleEdit?: () => void;
+  onCancelEdit?: () => void;
   isStageRunning?: boolean;
   isRegenerating?: boolean;
   isEditing?: boolean;
@@ -159,7 +161,7 @@
       isFailed ? 'border-red-200' : 'border-gray-200'
     }`}>
       {/* 左侧: 描述信息 */}
-      <div className="w-full xl:w-72 xl:flex-shrink-0 p-4 border-b xl:border-b-0 xl:border-r border-gray-100 flex flex-col">
+      <div className="w-full xl:w-80 xl:flex-shrink-0 p-4 border-b xl:border-b-0 xl:border-r border-gray-100 flex flex-col">
         <div className="flex items-center gap-2 mb-2">
           <span className="flex items-center justify-center h-6 px-1.5 rounded-full bg-rose-100 text-rose-700 text-[10px] font-bold flex-shrink-0 whitespace-nowrap">
             {clip.index ?? clip.id.replace('Scene_', '')}
@@ -182,18 +184,26 @@
           {/* 编辑/保存按钮 */}
           {canEdit && !isStageRunning && (
             isEditing ? (
-              <button
-                onClick={onSavePrompt}
-                disabled={!hasChanges || isSaving}
-                className={`ml-auto flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium transition-colors ${
-                  hasChanges && !isSaving
-                    ? 'text-white bg-emerald-500 hover:bg-emerald-600'
-                    : 'text-gray-400 bg-gray-100 cursor-not-allowed'
-                }`}
-              >
-                <Save className="w-3 h-3" />
-                {isSaving ? '保存中' : '保存'}
-              </button>
+              <div className="ml-auto flex gap-1">
+                <button
+                  onClick={onCancelEdit}
+                  className="flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium text-gray-500 hover:bg-gray-100"
+                >
+                  <X className="w-3 h-3" />取消
+                </button>
+                <button
+                  onClick={onSavePrompt}
+                  disabled={!hasChanges || isSaving}
+                  className={`flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium transition-colors ${
+                    hasChanges && !isSaving
+                      ? 'text-white bg-emerald-500 hover:bg-emerald-600'
+                      : 'text-gray-400 bg-gray-100 cursor-not-allowed'
+                  }`}
+                >
+                  <Save className="w-3 h-3" />
+                  {isSaving ? '保存中' : '保存'}
+                </button>
+              </div>
             ) : (
               <button
                 onClick={onToggleEdit}
@@ -463,6 +473,16 @@
     });
   };
 
+  const handleCancelEdit = (clipId: string) => {
+    const clip = clips.find(item => item.id === clipId);
+    setEditDescs(prev => ({ ...prev, [clipId]: clip?.description || '' }));
+    setEditingIds(prev => {
+      const next = new Set(prev);
+      next.delete(clipId);
+      return next;
+    });
+  };
+
   const handleRegenerate = (clipId: string) => {
     const clip = clips.find(c => c.id === clipId);
     regenerationStartCounts.current[clipId] = clip?.versions?.length ?? 0;
@@ -615,6 +635,7 @@
                               onRegenerate={() => handleRegenerate(clip.id)}
                               onSelectVersion={path => handleSelectVersion(clip.id, path)}
                               onToggleEdit={() => handleToggleEdit(clip.id)}
+                              onCancelEdit={() => handleCancelEdit(clip.id)}
                               isStageRunning={state.status === 'running'}
                               isRegenerating={regeneratingIds.has(clip.id)}
                               isEditing={editingIds.has(clip.id)}
diff --git a/video-claw/video-claw/frontend/components/stages/utils.ts b/video-claw/video-claw/frontend/components/stages/utils.ts
index 8ef6f9e..78f88d0 100644
--- a/video-claw/video-claw/frontend/components/stages/utils.ts
+++ b/video-claw/video-claw/frontend/components/stages/utils.ts
@@ -11,6 +11,15 @@
   return '/' + path;
 }
 
+export function assetVersionLabel(path: string, index: number): string {
+  const file = (path || '').split('/').pop() || '';
+  const uploadMatch = file.match(/_upload_(v\d+)/i);
+  if (uploadMatch) return `用户上传: ${uploadMatch[1].toLowerCase()}`;
+  const aiMatch = file.match(/_v(\d+)\.[^.]+$/i);
+  const version = aiMatch ? `v${aiMatch[1]}` : `v${index + 1}`;
+  return `AI生成: ${version}`;
+}
+
 /* ─── 剧本 / 分镜 结构化文本解析 ─── */
 
 export interface ParsedCharacter {
diff --git a/video-claw/video-claw/frontend/lib/workflowApi.ts b/video-claw/video-claw/frontend/lib/workflowApi.ts
index a090eda..ee8b2f4 100644
--- a/video-claw/video-claw/frontend/lib/workflowApi.ts
+++ b/video-claw/video-claw/frontend/lib/workflowApi.ts
@@ -222,6 +222,28 @@
   return resp.json();
 }
 
+export async function uploadArtifactImage(
+  sessionId: string,
+  stage: string,
+  itemType: string,
+  itemId: string,
+  file: File,
+): Promise<{ status: string; path: string; artifact: any; status_map: Record<string, string> }> {
+  const formData = new FormData();
+  formData.append('item_type', itemType);
+  formData.append('item_id', itemId);
+  formData.append('file', file);
+  const resp = await fetch(`/api/project/${sessionId}/artifact/${stage}/upload_image`, {
+    method: 'POST',
+    body: formData,
+  });
+  if (!resp.ok) {
+    const err = await resp.json().catch(() => ({ detail: '上传图片失败' }));
+    throw new Error(err.detail || '上传图片失败');
+  }
+  return resp.json();
+}
+
 export function subscribePipelineTask(
   taskId: string,
   onEvent: (event: PipelineTaskEvent) => void,

--
Gitblit v1.8.0