log
2026-06-25 7c4c956be0c3c4c2f76f181e356779003bc8f998
video-claw/video-claw/frontend/components/WorkflowPanel.tsx
@@ -72,6 +72,39 @@
  });
}
function hasRunningArtifactItems(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 === 'running');
  });
}
function mergeAssetVersions(current?: string[], incoming?: string[]): string[] {
  const merged: string[] = [];
  [...(Array.isArray(current) ? current : []), ...(Array.isArray(incoming) ? incoming : [])].forEach(path => {
    if (path && !merged.includes(path)) merged.push(path);
  });
  return merged;
}
function mergeAssetUpdateItem(item: any, assetUpdate: any): any {
  const hasExistingSelection = Boolean(item?.selected);
  const nextStatus = hasExistingSelection && ['done', 'failed'].includes(assetUpdate.status)
    ? 'done'
    : (assetUpdate.status ?? item.status);
  return {
    ...item,
    status: nextStatus,
    selected: hasExistingSelection
      ? item.selected
      : (assetUpdate.selected || item.selected),
    versions: assetUpdate.versions
      ? mergeAssetVersions(item.versions, assetUpdate.versions)
      : item.versions,
  };
}
function getStageProgressSnapshot(status: any, stageId: string): Partial<StageState> {
  const snapshot = status?.stage_progress?.[stageId];
  if (!snapshot || typeof snapshot !== 'object') return {};
@@ -98,28 +131,36 @@
  const [history, setHistory] = useState<HistoryItem[]>([]);
  const [projectParams, setProjectParams] = useState<ProjectParams | null>(null);
  const [autoMode, setAutoMode] = useState(false);
  const [videoSound, setVideoSound] = useState('on');
  const [videoShotType, setVideoShotType] = useState('multi');
  // 用于顶栏流程图状态判断
  const [currentStageFromSession, setCurrentStageFromSession] = useState<string | null>(null);
  const [completedStagesFromSession, setCompletedStagesFromSession] = useState<string[]>([]);
  const abortRef = useRef<AbortController | null>(null);
  const stoppedRef = useRef(false);
  const pollRef = useRef<string | null>(null);
  const autoModeRef = useRef(autoMode);
  const pollRef = useRef<Set<string>>(new Set());
  useEffect(() => {
    autoModeRef.current = autoMode;
  }, [autoMode]);
  const handleAutoModeChange = useCallback((nextAutoMode: boolean) => {
    autoModeRef.current = nextAutoMode;
    setAutoMode(nextAutoMode);
  }, []);
  // 清理轮询
  useEffect(() => {
    return () => { pollRef.current = null; };
    return () => { pollRef.current.clear(); };
  }, []);
  // 轮询等待后端阶段完成。运行中优先读后端内存,后端重启后再回退到磁盘快照。
  const pollForCompletion = useCallback(async (sid: string, stageId: string) => {
    const key = `${sid}:${stageId}`;
    pollRef.current = key;
    pollRef.current.add(key);
    for (let i = 0; i < 300; i++) {  // 增加轮询次数(最多10分钟)
      await new Promise(r => setTimeout(r, 2000));
      if (pollRef.current !== key) return;
      if (!pollRef.current.has(key)) return;
      try {
        let status: any;
        try {
@@ -127,11 +168,14 @@
        } catch {
          status = await getProjectStatusFromDisk(sid);
        }
        if (pollRef.current !== key) return;
        if (!pollRef.current.has(key)) return;
        setGlobalStatusMap(status.status || {});
        const done = Object.keys(status.status || {}).filter(k => ["completed", "session_completed"].includes(status.status[k]));
        const currentStageStatus = status.status?.[stageId] || 'idle';
        if (done.includes(stageId)) {
        const artifacts = status.artifacts || {};
        const currentArtifact = artifacts[stageId];
        const hasRunningItems = hasRunningArtifactItems(currentArtifact);
        if (done.includes(stageId) && !hasRunningItems) {
          const isWait = currentStageStatus === 'waiting' && status.current_stage === stageId;
          let artifact = null;
          try { artifact = (await getArtifact(sid, stageId)).artifact; } catch {}
@@ -141,35 +185,43 @@
            progressMessage: isWait ? '等待确认' : '已完成',
            artifact,
          });
          pollRef.current = null;
          pollRef.current.delete(key);
          return;
        }
        if (currentStageStatus === 'error') {
        if (currentStageStatus === 'error' && !hasRunningItems) {
          updateStageState(stageId, {
            status: 'error',
            error: status.error || '执行出错',
            progressMessage: '执行失败',
          });
          pollRef.current = null;
          pollRef.current.delete(key);
          return;
        }
        if (currentStageStatus === 'stopped') {
        if (currentStageStatus === 'stopped' && !hasRunningItems) {
          updateStageState(stageId, {
            status: 'stopped',
            error: '手动停止',
            progressMessage: '已停止',
          });
          pollRef.current = null;
          pollRef.current.delete(key);
          return;
        }
        // 如果当前阶段不再是 running,提前停止轮询(比如变成了 waiting_intervention 或已完成)
        if (currentStageStatus !== 'running') {
          pollRef.current = null;
        // 后台单卡重生成时,阶段状态可能仍是 waiting/completed;只要 item 还在 running 就继续轮询。
        if (currentStageStatus !== 'running' && !hasRunningItems) {
          updateStageState(stageId, {
            status: currentStageStatus === 'waiting'
              ? 'waiting'
              : (done.includes(stageId) ? 'completed' : 'pending'),
            progress: done.includes(stageId) ? 100 : undefined,
            progressMessage: currentStageStatus === 'waiting'
              ? '等待确认'
              : (done.includes(stageId) ? '已完成' : undefined),
            artifact: currentArtifact || null,
          });
          pollRef.current.delete(key);
          return;
        }
        // 更新进度信息(优先使用后端持久化的 stage_progress 快照)
        const artifacts = status.artifacts || {};
        const currentArtifact = artifacts[stageId];
        const update: Partial<StageState> = {
          status: 'running',
          ...getStageProgressSnapshot(status, stageId),
@@ -201,6 +253,7 @@
        }
      } catch { /* retry */ }
    }
    pollRef.current.delete(key);
  }, []);
  // 检查 URL 参数,加载指定的 session 和阶段
@@ -338,12 +391,7 @@
              const items = [...(prevArt[key] || [])];
              const idx = items.findIndex((item: any) => item.id === assetUpdate.id);
              if (idx >= 0) {
                items[idx] = {
                  ...items[idx],
                  status: assetUpdate.status,
                  selected: assetUpdate.selected || items[idx].selected,
                  versions: assetUpdate.versions || items[idx].versions,
                };
                items[idx] = mergeAssetUpdateItem(items[idx], assetUpdate);
              }
              return {
                ...prev,
@@ -468,7 +516,7 @@
    if (isRunning) return;
    stoppedRef.current = false;
    const useAutoMode = autoOverride !== undefined ? autoOverride : autoMode;
    if (autoOverride !== undefined) setAutoMode(autoOverride);
    if (autoOverride !== undefined) handleAutoModeChange(autoOverride);
    setIsRunning(true);
    setStageStates(initStageStates());
    setProjectParams(params);
@@ -484,6 +532,10 @@
        vlm_model: params.vlm_model,
        image_t2i_model: params.image_t2i_model,
        image_it2i_model: params.image_it2i_model,
        video_generation_mode: params.video_generation_mode,
        video_first_frame_model: params.video_first_frame_model,
        video_start_end_model: params.video_start_end_model,
        video_reference_model: params.video_reference_model,
        video_model: params.video_model,
        enable_concurrency: params.enable_concurrency,
        web_search: params.web_search,
@@ -515,6 +567,10 @@
        vlm_model: params.vlm_model,
        image_t2i_model: params.image_t2i_model,
        image_it2i_model: params.image_it2i_model,
        video_generation_mode: params.video_generation_mode,
        video_first_frame_model: params.video_first_frame_model,
        video_start_end_model: params.video_start_end_model,
        video_reference_model: params.video_reference_model,
        video_model: params.video_model,
        scene_number: result.params?.scene_number,
        expand_idea: params.expand_idea,
@@ -544,7 +600,7 @@
        // waiting: 等待用户介入(如选择角色/图片),不能自动 continue
        // completed: 阶段完成,等待确认进入下一阶段
        if (stageStatus === 'completed' || stageStatus === 'session_completed') {
          if (useAutoMode) {
          if (autoModeRef.current) {
            // 代理模式:自动确认并继续
            await continueWorkflow(result.session_id);
            updateStageState(stageId, { status: 'completed', progressMessage: '已自动确认' });
@@ -598,11 +654,15 @@
          vlm_model: projectParams?.vlm_model,
          image_t2i_model: projectParams?.image_t2i_model,
          image_it2i_model: projectParams?.image_it2i_model,
          video_generation_mode: projectParams?.video_generation_mode,
          video_first_frame_model: projectParams?.video_first_frame_model,
          video_start_end_model: projectParams?.video_start_end_model,
          video_reference_model: projectParams?.video_reference_model,
          video_model: projectParams?.video_model,
          video_ratio: projectParams?.video_ratio,
          video_resolution: projectParams?.video_resolution,
          video_sound: videoSound,
          video_shot_type: videoShotType,
          video_sound: 'on',
          video_shot_type: 'multi',
        };
        // 从剧本产物获取实际场景数
        try {
@@ -651,7 +711,7 @@
          // waiting: 等待用户介入(如选择角色/图片),不能自动 continue
          // completed: 阶段完成,等待确认进入下一阶段,可以自动 continue
          if (nStageStatus === 'completed' || nStageStatus === 'session_completed') {
            if (autoMode) {
            if (autoModeRef.current) {
              await continueWorkflow(sessionId);
              updateStageState(nextStage, { status: 'completed', progressMessage: '已自动确认' });
              setCompletedStagesFromSession(prev => [...prev, nextStage]);
@@ -682,6 +742,13 @@
  // ── 用户介入修改 ──
  const handleIntervene = async (stageId: string, modifications: Record<string, any>) => {
    if (!sessionId) return;
    const isBackgroundItemRegeneration =
      (stageId === 'character_design' && (
        Array.isArray(modifications.regenerate_characters) ||
        Array.isArray(modifications.regenerate_settings)
      )) ||
      (stageId === 'reference_generation' && Array.isArray(modifications.regenerate_scenes)) ||
      (stageId === 'video_generation' && Array.isArray(modifications.regenerate_clips));
    
    // 构建完整的 inputData 传给后端,确保比例等参数能传递
    const inputData: Record<string, any> = {
@@ -694,7 +761,13 @@
      vlm_model: projectParams?.vlm_model,
      image_t2i_model: projectParams?.image_t2i_model,
      image_it2i_model: projectParams?.image_it2i_model,
      video_generation_mode: projectParams?.video_generation_mode,
      video_first_frame_model: projectParams?.video_first_frame_model,
      video_start_end_model: projectParams?.video_start_end_model,
      video_reference_model: projectParams?.video_reference_model,
      video_model: projectParams?.video_model,
      video_sound: 'on',
      video_shot_type: 'multi',
    };
    // 设置 running 状态以便显示进度条(如 Logline 选择后生成剧本)
@@ -705,16 +778,22 @@
      : modifications.selected_mode
        ? { phase: 'generating', selected_logline: stageStates[stageId]?.artifact?.selected_logline }
        : undefined;
    setIsRunning(true);
    updateStageState(stageId, { status: 'running', progress: 0, progressMessage: '处理中...', ...(artifactPatch ? { artifact: artifactPatch } : {}) });
    if (!isBackgroundItemRegeneration) {
      setIsRunning(true);
      updateStageState(stageId, { status: 'running', progress: 0, progressMessage: '处理中...', ...(artifactPatch ? { artifact: artifactPatch } : {}) });
    } else if (artifactPatch) {
      updateStageState(stageId, { artifact: artifactPatch });
    }
    try {
      const response = await intervene(sessionId, stageId, inputData);
      for await (const event of parseStreamEvents(response)) {
        if (event.type === 'progress') {
          updateStageState(stageId, {
            progress: event.percent || 0,
            progressMessage: event.message || '',
          });
          if (!isBackgroundItemRegeneration) {
            updateStageState(stageId, {
              progress: event.percent || 0,
              progressMessage: event.message || '',
            });
          }
          // 处理 asset_complete 实时事件
          if (event.data?.asset_complete) {
            const assetUpdate = event.data.asset_complete;
@@ -725,12 +804,7 @@
              const items = [...(prevArt[key] || [])];
              const idx = items.findIndex((item: any) => item.id === assetUpdate.id);
              if (idx >= 0) {
                items[idx] = {
                  ...items[idx],
                  status: assetUpdate.status,
                  selected: assetUpdate.selected || items[idx].selected,
                  versions: assetUpdate.versions || items[idx].versions,
                };
                items[idx] = mergeAssetUpdateItem(items[idx], assetUpdate);
              }
              return {
                ...prev,
@@ -790,7 +864,11 @@
          }
        } else if (event.type === 'stage_complete') {
          const artResult = await getArtifact(sessionId, stageId);
          updateStageState(stageId, { artifact: artResult.artifact, status: 'waiting' });
          if (isBackgroundItemRegeneration) {
            updateStageState(stageId, { artifact: artResult.artifact });
          } else {
            updateStageState(stageId, { artifact: artResult.artifact, status: 'waiting' });
          }
        } else if (event.type === 'error') {
          console.error('Intervention error:', event.content);
        }
@@ -798,7 +876,9 @@
    } catch (error: any) {
      console.error('Intervention error:', error);
    } finally {
      setIsRunning(false);
      if (!isBackgroundItemRegeneration) {
        setIsRunning(false);
      }
    }
  };
@@ -826,8 +906,17 @@
        // 剧本阶段:直接保存整个 data 覆盖 artifact
        patch = selections;
      } else if (stageId === 'character_design') {
        const chars = (art.characters || []).map((c: any) => ({ ...c, selected: selections[c.id] || c.selected }));
        const sets = (art.settings || []).map((s: any) => ({ ...s, selected: selections[s.id] || s.selected }));
        const { _editDescs, ...restSelections } = selections;
        const chars = (art.characters || []).map((c: any) => ({
          ...c,
          selected: restSelections[c.id] || c.selected,
          description: _editDescs?.characters?.[c.id] ?? c.description,
        }));
        const sets = (art.settings || []).map((s: any) => ({
          ...s,
          selected: restSelections[s.id] || s.selected,
          description: _editDescs?.settings?.[s.id] ?? s.description,
        }));
        patch = { characters: chars, settings: sets };
      } else if (stageId === 'storyboard') {
        // 分镜阶段:保存 shots 数据(排除 original_shots,只保留 artifact 需要的字段)
@@ -972,6 +1061,10 @@
        vlm_model: projectParams?.vlm_model,
        image_t2i_model: projectParams?.image_t2i_model,
        image_it2i_model: projectParams?.image_it2i_model,
        video_generation_mode: projectParams?.video_generation_mode,
        video_first_frame_model: projectParams?.video_first_frame_model,
        video_start_end_model: projectParams?.video_start_end_model,
        video_reference_model: projectParams?.video_reference_model,
        video_model: projectParams?.video_model,
        video_ratio: projectParams?.video_ratio,
        video_resolution: projectParams?.video_resolution,
@@ -1078,6 +1171,8 @@
      const meta = ((status as any).meta || {}) as any;
      const s = Object.keys(meta).length > 0 ? meta : (status as any);
      if (s.idea || s.user_textbox_input) {
        // Legacy session compatibility: old sessions only stored one video_model, so hydrate it as the first-frame model.
        const restoredFirstFrameVideoModel = s.video_first_frame_model || s.video_model || '';
        setProjectParams({
          idea: s.idea || s.user_textbox_input || '',
          style: s.style || '',
@@ -1087,6 +1182,10 @@
          vlm_model: s.vlm_model || '',
          image_t2i_model: s.image_t2i_model || '',
          image_it2i_model: s.image_it2i_model || '',
          video_generation_mode: s.video_generation_mode || 'first_frame',
          video_first_frame_model: restoredFirstFrameVideoModel,
          video_start_end_model: s.video_start_end_model || 'wan2.7-i2v',
          video_reference_model: s.video_reference_model || 'wan2.7-r2v',
          video_model: s.video_model || '',
          expand_idea: s.expand_idea || false,
          enable_concurrency: s.enable_concurrency || false,
@@ -1102,9 +1201,11 @@
      setActiveStage(finalStage);
      setStageStates(newStates);
      // 轮询当前正在执行的阶段(仅当该阶段有 artifact 数据时)
      if (currentStage && stMap[currentStage] === 'running') {
        pollForCompletion(sid, currentStage);
      // 轮询正在执行的阶段;后台单卡重生成时阶段可能不是 running,但 item 会是 running。
      for (const stageId of STAGE_ORDER) {
        if (stMap[stageId] === 'running' || hasRunningArtifactItems(status.artifacts?.[stageId])) {
          pollForCompletion(sid, stageId);
        }
      }
    } catch {
      setActiveStage(STAGE_ORDER[0]);
@@ -1148,6 +1249,11 @@
        vlm_model: projectParams.vlm_model,
        image_t2i_model: projectParams.image_t2i_model,
        image_it2i_model: projectParams.image_it2i_model,
        // Legacy session compatibility: projectParams may come from an old session with only video_model.
        video_generation_mode: projectParams.video_generation_mode || 'first_frame',
        video_first_frame_model: projectParams.video_first_frame_model || projectParams.video_model,
        video_start_end_model: projectParams.video_start_end_model || 'wan2.7-i2v',
        video_reference_model: projectParams.video_reference_model || 'wan2.7-r2v',
        video_model: projectParams.video_model,
        video_ratio: projectParams.video_ratio,
        video_resolution: projectParams.video_resolution || '720P',
@@ -1181,7 +1287,7 @@
  }
  // ── 计算项目状态 ──
  // 后端状态: pending, running, waiting, completed, completed, error
  // 后端阶段状态: pending, running, waiting, completed, stopped, error
  // 前端 StageStatus: pending, running, waiting, completed, error
  const hasRunning = Object.values(stageStates).some(s => s.status === 'running');
  const hasWaiting = Object.values(stageStates).some(s => s.status === 'waiting');
@@ -1266,12 +1372,6 @@
        isRunning={effectiveIsRunning}
        hasPendingItems={hasPendingItems}
        hasNextStageStarted={hasNextStageStarted}
        videoSound={videoSound}
        videoShotType={videoShotType}
        onVideoParamsChange={(params: { videoSound?: string; videoShotType?: string }) => {
          if (params.videoSound !== undefined) setVideoSound(params.videoSound);
          if (params.videoShotType !== undefined) setVideoShotType(params.videoShotType);
        }}
        referenceArtifact={referenceArtifact}
        scriptArtifact={scriptArtifact}
        artifacts={Object.keys(stageStates).reduce((acc: any, key) => {
@@ -1295,7 +1395,7 @@
        isRunning={effectiveIsRunning}
        onStop={handleStop}
        autoMode={autoMode}
        onAutoModeChange={setAutoMode}
        onAutoModeChange={handleAutoModeChange}
        modelConfig={modelConfig}
        onModelConfigChange={handleModelConfigChange}
        projectStatus={projectStatus}