"""CommandDashboardReporter 测试——direct command → 看板伪 run 映射。"""

from __future__ import annotations

import dataclasses
import json

import pytest

from app.services.command_dashboard import (
    COMMAND_CATEGORY_LABELS,
    CommandDashboardReporter,
    _CommandContinuationDashboardReporter,
    command_category_metadata,
    report_command,
)


@pytest.fixture(autouse=True)
def _enable_dashboard_for_reporting(monkeypatch):
    monkeypatch.setenv("WORKFLOW_DASHBOARD_ENABLED", "true")


class _FakeServer:
    def __init__(self):
        self.calls = []
        self.events = []
        self.definitions = []
        self._workflow_def = None

    def set_workflow_def(self, wf):
        self._workflow_def = wf
        self.definitions.append(wf)
        self.calls.append(("def", wf.name))

    def append_workflow_nodes(self, wf):
        self._workflow_def = wf
        self.definitions.append(wf)

    def push_event(self, ev):
        self.events.append(ev)
        self.calls.append((ev.event_type.value, ev.data))

    def _archive_current_run(self):
        self.calls.append(("archive", None))

    def find_chat_run(self, c_id):
        """按 root 节点的 c_id 找回当前图,模拟真实 server 的恢复路径。"""
        if self._workflow_def is None:
            return None
        root = self._workflow_def.nodes[0] if self._workflow_def.nodes else None
        metadata = getattr(root, "metadata", None) or {}
        if metadata.get("c_id") != c_id:
            return None
        # 回复落在 node.output 的 output_full,恢复时据此判「上轮有上文」。
        outputs: dict[str, str] = {}
        for ev in self.events:
            if ev.event_type.value == "node.output" and ev.node_id:
                outputs[ev.node_id] = str(ev.data.get("output_full") or "")
        return {
            "workflow_id": self._workflow_def.workflow_id,
            "name": self._workflow_def.name,
            "nodes": [{"id": n.id, "label": n.label, "type": n.type,
                       "capability": n.capability, "metadata": dict(n.metadata),
                       "checklist": n.checklist or [],
                       "output_full": outputs.get(n.id, "")} for n in self._workflow_def.nodes],
            "edges": [dataclasses.asdict(e) for e in self._workflow_def.edges],
            "started_at": 0, "events": [], "node_state": {},
        }


def _reporter(monkeypatch, command="adapt", digest="Boltz2 迁移") -> tuple[CommandDashboardReporter, _FakeServer]:
    from app.model_agent.dashboard import server as dash_server
    fake = _FakeServer()
    monkeypatch.setattr(dash_server.DashboardServer, "get_instance", classmethod(lambda cls, config=None: fake))
    return CommandDashboardReporter(command, digest), fake


def test_short_command_logs_are_visible_before_finish(monkeypatch):
    reporter, server = _reporter(monkeypatch)
    reporter.on_output("检查模型")
    assert not any(event.event_type.value == "node.log" for event in server.events)
    reporter.on_output("文件完成\n下一段")
    assert [event.data["log_line"] for event in server.events
            if event.event_type.value == "node.log"] == ["检查模型文件完成"]
    assert reporter._log_buf == "下一段"


def test_long_command_log_without_newline_is_not_discarded(monkeypatch):
    reporter, server = _reporter(monkeypatch)
    text = "真实执行输出" * 430
    reporter.on_output(text)
    reporter.on_output(",完成\n")
    logs = [event.data["log_line"] for event in server.events
            if event.event_type.value == "node.log"]
    assert "".join(logs) == text + ",完成"
    assert reporter._log_buf == ""


def test_skill_activity_flushes_partial_log_without_fabricating_output(monkeypatch):
    from app.tools.claude_tools import CommandOutput

    reporter, server = _reporter(monkeypatch)
    reporter.on_output("已取得真实诊断")
    reporter.on_output(CommandOutput(content="", activity=True))
    assert [event.data["log_line"] for event in server.events
            if event.event_type.value == "node.log"] == ["已取得真实诊断"]
    assert "".join(reporter._output_parts) == "已取得真实诊断"


def test_slash_command_categories_are_stable():
    expected = {
        "common": "通用", "workflow": "全流程体验", "search": "查询", "doc": "文档",
        "deploy": "部署", "verify": "验证", "adapt": "适配", "optimize": "优化",
        "quantify": "量化", "commit": "一键提交", "ai4s": "AI for Science",
        "torch": "TorchNPU 问题接口",
    }
    assert COMMAND_CATEGORY_LABELS == expected
    assert command_category_metadata("/ADAPT") == {
        "source": "slash_command",
        "source_category": "adapt",
        "source_category_label": "适配",
    }
    assert command_category_metadata("unknown")["source_category"] == "common"


def test_commands_started_in_same_millisecond_keep_separate_graphs(monkeypatch, tmp_path):
    from app.model_agent.dashboard.config import DashboardConfig
    from app.model_agent.dashboard.server import DashboardServer
    from app.services import command_dashboard

    server = DashboardServer(DashboardConfig(enabled=False, history_dir=str(tmp_path)))
    monkeypatch.setattr(DashboardServer, "get_instance", classmethod(lambda cls, config=None: server))
    monkeypatch.setenv("WORKFLOW_DASHBOARD_ENABLED", "true")
    monkeypatch.setattr(command_dashboard.time, "time", lambda: 1_800_000_000.0)
    first = CommandDashboardReporter("verify", "检查甲模型", c_id="task-a")
    second = CommandDashboardReporter("verify", "检查乙模型", c_id="task-b")
    assert first._wf_id != second._wf_id

    first.on_output("甲第一段\n")
    second.on_output("乙第一段\n")
    first.on_output("甲异常前结果\n")
    first.finish(error="甲受控异常")
    second.on_output("乙最后一段\n")
    second.finish()

    for reporter, topic, expected, status in [
        (first, "task-a", "甲第一段\n甲异常前结果\n", "failed"),
        (second, "task-b", "乙第一段\n乙最后一段\n", "success"),
    ]:
        run = server.get_run(reporter._wf_id)
        assert run["topic_id"] == topic
        assert run["final_status"] == status
        root = next(node for node in run["nodes"] if node["id"] == "verify")
        assert root["output_full"] == expected


def test_command_node_contains_source_category_metadata(monkeypatch):
    r, fake = _reporter(monkeypatch, command="torch")
    node = fake._workflow_def.nodes[0]
    assert node.metadata == {
        "source": "slash_command",
        "source_category": "torch",
        "source_category_label": "TorchNPU 问题接口",
        "kind": "problem",
        "title_source": "user_input",
        "description": "Boltz2 迁移",
    }
    assert node.capability is None
    assert node.type == "topic_root"


def test_command_node_preserves_chat_c_id_when_provided(monkeypatch):
    from app.model_agent.dashboard import server as dash_server

    fake = _FakeServer()
    monkeypatch.setattr(
        dash_server.DashboardServer,
        "get_instance",
        classmethod(lambda cls, config=None: fake),
    )
    CommandDashboardReporter("ai4s", "分析 qwen3.5-0.8B", c_id="chat-42")

    node = fake._workflow_def.nodes[0]
    assert node.metadata["c_id"] == "chat-42"
    assert node.metadata["source_category"] == "ai4s"


