"""direct command 会话 → 动态执行图:入口任务 + 实际语义步骤。"""

from __future__ import annotations

import contextvars
import json
import logging
import re
import time
import uuid
from typing import Any

from app.model_agent.dashboard.titles import (
    _CATEGORY_ALIASES,
    command_category,
    command_category_metadata,
)
from app.model_agent.dashboard.titles import (
    COMMAND_CATEGORY_LABELS as COMMAND_CATEGORY_LABELS,
)
from app.model_agent.workflow.capability_events import clip
from app.model_agent.workflow.schemas import EdgeDef, NodeDef, WorkflowDef
from app.services.execution_outcome import classify_terminal_outcome

logger = logging.getLogger(__name__)

_LIVE_OUTPUT_MIN_INTERVAL = 0.1
_LIVE_OUTPUT_TARGET_CHARS_PER_SECOND = 20_000
_PTA_MODE_BANNERS = {"[RAG 检索]", "[CI 问答]", "[分布式排查]", "[Skill 查询]", "[分类诊断]", "[直接 LLM]"}
_REQUEST_ENTRY_CATEGORY: contextvars.ContextVar[str] = contextvars.ContextVar(
    "command_request_entry_category", default="",
)


def set_request_entry_category(value: str) -> contextvars.Token:
    return _REQUEST_ENTRY_CATEGORY.set(value)


def reset_request_entry_category(token: contextvars.Token) -> None:
    try:
        _REQUEST_ENTRY_CATEGORY.reset(token)
    except ValueError:
        _REQUEST_ENTRY_CATEGORY.set("")


def get_request_entry_category() -> str:
    return _REQUEST_ENTRY_CATEGORY.get()


_INTERNAL_STEP_RE = re.compile(
    r"^(?:bash|shell|terminal|tool|invoke_[a-z0-9_]+|[a-z][a-z0-9]*_[a-z0-9_]+)$",
    re.I,
)
_GENERIC_STEP_RE = re.compile(
    r"^(?:步骤|下一步|操作|step)[。.!!::\s]*$",
    re.IGNORECASE,
)


def _json_object(value: Any) -> dict[str, Any]:
    if isinstance(value, dict):
        return dict(value)
    if not isinstance(value, str) or not value.strip():
        return {}
    try:
        parsed = json.loads(value)
    except (TypeError, ValueError):
        return {}
    return parsed if isinstance(parsed, dict) else {}


def _semantic_step_label(value: Any) -> str:
    label = " ".join(str(value or "").split()).strip(" -::")
    if not label or _INTERNAL_STEP_RE.fullmatch(label) or _GENERIC_STEP_RE.fullmatch(label):
        return ""
    return label


_EXECUTION_UPDATE_FIELDS = ("status", "subject", "description", "activeForm", "active_form")


def _task_update_changes_execution(args: dict[str, Any]) -> bool:
    """改了状态或文案才算执行变更,纯依赖记账返回 False。"""
    return any(str(args.get(field) or "").strip() for field in _EXECUTION_UPDATE_FIELDS)


