from __future__ import annotations

import asyncio
import os
from unittest.mock import MagicMock

import pytest

from commands.registry import cmd_registry

from app.main import _stream_workflow_progress


@pytest.mark.asyncio
async def test_shutdown_drain_waits_for_finalization_and_scoring(monkeypatch):
    from app import main as app_main
    from app.services import realtime_scorer

    completed = []

    async def score():
        await asyncio.sleep(0)
        completed.append("score")

    async def finalize():
        await asyncio.sleep(0)
        realtime_scorer._scorer_tasks.add(asyncio.create_task(score()))
        completed.append("finalize")

    final_task = asyncio.create_task(finalize())
    monkeypatch.setattr(app_main.chat, "_finalize_tasks", {final_task})
    monkeypatch.setattr(app_main.chat, "_failed_report_tasks", set())
    monkeypatch.setattr(realtime_scorer, "_scorer_tasks", set())

    await app_main._drain_realtime_evaluation_tasks(timeout=1)

    assert completed == ["finalize", "score"]


@pytest.mark.asyncio
async def test_shutdown_drain_has_bounded_wait(monkeypatch):
    from app import main as app_main
    from app.services import realtime_scorer

    task = asyncio.create_task(asyncio.sleep(10))
    monkeypatch.setattr(app_main.chat, "_finalize_tasks", {task})
    monkeypatch.setattr(app_main.chat, "_failed_report_tasks", set())
    monkeypatch.setattr(realtime_scorer, "_scorer_tasks", set())
    try:
        await asyncio.wait_for(app_main._drain_realtime_evaluation_tasks(timeout=0.01), 1)
        assert not task.done()
    finally:
        task.cancel()
        await asyncio.gather(task, return_exceptions=True)


def test_lifespan_starts_when_enabled_scorer_is_unavailable(monkeypatch):
    from unittest.mock import AsyncMock, Mock, patch

    from app import main as app_main
    from app.services import realtime_scorer

    monkeypatch.setattr(app_main.settings, "realtime_eval_enabled", True)
    monkeypatch.setattr(app_main.settings, "workflow_dashboard_enabled", False)
    monkeypatch.setattr(app_main.settings, "mcp_auto_start", False)
    monkeypatch.setattr(app_main.settings, "hermes_enabled", False)
    monkeypatch.setattr(app_main.settings, "claude_history_enabled", False)
    monkeypatch.setattr(realtime_scorer, "get_realtime_scorer", Mock(return_value=None))
    monkeypatch.setattr(realtime_scorer, "_SCORER_INIT_RETRY_SECONDS", 0.01)

    create_task = asyncio.create_task

    def schedule_recovery(coro):
        if getattr(coro, "__qualname__", "") == "recover_realtime_scorer":
            return create_task(coro)
        coro.close()
        return Mock()

    monkeypatch.setattr(app_main.asyncio, "create_task", schedule_recovery)
    from lts_logger import lts_logger

    monkeypatch.setattr(lts_logger, "shutdown", AsyncMock())

    async def enter():
        async with app_main.lifespan(None):
            await asyncio.sleep(0.03)
            return True

    with patch("app.tools.workflow.mcp_integration.shutdown_mcp_manager", new_callable=AsyncMock):
        assert asyncio.run(enter()) is True
    assert realtime_scorer.get_realtime_scorer.call_count >= 1


def test_dashboard_start_failure_does_not_block_main_lifespan(monkeypatch):
    from unittest.mock import AsyncMock, patch

    from app import main as app_main
    from app.model_agent.dashboard import server as dashboard_module
    from lts_logger import lts_logger

    class FailingDashboard:
        async def start(self):
            raise RuntimeError("dashboard bind failed")

        async def stop(self):
            return None

    monkeypatch.setattr(
        dashboard_module.DashboardServer,
        "get_instance",
        classmethod(lambda cls, config=None: FailingDashboard()),
    )
    monkeypatch.setattr(
        dashboard_module.DashboardConfig,
        "from_env",
        staticmethod(lambda: MagicMock()),
    )
    monkeypatch.setattr(app_main.settings, "realtime_eval_enabled", False)
    monkeypatch.setattr(app_main.settings, "workflow_dashboard_enabled", True)
    monkeypatch.setattr(app_main.settings, "workflow_dashboard_host", "127.0.0.1")
    monkeypatch.setattr(app_main.settings, "workflow_dashboard_http_port", 9300)
    monkeypatch.setattr(app_main.settings, "workflow_dashboard_ws_port", 9301)
    monkeypatch.setattr(app_main.settings, "workflow_dashboard_ws_connect", "")
    monkeypatch.setattr(app_main.settings, "workflow_dashboard_token", "")
    monkeypatch.setattr(app_main.settings, "mcp_auto_start", False)
    monkeypatch.setattr(app_main.settings, "hermes_enabled", False)
    monkeypatch.setattr(app_main.settings, "claude_history_enabled", False)
    monkeypatch.setattr(lts_logger, "shutdown", AsyncMock())
    monkeypatch.setenv("CLAUDE_HISTORY_ENABLED", "false")

    create_task = asyncio.create_task
    created = 0

    def schedule_dashboard_only(coro):
        nonlocal created
        created += 1
        if created == 1:
            return create_task(coro)
        coro.close()
        return MagicMock()

    monkeypatch.setattr(app_main.asyncio, "create_task", schedule_dashboard_only)

    async def enter():
        async with app_main.lifespan(None):
            await asyncio.sleep(0.05)
            return True

    with patch("app.tools.workflow.mcp_integration.shutdown_mcp_manager", new_callable=AsyncMock):
        assert asyncio.run(enter()) is True