def test_explicit_common_input_keeps_direct_command_dashboard_common(monkeypatch):
    from app.model_agent.dashboard import server as dash_server
    from app.model_agent.dashboard.titles import display_workflow_title
    from app.services import chat_dashboard

    fake = _FakeServer()
    monkeypatch.setattr(
        dash_server.DashboardServer, "get_instance",
        classmethod(lambda cls, config=None: fake),
    )
    from app.services.command_dashboard import reset_request_entry_category, set_request_entry_category

    token, _, sequence = chat_dashboard.begin_topic_scope(
        "common-direct-input", "/search deepseek",
    )
    entry_token = set_request_entry_category("通用")
    try:
        reporter = report_command("search", "deepseek", c_id="common-direct-input")
        assert isinstance(reporter, CommandDashboardReporter)
        root = fake._workflow_def.nodes[0]
        assert root.metadata["source_category"] == "common"
        assert root.metadata["source_category_explicit"] is True
        assert display_workflow_title(
            fake._workflow_def.name, fake._workflow_def.nodes,
            workflow_id=fake._workflow_def.workflow_id,
        ) == "通用 · /search deepseek"
    finally:
        reset_request_entry_category(entry_token)
        chat_dashboard.end_topic_scope("common-direct-input", sequence, token)


def test_torch_command_starts_a_linked_analysis_step_and_streams_its_output(monkeypatch):
    from app.model_agent.dashboard import server as dash_server
    from app.tools.claude_tools import CommandOutput

    fake = _FakeServer()
    monkeypatch.setattr(
        dash_server.DashboardServer,
        "get_instance",
        classmethod(lambda cls, config=None: fake),
    )
    question = (
        "950PR 单卡 HCCL 初始化失败:逻辑卡 0 映射物理卡 4,"
        "RaHdcInit(phyId=4) 成功,但 VNIC 查询误用 phyId=0,返回错误码 19。"
    )
    reporter = report_command("torch", question, c_id="frontend-session-950pr")

    assert isinstance(reporter, CommandDashboardReporter)
    definition = fake._workflow_def
    assert [node.id for node in definition.nodes] == ["torch", "torch-analysis"]
    assert definition.nodes[0].metadata["c_id"] == "frontend-session-950pr"
    assert definition.nodes[1].metadata["kind"] == "semantic_step"
    assert definition.edges[0].from_id == "torch"
    assert definition.edges[0].to_id == "torch-analysis"
    analysis_start = next(
        event for event in fake.events
        if event.event_type.value == "node.started" and event.node_id == "torch-analysis"
    )
    assert analysis_start.data["input_snapshot"] == question

    reporter.on_output(CommandOutput(content="问题分类:底层依赖 CANN / HCCL\n"))
    reporter.on_step_completed("核对逻辑卡与物理卡映射", 0.25, "VNIC 查询设备号不一致")
    reporter.finish()

    analysis_output = [
        event for event in fake.events
        if event.event_type.value == "node.output.chunk" and event.node_id == "torch-analysis"
    ]
    assert [event.data["output_chunk"] for event in analysis_output] == [
        "问题分类:底层依赖 CANN / HCCL\n",
    ]
    step = next(node for node in fake._workflow_def.nodes if node.metadata.get("source") == "pta_helper")
    assert step.metadata["parent_id"] == "torch-analysis"
    assert ("torch-analysis", step.id, "执行步骤") in {
        (edge.from_id, edge.to_id, edge.condition) for edge in fake._workflow_def.edges
    }
    analysis_terminal = next(
        event for event in fake.events
        if event.event_type.value == "node.completed" and event.node_id == "torch-analysis"
    )
    assert analysis_terminal.data["status"] == "success"
    assert "问题分类:底层依赖 CANN / HCCL" in analysis_terminal.data["output_full"]


def test_torch_direct_llm_step_starts_with_question_and_only_records_answer(monkeypatch):
    from app.tools.claude_tools import CommandOutput

    question = "950PR 单卡 HCCL 初始化失败,逻辑卡 0 对应物理卡 4。"
    reporter, fake = _reporter(monkeypatch, command="torch", digest=question)

    reporter.on_output(CommandOutput(content="[直接 LLM]\n\n"))
    step = next(node for node in fake._workflow_def.nodes if node.metadata.get("source") == "pta_helper")
    assert step.label == "LLM 推理"
    started = next(event for event in fake.events
                   if event.event_type.value == "node.started" and event.node_id == step.id)
    assert started.data["input_snapshot"] == question

    reporter.on_output(CommandOutput(content="物理卡 4 的 VNIC 地址需要核对。"))
    reporter.on_step_completed("LLM 推理", 18.51, "")
    reporter.finish()

    step_output = [event.data["output_chunk"] for event in fake.events
                   if event.event_type.value == "node.output.chunk" and event.node_id == step.id]
    assert step_output == ["物理卡 4 的 VNIC 地址需要核对。"]
    completed = next(event for event in fake.events
                     if event.event_type.value == "node.completed" and event.node_id == step.id)
    assert completed.data["input_snapshot"] == question
    assert completed.data["output_full"] == "物理卡 4 的 VNIC 地址需要核对。"
    root_output = [event.data["output_chunk"] for event in fake.events
                   if event.event_type.value == "node.output.chunk" and event.node_id == "torch"]
    assert root_output == ["[直接 LLM]\n\n", "物理卡 4 的 VNIC 地址需要核对。"]


def test_torch_empty_llm_answer_is_not_marked_success(monkeypatch):
    from app.tools.claude_tools import CommandOutput

    reporter, fake = _reporter(monkeypatch, command="torch", digest="检查 HCCL")
    reporter.on_output(CommandOutput(content="[直接 LLM]\n\n"))
    step = next(node for node in fake._workflow_def.nodes if node.metadata.get("source") == "pta_helper")
    reporter.finish("PTA 模型未返回有效正文,回答未完成")

    failed = next(event for event in fake.events
                  if event.event_type.value == "node.failed" and event.node_id == step.id)
    assert failed.data["input_snapshot"] == "检查 HCCL"
    assert not failed.data.get("output_full")


def test_command_continuation_without_matching_history_falls_back_to_new_run(monkeypatch):
    from app.model_agent.dashboard import server as dash_server
    from app.services import chat_dashboard

    fake = _FakeServer()
    fake.find_chat_run = lambda _c_id: None
    monkeypatch.setattr(
        dash_server.DashboardServer,
        "get_instance",
        classmethod(lambda cls, config=None: fake),
    )
    chat_dashboard._TOPIC_RUNS.pop("missing-history", None)
    try:
        reporter = report_command(
            "adapt",
            "适配 qwen3.5-0.8B",
            c_id="missing-history",
            continuation_input="继续",
        )
        assert reporter is not None
        assert fake._workflow_def.workflow_id.startswith("cmd-adapt-")
    finally:
        chat_dashboard._TOPIC_RUNS.pop("missing-history", None)


