"""Exercise command interruption and continuation through the chat HTTP routes."""

from __future__ import annotations

import asyncio
import json
import os
import threading
from contextlib import aclosing
from unittest.mock import AsyncMock, MagicMock, patch

import httpx
import pytest
from langchain_core.messages import AIMessage


def _chat_content(response: httpx.Response) -> str:
    return "".join(
        json.loads(line[6:])["choices"][0]["delta"].get("content", "")
        for line in response.text.splitlines()
        if line.startswith("data: {") and '"choices"' in line
    )


async def _wait_until(predicate) -> None:
    async def _wait() -> None:
        while not predicate():
            await asyncio.sleep(0.01)

    await asyncio.wait_for(_wait(), 3)


def test_unstarted_command_cannot_cross_conversations():
    from app.api import chat as chat_api

    c_id = "unstarted-command-owner"
    chat_api._remember_unstarted_command(c_id, "/search original goal")
    try:
        assert chat_api._take_unstarted_command("different-conversation", "继续") is None
        assert chat_api._take_unstarted_command(c_id, "继续") == "/search original goal"
    finally:
        chat_api._unstarted_commands.pop(c_id, None)


@pytest.mark.asyncio
async def test_search_explicit_skill_request_executes_skill(command_app):
    from app.tools.claude_tools import CommandOutput
    from commands.registry import cmd_registry

    _, adapters = command_app
    calls = []

    async def skill(*args, **kwargs):
        calls.append((args, kwargs))
        yield CommandOutput(content="NPU 实测完成", user_facing=True)

    adapters["claude"] = skill
    adapters["search"] = lambda _payload: (_ for _ in ()).throw(AssertionError("不应降级为普通搜索"))
    command = cmd_registry.get("search")
    prompt = "现在开始适配,请调用 invoke_claude_skill,skill_name=npu-basic-migrate。"
    output = [chunk async for chunk in command.handler(prompt, c_id="search-explicit-skill")]

    assert calls and calls[0][0][0] == "npu-basic-migrate"
    assert prompt in calls[0][0][1]
    assert any("NPU 实测完成" in str(chunk) for chunk in output)


@pytest.mark.asyncio
@pytest.mark.parametrize("command,prompt", [
    ("claude", "verify-agent goal"),
    ("verify", "goal"),
    ("adapt", "goal"),
    ("optimize", "goal"),
    ("quantify", "goal"),
    ("commit", "goal"),
    ("ai4s", "goal"),
    ("deploy", "goal"),
    ("torch", "goal"),
    ("search", "models"),
    ("doc", "vllm"),
    ("workflow", "goal"),
])
async def test_interrupt_before_sse_starts_can_continue_original_command(
    command_app, monkeypatch, command, prompt,
):
    from app.api import chat as chat_api
    from app.tools import claude_tools
    from app.tools.workflow import brainstorming
    from app.tools.workflow.types import StepType, WorkflowPlan, WorkflowStep

    app, adapters = command_app
    calls = []
    if command in {"claude", "verify", "adapt", "optimize", "quantify", "commit", "ai4s", "deploy"}:
        async def skill(_skill, args, **_kwargs):
            calls.append(args)
            yield claude_tools.CommandOutput(content="ORIGINAL_RESULT")

        adapters["claude"] = skill
    elif command == "torch":
        async def torch(args, **_kwargs):
            calls.append(args)
            yield "ORIGINAL_RESULT"

        adapters["torch"] = torch
    elif command == "workflow":
        def plan(args):
            calls.append(args)
            return WorkflowPlan(
                workflow_id="pre-sse-workflow",
                intent=args,
                steps=[WorkflowStep(id="work", type=StepType.LLM_TOOL, name="Work")],
            )

        adapters["workflow_plan"] = plan
        monkeypatch.setattr(brainstorming, "assess_ambiguity", AsyncMock(return_value=(0, [])))
        monkeypatch.setattr(
            "app.tools.workflow.executor.execute_step_with_pattern",
            AsyncMock(return_value="ORIGINAL_RESULT"),
        )
    else:
        adapters[command] = lambda payload: calls.append(payload) or "ORIGINAL_RESULT"
    entered = asyncio.Event()
    proceed = asyncio.Event()
    original = chat_api._stream_with_replay

    async def paused_stream(*args, **kwargs):
        entered.set()
        await proceed.wait()
        async with aclosing(original(*args, **kwargs)) as stream:
            async for chunk in stream:
                yield chunk

    monkeypatch.setattr(chat_api, "_stream_with_replay", paused_stream)
    c_id = f"before-sse-{command}"
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app), base_url="http://test",
    ) as client:
        running = asyncio.create_task(client.post(
            "/v1/chat/completions",
            json={
                "c_id": c_id, "request_id": f"{c_id}-first",
                "messages": [{"role": "user", "content": f"/{command} {prompt}"}],
            },
        ))
        try:
            await asyncio.wait_for(entered.wait(), 3)
            interrupted = await client.post("/v1/chat/interrupt", json={"c_id": c_id})
            assert interrupted.json() == {"interrupted": True, "mode": "hard_cancel"}
            proceed.set()
            completed, = await asyncio.wait_for(
                asyncio.gather(running, return_exceptions=True), 3,
            )
            if isinstance(completed, httpx.Response):
                assert _chat_content(completed) == ""
            assert calls == []
            continued = await client.post(
                "/v1/chat/completions",
                json={
                    "c_id": c_id, "request_id": f"{c_id}-continue",
                    "messages": [{"role": "user", "content": "继续"}],
                },
            )
            assert "ORIGINAL_RESULT" in _chat_content(continued)
            assert len(calls) == 1
        finally:
            proceed.set()
            running.cancel()
            await asyncio.gather(running, return_exceptions=True)


@pytest.mark.asyncio
async def test_new_command_after_early_interrupt_does_not_resume_old_command(
    command_app, monkeypatch,
):
    from app.api import chat as chat_api

    app, adapters = command_app
    calls = []
    adapters["search"] = lambda payload: calls.append(payload["input"]) or "NEW_RESULT"
    entered = asyncio.Event()
    proceed = asyncio.Event()
    original = chat_api._stream_with_replay

    async def pause_first(*args, **kwargs):
        if not entered.is_set():
            entered.set()
            await proceed.wait()
        async with aclosing(original(*args, **kwargs)) as stream:
            async for chunk in stream:
                yield chunk

    monkeypatch.setattr(chat_api, "_stream_with_replay", pause_first)
    c_id = "new-command-after-interrupt"
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app), base_url="http://test",
    ) as client:
        running = asyncio.create_task(client.post(
            "/v1/chat/completions",
            json={
                "c_id": c_id, "request_id": f"{c_id}-old",
                "messages": [{"role": "user", "content": "/search old goal"}],
            },
        ))
        try:
            await asyncio.wait_for(entered.wait(), 3)
            interrupted = await client.post("/v1/chat/interrupt", json={"c_id": c_id})
            assert interrupted.json() == {"interrupted": True, "mode": "hard_cancel"}
            proceed.set()
            await asyncio.wait_for(asyncio.gather(running, return_exceptions=True), 3)

            fresh = await client.post(
                "/v1/chat/completions",
                json={
                    "c_id": c_id, "request_id": f"{c_id}-fresh",
                    "messages": [{"role": "user", "content": "/search new goal"}],
                },
            )
            assert "NEW_RESULT" in _chat_content(fresh)
            assert calls == ["new goal"]
            assert c_id not in chat_api._unstarted_commands
        finally:
            proceed.set()
            running.cancel()
            await asyncio.gather(running, return_exceptions=True)