def test_disabled_scorer_startup_gate_does_not_initialize_core(monkeypatch):
    from unittest.mock import Mock

    from app.services import realtime_scorer

    monkeypatch.setattr(realtime_scorer.settings, "realtime_eval_enabled", False)
    get_scorer = Mock(side_effect=AssertionError("disabled scoring must not load core"))
    monkeypatch.setattr(realtime_scorer, "get_realtime_scorer", get_scorer)
    realtime_scorer.ensure_realtime_scorer_ready()
    get_scorer.assert_not_called()


def test_workflow_stream_disconnect_cancels_execution_task():
    cancelled = asyncio.Event()

    async def long_running_workflow():
        try:
            await asyncio.sleep(3600)
        finally:
            cancelled.set()

    async def run_scenario():
        progress_queue = asyncio.Queue()
        await progress_queue.put({
            "event": "step_start",
            "step": "验证",
            "id": "s1",
            "type": "claude_skill",
        })
        execution_task = asyncio.create_task(long_running_workflow())
        await asyncio.sleep(0)
        stream = _stream_workflow_progress(execution_task, progress_queue)
        first_chunk = await anext(stream)
        await stream.aclose()
        return first_chunk, execution_task

    first_chunk, execution_task = asyncio.run(run_scenario())

    assert "[RUNNING]" in first_chunk
    assert execution_task.cancelled()
    assert cancelled.is_set()


def test_workflow_stream_drains_progress_after_task_completes():
    async def completed_workflow():
        return None

    async def run_scenario():
        progress_queue = asyncio.Queue()
        await progress_queue.put({
            "event": "step_end",
            "step": "验证",
            "id": "s1",
            "status": "completed",
        })
        execution_task = asyncio.create_task(completed_workflow())
        await execution_task
        return [
            chunk
            async for chunk in _stream_workflow_progress(
                execution_task,
                progress_queue,
            )
        ]

    chunks = asyncio.run(run_scenario())

    assert len(chunks) == 1
    assert "[PASS]" in chunks[0]


def test_workflow_stream_passes_step_output_through_and_keeps_progress():
    """step_output 全量进正文;定时心跳与空活动帧不进正文。"""
    async def completed_workflow():
        return None

    async def run_scenario():
        progress_queue = asyncio.Queue()
        await progress_queue.put({
            "event": "step_output",
            "step": "验证",
            "chunk": "Traceback (most recent call last):\nKeyError: 'x'",
        })
        await progress_queue.put({
            "event": "step_output",
            "step": "验证",
            "chunk": "\n> Claude Code 正在执行中...(已等待 8s)\n",
            "kind": "progress",
        })
        await progress_queue.put({
            "event": "step_output",
            "step": "验证",
            "chunk": "",
            "kind": "activity",
        })
        execution_task = asyncio.create_task(completed_workflow())
        await execution_task
        return [
            chunk
            async for chunk in _stream_workflow_progress(
                execution_task,
                progress_queue,
            )
        ]

    chunks = asyncio.run(run_scenario())

    assert len(chunks) == 2
    assert "KeyError" in chunks[0]
    assert chunks[1] == ": wf-activity\n\n"
    assert all("正在执行中" not in chunk for chunk in chunks)


def test_workflow_stream_shows_sparse_status_during_long_silent_steps(monkeypatch):
    monkeypatch.setattr("app.main._WORKFLOW_VISIBLE_HEARTBEAT_INTERVAL", 0.01)

    async def run_scenario():
        queue = asyncio.Queue()

        async def execute():
            await queue.put({
                "event": "step_output", "step": "验证", "id": "step_1",
                "chunk": "> Claude Code 正在执行中...(已等待 8s)", "kind": "progress",
            })
            await asyncio.sleep(0.03)
            await queue.put({
                "event": "step_output", "step": "验证", "id": "step_1",
                "chunk": "> Claude Code 正在执行中...(已等待 64s)", "kind": "progress",
            })

        task = asyncio.create_task(execute())
        return [chunk async for chunk in _stream_workflow_progress(task, queue)]

    assert asyncio.run(run_scenario()) == ["> Claude Code 正在执行中...(已等待 64s)"]


def test_workflow_stream_forwards_hidden_activity_as_sse_comments():
    """工具事件和重规划只刷新看门狗,不进入用户正文。"""
    async def completed_workflow():
        return None

    async def run_scenario():
        progress_queue = asyncio.Queue()
        await progress_queue.put({
            "event": "tool_event", "step": "验证", "tool": "Bash",
        })
        await progress_queue.put({
            "event": "plan_updated", "reason": "失败后重规划",
        })
        execution_task = asyncio.create_task(completed_workflow())
        await execution_task
        return [
            chunk
            async for chunk in _stream_workflow_progress(
                execution_task,
                progress_queue,
            )
        ]

    assert asyncio.run(run_scenario()) == [
        ": wf-activity\n\n",
        ": wf-activity\n\n",
    ]