def test_command_continuation_resume_pause_maps_to_chat_waiting_state():
    from app.services.command_dashboard import _CommandContinuationDashboardReporter

    captured = {}

    class _FakeChatReporter:
        def finish(self, error=None, awaiting_user=False, awaiting_prompt=""):
            captured.update({
                "error": error,
                "awaiting_user": awaiting_user,
                "awaiting_prompt": awaiting_prompt,
            })

    reporter = object.__new__(_CommandContinuationDashboardReporter)
    reporter._fallback = None
    reporter._reporter = _FakeChatReporter()
    reporter._log_buf = ""

    reporter.finish(awaiting_resume=True)

    assert captured == {
        "error": None,
        "awaiting_user": True,
        "awaiting_prompt": "当前执行阶段已暂停,等待继续处理。",
    }


def test_new_direct_command_discards_stale_in_memory_topic(monkeypatch):
    from app.model_agent.dashboard import server as dash_server
    from app.services import chat_dashboard

    fake = _FakeServer()
    monkeypatch.setattr(
        dash_server.DashboardServer,
        "get_instance",
        classmethod(lambda cls, config=None: fake),
    )
    stale = object()
    chat_dashboard._TOPIC_RUNS["reused-cid"] = stale
    try:
        reporter = report_command("adapt", "新的适配任务", c_id="reused-cid")
        assert isinstance(reporter, CommandDashboardReporter)
        assert "reused-cid" not in chat_dashboard._TOPIC_RUNS
    finally:
        chat_dashboard._TOPIC_RUNS.pop("reused-cid", None)


@pytest.mark.parametrize("followup", ["啥意思?", "为什么会这样", "继续", "补充一下",
                                       "那个报错还在吗", "帮我把结果转Word"])
def test_torch_followup_joins_original_graph_instead_of_new_run(monkeypatch, followup):
    """追问并入原图,不再出现两张。"""
    from app.model_agent.dashboard import server as dash_server
    from app.services import chat_dashboard

    fake = _FakeServer()
    monkeypatch.setattr(
        dash_server.DashboardServer,
        "get_instance",
        classmethod(lambda cls, config=None: fake),
    )
    chat_dashboard._TOPIC_RUNS.pop("torch-followup", None)
    try:
        first = report_command("torch", "950PR 单卡 HCCL 报错 19", c_id="torch-followup")
        assert isinstance(first, CommandDashboardReporter)
        first.on_output("先确认 RaHdcInit 用哪个号。")
        first.finish()
        original_wf_id = first._wf_id

        reporter = report_command("torch", followup, c_id="torch-followup")

        assert isinstance(reporter, _CommandContinuationDashboardReporter)
        assert reporter._reporter is not None
        assert reporter._reporter._wf_id == original_wf_id
        turn = reporter._reporter._nodes[-1]
        assert turn.metadata["description"] == followup
        # 追问原话要留在节点标题上,不能被改写成「继续处理」。
        assert turn.label != "继续处理"
    finally:
        chat_dashboard._TOPIC_RUNS.pop("torch-followup", None)


@pytest.mark.parametrize("relation,expect_join", [
    ("same_task", True), ("new_task", False), ("ambiguous", False),
])
def test_torch_uses_request_scoped_topic_decision(monkeypatch, relation, expect_join):
    """请求级判定(带历史/LLM)优先于本地词表。"""
    from app.model_agent.dashboard import server as dash_server
    from app.services import chat_dashboard

    fake = _FakeServer()
    monkeypatch.setattr(
        dash_server.DashboardServer,
        "get_instance",
        classmethod(lambda cls, config=None: fake),
    )
    chat_dashboard._TOPIC_RUNS.pop("torch-hint", None)
    try:
        first = report_command("torch", "950PR HCCL error 19 排查", c_id="torch-hint")
        first.on_output("两个方向:\n1 转 Word\n2 填数据")
        first.finish()
        # 词表抓不到的措辞,只能靠请求级判定区分接续/新题。
        text = "嗯这个我懂了"
        chat_dashboard.set_topic_hint("torch-hint", chat_dashboard.TopicDecision(relation, 0.9, "llm"))
        reporter = report_command("torch", text, c_id="torch-hint")

        assert isinstance(reporter, _CommandContinuationDashboardReporter) is expect_join
    finally:
        chat_dashboard.clear_topic_hint()
        chat_dashboard._TOPIC_RUNS.pop("torch-hint", None)


@pytest.mark.parametrize("command", ["torch", "adapt", "verify", "search", "doc"])
def test_any_command_followup_joins_original_graph(monkeypatch, command):
    """接续判定对全部直接命令一致生效,不是只给 /torch。"""
    from app.model_agent.dashboard import server as dash_server
    from app.services import chat_dashboard

    fake = _FakeServer()
    monkeypatch.setattr(
        dash_server.DashboardServer,
        "get_instance",
        classmethod(lambda cls, config=None: fake),
    )
    chat_dashboard._TOPIC_RUNS.pop("cmd-any", None)
    try:
        first = report_command(command, "排查一下版本问题", c_id="cmd-any")
        first.on_output("两个方向:\n1 查日志\n2 跑复现")
        first.finish()
        original_wf_id = first._wf_id

        reporter = report_command(command, "1", c_id="cmd-any")

        assert isinstance(reporter, _CommandContinuationDashboardReporter)
        assert reporter._reporter._wf_id == original_wf_id
    finally:
        chat_dashboard._TOPIC_RUNS.pop("cmd-any", None)


def test_command_switch_opens_its_own_graph(monkeypatch):
    """换命令是另一类任务,即使话题判定为接续也另开图,不挂进旧图。"""
    from app.model_agent.dashboard import server as dash_server
    from app.services import chat_dashboard

    fake = _FakeServer()
    monkeypatch.setattr(
        dash_server.DashboardServer,
        "get_instance",
        classmethod(lambda cls, config=None: fake),
    )
    chat_dashboard._TOPIC_RUNS.pop("cmd-switch", None)
    try:
        first = report_command("torch", "950PR HCCL error 19 排查", c_id="cmd-switch")
        first.on_output("结论见上。")
        first.finish()

        chat_dashboard.set_topic_hint(
            "cmd-switch", chat_dashboard.TopicDecision("same_task", 0.9, "llm"),
        )
        reporter = report_command("verify", "帮我验证一下这个结论", c_id="cmd-switch")

        assert isinstance(reporter, CommandDashboardReporter)
        assert reporter._wf_id != first._wf_id
        # /verify 的图里不能出现 torch 的节点
        assert all(not node.id.startswith("torch") for node in reporter._nodes)
    finally:
        chat_dashboard.clear_topic_hint()
        chat_dashboard._TOPIC_RUNS.pop("cmd-switch", None)