@pytest.mark.asyncio
async def test_new_topic_after_planning_interrupt_keeps_memory_bridge(
    command_app, monkeypatch,
):
    from app.api import chat as chat_api
    from app.services import chat_service
    from app.services.direct_command_sessions import direct_command_sessions
    from app.tools import workflow
    from app.tools.workflow import brainstorming

    app, _adapters = command_app
    planning = asyncio.Event()
    calls = []

    async def plan(_self, args):
        calls.append(args)
        planning.set()
        await asyncio.Event().wait()

    monkeypatch.setattr(workflow.DynamicPlanner, "aplan", plan)
    monkeypatch.setattr(brainstorming, "assess_ambiguity", AsyncMock(return_value=(0, [])))
    agent = MagicMock()
    agent.get_state.return_value = MagicMock(values={"messages": []})

    async def agent_stream(*_args, **_kwargs):
        yield "messages", (AIMessage(content="新话题回复"), {})

    agent.astream = MagicMock(side_effect=agent_stream)
    build_agent = MagicMock(return_value=agent)
    monkeypatch.setattr(chat_service, "build_agent", build_agent)
    c_id = "new-topic-after-planning"
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app), base_url="http://test",
    ) as client:
        running = asyncio.create_task(client.post(
            "/v1/chat/completions",
            json={
                "c_id": c_id, "request_id": f"{c_id}-old",
                "messages": [{"role": "user", "content": "/workflow old goal"}],
            },
        ))
        try:
            await asyncio.wait_for(planning.wait(), 3)
            interrupted = await client.post("/v1/chat/interrupt", json={"c_id": c_id})
            assert interrupted.json() == {"interrupted": True, "mode": "hard_cancel"}
            await asyncio.wait_for(asyncio.gather(running, return_exceptions=True), 3)
            await _wait_until(lambda: not direct_command_sessions.is_in_flight(c_id))
            assert direct_command_sessions.get_recent_task_context(c_id) == ("workflow", "old goal")

            fresh = await client.post(
                "/v1/chat/completions",
                json={
                    "c_id": c_id, "request_id": f"{c_id}-fresh",
                    "messages": [{"role": "user", "content": "换个话题,介绍新模型"}],
                },
            )
            assert fresh.status_code == 200
            assert "新话题回复" in _chat_content(fresh)
            assert calls == ["old goal"]
            assert "old goal" in build_agent.call_args.kwargs["user_system_prompt"]
            assert c_id not in chat_api._unstarted_commands
            assert direct_command_sessions.get_for_continuation(c_id, "继续") is None
        finally:
            running.cancel()
            await asyncio.gather(running, return_exceptions=True)


@pytest.mark.asyncio
@pytest.mark.parametrize("command,prompt", [("search", "models"), ("doc", "vllm")])
async def test_interrupted_worker_failure_is_delivered_once(
    command_app, monkeypatch, command, prompt,
):
    from app.services.direct_command_sessions import direct_command_sessions

    app, adapters = command_app
    started = threading.Event()
    release = threading.Event()
    calls = []

    def invoke(payload):
        calls.append(payload)
        started.set()
        release.wait(10)
        raise RuntimeError("original worker failed")

    adapters[command] = invoke
    monkeypatch.setattr("app.services.command_dashboard.report_command", lambda *a, **kw: MagicMock())
    c_id = f"failed-worker-{command}"
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app), base_url="http://test",
    ) as client:
        running = asyncio.create_task(client.post(
            "/v1/chat/completions",
            json={
                "c_id": c_id, "request_id": f"{c_id}-first",
                "messages": [{"role": "user", "content": f"/{command} {prompt}"}],
            },
        ))
        try:
            assert await asyncio.to_thread(started.wait, 3)
            interrupted = await client.post("/v1/chat/interrupt", json={"c_id": c_id})
            assert interrupted.json() == {"interrupted": True, "mode": "hard_cancel"}
            await asyncio.wait_for(asyncio.gather(running, return_exceptions=True), 3)
            release.set()
            await _wait_until(lambda: not direct_command_sessions.is_in_flight(c_id))
            continued = await client.post(
                "/v1/chat/completions",
                json={
                    "c_id": c_id, "request_id": f"{c_id}-continue",
                    "messages": [{"role": "user", "content": "继续"}],
                },
            )
            assert "RuntimeError: original worker failed" in _chat_content(continued)
            assert len(calls) == 1
            assert direct_command_sessions.get_for_continuation(c_id, "继续") is None
        finally:
            release.set()
            running.cancel()
            await asyncio.gather(running, return_exceptions=True)


@pytest.mark.asyncio
async def test_doc_result_survives_interrupt_during_continued_delivery(
    command_app, monkeypatch,
):
    from app.services.direct_command_sessions import direct_command_sessions
    from commands.registry import cmd_registry

    app, adapters = command_app
    started = threading.Event()
    release = threading.Event()
    calls = []

    def invoke(payload):
        calls.append(payload)
        started.set()
        release.wait(10)
        return "FIRST_LINE\nSECOND_LINE\n"

    adapters["doc"] = invoke
    monkeypatch.setattr("app.services.command_dashboard.report_command", lambda *a, **kw: MagicMock())
    c_id = "doc-twice-interrupted"
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app), base_url="http://test",
    ) as client:
        running = asyncio.create_task(client.post(
            "/v1/chat/completions",
            json={
                "c_id": c_id, "request_id": f"{c_id}-first",
                "messages": [{"role": "user", "content": "/doc vllm"}],
            },
        ))
        try:
            assert await asyncio.to_thread(started.wait, 3)
            interrupted = await client.post("/v1/chat/interrupt", json={"c_id": c_id})
            assert interrupted.json() == {"interrupted": True, "mode": "hard_cancel"}
            await asyncio.wait_for(asyncio.gather(running, return_exceptions=True), 3)
            release.set()
            await _wait_until(lambda: not direct_command_sessions.is_in_flight(c_id))

            handler = cmd_registry.get("doc").handler
            replay = handler("继续", c_id=c_id)
            assert await anext(replay) == "FIRST_LINE\n"
            await replay.aclose()
            assert direct_command_sessions.get_for_continuation(c_id, "继续") is not None

            replay = handler("继续", c_id=c_id)
            assert "".join([line async for line in replay]) == "FIRST_LINE\nSECOND_LINE\n"
            assert len(calls) == 1
            assert direct_command_sessions.get_for_continuation(c_id, "继续") is None
        finally:
            release.set()
            running.cancel()
            await asyncio.gather(running, return_exceptions=True)


@pytest.mark.asyncio
@pytest.mark.parametrize("followup", ["继续", "继续回复"])
async def test_torch_interrupt_during_helper_load_restarts_original_prompt(
    command_app, monkeypatch, tmp_path, followup,
):
    from app.services.direct_command_sessions import direct_command_sessions
    from app.tools import pta_tools

    app, adapters = command_app
    adapters["torch"] = adapters["torch_actual"]
    monkeypatch.setattr(pta_tools, "_PTA_HELPER_ROOT", tmp_path)
    monkeypatch.setattr(pta_tools, "_ensure_pta_helper_in_path", lambda: None)
    monkeypatch.setattr("app.services.command_dashboard.report_command", lambda *a, **kw: MagicMock())
    loading = threading.Event()
    release = threading.Event()
    calls = []

    def helper(prompt, **kwargs):
        calls.append(prompt)
        kwargs["on_text"]("ORIGINAL_RESULT")

    def load_helper():
        loading.set()
        release.wait(10)
        return helper

    monkeypatch.setattr(pta_tools, "_load_pta_helper", load_helper)
    c_id = "torch-cold-load-reply" if followup == "继续回复" else "torch-cold-load-continue"
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app), base_url="http://test",
    ) as client:
        running = asyncio.create_task(client.post(
            "/v1/chat/completions",
            json={
                "c_id": c_id, "request_id": f"{c_id}-first",
                "messages": [{"role": "user", "content": "/torch original goal"}],
            },
        ))
        try:
            assert await asyncio.to_thread(loading.wait, 3)
            interrupted = await client.post("/v1/chat/interrupt", json={"c_id": c_id})
            assert interrupted.json() == {"interrupted": True, "mode": "hard_cancel"}
            await asyncio.wait_for(asyncio.gather(running, return_exceptions=True), 3)
            await _wait_until(lambda: not direct_command_sessions.is_in_flight(c_id))
            assert calls == []
            release.set()

            continued = await client.post(
                "/v1/chat/completions",
                json={
                    "c_id": c_id, "request_id": f"{c_id}-continue",
                    "messages": [{"role": "user", "content": followup}],
                },
            )
            assert "ORIGINAL_RESULT" in _chat_content(continued)
            assert len(calls) == 1
            assert "original goal" in calls[0]
        finally:
            release.set()
            running.cancel()
            await asyncio.gather(running, return_exceptions=True)