def _collect_chunks(handler_output) -> list[str]:
    async def _run():
        return [str(chunk) async for chunk in handler_output]

    return asyncio.run(_run())


def _get_workflow_handler():
    """workflow_handler 嵌套在 lifespan 里,无法直接导入;手动驱动 lifespan
    进入段完成命令注册,再从 cmd_registry 拿闭包引用。注册是幂等 dict 赋值,
    只跑一次。lifespan 进入段的副作用(MCP init、doc 环境检查、history
    watcher)都是 asyncio.create_task 启动的后台任务——替换 create_task
    为丢弃 stub,测试循环里不留下任何真实后台动作。"""
    from unittest.mock import patch

    from app import main as app_main

    if cmd_registry.get("workflow") is None:

        def _drop_tasks(coro, *args, **kwargs):
            coro.close()
            return MagicMock()

        async def _enter_lifespan():
            # conftest 的 lts_logger.shutdown 是 MagicMock,退出段 await 会 TypeError
            from unittest.mock import AsyncMock
            from lts_logger import lts_logger as _log
            _log.shutdown = AsyncMock()
            with patch.object(asyncio, "create_task", _drop_tasks), \
                    patch.dict(os.environ, {"CLAUDE_HISTORY_ENABLED": "false"}):
                async with app_main.lifespan(None):
                    pass

        asyncio.run(_enter_lifespan())
    cmd = cmd_registry.get("workflow")
    assert cmd is not None and cmd.handler is not None
    return cmd.handler


def _patch_workflow_plumbing(monkeypatch, step_result: str, step_type=None):
    """Plan 有一个指定类型的步骤;executor 返回带指定 step_result 的 ctx。

    planner/executor 全部 mock,只验证完成帧格式化逻辑。
    """
    from app.tools.workflow.types import (
        ExecutionContext,
        StepStatus,
        StepType,
        WorkflowPlan,
        WorkflowStep,
    )
    if step_type is None:
        step_type = StepType.CLAUDE_SKILL

    handler = _get_workflow_handler()

    plan = WorkflowPlan(
        intent="验证",
        goal="验证",
        steps=[
            WorkflowStep(
                id="step_1",
                type=step_type,
                name="快速验证适配",
                skill_name="verify-agent",
            ),
        ],
    )

    ctx = ExecutionContext(workflow_id=plan.workflow_id)
    ctx.set_step_result("step_1", step_result)
    plan.steps[0].status = StepStatus.COMPLETED

    class _FakePlanner:
        async def aplan(self, args):
            return plan

    class _FakeExecutor:
        interrupt_requested = False  # 中断特性新增属性:fake 无中断,终态走原口径

        async def execute(self, plan, progress_callback=None):
            return ctx

    # lazy-import 工厂 re-export:patch 必须打在 planner/executor 模块的真类上
    monkeypatch.setattr("app.tools.workflow.planner.DynamicPlanner", _FakePlanner)
    monkeypatch.setattr("app.tools.workflow.executor.WorkflowExecutor", _FakeExecutor)
    return handler


def test_workflow_completion_frame_warns_on_skeleton_placeholder(monkeypatch):
    """骨架占位步骤的 PASS 帧必须携带未实现警示。"""
    from app.tools.workflow.types import ExecutionContext, StepStatus, StepType, WorkflowPlan, WorkflowStep

    handler = _patch_workflow_plumbing(
        monkeypatch,
        "[verify-agent] 暂未接入(verify_check_npu_status)。该能力未内置为工具。",
    )
    chunks = _collect_chunks(handler("验证 qwen3.5-0.8B", c_id=None))

    joined = "\n".join(chunks)
    assert "[PASS] **快速验证适配**" in joined
    assert "暂未接入" in joined
    assert "不能视为验证/执行通过" in joined


def test_workflow_completion_frame_no_warning_on_real_result(monkeypatch):
    """真实结果的步骤不带警示帧——变异验证防永久警示。"""
    from app.tools.workflow.types import ExecutionContext, StepStatus, StepType, WorkflowPlan, WorkflowStep

    handler = _patch_workflow_plumbing(
        monkeypatch,
        "NPU Health OK, model loaded in 0.62s, HTTP 200",
    )
    chunks = _collect_chunks(handler("验证 qwen3.5-0.8B", c_id=None))

    joined = "\n".join(chunks)
    assert "[PASS] **快速验证适配**" in joined
    assert "不能视为验证/执行通过" not in joined


def test_workflow_completion_frame_warns_on_json_skeleton(monkeypatch):
    """adapt_tools 的 JSON 骨架形态(status: not_implemented)同样警示。"""
    import json as _json

    from app.tools.workflow.types import ExecutionContext, StepStatus, StepType, WorkflowPlan, WorkflowStep

    handler = _patch_workflow_plumbing(
        monkeypatch,
        _json.dumps({
            "status": "not_implemented",
            "message": "verify_run_benchmark 暂未接入",
            "tool": "verify_run_benchmark",
        }, ensure_ascii=False),
    )
    chunks = _collect_chunks(handler("验证 qwen3.5-0.8B", c_id=None))

    joined = "\n".join(chunks)
    assert "不能视为验证/执行通过" in joined


