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(xiaoyi): persist push_id for cron notifications

NickFuryXXXaa32ded9f242
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index 212918415d..1511cdb038 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -13,7 +13,7 @@ from pathlib import Path
from typing import Any, Optional
from ruamel.yaml import YAML
-from ruamel.yaml.scalarstring import DoubleQuotedScalarString
+from ruamel.yaml.scalarstring import DoubleQuotedScalarString, PlainScalarString
import yaml
import portalocker
@@ -381,6 +381,67 @@ def update_channel_in_config(channel_id: str, conf: dict[str, Any]) -> None:
dump_yaml_round_trip(CONFIG_YAML_PATH, data)
+def _as_plain_yaml_str(value: Any) -> Any:
+ """字符串写成无引号 plain scalar,避免顶层/apps 因旧值风格(如 ``''``)不一致。"""
+ if isinstance(value, str):
+ return PlainScalarString(value)
+ return value
+
+
+def update_xiaoyi_runtime_in_config(
+ conf: dict[str, Any],
+ *,
+ api_id: str = "",
+ agent_id: str = "",
+) -> None:
+ """更新 ``channels.xiaoyi`` 运行时身份,并在存在 ``push_id`` 时同步写入 ``apps[]``。
+
+ 顶层字段(``last_session_id`` / ``last_task_id`` / ``push_id`` 等)供 cron 等读;
+ ``apps[].push_id`` 供频道重启后 ``XiaoyiChannelConfig`` 加载。一次 IO 写完,避免不一致。
+
+ ``apps`` 匹配优先级:``api_id`` → ``agent_id`` → ``is_default`` → 唯一 app。
+ """
+ data = load_yaml_round_trip(CONFIG_YAML_PATH)
+ if "channels" not in data:
+ data["channels"] = {}
+ channels = data["channels"]
+ if "xiaoyi" not in channels or not isinstance(channels["xiaoyi"], dict):
+ channels["xiaoyi"] = {}
+ section = channels["xiaoyi"]
+ for k, v in conf.items():
+ section[k] = _as_plain_yaml_str(v)
+
+ push_id = conf.get("push_id")
+ if push_id:
+ plain_push_id = _as_plain_yaml_str(str(push_id))
+ apps = section.get("apps")
+ if isinstance(apps, list) and apps:
+ target: dict[str, Any] | None = None
+ api_id = str(api_id or "").strip()
+ agent_id = str(agent_id or "").strip()
+ if api_id:
+ for app in apps:
+ if isinstance(app, dict) and str(app.get("api_id") or "").strip() == api_id:
+ target = app
+ break
+ if target is None and agent_id:
+ for app in apps:
+ if isinstance(app, dict) and str(app.get("agent_id") or "").strip() == agent_id:
+ target = app
+ break
+ if target is None:
+ for app in apps:
+ if isinstance(app, dict) and app.get("is_default", False):
+ target = app
+ break
+ if target is None and len(apps) == 1 and isinstance(apps[0], dict):
+ target = apps[0]
+ if target is not None:
+ target["push_id"] = plain_push_id
+
+ dump_yaml_round_trip(CONFIG_YAML_PATH, data)
+
+
def update_channel_subsection_in_config(
channel_id: str,
subsection_id: str,
diff --git a/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_connect.py b/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_connect.py
index 1920da68d2..1a79c1c1a9 100644
--- a/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_connect.py
+++ b/jiuwenswarm/gateway/channel_manager/im_platforms/xiaoyi/xiaoyi_connect.py
@@ -1296,7 +1296,7 @@ class XiaoyiChannel(BaseChannel):
# 将最近一次可回发的小艺身份写入 config.yaml,供 cron 推送时使用
try:
- from jiuwenswarm.common.config import update_channel_in_config
+ from jiuwenswarm.common.config import update_xiaoyi_runtime_in_config
rpc_id = message.get("id")
conf_update: dict[str, Any] = {
@@ -1304,10 +1304,14 @@ class XiaoyiChannel(BaseChannel):
"last_task_id": task_id or "",
"last_message_id": str(rpc_id) if rpc_id is not None else "",
}
- # V2: 首次收到非空 push_id 时持久化(webhook 推送 token,供 cron 推送兜底)
+ # V2: 收到非空 push_id 时同时写入顶层与 apps[].push_id(webhook 推送 token)
if push_id:
conf_update["push_id"] = push_id
- update_channel_in_config("xiaoyi", conf_update)
+ update_xiaoyi_runtime_in_config(
+ conf_update,
+ api_id=self.config.api_id,
+ agent_id=self.config.agent_id,
+ )
except Exception as config_error:
logger.warning(f"XiaoyiChannel 更新配置失败: {config_error}")
diff --git a/tests/unit_tests/test_config.py b/tests/unit_tests/test_config.py
index 2599b641bf..ae82d7cee3 100644
--- a/tests/unit_tests/test_config.py
+++ b/tests/unit_tests/test_config.py
@@ -19,6 +19,7 @@ from jiuwenswarm.common.config import (
replace_teams_in_config,
resolve_env_vars,
update_skill_retrieval_in_config,
+ update_xiaoyi_runtime_in_config,
)
@@ -767,3 +768,112 @@ modes:
raw = yaml.safe_load(temp_config_file.read_text(encoding="utf-8"))
assert "team" not in raw["modes"]
+
+
+class TestUpdateXiaoyiRuntimeInConfig:
+ """push_id 需同时写入顶层与 apps[],供 cron 与频道重启共用。"""
+
+ @staticmethod
+ def test_writes_top_level_and_matching_app_push_id(
+ monkeypatch: pytest.MonkeyPatch,
+ temp_config_file: Path,
+ ):
+ temp_config_file.write_text(
+ """
+channels:
+ xiaoyi:
+ apps:
+ - name: 默认应用
+ is_default: true
+ api_id: webhook_api_1
+ agent_id: agent_abc
+ push_id: ""
+ - name: 其他
+ api_id: webhook_api_2
+ agent_id: agent_other
+ push_id: ""
+""",
+ encoding="utf-8",
+ )
+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", temp_config_file)
+
+ update_xiaoyi_runtime_in_config(
+ {
+ "last_session_id": "sess-1",
+ "last_task_id": "task-1",
+ "last_message_id": "msg-1",
+ "push_id": "push-token-xyz",
+ },
+ api_id="webhook_api_1",
+ agent_id="agent_abc",
+ )
+
+ raw = yaml.safe_load(temp_config_file.read_text(encoding="utf-8"))
+ xy = raw["channels"]["xiaoyi"]
+ assert xy["push_id"] == "push-token-xyz"
+ assert xy["last_session_id"] == "sess-1"
+ assert xy["apps"][0]["push_id"] == "push-token-xyz"
+ assert xy["apps"][1]["push_id"] == ""
+
+ @staticmethod
+ def test_without_push_id_does_not_touch_apps(
+ monkeypatch: pytest.MonkeyPatch,
+ temp_config_file: Path,
+ ):
+ temp_config_file.write_text(
+ """
+channels:
+ xiaoyi:
+ apps:
+ - name: 默认应用
+ is_default: true
+ api_id: webhook_api_1
+ push_id: keep-me
+""",
+ encoding="utf-8",
+ )
+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", temp_config_file)
+
+ update_xiaoyi_runtime_in_config(
+ {"last_session_id": "sess-2"},
+ api_id="webhook_api_1",
+ )
+
+ raw = yaml.safe_load(temp_config_file.read_text(encoding="utf-8"))
+ xy = raw["channels"]["xiaoyi"]
+ assert xy["last_session_id"] == "sess-2"
+ assert "push_id" not in xy
+ assert xy["apps"][0]["push_id"] == "keep-me"
+
+ @staticmethod
+ def test_push_id_dumped_without_quotes_even_if_old_app_value_quoted(
+ monkeypatch: pytest.MonkeyPatch,
+ temp_config_file: Path,
+ ):
+ # apps 旧值为单引号空串时,覆盖后顶层与 apps 均应无引号
+ temp_config_file.write_text(
+ """
+channels:
+ xiaoyi:
+ apps:
+ - name: 默认应用
+ is_default: true
+ api_id: webhook_api_1
+ agent_id: agent_abc
+ push_id: ''
+""",
+ encoding="utf-8",
+ )
+ monkeypatch.setattr("jiuwenswarm.common.config.CONFIG_YAML_PATH", temp_config_file)
+
+ token = "88062548d4436ba6b6bfb573c641ad5d2a3f10a649dae5f52ad6f31f851cad64"
+ update_xiaoyi_runtime_in_config(
+ {"push_id": token},
+ api_id="webhook_api_1",
+ agent_id="agent_abc",
+ )
+
+ text = temp_config_file.read_text(encoding="utf-8")
+ assert f"push_id: {token}" in text
+ assert f"push_id: '{token}'" not in text
+ assert f'push_id: "{token}"' not in text