"""聊天会话 → 实时事件图:同一 c_id 可含多个问题,每题有自己的续接树。"""

from __future__ import annotations

import asyncio
import contextvars
import itertools
import json
import logging
import re
import time
from dataclasses import dataclass
from typing import Any

from app.model_agent.dashboard.titles import (
    _CATEGORY_ALIASES,
    COMMAND_CATEGORY_LABELS,
    compact_title,
    display_workflow_title,
    event_title,
    infer_command_category,
    is_internal_retry_instruction,
    semantic_title,
)
from app.model_agent.workflow.capability_events import clip
from app.model_agent.workflow.schemas import EdgeDef, EventType, NodeDef, WorkflowDef, WorkflowEvent
from app.services import chat_selection as _chat_selection
from app.services.command_dashboard import command_category_metadata
from app.services.execution_outcome import FAILURE_LABELS, TerminalOutcome, classify_terminal_outcome

logger = logging.getLogger(__name__)

# 仅放宽聊天看板的工具详情;共享工作流事件上限保持不变。
CHAT_TOOL_DETAIL_MAX_CHARS = 32_000

# Preserve the established chat_dashboard entry points for callers.
_NUMBERED_SELECTION_RE = _chat_selection._NUMBERED_SELECTION_RE
_is_numbered_reply_selection = _chat_selection._is_numbered_reply_selection
_report_menu_options = _chat_selection._report_menu_options
_reply_offers_menu = _chat_selection._reply_offers_menu
_menu_options = _chat_selection._menu_options
_numbered_reply_selection = _chat_selection._numbered_reply_selection
_menu_option_text = _chat_selection._menu_option_text
_menu_option_display_text = _chat_selection._menu_option_display_text
_selection_reply = _chat_selection._selection_reply
looks_like_numbered_choice = _chat_selection.looks_like_numbered_choice
numbered_reply_context = _chat_selection.numbered_reply_context
numbered_selection_context = _chat_selection.numbered_selection_context
numbered_reply_display_context = _chat_selection.numbered_reply_display_context
numbered_selection_display_context = _chat_selection.numbered_selection_display_context

# wf_id 唯一性兜底:同毫秒多 run 时间戳相同
_RUN_SEQ = itertools.count()

# 模型有时会在工具调用前只吐出一个句号/省略号;这不是可用的事件名。
def _event_label(value: Any) -> str:
    """清理事件标题的首尾空白/标点,避免占位符成为节点名。"""
    return semantic_title(value)


_INTERNAL_STEP_RE = re.compile(
    r"^(?:bash|shell|terminal|tool|invoke_[a-z0-9_]+|[a-z][a-z0-9]*_[a-z0-9_]+)$",
    re.I,
)
_INTERNAL_PLANNING_STEP_RE = re.compile(
    r"^(?:请不要重复询问同一个问题|请基于当前上下文、本地资源、已有配置和全部可用工具|"
    r"please do not ask the same question again|based on the current context)",
    re.IGNORECASE,
)
_GENERIC_STEP_RE = re.compile(
    r"^(?:步骤|下一步|操作|step)[。.!!::\s]*$",
    re.IGNORECASE,
)


def _semantic_step_label(value: Any) -> str:
    """只允许用户能理解的任务步骤进入问题分解图。"""
    label = _event_label(value)
    if (
        not label
        or _INTERNAL_STEP_RE.fullmatch(label.strip())
        or _INTERNAL_PLANNING_STEP_RE.match(label.strip())
        or _GENERIC_STEP_RE.fullmatch(label.strip())
        or is_internal_retry_instruction(label)
    ):
        return ""
    return label


def _json_object(value: Any) -> dict[str, Any]:
    """Return only an actual JSON object; never infer structure from prose."""
    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 {}


_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)

def _entry_command(value: str) -> str:
    # 纯文本一律 common;辅助命令由参数确定入口类别。
    slash = re.match(r"^/(\S+?)(?:[\s::·]|$)", value.strip(), re.I)
    return infer_command_category(value) if slash else "common"


def _slash_stem(value: str) -> str:
    slash = re.match(r"^/(\S+?)(?:[\s::·]|$)", str(value or "").strip(), re.I)
    return slash.group(1).casefold() if slash else ""

# c_id 定位当前问题;相关补充接续,明确的新问题另开 run。
_TOPIC_RUNS: dict[str, "ChatTurnDashboardReporter"] = {}
_TOPIC_RUN_LIMIT = 256
_TOPIC_SCOPE_SEQ = itertools.count()
_ACTIVE_TOPIC_SCOPES: dict[str, set[int]] = {}
_LATEST_TOPIC_SCOPE: dict[str, int] = {}
_SUSPENDED_TTL = 30 * 60
_pruned: set[int] = set()

# True 期间 report_command 返回 None:轮内 skill 不自建 run(会归档本 run 且丢帧)
_CHAT_TURN_ACTIVE: contextvars.ContextVar[bool] = contextvars.ContextVar(
    "chat_turn_active", default=False,
)

# 话题判定结果经请求上下文传给内层聊天流,避免重复调用分类器且防并发覆盖。
@dataclass(frozen=True)
class TopicDecision:
    """关系判定结果;c_id 只标识会话,不等于逻辑任务。"""

    relation: str  # same_task | new_task | ambiguous
    confidence: float = 0.0
    reason: str = ""
    candidate_task_id: str | None = None

    @property
    def is_new_task(self) -> bool:
        return self.relation == "new_task"

    @property
    def is_same_task(self) -> bool:
        return self.relation == "same_task"

    @property
    def isolates_task(self) -> bool:
        """Whether downstream state must be isolated from the previous task.

        ``ambiguous`` is deliberately isolated.  It is safer to lose a
        possible continuation than to attach a new request to the wrong
        workflow graph or realtime-evaluation parent.
        """
        return self.relation in {"new_task", "ambiguous"}


_TOPIC_HINT: contextvars.ContextVar[tuple[str, TopicDecision] | None] = contextvars.ContextVar(
    "chat_topic_hint", default=None,
)


@dataclass
class _TopicScope:
    c_id: str
    sequence: int
    initial_host: "ChatTurnDashboardReporter | None"
    reporter: "ChatTurnDashboardReporter | None" = None
    started: bool = False


_TOPIC_SCOPE: contextvars.ContextVar[_TopicScope | None] = contextvars.ContextVar(
    "chat_topic_scope", default=None,
)


def begin_topic_scope(c_id: str, selection: str = "") -> tuple[contextvars.Token, bool, int]:
    """Pin this stream's graph before another stream can replace the c_id host."""
    host = get_topic_host(c_id, selection)
    sequence = next(_TOPIC_SCOPE_SEQ)
    overlapping = bool(_ACTIVE_TOPIC_SCOPES.get(c_id))
    _ACTIVE_TOPIC_SCOPES.setdefault(c_id, set()).add(sequence)
    _LATEST_TOPIC_SCOPE[c_id] = sequence
    scope = _TopicScope(c_id, sequence, host)
    _ACTIVE_TOPIC_SCOPE_OBJECTS.setdefault(c_id, {})[sequence] = scope
    return _TOPIC_SCOPE.set(scope), overlapping, sequence


def end_topic_scope(c_id: str, sequence: int, token: contextvars.Token) -> None:
    active = _ACTIVE_TOPIC_SCOPES.get(c_id)
    if active is not None:
        active.discard(sequence)
        objects = _ACTIVE_TOPIC_SCOPE_OBJECTS.get(c_id)
        if objects is not None:
            objects.pop(sequence, None)
            if not objects:
                _ACTIVE_TOPIC_SCOPE_OBJECTS.pop(c_id, None)
        scope = _TOPIC_SCOPE.get()
        if (active and _LATEST_TOPIC_SCOPE.get(c_id) == sequence
                and scope is not None and not scope.started):
            _LATEST_TOPIC_SCOPE[c_id] = max(active)
        if not active:
            _ACTIVE_TOPIC_SCOPES.pop(c_id, None)
            _LATEST_TOPIC_SCOPE.pop(c_id, None)
    try:
        _TOPIC_SCOPE.reset(token)
    except ValueError:
        _TOPIC_SCOPE.set(None)


def is_latest_topic_scope(c_id: str, sequence: int) -> bool:
    return _LATEST_TOPIC_SCOPE.get(c_id) == sequence


# c_id 下的活跃流 seq → _TopicScope(弱引用快照,供 cross-request 归属校验)
_ACTIVE_TOPIC_SCOPE_OBJECTS: dict[str, dict[int, "_TopicScope"]] = {}


def iter_active_topic_scope_hosts(c_id: str, exclude_scope=None) -> list:
    """供「收尾挂起 run」前做归属校验:非 latest 接管流不会写 _TOPIC_RUNS。"""
    scopes = _ACTIVE_TOPIC_SCOPE_OBJECTS.get(c_id) or {}
    hosts = []
    for scope in scopes.values():
        if scope is exclude_scope:
            continue
        reporter = scope.reporter or scope.initial_host
        if reporter is not None and getattr(reporter, "_node_id", ""):
            hosts.append(reporter)
    return hosts


def mark_topic_scope_started(c_id: str) -> None:
    scope = _TOPIC_SCOPE.get()
    if scope is not None and scope.c_id == c_id:
        scope.started = True

# 分类器保持旧四参数调用形态,额外上下文经请求上下文传入,避免旧测试/集成替换分类器时签名失效。
_TOPIC_CLASSIFICATION_CONTEXT: contextvars.ContextVar[dict[str, Any] | None] = contextvars.ContextVar(
    "chat_topic_classification_context", default=None,
)

# 判题时保留最近几轮实质输入,避免只拿首问把后续补充错判成新题。
_RECENT_INPUT_LIMIT = 5


def chat_turn_active() -> bool:
    return _CHAT_TURN_ACTIVE.get()


def set_topic_hint(c_id: str, decision: TopicDecision | bool) -> None:
    """设置当前请求的话题判定;保留 bool 兼容入口。"""
    if isinstance(decision, TopicDecision):
        value = decision
    else:
        value = TopicDecision(
            "new_task" if decision else "same_task", 1.0, "legacy_hint",
        )
    _TOPIC_HINT.set((str(c_id or ""), value))


def get_topic_hint(c_id: str | None) -> bool | None:
    """读取当前请求的话题判定;不同会话不会复用 hint。"""
    value = _TOPIC_HINT.get()
    if value is None or value[0] != str(c_id or ""):
        return None
    return value[1].is_new_task


def get_topic_decision(c_id: str | None) -> TopicDecision | None:
    """读取完整判定;ambiguous 不能被旧 bool 接口静默折成续接。"""
    value = _TOPIC_HINT.get()
    if value is None or value[0] != str(c_id or ""):
        return None
    return value[1]


def clear_topic_hint() -> None:
    """清理当前异步上下文的话题判定。"""
    _TOPIC_HINT.set(None)


def _remember_topic(c_id: str, reporter: "ChatTurnDashboardReporter") -> None:
    """保留近期会话;只淘汰已结束项,活跃项交给执行路径收尾。"""
    scope = _TOPIC_SCOPE.get()
    if scope is not None and scope.c_id == c_id:
        scope.reporter = reporter
        if not is_latest_topic_scope(c_id, scope.sequence):
            return
    _TOPIC_RUNS.pop(c_id, None)
    _TOPIC_RUNS[c_id] = reporter
    if len(_TOPIC_RUNS) <= _TOPIC_RUN_LIMIT:
        return
    for key, run in list(_TOPIC_RUNS.items()):
        if len(_TOPIC_RUNS) <= _TOPIC_RUN_LIMIT:
            break
        if key != c_id and not run._node_id and not run._suspended_at:
            _TOPIC_RUNS.pop(key, None)