def test_workflow_completion_frame_warns_on_mixed_parallel_list(monkeypatch):
    """PARALLEL 混合结果(真实子结果 + JSON 骨架)仍须警示——骨架藏在
    list repr 后半段时,首 80 字符窗口与整串 json.loads 都会漏判。"""
    import json as _json

    from app.tools.workflow.types import ExecutionContext, StepStatus, StepType, WorkflowPlan, WorkflowStep

    mixed = [
        "NPU Health OK, model loaded in 0.62s, HTTP 200, all checks passed for qwen3.5-0.8B deployment",
        {"status": "not_implemented", "message": "adapt_review_repo 暂未接入",
         "tool": "adapt_review_repo"},
    ]
    handler = _patch_workflow_plumbing(monkeypatch, mixed)
    chunks = _collect_chunks(handler("验证 qwen3.5-0.8B", c_id=None))

    joined = "\n".join(chunks)
    assert "不能视为验证/执行通过" in joined
    assert "不能视为验证/执行通过" in joined


def test_workflow_completion_frame_no_warning_when_placeholder_only_quoted(monkeypatch):
    """子代理按骨架指引完成真实工作后叙述中引用过「暂未接入」的,
    不反扣警示——中途引用不算占位。"""
    from app.tools.workflow.types import ExecutionContext, StepStatus, StepType, WorkflowPlan, WorkflowStep

    handler = _patch_workflow_plumbing(
        monkeypatch,
        "先调 verify_run_benchmark 返回「暂未接入」,随后按指引改用 "
        "npu-smi info 实查:Health=OK,bench.sh 跑通 QPS=15.7。",
    )
    chunks = _collect_chunks(handler("验证 qwen3.5-0.8B", c_id=None))

    joined = "\n".join(chunks)
    assert "不能视为验证/执行通过" not in joined


def test_workflow_llm_tool_result_surfaced_in_reply(monkeypatch):
    """llm_tool 的交付文本直接进入回复,不替换为占位内容。"""
    from app.tools.workflow.types import StepType

    handler = _patch_workflow_plumbing(
        monkeypatch,
        "适配状态:qwen3.5-0.8B 已在昇腾模型库上架,支持 vLLM-Ascend 0.9.2",
        step_type=StepType.LLM_TOOL,
    )
    chunks = _collect_chunks(handler("查一下 qwen3.5-0.8B 适配", c_id=None))

    joined = "\n".join(chunks)
    assert "已在昇腾模型库上架" in joined
    assert "执行完成,交付物见子代理写入的产物文件" not in joined


def test_workflow_claude_skill_result_dumped_in_reply(monkeypatch):
    """claude_skill 的步骤结果原文进回复(7b24eb9 前形态)。"""
    handler = _patch_workflow_plumbing(
        monkeypatch,
        "思考: Let me check... [PASS] Bash 输出 npu-smi info ...",
    )
    chunks = _collect_chunks(handler("验证 qwen3.5-0.8B", c_id=None))

    joined = "\n".join(chunks)
    assert "npu-smi info" in joined
    assert "执行完成,交付物见子代理写入的产物文件" not in joined


def test_workflow_claude_skill_full_result_surfaced_in_report(monkeypatch):
    """claude_skill 完整结果原文透出,含锚点前过程文本。"""
    handler = _patch_workflow_plumbing(
        monkeypatch,
        "思考: 执行中 [PASS] Bash 输出 npu-smi info ...\n\n"
        "**最终结果**:\n## 验证完成\n\n**状态**:✅ 通过(功能样例验证)\n"
        "精度 top1=0.92,与基线一致。",
    )
    chunks = _collect_chunks(handler("验证 qwen3.5-0.8B", c_id=None))

    joined = "\n".join(chunks)
    assert "## 验证完成" in joined
    assert "精度 top1=0.92" in joined
    assert "npu-smi info" in joined
    assert "执行完成,交付物见子代理写入的产物文件" not in joined


def test_workflow_claude_skill_result_truncated_in_report(monkeypatch):
    """结果原文超长限幅——与 llm_tool 步骤同口径。"""
    handler = _patch_workflow_plumbing(
        monkeypatch,
        "**最终结果**:\n" + "长交付文本" * 800,
    )
    chunks = _collect_chunks(handler("验证 qwen3.5-0.8B", c_id=None))

    joined = "\n".join(chunks)
    assert "(输出已截断)" in joined
    assert "执行完成,交付物见子代理写入的产物文件" not in joined