@pytest.mark.asyncio
@pytest.mark.parametrize("command,prompt", [("search", "models"), ("doc", "vllm")])
async def test_continue_after_success_does_not_repeat_direct_tool(command_app, command, prompt):
    from app.services.direct_command_sessions import direct_command_sessions

    app, adapters = command_app
    calls = []
    adapters[command] = lambda payload: calls.append(payload) or "COMPLETED_RESULT"
    c_id = f"completed-{command}"
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app), base_url="http://test",
    ) as client:
        completed = await client.post(
            "/v1/chat/completions",
            json={
                "c_id": c_id, "request_id": f"{c_id}-first",
                "messages": [{"role": "user", "content": f"/{command} {prompt}"}],
            },
        )
        assert "COMPLETED_RESULT" in _chat_content(completed)
        assert direct_command_sessions.get_for_continuation(c_id, "继续") is None
        continued = await client.post(
            "/v1/chat/completions",
            json={
                "c_id": c_id, "request_id": f"{c_id}-continue",
                "messages": [{"role": "user", "content": "继续"}],
            },
        )
        assert continued.status_code == 200
        assert len(calls) == 1


@pytest.mark.asyncio
@pytest.mark.parametrize("command,prompt", [("search", "models"), ("doc", "vllm")])
async def test_continue_after_terminal_failure_does_not_repeat_direct_tool(
    command_app, command, prompt,
):
    from app.services.direct_command_sessions import direct_command_sessions

    app, adapters = command_app
    calls = []

    def invoke(payload):
        calls.append(payload)
        raise RuntimeError("terminal failure")

    adapters[command] = invoke
    c_id = f"terminal-failure-{command}"
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app), base_url="http://test",
    ) as client:
        failed = await client.post(
            "/v1/chat/completions",
            json={
                "c_id": c_id, "request_id": f"{c_id}-first",
                "messages": [{"role": "user", "content": f"/{command} {prompt}"}],
            },
        )
        assert "RuntimeError: terminal failure" in _chat_content(failed)
        assert direct_command_sessions.get_for_continuation(c_id, "继续") is None
        continued = await client.post(
            "/v1/chat/completions",
            json={
                "c_id": c_id, "request_id": f"{c_id}-continue",
                "messages": [{"role": "user", "content": "继续"}],
            },
        )
        assert continued.status_code == 200
        assert len(calls) == 1


@pytest.mark.asyncio
async def test_interrupt_during_workflow_planning_restarts_original_goal(
    command_app, monkeypatch,
):
    from app.services.direct_command_sessions import direct_command_sessions
    from app.tools import workflow
    from app.tools.workflow import brainstorming
    from app.tools.workflow.types import StepType, WorkflowPlan, WorkflowStep

    app, _adapters = command_app
    planning = asyncio.Event()
    planning_calls = []

    async def plan(_self, args):
        planning_calls.append(args)
        if len(planning_calls) == 1:
            planning.set()
            await asyncio.Event().wait()
        return WorkflowPlan(
            workflow_id="immediate-workflow-resume",
            intent=args,
            steps=[WorkflowStep(id="work", type=StepType.LLM_TOOL, name="Work")],
        )

    monkeypatch.setattr(workflow.DynamicPlanner, "aplan", plan)
    monkeypatch.setattr(brainstorming, "assess_ambiguity", AsyncMock(return_value=(0, [])))
    c_id = "immediate-workflow-planning"

    async def execute_step(*_args, **_kwargs):
        current = direct_command_sessions.get_for_continuation(c_id, "继续")
        assert current is not None
        assert current.workflow_id == "immediate-workflow-resume"
        return "ORIGINAL_RESULT"

    monkeypatch.setattr(
        "app.tools.workflow.executor.execute_step_with_pattern", execute_step,
    )
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app), base_url="http://test",
    ) as client:
        running = asyncio.create_task(client.post(
            "/v1/chat/completions",
            json={
                "c_id": c_id, "request_id": f"{c_id}-first",
                "messages": [{"role": "user", "content": "/workflow original goal"}],
            },
        ))
        try:
            await asyncio.wait_for(planning.wait(), 3)
            interrupted = await client.post("/v1/chat/interrupt", json={"c_id": c_id})
            assert interrupted.json() == {"interrupted": True, "mode": "hard_cancel"}
            await asyncio.wait_for(asyncio.gather(running, return_exceptions=True), 3)
            await _wait_until(lambda: not direct_command_sessions.is_in_flight(c_id))

            continued = await client.post(
                "/v1/chat/completions",
                json={
                    "c_id": c_id, "request_id": f"{c_id}-continue",
                    "messages": [{"role": "user", "content": "继续"}],
                },
            )
            assert "ORIGINAL_RESULT" in _chat_content(continued)
            assert planning_calls == ["original goal", "original goal"]
        finally:
            running.cancel()
            await asyncio.gather(running, return_exceptions=True)


@pytest.mark.asyncio
@pytest.mark.parametrize("command,prompt", [
    ("verify", "goal"), ("search", "models"), ("workflow", "goal"),
])
async def test_interrupt_after_stream_registration_before_command_starts(
    command_app, monkeypatch, command, prompt,
):
    from app.services import chat_service
    from app.tools import claude_tools
    from app.tools.workflow import brainstorming
    from app.tools.workflow.types import StepType, WorkflowPlan, WorkflowStep

    app, adapters = command_app
    calls = []
    if command == "verify":
        async def skill(_skill, args, **_kwargs):
            calls.append(args)
            yield claude_tools.CommandOutput(content="ORIGINAL_RESULT")

        adapters["claude"] = skill
    elif command == "search":
        adapters["search"] = lambda payload: calls.append(payload) or "ORIGINAL_RESULT"
    else:
        def plan(args):
            calls.append(args)
            return WorkflowPlan(
                workflow_id="registered-workflow",
                intent=args,
                steps=[WorkflowStep(id="work", type=StepType.LLM_TOOL, name="Work")],
            )

        adapters["workflow_plan"] = plan
        monkeypatch.setattr(brainstorming, "assess_ambiguity", AsyncMock(return_value=(0, [])))
        monkeypatch.setattr(
            "app.tools.workflow.executor.execute_step_with_pattern",
            AsyncMock(return_value="ORIGINAL_RESULT"),
        )

    entered = asyncio.Event()
    proceed = asyncio.Event()
    original = chat_service._execute_command

    async def paused_command(*args, **kwargs):
        entered.set()
        await proceed.wait()
        async with aclosing(original(*args, **kwargs)) as stream:
            async for chunk in stream:
                yield chunk

    monkeypatch.setattr(chat_service, "_execute_command", paused_command)
    c_id = f"registered-before-command-{command}"
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app), base_url="http://test",
    ) as client:
        running = asyncio.create_task(client.post(
            "/v1/chat/completions",
            json={
                "c_id": c_id, "request_id": f"{c_id}-first",
                "messages": [{"role": "user", "content": f"/{command} {prompt}"}],
            },
        ))
        try:
            await asyncio.wait_for(entered.wait(), 3)
            interrupted = await client.post("/v1/chat/interrupt", json={"c_id": c_id})
            assert interrupted.json() == {"interrupted": True, "mode": "hard_cancel"}
            proceed.set()
            await asyncio.wait_for(asyncio.gather(running, return_exceptions=True), 3)
            assert calls == []

            continued = await client.post(
                "/v1/chat/completions",
                json={
                    "c_id": c_id, "request_id": f"{c_id}-continue",
                    "messages": [{"role": "user", "content": "继续"}],
                },
            )
            assert "ORIGINAL_RESULT" in _chat_content(continued)
            assert len(calls) == 1
        finally:
            proceed.set()
            running.cancel()
            await asyncio.gather(running, return_exceptions=True)