@pytest.mark.parametrize("reply,choice,expect_label", [
    ("两件事:\n1 转 Word\n2 填实测数据\n需要哪个?", "1", "1 转 Word"),
    ("下一步:\n1 升级 CANN\n2 改脚本", "2", "2 改脚本"),
])
def test_torch_menu_choice_joins_original_graph(monkeypatch, reply, choice, expect_label):
    """编号选择指代上轮菜单,并入原图并带出所选项。"""
    from app.model_agent.dashboard import server as dash_server
    from app.services import chat_dashboard

    fake = _FakeServer()
    monkeypatch.setattr(
        dash_server.DashboardServer,
        "get_instance",
        classmethod(lambda cls, config=None: fake),
    )
    chat_dashboard._TOPIC_RUNS.pop("torch-menu", None)
    try:
        first = report_command("torch", "950PR HCCL error 19 排查", c_id="torch-menu")
        first.on_output(reply)
        first.finish()
        original_wf_id = first._wf_id

        reporter = report_command("torch", choice, c_id="torch-menu")

        assert isinstance(reporter, _CommandContinuationDashboardReporter)
        assert reporter._reporter._wf_id == original_wf_id
        assert reporter._reporter._nodes[-1].label == expect_label
    finally:
        chat_dashboard._TOPIC_RUNS.pop("torch-menu", None)


@pytest.mark.parametrize("new_request", [
    "把 Qwen 量化一下", "换个话题", "你好", "950PR 上 vLLM 部署怎么配",
    "那顺便问下量化怎么做", "那再查下950PR的另一个报错", "另一个思路怎么搞",
])
def test_torch_unrelated_request_still_opens_new_graph(monkeypatch, new_request):
    """带自身主题、换题短语或显式换话题的请求必须新建图。"""
    from app.model_agent.dashboard import server as dash_server
    from app.services import chat_dashboard

    fake = _FakeServer()
    monkeypatch.setattr(
        dash_server.DashboardServer,
        "get_instance",
        classmethod(lambda cls, config=None: fake),
    )
    chat_dashboard._TOPIC_RUNS.pop("torch-unrelated", None)
    try:
        first = report_command("torch", "950PR HCCL error 19 排查", c_id="torch-unrelated")
        first.on_output("两件事:\n1 转 Word\n2 填数据\n需要哪个?")
        first.finish()
        before = len(fake.definitions)

        reporter = report_command("torch", new_request, c_id="torch-unrelated")

        assert isinstance(reporter, CommandDashboardReporter)
        # 新建图 = 又推了一次 set_workflow_def(wf_id 是毫秒时间戳,不能直接比)
        assert len(fake.definitions) == before + 1
    finally:
        chat_dashboard._TOPIC_RUNS.pop("torch-unrelated", None)


@pytest.mark.parametrize("ack", ["可以", "可以呀", "行", "开始吧", "好的", "好,开始",
                                 "行吧", "可以,行,开始吧"])
def test_acknowledgement_word_joins_original_graph(monkeypatch, ack):
    """确认词只改变执行方式,承接的还是原图。"""
    from app.model_agent.dashboard import server as dash_server
    from app.services import chat_dashboard

    fake = _FakeServer()
    monkeypatch.setattr(
        dash_server.DashboardServer,
        "get_instance",
        classmethod(lambda cls, config=None: fake),
    )
    chat_dashboard._TOPIC_RUNS.pop("torch-ack", None)
    try:
        first = report_command("torch", "950PR HCCL error 19 排查", c_id="torch-ack")
        first.on_output("两件事:\n1 转 Word\n2 填数据\n需要哪个?")
        first.finish()

        reporter = report_command("torch", ack, c_id="torch-ack")

        assert isinstance(reporter, _CommandContinuationDashboardReporter)
        # 标题保留用户原话,执行语义由前端按 kind 渲染。
        assert reporter._reporter._nodes[-1].label == ack
    finally:
        chat_dashboard._TOPIC_RUNS.pop("torch-ack", None)


def test_topic_hint_survives_command_routing(monkeypatch):
    """命令侧只读判定,清理由 api 层统一做,后续读取方还能拿到。"""
    from app.model_agent.dashboard import server as dash_server
    from app.services import chat_dashboard

    fake = _FakeServer()
    monkeypatch.setattr(
        dash_server.DashboardServer,
        "get_instance",
        classmethod(lambda cls, config=None: fake),
    )
    chat_dashboard._TOPIC_RUNS.pop("torch-hint-life", None)
    try:
        first = report_command("torch", "950PR HCCL error 19 排查", c_id="torch-hint-life")
        first.on_output("结论见上。")
        first.finish()
        decision = chat_dashboard.TopicDecision("same_task", 0.9, "llm")
        chat_dashboard.set_topic_hint("torch-hint-life", decision)

        report_command("torch", "嗯这个我懂了", c_id="torch-hint-life")

        assert chat_dashboard.get_topic_decision("torch-hint-life") is decision
    finally:
        chat_dashboard.clear_topic_hint()
        chat_dashboard._TOPIC_RUNS.pop("torch-hint-life", None)


def test_torch_new_request_still_opens_its_own_graph(monkeypatch):
    """带自身主题的新请求保持独立成图。"""
    from app.model_agent.dashboard import server as dash_server
    from app.services import chat_dashboard

    fake = _FakeServer()
    monkeypatch.setattr(
        dash_server.DashboardServer,
        "get_instance",
        classmethod(lambda cls, config=None: fake),
    )
    chat_dashboard._TOPIC_RUNS.pop("torch-new-request", None)
    try:
        report_command("torch", "950PR 单卡 HCCL 报错 19", c_id="torch-new-request")
        reporter = report_command("torch", "把 Qwen 量化一下", c_id="torch-new-request")
        assert isinstance(reporter, CommandDashboardReporter)
    finally:
        chat_dashboard._TOPIC_RUNS.pop("torch-new-request", None)


def test_report_command_root_output_matches_frontend_from_start(monkeypatch):
    from app.model_agent.dashboard import server as dash_server

    fake = _FakeServer()
    monkeypatch.setattr(
        dash_server.DashboardServer,
        "get_instance",
        classmethod(lambda cls, config=None: fake),
    )
    reporter = report_command("adapt", "适配 Qwen", c_id="start-output")
    assert isinstance(reporter, CommandDashboardReporter)

    reporter.on_output("开始分析")
    reporter.finish()

    completed = next(c for c in fake.calls if c[0] == "node.completed")
    assert completed[1]["output_full"] == "正在执行 /adapt...\n\n开始分析"


def test_direct_command_streams_output_before_finish(monkeypatch):
    from app.tools.claude_tools import CommandOutput

    r, fake = _reporter(monkeypatch)
    r.on_output(CommandOutput(content="第一段", user_facing=True))
    r.on_output(CommandOutput(content="第二段", user_facing=True))
    r.on_output(CommandOutput(content="", activity=True))

    live = [data for event, data in fake.calls if event == "node.output"]
    assert live
    assert live[-1]["output_full"] == "第一段第二段"
    assert not any(event == "node.completed" for event, _ in fake.calls)


def test_authoritative_command_result_replaces_intermediate_text(monkeypatch):
    from app.tools.claude_tools import CommandOutput

    r, fake = _reporter(monkeypatch)
    r.on_output(CommandOutput(content="过程说明", user_facing=True))
    r.on_output(CommandOutput(
        content="最终答案",
        user_facing=True,
        output_reset=True,
    ))
    r.finish()

    chunks = [
        data for event, data in fake.calls
        if event == "node.output.chunk"
    ]
    completed = next(data for event, data in fake.calls if event == "node.completed")
    assert chunks == [
        {"output_chunk": "过程说明", "output_reset": False},
        {"output_chunk": "最终答案", "output_reset": True},
    ]
    assert completed["output_full"] == "最终答案"