def test_workflow_interrupted_stops_silently(monkeypatch):
    """协作中断未跑完:流即断即停,不发报告与终帧;恢复静默承载。"""
    from app.tools.workflow.types import (
        ExecutionContext,
        StepStatus,
        StepType,
        WorkflowPlan,
        WorkflowStep,
    )

    handler = _get_workflow_handler()

    plan = WorkflowPlan(
        intent="验证",
        goal="验证",
        steps=[
            WorkflowStep(
                id="step_1",
                type=StepType.CLAUDE_SKILL,
                name="快速验证适配",
                skill_name="verify-agent",
            ),
            WorkflowStep(
                id="step_2",
                type=StepType.CLAUDE_SKILL,
                name="输出报告",
            ),
        ],
    )
    plan.steps[0].status = StepStatus.COMPLETED
    ctx = ExecutionContext(workflow_id=plan.workflow_id)

    class _FakePlanner:
        async def aplan(self, args):
            return plan

    class _FakeInterruptedExecutor:
        interrupt_requested = True

        async def execute(self, plan, progress_callback=None):
            return ctx

    monkeypatch.setattr("app.tools.workflow.planner.DynamicPlanner", _FakePlanner)
    monkeypatch.setattr(
        "app.tools.workflow.executor.WorkflowExecutor", _FakeInterruptedExecutor
    )

    chunks = _collect_chunks(handler("验证", c_id=None))
    joined = "\n".join(chunks)
    assert "工作流已被中断" not in joined
    assert "发送「继续」" not in joined
    assert "工作流执行完毕" not in joined
    assert "端到端工作流执行报告" not in joined


def test_workflow_end_frame_full_complete_keeps_legacy_text(monkeypatch):
    """协作中断但所有步骤恰好完成:仍报「执行完毕」,不误导用户还有断点。"""
    from app.tools.workflow.types import (
        ExecutionContext,
        StepStatus,
        StepType,
        WorkflowPlan,
        WorkflowStep,
    )

    handler = _get_workflow_handler()

    plan = WorkflowPlan(
        intent="验证",
        goal="验证",
        steps=[
            WorkflowStep(
                id="step_1",
                type=StepType.CLAUDE_SKILL,
                name="快速验证适配",
                skill_name="verify-agent",
            ),
        ],
    )
    plan.steps[0].status = StepStatus.COMPLETED
    ctx = ExecutionContext(workflow_id=plan.workflow_id)

    class _FakePlanner:
        async def aplan(self, args):
            return plan

    class _FakeInterruptedExecutor:
        interrupt_requested = True

        async def execute(self, plan, progress_callback=None):
            return ctx

    monkeypatch.setattr("app.tools.workflow.planner.DynamicPlanner", _FakePlanner)
    monkeypatch.setattr(
        "app.tools.workflow.executor.WorkflowExecutor", _FakeInterruptedExecutor
    )

    chunks = _collect_chunks(handler("验证", c_id=None))
    joined = "\n".join(chunks)
    assert "工作流执行完毕" in joined
    assert "工作流已被中断" not in joined


def test_workflow_mcp_tool_result_surfaced_in_reply(monkeypatch):
    """mcp_tool 步骤同 llm_tool:交付文本透出 + MCP 调用行保留。"""
    from app.tools.workflow.types import StepType

    handler = _patch_workflow_plumbing(
        monkeypatch,
        "检索完成:命中 3 个昇腾适配文档",
        step_type=StepType.MCP_TOOL,
    )
    chunks = _collect_chunks(handler("检索适配文档", c_id=None))

    joined = "\n".join(chunks)
    assert "命中 3 个昇腾适配文档" in joined
    assert "**MCP 调用**" in joined
    assert "执行完成,交付物见子代理写入的产物文件" not in joined


async def _enter_lifespan_once(*, force: bool = False):
    """在当前事件循环内驱动 lifespan 进入段完成命令注册(幂等)。"""
    from unittest.mock import AsyncMock, patch

    from app import main as app_main
    from app.model_agent.dashboard import server as dashboard_module

    if not force and cmd_registry.get("torch") is not None:
        return

    def _drop_tasks(coro, *args, **kwargs):
        coro.close()
        return MagicMock()

    from lts_logger import lts_logger as _log
    _log.shutdown = AsyncMock()

    class _RegistrationDashboard:
        async def start(self):
            return None

        async def stop(self):
            return None

    with patch.object(asyncio, "create_task", _drop_tasks), \
            patch.object(
                dashboard_module.DashboardServer,
                "get_instance",
                classmethod(lambda cls, config=None: _RegistrationDashboard()),
            ), \
            patch.dict(os.environ, {"CLAUDE_HISTORY_ENABLED": "false"}):
        async with app_main.lifespan(None):
            pass


def _get_torch_handler():
    """注册 /torch 后从 cmd_registry 取 handler 闭包。"""
    assert cmd_registry.get("torch") is not None
    cmd = cmd_registry.get("torch")
    assert cmd is not None and cmd.handler is not None
    return cmd.handler