@pytest.fixture
async def command_app(monkeypatch, tmp_path):
    from app import main
    from app.api import chat as chat_api
    from app.config import settings
    from app.services.direct_command_sessions import direct_command_sessions
    from app.tools import claude_tools, doc_tools, pta_tools, search_tools, workflow
    from commands.registry import cmd_registry
    from lts_logger import lts_logger

    monkeypatch.setattr(settings, "model_agent_eval_enabled", False)
    monkeypatch.setattr(settings, "realtime_eval_enabled", False)
    monkeypatch.setattr(settings, "workflow_dashboard_enabled", False)
    monkeypatch.setattr(settings, "claude_history_enabled", False)
    monkeypatch.setattr(settings, "mcp_auto_start", False)
    monkeypatch.setattr(settings, "hermes_enabled", False)
    monkeypatch.setattr(settings, "workflow_checkpoint_dir", str(tmp_path))
    monkeypatch.setattr(chat_api, "build_llm", lambda **_kwargs: MagicMock())
    monkeypatch.setattr(cmd_registry, "_commands", {})
    monkeypatch.setattr(lts_logger, "shutdown", AsyncMock())
    adapters = {"torch_actual": pta_tools.stream_pta_query}

    async def skill_output(*args, **kwargs):
        async for chunk in adapters["claude"](*args, **kwargs):
            yield chunk

    async def pta_output(*args, **kwargs):
        # Match the production relay: closing this adapter must close the
        # helper stream so its detached-worker callback retains the session.
        async with aclosing(adapters["torch"](*args, **kwargs)) as inner:
            async for chunk in inner:
                yield chunk

    class ToolProxy:
        def __init__(self, command):
            self.command = command

        def invoke(self, payload):
            return adapters[self.command](payload)

    class PlannerProxy:
        async def aplan(self, args):
            return adapters["workflow_plan"](args)

    monkeypatch.setattr(claude_tools, "stream_claude_skill_output", skill_output)
    monkeypatch.setattr(pta_tools, "stream_pta_query", pta_output)
    monkeypatch.setattr(search_tools, "search_ascend_models", ToolProxy("search"))
    monkeypatch.setattr(doc_tools, "doc_agent_vllm_adapter_docs", ToolProxy("doc"))
    monkeypatch.setattr(workflow, "DynamicPlanner", PlannerProxy)

    def drop_background_task(coro):
        coro.close()
        return MagicMock()

    with (
        patch.object(asyncio, "create_task", drop_background_task),
        patch.dict(os.environ),
        patch("app.tools.workflow.mcp_integration.shutdown_mcp_manager", new_callable=AsyncMock),
    ):
        async with main.lifespan(main.app):
            pass
    yield main.app, adapters
    direct_command_sessions.clear_all()


@pytest.mark.asyncio
@pytest.mark.parametrize("command,prompt", [
    ("claude", "verify-agent 检查模型"), ("verify", "检查模型"),
    ("adapt", "检查模型"), ("optimize", "检查模型"),
    ("quantify", "检查模型"), ("commit", "检查模型"),
    ("ai4s", "检查模型"), ("deploy", "检查模型"),
    ("search", "models"), ("doc", "vllm"), ("torch", "检查模型"),
    ("workflow", "检查模型"), ("experience", "stats"), ("learn", "检查模型"),
])
@pytest.mark.parametrize("outcome", ["success", "failure"])
async def test_all_fourteen_commands_match_body_and_graph_and_ignore_dashboard_faults(
    command_app, monkeypatch, tmp_path, command, prompt, outcome,
):
    """真实 HTTP/命令/看板链;仅模型、外部工具和经验存储使用替身。"""
    from app.model_agent.dashboard.server import DashboardServer
    from app.services import command_dashboard
    from app.services.dashboard_bridge import DashboardBridge
    from app.tools import pta_tools
    from app.tools.claude_tools import CommandOutput
    from app.tools.workflow import brainstorming
    from app.tools.workflow.types import StepType, WorkflowPlan, WorkflowStep

    app, adapters = command_app
    marker = "真实结果:受控执行输出" if outcome == "success" else f"[{command}] 调用失败:受控执行异常"

    async def skill(*args, **kwargs):
        yield CommandOutput(content=marker, user_facing=True, is_error=outcome == "failure")

    adapters.update(claude=skill, search=lambda payload: marker, doc=lambda payload: marker)
    adapters["workflow_plan"] = lambda args: WorkflowPlan(
        workflow_id="contract-workflow", intent=args, goal=args,
        steps=[WorkflowStep(id="inspect", type=StepType.LLM_TOOL, name="检查环境", skill_name="fake-tool")],
    )
    monkeypatch.setattr(brainstorming, "assess_ambiguity", AsyncMock(return_value=(0, [])))
    from app.tools.workflow.patterns import WorkflowStepExecutionError

    execute = AsyncMock(return_value=marker) if outcome == "success" else AsyncMock(side_effect=WorkflowStepExecutionError(marker, retryable=False))
    monkeypatch.setattr("app.tools.workflow.executor.execute_step_with_pattern", execute)
    store = MagicMock()
    store.count_memories.return_value = 0
    store.get_all_skills.return_value = []
    store.get_pending_insights.return_value = []
    if outcome == "failure":
        store.count_memories.side_effect = RuntimeError(marker)
        store.append_memory.side_effect = RuntimeError(marker)
    monkeypatch.setattr("app.tools.experience.store.ExperienceStore", lambda: store)
    monkeypatch.setattr(pta_tools, "_PTA_HELPER_ROOT", tmp_path)
    monkeypatch.setattr(pta_tools, "_ensure_pta_helper_in_path", lambda: None)
    def helper(prompt, **kwargs):
        if outcome == "failure":
            raise RuntimeError(marker)
        kwargs["on_text"](marker)

    monkeypatch.setattr(pta_tools, "_load_pta_helper", lambda: helper)
    adapters["torch"] = adapters["torch_actual"]

    class Dashboard:
        def __init__(self):
            self._workflow_def = None
            self.events = []

        def set_workflow_def(self, definition):
            if mode == "initialize_error":
                raise RuntimeError("dashboard injected initialization failure")
            self._workflow_def = definition

        append_workflow_nodes = set_workflow_def

        def push_event(self, event):
            terminal = event.event_type.value in {"workflow.completed", "workflow.failed"}
            if (mode == "output_error" and not terminal) or (mode == "finish_error" and terminal):
                raise RuntimeError("dashboard injected transport failure")
            self.events.append(event)

    dashboard = Dashboard()
    monkeypatch.setattr(DashboardServer, "get_instance", classmethod(lambda cls, config=None: dashboard))

    def ready(bridge):
        if os.environ.get("WORKFLOW_DASHBOARD_ENABLED") != "true":
            return False
        bridge._server = dashboard
        return True

    monkeypatch.setattr(DashboardBridge, "_server_ready", ready)
    original_report = command_dashboard.report_command
    original_output = command_dashboard.CommandDashboardReporter.on_output
    original_finish = command_dashboard.CommandDashboardReporter.finish
    baseline = None
    async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
        for mode in ["normal", "disabled", "initialize_error", "output_error", "finish_error"]:
            dashboard.events.clear()
            monkeypatch.setenv("WORKFLOW_DASHBOARD_ENABLED", "false" if mode == "disabled" else "true")

            def fail(*args, **kwargs):
                raise RuntimeError("dashboard injected failure")

            monkeypatch.setattr(command_dashboard, "report_command", fail if mode == "initialize_error" else original_report)
            monkeypatch.setattr(command_dashboard.CommandDashboardReporter, "on_output", fail if mode == "output_error" else original_output)
            monkeypatch.setattr(command_dashboard.CommandDashboardReporter, "finish", fail if mode == "finish_error" else original_finish)
            response = await client.post("/v1/chat/completions", json={
                "c_id": f"contract-{command}-{outcome}-{mode}", "request_id": f"contract-{command}-{outcome}-{mode}",
                "messages": [{"role": "user", "content": f"/{command} {prompt}"}],
            })
            assert response.status_code == 200
            body = _chat_content(response)
            frames = [json.loads(line[6:]) for line in response.text.splitlines() if line.startswith("data: {")]
            terminal = [choice for frame in frames for choice in frame.get("choices", []) if choice.get("finish_reason")]
            assert [choice["finish_reason"] for choice in terminal] == ["error" if outcome == "failure" else "stop"]
            assert response.text.count("data: [DONE]") == 1
            if mode == "normal":
                baseline = body
                assert any(event.event_type.value == "node.started" for event in dashboard.events)
                if outcome == "failure":
                    assert marker in body
                    assert any(event.event_type.value == "workflow.failed" for event in dashboard.events)
                    assert any(event.event_type.value in {"node.failed", "workflow.failed"}
                               and marker in str(event.data.get("error")) for event in dashboard.events)
                    assert not any(event.event_type.value == "workflow.completed" for event in dashboard.events)
                    continue
                assert any(event.event_type.value == "workflow.completed" for event in dashboard.events)
                outputs = [event.data.get("output_full") or event.data.get("output_preview") or ""
                           for event in dashboard.events if event.event_type.value == "node.completed"]
                if command == "workflow":
                    assert marker in body
                    assert any(marker in output for output in outputs)
                else:
                    assert body in outputs
            else:
                assert body == baseline, (command, mode, body)


