Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(web): avoid blocking config saves on agent reload

zhengkailancef62cb1d785
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index 43a0542c2f..8570e2e31f 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -746,6 +746,12 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
return ref.get(key)
return ref
+ def _schedule_clear_agent_config_cache(name: str) -> None:
+ asyncio.create_task(
+ _clear_agent_config_cache(_resolve(agent_client)),
+ name=f"{name}.clear_agent_config_cache",
+ )
+
def _resolve_env_vars(value: Any) -> Any:
"""Recursively resolve environment variables in config values."""
if isinstance(value, str):
@@ -1858,12 +1864,17 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
# 检查通过后再保存配置
await hb.set_heartbeat_conf(every=every, target=target, active_hours=active_hours)
payload = dict(hb.get_heartbeat_conf())
+ should_clear_agent_config_cache = False
try:
update_heartbeat_in_config(payload)
- await _clear_agent_config_cache(_resolve(agent_client))
+ should_clear_agent_config_cache = True
except Exception as e: # noqa: BLE001
logger.warning("[heartbeat.set_conf] 写回 config.yaml 失败: %s", e)
- await channel.send_response(ws, req_id, ok=True, payload=payload)
+ try:
+ await channel.send_response(ws, req_id, ok=True, payload=payload)
+ finally:
+ if should_clear_agent_config_cache:
+ _schedule_clear_agent_config_cache("heartbeat.set_conf")
except ValueError as e:
await channel.send_response(ws, req_id, ok=False, error=str(e), code="BAD_REQUEST")
except Exception as e:
@@ -1933,12 +1944,17 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
try:
await cm.set_conf("feishu", params)
conf = cm.get_conf("feishu")
+ should_clear_agent_config_cache = False
try:
update_channel_in_config("feishu", conf)
- await _clear_agent_config_cache(_resolve(agent_client))
+ should_clear_agent_config_cache = True
except Exception as e: # noqa: BLE001
logger.warning("[channel.feishu.set_conf] 写回 config.yaml 失败: %s", e)
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ try:
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ finally:
+ if should_clear_agent_config_cache:
+ _schedule_clear_agent_config_cache("channel.feishu.set_conf")
except Exception as e: # noqa: BLE001
logger.exception("[channel.feishu.set_conf] %s", e)
await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
@@ -2090,12 +2106,17 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
try:
await cm.set_conf("dingtalk", params)
conf = cm.get_conf("dingtalk")
+ should_clear_agent_config_cache = False
try:
update_channel_in_config("dingtalk", conf)
- await _clear_agent_config_cache(_resolve(agent_client))
+ should_clear_agent_config_cache = True
except Exception as e: # noqa: BLE001
logger.warning("[channel.dingtalk.set_conf] 写回 config.yaml 失败: %s", e)
- await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ try:
+ await channel.send_response(ws, req_id, ok=True, payload={"config": conf})
+ finally:
+ if should_clear_agent_config_cache:
+ _schedule_clear_agent_config_cache("channel.dingtalk.set_conf")
except Exception as e: # noqa: BLE001
logger.exception("[channel.dingtalk.set_conf] %s", e)
await channel.send_response(ws, req_id, ok=False, error=str(e), code="INTERNAL_ERROR")
diff --git a/tests/unit_tests/test_app_web_handlers.py b/tests/unit_tests/test_app_web_handlers.py
index cde6096d56..1d8bee3b90 100644
--- a/tests/unit_tests/test_app_web_handlers.py
+++ b/tests/unit_tests/test_app_web_handlers.py
@@ -1,5 +1,7 @@
# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+import asyncio
+
import pytest
from jiuwenswarm.gateway.channel_manager.web.app_web_handlers import (
@@ -34,6 +36,95 @@ class FakeWebChannel:
)
+class FakeAgentClient:
+ def __init__(self):
+ self.reload_started = asyncio.Event()
+ self.release_reload = asyncio.Event()
+ self.reload_finished = asyncio.Event()
+
+ async def send_request(self, envelope):
+ self.reload_started.set()
+ try:
+ await self.release_reload.wait()
+ return type("Resp", (), {"ok": True, "payload": {}})()
+ finally:
+ self.reload_finished.set()
+
+
+class FakeChannelManager:
+ def __init__(self):
+ self.configs: dict[str, dict] = {}
+
+ async def set_conf(self, channel_id, new_conf):
+ self.configs[channel_id] = dict(new_conf)
+
+ def get_conf(self, channel_id):
+ return dict(self.configs.get(channel_id, {}))
+
+
+class FakeHeartbeatService:
+ def __init__(self):
+ self.config = {"every": 60.0, "target": "web"}
+
+ async def set_heartbeat_conf(self, *, every=None, target=None, active_hours=None):
+ if every is not None:
+ self.config["every"] = every
+ if target is not None:
+ self.config["target"] = target
+ if active_hours is not None:
+ self.config["active_hours"] = active_hours
+
+ def get_heartbeat_conf(self):
+ return dict(self.config)
+
+
+ ("method", "params"),
+ [
+ ("channel.feishu.set_conf", {"enabled": False, "app_id": "app-1"}),
+ ("channel.dingtalk.set_conf", {"enabled": False, "client_id": "client-1"}),
+ ("heartbeat.set_conf", {"every": 30, "target": "web"}),
+ ],
+)
+async def test_config_save_handlers_respond_before_agent_reload_finishes(monkeypatch, method, params):
+ channel = FakeWebChannel()
+ agent_client = FakeAgentClient()
+ channel_manager = FakeChannelManager()
+ heartbeat_service = FakeHeartbeatService()
+ persisted: list[tuple[str, dict]] = []
+
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.channel_manager.web.app_web_handlers.update_channel_in_config",
+ lambda channel_id, conf: persisted.append((channel_id, dict(conf))),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.channel_manager.web.app_web_handlers.update_heartbeat_in_config",
+ lambda payload: persisted.append(("heartbeat", dict(payload))),
+ )
+
+ _register_web_handlers(
+ WebHandlersBindParams(
+ channel=channel,
+ agent_client=agent_client,
+ channel_manager=channel_manager,
+ heartbeat_service=heartbeat_service,
+ )
+ )
+
+ task = asyncio.create_task(channel.methods[method](object(), "req-save", params, "sess-1"))
+ try:
+ await asyncio.wait_for(agent_client.reload_started.wait(), timeout=0.5)
+
+ assert persisted
+ assert channel.responses[-1]["id"] == "req-save"
+ assert channel.responses[-1]["ok"] is True
+ finally:
+ agent_client.release_reload.set()
+ await task
+ await asyncio.wait_for(agent_client.reload_finished.wait(), timeout=0.5)
+
+
@pytest.mark.asyncio
async def test_config_set_routes_team_payload_to_modes_team_helper(monkeypatch):
channel = FakeWebChannel()