async def test_torch_command_registers_session_and_releases_on_completion(tmp_path):
    """/torch 完成后会话置为 idle 并保留任务摘要。"""
    from unittest.mock import patch

    from app.services.direct_command_sessions import direct_command_sessions
    from app.tools import pta_tools

    await _enter_lifespan_once()
    handler = _get_torch_handler()
    direct_command_sessions.clear_all()

    def fake_pta(prompt, *, memory, session_id, on_text, on_step=None):
        on_text("pta-answer")

    with (
        patch.object(pta_tools, "_PTA_HELPER_ROOT", tmp_path),
        patch.object(pta_tools, "_load_pta_helper", return_value=fake_pta),
    ):
        chunks = [str(c) async for c in handler("torchair 编译流程", c_id="torch-cid-1")]

    assert any("pta-answer" in c for c in chunks)
    # 会话已置 idle(release)但条目保留:桥接可取、in_flight 为假
    assert direct_command_sessions.is_in_flight("torch-cid-1") is False
    context = direct_command_sessions.get_recent_task_context("torch-cid-1")
    assert context is not None
    assert context[0] == "torch"
    assert "torchair" in context[1]

    # 显式「继续」可 claim(supports_continuation=True 的前置)
    claimed = direct_command_sessions.claim_for_continuation(
        "torch-cid-1", "继续", "torch",
    )
    assert claimed is not None
    direct_command_sessions.release("torch-cid-1", "torch", claimed.generation)
    direct_command_sessions.clear_all()


async def test_torch_command_without_c_id_keeps_existing_behavior(tmp_path):
    from unittest.mock import patch

    from app.tools import pta_tools

    await _enter_lifespan_once()
    handler = _get_torch_handler()

    def fake_pta(prompt, *, memory, session_id, on_text, on_step=None):
        assert session_id is None
        on_text("pta-answer")

    with (
        patch.object(pta_tools, "_PTA_HELPER_ROOT", tmp_path),
        patch.object(pta_tools, "_load_pta_helper", return_value=fake_pta),
    ):
        chunks = [str(c) async for c in handler("torchair 编译流程", c_id=None)]

    assert any("pta-answer" in c for c in chunks)


async def test_torch_command_rejects_concurrent_start():
    """执行中重复 /torch 必须被忙碌守卫拒绝且不覆盖原摘要。"""
    from unittest.mock import patch

    from app.services.direct_command_sessions import direct_command_sessions
    from app.tools import pta_tools

    await _enter_lifespan_once()
    handler = _get_torch_handler()
    direct_command_sessions.clear_all()

    gate = asyncio.Event()

    def fake_pta(prompt, *, memory, session_id, on_text, on_step=None):
        gate.wait(timeout=5)

    with patch.object(pta_tools, "_load_pta_helper", return_value=fake_pta):
        first = handler("长任务", c_id="torch-cid-2")
        chunk_iter = first.__aiter__()
        # 启动第一个调用(阻塞在 fake_pta)
        task = asyncio.ensure_future(chunk_iter.__anext__())
        await asyncio.sleep(0.05)
        assert direct_command_sessions.is_in_flight("torch-cid-2")
        # 第二个并发调用被拒
        chunks2 = [str(c) async for c in handler("并发任务", c_id="torch-cid-2")]
        assert any("仍在执行" in c for c in chunks2)
        gate.set()
        await task
    direct_command_sessions.clear_all()


def test_lifespan_starts_dashboard_when_enabled(monkeypatch):
    """看板与主服务同生命周期启动、停止。"""
    from unittest.mock import patch

    from app import main as app_main
    from app.model_agent.dashboard import server as dash_server

    lifecycle = []

    class _FakeServer:
        async def start(self):
            lifecycle.append("start")

        async def stop(self):
            lifecycle.append("stop")

    monkeypatch.setattr(dash_server.DashboardServer, "get_instance", classmethod(
        lambda cls, config=None: _FakeServer()))
    monkeypatch.setattr(dash_server.DashboardConfig, "from_env", staticmethod(
        lambda: MagicMock()))

    # 已有注册缓存时 lifespan 不会重跑;直接以 create_task 不丢弃的方式驱动一次
    from lts_logger import lts_logger
    from unittest.mock import AsyncMock
    lts_logger.shutdown = AsyncMock()

    async def _enter():
        with patch.dict(os.environ, {"WORKFLOW_DASHBOARD_ENABLED": "true",
                                     "CLAUDE_HISTORY_ENABLED": "false"}), \
                patch("app.main.settings") as fake_settings:
            fake_settings.workflow_dashboard_enabled = True
            fake_settings.workflow_dashboard_host = "127.0.0.1"
            fake_settings.workflow_dashboard_http_port = 9300
            fake_settings.workflow_dashboard_ws_port = 9301
            fake_settings.workflow_dashboard_ws_connect = ""
            fake_settings.workflow_dashboard_max_snapshot = 500
            fake_settings.workflow_dashboard_history_dir = ""
            fake_settings.workflow_dashboard_token = None
            fake_settings.claude_history_enabled = False
            fake_settings.hermes_enabled = False
            async with app_main.lifespan(None):
                await asyncio.sleep(0.05)  # 让后台 _start_dashboard 跑完

    asyncio.run(_enter())
    assert lifecycle == ["start", "stop"]