@pytest.mark.asyncio
async def test_parallel_commands_preserve_each_body_partial_failure_and_graph(command_app, monkeypatch, tmp_path):
    from app.model_agent.dashboard.config import DashboardConfig
    from app.model_agent.dashboard.server import DashboardServer
    from app.tools.claude_tools import CommandOutput

    app, adapters = command_app
    server = DashboardServer(DashboardConfig(enabled=False, history_dir=str(tmp_path / "parallel-history")))
    monkeypatch.setenv("WORKFLOW_DASHBOARD_ENABLED", "true")
    monkeypatch.setattr(DashboardServer, "get_instance", classmethod(lambda cls, config=None: server))
    barrier = asyncio.Barrier(3)
    executions = []

    async def skill(skill_name, prompt, **kwargs):
        executions.append(prompt)
        yield CommandOutput(content=f"{prompt} 第一段\n", user_facing=True)
        await asyncio.wait_for(barrier.wait(), 2)
        yield CommandOutput(content=f"{prompt} 已完成的阶段结果\n", user_facing=True)
        if prompt == "任务甲":
            raise RuntimeError("任务甲受控异常")
        await asyncio.sleep(0)
        yield CommandOutput(content=f"{prompt} 最后一段\n", user_facing=True)

    adapters["claude"] = skill
    prompts = ["任务甲", "任务乙", "任务丙"]
    async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
        async def send(prompt):
            return await client.post("/v1/chat/completions", json={
                "c_id": f"parallel-{prompt}", "request_id": "same-id-in-different-conversations",
                "messages": [{"role": "user", "content": f"/verify {prompt}"}],
            })

        responses = await asyncio.wait_for(asyncio.gather(*(send(prompt) for prompt in prompts)), 5)
        runs = {run["topic_id"]: server.get_run(run["workflow_id"]) for run in server.list_runs()}
        assert len(runs) == 3
        for prompt, response in zip(prompts, responses):
            assert response.status_code == 200
            body = _chat_content(response)
            expected = f"正在执行 /verify...\n\n{prompt} 第一段\n{prompt} 已完成的阶段结果\n"
            assert body.startswith(expected)
            assert all(other not in body for other in prompts if other != prompt)
            failed = prompt == "任务甲"
            if failed:
                assert "任务甲受控异常" in body
            else:
                assert body == expected + f"{prompt} 最后一段\n"
            frames = [json.loads(line[6:]) for line in response.text.splitlines() if line.startswith("data: {")]
            terminals = [choice["finish_reason"] for frame in frames for choice in frame.get("choices", []) if choice.get("finish_reason")]
            assert terminals == ["error" if failed else "stop"]
            assert response.text.count("data: [DONE]") == 1
            run = runs[f"parallel-{prompt}"]
            assert run["final_status"] == ("failed" if failed else "success")
            root = next(node for node in run["nodes"] if node["id"] == "verify")
            assert root["output_full"] == expected + ("" if failed else f"{prompt} 最后一段\n")
            assert (await send(prompt)).text == response.text
        assert sorted(executions) == sorted(prompts)


@pytest.mark.asyncio
async def test_workflow_planning_for_new_conversations_is_concurrent(command_app, monkeypatch):
    from app.tools import workflow
    from app.tools.workflow import brainstorming
    from app.tools.workflow.types import StepType, WorkflowPlan, WorkflowStep

    app, _adapters = command_app
    barrier = asyncio.Barrier(2)
    planned = []

    async def plan(self, args):
        planned.append(args)
        await asyncio.wait_for(barrier.wait(), 2)
        return WorkflowPlan(
            workflow_id=f"parallel-plan-{args}", intent=args, goal=args,
            steps=[WorkflowStep(id="check", type=StepType.LLM_TOOL, name=f"检查{args}", skill_name="fake-tool")],
        )

    async def execute(step, ctx, *args, **kwargs):
        return f"真实结果 {ctx.workflow_id}"

    monkeypatch.setattr(workflow.DynamicPlanner, "aplan", plan)
    monkeypatch.setattr(brainstorming, "assess_ambiguity", AsyncMock(return_value=(0, [])))
    monkeypatch.setattr("app.tools.workflow.executor.execute_step_with_pattern", execute)
    monkeypatch.setenv("WORKFLOW_DASHBOARD_ENABLED", "false")
    async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
        async def send(prompt):
            return await client.post("/v1/chat/completions", json={
                "c_id": f"concurrent-plan-{prompt}", "request_id": "concurrent-plan-a" if prompt == "甲" else "concurrent-plan-b",
                "messages": [{"role": "user", "content": f"/workflow {prompt}"}],
            })

        responses = await asyncio.wait_for(asyncio.gather(send("甲"), send("乙")), 5)
    assert sorted(planned) == ["乙", "甲"], [response.text for response in responses]
    for prompt, response in zip(["甲", "乙"], responses):
        assert response.status_code == 200
        assert f"真实结果 parallel-plan-{prompt}" in _chat_content(response)
        assert '"finish_reason":"error"' not in response.text


@pytest.mark.asyncio
@pytest.mark.parametrize("command,prompt", [("search", "models"), ("doc", "vllm")])
async def test_sync_command_no_longer_injects_progress_into_body(
    command_app, monkeypatch, command, prompt,
):
    from app.services.direct_command_sessions import direct_command_sessions
    from commands.registry import cmd_registry

    _app, adapters = command_app
    called = False

    def blocked_tool(_payload):
        nonlocal called
        called = True
        raise AssertionError("tool failure")

    adapters[command] = blocked_tool
    monkeypatch.setattr(
        "app.services.command_dashboard.report_command",
        lambda *args, **kwargs: MagicMock(),
    )
    c_id = f"progress-before-tool-{command}"
    stream = cmd_registry.get(command).handler(prompt, c_id=c_id)

    first = await asyncio.wait_for(anext(stream), timeout=1)

    assert "tool failure" in first
    assert called is True
    await stream.aclose()
    assert direct_command_sessions.is_in_flight(c_id) is False


async def _consume_response_until(iterator, marker: str) -> list[str]:
    chunks = []
    while marker not in "".join(chunks):
        chunks.append(await asyncio.wait_for(anext(iterator), 3))
    return chunks


def _capture_command_reporters(monkeypatch):
    from app.services import command_dashboard

    reporters = {}

    class Reporter:
        def __init__(self):
            self.outputs = []
            self.finished = []

        def on_output(self, output):
            self.outputs.append(output)

        def finish(self, *args, **kwargs):
            self.finished.append((args, kwargs))

    def report(command, args, c_id="", **_kwargs):
        reporter = Reporter()
        reporters[c_id] = reporter
        return reporter

    monkeypatch.setattr(command_dashboard, "report_command", report)
    return reporters


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "command,prompt",
    [
        ("claude", "verify-agent task"),
        ("verify", "task"),
        ("adapt", "task"),
        ("optimize", "task"),
        ("quantify", "task"),
        ("commit", "task"),
        ("ai4s", "task"),
        ("deploy", "task"),
    ],
)
async def test_claude_commands_stream_body_before_skill_finishes(
    command_app, monkeypatch, command, prompt,
):
    from app.api import chat as chat_api
    from app.models.chat import ChatCompletionRequest, ChatMessage
    from app.tools.claude_tools import CommandOutput

    _app, adapters = command_app
    reporters = _capture_command_reporters(monkeypatch)
    release = asyncio.Event()
    waiting = asyncio.Event()

    async def skill(_skill, _args, **_kwargs):
        yield CommandOutput(content="STREAM_FIRST")
        waiting.set()
        await release.wait()
        yield CommandOutput(content="STREAM_SECOND")

    adapters["claude"] = skill
    c_id = f"stream-body-{command}"
    request = ChatCompletionRequest(
        c_id=c_id,
        request_id=c_id,
        messages=[ChatMessage(role="user", content=f"/{command} {prompt}")],
    )
    response = await chat_api.chat_completions(request)
    chunks = response.body_iterator
    try:
        initial = await _consume_response_until(chunks, "STREAM_FIRST")
        await asyncio.wait_for(waiting.wait(), 1)
        assert "STREAM_FIRST" in "".join(initial)
        assert not release.is_set()
        assert any(
            getattr(output, "content", "") == "STREAM_FIRST"
            for output in reporters[c_id].outputs
        )

        release.set()
        tail = [chunk async for chunk in chunks]
        assert "STREAM_SECOND" in "".join(tail)
        assert "[DONE]" in "".join(tail)
    finally:
        release.set()
        await chunks.aclose()


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "command,prompt",
    [
        ("search", "models"),
        ("doc", "vllm"),
    ],
)
async def test_sync_commands_deliver_start_notice_before_tool_result(
    command_app, monkeypatch, command, prompt,
):
    from app.api import chat as chat_api
    from app.models.chat import ChatCompletionRequest, ChatMessage

    _app, adapters = command_app
    reporters = _capture_command_reporters(monkeypatch)
    started = threading.Event()
    release = threading.Event()

    def tool(_payload):
        started.set()
        release.wait(5)
        return "SYNC_TOOL_RESULT"

    adapters[command] = tool
    c_id = f"sync-progress-{command}"
    response = await chat_api.chat_completions(ChatCompletionRequest(
        c_id=c_id,
        request_id=c_id,
        messages=[ChatMessage(role="user", content=f"/{command} {prompt}")],
    ))
    chunks = response.body_iterator
    pending = None
    try:
        initial = await _consume_response_until(chunks, f"正在执行 /{command}")
        pending = asyncio.create_task(anext(chunks))
        assert await asyncio.to_thread(started.wait, 2)
        assert not release.is_set()
        assert reporters[c_id].outputs == []
        assert not pending.done()
        release.set()
        first_result_chunk = await asyncio.wait_for(pending, 3)
        tail = [first_result_chunk, *[chunk async for chunk in chunks]]
        assert "SYNC_TOOL_RESULT" in "".join(initial + tail)
        assert "[DONE]" in "".join(tail)
        assert reporters[c_id].outputs == ["SYNC_TOOL_RESULT"]
        assert reporters[c_id].finished
    finally:
        release.set()
        if pending is not None and not pending.done():
            pending.cancel()
            await asyncio.gather(pending, return_exceptions=True)
        await chunks.aclose()