def test_direct_command_high_frequency_chunks_use_bounded_snapshots(monkeypatch):
    from app.services import command_dashboard
    from app.tools.claude_tools import CommandOutput

    now = 100.0
    monkeypatch.setattr(command_dashboard.time, "monotonic", lambda: now)
    r, fake = _reporter(monkeypatch)
    r._output_last_emitted_at = 0.0

    chunks = [str(i % 10) * 80 for i in range(1000)]
    for chunk in chunks:
        r.on_output(CommandOutput(content=chunk, user_facing=True))
    r.on_output(CommandOutput(content="", activity=True))

    live = [data for event, data in fake.calls if event == "node.output"]
    assert len(live) == 2
    assert live[-1]["output_full"] == "".join(chunks)


def test_command_node_and_started_event_preserve_real_input(monkeypatch):
    _, fake = _reporter(monkeypatch, command="search", digest="查询哪些多模态模型在昇腾上支持推理")
    node = fake._workflow_def.nodes[0]
    assert node.label == "查询哪些多模态模型在昇腾上支持推理"
    assert node.metadata["description"] == node.label
    assert fake.calls[1] == ("workflow.started", {"status": "running"})
    assert fake.calls[2] == (
        "node.started",
        {
            "status": "running", "input_snapshot": node.label,
            "graph_only": True, "source": "user_input",
        },
    )


def test_first_output_starts_run_with_command_name(monkeypatch):
    r, fake = _reporter(monkeypatch)
    r.on_output("开始适配")
    assert fake.calls[0] == ("def", "adapt Boltz2 迁移")
    assert fake.calls[1][0] == "workflow.started"
    assert fake.calls[2][0] == "node.started"
    # 无换行的 chunk 进缓冲,finish 冲刷后才落日志
    r.finish()
    assert ("node.log", {"log_line": "开始适配"}) in fake.calls


def test_multiline_output_emits_whole_lines(monkeypatch):
    """碎片 chunk 拼接后按整行落日志,不逐帧碎列。"""
    r, fake = _reporter(monkeypatch)
    r.on_output("torch 编译\n")
    r.on_output("不支持\n部分算子\n")
    r.finish()
    logs = [c[1]["log_line"] for c in fake.calls if c[0] == "node.log"]
    assert logs == ["torch 编译", "不支持", "部分算子"]


def test_node_completed_carries_measured_elapsed(monkeypatch):
    r, fake = _reporter(monkeypatch)
    r.on_output("done\n")
    r.finish()
    completed = [c for c in fake.calls if c[0] == "node.completed"][0]
    assert completed[1]["elapsed_ms"] >= 0


def test_tool_event_frames_map_to_tool_calls(monkeypatch):
    r, fake = _reporter(monkeypatch)
    from app.tools.claude_tools import CommandOutput
    r.on_output(CommandOutput(content="", tool_event={"phase": "started", "tool": "Bash", "args_summary": "ls", "args_full": "完整参数"}))
    r.on_output(CommandOutput(content="", tool_event={"phase": "completed", "tool": "", "result_summary": "ok", "result_full": "完整结果", "elapsed_ms": 87}))
    kinds = [c[0] for c in fake.calls if c[0] != "def"]
    assert kinds == [
        "workflow.started", "node.started", "tool.started", "tool.completed",
    ]
    tool_completed = next(c for c in fake.calls if c[0] == "tool.completed")
    assert tool_completed[1]["elapsed_ms"] == 87
    # completed 帧回填 started 的工具名(Timeline "Bash 完成 (87ms)" 不再显示 'tool')
    assert tool_completed[1]["tool"] == "Bash"
    tool_started = next(c for c in fake.calls if c[0] == "tool.started")
    assert tool_started[1]["arguments_full"] == "完整参数"
    assert tool_completed[1]["result_full"] == "完整结果"


def test_tool_event_bounds_dashboard_detail_only(monkeypatch):
    from app.model_agent.workflow.capability_events import EVENT_DETAIL_MAX_CHARS
    from app.tools.claude_tools import CommandOutput

    r, fake = _reporter(monkeypatch)
    huge = "x" * (EVENT_DETAIL_MAX_CHARS + 100)
    r.on_output(CommandOutput(content="原始正文", tool_event={
        "phase": "started", "tool": "Bash", "call_id": "large",
        "args_full": huge,
    }))
    r.on_output(CommandOutput(content=huge, tool_event={
        "phase": "completed", "tool": "Bash", "call_id": "large",
        "result_full": huge,
    }))

    started = next(data for event, data in fake.calls if event == "tool.started")
    completed = next(data for event, data in fake.calls if event == "tool.completed")
    assert len(started["arguments_full"]) == EVENT_DETAIL_MAX_CHARS
    assert len(completed["result_full"]) == EVENT_DETAIL_MAX_CHARS
    assert started["arguments_full"].endswith("…")
    assert completed["result_full"].endswith("…")
    assert r._output_chars == len("原始正文") + len(huge)


def test_tool_event_binds_summaries_without_losing_full_detail(monkeypatch):
    from app.tools.claude_tools import CommandOutput

    reporter, fake = _reporter(monkeypatch)
    huge = "输出" * 1000
    reporter.on_output(CommandOutput(content="", tool_event={
        "phase": "started", "tool": "Bash", "call_id": "large",
        "args_summary": huge,
    }))
    reporter.on_output(CommandOutput(content="", tool_event={
        "phase": "completed", "tool": "Bash", "call_id": "large",
        "result_summary": huge,
    }))
    started = next(data for event, data in fake.calls if event == "tool.started")
    completed = next(data for event, data in fake.calls if event == "tool.completed")
    assert len(started["arguments_summary"]) == 500
    assert started["arguments_full"] == huge
    assert len(completed["result_summary"]) == 500
    assert completed["result_full"] == huge


def _create_task(r, call_id, task_id, subject, *, blocked_by=None):
    from app.tools.claude_tools import CommandOutput
    arguments = {
        "subject": subject,
        "description": f"真实描述:{subject}",
        "activeForm": f"正在{subject}",
    }
    if blocked_by is not None:
        arguments["blockedBy"] = blocked_by
    r.on_output(CommandOutput(content="", tool_event={
        "phase": "started", "call_id": call_id, "tool": "TaskCreate",
        "arguments": arguments,
        "args_full": json.dumps(arguments, ensure_ascii=False),
    }))
    r.on_output(CommandOutput(content="", tool_event={
        "phase": "completed", "call_id": call_id, "tool": "TaskCreate",
        "result_data": {"task": {"id": task_id, "subject": subject}},
        "result_full": f'{{"task":{{"id":"{task_id}"}}}}',
    }))