def test_lifespan_no_dashboard_when_disabled(monkeypatch):
    """禁用环境零动作——不实例化不启动。"""
    from unittest.mock import patch

    from app import main as app_main
    from app.model_agent.dashboard import server as dash_server

    calls = []
    monkeypatch.setattr(dash_server.DashboardServer, "get_instance", classmethod(
        lambda cls, config=None: calls.append(1) or MagicMock()))

    from lts_logger import lts_logger
    from unittest.mock import AsyncMock
    lts_logger.shutdown = AsyncMock()

    async def _enter():
        with patch.dict(os.environ, {"CLAUDE_HISTORY_ENABLED": "false"}), \
                patch("app.main.settings") as fake_settings:
            fake_settings.workflow_dashboard_enabled = False
            fake_settings.workflow_dashboard_host = "127.0.0.1"
            fake_settings.workflow_dashboard_http_port = 9300
            fake_settings.workflow_dashboard_ws_port = 9301
            fake_settings.workflow_dashboard_ws_connect = ""
            fake_settings.workflow_dashboard_max_snapshot = 500
            fake_settings.workflow_dashboard_history_dir = ""
            fake_settings.workflow_dashboard_token = ""
            fake_settings.claude_history_enabled = False
            fake_settings.hermes_enabled = False
            async with app_main.lifespan(None):
                pass

    asyncio.run(_enter())
    assert calls == []


def test_lifespan_overrides_stale_dashboard_env(monkeypatch):
    """settings 覆盖镜像中遗留的看板环境变量。"""
    from unittest.mock import patch, AsyncMock

    from app import main as app_main
    from app.model_agent.dashboard import server as dash_server

    monkeypatch.setattr(dash_server.DashboardServer, "get_instance", classmethod(
        lambda cls, config=None: MagicMock()))
    monkeypatch.setattr(dash_server.DashboardConfig, "from_env", staticmethod(
        lambda: MagicMock()))

    from lts_logger import lts_logger
    lts_logger.shutdown = AsyncMock()

    async def _enter():
        with patch.dict(os.environ, {"WORKFLOW_DASHBOARD_ENABLED": "false",
                                     "CLAUDE_HISTORY_ENABLED": "false"}), \
                patch("app.main.settings") as fake_settings:
            fake_settings.workflow_dashboard_enabled = True
            fake_settings.workflow_dashboard_host = "127.0.0.1"
            fake_settings.workflow_dashboard_http_port = 9300
            fake_settings.workflow_dashboard_ws_port = 9301
            fake_settings.workflow_dashboard_ws_connect = ""
            fake_settings.workflow_dashboard_max_snapshot = 500
            fake_settings.workflow_dashboard_history_dir = ""
            fake_settings.workflow_dashboard_token = ""
            fake_settings.claude_history_enabled = False
            fake_settings.hermes_enabled = False
            async with app_main.lifespan(None):
                pass
            # bridge 的判定路径此时必须看到 true
            assert os.environ["WORKFLOW_DASHBOARD_ENABLED"] == "true"

    asyncio.run(_enter())


@pytest.mark.asyncio
@pytest.mark.parametrize("cleanup_error", [None, "source", "reporter"])
async def test_resumable_command_disconnect_marks_interrupted(monkeypatch, cleanup_error):

    """断连 GeneratorExit:relay 显式关内层 gen,finish 即时收到 err="连接中断"(异常中断,非用户中断)。"""
    from app.services import direct_command_sessions as dcs

    captured: dict = {}

    class _FakeReporter:
        def finish(self, error=None, awaiting_user=False):
            captured["error"] = error
            if cleanup_error == "reporter":
                raise RuntimeError("reporter close failed")

        def on_output(self, chunk):
            pass

    async def _fake_stream(*args, **kwargs):
        try:
            yield "第一段"
            yield "第二段"
        finally:
            captured["source_closed"] = True
            if cleanup_error == "source":
                raise RuntimeError("source close failed")

    retained = []

    def _retained_stream(*args, **kwargs):
        stream = _fake_stream(*args, **kwargs)
        retained.append(stream)
        return stream

    sessions = dcs.DirectCommandSessionStore()
    monkeypatch.setattr(dcs, "direct_command_sessions", sessions)
    monkeypatch.setattr(
        "app.tools.claude_tools.stream_claude_skill_output", _retained_stream
    )
    monkeypatch.setattr(
        "app.services.command_dashboard.report_command",
        lambda name, digest, **_kwargs: _FakeReporter(),
    )

    # lifespan 注册的 handler 闭包捕获当时的 stream 函数;已注册时需在 patch 生效期间重建并事后恢复
    original_commands = dict(cmd_registry._commands)
    try:
        await _enter_lifespan_once(force=True)
        cmd = cmd_registry.get("adapt")
        if cmd is None:
            pytest.skip("adapt 未注册")

        gen = cmd.handler("验证适配", c_id="command-close")
        assert await gen.__anext__() is not None
        assert sessions.is_in_flight("command-close")
        if cleanup_error == "source":
            with pytest.raises(RuntimeError):
                await gen.aclose()
            await gen.aclose()
        else:
            await gen.aclose()  # 模拟客户端断连 → GeneratorExit

        assert not sessions.is_in_flight("command-close")
        assert captured["error"] == "连接中断"
        assert captured.get("source_closed") is True
    finally:
        for stream in retained:
            await stream.aclose()
        cmd_registry._commands.clear()
        cmd_registry._commands.update(original_commands)