@pytest.mark.asyncio
async def test_torch_streams_helper_output_before_helper_finishes(
    command_app, monkeypatch, tmp_path,
):
    from app.api import chat as chat_api
    from app.models.chat import ChatCompletionRequest, ChatMessage
    from app.tools import pta_tools

    _app, adapters = command_app
    reporters = _capture_command_reporters(monkeypatch)
    monkeypatch.setattr(pta_tools, "_PTA_HELPER_ROOT", tmp_path)
    monkeypatch.setattr(pta_tools, "_ensure_pta_helper_in_path", lambda: None)
    adapters["torch"] = adapters["torch_actual"]
    release = threading.Event()
    waiting = threading.Event()

    def helper(_prompt, *, memory, session_id, on_text, on_step=None):
        on_text("PTA_FIRST")
        waiting.set()
        release.wait(5)
        on_text("PTA_SECOND")

    monkeypatch.setattr(pta_tools, "_load_pta_helper", lambda: helper)
    c_id = "torch-stream-body"
    response = await chat_api.chat_completions(ChatCompletionRequest(
        c_id=c_id,
        request_id=c_id,
        messages=[ChatMessage(role="user", content="/torch long task")],
    ))
    chunks = response.body_iterator
    try:
        initial = await _consume_response_until(chunks, "PTA_FIRST")
        assert await asyncio.to_thread(waiting.wait, 1)
        assert not release.is_set()
        assert "PTA_FIRST" in "".join(initial)

        release.set()
        tail = [chunk async for chunk in chunks]
        assert "PTA_SECOND" in "".join(tail)
        assert "[DONE]" in "".join(tail)
        assert any("PTA_FIRST" in str(output) for output in reporters[c_id].outputs)
    finally:
        release.set()
        await chunks.aclose()


@pytest.mark.asyncio
async def test_workflow_starts_dashboard_during_planning_and_streams_step_events(
    command_app, monkeypatch,
):
    from app.api import chat as chat_api
    from app.models.chat import ChatCompletionRequest, ChatMessage
    from app.services.dashboard_bridge import DashboardBridge
    from app.tools.workflow import brainstorming
    from app.tools.workflow.types import StepType, WorkflowPlan, WorkflowStep

    _app, adapters = command_app

    class Dashboard:
        def __init__(self):
            self._workflow_def = None
            self.events = []
            self.sequence = []

        def set_workflow_def(self, workflow_def):
            self._workflow_def = workflow_def

        def append_workflow_nodes(self, workflow_def):
            self._workflow_def = workflow_def

        def push_event(self, event):
            self.events.append(event)
            self.sequence.append(("event", event.event_type.value, event.data.copy()))

    dashboard = Dashboard()

    def server_ready(bridge):
        bridge._server = dashboard
        return True

    monkeypatch.setattr(DashboardBridge, "_server_ready", server_ready)
    monkeypatch.setattr(brainstorming, "assess_ambiguity", AsyncMock(return_value=(0, [])))
    planner_called = False
    step_started = asyncio.Event()
    release_step = asyncio.Event()
    plan = WorkflowPlan(
        workflow_id="workflow-stream-live",
        intent="workflow stream task",
        goal="workflow stream task",
        steps=[WorkflowStep(
            id="step-1", type=StepType.LLM_TOOL, name="Inspect environment",
            skill_name="fake-tool",
        )],
    )

    def planner(_args):
        nonlocal planner_called
        planner_called = True
        dashboard.sequence.append(("planner",))
        return plan

    adapters["workflow_plan"] = planner

    async def execute_step(step, ctx, execution_plan, *, progress_callback=None):
        await progress_callback({
            "event": "step_output", "id": step.id, "step": step.name,
            "kind": "output", "chunk": "LIVE_NODE_OUTPUT",
        })
        await progress_callback({
            "event": "step_output", "id": step.id, "step": step.name,
            "kind": "progress", "chunk": "WORKFLOW_PROGRESS",
        })
        step_started.set()
        await release_step.wait()
        return "WORKFLOW_RESULT"

    monkeypatch.setattr(
        "app.tools.workflow.executor.execute_step_with_pattern", execute_step,
    )
    c_id = "workflow-stream-live"
    response = await chat_api.chat_completions(ChatCompletionRequest(
        c_id=c_id,
        request_id=c_id,
        messages=[ChatMessage(role="user", content="/workflow workflow stream task")],
    ))
    chunks = response.body_iterator
    try:
        await _consume_response_until(chunks, "正在分析您的需求并规划工作流")
        # 提示先交付,不能依赖后台预拉取已进入规划器的调度顺序。
        await _wait_until(lambda: planner_called)
        assert any(
            event.event_type.value == "node.started"
            and event.data.get("source") == "user_input"
            for event in dashboard.events
        )
        planning_start = next(
            index for index, entry in enumerate(dashboard.sequence)
            if entry[0] == "event" and entry[1] == "node.started"
            and entry[2].get("source") == "user_input"
        )
        planner_index = next(
            index for index, entry in enumerate(dashboard.sequence)
            if entry[0] == "planner"
        )
        assert planning_start < planner_index
        execution = await _consume_response_until(chunks, "WORKFLOW_PROGRESS")
        assert planner_called
        assert await asyncio.wait_for(step_started.wait(), 1)
        assert "WORKFLOW_PROGRESS" in "".join(execution)
        assert any(
            event.event_type.value == "node.output.chunk"
            and event.data.get("output_chunk") == "LIVE_NODE_OUTPUT"
            for event in dashboard.events
        )
        assert any(
            event.event_type.value == "node.started" and event.node_id == "step-1"
            for event in dashboard.events
        )

        release_step.set()
        tail = [chunk async for chunk in chunks]
        assert "WORKFLOW_RESULT" in "".join(tail)
        assert "[DONE]" in "".join(tail)
    finally:
        release_step.set()
        await chunks.aclose()


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "command,prefix",
    [
        ("claude", "verify-agent "),
        ("verify", ""),
        ("adapt", ""),
        ("optimize", ""),
        ("quantify", ""),
        ("commit", ""),
        ("ai4s", ""),
        ("deploy", ""),
    ],
)
async def test_claude_command_http_short_interrupt_and_resume(command_app, command, prefix):
    from app.tools import claude_tools

    app, adapters = command_app

    started = asyncio.Event()
    closed = asyncio.Event()
    resumed = []

    async def skill(_skill, args, *, resume_session_id=None, on_session_id=None):
        resumed.append(resume_session_id)
        if on_session_id:
            on_session_id("isolated-session")
        if args == "short":
            yield claude_tools.CommandOutput(content="SHORT_RESULT")
            return
        if resume_session_id:
            yield claude_tools.CommandOutput(content="RESUMED_RESULT")
            return
        yield claude_tools.CommandOutput(content="STARTED")
        started.set()
        try:
            await asyncio.Event().wait()
        finally:
            closed.set()

    adapters["claude"] = skill
    short_c_id = f"module-{command}-short"
    long_c_id = f"module-{command}-long"
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app),
        base_url="http://test",
    ) as client:
        short = await client.post(
            "/v1/chat/completions",
            json={
                "c_id": short_c_id,
                "request_id": short_c_id,
                "messages": [{"role": "user", "content": f"/{command} {prefix}short"}],
            },
        )
        assert short.status_code == 200
        assert "SHORT_RESULT" in short.text

        running = asyncio.create_task(
            client.post(
                "/v1/chat/completions",
                json={
                    "c_id": long_c_id,
                    "request_id": long_c_id,
                    "messages": [{"role": "user", "content": f"/{command} {prefix}long"}],
                },
            )
        )
        try:
            await asyncio.wait_for(started.wait(), 3)
            interrupt = await client.post("/v1/chat/interrupt", json={"c_id": long_c_id})
            assert interrupt.json() == {"interrupted": True, "mode": "hard_cancel"}
            await asyncio.wait_for(closed.wait(), 3)
            await asyncio.gather(running, return_exceptions=True)
            continuation = await client.post(
                "/v1/chat/completions",
                json={
                    "c_id": long_c_id,
                    "request_id": f"module-{command}-resume",
                    "messages": [{"role": "user", "content": "继续"}],
                },
            )
            assert continuation.status_code == 200
            assert "RESUMED_RESULT" in continuation.text
            assert resumed[-1] == "isolated-session"
        finally:
            running.cancel()
            await asyncio.gather(running, return_exceptions=True)