class CommandDashboardReporter:
    """单次 direct command 执行的上报会话(一实例一 run)。"""

    def __init__(
        self,
        command_name: str,
        task_digest: str,
        c_id: str = "",
        initial_output: str = "",
        task_input: str = "",
        entry_category: str = "",
    ) -> None:
        self._command = command_name
        self._entry_category = _CATEGORY_ALIASES.get(str(entry_category or "").strip().casefold(), "")
        self._digest = task_digest.strip().replace("\n", " ") or command_name
        self._task_input = task_input if task_input.strip() else task_digest
        self._c_id = str(c_id or "")
        self._server: Any = None
        self._node_id = command_name
        self._analysis_node_id = f"{command_name}-analysis" if command_name == "torch" else ""
        self._started = False
        self._closed = False
        self._wf_id: str | None = None
        self._tail: list[str] = [initial_output] if initial_output else []
        # Keep the complete user-visible, warning-filtered stream for the node
        # detail panel.  ``_tail`` remains bounded for the timeline preview.
        self._output_parts: list[str] = [initial_output] if initial_output else []
        self._output_chars = len(initial_output)
        self._output_emitted_chars = len(initial_output)
        self._output_last_emitted_at = time.monotonic()
        self._step_input_snapshot = self._task_input
        self._pending_step_output: list[str] = []
        self._live_step_node_id: str | None = None
        self._live_step_input_snapshot = ""
        self._live_step_output: list[str] = []
        self._live_step_started_at: float | None = None
        self._completed_pta_steps = 0
        self._log_buf: str = ""  # 跨 chunk 拼接缓冲,整行才落日志
        # call_id -> (tool name, start time, owning semantic/root node, arguments)
        self._pending_tools: dict[str, tuple[str, float, str, dict[str, Any]]] = {}
        self._nodes: list[NodeDef] = []
        self._edges: list[EdgeDef] = []
        self._tool_seq = 0
        self._agent_task_nodes: dict[str, str] = {}
        self._agent_task_calls: dict[str, str] = {}
        self._agent_task_status: dict[str, str] = {}
        self._agent_task_started_at: dict[str, float] = {}
        self._pending_task_dependencies: dict[str, set[str]] = {}
        self._pending_task_blocks: dict[str, set[str]] = {}
        self._agent_task_seq = 0
        self._started_monotonic: float | None = None
        self._analysis_started_at: float | None = None
        # 创建即占位,不等首个输出
        self._ensure_started()

    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(warn_label="Command dashboard")
        if server is None:
            return False
        self._server = server
        return True

    def _ensure_started(self) -> None:
        if self._started or self._closed or not self._server_ready():
            return
        entry_override = bool(
            self._entry_category and self._entry_category != command_category(self._command)
        )
        display_input = f"/{self._command} {self._digest}" if entry_override else self._digest
        root = NodeDef(
            id=self._node_id, label=self._digest, type="topic_root",
            metadata={
                **command_category_metadata(self._entry_category or self._command),
                **({"source_category_explicit": True} if self._entry_category else {}),
                "kind": "problem",
                "title_source": "user_input",
                "description": display_input,
                **({"c_id": self._c_id} if self._c_id else {}),
            },
        )
        self._nodes = [root]
        self._edges = []
        if self._analysis_node_id:
            self._nodes.append(NodeDef(
                id=self._analysis_node_id,
                label="分析问题并整理答复",
                type="task",
                metadata={
                    "kind": "semantic_step",
                    "source": "command_execution",
                    "parent_id": self._node_id,
                    "description": self._digest,
                },
            ))
            self._edges.append(EdgeDef(
                from_id=self._node_id,
                to_id=self._analysis_node_id,
                condition="任务拆解",
            ))
        wf = WorkflowDef(
            workflow_id=f"cmd-{self._command}-{uuid.uuid4().hex}",
            name=display_input if entry_override else f"{self._command} {self._digest}",
            nodes=self._nodes,
            edges=self._edges,
        )
        try:
            self._wf_id = wf.workflow_id
            self._server.set_workflow_def(wf)
            self._server.push_event(self._event("workflow.started", {
                "status": "running",
            }))
            started_data: dict[str, Any] = {
                "status": "running",
                "input_snapshot": self._task_input,
                "graph_only": True,
                "source": "user_input",
            }
            if self._output_parts:
                initial = "".join(self._output_parts)
                started_data["output_summary"] = initial[-500:]
                started_data["output_full"] = initial
            self._server.push_event(self._event("node.started", started_data))
            if self._analysis_node_id:
                self._analysis_started_at = time.monotonic()
                self._server.push_event(self._event(
                    "node.started",
                    {"status": "running", "input_snapshot": self._task_input},
                    self._analysis_node_id,
                ))
            self._started = True
            self._started_monotonic = time.monotonic()
        except Exception as exc:
            logger.warning("Command dashboard start failed: %s", exc)
            self._server = None

    def _event(self, event_type: str, data: dict[str, Any], node_id: str | None = None):
        from app.model_agent.workflow.schemas import EventType, WorkflowEvent

        return WorkflowEvent(
            event_type=EventType(event_type),
            # 锁定本 run id:推送时取当前 def 会把迟帧盖上别 run 的 id 造成串档
            workflow_id=self._wf_id,
            node_id=None if event_type.startswith("workflow.") else (node_id or self._node_id),
            timestamp=time.time(),
            data=data,
        )

    def _push(self, event_type: str, data: dict[str, Any], node_id: str | None = None) -> None:
        self._ensure_started()
        if not self._started:
            return
        try:
            self._server.push_event(self._event(event_type, data, node_id))
        except Exception as exc:
            logger.warning("Command dashboard push failed: %s", exc)

    def _send_def(self) -> None:
        if self._server is None or self._wf_id is None:
            return
        wf = WorkflowDef(
            workflow_id=self._wf_id,
            name=f"{self._command} {self._digest}",
            nodes=self._nodes,
            edges=self._edges,
        )
        try:
            self._server.append_workflow_nodes(wf)
        except Exception as exc:
            logger.warning("Command dashboard definition update failed: %s", exc)

    @staticmethod
    def _task_ids(raw: Any) -> list[str]:
        if isinstance(raw, str):
            return [raw] if raw else []
        if not isinstance(raw, list):
            return []
        return [str(item) for item in raw if str(item)]

    @classmethod
    def _task_dependencies(cls, args: dict[str, Any]) -> list[str]:
        raw = (args.get("blockedBy") or args.get("blocked_by")
               or args.get("depends_on") or args.get("addBlockedBy") or [])
        return cls._task_ids(raw)

    @classmethod
    def _task_blocks(cls, args: dict[str, Any]) -> list[str]:
        return cls._task_ids(args.get("addBlocks") or args.get("blocks") or [])

    def _tool_parent(self, name: str, args: dict[str, Any]) -> str:
        if name == "TaskUpdate" and _task_update_changes_execution(args):
            task_id = str(args.get("taskId") or args.get("task_id") or "")
            if task_id in self._agent_task_nodes:
                return self._agent_task_nodes[task_id]
        active = [node_id for node_id, status in self._agent_task_status.items()
                  if status == "in_progress"]
        if name != "TaskCreate" and len(active) == 1:
            return active[0]
        return self._analysis_node_id or self._node_id

    def _append_task_edge(self, from_id: str, to_id: str, condition: str) -> bool:
        if not from_id or not to_id or from_id == to_id:
            return False
        changed = False
        if condition == "显式依赖":
            kept = [edge for edge in self._edges
                    if not (edge.to_id == to_id and edge.condition == "任务拆解")]
            changed = len(kept) != len(self._edges)
            self._edges = kept
        if any(edge.from_id == from_id and edge.to_id == to_id for edge in self._edges):
            return changed
        self._edges.append(EdgeDef(from_id=from_id, to_id=to_id, condition=condition))
        return True

    def _add_task_dependency_edges(self, node_id: str, task_ids: list[str]) -> bool:
        changed = False
        for task_id in task_ids:
            dependency = self._agent_task_nodes.get(task_id)
            if dependency:
                changed = self._append_task_edge(dependency, node_id, "显式依赖") or changed
            else:
                self._pending_task_dependencies.setdefault(node_id, set()).add(task_id)
        return changed

    def _add_task_block_edges(self, node_id: str, task_ids: list[str]) -> bool:
        changed = False
        for task_id in task_ids:
            target = self._agent_task_nodes.get(task_id)
            if target:
                changed = self._append_task_edge(node_id, target, "显式依赖") or changed
            else:
                self._pending_task_blocks.setdefault(node_id, set()).add(task_id)
        return changed

    def _resolve_task_edges(self) -> bool:
        changed = False
        for node_id, task_ids in list(self._pending_task_dependencies.items()):
            unresolved = {task_id for task_id in task_ids if task_id not in self._agent_task_nodes}
            for task_id in task_ids - unresolved:
                changed = self._append_task_edge(
                    self._agent_task_nodes[task_id], node_id, "显式依赖",
                ) or changed
            if unresolved:
                self._pending_task_dependencies[node_id] = unresolved
            else:
                self._pending_task_dependencies.pop(node_id, None)
        for node_id, task_ids in list(self._pending_task_blocks.items()):
            unresolved = {task_id for task_id in task_ids if task_id not in self._agent_task_nodes}
            for task_id in task_ids - unresolved:
                changed = self._append_task_edge(
                    node_id, self._agent_task_nodes[task_id], "显式依赖",
                ) or changed
            if unresolved:
                self._pending_task_blocks[node_id] = unresolved
            else:
                self._pending_task_blocks.pop(node_id, None)
        return changed

    def _register_agent_task(
        self, args: dict[str, Any], result: dict[str, Any], call_id: str,
    ) -> None:
        task = result.get("task") if isinstance(result.get("task"), dict) else {}
        task_id = str(task.get("id") or result.get("taskId") or result.get("id")
                      or args.get("taskId") or "")
        subject = _semantic_step_label(task.get("subject") or args.get("subject"))
        if not subject:
            return
        existing = self._agent_task_nodes.get(task_id) if task_id else None
        existing = existing or self._agent_task_calls.get(call_id)
        if existing:
            changed = self._add_task_dependency_edges(existing, self._task_dependencies(args))
            changed = self._add_task_block_edges(existing, self._task_blocks(args)) or changed
            if changed:
                self._send_def()
            return
        self._agent_task_seq += 1
        node_id = f"command-step-{self._agent_task_seq}"
        description = str(task.get("description") or args.get("description") or subject).strip()
        active_form = str(task.get("activeForm") or args.get("activeForm") or "").strip()
        self._nodes.append(NodeDef(
            id=node_id,
            label=subject[:48],
            type="task",
            metadata={
                "kind": "semantic_step",
                "source": "agent_task",
                "parent_id": self._analysis_node_id or self._node_id,
                "task_create_call_id": call_id,
                "description": description,
                **({"agent_task_id": task_id} if task_id else {}),
                **({"active_form": active_form} if active_form else {}),
            },
        ))
        if task_id:
            self._agent_task_nodes[task_id] = node_id
        self._agent_task_calls[call_id] = node_id
        self._agent_task_status[node_id] = "pending"
        self._append_task_edge(self._analysis_node_id or self._node_id, node_id, "任务拆解")
        self._add_task_dependency_edges(node_id, self._task_dependencies(args))
        self._add_task_block_edges(node_id, self._task_blocks(args))
        self._resolve_task_edges()
        self._send_def()

    def _update_agent_task(
        self, args: dict[str, Any], result: dict[str, Any], result_full: str,
    ) -> None:
        task = result.get("task") if isinstance(result.get("task"), dict) else {}
        task_id = str(args.get("taskId") or args.get("task_id")
                      or result.get("taskId") or task.get("id") or "")
        node_id = self._agent_task_nodes.get(task_id)
        if not node_id:
            return
        changed = self._add_task_dependency_edges(node_id, self._task_dependencies(args))
        changed = self._add_task_block_edges(node_id, self._task_blocks(args)) or changed
        changed = self._resolve_task_edges() or changed
        node = next((item for item in self._nodes if item.id == node_id), None)
        if node:
            subject = _semantic_step_label(args.get("subject") or task.get("subject"))
            description = str(args.get("description") or task.get("description") or "").strip()
            active_form = str(args.get("activeForm") or task.get("activeForm") or "").strip()
            if subject and subject != node.label:
                node.label = subject[:48]
                changed = True
            if description and description != node.metadata.get("description"):
                node.metadata["description"] = description
                changed = True
            if active_form and active_form != node.metadata.get("active_form"):
                node.metadata["active_form"] = active_form
                changed = True
        if changed:
            self._send_def()
        status_change = result.get("statusChange") if isinstance(result.get("statusChange"), dict) else {}
        status = str(status_change.get("to") or args.get("status") or task.get("status") or "").lower()
        if not status or self._agent_task_status.get(node_id) == status:
            return
        description = str(node.metadata.get("description") or node.label) if node else ""
        if status == "in_progress":
            self._agent_task_started_at[node_id] = time.monotonic()
            self._push("node.started", {
                "status": "running", "input_snapshot": description,
            }, node_id)
        elif status == "completed":
            started_at = self._agent_task_started_at.pop(node_id, None)
            self._push("node.completed", {
                "status": "success",
                **({"elapsed_ms": max(0, int((time.monotonic() - started_at) * 1000))}
                   if started_at is not None else {}),
            }, node_id)
        elif status == "deleted":
            started_at = self._agent_task_started_at.pop(node_id, None)
            self._push("node.completed", {
                "status": "skipped",
                **({"elapsed_ms": max(0, int((time.monotonic() - started_at) * 1000))}
                   if started_at is not None else {}),
            }, node_id)
        elif status == "pending":
            self._agent_task_started_at.pop(node_id, None)
            self._push("node.started", {
                "status": "pending", "input_snapshot": description,
                "graph_only": True,
            }, node_id)
        else:
            return
        self._agent_task_status[node_id] = status

    def on_output(self, chunk: str | Any) -> None:
        """命令流片段:CommandOutput 的 tool_event 映射工具调用,文本入日志。"""
        if getattr(chunk, "activity", False):
            self._flush_log(final=True)
            self._emit_output_snapshot(force=True)
            return
        tool_event = getattr(chunk, "tool_event", None)
        if tool_event:
            self._flush_log(final=True)
            phase = tool_event.get("phase")
            if phase == "started":
                self._tool_seq += 1
                call_id = str(tool_event.get("call_id") or f"cmd-{self._tool_seq}")
                if call_id not in self._pending_tools:
                    name = str(tool_event.get("tool") or "")
                    raw_args_summary = str(tool_event.get("args_summary") or "")
                    args_summary = clip(raw_args_summary, 500)
                    raw_args_full = str(tool_event.get("args_full") or "")
                    args = _json_object(tool_event.get("arguments")) or _json_object(raw_args_full)
                    if name == "TaskUpdate" and not _task_update_changes_execution(args):
                        self._pending_tools[call_id] = (name, time.monotonic(), "", args)
                        return
                    args_full = clip(raw_args_full)
                    parent_id = self._tool_parent(name, args)
                    self._pending_tools[call_id] = (name, time.monotonic(), parent_id, args)
                    data: dict[str, Any] = {
                        "call_id": call_id,
                        "tool": name,
                        "arguments_summary": args_summary,
                    }
                    if tool_event.get("args_full") is not None:
                        data["arguments_full"] = args_full
                    elif len(raw_args_summary) > 500:
                        data["arguments_full"] = clip(raw_args_summary)
                    self._push("tool.started", data, parent_id)
            elif phase in ("failed", "completed"):
                call_id = str(tool_event.get("call_id") or "")
                if not call_id and len(self._pending_tools) == 1:
                    call_id = next(iter(self._pending_tools))
                matched = self._pending_tools.pop(call_id, None) if call_id else None
                if matched is None:
                    logger.warning("Ignoring unmatched command tool result: %s", call_id or "missing call_id")
                    self._push("node.log", {
                        "log_line": f"工具结果无法归属:{tool_event.get('tool') or 'tool'},"
                                    f"call_id={call_id or '缺失'}",
                    })
                else:
                    name, started_at, parent_id, args = matched
                    elapsed = tool_event.get("elapsed_ms")
                    if elapsed is None:
                        elapsed = int((time.monotonic() - started_at) * 1000)
                    raw_result_full = str(tool_event.get("result_full") or "")
                    result_full = clip(raw_result_full)
                    result_summary = str(tool_event.get("result_summary") or "")
                    if name == "TaskUpdate" and not _task_update_changes_execution(args):
                        failed = phase == "failed"
                        if not failed:
                            result_data = _json_object(tool_event.get("result_data")) or _json_object(raw_result_full)
                            self._update_agent_task(args, result_data, raw_result_full)
                        detail = str(tool_event.get("error") or result_summary or "")
                        self._push("node.log", {
                            "log_line": f"依赖已记录:taskId={args.get('taskId') or ''} "
                                        f"{'失败:' + detail if failed else '成功'}",
                        })
                        return
                    data: dict[str, Any] = {"call_id": call_id, "tool": name, "elapsed_ms": elapsed}
                    if result_full:
                        data["result_full"] = result_full
                    elif len(result_summary) > 500:
                        data["result_full"] = clip(result_summary)
                    if phase == "failed":
                        # Failed frames may use either the explicit error fields
                        # or the legacy result_summary slot.  Preserve both a
                        # compact row value and the complete diagnostic text.
                        error_summary = str(tool_event.get("error") or result_summary or "tool error")
                        raw_error_full = str(tool_event.get("error_full") or raw_result_full or error_summary)
                        outcome = classify_terminal_outcome(
                            raw_error_full,
                            str(tool_event.get("status") or "failed"),
                        )
                        data["error"] = clip(error_summary, 500)
                        data["error_full"] = clip(raw_error_full)
                        data.update(outcome.event_fields())
                        if result_summary:
                            data["result_summary"] = clip(result_summary, 500)
                        self._push("tool.failed", data, parent_id)
                    else:
                        data["result_summary"] = clip(result_summary, 500) or result_full[:500]
                        self._push("tool.completed", data, parent_id)
                        result_data = _json_object(tool_event.get("result_data")) or _json_object(raw_result_full)
                        if name == "TaskCreate":
                            self._register_agent_task(args, result_data, call_id)
                        elif name == "TaskUpdate":
                            self._update_agent_task(args, result_data, raw_result_full)
        text = getattr(chunk, "content", None) if not isinstance(chunk, str) else chunk
        if text:
            line = str(text)
            if line:
                output_reset = bool(getattr(chunk, "output_reset", False))
                if output_reset:
                    self._output_parts.clear()
                    self._output_chars = 0
                    self._output_emitted_chars = 0
                    self._tail.clear()
                    self._pending_step_output.clear()
                    self._live_step_output.clear()
                self._output_parts.append(line)
                self._output_chars += len(line)
                # 尾窗不分 decor:答案正文(decor=True)也进 output_summary 预览
                self._tail.append(line)
                if len(self._tail) > 20:
                    self._tail = self._tail[-20:]
                # 日志仅记录非装饰内容,避免重复展示答案正文
                if not getattr(chunk, "decor", False):
                    # SSE 路径按 80 字符切块且跨 chunk 拼接,逐帧 push 会碎成伪行流——
                    # 缓冲拼接,仅整行(或停顿/超限)时落一条日志。
                    self._log_buf += line
                    self._flush_log(final=False)
                self._push("node.output.chunk", {
                    "output_chunk": line,
                    "output_reset": output_reset,
                })
                if self._analysis_node_id:
                    self._push("node.output.chunk", {
                        "output_chunk": line,
                        "output_reset": output_reset,
                    }, self._analysis_node_id)
                    stripped_line = line.strip()
                    if stripped_line == "[直接 LLM]":
                        self._ensure_live_pta_step("LLM 推理")
                    elif (self._live_step_node_id or self._completed_pta_steps) and stripped_line not in _PTA_MODE_BANNERS:
                        node_id = self._ensure_live_pta_step()
                        self._live_step_output.append(line)
                        self._push("node.output.chunk", {
                            "output_chunk": line,
                            "output_reset": output_reset,
                        }, node_id)
                    elif stripped_line not in _PTA_MODE_BANNERS:
                        self._pending_step_output.append(line)
                self._emit_output_snapshot(force=bool(tool_event) or output_reset)

    def _ensure_live_pta_step(self, label: str = "LLM 回答") -> str:
        if self._live_step_node_id:
            return self._live_step_node_id
        node_id = f"command-pta-step-{len(self._nodes)}"
        parent_id = self._analysis_node_id or self._node_id
        self._nodes.append(NodeDef(
            id=node_id,
            label=label,
            type="task",
            metadata={
                "kind": "semantic_step",
                "source": "pta_helper",
                "parent_id": parent_id,
                "description": label,
            },
        ))
        self._append_task_edge(parent_id, node_id, "执行步骤")
        self._send_def()
        self._live_step_node_id = node_id
        self._live_step_input_snapshot = self._step_input_snapshot or self._task_input
        self._live_step_output = []
        self._live_step_started_at = time.monotonic()
        self._push("node.started", {
            "status": "running",
            "input_snapshot": self._live_step_input_snapshot,
        }, node_id)
        return node_id

    def _complete_live_pta_step(self, name: str, duration_sec: float, detail: str = "") -> str:
        node_id = self._live_step_node_id or self._ensure_live_pta_step()
        label = _semantic_step_label(name) or "LLM 回答"
        node = next((item for item in self._nodes if item.id == node_id), None)
        if node is not None:
            node.label = label[:48]
            node.metadata["description"] = label
            self._send_def()
        output = "".join(self._live_step_output) or str(detail or "")
        try:
            elapsed_ms = max(0, int(float(duration_sec or 0) * 1000))
        except (TypeError, ValueError):
            elapsed_ms = max(
                0,
                int((time.monotonic() - self._live_step_started_at) * 1000),
            ) if self._live_step_started_at is not None else 0
        data: dict[str, Any] = {
            "status": "success",
            "input_snapshot": self._live_step_input_snapshot or self._task_input,
            "elapsed_ms": elapsed_ms,
        }
        if output:
            data.update({"output_summary": output[-500:], "output_full": output})
        self._push("node.completed", data, node_id)
        if output:
            self._step_input_snapshot = output
        self._live_step_node_id = None
        self._live_step_input_snapshot = ""
        self._live_step_output = []
        self._live_step_started_at = None
        self._completed_pta_steps += 1
        return output

    def _finish_live_pta_step(self, error: str | None) -> None:
        node_id = self._live_step_node_id
        if not node_id:
            return
        outcome = classify_terminal_outcome(error)
        output = "".join(self._live_step_output)
        elapsed_ms = max(
            0,
            int((time.monotonic() - self._live_step_started_at) * 1000),
        ) if self._live_step_started_at is not None else 0
        data: dict[str, Any] = {
            **outcome.event_fields(),
            "input_snapshot": self._live_step_input_snapshot or self._task_input,
            "elapsed_ms": elapsed_ms,
        }
        if output:
            data.update({"output_summary": output[-500:], "output_full": output})
        event_type = "node.completed" if outcome.status == "success" else "node.failed"
        self._push(event_type, data, node_id)
        if output:
            self._step_input_snapshot = output
        self._live_step_node_id = None
        self._live_step_input_snapshot = ""
        self._live_step_output = []
        self._live_step_started_at = None

    def on_step_completed(self, name: str, duration_sec: float, detail: str = "") -> None:
        """Map PTA's completed-step callback to a semantic graph node."""
        label = _semantic_step_label(name)
        if not label:
            return
        if self._live_step_node_id:
            self._complete_live_pta_step(label, duration_sec, detail)
            return
        node_id = f"command-pta-step-{len(self._nodes)}"
        parent_id = self._analysis_node_id or self._node_id
        self._nodes.append(NodeDef(
            id=node_id,
            label=label[:48],
            type="task",
            metadata={
                "kind": "semantic_step",
                "source": "pta_helper",
                "parent_id": parent_id,
                "description": label,
            },
        ))
        self._append_task_edge(parent_id, node_id, "执行步骤")
        self._send_def()
        try:
            elapsed_ms = max(0, int(float(duration_sec or 0) * 1000))
        except (TypeError, ValueError):
            elapsed_ms = 0
        output = str(detail or "") or "".join(self._pending_step_output)
        input_snapshot = self._step_input_snapshot or self._task_input
        data: dict[str, Any] = {
            "status": "success",
            "input_snapshot": input_snapshot,
            "elapsed_ms": elapsed_ms,
        }
        if output:
            data.update({"output_summary": output[-500:], "output_full": output})
        self._push("node.completed", data, node_id)
        self._pending_step_output.clear()
        if output:
            self._step_input_snapshot = output
        self._completed_pta_steps += 1

    def _emit_output_snapshot(self, *, force: bool = False) -> None:
        """Rate-limit existing full snapshots; force at execution boundaries."""
        if self._output_chars <= self._output_emitted_chars:
            return
        now = time.monotonic()
        min_interval = max(
            _LIVE_OUTPUT_MIN_INTERVAL,
            self._output_chars / _LIVE_OUTPUT_TARGET_CHARS_PER_SECOND,
        )
        if not force and now - self._output_last_emitted_at < min_interval:
            return
        full = "".join(self._output_parts)
        self._push("node.output", {
            "output_summary": full[-500:],
            "output_full": full,
        })
        if self._analysis_node_id:
            self._push("node.output", {
                "output_summary": full[-500:],
                "output_full": full,
            }, self._analysis_node_id)
        self._output_emitted_chars = self._output_chars
        self._output_last_emitted_at = now

    def _flush_log(self, final: bool) -> None:
        buf = self._log_buf
        if not buf:
            return
        if final:
            self._log_buf = ""
            for l in buf.splitlines():
                if l.strip():
                    self._push_log_line(l)
            return
        # 只落已完整的行,残行留缓冲
        cut = buf.rfind("\n")
        if cut < 0:
            # 无换行的长输出也要透出,余下残行继续拼接,不能清空缓冲。
            while len(self._log_buf) >= 2000:
                self._push_log_line(self._log_buf[:2000])
                self._log_buf = self._log_buf[2000:]
            return
        done, self._log_buf = buf[:cut], buf[cut + 1:]
        for l in done.splitlines():
            if l.strip():
                self._push_log_line(l)

    def _push_log_line(self, line: str) -> None:
        line = line.strip()
        if not line:
            return
        active = [node_id for node_id, status in self._agent_task_status.items()
                  if status == "in_progress"]
        owner = active[0] if len(active) == 1 else self._analysis_node_id or self._node_id
        self._push(
            "node.log",
            {"log_line": line if len(line) <= 2000 else line[:1900] + "\n…(后略)"},
            owner,
        )

    def finish(
        self,
        error: str | None = None,
        awaiting_user: bool = False,
        awaiting_resume: bool = False,
    ) -> None:
        """Close the run using the shared success/failure/interruption contract."""
        if not self._started:
            return
        self._emit_output_snapshot(force=True)
        if (awaiting_user or awaiting_resume) and not error:
            paused_at = time.monotonic()
            status = "paused" if awaiting_resume else "waiting"
            pause_data = {"status": status, "awaiting_user": True}
            if self._analysis_node_id:
                self._push("node.started", {
                    **pause_data,
                    **({"elapsed_ms": max(0, int((paused_at - self._analysis_started_at) * 1000))}
                       if self._analysis_started_at is not None else {}),
                }, self._analysis_node_id)
            if self._live_step_node_id:
                self._push("node.started", {
                    **pause_data,
                    **({"elapsed_ms": max(0, int((paused_at - self._live_step_started_at) * 1000))}
                       if self._live_step_started_at is not None else {}),
                }, self._live_step_node_id)
            for node_id, task_status in self._agent_task_status.items():
                if task_status == "in_progress":
                    started_at = self._agent_task_started_at.get(node_id)
                    self._push("node.started", {
                        **pause_data,
                        **({"elapsed_ms": max(0, int((paused_at - started_at) * 1000))}
                           if started_at is not None else {}),
                    }, node_id)
            self._push("node.started", {
                **pause_data,
                "graph_only": True, "source": "user_input",
                **({"elapsed_ms": max(0, int((paused_at - self._started_monotonic) * 1000))}
                   if self._started_monotonic is not None else {}),
            })
            self._push("node.log", {"log_line": (
                "⏸ 当前执行阶段已暂停,等待继续处理…"
                if awaiting_resume
                else "⏸ 等待用户补充信息…"
            )})
            self._closed = True
            self._started = False
            return
        self._finish_live_pta_step(error)
        # 只有挂到节点上的记账调用才算「结果未返回」。
        lingering = any(parent_id for _n, _s, parent_id, _a in self._pending_tools.values())
        effective_error = error or ("工具结果未返回" if lingering else None)
        outcome = classify_terminal_outcome(effective_error)
        status = outcome.status
        for call_id, (name, started_at, parent_id, _args) in list(self._pending_tools.items()):
            if not parent_id:
                continue
            error_text = effective_error or "工具结果未返回"
            tool_outcome = classify_terminal_outcome(error_text)
            elapsed_ms = int((time.monotonic() - started_at) * 1000)
            self._push("tool.failed", {
                "call_id": call_id, "tool": name,
                "error": error_text,
                "error_full": error_text,
                **tool_outcome.event_fields(),
                "elapsed_ms": elapsed_ms,
            }, parent_id)
        self._pending_tools.clear()
        # Flush while task statuses still describe the active owner. Closing
        # steps first would incorrectly attach the last partial line to root.
        self._flush_log(final=True)
        for node_id, task_status in list(self._agent_task_status.items()):
            if task_status == "in_progress":
                started_at = self._agent_task_started_at.pop(node_id, None)
                if effective_error is None:
                    self._push("node.completed", {
                        "status": "success",
                        **({"elapsed_ms": max(0, int((time.monotonic() - started_at) * 1000))}
                           if started_at is not None else {}),
                    }, node_id)
                    self._agent_task_status[node_id] = "success"
                    continue
                reason = error or effective_error
                task_outcome = classify_terminal_outcome(reason, status if error else "aborted")
                self._push("node.failed", {
                    **task_outcome.event_fields(),
                    "error": reason,
                    "error_full": reason,
                    **({"elapsed_ms": max(0, int((time.monotonic() - started_at) * 1000))}
                       if started_at is not None else {}),
                }, node_id)
                self._agent_task_status[node_id] = task_outcome.status
            elif task_status == "pending":
                self._push("node.completed", {
                    "status": "skipped",
                    "output_summary": "任务结束前未执行该步骤",
                }, node_id)
                self._agent_task_status[node_id] = "skipped"
        data: dict[str, Any] = outcome.event_fields()
        # 使用实际运行时长补全节点耗时
        if self._started_monotonic is not None:
            data["elapsed_ms"] = int((time.monotonic() - self._started_monotonic) * 1000)
        output = "".join(self._output_parts)
        if status == "success" and output:
            data["output_summary"] = output[-500:]
        if output:
            data["output_full"] = output
        if effective_error:
            data["error"] = effective_error
            data["error_full"] = effective_error
        if self._analysis_node_id:
            analysis_data: dict[str, Any] = {
                **outcome.event_fields(),
                "output_summary": data.get("output_summary", ""),
                "output_full": data.get("output_full", ""),
            }
            if self._analysis_started_at is not None:
                analysis_data["elapsed_ms"] = max(
                    0, int((time.monotonic() - self._analysis_started_at) * 1000),
                )
            if effective_error:
                analysis_data["error"] = effective_error
                analysis_data["error_full"] = effective_error
            self._push(
                "node.failed" if status != "success" else "node.completed",
                analysis_data,
                self._analysis_node_id,
            )
        root_data = {**data, "graph_only": True, "source": "user_input"}
        self._push("node.failed" if status != "success" else "node.completed", root_data)
        self._push("workflow.failed" if status != "success" else "workflow.completed", data)
        self._closed = True
        self._started = False
        # 终帧即时归档:归档只发生在下一个 set_workflow_def,越晚快照离真实终态越远
        self._archive_now()

    def _archive_now(self) -> None:
        if self._server is None or self._wf_id is None:
            return
        archive = getattr(self._server, "_archive_current_run", None)
        if archive is None:
            return
        try:
            if self._server._workflow_def and self._server._workflow_def.workflow_id == self._wf_id:
                archive()
        except Exception as exc:
            logger.warning("Command dashboard archive failed: %s", exc)