def _update_task(r, call_id, task_id, status):
    from app.tools.claude_tools import CommandOutput
    arguments = {"taskId": task_id, "status": status}
    r.on_output(CommandOutput(content="", tool_event={
        "phase": "started", "call_id": call_id, "tool": "TaskUpdate",
        "arguments": arguments,
    }))
    r.on_output(CommandOutput(content="", tool_event={
        "phase": "completed", "call_id": call_id, "tool": "TaskUpdate",
        "result_data": {"taskId": task_id, "statusChange": {"to": status}},
        "result_full": f'{{"taskId":"{task_id}","statusChange":{{"to":"{status}"}}}}',
    }))


def test_command_graph_contains_only_real_semantic_tasks(monkeypatch):
    r, fake = _reporter(monkeypatch, command="commit", digest="发布适配文档")
    from app.tools.claude_tools import CommandOutput

    r.on_output(CommandOutput(content="", tool_event={
        "phase": "started", "call_id": "read-1", "tool": "Read",
        "args_full": '{"file_path":"README.md"}',
    }))
    r.on_output(CommandOutput(content="", tool_event={
        "phase": "completed", "call_id": "read-1", "result_summary": "ok",
    }))
    _create_task(r, "create-1", "1", "检查适配状态")

    graph = fake._workflow_def
    assert [node.label for node in graph.nodes] == ["发布适配文档", "检查适配状态"]
    assert all(node.type != "tool_call" for node in graph.nodes)
    task = graph.nodes[1]
    assert task.metadata["kind"] == "semantic_step"
    assert task.metadata["description"] == "真实描述:检查适配状态"
    assert graph.edges == [type(graph.edges[0])(
        from_id="commit", to_id=task.id, condition="任务拆解",
    )]


def test_real_task_dependencies_and_parallel_statuses_drive_graph(monkeypatch):
    r, fake = _reporter(monkeypatch)
    _create_task(r, "create-2", "2", "执行精度验证", blocked_by=["1"])
    _create_task(r, "create-1", "1", "检查适配状态")
    _create_task(r, "create-3", "3", "生成发布清单")
    tasks = {
        node.metadata.get("agent_task_id"): node.id
        for node in fake._workflow_def.nodes if node.metadata.get("kind") == "semantic_step"
    }
    edges = {(edge.from_id, edge.to_id, edge.condition) for edge in fake._workflow_def.edges}
    assert (tasks["1"], tasks["2"], "显式依赖") in edges
    assert not any(to_id == tasks["2"] and condition == "任务拆解"
                   for _from_id, to_id, condition in edges)
    assert ("adapt", tasks["1"], "任务拆解") in edges
    assert ("adapt", tasks["3"], "任务拆解") in edges

    _update_task(r, "start-1", "1", "in_progress")
    _update_task(r, "start-3", "3", "in_progress")
    running = {
        event.node_id for event in fake.events
        if event.event_type.value == "node.started" and event.data.get("status") == "running"
    }
    assert tasks["1"] in running and tasks["3"] in running


def test_tools_attach_to_unique_running_step_without_becoming_nodes(monkeypatch):
    r, fake = _reporter(monkeypatch)
    from app.tools.claude_tools import CommandOutput
    _create_task(r, "create-1", "1", "验证 NPU 推理")
    _update_task(r, "start-1", "1", "in_progress")
    task_id = r._agent_task_nodes["1"]

    r.on_output(CommandOutput(content="", tool_event={
        "phase": "started", "call_id": "bash-1", "tool": "Bash",
        "args_full": '{"command":"npu-smi info"}',
    }))
    r.on_output(CommandOutput(content="", tool_event={
        "phase": "failed", "call_id": "bash-1", "tool": "Bash",
        "error": "首次检查失败",
    }))
    assert fake.events[-1].event_type.value == "tool.failed"
    assert fake.events[-1].node_id == task_id
    assert all(node.type != "tool_call" for node in fake._workflow_def.nodes)

    _update_task(r, "done-1", "1", "completed")
    terminal = [event for event in fake.events if event.node_id == task_id
                and event.event_type.value in {"node.completed", "node.failed"}]
    assert terminal[-1].event_type.value == "node.completed"
    assert terminal[-1].data["status"] == "success"


def test_dependency_only_task_update_is_not_a_tool_call(monkeypatch):
    """纯依赖记账不对应任何步骤执行:不挂步骤,也不产生工具调用面板。"""
    r, fake = _reporter(monkeypatch)
    from app.tools.claude_tools import CommandOutput
    _create_task(r, "create-1", "1", "检查适配状态")
    _create_task(r, "create-3", "3", "执行功能验证")
    pending_id = r._agent_task_nodes["3"]

    arguments = {"taskId": "3", "addBlockedBy": ["1"]}
    r.on_output(CommandOutput(content="", tool_event={
        "phase": "started", "call_id": "dep-1", "tool": "TaskUpdate",
        "arguments": arguments,
    }))
    r.on_output(CommandOutput(content="", tool_event={
        "phase": "completed", "call_id": "dep-1", "tool": "TaskUpdate",
        "result_data": {"success": True, "taskId": "3", "updatedFields": ["blockedBy"]},
    }))

    assert not [event for event in fake.events
                if event.event_type.value.startswith("tool.")
                and event.data.get("call_id") == "dep-1"]
    # 依赖边仍然成立,只是这条调用不进入步骤明细
    edges = {(edge.from_id, edge.to_id, edge.condition) for edge in fake._workflow_def.edges}
    assert (r._agent_task_nodes["1"], pending_id, "显式依赖") in edges


def test_dependency_only_task_update_running_step_unaffected(monkeypatch):
    """有步骤在跑时,记账调用也不得冒充成该步骤的工具调用。"""
    r, fake = _reporter(monkeypatch)
    from app.tools.claude_tools import CommandOutput
    _create_task(r, "create-1", "1", "检查适配状态")
    _create_task(r, "create-3", "3", "执行功能验证")
    _update_task(r, "start-1", "1", "in_progress")

    r.on_output(CommandOutput(content="", tool_event={
        "phase": "started", "call_id": "dep-1", "tool": "TaskUpdate",
        "arguments": {"taskId": "3", "addBlockedBy": ["1"]},
    }))

    assert not [event for event in fake.events
                if event.event_type.value == "tool.started"
                and event.data.get("call_id") == "dep-1"]


def test_execution_task_update_still_attaches_to_its_step(monkeypatch):
    r, fake = _reporter(monkeypatch)
    from app.tools.claude_tools import CommandOutput
    _create_task(r, "create-1", "1", "检查适配状态")
    task_id = r._agent_task_nodes["1"]

    r.on_output(CommandOutput(content="", tool_event={
        "phase": "started", "call_id": "start-1", "tool": "TaskUpdate",
        "arguments": {"taskId": "1", "status": "in_progress"},
    }))

    tool_events = [event for event in fake.events if event.event_type.value == "tool.started"]
    assert tool_events[-1].node_id == task_id