@pytest.mark.asyncio
async def test_torch_http_short_interrupt_and_continue(command_app):
    app, adapters = command_app
    started = asyncio.Event()
    closed = asyncio.Event()
    calls = []

    async def torch(prompt, *, thread_id=None, dashboard_continuation=False, **_kwargs):
        calls.append((prompt, thread_id, dashboard_continuation))
        if prompt == "short":
            yield "SHORT_RESULT"
        elif dashboard_continuation:
            yield "RESUMED_RESULT"
        else:
            yield "STARTED"
            started.set()
            try:
                await asyncio.Event().wait()
            finally:
                closed.set()

    adapters["torch"] = torch
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app),
        base_url="http://test",
    ) as client:
        short = await client.post(
            "/v1/chat/completions",
            json={
                "c_id": "module-torch-short",
                "request_id": "module-torch-short",
                "messages": [{"role": "user", "content": "/torch short"}],
            },
        )
        assert short.status_code == 200
        assert "SHORT_RESULT" in short.text

        running = asyncio.create_task(
            client.post(
                "/v1/chat/completions",
                json={
                    "c_id": "module-torch-long",
                    "request_id": "module-torch-long",
                    "messages": [{"role": "user", "content": "/torch long"}],
                },
            )
        )
        try:
            await asyncio.wait_for(started.wait(), 3)
            interrupt = await client.post("/v1/chat/interrupt", json={"c_id": "module-torch-long"})
            assert interrupt.json() == {"interrupted": True, "mode": "hard_cancel"}
            await asyncio.wait_for(closed.wait(), 3)
            await asyncio.gather(running, return_exceptions=True)
            continuation = await client.post(
                "/v1/chat/completions",
                json={
                    "c_id": "module-torch-long",
                    "request_id": "module-torch-resume",
                    "messages": [{"role": "user", "content": "继续"}],
                },
            )
            assert continuation.status_code == 200
            assert "RESUMED_RESULT" in continuation.text
            assert calls[-1] == ("继续", "module-torch-long", True)
        finally:
            running.cancel()
            await asyncio.gather(running, return_exceptions=True)


@pytest.mark.asyncio
@pytest.mark.parametrize("command,prompt", [("search", "models"), ("doc", "vllm")])
async def test_sync_command_http_short_and_interrupt(command_app, monkeypatch, command, prompt):
    from app.services.direct_command_sessions import direct_command_sessions
    from commands.registry import cmd_registry

    app, adapters = command_app
    assert cmd_registry.get(command).supports_continuation is True
    started = threading.Event()
    release = threading.Event()
    finished = threading.Event()
    interrupted = asyncio.Event()
    call_count = 0
    reporters = {}

    def report_command(_command, _args, c_id="", **_kwargs):
        reporter = MagicMock()
        if c_id == f"module-{command}-long":
            reporter.finish.side_effect = lambda *a, **kw: interrupted.set()
        reporters[c_id] = reporter
        return reporter

    monkeypatch.setattr("app.services.command_dashboard.report_command", report_command)

    def invoke(payload):
        nonlocal call_count
        call_count += 1
        if isinstance(payload, dict) and payload.get("input") == "short":
            return "SHORT_RESULT"
        if command == "doc" and call_count == 1:
            return "SHORT_RESULT"
        if call_count > 2:
            return "FOLLOWUP_RESULT"
        started.set()
        try:
            release.wait(10)
            return "LONG_RESULT"
        finally:
            finished.set()

    adapters[command] = invoke
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app),
        base_url="http://test",
    ) as client:
        short = await client.post(
            "/v1/chat/completions",
            json={
                "c_id": f"module-{command}-short",
                "request_id": f"module-{command}-short",
                "messages": [{"role": "user", "content": f"/{command} {('short' if command == 'search' else prompt)}"}],
            },
        )
        assert short.status_code == 200
        assert "SHORT_RESULT" in short.text
        assert direct_command_sessions.get_for_continuation(
            f"module-{command}-short", "继续",
        ) is None

        running = asyncio.create_task(
            client.post(
                "/v1/chat/completions",
                json={
                    "c_id": f"module-{command}-long",
                    "request_id": f"module-{command}-long",
                    "messages": [{"role": "user", "content": f"/{command} {prompt}"}],
                },
            )
        )
        try:
            assert await asyncio.to_thread(started.wait, 3)
            interrupt = await client.post("/v1/chat/interrupt", json={"c_id": f"module-{command}-long"})
            assert interrupt.json() == {"interrupted": True, "mode": "hard_cancel"}
            await asyncio.wait_for(interrupted.wait(), 3)
            reporters[f"module-{command}-long"].finish.assert_called_once()
            completed, = await asyncio.wait_for(
                asyncio.gather(running, return_exceptions=True), 3,
            )
            if isinstance(completed, httpx.Response):
                assert "LONG_RESULT" not in _chat_content(completed)
            assert not finished.is_set()
            assert direct_command_sessions.is_in_flight(f"module-{command}-long")
            for index, message in enumerate((f"/{command} {prompt}", "继续")):
                busy = await client.post(
                    "/v1/chat/completions",
                    json={
                        "c_id": f"module-{command}-long",
                        "request_id": f"module-{command}-busy-{index}",
                        "messages": [{"role": "user", "content": message}],
                    },
                )
                assert busy.status_code == 200
                assert "在执行" in _chat_content(busy)
                assert "已中断" not in _chat_content(busy)
            assert call_count == 2
            release.set()
            assert await asyncio.to_thread(finished.wait, 3)
            await _wait_until(lambda: not direct_command_sessions.is_in_flight(f"module-{command}-long"))
            assert not direct_command_sessions.is_in_flight(f"module-{command}-long")
            assert direct_command_sessions.get_for_continuation(
                f"module-{command}-long", "继续",
            ) is not None

            continuation = await client.post(
                "/v1/chat/completions",
                json={
                    "c_id": f"module-{command}-long",
                    "request_id": f"module-{command}-resume",
                    "messages": [{"role": "user", "content": "继续"}],
                },
            )
            assert continuation.status_code == 200
            assert "LONG_RESULT" in _chat_content(continuation)
            assert call_count == 2
            assert direct_command_sessions.get_for_continuation(
                f"module-{command}-long", "继续",
            ) is None

            followup = await client.post(
                "/v1/chat/completions",
                json={
                    "c_id": f"module-{command}-long",
                    "request_id": f"module-{command}-followup",
                    "messages": [{"role": "user", "content": f"/{command} {prompt}"}],
                },
            )
            assert followup.status_code == 200
            assert "FOLLOWUP_RESULT" in followup.text
            assert call_count == 3
            assert direct_command_sessions.get_for_continuation(
                f"module-{command}-long", "继续",
            ) is None
        finally:
            release.set()
            await asyncio.to_thread(finished.wait, 5)
            running.cancel()
            await asyncio.gather(running, return_exceptions=True)