class _CommandContinuationDashboardReporter:
    """把已确认的直接命令续跑追加到原问题图。"""

    def __init__(
        self,
        command_name: str,
        task_digest: str,
        c_id: str,
        continuation_input: str,
        initial_output: str = "",
        task_input: str = "",
        placeholder: bool = True,
    ) -> None:
        self._fallback: CommandDashboardReporter | None = None
        self._reporter: Any = None
        self._log_buf = ""
        from app.services.chat_dashboard import get_topic_host, open_chat_turn_dashboard

        host = get_topic_host(c_id)
        # 换命令是另一类任务,不能挂进旧图。
        if host is not None and str(getattr(host, "_wf_id", "") or "").startswith(f"cmd-{command_name}-"):
            self._reporter = open_chat_turn_dashboard(
                c_id,
                continuation_input,
                c_id=c_id,
                placeholder=placeholder,
            )
        if self._reporter is not None:
            self._reporter.start_turn_node(continuation_input, placeholder=placeholder)
            if initial_output:
                self._reporter.record_reply(initial_output, output_reset=True)
        if self._reporter is None:
            # 找不到可证明归属的旧图时保持原行为,不能凭标题猜接历史。
            from app.services.chat_dashboard import forget_topic_host

            forget_topic_host(c_id)
            self._fallback = CommandDashboardReporter(
                command_name,
                task_digest,
                c_id=c_id,
                initial_output=initial_output,
                task_input=task_input,
                entry_category=get_request_entry_category(),
            )

    @staticmethod
    def _skill_tool_event(event: dict[str, Any]) -> dict[str, Any]:
        mapped: dict[str, Any] = {
            "name": str(event.get("tool") or "tool"),
            "phase": event.get("phase"),
        }
        for key in (
            "call_id", "arguments", "result_data", "result_summary", "result_full",
            "error", "error_full", "elapsed_ms", "status",
        ):
            if event.get(key) is not None:
                mapped[key] = event[key]
        if event.get("args_summary") is not None:
            mapped["brief"] = event["args_summary"]
        if event.get("args_full") is not None:
            mapped["brief_full"] = event["args_full"]
        return mapped

    def on_output(self, chunk: str | Any) -> None:
        if self._fallback is not None:
            self._fallback.on_output(chunk)
            return
        if self._reporter is None:
            return
        tool_event = getattr(chunk, "tool_event", None)
        if isinstance(tool_event, dict):
            self._reporter.on_skill_tool(self._skill_tool_event(tool_event))
        text = getattr(chunk, "content", None) if not isinstance(chunk, str) else chunk
        if not text:
            return
        value = str(text)
        self._reporter.record_reply(
            value,
            output_reset=bool(getattr(chunk, "output_reset", False)),
        )
        if not getattr(chunk, "decor", False):
            self._log_buf += value
            self._flush_log(final=False)

    def on_step_completed(self, name: str, duration_sec: float, detail: str = "") -> None:
        if self._fallback is not None:
            self._fallback.on_step_completed(name, duration_sec, detail)
        elif self._reporter is not None:
            self._reporter.record_completed_step(name, duration_sec, detail)

    def _flush_log(self, *, final: bool) -> None:
        if not self._log_buf:
            return
        if final:
            complete, self._log_buf = self._log_buf, ""
        else:
            cut = self._log_buf.rfind("\n")
            if cut < 0:
                return
            complete, self._log_buf = self._log_buf[:cut], self._log_buf[cut + 1:]
        for line in complete.splitlines():
            if line.strip():
                self._reporter.on_log(line)

    def finish(
        self,
        error: str | None = None,
        awaiting_user: bool = False,
        awaiting_resume: bool = False,
    ) -> None:
        if self._fallback is not None:
            self._fallback.finish(
                error,
                awaiting_user=awaiting_user,
                awaiting_resume=awaiting_resume,
            )
            return
        if self._reporter is None:
            return
        self._flush_log(final=True)
        self._reporter.finish(
            error,
            awaiting_user=awaiting_user or awaiting_resume,
            awaiting_prompt=(
                "当前执行阶段已暂停,等待继续处理。"
                if awaiting_resume
                else ""
            ),
        )