def test_plain_logs_attach_to_the_only_running_semantic_step(monkeypatch):
    r, fake = _reporter(monkeypatch)
    _create_task(r, "create-1", "1", "检查模型下载")
    _update_task(r, "start-1", "1", "in_progress")

    r.on_output("已确认模型文件可用\n")
    r.finish()

    log = next(event for event in fake.events
               if event.event_type.value == "node.log"
               and event.data.get("log_line") == "已确认模型文件可用")
    assert log.node_id == r._agent_task_nodes["1"]


def test_resetting_task_to_pending_does_not_add_visible_start(monkeypatch):
    r, fake = _reporter(monkeypatch)
    _create_task(r, "create-1", "1", "检查模型下载")
    _update_task(r, "start-1", "1", "in_progress")
    _update_task(r, "reset-1", "1", "pending")

    reset = fake.events[-1]
    assert reset.event_type.value == "node.started"
    assert reset.data["status"] == "pending"
    assert reset.data["graph_only"] is True


def test_finish_closes_unfinished_semantic_steps_truthfully(monkeypatch):
    r, fake = _reporter(monkeypatch)
    _create_task(r, "create-1", "1", "运行验证")
    _create_task(r, "create-2", "2", "整理报告")
    _update_task(r, "start-1", "1", "in_progress")
    running_id = r._agent_task_nodes["1"]
    pending_id = r._agent_task_nodes["2"]

    r.finish()
    running_terminal = next(event for event in fake.events
                            if event.node_id == running_id and event.event_type.value == "node.completed")
    pending_terminal = next(event for event in fake.events
                            if event.node_id == pending_id and event.event_type.value == "node.completed")
    assert running_terminal.data["status"] == "success"
    assert "output_summary" not in running_terminal.data
    assert pending_terminal.data["status"] == "skipped"
    assert not any(event.event_type.value == "node.failed" for event in fake.events)


def test_finish_with_error_marks_running_step_failed(monkeypatch):
    """真出错时,正在跑的步骤仍按失败关闭,不被记账缺口口径吞掉。"""
    r, fake = _reporter(monkeypatch)
    _create_task(r, "create-1", "1", "运行验证")
    _update_task(r, "start-1", "1", "in_progress")
    running_id = r._agent_task_nodes["1"]

    r.finish("RuntimeError: boom")
    failed = next(event for event in fake.events
                  if event.node_id == running_id and event.event_type.value == "node.failed")
    assert failed.data["status"] == "failed"
    assert failed.data["error"] == "RuntimeError: boom"


def test_failed_tool_prefers_explicit_full_error(monkeypatch):
    r, fake = _reporter(monkeypatch)
    from app.tools.claude_tools import CommandOutput
    r.on_output(CommandOutput(content="", tool_event={"phase": "started", "call_id": "c1", "tool": "Bash"}))
    r.on_output(CommandOutput(content="", tool_event={
        "phase": "failed", "call_id": "c1", "tool": "Bash",
        "error": "失败摘要", "error_full": "完整错误", "result_full": "原始结果",
    }))
    failed = next(data for kind, data in fake.calls if kind == "tool.failed")
    assert failed["error"] == "失败摘要"
    assert failed["error_full"] == "完整错误"
    assert failed["result_full"] == "原始结果"


def test_parallel_command_tools_match_results_by_call_id(monkeypatch):
    r, fake = _reporter(monkeypatch)
    from app.tools.claude_tools import CommandOutput

    for call_id, name in (("one", "Bash"), ("two", "Read")):
        r.on_output(CommandOutput(content="", tool_event={
            "phase": "started", "call_id": call_id, "tool": name,
        }))
    r.on_output(CommandOutput(content="", tool_event={
        "phase": "completed", "call_id": "unknown", "result_summary": "wrong",
    }))
    r.on_output(CommandOutput(content="", tool_event={
        "phase": "completed", "call_id": "two", "result_summary": "read ok",
    }))
    r.on_output(CommandOutput(content="", tool_event={
        "phase": "failed", "call_id": "one", "result_summary": "bash failed",
    }))
    terminal = [c for c in fake.calls if c[0] in ("tool.completed", "tool.failed")]
    assert [(kind, data["call_id"], data["tool"]) for kind, data in terminal] == [
        ("tool.completed", "two", "Read"), ("tool.failed", "one", "Bash"),
    ]
    assert terminal[-1][1]["error"] == "bash failed"
    assert any(c[0] == "node.log" and "unknown" in c[1]["log_line"] for c in fake.calls)


def test_command_run_closes_unreturned_tool_without_borrowing_other_result(monkeypatch):
    r, fake = _reporter(monkeypatch)
    from app.tools.claude_tools import CommandOutput

    r.on_output(CommandOutput(content="", tool_event={
        "phase": "started", "call_id": "one", "tool": "Bash",
    }))
    r.on_output(CommandOutput(content="", tool_event={
        "phase": "completed", "call_id": "unknown", "result_summary": "wrong",
    }))
    r.finish()
    terminal = [c for c in fake.calls if c[0] in ("tool.completed", "tool.failed")]
    assert len(terminal) == 1
    assert terminal[0][0] == "tool.failed"
    assert terminal[0][1]["call_id"] == "one"
    assert terminal[0][1]["error"] == "工具结果未返回"


def test_decor_chunks_dropped_from_logs(monkeypatch):
    """decor=True 的聊天装饰(横幅/围栏/等待提示)不入看板日志,正文照常。"""
    r, fake = _reporter(monkeypatch)
    from app.tools.claude_tools import CommandOutput
    r.on_output(CommandOutput(content="\n\n⏳ **命令执行中,请稍候...**", decor=True))
    r.on_output(CommandOutput(content="\n\n```bash\nls\n```", decor=True))
    r.on_output(CommandOutput(content="真实输出\n"))
    r.finish()
    logs = [c[1]["log_line"] for c in fake.calls if c[0] == "node.log"]
    assert logs == ["真实输出"]


def test_internal_reasoning_is_collected_in_root_output_but_not_dashboard_log(monkeypatch):
    r, fake = _reporter(monkeypatch)
    from app.tools.claude_tools import CommandOutput

    r.on_output(CommandOutput(
        content="Let me inspect the repository first.", decor=True, internal=True,
    ))
    r.on_output(CommandOutput(content="已完成发布", decor=True))
    r.finish()
    assert not any(c[0] == "node.log" for c in fake.calls)
    completed = next(c for c in fake.calls if c[0] == "node.completed")
    assert completed[1]["output_full"] == "Let me inspect the repository first.已完成发布"


def test_decor_answer_enters_output_summary_not_logs(monkeypatch):
    """答案正文 decor=True:不刷日志,但 finish 的 output_summary 尾窗保留。"""
    r, fake = _reporter(monkeypatch)
    from app.tools.claude_tools import CommandOutput
    r.on_output(CommandOutput(content="```yaml\nquant: w4a4\n```", decor=True))
    r.on_output(CommandOutput(content="[skill-progress] 🔧 Bash 开始"))
    r.finish()
    logs = [c[1]["log_line"] for c in fake.calls if c[0] == "node.log"]
    assert logs == ["[skill-progress] 🔧 Bash 开始"]
    completed = next(c for c in fake.calls if c[0] == "node.completed")
    assert "quant: w4a4" in completed[1]["output_summary"]
    assert completed[1]["output_full"] == "```yaml\nquant: w4a4\n```[skill-progress] 🔧 Bash 开始"


