"""主服务 WorkflowExecutor → 看板桥接。

progress_callback 事件转换为 model_agent 事件并发送给 DashboardServer;
桥接异常仅记录日志,看板故障不影响执行。
WORKFLOW_DASHBOARD_ENABLED=false 关闭。PARALLEL 子步骤展开为独立节点
(`{parent_id}::{sub_id}`),心跳翻译为 node.log,用户可见正文实时映射为 node.output。
"""

from __future__ import annotations

import asyncio
import logging
import re
import time
import uuid
from functools import wraps
from typing import Any

from app.model_agent.workflow.capability_events import clip
from app.model_agent.workflow.schemas import EdgeDef, NodeDef, WorkflowDef
from app.services.command_dashboard import command_category_metadata
from app.services.execution_outcome import (
    TerminalOutcome,
    classify_terminal_outcome,
    explicit_failure_output,
)
from app.tools.workflow.types import ExecutionContext, StepStatus, WorkflowPlan, WorkflowStep

logger = logging.getLogger(__name__)

SUB_SEP = "::"
_LIVE_OUTPUT_MIN_INTERVAL = 0.1
_LIVE_OUTPUT_TARGET_CHARS_PER_SECOND = 20_000


def _background_report(method):
    @wraps(method)
    async def report(self, *args, **kwargs):
        if self._server_ready():
            server = self._server
            from app.model_agent.dashboard.server import DashboardServer

            if isinstance(server, DashboardServer):
                def deliver():
                    task = asyncio.create_task(method(self, *args, **kwargs))
                    task.add_done_callback(_report_done)

                if server.dispatch_report(deliver):
                    return None
        return await method(self, *args, **kwargs)
    return report


def _report_done(task):
    if not task.cancelled() and task.exception() is not None:
        logger.warning("Dashboard background reporting failed: %s", task.exception())


def _step_node(
    s: WorkflowStep,
    *,
    id_override: str | None = None,
    label: str | None = None,
    type_override: str | None = None,
    c_id: str = "",
) -> NodeDef:
    metadata: dict[str, Any] = {
        "description": s.description,
        **command_category_metadata("workflow"),
    }
    if c_id:
        # Keep the chat session identity beside direct-workflow nodes so a
        # later natural-language continuation can be grouped with this run.
        metadata["c_id"] = c_id
    if s.type.value == "condition" and s.condition_expression:
        metadata["condition_expression"] = s.condition_expression
    if s.type.value == "loop":
        metadata["loop_max"] = s.loop_max_iterations
    return NodeDef(
        id=id_override or s.id,
        label=label or s.name,
        type=type_override or s.type.value,
        metadata=metadata,
        checklist=[],
        capability=s.skill_name,
    )


def _execution_anchor(nodes: list[NodeDef]) -> NodeDef | None:
    """Connect execution to the latest input in the same task graph."""
    for node in reversed(nodes):
        if node.type == "user_input":
            return node
    return next((node for node in nodes if node.type == "task"), None) or next(
        (node for node in nodes if node.type == "topic_root"), None
    )


def _dependency_relation(node_type: str | None) -> str:
    """Describe ordering only; a condition result does not gate its successors."""
    return {
        "condition": "判断完成后",
        "parallel": "并行完成后",
    }.get(node_type or "", "完成后")


def plan_to_def(plan: WorkflowPlan, c_id: str = "") -> WorkflowDef:
    """WorkflowPlan → 看板 WorkflowDef(与 model_agent to_def 同构)。

    depends_on 即 DAG 边;PARALLEL 子步骤展开为独立节点(id 加父前缀,
    边从父节点连出)。checklist 留空(主服务步骤无 todo 概念)。
    """
    nodes: list[NodeDef] = []
    edges: list[EdgeDef] = []
    step_types = {step.id: step.type.value for step in plan.steps}
    for s in plan.steps:
        nodes.append(_step_node(s, c_id=c_id))
        edges.extend(EdgeDef(
            from_id=dep, to_id=s.id,
            condition=_dependency_relation(step_types.get(dep)),
        ) for dep in s.depends_on)
        if s.type.value == "parallel" and s.parallel_steps:
            for sub in s.parallel_steps:
                nodes.append(_step_node(
                    sub,
                    id_override=f"{s.id}{SUB_SEP}{sub.id}",
                    label=sub.name,
                    c_id=c_id,
                ))
                edges.append(EdgeDef(from_id=s.id, to_id=f"{s.id}{SUB_SEP}{sub.id}", condition="并行"))
    return WorkflowDef(
        workflow_id=plan.workflow_id,
        name=plan.goal or plan.intent or "workflow",
        nodes=nodes,
        edges=edges,
    )


