from threading import Event from time import monotonic, sleep from mulit_agent_app.application.agent_service import AgentService from mulit_agent_app.config import AgentConfig def _config(tmp_path) -> AgentConfig: data = tmp_path / "agent" return AgentConfig(data, data / "settings.json", data / "agent.sqlite3", data / "agent.log", agent_name="restart-test") def test_duplicate_restart_requests_start_only_one_replacement_and_cancel_work(tmp_path): started, old_exited = [], Event() service = AgentService(_config(tmp_path), restart_process=lambda: started.append("replacement") or True, on_restarted=old_exited.set) service.task_executor.submit("restart-task", "应因 Agent 重启中止") service.restart("restart-1") service.restart("restart-1") assert old_exited.wait(2) assert started == ["replacement"] assert service.task_executor._database.task_status("restart-task") == "cancelled" def test_restart_failure_does_not_exit_old_agent_or_start_another_process(tmp_path): old_exited = Event() service = AgentService(_config(tmp_path), restart_process=lambda: False, on_restarted=old_exited.set) service.restart("restart-fail") deadline = monotonic() + 2 while service._restart_request_id and monotonic() < deadline: sleep(0.01) assert not old_exited.is_set() assert service._restart_request_id == ""