@pytest.mark.parametrize("command", ["adapt", "torch"])
def test_finish_summary_does_not_insert_newlines_between_stream_chunks(monkeypatch, command):
    reporter, fake = _reporter(monkeypatch, command=command)
    chunks = ["不支持的关键", "词通常\n", "graph", " break"]
    for chunk in chunks:
        reporter.on_output(chunk)
    reporter.finish()

    expected = "".join(chunks)
    node_ids = {command, f"{command}-analysis"} if command == "torch" else {command}
    completed = [
        event for event in fake.events
        if event.event_type.value == "node.completed" and event.node_id in node_ids
    ]
    assert len(completed) == len(node_ids)
    assert all(event.data["output_summary"] == expected for event in completed)
    assert all(event.data["output_full"] == expected for event in completed)


def test_finish_completes_and_archives(monkeypatch):
    r, fake = _reporter(monkeypatch)
    r.on_output("x")
    r.finish()
    assert [c[0] for c in fake.calls][-3:] == [
        "node.completed", "workflow.completed", "archive",
    ]
    assert fake.calls[-2][1]["status"] == "success"


def test_finish_with_error_marks_failed(monkeypatch):
    r, fake = _reporter(monkeypatch)
    r.on_output("x")
    r.finish(" boom")
    assert [c[0] for c in fake.calls][-3:] == [
        "node.failed", "workflow.failed", "archive",
    ]
    assert "boom" in fake.calls[-2][1]["error"]


def test_finish_without_output_marks_completed(monkeypatch):
    """创建即启动:无输出 finish 也置终态并即时归档。"""
    r, fake = _reporter(monkeypatch)
    r.finish()
    assert ("def", "adapt Boltz2 迁移") in fake.calls
    assert [c[0] for c in fake.calls][-3:] == [
        "node.completed", "workflow.completed", "archive",
    ]


def test_disabled_env_is_headless(monkeypatch):
    import os
    monkeypatch.setenv("WORKFLOW_DASHBOARD_ENABLED", "false")
    r, fake = _reporter(monkeypatch)
    r.on_output("x")
    r.finish()
    assert fake.calls == []


def test_finish_awaiting_user_stays_incomplete(monkeypatch):
    """agent 停下问用户——正文先送达,图切为等待且不推终态。"""
    r, fake = _reporter(monkeypatch)
    r.on_output("📋 需要补充以下信息:1. 目标环境?")
    r.finish(awaiting_user=True)
    kinds = [c[0] for c in fake.calls if c[0] != "def"]
    assert "node.completed" not in kinds and "node.failed" not in kinds
    waiting = [event for event in fake.events if event.event_type.value == "node.started"
               and event.data.get("status") == "waiting"]
    assert len(waiting) == 1
    assert waiting[0].node_id == r._node_id
    assert waiting[0].data["awaiting_user"] is True
    assert waiting[0].data["elapsed_ms"] >= 0
    assert any(event.event_type.value == "node.output" for event in fake.events[:fake.events.index(waiting[0])])
    assert fake.calls[-1] == ("node.log", {"log_line": "⏸ 等待用户补充信息…"})


def test_finish_awaiting_resume_stays_incomplete(monkeypatch):
    r, fake = _reporter(monkeypatch, command="deploy", digest="部署 qwen 到 A2")
    r.finish(awaiting_resume=True)

    assert not any(call[0] in {"node.completed", "node.failed"} for call in fake.calls)
    assert not any(call[0] in {"workflow.completed", "workflow.failed"} for call in fake.calls)
    assert any(event.event_type.value == "node.started" and event.data.get("status") == "paused"
               and event.data.get("awaiting_user") is True for event in fake.events)
    assert fake.calls[-1] == (
        "node.log",
        {"log_line": "⏸ 当前执行阶段已暂停,等待继续处理…"},
    )


def test_late_output_after_wait_does_not_start_another_graph(monkeypatch):
    r, fake = _reporter(monkeypatch)
    r.finish(awaiting_user=True)
    original_id = r._wf_id
    original_def_count = len(fake.definitions)

    r.on_output("迟到的输出")
    r.finish()

    assert r._wf_id == original_id
    assert len(fake.definitions) == original_def_count
    assert not any(event.event_type.value in {"workflow.completed", "workflow.failed"}
                   for event in fake.events)


def test_finish_user_interrupt_marks_interrupted(monkeypatch):
    r, fake = _reporter(monkeypatch)
    r.finish("用户中断")
    kinds = [c[0] for c in fake.calls]
    assert kinds[-3:-1] == ["node.failed", "workflow.failed"]
    assert fake.calls[-2][1]["status"] == "interrupted"


def test_finish_disconnect_and_execution_failure_are_distinct(monkeypatch):
    """断连可恢复;普通执行失败必须标 failed,不能混成异常中断。"""
    r, fake = _reporter(monkeypatch)
    r.finish("连接中断")
    assert fake.calls[-2][1]["status"] == "aborted"
    assert fake.calls[-2][1]["failure_kind"] == "connection_interrupted"
    assert fake.calls[-2][1]["failure_label"] == "连接中断,可重试"
    assert fake.calls[-2][1]["recoverable"] is True
    r2, fake2 = _reporter(monkeypatch)
    r2.finish("RuntimeError: boom")
    assert fake2.calls[-2][1]["status"] == "failed"
    assert fake2.calls[-2][1]["failure_kind"] == "execution_failure"
    assert fake2.calls[-2][1]["failure_label"] == "执行中出错,请检查失败原因"
    assert fake2.calls[-2][1]["recoverable"] is False


def test_events_carry_locked_workflow_id(monkeypatch):
    """事件 id 锁创建时刻:别 run 抢占 set_workflow_def 后迟帧不串档。"""
    r, fake = _reporter(monkeypatch)
    r.on_output("x")
    origin = r._wf_id
    # 模拟别 run 抢占当前视图
    from app.model_agent.workflow.schemas import WorkflowDef

    fake._workflow_def = WorkflowDef(workflow_id="cmd-other-999", name="other", nodes=[], edges=[])
    r.finish()
    # _event 构造的 workflow_id 不再读 fake._workflow_def,全程=创建时 id
    assert r._event("node.log", {"log_line": "z"}).workflow_id == origin


def test_finish_archives_current_run(monkeypatch):
    """终帧即时归档:run 仍是当前视图时 finish 触发 _archive_current_run。"""
    r, fake = _reporter(monkeypatch)
    r.finish()
    assert ("archive", None) in fake.calls


def test_finish_no_archive_when_superseded(monkeypatch):
    """已被别 run 抢占(快照不再是本 run)→ 不归档,避免盖掉别人的当前视图。"""
    r, fake = _reporter(monkeypatch)
    from app.model_agent.workflow.schemas import WorkflowDef

    fake._workflow_def = WorkflowDef(workflow_id="cmd-other-999", name="other", nodes=[], edges=[])
    fake.calls.clear()
    r.finish()
    assert ("archive", None) not in fake.calls