class DashboardBridge:
    """懒启动看板并转发进度事件;未启用/启动失败时全部方法为 no-op。"""

    def __init__(self) -> None:
        self._server: Any = None
        self._wf_id: str | None = None
        self._finished = False  # 终帧只发一次;二次收尾直接返回
        self._c_id: str = ""
        # 保留 _name_to_id 兼容旧调试/测试调用;路由使用完整候选表。
        self._name_to_id: dict[str, str] = {}
        self._name_to_ids: dict[str, list[str]] = {}  # step 名 → 节点 id 候选
        self._last_active_id: str | None = None  # 最近 step_start 的节点,路由 miss 时回退
        self._started_ids: set[str] = set()  # 已发过 node.started 的节点,防重复
        self._parent_to_subs: dict[str, list[str]] = {}  # parallel 父节点 → 子节点(按声明序)
        self._terminal_ids: set[str] = set()  # 已发过终态的节点,终态不可逆
        self._skipped_ids: set[str] = set()
        self._tool_call_to_node: dict[str, str] = {}
        self._node_labels: dict[str, str] = {}
        self._node_types: dict[str, str] = {}
        self._live_outputs: dict[str, list[str]] = {}
        self._live_output_chars: dict[str, int] = {}
        self._live_output_emitted_chars: dict[str, int] = {}
        self._live_output_last_emitted_at: dict[str, float] = {}
        self._planning_node_id: str | None = None
        self._planning_workflow_id: str | None = None
        self._definition: WorkflowDef | None = None

    def _own_definition(self) -> WorkflowDef | None:
        """只读取本任务的图;并发切换画布后仍使用本桥接持有的定义。"""
        current = getattr(self._server, "_workflow_def", None)
        if isinstance(current, WorkflowDef) and current.workflow_id == self._wf_id:
            return current
        return self._definition if self._definition is not None and self._definition.workflow_id == self._wf_id else None

    def _chat_def_from_run(self, chat_run) -> WorkflowDef | None:
        """find_chat_run 返回 get_run 快照(nodes 是 dict),从 server 直接读原始 def。"""
        chat_def = chat_run.get("workflow_def")
        if isinstance(chat_def, WorkflowDef):
            return chat_def
        # get_run 快照 nodes 是 dict,从 server 读原始 WorkflowDef
        wid = chat_run.get("workflow_id")
        current = getattr(self._server, "_workflow_def", None)
        if current is not None and current.workflow_id == wid:
            return current
        inactive = getattr(self._server, "_inactive_runs", {}).get(wid)
        if inactive:
            return inactive.get("workflow_def")
        return None

    def _merge_chat_context(self, workflow_def: WorkflowDef) -> WorkflowDef | None:
        """引擎直连路径 set_workflow_def 前,把同 c_id 的 chat 历史节点并入新图。

        chat run 是当前画布时返回 None(由 attach 走 append 分支);
        已归档或找不到时也返回 None(走原 set_workflow_def)。
        """
        if not self._c_id or self._server is None:
            return None
        find_chat_run = getattr(self._server, "find_chat_run", None)
        if not callable(find_chat_run):
            return None
        chat_run = find_chat_run(self._c_id)
        if chat_run is None:
            return None
        chat_def = self._chat_def_from_run(chat_run)
        if chat_def is None:
            return None
        # chat run 仍是当前画布:不复制节点,让 attach 走 append 分支
        current_def = getattr(self._server, "_workflow_def", None)
        if current_def is not None and current_def.workflow_id == chat_def.workflow_id:
            return None
        existing_ids = {node.id for node in workflow_def.nodes}
        extra_nodes = [node for node in chat_def.nodes if node.id not in existing_ids]
        if not extra_nodes:
            return None
        existing_edges = {(edge.from_id, edge.to_id) for edge in workflow_def.edges}
        all_node_ids = existing_ids | {n.id for n in extra_nodes}
        extra_edges = [
            edge for edge in chat_def.edges
            if (edge.from_id, edge.to_id) not in existing_edges
            and edge.from_id in all_node_ids
            and edge.to_id in all_node_ids
        ]
        bridge_edges = []
        entry_steps = [n for n in workflow_def.nodes if not any(
            edge.to_id == n.id for edge in workflow_def.edges
        )]
        anchor = _execution_anchor(extra_nodes)
        if anchor and entry_steps:
            bridge_edges = [
                EdgeDef(from_id=anchor.id, to_id=step.id, condition="开始执行")
                for step in entry_steps
            ]
        root_label = next((n.label for n in chat_def.nodes if n.type == "topic_root"), None)
        run_name = root_label or workflow_def.name
        return WorkflowDef(
            workflow_id=workflow_def.workflow_id,
            name=run_name,
            nodes=[*workflow_def.nodes, *extra_nodes],
            edges=[*workflow_def.edges, *extra_edges, *bridge_edges],
        )

    def _append_to_chat_run(self, workflow_def: WorkflowDef) -> WorkflowDef | None:
        """chat run 是当前画布时,把执行步骤追加进去,返回合并后的 def。"""
        if not self._c_id or self._server is None:
            return None
        find_chat_run = getattr(self._server, "find_chat_run", None)
        if not callable(find_chat_run):
            return None
        chat_run = find_chat_run(self._c_id)
        if chat_run is None:
            return None
        chat_def = self._chat_def_from_run(chat_run)
        if chat_def is None:
            return None
        # 本桥接自身的规划 run 不算 chat run,防自匹配
        if self._planning_workflow_id is not None \
                and chat_def.workflow_id == self._planning_workflow_id:
            return None
        # chat run 必须与 plan 不同 id,防 workflow run 自匹配
        if chat_def.workflow_id == workflow_def.workflow_id:
            return None
        if not any(n.type == "topic_root" for n in chat_def.nodes):
            return None
        current_def = getattr(self._server, "_workflow_def", None)
        if current_def is None or current_def.workflow_id != chat_def.workflow_id:
            return None
        anchor = _execution_anchor(chat_def.nodes)
        entry_steps = [
            n for n in workflow_def.nodes
            if not any(edge.to_id == n.id for edge in workflow_def.edges)
        ]
        approve_edges = []
        if anchor and entry_steps:
            approve_edges = [
                EdgeDef(from_id=anchor.id, to_id=step.id, condition="开始执行")
                for step in entry_steps
            ]
        merged = WorkflowDef(
            workflow_id=chat_def.workflow_id,
            name=chat_def.name,
            nodes=[*chat_def.nodes, *workflow_def.nodes],
            edges=[*chat_def.edges, *workflow_def.edges, *approve_edges],
        )
        return merged

    def _server_ready(self) -> bool:
        if self._server is not None:
            return True
        from app.model_agent.dashboard.runtime import dashboard_server_or_none

        # 与其他看板入口同一开关;关闭时仅停用看板,主对话照常执行。
        server = dashboard_server_or_none()
        if server is None:
            return False
        start = getattr(server, "start_background", server.start)
        task = asyncio.get_running_loop().create_task(start())
        task.add_done_callback(_report_done)
        self._server = server
        return True

    @_background_report
    async def start_planning(
        self, workflow_id: str, intent: str, c_id: str | None = None,
    ) -> None:
        """Publish a visible planning node before the workflow LLM returns."""
        if not self._server_ready():
            return
        try:
            self._c_id = str(c_id or "")
            chat_def = None
            if self._c_id:
                find_chat_run = getattr(self._server, "find_chat_run", None)
                if callable(find_chat_run):
                    chat_run = find_chat_run(self._c_id)
                    if chat_run is not None:
                        candidate = self._chat_def_from_run(chat_run)
                        current = getattr(self._server, "_workflow_def", None)
                        if (
                            candidate is not None
                            and current is not None
                            and candidate.workflow_id == current.workflow_id
                            and any(node.type == "topic_root" for node in candidate.nodes)
                            and all(
                                node.metadata.get("kind") in {
                                    "problem", "problem_execution", "supplement",
                                    "approval", "rejection", "resume", "retry",
                                    "continuation", "problem_repeat", "semantic_step",
                                    "agent_event", "turn", "internal_operation",
                                    "tool_call",
                                }
                                for node in candidate.nodes
                            )
                        ):
                            chat_def = candidate
            self._wf_id = chat_def.workflow_id if chat_def is not None else workflow_id
            node_id = f"planning-{uuid.uuid4().hex[:12]}"
            root = NodeDef(
                id=node_id,
                label="分析并规划工作流",
                type="task" if chat_def is not None else "topic_root",
                metadata={
                    **command_category_metadata("workflow"),
                    "kind": "semantic_step" if chat_def is not None else "problem",
                    "title_source": "user_input",
                    "description": intent,
                    **({"c_id": self._c_id} if self._c_id else {}),
                },
            )
            anchor = _execution_anchor(chat_def.nodes) if chat_def is not None else None
            self._definition = WorkflowDef(
                workflow_id=self._wf_id,
                name=chat_def.name if chat_def is not None else intent or "workflow",
                nodes=[*chat_def.nodes, root] if chat_def is not None else [root],
                edges=[*chat_def.edges, EdgeDef(
                    from_id=anchor.id, to_id=node_id, condition="规划工作流",
                )] if chat_def is not None and anchor is not None else [],
            )
            if chat_def is not None:
                self._server.append_workflow_nodes(self._definition)
            else:
                self._server.set_workflow_def(self._definition)
            self._planning_node_id = node_id
            self._planning_workflow_id = workflow_id
            self._node_labels = {node_id: root.label}
            self._node_types = {node_id: root.type}
            self._push("workflow.started", None, {"status": "running"})
            self._push("node.started", node_id, {
                "status": "running",
                "input_snapshot": intent,
                "graph_only": True,
                "source": "user_input",
            })
        except Exception as exc:
            self._planning_node_id = None
            self._planning_workflow_id = None
            logger.warning("Dashboard planning start failed: %s", exc)

    @_background_report
    async def attach(
        self, plan: WorkflowPlan, c_id: str | None = None, *, resume: bool = False,
    ) -> None:
        """下发计划并建立路由表;续跑时保留同一工作流的历史状态。"""
        if not self._server_ready():
            return
        try:
            planning_node_id = (
                self._planning_node_id
                if self._planning_workflow_id == plan.workflow_id
                else None
            )
            self._wf_id = (
                self._definition.workflow_id
                if planning_node_id and self._definition is not None
                else plan.workflow_id
            )
            self._c_id = str(c_id or "")
            workflow_def = plan_to_def(plan, c_id=self._c_id)
            restored = False
            if (
                resume and callable(getattr(self._server, "get_run", None))
                and self._server.get_run(plan.workflow_id) is not None
            ):
                self._server.activate_run(plan.workflow_id)
                current_def = self._own_definition()
                restored = current_def is not None and current_def.workflow_id == plan.workflow_id
                if restored:
                    existing_ids = {node.id for node in current_def.nodes}
                    missing_nodes = [node for node in workflow_def.nodes if node.id not in existing_ids]
                    if missing_nodes:
                        missing_ids = {node.id for node in missing_nodes}
                        missing_edges = [
                            edge for edge in workflow_def.edges
                            if edge.from_id in missing_ids or edge.to_id in missing_ids
                        ]
                        workflow_def = WorkflowDef(
                            workflow_id=plan.workflow_id, name=current_def.name,
                            nodes=[*current_def.nodes, *missing_nodes],
                            edges=[*current_def.edges, *missing_edges],
                        )
                        self._server.append_workflow_nodes(workflow_def)
                    else:
                        workflow_def = current_def
            if planning_node_id:
                current_def = self._own_definition()
                root = next(
                    (node for node in getattr(current_def, "nodes", [])
                     if node.id == planning_node_id),
                    None,
                )
                if root is None:
                    planning_node_id = None
                else:
                    roots = [step.id for step in plan.steps if not step.depends_on]
                    planning_edges = [
                        EdgeDef(from_id=planning_node_id, to_id=step_id, condition="规划完成")
                        for step_id in roots
                    ]
                    workflow_def = WorkflowDef(
                        workflow_id=current_def.workflow_id,
                        name=current_def.name,
                        nodes=[*current_def.nodes, *workflow_def.nodes],
                        edges=[*current_def.edges, *workflow_def.edges, *planning_edges],
                    )
                    self._server.append_workflow_nodes(workflow_def)
            if not restored and not planning_node_id:
                appended = self._append_to_chat_run(workflow_def)
                if appended is not None:
                    # 追加进现有 chat run:bridge 归属切换到 chat run id
                    self._wf_id = appended.workflow_id
                    self._server.append_workflow_nodes(appended)
                    workflow_def = appended
                else:
                    merged = self._merge_chat_context(workflow_def)
                    if merged is not None:
                        self._server.set_workflow_def(merged)
                        workflow_def = merged
                    else:
                        self._server.set_workflow_def(workflow_def)
            self._definition = workflow_def
            name_map: dict[str, list[str]] = {}
            parent_to_subs: dict[str, list[str]] = {}
            for s in plan.steps:
                name_map.setdefault(s.name, []).append(s.id)
                if s.type.value == "parallel" and s.parallel_steps:
                    parent_to_subs[s.id] = [f"{s.id}{SUB_SEP}{sub.id}" for sub in s.parallel_steps]
                    for sub in s.parallel_steps:
                        name_map.setdefault(sub.name, []).append(f"{s.id}{SUB_SEP}{sub.id}")
            self._name_to_ids = name_map
            self._name_to_id = {name: ids[0] for name, ids in name_map.items() if ids}
            self._node_labels = {
                node.id: node.label for node in workflow_def.nodes
            }
            self._node_types = {
                node.id: node.type for node in workflow_def.nodes
            }
            self._parent_to_subs = parent_to_subs
            if planning_node_id:
                self._push("node.completed", planning_node_id, {
                    "status": "success",
                    "output_summary": f"已生成 {len(plan.steps)} 个执行步骤",
                    "output_full": plan.goal or plan.intent or "工作流规划完成",
                    "graph_only": True,
                })
            else:
                # 总耗时口径与引擎一致:前端 workflowStartedAt 以此为起点
                self._push("workflow.started", None, {"status": "running"})
            self._planning_node_id = None
            self._planning_workflow_id = None
            if resume and not restored:
                for step in plan.steps:
                    if step.status == StepStatus.COMPLETED:
                        result = str(step.result) if step.result is not None else ""
                        self._push("node.completed", step.id, {
                            "status": "success", "output_summary": result[:500],
                            "output_full": result,
                        })
                        self._terminal_ids.add(step.id)
                        self._propagate_parallel_terminal(step.id, "completed", None)
                    elif step.status == StepStatus.SKIPPED:
                        self._push("node.completed", step.id, {"status": "skipped"})
                        self._terminal_ids.add(step.id)
                        for sub_id in self._parent_to_subs.get(step.id, []):
                            self._push("node.completed", sub_id, {"status": "skipped"})
                            self._terminal_ids.add(sub_id)
                    elif step.status == StepStatus.FAILED:
                        error = step.error or "执行失败"
                        outcome = classify_terminal_outcome(error, "failed")
                        self._push("node.failed", step.id, {
                            **outcome.event_fields(), "error": error,
                        })
                        self._terminal_ids.add(step.id)
                        self._propagate_parallel_terminal(
                            step.id, "failed", error,
                            terminal_status=outcome.status, outcome=outcome,
                        )
        except Exception as exc:
            logger.warning("Dashboard attach failed: %s", exc)

    def _route(self, event: dict[str, Any]) -> str | None:
        """事件 → 节点 id。

        同名步骤可能并行运行,不能再用一个 name→id 覆盖。优先使用事件中的
        id/parent_id/call_id,其次选仍活跃的最近候选;无法证明归属时才回退
        最近活跃节点,并留一条告警,避免静默错配。
        """
        nid = event.get("id")
        if nid:
            return nid
        call_id = str(event.get("call_id") or "")
        if call_id and call_id in self._tool_call_to_node:
            return self._tool_call_to_node[call_id]
        name = event.get("step")
        candidates = list(self._name_to_ids.get(name, []))
        parent_id = event.get("parent_id")
        if parent_id:
            descendants = [c for c in candidates if c == parent_id or c.startswith(f"{parent_id}{SUB_SEP}")]
            if descendants:
                candidates = descendants
        active = [c for c in candidates if c in self._started_ids and c not in self._terminal_ids]
        if active:
            if self._last_active_id in active:
                return self._last_active_id
            return active[-1]
        if len(candidates) == 1:
            return candidates[0]
        if len(candidates) > 1:
            logger.warning("Ambiguous dashboard step route name=%r candidates=%s", name, candidates)
        return self._last_active_id

    @_background_report
    async def on_progress(self, event: dict[str, Any]) -> None:
        """progress_callback 事件 → 看板 WorkflowEvent。"""
        if self._server is None or self._wf_id is None:
            return
        try:
            kind = event.get("event")
            if kind == "plan_updated":
                await self._handle_plan_updated(event)
                return
            if kind == "tool_event":
                nid = self._route(event)
                if not nid:
                    return
                self._emit_live_output(nid, force=True)
                etype = {"started": "tool.started", "failed": "tool.failed"}.get(
                    event.get("phase"), "tool.completed")
                data: dict[str, Any] = {"tool": event.get("tool", "")}
                if event.get("args_summary"):
                    args_summary = str(event["args_summary"])
                    data["arguments_summary"] = clip(args_summary, 500)
                    if len(args_summary) > 500 and event.get("args_full") is None:
                        data["arguments_full"] = clip(args_summary)
                if event.get("args_full") is not None:
                    data["arguments_full"] = clip(str(event["args_full"]))
                if event.get("result_summary"):
                    result_summary = str(event["result_summary"])
                    data["result_summary"] = clip(result_summary, 500)
                    if len(result_summary) > 500 and event.get("result_full") is None:
                        data["result_full"] = clip(result_summary)
                if event.get("result_full") is not None:
                    data["result_full"] = clip(str(event["result_full"]))
                if event.get("error"):
                    data["error"] = clip(str(event["error"]), 500)
                if event.get("error_full") is not None:
                    data["error_full"] = clip(str(event["error_full"]))
                if event.get("elapsed_ms") is not None:
                    data["elapsed_ms"] = event["elapsed_ms"]
                call_id = str(event.get("call_id") or "")
                # Keep the stable call identity in the wire event as well as
                # the in-process routing table.  The frontend uses it to
                # collapse mirrored lifecycle frames and to keep parallel
                # tool results attached to the right step.
                if call_id:
                    data["call_id"] = call_id
                if call_id and event.get("phase") == "started":
                    self._tool_call_to_node[call_id] = nid
                elif call_id and event.get("phase") in ("completed", "failed"):
                    self._tool_call_to_node.pop(call_id, None)
                self._push(etype, nid, data)
                return
            if kind == "step_output":
                nid = self._route(event)
                output_kind = event.get("kind")
                if nid and output_kind == "output":
                    if nid not in self._started_ids:
                        self._started_ids.add(nid)
                        if nid != self._last_active_id:
                            self._push("node.started", nid, {"status": "running"})
                    chunk = str(event.get("chunk", ""))
                    if event.get("reset"):
                        self._live_outputs[nid] = [chunk]
                        self._live_output_chars[nid] = len(chunk)
                        self._live_output_emitted_chars[nid] = 0
                    else:
                        self._live_outputs.setdefault(nid, []).append(chunk)
                        self._live_output_chars[nid] = self._live_output_chars.get(nid, 0) + len(chunk)
                    self._push("node.output.chunk", nid, {
                        "output_chunk": chunk,
                        "output_reset": bool(event.get("reset")),
                    })
                    self._emit_live_output(nid, force=bool(event.get("reset")))
                # progress=心跳;无 kind=兼容旧 agent 文本流,同入日志
                elif nid and output_kind in ("progress", None):
                    # PARALLEL 子步骤无独立生命周期事件(start/end 发在父步骤),首个心跳视作其开始的最佳近似。
                    if nid not in self._started_ids:
                        self._started_ids.add(nid)
                        if nid != self._last_active_id:
                            self._push("node.started", nid, {"status": "running"})
                    line = str(event.get("chunk", "")).strip()
                    if line:
                        data: dict[str, Any] = {"log_line": line}
                        if event.get("loop_iteration") is not None:
                            data["loop_iteration"] = event["loop_iteration"]
                        self._push("node.log", nid, data)
                elif nid and output_kind == "activity":
                    # 内部活动不形成可见日志,只补齐尚未发出的用户正文快照。
                    self._emit_live_output(nid, force=True)
                return
            nid = self._route(event)
            if not nid:
                return
            if kind == "step_start":
                first_start = nid not in self._started_ids
                self._started_ids.add(nid)
                self._last_active_id = nid
                if first_start and nid not in self._terminal_ids:
                    payload = {"status": "running"}
                    if event.get("input_snapshot") is not None:
                        payload["input_snapshot"] = clip(str(event["input_snapshot"]))
                    self._push("node.started", nid, payload)
            elif kind == "step_end":
                self._emit_live_output(nid, force=True)
                self._live_outputs.pop(nid, None)
                self._live_output_chars.pop(nid, None)
                self._live_output_emitted_chars.pop(nid, None)
                self._live_output_last_emitted_at.pop(nid, None)
                status = event.get("status")
                elapsed = event.get("elapsed_ms")
                if status == "completed":
                    # output_full is the already filtered agent result returned by
                    # the execution pattern. Keep the compact preview for cards
                    # and timeline rows, while retaining the full result for the
                    # selected node's detail panel.
                    output_full = event.get("output_full")
                    if output_full is None:
                        output_full = event.get("result_full")
                    if output_full is None:
                        output_full = event.get("result")
                    output_summary = event.get("result_preview") or f"result_len={event.get('result_len', 0)}"
                    if self._node_types.get(nid) == "condition":
                        raw_condition = str(output_full if output_full is not None else output_summary).strip().lower()
                        if raw_condition in {"true", "false"}:
                            output_summary = _condition_result_summary(
                                self._node_labels.get(nid, event.get("step", nid)),
                                raw_condition == "true",
                            )
                            output_full = output_summary
                    explicit_failure = explicit_failure_output(output_full, output_summary)
                    if explicit_failure:
                        outcome = classify_terminal_outcome(explicit_failure, "failed")
                        payload = {
                            **outcome.event_fields(),
                            "error": explicit_failure,
                            "error_full": explicit_failure,
                            "output_summary": output_summary,
                        }
                        if output_full is not None:
                            payload["output_full"] = str(output_full)
                        if elapsed is not None:
                            payload["elapsed_ms"] = elapsed
                        self._push("node.failed", nid, payload)
                        self._terminal_ids.add(nid)
                        self._propagate_parallel_terminal(
                            nid, "failed", explicit_failure, event.get("failed_indices"),
                            terminal_status=outcome.status, outcome=outcome,
                        )
                        return
                    payload: dict[str, Any] = {
                        "status": "success",
                        # result_preview 优先(实际产出预览);旧事件源无此字段时回退 result_len
                        "output_summary": output_summary,
                    }
                    if output_full is not None:
                        payload["output_full"] = str(output_full)
                    if elapsed is not None:
                        payload["elapsed_ms"] = elapsed
                    self._push("node.completed", nid, payload)
                    self._terminal_ids.add(nid)
                    self._propagate_parallel_terminal(nid, "completed", None)
                elif status == "failed":
                    error = str(event.get("error", "unknown"))
                    outcome = classify_terminal_outcome(error, "failed")
                    payload = {
                        **outcome.event_fields(),
                        "error": error,
                        "error_full": error,
                    }
                    if elapsed is not None:
                        payload["elapsed_ms"] = elapsed
                    self._push("node.failed", nid, payload)
                    self._terminal_ids.add(nid)
                    self._propagate_parallel_terminal(
                        nid, "failed", error, event.get("failed_indices"),
                        terminal_status=outcome.status,
                        outcome=outcome,
                    )
            elif kind == "step_retry":
                # 重试中:状态回 running + 日志行;retry_count 随帧折叠进节点状态(前端 ↻N 徽标数据源)。
                self._push("node.log", nid, {
                    "log_line": f"第 {event.get('attempt')} 次重试: {event.get('error', '')}",
                    "retry_count": event.get("attempt"),
                })
        except Exception as exc:
            logger.warning("Dashboard on_progress failed: %s", exc)

    def _emit_live_output(self, nid: str, *, force: bool = False) -> None:
        """Emit bounded cumulative snapshots while chunks stream separately."""
        parts = self._live_outputs.get(nid)
        output_chars = self._live_output_chars.get(nid, 0)
        emitted_chars = self._live_output_emitted_chars.get(nid, 0)
        if not parts or output_chars <= emitted_chars:
            return
        now = time.monotonic()
        min_interval = max(
            _LIVE_OUTPUT_MIN_INTERVAL,
            output_chars / _LIVE_OUTPUT_TARGET_CHARS_PER_SECOND,
        )
        if not force and now - self._live_output_last_emitted_at.get(nid, 0.0) < min_interval:
            return
        full = "".join(parts)
        self._push("node.output", nid, {
            "output_summary": full[-500:],
            "output_full": full,
        })
        self._live_output_emitted_chars[nid] = output_chars
        self._live_output_last_emitted_at[nid] = now

    def _propagate_parallel_terminal(
        self,
        parent_id: str,
        kind: str,
        error: str | None,
        failed_indices_event: list[int] | None = None,
        terminal_status: str = "failed",
        outcome: TerminalOutcome | None = None,
    ) -> None:
        """parallel 父节点终态传播给子节点(事件源无子步骤 step_end)。

        父成功 ⇒ 全部分支成功(任一异常父即 raise);父失败时失败分支优先取
        事件结构化字段 failed_indices(patterns.py 异常直接携带),旧事件回退
        解析错误串 "step_N: ...";两者皆无才全部标失败。
        """
        subs = self._parent_to_subs.get(parent_id)
        if not subs:
            return
        if kind == "completed":
            failed_idx: set[int] = set()
        elif failed_indices_event:
            failed_idx = set(failed_indices_event)
        else:
            parsed = self._parse_failed_indices(error)
            failed_idx = parsed if parsed is not None else set(range(len(subs)))
        for i, sub_id in enumerate(subs):
            if sub_id in self._terminal_ids:
                continue
            if i in failed_idx:
                terminal = outcome or classify_terminal_outcome(error, terminal_status)
                self._push("node.failed", sub_id, {
                    **terminal.event_fields(), "error": error, "error_full": error,
                })
            else:
                self._push("node.completed", sub_id, {"status": "success"})
            self._terminal_ids.add(sub_id)

    @staticmethod
    def _parse_failed_indices(error: str | None) -> set[int] | None:
        """旧事件无 failed_indices 时从 "step_0: ...; step_2: ..." 错误串解析;解析不到返回 None。"""
        if not error:
            return None
        idxs = {int(m) for m in re.findall(r"\bstep_(\d+):", error)}
        return idxs or None

    async def _handle_plan_updated(self, event: dict[str, Any]) -> None:
        """replan 追加的恢复步骤补进 DAG(不重发整图,增补节点/边/路由);空恢复计划=跳过,同样收敛节点。"""
        new_steps = event.get("new_steps") or []
        try:
            from app.tools.workflow.types import StepType

            skipped_id = str(event.get("skipped_step_id") or "")
            base = self._own_definition()
            existing_node_ids = {node.id for node in base.nodes} if base is not None else set()
            already_skipped = skipped_id in self._skipped_ids
            if skipped_id and not already_skipped:
                # 失败步骤被恢复步骤替代或整步跳过:保留 node.failed 兼容事件,最终节点状态收敛为 skipped。
                self._push("node.completed", skipped_id, {
                    "status": "skipped",
                    "output_summary": "已由恢复步骤替代" if new_steps else "恢复计划选择跳过该步骤",
                    "replan_replacement": True,
                })
                self._skipped_ids.add(skipped_id)
                self._terminal_ids.add(skipped_id)

            if not new_steps:
                if already_skipped:
                    return
                if skipped_id and base is not None:
                    downstream = [edge for edge in base.edges if edge.from_id == skipped_id]
                    if downstream:
                        upstream = [str(dep) for dep in (event.get("skipped_step_dependencies") or [])]
                        removed = {(edge.from_id, edge.to_id, edge.condition) for edge in downstream}
                        replacement = [EdgeDef(
                            from_id=dep if upstream else skipped_id,
                            to_id=edge.to_id, condition="跳过后继续",
                        ) for edge in downstream for dep in (upstream or [skipped_id])]
                        self._server.append_workflow_nodes(self._current_def(
                            [], replacement, removed_edges=removed,
                        ))
                return
            if all(str(raw.get("id") or "") in existing_node_ids for raw in new_steps):
                return
            new_nodes: list[NodeDef] = []
            new_edges: list[EdgeDef] = []
            replacement_ids = {
                str(raw.get("id")) for raw in new_steps if raw.get("id")
            }
            replacement_types = {
                str(raw["id"]): str(raw.get("type", "claude_skill"))
                for raw in new_steps if raw.get("id")
            }
            replacement_roots: list[str] = []
            skipped_dependencies = event.get("skipped_step_dependencies")
            if skipped_dependencies is not None:
                skipped_dependencies = {
                    str(dep) for dep in skipped_dependencies if str(dep)
                }
            for raw in new_steps:
                sid = str(raw.get("id") or "")
                if not sid or sid in existing_node_ids:
                    continue
                existing_node_ids.add(sid)
                raw_dependencies = [str(dep) for dep in (raw.get("depends_on") or []) if str(dep)]
                if not any(dep in replacement_ids for dep in raw_dependencies):
                    replacement_roots.append(str(sid))
                step_type = raw.get("type", "claude_skill")
                metadata: dict[str, Any] = {
                    "description": raw.get("description", ""),
                    **command_category_metadata("workflow"),
                }
                if self._c_id:
                    metadata["c_id"] = self._c_id
                if step_type == StepType.CONDITION.value and raw.get("condition_expression"):
                    metadata["condition_expression"] = raw["condition_expression"]
                if step_type == StepType.LOOP.value:
                    metadata["loop_max"] = raw.get("loop_max_iterations")
                node = NodeDef(
                    id=sid,
                    label=raw.get("name", sid),
                    type=step_type,
                    metadata=metadata,
                    checklist=[],
                    capability=raw.get("skill_name"),
                )
                new_nodes.append(node)
                for dep in raw_dependencies:
                    # New executor events identify only the old failed step's
                    # dependencies as replaced. Older events did not carry
                    # that field and retain the historical skip-all behavior.
                    if (
                        skipped_id
                        and str(sid) in replacement_roots
                        and (
                            dep == skipped_id or skipped_dependencies is None
                            or dep in skipped_dependencies
                        )
                    ):
                        continue
                    dep_type = replacement_types.get(dep) or self._node_types.get(dep)
                    new_edges.append(EdgeDef(
                        from_id=dep, to_id=sid,
                        condition=_dependency_relation(dep_type),
                    ))
                # 路由表扩容(setdefault:已有同名不覆盖)
                step_name = raw.get("name", "")
                self._name_to_ids.setdefault(step_name, []).append(sid)
                self._name_to_id.setdefault(step_name, sid)
                self._node_labels[str(sid)] = step_name or str(sid)
                self._node_types[str(sid)] = str(step_type)
                if step_type == StepType.PARALLEL.value:
                    for sub in raw.get("parallel_steps") or []:
                        sub_id = f"{sid}{SUB_SEP}{sub.get('id', '')}"
                        if sub_id in existing_node_ids:
                            continue
                        existing_node_ids.add(sub_id)
                        new_nodes.append(NodeDef(
                            id=sub_id, label=sub.get("name", ""), type=sub.get("type", "claude_skill"),
                            metadata={
                                "description": sub.get("description", ""),
                                **command_category_metadata("workflow"),
                                **({"c_id": self._c_id} if self._c_id else {}),
                            },
                            checklist=[], capability=sub.get("skill_name"),
                        ))
                        new_edges.append(EdgeDef(from_id=sid, to_id=sub_id, condition="并行"))
                        sub_name = sub.get("name", "")
                        self._name_to_ids.setdefault(sub_name, []).append(sub_id)
                        self._name_to_id.setdefault(sub_name, sub_id)
                        self._node_labels[sub_id] = sub_name or sub_id
                        self._node_types[sub_id] = str(sub.get("type", "claude_skill"))
                    self._parent_to_subs[sid] = [f"{sid}{SUB_SEP}{sub.get('id', '')}" for sub in (raw.get("parallel_steps") or [])]
            # Replan replaces a failed step in the execution plan, so its
            # replacement root has a proven visual recovery relation even when
            # the executor rewrites the runtime dependency to the old step's
            # parents. Keep that relation explicit in the dashboard DAG.
            if skipped_id and replacement_roots:
                existing = {(edge.from_id, edge.to_id) for edge in new_edges}
                for replacement_id in replacement_roots:
                    if replacement_id != skipped_id and (skipped_id, replacement_id) not in existing:
                        new_edges.append(EdgeDef(
                            from_id=skipped_id,
                            to_id=replacement_id,
                            condition="恢复替代",
                        ))
            removed_edges: set[tuple[str, str, str | None]] = set()
            if skipped_id and base is not None and replacement_ids:
                internal_dependencies = {
                    str(dep)
                    for raw in new_steps
                    for dep in (raw.get("depends_on") or [])
                    if str(dep) in replacement_ids
                }
                replacement_terminals = [
                    str(raw.get("id")) for raw in new_steps
                    if raw.get("id") and str(raw.get("id")) not in internal_dependencies
                ]
                downstream = [
                    edge for edge in base.edges
                    if edge.from_id == skipped_id and edge.to_id not in replacement_ids
                ]
                for edge in downstream:
                    removed_edges.add((edge.from_id, edge.to_id, edge.condition))
                    for terminal_id in replacement_terminals:
                        new_edges.append(EdgeDef(
                            from_id=terminal_id,
                            to_id=edge.to_id,
                            condition="恢复后继续",
                        ))
            if not new_nodes:
                return
            # 增补 def 广播新 init 帧(服务器不清历史/状态)——前端以新节点集重建 nodeStates。
            self._server.append_workflow_nodes(self._current_def(
                new_nodes, new_edges, removed_edges=removed_edges,
            ))
            # 新节点立即广播 snapshot 终态基线;replan 前已 SKIPPED 的依赖不上图也无妨。
            for node in new_nodes:
                if node.id not in self._started_ids:
                    self._push("node.log", node.id, {"log_line": "replan 恢复步骤已加入执行计划"})
        except Exception as exc:
            logger.warning("Dashboard plan_updated failed: %s", exc)

    def _current_def(
        self,
        extra_nodes: list[NodeDef],
        extra_edges: list[EdgeDef],
        *,
        removed_edges: set[tuple[str, str, str | None]] | None = None,
    ) -> WorkflowDef:
        """当前已下发 def + 增量节点合并成新 def(attach 后的运行时重建)。"""
        base = self._own_definition()
        if base is not None and hasattr(base, "nodes"):
            edges = [
                edge for edge in base.edges
                if (edge.from_id, edge.to_id, edge.condition) not in (removed_edges or set())
            ]
            seen = {(edge.from_id, edge.to_id, edge.condition) for edge in edges}
            for edge in extra_edges:
                key = (edge.from_id, edge.to_id, edge.condition)
                if key not in seen:
                    edges.append(edge)
                    seen.add(key)
            existing_node_ids = {node.id for node in base.nodes}
            self._definition = WorkflowDef(
                workflow_id=self._wf_id or base.workflow_id,
                name=base.name,
                nodes=list(base.nodes) + [node for node in extra_nodes if node.id not in existing_node_ids],
                edges=edges,
            )
        else:
            self._definition = WorkflowDef(workflow_id=self._wf_id or "wf", name="workflow", nodes=extra_nodes, edges=extra_edges)
        return self._definition

    def finish_sync(
        self,
        plan: WorkflowPlan,
        *,
        user: bool = False,
        reason: str = "连接中断",
    ) -> None:
        """断连收尾(GeneratorExit 上下文不能 await);user=True 即中断端点硬停。"""
        from app.model_agent.dashboard.server import DashboardServer

        async def finish_on_dashboard():
            self.finish_sync(plan, user=user, reason=reason)

        def deliver():
            # 与异步 progress 使用同一调度层,避免终态抢在已排队的末片之前。
            task = asyncio.create_task(finish_on_dashboard())
            task.add_done_callback(_report_done)

        if isinstance(self._server, DashboardServer) and self._server.dispatch_report(deliver):
            return
        if self._server is None or self._wf_id is None or self._finished:
            return
        for node_id in list(self._live_outputs):
            self._emit_live_output(node_id, force=True)
        self._finished = True
        outcome = classify_terminal_outcome(reason, user_initiated=user)
        status = outcome.status
        if self._planning_node_id and self._planning_node_id not in self._terminal_ids:
            self._push("node.failed", self._planning_node_id, {
                **outcome.event_fields(), "error": reason, "error_full": reason,
                "graph_only": True,
            })
            self._terminal_ids.add(self._planning_node_id)
            self._planning_node_id = None
            self._planning_workflow_id = None
        for s in plan.steps:
            if s.status in (StepStatus.RUNNING, StepStatus.RETRYING) and s.id not in self._terminal_ids:
                self._push("node.failed", s.id, {
                    **outcome.event_fields(), "error": reason, "error_full": reason,
                })
                self._terminal_ids.add(s.id)
                self._propagate_parallel_terminal(
                    s.id, "failed", reason, terminal_status=status, outcome=outcome,
                )
        done = sum(1 for s in plan.steps if s.status == StepStatus.COMPLETED)
        terminal_label = {
            "interrupted": "用户中断",
            "aborted": "异常中断",
            "failed": "执行失败",
        }.get(status, "执行失败")
        self._push("workflow.failed", None, {
            **outcome.event_fields(),
            "error": f"{terminal_label}(成功完成 {done}/{len(plan.steps)} 个任务):{reason}",
            "error_full": reason,
        })

    @_background_report
    async def finish(
        self,
        plan: WorkflowPlan,
        ctx: ExecutionContext,
        *,
        interrupted: bool = False,
    ) -> None:
        """执行结束发终态帧:任一步骤 failed 即 workflow.failed;
        中断且未完成也发 workflow.failed(error 文案区分中断与失败)。"""
        if self._server is None or self._wf_id is None or self._finished:
            return
        for node_id in list(self._live_outputs):
            self._emit_live_output(node_id, force=True)
        self._finished = True
        try:
            failed = [s for s in plan.steps if s.status == StepStatus.FAILED]
            interrupted_incomplete = interrupted and not plan.is_complete()
            if interrupted:
                reason = "用户中断"
                outcome = classify_terminal_outcome(reason, user_initiated=True)
                self._close_running_nodes(plan, outcome=outcome, reason=reason)
            if interrupted_incomplete:
                done = sum(1 for s in plan.steps if s.status in (StepStatus.COMPLETED, StepStatus.SKIPPED))
                self._push("workflow.failed", None, {
                    **outcome.event_fields(),
                    "error": f"已被用户中断(成功完成 {done}/{len(plan.steps)} 个任务)",
                })
            elif failed:
                outcomes = [classify_terminal_outcome(step.error or "执行失败", "failed") for step in failed]
                outcome = next((item for item in outcomes if item.status == "failed"), outcomes[0])
                self._push("workflow.failed", None, {
                    **outcome.event_fields(),
                    "error": f"{len(failed)} step(s) failed: " + ", ".join(s.id for s in failed),
                })
            else:
                self._push("workflow.completed", None, {"status": "success"})
        except Exception as exc:
            logger.warning("Dashboard finish failed: %s", exc)

    def _close_running_nodes(
        self,
        plan: WorkflowPlan,
        *,
        outcome: TerminalOutcome,
        reason: str,
    ) -> None:
        """把协作式中断时仍在运行/重试的节点收敛成明确终态。"""
        for step in plan.steps:
            if step.status not in (StepStatus.RUNNING, StepStatus.RETRYING):
                continue
            if step.id not in self._terminal_ids:
                self._push("node.failed", step.id, {
                    **outcome.event_fields(), "error": reason, "error_full": reason,
                })
                self._terminal_ids.add(step.id)
            self._propagate_parallel_terminal(
                step.id, "failed", reason, terminal_status=outcome.status, outcome=outcome,
            )

    def _push(self, event_type: str, node_id: str | None, data: dict[str, Any]) -> None:
        # finish_sync 在 GeneratorExit 清理路径上调用:抛异常会掩盖原异常;
        # 看板故障不得影响执行器收尾,与 chat_dashboard._push 同一防护模式。
        try:
            from app.model_agent.workflow.schemas import EventType, WorkflowEvent

            if node_id and event_type.startswith("node."):
                label = self._node_labels.get(node_id)
                if label:
                    data = {"node_label": label, **data}

            self._server.push_event(WorkflowEvent(
                event_type=EventType(event_type),
                workflow_id=self._wf_id,
                node_id=node_id,
                timestamp=time.time(),
                data=data,
            ))
        except Exception as exc:
            logger.warning("Dashboard bridge push failed: %s", exc)


def _condition_result_summary(label: str, value: bool) -> str:
    """Turn an internal boolean into the decision a user actually made."""
    predicate = re.sub(r"^(?:判定|判断|检查|确认)\s*", "", label).strip()
    predicate = re.sub(r"^是否\s*", "", predicate).strip() or "条件成立"
    if value:
        return f"判定结果:{predicate}"

    replacements = (
        (r"^需要", "不需要"),
        (r"^已", "未"),
        (r"^可以", "不可以"),
        (r"^可", "不可"),
        (r"^支持", "不支持"),
        (r"^存在", "不存在"),
        (r"^通过", "未通过"),
    )
    for pattern, replacement in replacements:
        if re.search(pattern, predicate):
            return f"判定结果:{re.sub(pattern, replacement, predicate, count=1)}"
    return f"判定结果:条件不成立({predicate})"