@pytest.mark.asyncio
@pytest.mark.parametrize("failure_stage", ["output", "finish"])
async def test_verify_dashboard_failure_does_not_interrupt_body(monkeypatch, failure_stage):
    from app.services import direct_command_sessions as dcs
    from app.tools.claude_tools import CommandOutput

    outputs = [CommandOutput(content="首段正文"), CommandOutput(content="后续正文")]
    finished = []

    class _FailingReporter:
        def on_output(self, chunk):
            if failure_stage == "output":
                raise RuntimeError("dashboard output failed")

        def finish(self, *args, **kwargs):
            finished.append(True)
            if failure_stage == "finish":
                raise RuntimeError("dashboard finish failed")

    async def _fake_stream(*args, **kwargs):
        for output in outputs:
            yield output

    sessions = dcs.DirectCommandSessionStore()
    monkeypatch.setattr(dcs, "direct_command_sessions", sessions)
    monkeypatch.setattr("app.tools.claude_tools.stream_claude_skill_output", _fake_stream)
    monkeypatch.setattr(
        "app.services.command_dashboard.report_command",
        lambda *args, **kwargs: _FailingReporter(),
    )
    original_commands = dict(cmd_registry._commands)
    try:
        await _enter_lifespan_once(force=True)
        chunks = [chunk async for chunk in cmd_registry.get("verify").handler(
            "帮我验证 Qwen3-8B 在 A2 上的适配", c_id="verify-dashboard-failure",
        )]
        assert chunks == outputs
        assert finished == [True]
        assert sessions.is_in_flight("verify-dashboard-failure") is False
    finally:
        cmd_registry._commands.clear()
        cmd_registry._commands.update(original_commands)


@pytest.mark.asyncio
async def test_resumable_command_pause_keeps_dashboard_incomplete(monkeypatch):
    """可续跑超时只是暂停点;看板不能在真实任务完成前写 success。"""
    from app.services import direct_command_sessions as dcs
    from app.tools.claude_tools import CommandOutput

    captured: dict = {}

    class _FakeReporter:
        def on_output(self, chunk):
            captured["output"] = chunk

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

    async def _paused_stream(*args, **kwargs):
        on_session_id = kwargs.get("on_session_id")
        if on_session_id:
            on_session_id("deploy-session")
        yield CommandOutput(
            content="[系统] 当前任务处理超时。",
            requires_resume=True,
            is_error=True,
        )

    sessions = dcs.DirectCommandSessionStore()
    monkeypatch.setattr(dcs, "direct_command_sessions", sessions)
    monkeypatch.setattr(
        "app.tools.claude_tools.stream_claude_skill_output",
        _paused_stream,
    )
    monkeypatch.setattr(
        "app.services.command_dashboard.report_command",
        lambda name, digest, **_kwargs: _FakeReporter(),
    )

    original_commands = dict(cmd_registry._commands)
    try:
        await _enter_lifespan_once(force=True)
        cmd = cmd_registry.get("deploy")
        assert cmd is not None

        chunks = [chunk async for chunk in cmd.handler(
            "qwen3.5-0.8B 在 A2 上怎么部署?",
            c_id="b1792384305-base-thread-deploy-00",
        )]

        assert chunks[-1].requires_resume is True
        assert captured == {
            "output": chunks[-1],
            "error": None,
            "awaiting_user": False,
            "awaiting_resume": True,
        }
        assert sessions.is_in_flight("b1792384305-base-thread-deploy-00") is False
        assert sessions.get_for_continuation(
            "b1792384305-base-thread-deploy-00",
            "继续",
        ) is not None
    finally:
        cmd_registry._commands.clear()
        cmd_registry._commands.update(original_commands)


@pytest.mark.asyncio
async def test_resumable_command_error_frame_marks_dashboard_failed(monkeypatch):
    """共享 Claude 命令链须将 is_error 终帧映射为失败,续接暂停仍单独处理。"""
    from app.services import direct_command_sessions as dcs
    from app.tools.claude_tools import CommandOutput

    captured: dict = {}
    error_output = CommandOutput(content="[deploy] 调用失败:上游返回错误", is_error=True)

    class _FakeReporter:
        def on_output(self, chunk):
            captured["output"] = chunk

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

    async def _failed_stream(*args, **kwargs):
        yield error_output

    sessions = dcs.DirectCommandSessionStore()
    monkeypatch.setattr(dcs, "direct_command_sessions", sessions)
    monkeypatch.setattr(
        "app.tools.claude_tools.stream_claude_skill_output",
        _failed_stream,
    )
    monkeypatch.setattr(
        "app.services.command_dashboard.report_command",
        lambda name, digest, **_kwargs: _FakeReporter(),
    )

    original_commands = dict(cmd_registry._commands)
    try:
        await _enter_lifespan_once(force=True)
        cmd = cmd_registry.get("deploy")
        assert cmd is not None

        chunks = [chunk async for chunk in cmd.handler(
            "部署 Qwen",
            c_id="direct-error-terminal",
        )]

        assert chunks == [error_output]
        assert captured == {
            "output": error_output,
            "error": error_output.content,
            "awaiting_user": False,
            "awaiting_resume": False,
        }
        assert sessions.is_in_flight("direct-error-terminal") is False
    finally:
        cmd_registry._commands.clear()
        cmd_registry._commands.update(original_commands)