@pytest.mark.asyncio
async def test_workflow_http_short_task_completes(command_app, monkeypatch):
    from app.tools.workflow import brainstorming
    from app.tools.workflow.types import StepType, WorkflowPlan, WorkflowStep

    app, adapters = command_app
    plan = WorkflowPlan(
        workflow_id="module-workflow-short",
        intent="short task",
        steps=[WorkflowStep(id="work", type=StepType.LLM_TOOL, name="Work")],
    )
    adapters["workflow_plan"] = lambda _args: plan
    monkeypatch.setattr(brainstorming, "assess_ambiguity", AsyncMock(return_value=(0, [])))
    monkeypatch.setattr(
        "app.tools.workflow.executor.execute_step_with_pattern",
        AsyncMock(return_value="SHORT_RESULT"),
    )
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app),
        base_url="http://test",
    ) as client:
        response = await client.post(
            "/v1/chat/completions",
            json={
                "c_id": "module-workflow-short",
                "request_id": "module-workflow-short",
                "messages": [{"role": "user", "content": "/workflow short task"}],
            },
        )

    assert response.status_code == 200
    assert "SHORT_RESULT" in response.text
    assert plan.is_complete()


@pytest.mark.asyncio
async def test_torch_helper_worker_blocks_reentry_after_http_interrupt(
    command_app,
    monkeypatch,
    tmp_path,
):
    from app.services.direct_command_sessions import direct_command_sessions
    from app.tools import pta_tools

    app, adapters = command_app
    adapters["torch"] = adapters["torch_actual"]
    monkeypatch.setattr(pta_tools, "_PTA_HELPER_ROOT", tmp_path)
    monkeypatch.setattr(pta_tools, "_ensure_pta_helper_in_path", lambda: None)
    started = threading.Event()
    release = threading.Event()
    finished = threading.Event()
    interrupted = asyncio.Event()
    reporter = MagicMock()
    reporter.finish.side_effect = lambda *a, **kw: interrupted.set()
    calls = []

    def helper(_prompt, *, memory, session_id, on_text, on_step=None):
        calls.append(_prompt)
        if len(calls) > 1:
            on_text("RESUMED_RESULT")
            return
        on_text("STARTED")
        started.set()
        try:
            release.wait(10)
            on_text("LATE_OUTPUT")
            if on_step:
                on_step("late step", 1.0, "late detail")
        finally:
            finished.set()

    monkeypatch.setattr(pta_tools, "_load_pta_helper", lambda: helper)
    monkeypatch.setattr("app.services.command_dashboard.report_command", lambda *a, **kw: reporter)
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app),
        base_url="http://test",
    ) as client:
        running = asyncio.create_task(
            client.post(
                "/v1/chat/completions",
                json={
                    "c_id": "module-torch-worker",
                    "request_id": "module-torch-worker",
                    "messages": [{"role": "user", "content": "/torch long"}],
                },
            )
        )
        try:
            assert await asyncio.to_thread(started.wait, 3)
            interrupt = await client.post("/v1/chat/interrupt", json={"c_id": "module-torch-worker"})
            assert interrupt.json() == {"interrupted": True, "mode": "hard_cancel"}
            await asyncio.wait_for(interrupted.wait(), 3)
            reporter.finish.assert_called_once_with("用户中断")
            completed, = await asyncio.wait_for(
                asyncio.gather(running, return_exceptions=True), 3,
            )
            if isinstance(completed, httpx.Response):
                assert "LATE_OUTPUT" not in _chat_content(completed)
            assert not finished.is_set()
            assert direct_command_sessions.is_in_flight("module-torch-worker")
            busy = await client.post(
                "/v1/chat/completions",
                json={
                    "c_id": "module-torch-worker",
                    "request_id": "module-torch-worker-busy",
                    "messages": [{"role": "user", "content": "继续"}],
                },
            )
            assert busy.status_code == 200
            assert "在执行" in _chat_content(busy)
            assert len(calls) == 1

            release.set()
            assert await asyncio.to_thread(finished.wait, 3)
            await _wait_until(lambda: not direct_command_sessions.is_in_flight("module-torch-worker"))
            assert not direct_command_sessions.is_in_flight("module-torch-worker")
            reporter.on_output.assert_called_once_with("STARTED")

            continuation = await client.post(
                "/v1/chat/completions",
                json={
                    "c_id": "module-torch-worker",
                    "request_id": "module-torch-worker-resume",
                    "messages": [{"role": "user", "content": "继续"}],
                },
            )
            assert continuation.status_code == 200
            assert "RESUMED_RESULT" in continuation.text
            assert len(calls) == 2
        finally:
            release.set()
            await asyncio.to_thread(finished.wait, 5)
            running.cancel()
            await asyncio.gather(running, return_exceptions=True)


@pytest.mark.asyncio
async def test_workflow_http_long_interrupt_and_checkpoint_resume(
    command_app,
    monkeypatch,
    tmp_path,
):
    from app.model_agent.dashboard.config import DashboardConfig
    from app.model_agent.dashboard.server import DashboardServer
    from app.services.dashboard_bridge import DashboardBridge
    from app.tools.workflow.checkpointer import Checkpointer
    from app.tools.workflow.types import StepStatus, StepType, WorkflowPlan, WorkflowStep

    app, adapters = command_app
    plan = WorkflowPlan(
        workflow_id="module-workflow-long",
        intent="long task",
        steps=[
            WorkflowStep(id="first", type=StepType.LLM_TOOL, name="First"),
            WorkflowStep(id="active", type=StepType.LLM_TOOL, name="Active", depends_on=["first"]),
            WorkflowStep(id="later", type=StepType.LLM_TOOL, name="Later", depends_on=["active"]),
        ],
    )
    adapters["workflow_plan"] = lambda _args: plan
    monkeypatch.setattr(
        "app.tools.workflow.brainstorming.assess_ambiguity",
        AsyncMock(return_value=(0, [])),
    )
    server = DashboardServer(DashboardConfig(history_dir=str(tmp_path / "dashboard")))

    def use_server(bridge):
        bridge._server = server
        return True

    monkeypatch.setattr(DashboardBridge, "_server_ready", use_server)
    started = asyncio.Event()
    release = asyncio.Event()
    executed = []

    async def execute(step, _ctx, _plan, progress_callback=None):
        executed.append(step.id)
        if step.id == "active":
            started.set()
            await release.wait()
        return f"result-{step.id}"

    monkeypatch.setattr("app.tools.workflow.executor.execute_step_with_pattern", execute)
    async with httpx.AsyncClient(
        transport=httpx.ASGITransport(app=app),
        base_url="http://test",
    ) as client:
        running = asyncio.create_task(
            client.post(
                "/v1/chat/completions",
                json={
                    "c_id": "module-workflow-long",
                    "request_id": "module-workflow-long",
                    "messages": [{"role": "user", "content": "/workflow long task"}],
                },
            )
        )
        try:
            await asyncio.wait_for(started.wait(), 3)
            interrupt = await client.post("/v1/chat/interrupt", json={"c_id": "module-workflow-long"})
            assert interrupt.json() == {"interrupted": True, "mode": "collaborative"}
            assert not running.done()
            release.set()
            initial = await asyncio.wait_for(running, 5)
            assert initial.status_code == 200
            assert executed == ["first", "active"]

            checkpoint = Checkpointer(tmp_path)
            saved_plan, saved_ctx = await checkpoint.load(plan.workflow_id)
            assert [step.status for step in saved_plan.steps] == [
                StepStatus.COMPLETED,
                StepStatus.COMPLETED,
                StepStatus.PENDING,
            ]
            assert saved_ctx.step_results == {
                "first": "result-first",
                "active": "result-active",
            }
            assert server.get_run(plan.workflow_id)["final_status"] == "interrupted"
            assert [node.get("status") for node in server.get_run(plan.workflow_id)["nodes"]] == [
                "success",
                "success",
                None,
            ]

            continuation = await client.post(
                "/v1/chat/completions",
                json={
                    "c_id": "module-workflow-long",
                    "request_id": "module-workflow-resume",
                    "messages": [{"role": "user", "content": "继续"}],
                },
            )
            assert continuation.status_code == 200
            assert "已恢复执行完毕" in continuation.text
            assert executed == ["first", "active", "later"]
            assert server.get_run(plan.workflow_id)["final_status"] == "success"
            assert [node["status"] for node in server.get_run(plan.workflow_id)["nodes"]] == [
                "success",
                "success",
                "success",
            ]
        finally:
            release.set()
            running.cancel()
            await asyncio.gather(running, return_exceptions=True)