class ChatTurnDashboardReporter:
    """同一会话中的首问、补充、执行事件与工具调用。"""

    def __init__(
        self,
        thread_id: str,
        digest: str,
        c_id: str = "",
        entry_category: str = "",
    ) -> None:
        self._c_id = c_id or thread_id
        self._wf_id = f"chat-{thread_id or 'nothread'}-{int(time.time() * 1000)}-{next(_RUN_SEQ)}"
        self._initial_input = (digest or "聊天").strip()
        explicit_category = _CATEGORY_ALIASES.get(
            str(entry_category or "").strip().casefold(), "",
        )
        self._entry_category_explicit = bool(explicit_category)
        self._entry_category = (
            explicit_category
            if explicit_category in COMMAND_CATEGORY_LABELS
            else _entry_command(self._initial_input)
        )
        # Keep a readable user title from the first substantive input.  The
        # display layer performs stricter placeholder rejection for old runs;
        # a standalone "确认" can still be a real first user message.
        self._name = compact_title(
            self._initial_input,
            fallback="聊天",
            allow_punctuation=True,
        )
        self._server: Any = None
        self._nodes: list[NodeDef] = []
        self._edges: list[EdgeDef] = []
        self._pushed_def = False
        self._seq = 0
        self._node_id: str = ""  # 当前活跃顶层事件节点
        self._node_started_at = 0.0
        self._turn_anchor_ts: float = 0.0  # 与 workflow.started 同源的墙钟锚点
        self._started_emitted = False
        self._last_node_id: str | None = None
        self._def_sent: WorkflowDef | None = None
        self._suspended_at = 0.0
        self._last_reply = ""
        # A restored direct command has no chat turn, so keep its output in a
        # separate one-turn selection source instead of changing chat memory.
        self._direct_command_reply = ""
        self._reply_last_emitted_at = 0.0
        self._reply_revision = 0
        self._reply_emitted_revision = 0
        self._reply_flush_handle: asyncio.TimerHandle | None = None
        self._last_input = ""
        self._seen_call_ids: set[str] = set()
        self._call_to_name: dict[str, str] = {}  # call_id → 工具名,结果按 id 精配
        self._call_to_sub: dict[str, str] = {}  # call_id → 子事件 id,结果归组
        self._call_to_node: dict[str, str] = {}
        self._call_started_at: dict[str, float] = {}
        self._pending_skill_tools: list[str] = []
        self._skill_tool_args: dict[str, dict[str, Any]] = {}
        self._seen_skill_call_ids: set[str] = set()
        self._tool_seq = 0
        self._tool_error_seen = False
        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._root_id = "root"
        self._turn_count = 0
        self._sub_seq = 0
        self._sub_active: str = ""  # 当前活跃子事件 id
        self._sub_started_at = 0.0
        self._sub_reply = ""  # 当前子事件的流式正文,终态时保留完整输出
        self._last_step_id = ""
        self._blocked_step_id = ""
        self._first_input_done = False
        self._recent_inputs: list[str] = []
        self._last_finished_turn = 0
        self._root_interrupted = False
        self._last_terminal_status = "success"
        self._last_failure_kind = ""
        self._recovery_anchor_ids: list[str] = []

    def _category_for_input(self, value: str) -> str:
        """Use explicit request/eval category as authoritative over text prefixes."""
        if self._entry_category_explicit:
            return self._entry_category
        if re.match(r"^/[a-z][a-z0-9_-]*\b", (value or "").strip(), re.I):
            return _entry_command(value)
        return self._entry_category

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

    def _push(self, event_type: str, node_id: str | None, data: dict[str, Any]) -> None:
        if self._server is None:
            return
        try:
            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("Chat turn dashboard push failed: %s", exc)

    # ── 话题树结构 ─────────────────────────────────────────────────

    def _send_def(self, *, _first_bootstrap: bool = False) -> None:
        # 看板已降级为无头模式时静默跳过,不再触发 None 属性异常。
        if self._server is None:
            return
        wf = WorkflowDef(
            workflow_id=self._wf_id, name=self._name,
            nodes=self._nodes, edges=self._edges,
        )
        try:
            append_chat = getattr(self._server, "append_chat_nodes", None)
            if not self._pushed_def:
                self._server.set_workflow_def(wf)
                self._pushed_def = True
            elif _first_bootstrap:
                sent_nodes = self._def_sent.nodes if self._def_sent else []
                for node in self._nodes:
                    if all(existing.id != node.id for existing in sent_nodes):
                        (append_chat or self._server.append_workflow_nodes)(wf)
                        break
            else:
                (append_chat or self._server.append_workflow_nodes)(wf)
            self._def_sent = wf
        except Exception as exc:
            # 看板故障不得杀死聊天流;自愈后其余推送点按 _server is None 静默跳过。
            logger.warning("Chat turn dashboard def send failed: %s", exc)
            self._server = None

    def _ensure_turn_node(
        self,
        digest: str,
        *,
        label_override: str = "",
        repeated_input: bool = False,
        relation_kind: str = "",
    ) -> None:
        """用户提交时立即创建标题和执行节点,不等待模型或工具首帧。"""
        if self._node_id and self._node_started_at:
            return
        first_turn = not self._pushed_def
        if first_turn:
            self._nodes.append(NodeDef(
                id=self._root_id, label=self._name, type="topic_root", capability=None,
                metadata={
                    "description": self._initial_input,
                    "kind": "problem",
                    "request_kind": "chat",
                    "title_source": "user_input",
                    "c_id": self._c_id,
                    **command_category_metadata(self._entry_category, source="chat"),
                    "source_category_explicit": self._entry_category_explicit,
                },
            ))
        else:
            # 真实请求接续历史图后,不再按探针记录推断可见性
            root = next((node for node in self._nodes if node.type == "topic_root"), None)
            if root is not None:
                root.metadata["request_kind"] = "chat"
        node_id = f"turn{self._seq}"
        self._seq += 1
        self._turn_count += 1
        self._node_id = node_id
        self._last_node_id = node_id
        self._last_step_id = ""
        # 编号选择展开标题要用展开前的上轮回复;直接命令恢复结果只消费一次。
        previous_reply, report_style = _selection_reply(self)
        self._cancel_reply_flush()
        self._last_reply = ""
        self._direct_command_reply = ""
        self._reply_last_emitted_at = 0.0
        self._reply_revision = 0
        self._reply_emitted_revision = 0
        selected = _numbered_reply_selection(
            digest, previous_reply, report_style=report_style,
        )
        # 相同编号可在不同轮菜单里反复出现;编号(含无效编号)不是原问题的再次提问。
        if selected is not None or looks_like_numbered_choice(digest):
            repeated_input = False
        selection_label = ""
        if selected is not None and _chat_selection.parse_selection_number(digest) is not None:
            option = _menu_option_display_text(
                previous_reply, selected, report_style=report_style,
            )
            if option:
                selection_label = option
        label = (
            selection_label
            or _event_label(label_override)
            or event_title(digest, fallback="")
            or event_title(self._initial_input, fallback="")
            or "回应用户输入"
        ).replace("\n", " ")[:48]
        affected_step_ids: list[str] = []
        if not first_turn and not repeated_input:
            if relation_kind in {"resume", "retry"}:
                affected_step_ids = [
                    node_id for node_id in self._recovery_anchor_ids
                    if any(node.id == node_id for node in self._nodes)
                ]
            elif relation_kind not in {"continuation", "restart", "problem_repeat"}:
                affected_step_id = self._affected_step_id()
                if affected_step_id:
                    affected_step_ids = [affected_step_id]
        turn_kind = (
            "problem_execution" if first_turn else
            relation_kind if relation_kind else
            "problem_repeat" if repeated_input else
            "supplement"
        )
        self._nodes.append(NodeDef(
            id=node_id, label=label, type="task" if first_turn else "user_input",
            capability=None, metadata={
                "description": digest,
                "kind": turn_kind,
                **({"affected_step_id": affected_step_ids[0]} if len(affected_step_ids) == 1 else {}),
                **({"affected_step_ids": affected_step_ids} if len(affected_step_ids) > 1 else {}),
                # Follow-up turns usually omit the slash command. They remain
                # in the same problem tree and inherit its entry category;
                # slash commands only set the category without an explicit entry.
                **command_category_metadata(
                    self._category_for_input(digest),
                    source="chat",
                ),
                "source_category_explicit": self._entry_category_explicit,
            },
        ))
        relation = {
            "supplement": "补充信息",
            "resume": "恢复执行",
            "retry": "修复后重试",
            "continuation": "继续处理",
            "problem_repeat": "再次提问",
            "restart": "重新处理",
            "approval": "确认后执行",
            "rejection": "否决后重议",
        }.get(turn_kind)
        anchors = affected_step_ids or [self._root_id]
        for anchor in anchors:
            self._edges.append(EdgeDef(from_id=anchor, to_id=node_id, condition=relation))
        if affected_step_ids:
            self._blocked_step_id = ""
            self._recovery_anchor_ids = []
        if not first_turn or not self._turn_anchor_ts:
            self._turn_anchor_ts = time.time()
        if not self._server_ready():
            self._node_started_at = time.monotonic()
            return
        try:
            self._send_def(_first_bootstrap=first_turn)
            self._node_started_at = time.monotonic()
            if self._server is None:
                return
            if not self._started_emitted:
                self._push("workflow.started", None, {"status": "running"})
                self._started_emitted = True
            if first_turn:
                self._push("node.log", node_id, {"log_line": "已接收输入"})
                self._push("node.completed", self._root_id, {
                    "status": "success", "input_snapshot": self._initial_input,
                    # The root is a graph/title anchor.  The bottom timeline
                    # is an execution stream and filters this event even if
                    # it is replayed before the workflow definition.
                    "source": "user_input", "graph_only": True,
                })
            elif self._root_interrupted:
                self._push("node.started", self._root_id, {
                    "status": "running", "graph_only": True,
                    "source": "user_input", "relation": turn_kind,
                })
            self._push("node.started", node_id, {
                "status": "running", "input_snapshot": digest,
            })
        except Exception as exc:
            logger.warning("Chat turn dashboard def failed: %s", exc)
            self._server = None

    # ── 本轮生命周期 ───────────────────────────────────────────────

    def start_turn_node(
        self, digest: str, *, placeholder: bool = False,
        relation_kind: str = "", label_override: str = "",
    ) -> None:
        """实质问题立即入图;短续接词接等待中的轮,或创建续接事件。"""
        if placeholder:
            # 重启后没有内存中的话题树时,用会话历史里找到的真实首问建图;
            # placeholder 表示已认定接旧任务。
            if not self._first_input_done and digest and not _is_placeholder(digest):
                self._initial_input = digest.strip()
                self._name = compact_title(
                    self._initial_input,
                    fallback="聊天",
                    allow_punctuation=True,
                )
                self.start_turn_node(digest)
            elif self._first_input_done and not self._node_id:
                # 旧轮已经结束:本次续接仍需可见的顶层执行事件。
                self._last_input = digest
                relation_kind = {
                    "failed": "retry",
                    "interrupted": "resume",
                    "aborted": "resume",
                }.get(self._last_terminal_status, "continuation")
                self._ensure_turn_node(
                    digest,
                    relation_kind=relation_kind,
                    label_override=label_override,
                )
            if label_override and self._node_id:
                self._push("node.log", self._node_id, {
                    "log_line": f"{label_override}:{self._name}",
                })
            return
        digest = (digest or "").strip()
        self._last_input = digest
        repeated_input = _is_repeated_turn_input(self, digest)
        if digest and (not self._recent_inputs or self._recent_inputs[-1] != digest):
            self._recent_inputs.append(digest[:80])
            if len(self._recent_inputs) > _RECENT_INPUT_LIMIT:
                self._recent_inputs = self._recent_inputs[-_RECENT_INPUT_LIMIT:]
        if not self._first_input_done:
            self._first_input_done = True
            self._ensure_turn_node(
                digest, relation_kind=relation_kind, label_override=label_override,
            )
            return
        if self._node_id and self._node_started_at:
            # 等确认中来了新实质输入:挂起 turn 如实收尾
            self._close_pending_tools("工具调用未获确认,未执行")
            self.end_turn_node(self._last_reply, error="工具调用未获确认,未执行")
        # 上一轮等待用户的时间只属于旧轮;新轮从本次输入重新计时。
        self._suspended_at = 0.0
        if relation_kind == "restart":
            self._blocked_step_id = ""
            self._recovery_anchor_ids = []
        self._ensure_turn_node(
            digest, repeated_input=repeated_input,
            relation_kind=relation_kind, label_override=label_override,
        )

    @staticmethod
    def _terminal_status(error: str | None, explicit: str | None = None) -> str:
        """将异常原因映射为节点终态,区分失败、用户中断与连接中断。"""
        return classify_terminal_outcome(error, explicit).status

    @staticmethod
    def _terminal_outcome(error: str | None, explicit: str | None = None) -> TerminalOutcome:
        return classify_terminal_outcome(error, explicit)

    def _agent_task_elapsed_ms(self, started_at: float) -> int:
        now = time.time()
        if self._suspended_at:
            now -= max(0.0, time.monotonic() - self._suspended_at)
        return max(0, int((now - started_at) * 1000))

    def end_turn_node(
        self,
        text: str = "",
        *,
        error: str | None = None,
        status: str | None = None,
        error_detail: str | None = None,
    ) -> None:
        """闭合当前问题轮及未结束的执行事件。

        error 参与终态分类(四字 reason),error_detail 仅用于展示。
        """
        self._cancel_reply_flush()
        if self._sub_active:
            self._close_sub_event(self._sub_reply or text, error=error, status=status)
        if not self._node_id or self._node_started_at <= 0:
            return
        node_id = self._node_id
        self._node_id = ""
        outcome = self._terminal_outcome(error, status)
        terminal_status = outcome.status
        output = self._last_reply or text or ""
        data: dict[str, Any] = {
            **outcome.event_fields(),
            "output_summary": output[:500],
            "output_full": output,
        }
        if self._node_started_at:
            elapsed = ((self._suspended_at or time.monotonic()) - self._node_started_at) * 1000
            if self._turn_anchor_ts and not self._suspended_at:
                elapsed = max(elapsed, (time.time() - self._turn_anchor_ts) * 1000)
            data["elapsed_ms"] = int(max(0, elapsed))
            self._node_started_at = 0.0
        if error:
            shown = error_detail or error
            data["error"] = shown[:500]
            data["error_full"] = shown
        self._push("node.failed" if terminal_status != "success" else "node.completed", node_id, data)
        self._last_terminal_status = terminal_status
        self._last_failure_kind = outcome.failure_kind or ""
        if terminal_status == "success":
            self._recovery_anchor_ids = []
            self._blocked_step_id = ""
        elif not self._recovery_anchor_ids:
            self._recovery_anchor_ids = [self._blocked_step_id or node_id]

    @staticmethod
    def _merge_reply_text(previous: str, current: str) -> str:
        if not previous or current.startswith(previous):
            return current
        if previous.endswith(current):
            return previous
        return previous + current

    def record_reply(
        self,
        text: str,
        *,
        message_id: str = "",
        capture_substep: bool = True,
        output_reset: bool = False,
    ) -> str:
        """逐片追加回复;完整快照由调用方显式设置 output_reset。"""
        if self._last_finished_turn == self._turn_count:
            return self._last_reply
        value = str(text or "")
        if not value:
            return self._last_reply
        # 回复边界由本轮节点生命周期确定,不能用 chunk id 判定。
        self._last_reply = value if output_reset else self._last_reply + value
        self._reply_revision += 1
        if self._sub_active and capture_substep:
            previous_sub_reply = self._sub_reply
            self._sub_reply = value if output_reset else previous_sub_reply + value
            if self._sub_reply != previous_sub_reply and self._accepting_events():
                data = {
                    "output_chunk": value if output_reset
                    else self._sub_reply[len(previous_sub_reply):],
                }
                if output_reset:
                    data["output_reset"] = True
                self._push("node.output.chunk", self._sub_active, data)
        now = time.monotonic()
        if self._accepting_events() and (
            output_reset or now - self._reply_last_emitted_at >= 0.05
        ):
            self._cancel_reply_flush()
            self._flush_reply_output()
        elif self._accepting_events() and self._server is not None and self._reply_flush_handle is None:
            try:
                loop = asyncio.get_running_loop()
            except RuntimeError:
                pass
            else:
                self._reply_flush_handle = loop.call_later(
                    max(0.0, 0.05 - (now - self._reply_last_emitted_at)),
                    self._flush_reply_output,
                )
        return self._last_reply

    def _cancel_reply_flush(self) -> None:
        if self._reply_flush_handle is not None:
            self._reply_flush_handle.cancel()
            self._reply_flush_handle = None

    def _flush_reply_output(self) -> None:
        self._reply_flush_handle = None
        if not self._accepting_events() or self._reply_emitted_revision == self._reply_revision:
            return
        self._push("node.output", self._node_id, {
            "output_summary": clip(self._last_reply, 500),
            "output_full": self._last_reply,
        })
        self._reply_emitted_revision = self._reply_revision
        self._reply_last_emitted_at = time.monotonic()

    def record_confirmation_decision(self, *, approved: bool) -> None:
        """在原任务节点记录授权决定,避免伪造新任务。"""
        if self._node_id and self._accepting_events():
            action = "用户确认执行" if approved else "用户否决执行"
            self._push("node.log", self._node_id, {
                "log_line": f"{action}:{self._name}",
            })

    def resume_after_confirmation(self) -> None:
        """确认后恢复挂起节点;不创建新节点或改写已有输出。"""
        if not self._accepting_events():
            return
        if self._suspended_at:
            paused = max(0.0, time.monotonic() - self._suspended_at)
            self._node_started_at += paused
            if self._turn_anchor_ts:
                self._turn_anchor_ts += paused
            if self._sub_started_at:
                self._sub_started_at += paused
            for call_id in self._call_started_at:
                self._call_started_at[call_id] += paused
            for task_id in self._agent_task_started_at:
                self._agent_task_started_at[task_id] += paused
        self._suspended_at = 0.0
        self.record_confirmation_decision(approved=True)
        self._push("node.started", self._node_id, {
            "status": "running",
            "awaiting_user": False,
            "resumed_from": "confirmation",
        })
        if self._sub_active:
            self._push("node.started", self._sub_active, {
                "status": "running",
                "awaiting_user": False,
                "resumed_from": "confirmation",
            })
        for tool_node in dict.fromkeys(self._call_to_node.values()):
            if not tool_node:
                continue
            self._push("node.started", tool_node, {
                "status": "running",
                "awaiting_user": False,
                "resumed_from": "confirmation",
            })

    def _accepting_events(self) -> bool:
        """终态后拒收迟到的模型/工具帧,避免旧任务重新长出节点。"""
        return bool(
            self._node_id
            and self._node_started_at > 0
            and self._last_finished_turn != self._turn_count
        )

    # ── 子事件:决策轮折进顶层事件节点 ─────────────────────────────

    def _affected_step_id(self) -> str:
        """只关联真实受阻步骤;无确证时由首问根节点承接补充。"""
        return self._blocked_step_id

    def _start_step_node(self, label: str, description: str, *, kind: str) -> None:
        """创建语义步骤或仅供证据归属的内部执行节点。"""
        if not label or self._last_finished_turn == self._turn_count and self._turn_count:
            return
        self._ensure_turn_node(self._last_input or self._name)
        if not self._accepting_events():
            return
        if self._sub_active:
            self._close_sub_event(self._sub_reply)
        if kind == "semantic_step":
            # Agent 已自行进入下一实际步骤,之前的受阻步骤不再等待用户补充。
            self._blocked_step_id = ""
            self._recovery_anchor_ids = []
        label = label[:48]
        self._sub_seq += 1
        sub_id = f"turn{self._seq - 1}-sub{self._sub_seq}"
        self._sub_active = sub_id
        self._sub_started_at = time.monotonic()
        self._sub_reply = ""
        anchor = self._last_step_id or self._node_id
        anchor_kind = next(
            (node.metadata.get("kind") for node in reversed(self._nodes) if node.id == anchor),
            None,
        )
        relation = {
            "supplement": "基于补充继续",
            "resume": "恢复后继续",
            "retry": "重试后继续",
            "continuation": "继续处理",
            "problem_repeat": "重新处理",
            "restart": "重新开始后执行",
        }.get(anchor_kind)
        self._last_step_id = sub_id
        self._nodes.append(NodeDef(
            id=sub_id, label=label, type="task",
            metadata={"kind": kind, "parent_id": self._node_id,
                      "description": description},
        ))
        self._edges.append(EdgeDef(from_id=anchor, to_id=sub_id, condition=relation))
        if self._server is not None:
            self._send_def()
        self._push("node.started", sub_id, {
            "status": "running",
            "input_snapshot": description,
        })

    def start_step_node(self, intent: str) -> None:
        """用户可理解的决策意图成为问题分解步骤。"""
        label = _semantic_step_label(intent)
        if label:
            self._start_step_node(label[:48], intent, kind="semantic_step")

    def record_completed_step(self, intent: str, duration_sec: float, detail: str = "") -> None:
        """Record a helper step whose callback arrives only after completion."""
        label = _semantic_step_label(intent)
        if not label:
            return
        try:
            elapsed_sec = max(0.0, float(duration_sec or 0))
        except (TypeError, ValueError):
            elapsed_sec = 0.0
        self._start_step_node(label[:48], label, kind="semantic_step")
        if self._sub_active:
            self._sub_started_at = time.monotonic() - elapsed_sec
            self.close_step_node(detail)

    def _close_sub_event(
        self,
        summary: str = "",
        *,
        error: str | None = None,
        status: str | None = None,
    ) -> None:
        if not self._sub_active or not self._node_id:
            self._sub_active = ""
            return
        outcome = self._terminal_outcome(error, status)
        terminal_status = outcome.status
        data: dict[str, Any] = {
            **outcome.event_fields(),
            "output_summary": summary[:500],
            "output_full": summary,
        }
        if self._sub_started_at:
            data["elapsed_ms"] = int(max(0, ((self._suspended_at or time.monotonic())
                - self._sub_started_at) * 1000))
        if error:
            data["error"] = (error or "执行异常")[:500]
            data["error_full"] = error
        closed_id = self._sub_active
        self._push("node.failed" if terminal_status != "success" else "node.completed", closed_id, data)
        closed_node = next((node for node in reversed(self._nodes) if node.id == closed_id), None)
        if closed_node and closed_node.metadata.get("kind") == "semantic_step" \
                and terminal_status in {"failed", "interrupted", "aborted"}:
            self._blocked_step_id = closed_id
            self._recovery_anchor_ids = [closed_id]
        self._sub_active = ""
        self._sub_started_at = 0.0
        self._sub_reply = ""

    def close_step_node(self, text: str = "", *, error: str | None = None, status: str | None = None) -> None:
        """闭合当前子事件(顶层事件节点不受影响,等轮末统一闭合)。"""
        summary = self._merge_reply_text(self._sub_reply, text) if text else self._sub_reply
        self._close_sub_event(summary, error=error, status=status)

    # ── 工具与日志:工具有图节点,也保留所属事件的明细记录 ────────────

    def on_tool_calls(self, calls: list[dict], intent: str = "") -> None:
        """按 call_id 去重;工具节点与决策事件相连,结果仍归属该事件。"""
        if self._last_finished_turn == self._turn_count and self._turn_count:
            return
        calls = [tc for tc in calls if tc.get("id") and tc.get("name")
                 and str(tc["id"]) not in self._seen_call_ids]
        if not calls:
            return
        # 上一步的工具均已返回时,新工具决策开启下一步骤;即使模型没有
        # 另发总结正文,也要用真实工具结果闭合上一步,避免卡片一直等待。
        completed_step_calls = self._sub_active and any(
            node.type == "tool_call" and node.metadata.get("parent_id") == self._sub_active
            for node in self._nodes
        ) and self._sub_active not in self._call_to_sub.values()
        if self._sub_active and (self._sub_reply or completed_step_calls):
            self._close_sub_event(self._sub_reply)
        if not self._sub_active or not self._node_id:
            # 优先用可理解的模型意图或工具参数;内部工具名只作证据归属。
            args = calls[0].get("args")
            action = next((text for key in ("description", "prompt", "task", "query")
                           if isinstance(args, dict) and (text := _semantic_step_label(args.get(key)))), "")
            event_intent = _semantic_step_label(intent) or action
            if event_intent:
                self._start_step_node(event_intent[:48], intent or action, kind="semantic_step")
            else:
                internal_name = str(calls[0].get("name") or "tool")
                self._start_step_node(
                    internal_name[:48], _event_label(intent) or internal_name,
                    kind="internal_operation",
                )
        started: list[tuple[str, str, str, str, str, bool]] = []
        for tc in calls:
            call_id = str(tc.get("id") or "")
            if not call_id or not tc.get("name") or call_id in self._seen_call_ids:
                continue
            self._seen_call_ids.add(call_id)
            name = str(tc.get("name") or "tool")
            raw_args_full = _args_full(tc.get("args"))
            args_full = clip(raw_args_full, CHAT_TOOL_DETAIL_MAX_CHARS)
            args_truncated = len(raw_args_full) > CHAT_TOOL_DETAIL_MAX_CHARS
            args = clip(args_full, 500)
            self._tool_seq += 1
            tool_node = f"tool{self._tool_seq}"
            self._call_to_name[call_id] = name
            self._call_to_sub[call_id] = self._sub_active
            self._call_to_node[call_id] = tool_node
            self._call_started_at[call_id] = time.monotonic()
            self._nodes.append(NodeDef(
                id=tool_node, label=name[:48], type="tool_call",
                metadata={"kind": "tool_call", "parent_id": self._sub_active,
                          "call_id": call_id}, capability=name,
            ))
            self._edges.append(EdgeDef(from_id=self._sub_active, to_id=tool_node, condition=None))
            started.append((call_id, name, args, args_full, tool_node, args_truncated))
        if started and self._server is not None:
            self._send_def()
        for call_id, name, args, args_full, tool_node, args_truncated in started:
            self._push("node.started", tool_node, {
                "status": "running", "input_snapshot": args,
            })
            self._push("tool.started", self._sub_active, {
                "call_id": call_id,
                "tool": name,
                "arguments_summary": args,
                "arguments_full": args_full,
                "arguments_truncated": args_truncated,
                "sub_id": self._sub_active,
            })

    def on_tool_result(
        self,
        tool_call_id: str,
        content: str,
        *,
        error: bool = False,
        status: str | None = None,
    ) -> None:
        """ToolMessage 按原 id 闭合对应 tool 事件;未匹配 id(历史轮重放)静默忽略。"""
        name = self._call_to_name.pop(tool_call_id, None)
        parent_id = self._call_to_sub.pop(tool_call_id, "")
        tool_node = self._call_to_node.pop(tool_call_id, "")
        started_at = self._call_started_at.pop(tool_call_id, None)
        if name is None or self._server is None or not tool_node:
            return
        elapsed_ms = int(max(0, ((self._suspended_at or time.monotonic()) - started_at) * 1000)) \
            if started_at is not None else 0
        raw_result_full = str(content or "")
        result_full = clip(raw_result_full, CHAT_TOOL_DETAIL_MAX_CHARS)
        result = clip(raw_result_full, 500)
        result_truncated = len(raw_result_full) > CHAT_TOOL_DETAIL_MAX_CHARS
        data: dict[str, Any] = {
            "call_id": tool_call_id,
            "tool": name,
            "result_summary": result,
            "result_full": result_full,
            "result_truncated": result_truncated,
            "sub_id": parent_id,
            "elapsed_ms": elapsed_ms,
        }
        outcome = self._terminal_outcome(clip(raw_result_full or "工具调用失败") if error else None, status)
        terminal_status = outcome.status
        data["status"] = terminal_status
        terminal_error = terminal_status != "success"
        if terminal_error:
            self._tool_error_seen = True
            raw_error_full = raw_result_full or "tool error"
            data["error"] = clip(raw_error_full, 500)
            data["error_full"] = clip(raw_error_full, CHAT_TOOL_DETAIL_MAX_CHARS)
            data["error_truncated"] = len(raw_error_full) > CHAT_TOOL_DETAIL_MAX_CHARS
            data.update({
                "failure_kind": outcome.failure_kind or "execution_failure",
                "recoverable": outcome.recoverable,
                "failure_label": FAILURE_LABELS[outcome.failure_kind or "execution_failure"],
            })
        self._push("tool.failed" if terminal_error else "tool.completed", parent_id, data)
        self._push("node.failed" if terminal_error else "node.completed", tool_node, {
            **outcome.event_fields(), "output_summary": result[:500],
            "output_full": result_full,
            "output_truncated": result_truncated,
            "elapsed_ms": elapsed_ms,
            **({"error": data["error"]} if terminal_error else {}),
        })

    def on_log(self, text: str) -> None:
        """日志归属当前执行事件;没有子事件时归属本轮。"""
        if not self._accepting_events():
            return
        line = (text or "").strip()
        if line and self._last_node_id is not None:
            self._push("node.log", self._sub_active or self._last_node_id, {
                "log_line": line,
            })

    def _close_pending_tools(self, reason: str, *, status: str | None = None) -> None:
        for call_id in list(self._call_to_node):
            self.on_tool_result(call_id, reason, error=True, status=status)
        self._pending_skill_tools.clear()
        self._skill_tool_args.clear()

    def _plan_anchor_id(self) -> str:
        """Return a proven owner for explicit agent-created tasks."""
        if self._sub_active:
            node = next((item for item in reversed(self._nodes) if item.id == self._sub_active), None)
            if node and node.metadata.get("kind") == "semantic_step":
                return node.id
        return self._node_id or self._root_id

    def _task_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._sub_active or self._last_node_id or self._root_id

    @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 _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 not dependency:
                self._pending_task_dependencies.setdefault(node_id, set()).add(task_id)
                continue
            changed = self._append_task_edge(dependency, node_id, "显式依赖") or changed
        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 not target:
                self._pending_task_blocks.setdefault(node_id, set()).add(task_id)
                continue
            changed = self._append_task_edge(node_id, target, "显式依赖") or changed
        return changed

    def _resolve_task_dependency_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,
        anchor_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_id = self._agent_task_nodes.get(task_id) if task_id else None
        existing_id = existing_id or self._agent_task_calls.get(call_id)
        if existing_id:
            changed = self._add_task_dependency_edges(existing_id, self._task_dependencies(args))
            changed = self._add_task_block_edges(existing_id, self._task_blocks(args)) or changed
            if changed:
                self._send_def()
            return
        self._agent_task_seq += 1
        node_id = f"agent-task-{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()
        anchor = anchor_id or self._plan_anchor_id()
        if not any(node.id == anchor for node in self._nodes):
            anchor = self._plan_anchor_id()
        self._nodes.append(NodeDef(
            id=node_id,
            label=subject[:48],
            type="task",
            metadata={
                "kind": "semantic_step",
                "source": "agent_task",
                "parent_id": anchor,
                "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(anchor, 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_dependency_edges()
        self._send_def()

    def _update_agent_task(
        self,
        args: dict[str, Any],
        result: dict[str, Any],
        result_full: str,
    ) -> None:
        task_id = str(args.get("taskId") or args.get("task_id") or result.get("taskId") 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_dependency_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"))
            description = str(args.get("description") or "").strip()
            active_form = str(args.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 "").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.time()
            self._push("node.started", node_id, {
                "status": "running",
                "input_snapshot": description,
            })
        elif status == "completed":
            started_at = self._agent_task_started_at.pop(node_id, None)
            self._push("node.completed", node_id, {
                "status": "success",
                **({"elapsed_ms": self._agent_task_elapsed_ms(started_at)}
                   if started_at is not None else {}),
            })
        elif status == "deleted":
            started_at = self._agent_task_started_at.pop(node_id, None)
            self._push("node.completed", node_id, {
                "status": "skipped",
                **({"elapsed_ms": self._agent_task_elapsed_ms(started_at)}
                   if started_at is not None else {}),
            })
        elif status == "pending":
            self._agent_task_started_at.pop(node_id, None)
            self._push("node.started", node_id, {
                "status": "pending",
                "input_snapshot": description,
            })
        else:
            return
        self._agent_task_status[node_id] = status

    def _close_running_agent_tasks(self, error: str | None, status: str) -> None:
        for node_id, task_status in list(self._agent_task_status.items()):
            if task_status == "pending":
                self._push("node.completed", node_id, {
                    "status": "skipped",
                    "output_summary": "任务结束前未执行该步骤",
                })
                self._agent_task_status[node_id] = "skipped"
                continue
            if task_status != "in_progress":
                continue
            reason = error or "Agent 已结束,但未返回该任务终态"
            outcome = self._terminal_outcome(reason, status if error else "aborted")
            terminal = outcome.status
            started_at = self._agent_task_started_at.pop(node_id, None)
            self._push("node.failed", node_id, {
                **outcome.event_fields(),
                "error": reason,
                "error_full": reason,
                **({"elapsed_ms": self._agent_task_elapsed_ms(started_at)}
                   if started_at is not None else {}),
            })
            self._agent_task_status[node_id] = terminal
            if node_id not in self._recovery_anchor_ids:
                self._recovery_anchor_ids.append(node_id)

    def on_skill_tool(self, ev: dict) -> None:
        """skill 内工具往返生成工具节点;有 ID 精配,无 ID 只匹配唯一候选。"""
        if not self._accepting_events() or self._server is None:
            return
        name = str(ev.get("name") or "tool")
        phase = ev.get("phase")
        if phase == "started":
            self._tool_seq += 1
            call_id = f"skill-{ev.get('call_id') or self._tool_seq}"
            if call_id in self._seen_skill_call_ids:
                return
            self._seen_skill_call_ids.add(call_id)
            tool_node = f"tool{self._tool_seq}"
            args = _json_object(ev.get("arguments")) or _json_object(
                ev.get("brief_full") or ev.get("brief")
            )
            if name == "TaskUpdate" and not _task_update_changes_execution(args):
                self._pending_skill_tools.append(call_id)
                self._skill_tool_args[call_id] = args
                self._call_to_name[call_id] = name
                self._call_to_sub[call_id] = ""
                self._call_to_node[call_id] = ""
                self._call_started_at[call_id] = time.monotonic()
                return
            parent_id = self._task_tool_parent(name, args)
            self._pending_skill_tools.append(call_id)
            self._skill_tool_args[call_id] = args
            self._call_to_name[call_id] = name
            self._call_to_sub[call_id] = parent_id
            self._call_to_node[call_id] = tool_node
            self._call_started_at[call_id] = time.monotonic()
            self._nodes.append(NodeDef(
                id=tool_node, label=name[:48], type="tool_call", capability=name,
                metadata={"kind": "tool_call", "parent_id": parent_id,
                          "call_id": call_id},
            ))
            self._edges.append(EdgeDef(from_id=parent_id, to_id=tool_node, condition=None))
            self._send_def()
            raw_args_summary = str(ev.get("brief") or _args_brief(args))
            args_summary = clip(raw_args_summary, 500)
            structured_args_full = _args_full(ev.get("arguments"))
            raw_args_full = str(ev.get("brief_full") or structured_args_full or raw_args_summary)
            args_full = clip(raw_args_full, CHAT_TOOL_DETAIL_MAX_CHARS)
            self._push("node.started", tool_node, {
                "status": "running", "input_snapshot": args_summary,
            })
            self._push("tool.started", parent_id, {
                "call_id": call_id,
                "tool": name,
                "arguments_summary": args_summary,
                "arguments_full": args_full,
                "arguments_truncated": len(raw_args_full) > CHAT_TOOL_DETAIL_MAX_CHARS,
                "sub_id": parent_id,
            })
        elif phase in ("completed", "failed", "interrupted", "aborted", "cancelled") and self._pending_skill_tools:
            specified = f"skill-{ev.get('call_id')}" if ev.get("call_id") else ""
            if specified:
                if specified not in self._pending_skill_tools:
                    logger.warning("Ignoring skill tool result with unknown call_id: %s", specified)
                    self.on_log(f"工具结果无法归属:{name},call_id={specified}")
                    return
                call_id = specified
            else:
                matching = [cid for cid in self._pending_skill_tools
                            if self._call_to_name.get(cid) == name]
                if len(matching) == 1:
                    call_id = matching[0]
                elif len(self._pending_skill_tools) == 1:
                    call_id = self._pending_skill_tools[0]
                else:
                    logger.warning("Ignoring ambiguous skill tool result without call_id: %s", name)
                    reason = f"工具结果无法归属:{name},缺少 call_id 且存在多个候选调用"
                    self.on_log(reason)
                    # 无法归属时全部标失败并清掉 pending;继续等待会让整轮永远 running。
                    candidates = matching or list(self._pending_skill_tools)
                    for candidate in candidates:
                        if candidate in self._pending_skill_tools:
                            self._pending_skill_tools.remove(candidate)
                        self._skill_tool_args.pop(candidate, None)
                        self.on_tool_result(candidate, reason, error=True, status="failed")
                    return
            self._pending_skill_tools.remove(call_id)
            args = self._skill_tool_args.pop(call_id, {})
            parent_id = self._call_to_sub.pop(call_id, self._last_node_id)
            tool_node = self._call_to_node.pop(call_id, "")
            tool_name = self._call_to_name.pop(call_id, name)
            started_at = self._call_started_at.pop(call_id, None)
            elapsed_ms = ev.get("elapsed_ms")
            if elapsed_ms is None and started_at is not None:
                elapsed_ms = int((time.monotonic() - started_at) * 1000)
            raw_result_full = str(ev.get("result_full") or ev.get("result_summary") or ("完成" if phase == "completed" else ""))
            if tool_name == "TaskUpdate" and not _task_update_changes_execution(args):
                detail = str(ev.get("error") or ev.get("result_summary") or "")
                self.on_log(f"依赖已记录:taskId={args.get('taskId') or ''} "
                            f"{'失败:' + detail if phase != 'completed' else '成功'}")
                if phase == "completed":
                    result_data = _json_object(ev.get("result_data")) or _json_object(raw_result_full)
                    self._update_agent_task(args, result_data, raw_result_full)
                return
            result_full = clip(raw_result_full, CHAT_TOOL_DETAIL_MAX_CHARS)
            result = clip(str(ev.get("result_summary") or raw_result_full), 500)
            is_error_phase = phase != "completed"
            raw_error_full = str(ev.get("error_full") or ev.get("error") or raw_result_full or "工具调用失败") if is_error_phase else ""
            error_full = clip(raw_error_full, CHAT_TOOL_DETAIL_MAX_CHARS)
            error = clip(str(ev.get("error") or error_full), 500) if is_error_phase else ""
            result_data = _json_object(ev.get("result_data")) or _json_object(raw_result_full)
            data = {"call_id": call_id, "tool": tool_name, "result_summary": result,
                    "result_full": result_full,
                    "result_truncated": len(raw_result_full) > CHAT_TOOL_DETAIL_MAX_CHARS,
                    "sub_id": parent_id, "elapsed_ms": elapsed_ms or 0}
            outcome = self._terminal_outcome(raw_error_full if error else None, str(ev.get("status") or phase))
            if ev.get("status") in {"success", "failed", "interrupted", "aborted"} and outcome.status != ev["status"]:
                outcome = self._terminal_outcome(None, ev["status"])
            data["status"] = outcome.status
            if error:
                data["error"] = error
                data["error_full"] = error_full
                data["error_truncated"] = len(raw_error_full) > CHAT_TOOL_DETAIL_MAX_CHARS
                self._tool_error_seen = True
                data.update({
                    "failure_kind": outcome.failure_kind or "execution_failure",
                    "recoverable": outcome.recoverable,
                    "failure_label": FAILURE_LABELS[outcome.failure_kind or "execution_failure"],
                })
            self._push("tool.failed" if error else "tool.completed", parent_id, data)
            if tool_node:
                self._push("node.failed" if error else "node.completed", tool_node, {
                    **outcome.event_fields(),
                    "output_summary": result[:500],
                    "elapsed_ms": elapsed_ms or 0,
                    **({"error": error} if error else {}),
                })
            if not error and tool_name == "TaskCreate":
                self._register_agent_task(args, result_data, call_id, parent_id)
            elif not error and tool_name == "TaskUpdate":
                self._update_agent_task(args, result_data, raw_result_full)

    # ── 终态 ───────────────────────────────────────────────────────

    def finish(
        self,
        error: str | None = None,
        *,
        awaiting_user: bool = False,
        awaiting_prompt: str = "",
        error_detail: str | None = None,
    ) -> None:
        """awaiting_user 挂起不闭合;终态闭合 running 节点 + 推 run 终帧。

        error 分类终态,error_detail 仅用于展示。
        """
        if not self._pushed_def or self._last_finished_turn == self._turn_count:
            return
        if awaiting_user and not error:
            wait_reason = "confirmation" if re.search(
                r"即将调用[\s\S]*是否确认执行[??]?$", awaiting_prompt.strip(),
            ) else "input"
            if not self._suspended_at:
                self._suspended_at = time.monotonic()
            # 已收到正文时确认提示属于顶层交互;先用完整流式缓冲闭合步骤再混入。
            if self._sub_active and self._sub_reply:
                self._close_sub_event(self._sub_reply)
            if awaiting_prompt:
                self.record_reply(
                    awaiting_prompt,
                    message_id="dashboard-confirmation",
                    capture_substep=False,
                )
            self._cancel_reply_flush()
            self._flush_reply_output()
            if self._sub_active:
                self._push("node.started", self._sub_active, {
                    "status": "waiting",
                    "awaiting_user": True,
                    "wait_reason": wait_reason,
                })
            for tool_node in dict.fromkeys(self._call_to_node.values()):
                if not tool_node:
                    continue
                self._push("node.started", tool_node, {
                    "status": "waiting",
                    "awaiting_user": True,
                    "wait_reason": wait_reason,
                })
            if self._node_id and self._node_started_at:
                # Keep the turn open for the confirmation/resume request, but
                # expose its real state to the dashboard instead of leaving it
                # looking like an actively running node.
                self._push("node.started", self._node_id, {
                    "status": "waiting",
                    "input_snapshot": self._last_input,
                    "awaiting_user": True,
                    "wait_reason": wait_reason,
                    "elapsed_ms": max(0, int((self._suspended_at - self._node_started_at) * 1000)),
                    **({"confirmation_prompt": awaiting_prompt} if awaiting_prompt else {}),
                })
            if _TOPIC_RUNS.get(self._c_id) in (None, self):
                _remember_topic(self._c_id, self)
            return
        outcome = self._terminal_outcome(error)
        terminal_status = outcome.status
        shown_error = (error_detail or error) if error else None
        self._close_pending_tools(
            error or "工具结果未返回",
            status=terminal_status if error else None,
        )
        self._close_running_agent_tasks(error, terminal_status)
        if self._node_id and self._node_started_at:
            self.end_turn_node(
                self._last_reply, error=error, status=terminal_status,
                error_detail=error_detail,
            )
        if error is None:
            if self._root_interrupted:
                self._push("node.completed", self._root_id, {
                    "status": "success", "graph_only": True,
                    "source": "user_input", "recovered": True,
                })
                self._root_interrupted = False
            self._push("workflow.completed", None, {"status": "success"})
            self._last_terminal_status = "success"
            self._last_failure_kind = ""
            self._recovery_anchor_ids = []
            self._blocked_step_id = ""
        else:
            workflow_status = terminal_status
            if not self._recovery_anchor_ids and self._last_node_id:
                self._recovery_anchor_ids = [self._last_node_id]
            self._push("node.failed", self._root_id, {
                **outcome.event_fields(), "error": shown_error,
                "graph_only": True, "source": "user_input",
            })
            self._root_interrupted = True
            self._last_terminal_status = workflow_status
            self._last_failure_kind = outcome.failure_kind or ""
            self._push("workflow.failed", None, {
                **outcome.event_fields(), "error": shown_error,
            })
        self._last_finished_turn = self._turn_count
        if id(self) in _pruned:
            return
        if _TOPIC_RUNS.get(self._c_id) in (None, self):
            _remember_topic(self._c_id, self)

    # ── 接续拷贝 ───────────────────────────────────────────────────

    def adopt_state(self, host: "ChatTurnDashboardReporter") -> None:
        """接续 host 话题树:继承 id/名/节点链/未闭合节点/判定记忆。"""
        if host._reply_flush_handle is not None:
            host._cancel_reply_flush()
            host._flush_reply_output()
        self._wf_id = host._wf_id
        self._name = host._name
        # WorkflowBridge may have appended planning/execution nodes after this
        # reporter last sent its definition. Reusing the stale in-memory graph
        # would erase those nodes on the next chat turn.
        current = getattr(host._server, "_workflow_def", None)
        inactive = getattr(host._server, "_inactive_runs", {}).get(host._wf_id, {})
        stored = current if getattr(current, "workflow_id", None) == host._wf_id else inactive.get("workflow_def")
        if isinstance(stored, WorkflowDef):
            # The stored definition includes workflow steps; the reporter may
            # still hold newer chat turns queued for delivery to the server.
            by_id = {node.id: node for node in stored.nodes}
            ordered_ids = list(by_id)
            for node in host._nodes:
                if node.id not in by_id:
                    ordered_ids.append(node.id)
                by_id[node.id] = node
            self._nodes = [by_id[node_id] for node_id in ordered_ids]
            self._edges = list(stored.edges)
            seen_edges = {(edge.from_id, edge.to_id, edge.condition) for edge in self._edges}
            for edge in host._edges:
                key = (edge.from_id, edge.to_id, edge.condition)
                if key not in seen_edges:
                    self._edges.append(edge)
                    seen_edges.add(key)
        else:
            self._nodes = list(host._nodes)
            self._edges = list(host._edges)
        self._seq = host._seq  # 保留序号:root 占位不增 seq,从节点数推导会跳号
        self._root_id = host._root_id
        self._turn_count = host._turn_count
        self._last_finished_turn = host._last_finished_turn
        self._turn_anchor_ts = host._turn_anchor_ts
        self._sub_seq = host._sub_seq
        self._node_id = host._node_id
        self._node_started_at = host._node_started_at
        self._sub_active = host._sub_active
        self._sub_reply = host._sub_reply
        self._last_node_id = host._last_node_id
        self._last_step_id = host._last_step_id
        self._blocked_step_id = host._blocked_step_id
        self._sub_started_at = host._sub_started_at
        self._call_to_name = dict(host._call_to_name)
        self._call_to_sub = dict(host._call_to_sub)
        self._call_to_node = dict(host._call_to_node)
        self._call_started_at = dict(host._call_started_at)
        self._pending_skill_tools = list(host._pending_skill_tools)
        self._skill_tool_args = {key: dict(value) for key, value in host._skill_tool_args.items()}
        self._seen_skill_call_ids = set(host._seen_skill_call_ids)
        self._tool_seq = host._tool_seq
        self._tool_error_seen = host._tool_error_seen
        self._agent_task_nodes = dict(host._agent_task_nodes)
        self._agent_task_calls = dict(host._agent_task_calls)
        self._agent_task_status = dict(host._agent_task_status)
        self._agent_task_started_at = dict(host._agent_task_started_at)
        self._pending_task_dependencies = {
            key: set(value) for key, value in host._pending_task_dependencies.items()
        }
        self._pending_task_blocks = {
            key: set(value) for key, value in host._pending_task_blocks.items()
        }
        self._agent_task_seq = host._agent_task_seq
        self._seen_call_ids = set(host._seen_call_ids)
        self._first_input_done = host._first_input_done
        self._initial_input = host._initial_input
        self._entry_category = host._entry_category
        self._entry_category_explicit = host._entry_category_explicit
        self._last_input = host._last_input
        self._last_reply = host._last_reply
        self._direct_command_reply = host._direct_command_reply
        self._reply_last_emitted_at = host._reply_last_emitted_at
        self._reply_revision = host._reply_revision
        self._reply_emitted_revision = host._reply_emitted_revision
        self._recent_inputs = list(host._recent_inputs)
        self._root_interrupted = host._root_interrupted
        self._last_terminal_status = host._last_terminal_status
        self._last_failure_kind = host._last_failure_kind
        self._recovery_anchor_ids = list(host._recovery_anchor_ids)
        self._pushed_def = host._pushed_def
        self._def_sent = None
        self._server = host._server
        self._suspended_at = host._suspended_at
        self._seq = max([self._seq] + [int(m.group(1)) + 1 for node in self._nodes
            if (m := re.fullmatch(r"turn(\d+)", node.id))])
        self._tool_seq = max([self._tool_seq] + [int(m.group(1)) for node in self._nodes
            if (m := re.fullmatch(r"tool(\d+)", node.id))])
        self._agent_task_seq = max([self._agent_task_seq] + [int(m.group(1)) for node in self._nodes
            if (m := re.fullmatch(r"agent-task-(\d+)", node.id))])

    @classmethod
    def from_run_snapshot(cls, c_id: str, run: dict, server: Any) -> "ChatTurnDashboardReporter":
        """从持久化问题图恢复判题记忆与节点序号。"""
        reporter = cls(c_id, run.get("name") or "", c_id=c_id)
        reporter._server = server
        reporter._wf_id = run["workflow_id"]
        activate = getattr(server, "activate_run", None)
        if activate:
            activate(reporter._wf_id)
        reporter._nodes = [NodeDef(
            id=n["id"], label=n["label"], type=n.get("type") or "task",
            capability=n.get("capability"), metadata=n.get("metadata") or {},
            checklist=n.get("checklist"),
        ) for n in run["nodes"]]
        reporter._edges = [EdgeDef(**e) for e in run["edges"]]
        reporter._pushed_def = True
        reporter._first_input_done = True
        # Direct /workflow runs have plan steps but no topic_root.  Their
        # c_id metadata still lets a chat continuation adopt the same run.
        root = next((n for n in reporter._nodes if n.type == "topic_root"), None)
        if root is None:
            root = reporter._nodes[0] if reporter._nodes else None
        if root is None:
            return reporter
        reporter._root_id = root.id
        raw_root = next(n for n in run["nodes"] if n["id"] == root.id)
        reporter._initial_input = str(root.metadata.get("description") or raw_root.get("input_snapshot") or run.get("name") or "")
        persisted_category = str(root.metadata.get("source_category") or "").lower()
        persisted_category_explicit = bool(root.metadata.get("source_category_explicit"))
        reporter._entry_category = (
            persisted_category
            if persisted_category in COMMAND_CATEGORY_LABELS
            else _entry_command(reporter._initial_input)
        )
        reporter._entry_category_explicit = persisted_category_explicit
        reporter._name = display_workflow_title(run.get("name"), run["nodes"], workflow_id=run["workflow_id"])
        if root.type == "topic_root":
            root.label = reporter._name
        turn_ids = [int(m.group(1)) for n in reporter._nodes
                    if (m := re.fullmatch(r"turn(\d+)", n.id))]
        reporter._seq = max(turn_ids, default=-1) + 1
        reporter._turn_count = reporter._seq
        reporter._last_finished_turn = reporter._turn_count if run.get("final_status") != "incomplete" else max(0, reporter._turn_count - 1)
        turns = [n for n in reporter._nodes if re.fullmatch(r"turn\d+", n.id)]
        reporter._last_node_id = turns[-1].id if turns else None
        reporter._recent_inputs = [str(n.metadata.get("description") or "")[:80]
                                   for n in turns if n.metadata.get("description")][- _RECENT_INPUT_LIMIT:]
        if not reporter._recent_inputs and reporter._initial_input:
            reporter._recent_inputs = [reporter._initial_input[:80]]
        reporter._last_input = reporter._recent_inputs[-1] if reporter._recent_inputs else reporter._initial_input
        node_by_id = {n["id"]: n for n in run["nodes"]}
        root_status = str(node_by_id[root.id].get("status") or "")
        reporter._root_interrupted = root_status in {
            "failed", "interrupted", "aborted",
        } or (not turns and root_status in {"running", "waiting", "paused"})
        if reporter._last_node_id:
            last_turn_state = node_by_id[reporter._last_node_id]
            reporter._last_reply = str(
                last_turn_state.get("output_full")
                or last_turn_state.get("output_summary")
                or ""
            )
            persisted_terminal = str(last_turn_state.get("status") or "")
            if persisted_terminal in {"success", "failed", "interrupted", "aborted"}:
                reporter._last_terminal_status = persisted_terminal
            reporter._last_failure_kind = str(last_turn_state.get("failure_kind") or "")
        else:
            if str(run.get("workflow_id") or "").startswith("cmd-"):
                reporter._direct_command_reply = str(
                    node_by_id[root.id].get("output_full")
                    or node_by_id[root.id].get("output_summary")
                    or ""
                )
            if root_status in {"success", "failed", "interrupted", "aborted"}:
                reporter._last_terminal_status = root_status
            reporter._last_failure_kind = str(node_by_id[root.id].get("failure_kind") or "")
        reporter._sub_seq = max((int(m.group(1)) for n in reporter._nodes
                                 if (m := re.search(r"-sub(\d+)$", n.id))), default=0)
        steps = [n for n in reporter._nodes if n.id.startswith(f"{reporter._last_node_id}-sub")]
        if steps:
            reporter._last_step_id = steps[-1].id
            if node_by_id[steps[-1].id].get("status") == "running":
                reporter._sub_active = steps[-1].id
                reporter._sub_started_at = time.monotonic()
                reporter._sub_reply = str(
                    node_by_id[steps[-1].id].get("output_full")
                    or node_by_id[steps[-1].id].get("output_summary")
                    or ""
                )
        consumed_blocked_steps: set[str] = set()
        for node in reporter._nodes:
            if node.metadata.get("kind") not in {"supplement", "resume", "retry"}:
                continue
            affected = node.metadata.get("affected_step_id")
            if affected:
                consumed_blocked_steps.add(str(affected))
            affected_many = node.metadata.get("affected_step_ids")
            if isinstance(affected_many, list):
                consumed_blocked_steps.update(str(item) for item in affected_many if item)
        latest_turn_index = next((
            index for index in range(len(reporter._nodes) - 1, -1, -1)
            if reporter._nodes[index].id == reporter._last_node_id
        ), -1)
        reporter._blocked_step_id = next((
            node.id for node in reversed(reporter._nodes[latest_turn_index + 1:])
            if node.metadata.get("kind") == "semantic_step"
            and node.id not in consumed_blocked_steps
            and node_by_id.get(node.id, {}).get("status") in {"failed", "interrupted", "aborted"}
        ), "")
        if reporter._last_terminal_status in {"failed", "interrupted", "aborted"}:
            anchor = reporter._blocked_step_id or reporter._last_node_id or ""
            reporter._recovery_anchor_ids = [anchor] if anchor else []
        reporter._tool_seq = max((int(m.group(1)) for n in reporter._nodes
                                  if (m := re.fullmatch(r"tool(\d+)", n.id))), default=0)
        reporter._seen_call_ids = {str(n.metadata["call_id"]) for n in reporter._nodes
                                   if n.metadata.get("call_id")}
        reporter._seen_skill_call_ids = {
            call_id for call_id in reporter._seen_call_ids if call_id.startswith("skill-")
        }
        agent_tasks = [
            node for node in reporter._nodes
            if node.metadata.get("source") == "agent_task"
        ]
        reporter._agent_task_seq = max((
            int(match.group(1)) for node in agent_tasks
            if (match := re.fullmatch(r"agent-task-(\d+)", node.id))
        ), default=0)
        for node in agent_tasks:
            task_id = str(node.metadata.get("agent_task_id") or "")
            create_call_id = str(node.metadata.get("task_create_call_id") or "")
            if task_id:
                reporter._agent_task_nodes[task_id] = node.id
            if create_call_id:
                reporter._agent_task_calls[create_call_id] = node.id
            persisted_status = str(node_by_id.get(node.id, {}).get("status") or "pending")
            reporter._agent_task_status[node.id] = {
                "running": "in_progress",
                "success": "completed",
                "skipped": "deleted",
            }.get(persisted_status, persisted_status)
            if persisted_status == "running":
                started_at = node_by_id.get(node.id, {}).get("started_at")
                if isinstance(started_at, (int, float)):
                    reporter._agent_task_started_at[node.id] = float(started_at)
        if run.get("final_status") == "incomplete" and reporter._last_node_id \
                and node_by_id[reporter._last_node_id].get("status") in {"running", "waiting", "paused"}:
            reporter._node_id = reporter._last_node_id
            turn_state = node_by_id[reporter._node_id]
            elapsed = max(0.0, float(turn_state.get("elapsed_ms") or 0) / 1000)
            now = time.monotonic()
            reporter._node_started_at = now - elapsed
            reporter._turn_anchor_ts = time.time() - elapsed
            if turn_state.get("status") in {"waiting", "paused"}:
                reporter._suspended_at = now
            steps = [n for n in reporter._nodes if n.id.startswith(f"{reporter._node_id}-sub")]
            if steps:
                reporter._sub_active = steps[-1].id
                sub_elapsed = max(0.0, float(node_by_id.get(steps[-1].id, {}).get("elapsed_ms") or 0) / 1000)
                reporter._sub_started_at = now - sub_elapsed
                reporter._sub_reply = str(
                    node_by_id.get(steps[-1].id, {}).get("output_full")
                    or node_by_id.get(steps[-1].id, {}).get("output_summary")
                    or ""
                )
            for node in reporter._nodes:
                call_id = node.metadata.get("call_id")
                if call_id and node_by_id.get(node.id, {}).get("status") in {"running", "waiting", "paused"}:
                    reporter._call_to_node[str(call_id)] = node.id
                    reporter._call_started_at[str(call_id)] = now - max(0.0,
                        float(node_by_id[node.id].get("elapsed_ms") or 0) / 1000)
        return reporter


def _args_full(args: Any) -> str:
    """工具参数的完整序列化值;事件详情保留它,摘要另行裁剪。"""
    if args is None or args == "" or args == {}:
        return ""
    try:
        import json
        value = args if isinstance(args, str) else json.dumps(args, ensure_ascii=False, default=str)
        return str(value)
    except Exception:
        return str(args)


def _args_brief(args: Any) -> str:
    """工具参数摘要,保留旧的 500 字符行级展示语义。"""
    return clip(_args_full(args), 500)


# ── 新话题判定:记忆式轻量 LLM ─────────────────────────────────────

_TOPIC_PROMPT = (
    "你在判断用户这条消息应接到当前问题图,还是创建新问题图。"
    "c_id 只是会话标识,不能单独决定归属。"
    "继续、确认、对原任务的补充、更改要求、追问均属于同一问题;"
    "目标和对象与当前任务无关的新请求属于新问题;证据不足时返回 ambiguous,"
    "不能猜测。\n"
    "初始问题: {title}\n"
    "最近的实质输入: {recent}\n"
    "最近的回复: {reply}\n"
    "当前状态: {state}\n"
    "入口类别: {entry_category}\n"
    "最近输入距现在: {age}\n"
    "新输入: {new_input}\n"
    '只输出 JSON: {{"relation": "same_task"|"new_task"|"ambiguous", '
    '"confidence": 0.0, "reason": "简短原因"}}'
)

_TOPIC_CONFIDENCE_THRESHOLD = 0.55


def _verified_topic_decision(
    relation: str,
    confidence: float,
    reason: str,
    candidate_task_id: str | None = None,
) -> TopicDecision:
    """Keep uncertain model verdicts from attaching input to the wrong task."""
    if relation != "ambiguous" and confidence < _TOPIC_CONFIDENCE_THRESHOLD:
        relation = "ambiguous"
        reason = f"low_confidence:{reason}" if reason else "low_confidence"
    return TopicDecision(relation, confidence, reason, candidate_task_id)


def _topic_decision_from_raw(raw: Any, *, reason: str = "") -> TopicDecision | None:
    """Normalize structured classifier output and the pre-existing bool API."""
    if isinstance(raw, TopicDecision):
        relation = raw.relation if raw.relation in {"same_task", "new_task", "ambiguous"} else "ambiguous"
        try:
            confidence = max(0.0, min(1.0, float(raw.confidence)))
        except (TypeError, ValueError):
            confidence = 0.0
        return _verified_topic_decision(
            relation, confidence, raw.reason or reason, raw.candidate_task_id,
        )
    # Older test doubles and integrations returned ``same_topic`` as a bool.
    # True means continuation; False means a new task.
    if isinstance(raw, bool):
        return TopicDecision("same_task" if raw else "new_task", 0.5, "legacy_bool")
    if not isinstance(raw, dict):
        return None
    relation = raw.get("relation")
    if relation not in {"same_task", "new_task", "ambiguous"}:
        same_topic = raw.get("same_topic")
        if isinstance(same_topic, bool):
            relation = "same_task" if same_topic else "new_task"
        else:
            return None
    confidence = raw.get("confidence", 0.0)
    try:
        confidence = max(0.0, min(1.0, float(confidence)))
    except (TypeError, ValueError):
        confidence = 0.0
    return _verified_topic_decision(
        relation,
        confidence,
        str(raw.get("reason") or reason)[:240],
        str(raw.get("candidate_task_id") or "") or None,
    )


def _topic_context(host: "ChatTurnDashboardReporter") -> dict[str, str]:
    """Build bounded context for the classifier without leaking tool output."""
    if host._suspended_at:
        state = "waiting_confirmation"
    elif host._node_id:
        state = "running"
    elif host._last_finished_turn:
        state = "completed"
    else:
        state = "created"
    entry_category = host._entry_category or "common"
    age = "unknown"
    if host._last_input:
        # The classifier should use time only as supporting evidence.  Do not
        # make wall-clock age part of the routing rule itself.
        age = "recent"
    return {"state": state, "entry_category": entry_category[:32], "age": age}


async def _classify_with_llm(title: str, recent: list[str], new_input: str, reply: str = "") -> TopicDecision | bool | None:
    """Lightweight structured classifier; failures return ``None``."""
    try:
        from langchain_anthropic import ChatAnthropic

        from app.core.llm_factory import _resolve_anthropic_config

        api_key, base_url, model = _resolve_anthropic_config()
        if not api_key:
            return None
        kwargs: dict[str, Any] = {
            "model": model or "claude-3-5-sonnet-20241022",
            "anthropic_api_key": api_key,
            # 预留足够 token,避免只返回思考块而没有文本结果
            "max_tokens": 512,
            "temperature": 0.0,
            "default_request_timeout": 30,
        }
        if base_url:
            kwargs["anthropic_api_url"] = base_url
        llm = ChatAnthropic(**kwargs)
        context = _TOPIC_CLASSIFICATION_CONTEXT.get() or {}
        # 菜单/选择问句在长回复尾部:改截头 80 + 尾 80,短回复原样。
        reply_window = (
            f"{reply[:80]}…{reply[-80:]}" if len(reply) > 160 else reply
        ) if reply else ""
        prompt = _TOPIC_PROMPT.format(
            title=title[:80],
            recent=" | ".join(recent[-3:])[:200] or "(无)",
            reply=reply_window or "(无)",
            state=str(context.get("state") or "unknown"),
            entry_category=str(context.get("entry_category") or "common"),
            age=str(context.get("age") or "unknown"),
            new_input=new_input[:200],
        )
        resp = await llm.ainvoke(prompt)
        import json as _json

        def _verdict(text: str) -> TopicDecision | None:
            text = (text or "").strip()
            if "{" not in text:
                return None
            try:
                m = _json.JSONDecoder().raw_decode(text[text.find("{"):])
            except (ValueError, TypeError):
                return None
            return _topic_decision_from_raw(m[0] if m else None, reason="llm")

        # text 块优先;思考被截断时 thinking 尾部常含结论(same_topic: true/false),兜底捞一次
        content = getattr(resp, "content", "") or ""
        blocks = content if isinstance(content, list) else [{"type": "text", "text": str(content)}]
        for block_type in ("text", "thinking"):
            for b in blocks:
                if isinstance(b, dict) and b.get("type") == block_type:
                    v = _verdict(b.get("text") or b.get("thinking") or "")
                    if v is not None:
                        return v
        return None
    except Exception as exc:
        logger.warning("Topic classify failed, isolating uncertain task: %s", type(exc).__name__)
        return None


_CTRL_WORD = (
    r"(?:确认|确定|确认执行|确定执行|确认续跑|继续回复|继续|继续执行|接着|恢复|续跑|"
    r"好的|好|可以|同意|执行|开始|行|嗯|"
    r"yes|ok|go|continue|confirmed|"
    r"等等|再等等|先等等|稍等)[呀吧啊呢哈嘛哦啦嘞]?"
)
# 习惯上会连说几个确认词(「可以,行,开始吧」),整串都是控制词才算。
_PLACEHOLDER_RE = re.compile(rf"^(?:{_CTRL_WORD})+[。!!,,\s]*$", re.I)
_RESTART_RE = re.compile(r"^(?:请)?(?:重新开始|从头开始|重头开始)(?:吧|呀)?[。!!,,\s]*$")
_REASK_SAME_RE = re.compile(
    r"^(?:请)?(?:再问|重新问|再提问|重新提问)(?:一遍|一次|一下)?"
    r"(?:刚才|上面|之前|同一个|原)(?:的|那个)?问题[。!!??,,\s]*$"
)
# 语气词只接单字核心词,断句分隔的空格归一后再匹配(「好,开始」这类复合确认)。
_PLACEHOLDER_SEP = re.compile(r"[\s,,]+")
_FOLLOWUP_RE = re.compile(r"^(?:补充|继续|接着|还有|以及|刚才|上面|之前|这个|它|该|那|请按|帮我把)")
# 指代前缀也可能是换题的开场:「那顺便问下量化怎么做」不指当前图。
_TOPIC_SHIFT_RE = re.compile(
    r"另一个|另外一?个?|另一(?:个|种|款)?(?:模型|任务|问题|项目|话题)|"
    r"新问题|新任务|新话题|全新(?:的)?(?:问题|任务|话题|验证)|"
    r"换个|换一个|顺便|下一个|再问(?:一|个)|再查(?:一|个)(?![遍次轮])"
)
# 裸反问要上轮有回复可指代才接续;带自身主题的问句不匹配。
_SHORT_QUESTION_RE = re.compile(
    r"^(?:这|那)?(?:是)?(?:"
    r"(?:啥|什么)(?:意思|含义|情况|回事|问题)"
    r"|(?:为什么|为啥|怎么|咋)(?:会)?(?:这样|如此)"
    r"|(?:为什么|为啥)"
    r"|(?:怎么|咋)(?:回事|理解|解释|办)?"
    r"|何解"
    r")(?:呢|呀|啊|吧)?[。!!,,??\s]*$"
)
_NEW_TOPIC_RE = re.compile(r"^(?:新问题|换个话题|另一个问题|另外一个问题|重新问|不谈上面|先不管上面)")
_GREETING_RE = re.compile(r"^(?:hello|hi|hey|(?:你好|您好|嗨)(?:呀|啊)?|ping|pong)[。!!,,\s]*$", re.I)
_ARITHMETIC_EXPRESSION_RE = re.compile(r"^\d+(?:\s*[+\-*/×÷]\s*\d+)+\s*(?:[==]\s*)?[??]?$")


def _is_placeholder(value: str) -> bool:
    return bool(_PLACEHOLDER_RE.fullmatch(_PLACEHOLDER_SEP.sub("", value.strip())))


def is_restart_request(value: str) -> bool:
    """仅裸控制语句重开当前任务,带具体对象的请求仍按实质问题判断。"""
    return bool(_RESTART_RE.fullmatch((value or "").strip()))


def is_repeat_request(value: str) -> bool:
    """明确指向原题的再次提问,不能被「重新问」的新话题规则截走。"""
    return bool(_REASK_SAME_RE.fullmatch((value or "").strip()))


def is_non_task_message(value: str) -> bool:
    """仅空输入不创建节点;短词也可能是用户的真实问题。"""
    return not bool((value or "").strip())


def _topic_input_key(value: str) -> str:
    """Ignore model-name case while preserving case-sensitive paths and repository IDs."""
    text = value.strip()
    command = re.match(r"^/[A-Za-z][\w-]*(?=\s|$)", text)
    args = text[command.end():] if command else text
    if re.search(
        r"https?://\S+|(?<!\S)(?:/|~/|\./|\.\./)\S+|(?<!\S)[\w.-]+/[\w.-]+",
        args, re.I,
    ):
        return command.group().casefold() + args if command else text
    return text.casefold()


def _is_repeated_turn_input(host: "ChatTurnDashboardReporter", value: str) -> bool:
    """只有重问原题才标为再次提问;重复补充仍是补充。"""
    text = _topic_input_key(value)
    return bool(text and text == _topic_input_key(host._initial_input))


def _is_repeated_supplement_input(host: "ChatTurnDashboardReporter", value: str) -> bool:
    """使用图中完整补充文本快速接续,避免重复选择被分类为新任务。"""
    text = _topic_input_key(value)
    return bool(text and any(
        node.metadata.get("kind") == "supplement"
        and text == _topic_input_key(str(node.metadata.get("description") or ""))
        for node in host._nodes
    ))


def _fallback_topic(host: "ChatTurnDashboardReporter", new_input: str) -> TopicDecision:
    """Offline fallback: only strong evidence joins; uncertainty is isolated."""
    text = new_input.strip()
    if _NEW_TOPIC_RE.match(text):
        return TopicDecision("new_task", 1.0, "explicit_new_topic")
    if _GREETING_RE.fullmatch(text):
        return TopicDecision("new_task", 1.0, "greeting_is_real_input")
    if is_restart_request(text):
        return TopicDecision("same_task", 1.0, "explicit_restart")
    if is_repeat_request(text):
        return TopicDecision("same_task", 1.0, "explicit_repeat")
    # 与 classify_topic 对齐:控制词只改变执行方式,承接的是上一轮任务。
    if _is_placeholder(text):
        return TopicDecision("same_task", 1.0, "control_placeholder")
    if _FOLLOWUP_RE.match(text):
        # 指代前缀带换题短语时是指向别处,不并入当前图。
        if _TOPIC_SHIFT_RE.search(text):
            return TopicDecision("new_task", 0.9, "shift_phrase_in_followup")
        return TopicDecision("same_task", 0.9, "explicit_followup")
    # 裸反问只指代上轮,无上文按不确定隔离。
    if _SHORT_QUESTION_RE.fullmatch(text):
        if str(_selection_reply(host)[0] or "").strip():
            return TopicDecision("same_task", 0.9, "short_question_reference")
        return TopicDecision("ambiguous", 0.0, "short_question_without_context")
    # 近期输入和首问中的独特词仍出现,视作接续;短句保守接续。
    context = " ".join([host._initial_input, *host._recent_inputs[-3:]]).lower()
    words = re.findall(r"[a-z][a-z0-9_-]{2,}|[\u4e00-\u9fff]{2,}", text.lower())
    if any(word in context for word in words):
        return TopicDecision("same_task", 0.65, "context_overlap")
    # 上轮给了编号菜单时,编号指代菜单项。
    reply, report_style = _selection_reply(host)
    if reply.strip() and _numbered_reply_selection(text, reply, report_style=report_style) is not None:
        return TopicDecision("same_task", 0.9, "numbered_reply_selection")
    return TopicDecision("ambiguous", 0.0, "insufficient_context")


def _fallback_new_topic(host: "ChatTurnDashboardReporter", new_input: str) -> bool:
    """Compatibility wrapper for callers that still consume a bool."""
    return _fallback_topic(host, new_input).is_new_task


async def classify_topic(host: "ChatTurnDashboardReporter" | None, new_input: str) -> TopicDecision:
    """Classify a message as continuation, new task, or uncertain.

    Control words are handled lexically before the model.  This keeps
    confirmation/resume flows stable and ensures ``ambiguous`` never silently
    reuses an old workflow or scoring parent.
    """
    text = (new_input or "").strip()
    if not text:
        return TopicDecision("same_task", 1.0, "empty_input")
    if host is None:
        return TopicDecision("ambiguous", 0.0, "no_current_task")
    if is_restart_request(text):
        return TopicDecision("same_task", 1.0, "explicit_restart")
    if is_repeat_request(text):
        return TopicDecision("same_task", 1.0, "explicit_repeat")
    if _is_placeholder(text):
        return TopicDecision("same_task", 1.0, "control_placeholder")
    if is_internal_retry_instruction(text):
        return TopicDecision("same_task", 1.0, "internal_retry_continuation")
    selection_reply, report_style = _selection_reply(host)
    if _numbered_reply_selection(
        text, selection_reply, report_style=report_style,
    ) is not None:
        return TopicDecision("same_task", 1.0, "numbered_reply_selection")
    if _NEW_TOPIC_RE.match(text):
        return TopicDecision("new_task", 1.0, "explicit_new_topic")
    if _ARITHMETIC_EXPRESSION_RE.fullmatch(text):
        return TopicDecision("new_task", 1.0, "standalone_arithmetic_expression")
    new_stem_command = _slash_stem(text)
    current_stem_command = _slash_stem(host._initial_input)
    if new_stem_command and current_stem_command and new_stem_command != current_stem_command:
        return TopicDecision("new_task", 1.0, "command_category_changed")
    if text.startswith("/"):
        new_stem = text.split(None, 1)[0].casefold()
        recent_stems = {
            (item.strip().split(None, 1)[0].casefold())
            for item in host._recent_inputs
        }
        if new_stem in recent_stems and not _is_placeholder(text):
            if _topic_input_key(text) not in (
                _topic_input_key(item) for item in host._recent_inputs
            ):
                return TopicDecision("new_task", 1.0, "same_command_new_object")
    if _FOLLOWUP_RE.match(text):
        if _TOPIC_SHIFT_RE.search(text):
            return TopicDecision("new_task", 0.9, "shift_phrase_in_followup")
        return TopicDecision("same_task", 0.9, "explicit_followup")
    # 裸反问同上,有上文才接续。
    if _SHORT_QUESTION_RE.fullmatch(text) and (host._last_reply or "").strip():
        return TopicDecision("same_task", 0.9, "short_question_reference")
    # 问候每次新开图,先于重复文本判定。
    if _GREETING_RE.fullmatch(text):
        return TopicDecision("new_task", 1.0, "greeting_is_real_input")
    # A repeated message is a new execution round, but it belongs to the same
    # logical task and must never be de-duplicated.
    if _is_repeated_turn_input(host, text):
        return TopicDecision("same_task", 1.0, "same_text_new_round", host._wf_id)
    if _is_repeated_supplement_input(host, text):
        return TopicDecision("same_task", 1.0, "repeated_supplement")
    context_token = _TOPIC_CLASSIFICATION_CONTEXT.set(_topic_context(host))
    try:
        import asyncio
        import time as _time
        _t0 = _time.monotonic()
        try:
            raw = await asyncio.wait_for(
                _classify_with_llm(host._initial_input, host._recent_inputs, text, host._last_reply),
                timeout=3,
            )
        except Exception:
            raw = None
        _elapsed = _time.monotonic() - _t0
        # 首字节延迟观测:>1.5s 或失败记 warning,正常耗时 debug 级。
        if raw is None:
            logger.warning("topic LLM classify failed in %.2fs, falling back to lexical", _elapsed)
        elif _elapsed > 1.5:
            logger.warning("topic LLM classify slow: %.2fs (>1.5s), first-byte impacted", _elapsed)
        else:
            logger.debug("topic LLM classify took %.2fs", _elapsed)
        decision = _topic_decision_from_raw(raw, reason="llm")
    finally:
        _TOPIC_CLASSIFICATION_CONTEXT.reset(context_token)
    return decision or _fallback_topic(host, text)


async def classify_new_topic(host: "ChatTurnDashboardReporter" | None, new_input: str) -> bool:
    """Backward-compatible bool facade; new code should use ``classify_topic``."""
    # The legacy bool API historically treated a reporter without substantive
    # memory as "continue".  Keep that narrow compatibility behavior while
    # the structured API still reports the correct ``ambiguous``/``new_task``
    # relation to new callers.
    if host is None or not (new_input or "").strip() or not host._recent_inputs:
        return False
    return (await classify_topic(host, new_input)).is_new_task


def take_suspended_run(c_id: str) -> ChatTurnDashboardReporter | None:
    """确认轮取回挂起的 run。"""
    return _TOPIC_RUNS.pop(c_id, None)


def get_topic_host(c_id: str, selection: str = "") -> ChatTurnDashboardReporter | None:
    """优先当前图;显式编号未命中时从新到旧精确查找历史菜单。"""
    scope = _TOPIC_SCOPE.get()
    if scope is not None and scope.c_id == c_id:
        return scope.reporter or scope.initial_host
    host = _TOPIC_RUNS.get(c_id)
    selection = (selection or "").strip()
    selection_lookup = bool(selection and _NUMBERED_SELECTION_RE.fullmatch(selection))
    if host is not None and (
        not selection_lookup or numbered_reply_context(host, selection) is not None
    ):
        return host
    if not c_id:
        return host
    from app.model_agent.dashboard.runtime import dashboard_server_or_none

    server = dashboard_server_or_none(warn_label="Chat topic host")
    if server is None:
        return host
    try:
        if selection_lookup:
            list_runs = getattr(server, "list_runs", None)
            get_run = getattr(server, "get_run", None)
            if callable(list_runs) and callable(get_run):
                summaries = sorted(
                    (
                        item for item in list_runs()
                        if str(item.get("topic_id") or "") == c_id
                    ),
                    key=lambda item: float(item.get("started_at") or 0),
                    reverse=True,
                )
                for summary in summaries:
                    if host is not None and summary.get("workflow_id") == host._wf_id:
                        continue
                    run = get_run(str(summary.get("workflow_id") or ""))
                    if run is None:
                        continue
                    candidate = ChatTurnDashboardReporter.from_run_snapshot(c_id, run, server)
                    if numbered_reply_context(candidate, selection) is None:
                        continue
                    _remember_topic(c_id, candidate)
                    return candidate
            return host
        run = server.find_chat_run(c_id)
        if run is None:
            return host
        host = ChatTurnDashboardReporter.from_run_snapshot(c_id, run, server)
        _remember_topic(c_id, host)
        return host
    except Exception as exc:
        logger.warning("Chat topic history recovery failed: %s", exc)
        return host


def forget_topic_host(c_id: str) -> None:
    """显式新任务替换会话当前问题时,丢弃仅存于内存的旧图引用。"""
    if c_id:
        _TOPIC_RUNS.pop(c_id, None)


def forget_deleted_run(workflow_id: str) -> None:
    """单条历史删除后丢弃对应的会话图记忆,避免续接时复活旧图。"""
    for c_id, host in list(_TOPIC_RUNS.items()):
        if host._wf_id == workflow_id:
            _TOPIC_RUNS.pop(c_id, None)


def cancel_suspended_run(c_id: str, reason: str = "用户中断") -> bool:
    """结束等待中的 run;主动停止与自动切换使用不同终止原因。"""
    scope = _TOPIC_SCOPE.get()
    reporter = (
        scope.reporter or scope.initial_host
        if scope is not None and scope.c_id == c_id
        else _TOPIC_RUNS.get(c_id)
    )
    if reporter is None or not reporter._suspended_at:
        return False
    if _TOPIC_RUNS.get(c_id) is reporter:
        _TOPIC_RUNS.pop(c_id, None)
    try:
        reporter.finish(reason)
    except Exception as exc:
        logger.warning("Chat dashboard suspended run cancel failed: %s", exc)
    finally:
        if _TOPIC_RUNS.get(c_id) is reporter:
            _TOPIC_RUNS.pop(c_id, None)
    return True


def prune_suspended_runs(
    now: float | None = None,
    has_pending_confirmation=None,
) -> None:
    now = now or time.monotonic()
    expired = [(c, r) for c, r in _TOPIC_RUNS.items()
               if r._suspended_at and now - r._suspended_at > _SUSPENDED_TTL]
    for c_id, reporter in expired:
        grace = (
            has_pending_confirmation is not None
            and has_pending_confirmation(c_id)
        )
        if grace:
            continue
        _pruned.add(id(reporter))
        try:
            reporter.finish("用户长时间未确认,自动中断")
        except Exception:
            pass
        _pruned.discard(id(reporter))
        _TOPIC_RUNS.pop(c_id, None)


def open_chat_turn_dashboard(
    thread_id: str, digest: str, c_id: str = "",
    *, placeholder: bool = False, new_topic: bool = False,
    entry_category: str = "",
) -> ChatTurnDashboardReporter | None:
    """同 c_id 接续话题树;新问题或归属不明时由调用方要求新开 run。

    旧 run 归档由新 run 首个 set_workflow_def 兜底。
    """
    key = c_id or thread_id
    try:
        host = get_topic_host(key, digest)
        if placeholder and host is None and _is_placeholder(digest):
            return None
        reporter = ChatTurnDashboardReporter(
            thread_id,
            digest,
            c_id=c_id,
            entry_category=entry_category,
        )
        if not reporter._server_ready():
            return None
        if host is not None and host is not reporter and not new_topic:
            reporter.adopt_state(host)
            activate = getattr(reporter._server, "activate_run", None)
            if activate:
                activate(reporter._wf_id)
        _remember_topic(key, reporter)  # 接续/新开都接管注册表位
        return reporter
    except Exception as exc:
        logger.warning("Chat turn dashboard open failed: %s", exc)
        return None