def _is_same_topic_followup(value: str, host: Any = None, c_id: str = "") -> bool:
    """优先用请求级话题判定(LLM 带历史);没有则退回本地记忆判定。"""
    from app.services.chat_dashboard import _fallback_topic, get_topic_decision

    # 只读不清:同一请求内多处要读,清理由 api 层在请求结束时统一做。
    decision = get_topic_decision(c_id)
    if decision is not None:
        return decision.is_same_task
    if host is None:
        return False
    # context_overlap 只是词面重合,同领域新任务也会命中,不能拿来并图。
    decision = _fallback_topic(host, value)
    return decision.is_same_task and decision.reason != "context_overlap"


def report_command(
    command_name: str,
    task_digest: str,
    c_id: str = "",
    continuation_input: str = "",
    task_input: str = "",
) -> CommandDashboardReporter | _CommandContinuationDashboardReporter | None:
    """工厂:禁用环境返回 no-op 会话;聊天轮次期间返回 None;同话题追问并入原图。"""
    from app.services.chat_dashboard import (
        _is_placeholder,
        chat_turn_active,
        forget_topic_host,
        get_topic_host,
    )

    if chat_turn_active():
        return None
    initial_output = f"正在执行 /{command_name}...\n\n"
    if c_id and continuation_input:
        return _CommandContinuationDashboardReporter(
            command_name,
            task_digest,
            c_id,
            continuation_input,
            initial_output=initial_output,
            task_input=task_input,
        )
    # 追问并入本命令的原图;换命令一律另开。
    if c_id:
        host = get_topic_host(c_id)
        if str(getattr(host, "_wf_id", "") or "").startswith(f"cmd-{command_name}-") \
                and _is_same_topic_followup(task_digest, host, c_id):
            reporter = _CommandContinuationDashboardReporter(
                command_name,
                task_digest,
                c_id,
                task_digest,
                initial_output=initial_output,
                task_input=task_input,
                # 控制词才传 True,否则原话被改写成「继续处理」。
                placeholder=_is_placeholder(task_digest),
            )
            if reporter._reporter is not None:
                return reporter
    forget_topic_host(c_id)
    return CommandDashboardReporter(
        command_name,
        task_digest,
        c_id=c_id,
        initial_output=initial_output,
        task_input=task_input,
        entry_category=get_request_entry_category(),
    )


