hit-cxf
2026-05-13 0c05477d19b9df8aa6aed137927ba85312e12941
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
import asyncio
import json
import queue
import threading
import time
from typing import Any, AsyncIterator, Callable, Dict, Optional
 
from fastapi import Request
 
from core.orchestrator import WorkflowStage
 
STAGE_NAME_MAP = {
    "script_generation": "剧本生成",
    "character_design": "角色/场景设计",
    "storyboard": "分镜设计",
    "reference_generation": "参考图生成",
    "video_generation": "视频生成",
    "post_production": "后期剪辑",
}
 
 
def inject_user_selections(state, stage: str, data: dict):
    """Inject persisted user choices into downstream stage input."""
    if stage == 'video_generation' and 'selected_images' not in data:
        ref_art = state.artifacts.get('reference_generation', {})
        if isinstance(ref_art, dict):
            scenes = ref_art.get('scenes', [])
            selected_images = {s['id']: s['selected'] for s in scenes
                              if isinstance(s, dict) and s.get('id') and s.get('selected')}
            if selected_images:
                data['selected_images'] = selected_images
 
    if stage == 'video_generation' and 'clips' not in data:
        vid_art = state.artifacts.get('video_generation', {})
        if isinstance(vid_art, dict):
            clips = vid_art.get('clips', [])
            if clips:
                data['clips'] = clips
 
    if stage == 'post_production' and 'selected_clips' not in data:
        vid_art = state.artifacts.get('video_generation', {})
        if isinstance(vid_art, dict):
            clips = vid_art.get('clips', [])
            selected_clips = {c['id']: c['selected'] for c in clips
                             if isinstance(c, dict) and c.get('id') and c.get('selected')}
            if selected_clips:
                data['selected_clips'] = selected_clips
 
 
 
def build_openclaw_message(stage: str, result: Dict[str, Any]) -> str:
    openclaw_msg = result.get("openclaw_hint", "")
    if not openclaw_msg and result.get("requires_intervention", False):
        stage_name = STAGE_NAME_MAP.get(stage, stage)
        openclaw_msg = f"{stage_name}完成,需要用户确认。请展示给用户并等待用户确认后才能调用 /continue。"
    return openclaw_msg
 
 
def make_progress_channel():
    progress_events = queue.Queue()
    event_trigger = asyncio.Event()
 
    def progress_callback(phase, step, percent, data=None):
        event = {"phase": phase, "step": step, "percent": percent}
        if data:
            event["data"] = data
        progress_events.put(event)
        try:
            loop = asyncio.get_running_loop()
            loop.call_soon_threadsafe(event_trigger.set)
        except RuntimeError:
            pass
 
    return progress_events, event_trigger, progress_callback
 
 
def serialize_progress_event(progress: Dict[str, Any]) -> str:
    event = {
        "type": "progress",
        "message": f"{progress['phase']}: {progress['step']}",
        "phase": progress["phase"],
        "step_desc": progress["step"],
        "percent": progress["percent"],
    }
    if progress.get("data"):
        event["data"] = progress["data"]
    return json.dumps(event) + "\n"
 
 
async def stream_workflow_task(
    *,
    request: Request,
    workflow_engine,
    state,
    stage: str,
    input_data: Dict[str, Any],
    cancellation_check: Callable[[], bool],
    progress_callback: Callable[..., None],
    progress_events,
    event_trigger: asyncio.Event,
    intervention: Optional[Dict[str, Any]] = None,
    include_payload_summary: bool = False,
    on_disconnect: Optional[Callable[[], None]] = None,
) -> AsyncIterator[str]:
    stage_enum = WorkflowStage(stage)
 
    try:
        task = asyncio.create_task(
            workflow_engine.execute_stage(
                state,
                stage_enum,
                input_data,
                cancellation_check=cancellation_check,
                progress_callback=progress_callback,
                intervention=intervention,
            )
        )
 
        while not task.done():
            try:
                await asyncio.wait_for(event_trigger.wait(), timeout=15.0)
            except asyncio.TimeoutError:
                yield json.dumps({"type": "heartbeat", "time": time.time()}) + "\n"
 
            event_trigger.clear()
 
            while not progress_events.empty():
                try:
                    yield serialize_progress_event(progress_events.get_nowait())
                except queue.Empty:
                    break
 
            if await request.is_disconnected():
                if on_disconnect:
                    on_disconnect()
                yield json.dumps({"type": "error", "content": "Client disconnected"}) + "\n"
                return
 
        while not progress_events.empty():
            try:
                yield serialize_progress_event(progress_events.get_nowait())
                await asyncio.sleep(0)
            except queue.Empty:
                break
 
        result = task.result()
        workflow_engine.save_session_to_disk(state.session_id)
 
        payload = {
            "type": "stage_complete",
            "stage": stage,
            "status": state.status,
            "requires_intervention": result.get("requires_intervention", False),
            "openclaw": build_openclaw_message(stage, result),
        }
        if include_payload_summary:
            payload["payload_summary"] = result.get("payload")
        yield json.dumps(payload) + "\n"
 
    except Exception as e:
        try:
            workflow_engine.save_session_to_disk(state.session_id)
        except Exception:
            pass
        yield json.dumps({"type": "error", "content": str(e)}) + "\n"
 
 
def make_cancellation(workflow_engine, session_id: str):
    workflow_engine.reset_stop_event(session_id)
    session_stop = workflow_engine.get_stop_event(session_id)
    request_stop = threading.Event()
    return lambda: request_stop.is_set() or session_stop.is_set(), request_stop.set