class _BestEffortCommandDashboard:
    """隔离画图的解析/推送异常,不修改命令正文或执行结果。"""

    def __init__(self, reporter):
        self._reporter = reporter
        self._warned: set[str] = set()

    def __getattr__(self, name):
        if name not in {"on_output", "on_step_completed", "finish"}:
            return getattr(self._reporter, name)

        def report(*args, **kwargs):
            def deliver():
                try:
                    return getattr(self._reporter, name)(*args, **kwargs)
                except Exception as exc:
                    if name not in self._warned:
                        self._warned.add(name)
                        logger.warning("Command dashboard %s skipped: %s", name, type(exc).__name__, exc_info=True)
                    return None

            owner = self._reporter
            if isinstance(owner, _CommandContinuationDashboardReporter):
                # 聊天续接共享话题记忆与定时刷新,留在正文循环;底层服务器异步接收事件。
                owner = owner._fallback
            server = getattr(owner, "_server", None)
            if server is not None:
                from app.model_agent.dashboard.server import DashboardServer

                if isinstance(server, DashboardServer) and server.dispatch_report(deliver):
                    return None
            return deliver()
        return report


def safe_report_command(*args, **kwargs):
    """命令入口共用的可降级看板;初始化失败同样不阻断业务。"""
    try:
        reporter = report_command(*args, **kwargs)
    except Exception as exc:
        logger.warning("Command dashboard initialization skipped: %s", type(exc).__name__, exc_info=True)
        return None
    return _BestEffortCommandDashboard(reporter) if reporter is not None else None