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): 企业会话历史改存 MySQL 库 web,避免删 Pod 丢记录
zhangxiangyu520231dd68256e
diff --git a/.env.example b/.env.exampleindex 49b37d5ade..680d35d3e6 100644--- a/.env.example+++ b/.env.example@@ -42,6 +42,16 @@ GATEWAY_DB_USER=rootGATEWAY_DB_PASSWORD=rootGATEWAY_DB_NAME=gateway+# Web database: sqlite | mysql(当前用于会话历史;sqlite 路径可复用给 Web 其它本地库)+# Enterprise (active-standby / distributed) should use mysql + WEB_DB_HOST+WEB_DB_TYPE=sqlite+WEB_SQLITE_PATH=web.db+WEB_DB_HOST=127.0.0.1+WEB_DB_PORT=3306+WEB_DB_USER=root+WEB_DB_PASSWORD=root+WEB_DB_NAME=web+# Gateway / AgentServer 访问 MySQL、PostgreSQL 时的 SQLAlchemy 连接池参数(企业 checkpoint 复用)# 单池峰值连接数 ≈ GATEWAY_DB_POOL_SIZE + GATEWAY_DB_MAX_OVERFLOWGATEWAY_DB_POOL_SIZE=2diff --git a/deploy/enterprise/.env.example b/deploy/enterprise/.env.exampleindex 766610d8a8..40ab595555 100644--- a/deploy/enterprise/.env.example+++ b/deploy/enterprise/.env.example@@ -76,12 +76,15 @@ NFS_SC_NAME=""DB_HOST="" # 外部数据服务的连接地址, 不设置则使用本工具内置部署的数据库服务DB_PORT="" # 数据服务的连接端口(本工具内置部署的数据库服务时设置端口,外部数据库服务填写对应端口)MANAGER_DB_NAME="" # Manager 业务模块对应的数据库实例名称,未设置则使用默认值"manager"-GATEWAY_DB_NAME="" # Gateway 网关服务对应的数据库实例名称,未设置则使用默认值"gateway”+GATEWAY_DB_NAME="" # Gateway 网关服务对应的数据库实例名称,未设置则使用默认值"gateway"+WEB_DB_NAME="" # 企业 Web 会话历史库名称,未设置则使用默认值"web"# 仅 DB_TYPE 取值为 postgresql / mysql 且使用外部独立数据库服务时,本段账号配置生效,账号权限区分规则:-# 1. 分库独立账号配置:分别定义 MANAGER_DB_USER / MANAGER_DB_PASSWORD、GATEWAY_DB_USER / GATEWAY_DB_PASSWORD,实现两个业务库账号、密码完全隔离-# 2. 全局统一账号配置:仅配置 DB_USER、DB_PASSWORD,Manager、Gateway 共用同一套数据库访问凭证+# 1. 分库独立账号配置:分别定义 MANAGER_DB_USER / MANAGER_DB_PASSWORD、GATEWAY_DB_USER / GATEWAY_DB_PASSWORD、WEB_DB_USER / WEB_DB_PASSWORD+# 2. 全局统一账号配置:仅配置 DB_USER、DB_PASSWORD,Manager、Gateway、Web 共用同一套数据库访问凭证+# 地址/端口与 Manager、Gateway 一样使用上面的 DB_HOST / DB_PORT+# 未单独配 WEB_DB_USER/PASSWORD 时,部署脚本回退到全局 DB_USER / DB_PASSWORD(与 Manager/Gateway 相同规则)# 优先级规则:分库专属账号变量优先级 > 全局通用账号变量;若两类变量同时配置,以分库专属账号为准,全局账号配置自动失效DB_USER=""DB_PASSWORD=""@@ -89,6 +92,8 @@ GATEWAY_DB_USER=""GATEWAY_DB_PASSWORD=""MANAGER_DB_USER=""MANAGER_DB_PASSWORD=""+WEB_DB_USER=""+WEB_DB_PASSWORD=""# Gateway / AgentServer 访问 MySQL、PostgreSQL 时的 SQLAlchemy 连接池参数# 会写入 Gateway 环境并通过 Runtime Management 下发给 AgentServer Poddiff --git a/deploy/enterprise/check_handler.sh b/deploy/enterprise/check_handler.shindex 5b70a74cf8..4c1f0379b4 100755--- a/deploy/enterprise/check_handler.sh+++ b/deploy/enterprise/check_handler.sh@@ -216,6 +216,20 @@ check_if_db_up() {if [ -z "${DEPLOY_VARS["GATEWAY_DB_PASSWORD"]:-}" ]; thenerror "Please set up GATEWAY_DB_PASSWORD or DB_PASSWORD."fi++ if [ -z "${DEPLOY_VARS["WEB_DB_USER"]:-}" ]; then+ DEPLOY_VARS["WEB_DB_USER"]=${DEPLOY_VARS["DB_USER"]}+ fi+ if [ -z "${DEPLOY_VARS["WEB_DB_USER"]:-}" ]; then+ error "Please set up WEB_DB_USER or DB_USER."+ fi++ if [ -z "${DEPLOY_VARS["WEB_DB_PASSWORD"]:-}" ]; then+ DEPLOY_VARS["WEB_DB_PASSWORD"]=${DEPLOY_VARS["DB_PASSWORD"]}+ fi+ if [ -z "${DEPLOY_VARS["WEB_DB_PASSWORD"]:-}" ]; then+ error "Please set up WEB_DB_PASSWORD or DB_PASSWORD."+ fifi}diff --git a/deploy/enterprise/configmap_secret_handler.sh b/deploy/enterprise/configmap_secret_handler.shindex 9b1892f046..f58ce95a15 100755--- a/deploy/enterprise/configmap_secret_handler.sh+++ b/deploy/enterprise/configmap_secret_handler.sh@@ -15,6 +15,7 @@ render_secret_configmap() {local secret_keys=("GATEWAY_DB_PASSWORD""MANAGER_DB_PASSWORD"+ "WEB_DB_PASSWORD""REDIS_PASSWORD""OBS_SECRET_KEY""API_KEY"diff --git a/deploy/enterprise/example/configmap-secret.yaml b/deploy/enterprise/example/configmap-secret.yamlindex 46b3ecc0d4..a106a60992 100644--- a/deploy/enterprise/example/configmap-secret.yaml+++ b/deploy/enterprise/example/configmap-secret.yaml@@ -7,6 +7,7 @@ type: Opaquedata:GATEWAY_DB_PASSWORD: "<<DB_PASSWORD 的 Base64 编码值>>"MANAGER_DB_PASSWORD: "<<DB_PASSWORD 的 Base64 编码值>>"+ WEB_DB_PASSWORD: "<<DB_PASSWORD 的 Base64 编码值>>"REDIS_PASSWORD: "<<REDIS_PASSWORD 的 Base64 编码值>>"JIUWENCLAW_MINIO_SECRET_KEY: "<<OBS_SECRET_KEY 的 Base64 编码值>>"API_KEY: "<<API_KEY 的 Base64 编码值>>"diff --git a/deploy/enterprise/example/web.yaml b/deploy/enterprise/example/web.yamlindex ebc2b221a5..05d8c526c2 100644--- a/deploy/enterprise/example/web.yaml+++ b/deploy/enterprise/example/web.yaml@@ -44,6 +44,16 @@ spec:value: ""- name: TZvalue: "Asia/Shanghai"+ - name: WEB_DB_TYPE+ value: "<<DB_TYPE>>"+ - name: WEB_DB_HOST+ value: "<<DB_HOST>>"+ - name: WEB_DB_PORT+ value: "<<DB_PORT>>"+ - name: WEB_DB_USER+ value: "<<WEB_DB_USER>>"+ - name: WEB_DB_NAME+ value: "web"- name: JIUWENCLAW_MINIO_ENDPOINTvalue: <<OBS_URL>>- name: JIUWENCLAW_MINIO_ACCESS_KEYdiff --git a/deploy/enterprise/global_vars.sh b/deploy/enterprise/global_vars.shindex f30a056778..b8af21e197 100755--- a/deploy/enterprise/global_vars.sh+++ b/deploy/enterprise/global_vars.sh@@ -119,6 +119,7 @@ declare -A DEPLOY_VARS=(["TOOL_RESULT_DISPLAY_MAX_CHARS"]="500"["GATEWAY_CONFIG_MAP_NAME"]="jiuwenclaw-gateway-config"["GATEWAY_DB_NAME"]="gateway"+ ["WEB_DB_NAME"]="web"["GATEWAY_DB_MAX_OVERFLOW"]="20"["GATEWAY_DB_POOL_SIZE"]="2"["GATEWAY_DB_POOL_TIMEOUT"]="30"diff --git a/deploy/enterprise/templates/configmap-secret.template.yaml b/deploy/enterprise/templates/configmap-secret.template.yamlindex a24006380a..f03cdea78d 100644--- a/deploy/enterprise/templates/configmap-secret.template.yaml+++ b/deploy/enterprise/templates/configmap-secret.template.yaml@@ -7,6 +7,7 @@ type: Opaquedata:GATEWAY_DB_PASSWORD: "<<GATEWAY_DB_PASSWORD_ENCODED>>"MANAGER_DB_PASSWORD: "<<MANAGER_DB_PASSWORD_ENCODED>>"+ WEB_DB_PASSWORD: "<<WEB_DB_PASSWORD_ENCODED>>"REDIS_PASSWORD: "<<REDIS_PASSWORD_ENCODED>>"JIUWENCLAW_MINIO_SECRET_KEY: "<<OBS_SECRET_KEY_ENCODED>>"API_KEY: "<<API_KEY_ENCODED>>"diff --git a/deploy/enterprise/templates/web.template.yaml b/deploy/enterprise/templates/web.template.yamlindex 5760ce4e9a..81ecb79e98 100644--- a/deploy/enterprise/templates/web.template.yaml+++ b/deploy/enterprise/templates/web.template.yaml@@ -44,6 +44,16 @@ spec:value: "<<WS_ALLOWED_ORIGINS>>"- name: TZvalue: "<<TIMEZONE>>"+ - name: WEB_DB_TYPE+ value: "<<DB_TYPE>>"+ - name: WEB_DB_HOST+ value: "<<DB_HOST>>"+ - name: WEB_DB_PORT+ value: "<<DB_PORT>>"+ - name: WEB_DB_USER+ value: "<<WEB_DB_USER>>"+ - name: WEB_DB_NAME+ value: "<<WEB_DB_NAME>>"---# 集群内部访问: 提供稳定 DNS 域名diff --git a/jiuwenswarm/channels/web/history_store.py b/jiuwenswarm/channels/web/history_store.pyindex 04ed9bd365..86e2a8b435 100644--- a/jiuwenswarm/channels/web/history_store.py+++ b/jiuwenswarm/channels/web/history_store.py@@ -7,12 +7,12 @@- Gateway ``WebChannel`` Listen(无 Pod 时的主路径)存储按库类型分支:-- ``sqlite``:本地 ``web_history.db``(``WEB_HISTORY_SQLITE_PATH`` 可覆盖)+- ``sqlite``:本地 ``web_history.db``(``WEB_SQLITE_PATH`` 可覆盖;兼容旧名 ``WEB_HISTORY_SQLITE_PATH``)- ``mysql``:独立库 ``web``(``WEB_DB_*``);缺 ``WEB_DB_HOST`` 则不可用,不回退 SQLite- ``postgresql`` 等:暂不支持,明确不可用选型与 Gateway ``GATEWAY_DB_TYPE`` 对齐:``WEB_DB_TYPE`` → ``DB_TYPE`` →-已配 ``WEB_DB_HOST`` 则视为 mysql → 默认 sqlite。+已配 ``WEB_DB_HOST`` 则视为 mysql → 按 ``DEPLOYMENT_MODE``(企业主备/分布式 mysql,standalone sqlite)。"""from __future__ import annotations@@ -138,19 +138,29 @@ def _env(*names: str, default: str = "") -> str:def resolve_history_db_type() -> str:"""解析 Web 会话历史库类型。- 优先级:``WEB_DB_TYPE`` → ``DB_TYPE`` → 已配 ``WEB_DB_HOST`` 则 ``mysql`` → 默认 ``sqlite``。+ 优先级:``WEB_DB_TYPE`` → ``DB_TYPE`` → 已配 ``WEB_DB_HOST`` 则 ``mysql`` →+ 按 ``DEPLOYMENT_MODE``(企业主备/分布式 ``mysql``,standalone ``sqlite``)。"""explicit = _env("WEB_DB_TYPE") or _env("DB_TYPE")if explicit:return explicit.strip().lower()if _env("WEB_DB_HOST"):return "mysql"- return "sqlite"+ try:+ from jiuwenswarm.deployment_mode import (+ history_storage_backend,+ normalize_deployment_mode,+ )++ mode = normalize_deployment_mode(os.getenv("DEPLOYMENT_MODE", "standalone"))+ return history_storage_backend(mode)+ except Exception:+ return "sqlite"def default_history_sqlite_path() -> Path:- """SQLite 历史默认路径;``WEB_HISTORY_SQLITE_PATH`` 可覆盖。"""- override = _env("WEB_HISTORY_SQLITE_PATH")+ """SQLite 历史默认路径;``WEB_SQLITE_PATH`` 可覆盖,兼容旧名 ``WEB_HISTORY_SQLITE_PATH``。"""+ override = _env("WEB_SQLITE_PATH", "WEB_HISTORY_SQLITE_PATH")if override:return Path(override).expanduser().resolve()from jiuwenswarm.common.utils import (diff --git a/jiuwenswarm/deployment_mode.py b/jiuwenswarm/deployment_mode.pyindex 887c7c3716..b919cb4f55 100644--- a/jiuwenswarm/deployment_mode.py+++ b/jiuwenswarm/deployment_mode.py@@ -26,6 +26,7 @@ VALID_DEPLOYMENT_MODES: tuple[str, ...] = ()SessionStorageBackend = Literal["local", "redis"]+HistoryStorageBackend = Literal["sqlite", "mysql"]def normalize_deployment_mode(raw: object) -> str:@@ -53,6 +54,20 @@ def session_storage_backend(mode: str) -> SessionStorageBackend:return "local"+def history_storage_backend(mode: str) -> HistoryStorageBackend:+ """Web 会话历史默认存储后端。++ - standalone:本地 SQLite(可无 MySQL)+ - active-standby / distributed:MySQL 独立库 ``web``(删 Pod 不丢历史)++ 实际运行时仍以 ``WEB_DB_TYPE`` / ``WEB_DB_HOST`` 等环境变量优先+ (见 ``resolve_history_db_type``);本函数表达「部署模式推荐默认值」。+ """+ if normalize_deployment_mode(mode) in (MODE_ACTIVE_STANDBY, MODE_DISTRIBUTED):+ return "mysql"+ return "sqlite"++def default_cron_enabled(mode: str) -> bool:"""Cron 默认开关:distributed 默认关闭(多副本无选主,避免重复调度)。"""return normalize_deployment_mode(mode) != MODE_DISTRIBUTEDdiff --git a/pyproject.toml b/pyproject.tomlindex 82f015f991..05c891d357 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -25,6 +25,8 @@ dependencies = ["websockets>=12.0","psutil>=7.2.2","aiosqlite>=0.22.1",+ "pymysql>=1.1.0",+ "cryptography>=42.0.0","asyncpg>=0.29","croniter>=2.0.0","python-telegram-bot>=20.0",diff --git a/tests/unit_tests/gateway/test_deployment_mode.py b/tests/unit_tests/gateway/test_deployment_mode.pyindex c8586b45b3..1cfd9caf63 100644--- a/tests/unit_tests/gateway/test_deployment_mode.py+++ b/tests/unit_tests/gateway/test_deployment_mode.py@@ -13,6 +13,7 @@ from jiuwenswarm.deployment_mode import (channel_config_overlay_default,default_cron_enabled,distributed_channel_whitelist,+ history_storage_backend,normalize_deployment_mode,session_storage_backend,uses_gateway_redis,@@ -66,6 +67,13 @@ def test_session_storage_backend():assert session_storage_backend("bogus") == "local"+def test_history_storage_backend():+ assert history_storage_backend(MODE_STANDALONE) == "sqlite"+ assert history_storage_backend(MODE_ACTIVE_STANDBY) == "mysql"+ assert history_storage_backend(MODE_DISTRIBUTED) == "mysql"+ assert history_storage_backend("bogus") == "sqlite"++def test_default_cron_enabled():assert default_cron_enabled(MODE_STANDALONE)assert default_cron_enabled(MODE_ACTIVE_STANDBY)diff --git a/tests/unit_tests/test_history.py b/tests/unit_tests/test_history.pyindex c3480673e4..54fe28ace5 100644--- a/tests/unit_tests/test_history.py+++ b/tests/unit_tests/test_history.py@@ -10,16 +10,25 @@ from jiuwenswarm.channels.web.history_store import (get_session_detail_sync,list_sessions_sync,make_history_callback,+ resolve_history_db_type,+ set_default_store,)+def _mem_store() -> ChatHistoryStore:+ return ChatHistoryStore.memory()++@pytest.mark.asyncio-async def test_record_user_and_assistant_then_list_detail(tmp_path) -> None:- store = ChatHistoryStore(tmp_path / "h.db")+async def test_record_user_and_assistant_then_list_detail() -> None:+ store = _mem_store()await store.record_user(request_id="r1", session_id="s1", query="你好", ts=1000.0)await store.record_assistant(- request_id="r1", session_id="s1", content="你好,有什么可以帮你?",- event_type="chat.final", ts=1001.0,+ request_id="r1",+ session_id="s1",+ content="你好,有什么可以帮你?",+ event_type="chat.final",+ ts=1001.0,)sessions = await store.list_sessions()assert len(sessions) == 1@@ -35,10 +44,14 @@ async def test_record_user_and_assistant_then_list_detail(tmp_path) -> None:@pytest.mark.asyncio-async def test_record_idempotent_on_resend(tmp_path) -> None:- store = ChatHistoryStore(tmp_path / "h.db")- inserted1 = await store.record_user(request_id="r1", session_id="s1", query="hello", ts=1000.0)- inserted2 = await store.record_user(request_id="r1", session_id="s1", query="hello", ts=1000.0)+async def test_record_idempotent_on_resend() -> None:+ store = _mem_store()+ inserted1 = await store.record_user(+ request_id="r1", session_id="s1", query="hello", ts=1000.0+ )+ inserted2 = await store.record_user(+ request_id="r1", session_id="s1", query="hello", ts=1000.0+ )assert inserted1 is Trueassert inserted2 is Falsesessions = await store.list_sessions()@@ -47,12 +60,17 @@ async def test_record_idempotent_on_resend(tmp_path) -> None:@pytest.mark.asyncio-async def test_title_first_set_not_overwritten(tmp_path) -> None:- store = ChatHistoryStore(tmp_path / "h.db")- await store.record_user(request_id="r1", session_id="s1", query="第一条用户消息", ts=1000.0)+async def test_title_first_set_not_overwritten() -> None:+ store = _mem_store()+ await store.record_user(+ request_id="r1", session_id="s1", query="第一条用户消息", ts=1000.0+ )await store.record_assistant(- request_id="r1", session_id="s1", content="回复内容",- event_type="chat.final", ts=1001.0,+ request_id="r1",+ session_id="s1",+ content="回复内容",+ event_type="chat.final",+ ts=1001.0,)detail = await store.get_session_detail("s1")assert detail is not None@@ -61,20 +79,50 @@ async def test_title_first_set_not_overwritten(tmp_path) -> None:@pytest.mark.asyncio-async def test_callback_whitelist_ignores_non_chat(tmp_path) -> None:- store = ChatHistoryStore(tmp_path / "h.db")+async def test_callback_whitelist_ignores_non_chat() -> None:+ store = _mem_store()cb = make_history_callback(store)- await cb("browser", json.dumps({"type": "req", "id": "x1", "method": "skilldev.start", "params": {"query": "应被忽略"}}))- await cb("browser", json.dumps({"type": "req", "id": "x2", "method": "chat.interrupt", "params": {"query": "应被忽略"}}))+ await cb(+ "browser",+ json.dumps(+ {+ "type": "req",+ "id": "x1",+ "method": "skilldev.start",+ "params": {"query": "应被忽略"},+ }+ ),+ )+ await cb(+ "browser",+ json.dumps(+ {+ "type": "req",+ "id": "x2",+ "method": "chat.interrupt",+ "params": {"query": "应被忽略"},+ }+ ),+ )assert await store.list_sessions() == []await store.close()@pytest.mark.asyncio-async def test_callback_user_with_session_id_records_directly(tmp_path) -> None:- store = ChatHistoryStore(tmp_path / "h.db")+async def test_callback_user_with_session_id_records_directly() -> None:+ store = _mem_store()cb = make_history_callback(store)- await cb("browser", json.dumps({"type": "req", "id": "r1", "method": "chat.send", "params": {"session_id": "s1", "query": "直接落盘"}}))+ await cb(+ "browser",+ json.dumps(+ {+ "type": "req",+ "id": "r1",+ "method": "chat.send",+ "params": {"session_id": "s1", "query": "直接落盘"},+ }+ ),+ )detail = await store.get_session_detail("s1")assert detail is not Noneassert len(detail["messages"]) == 1@@ -82,40 +130,41 @@ async def test_callback_user_with_session_id_records_directly(tmp_path) -> None:@pytest.mark.asyncio-async def test_callback_pending_backfill_on_final(tmp_path) -> None:- store = ChatHistoryStore(tmp_path / "h.db")- cb = make_history_callback(store)- await cb("browser", json.dumps({"type": "req", "id": "r1", "method": "chat.send", "params": {"query": "在吗"}}))- assert await store.list_sessions() == []- # 流式增量 chat.delta 逐帧累积- await cb("uplink", json.dumps({"type": "event", "event": "chat.delta", "request_id": "r1", "payload": {"session_id": "s1", "content": "在"}}))- await cb("uplink", json.dumps({"type": "event", "event": "chat.delta", "request_id": "r1", "payload": {"session_id": "s1", "content": "的"}}))- # chat.final 终止信号,content 为空- await cb("uplink", json.dumps({"type": "event", "event": "chat.final", "request_id": "r1", "payload": {"session_id": "s1", "content": ""}}))- detail = await store.get_session_detail("s1")- assert detail is not None- roles = [m["role"] for m in detail["messages"]]- assert roles == ["user", "assistant"]- assert detail["messages"][1]["content"] == "在的" # delta 累积- await store.close()---async def test_callback_uplink_request_id_in_payload(tmp_path) -> None:- store = ChatHistoryStore(tmp_path / "h.db")+async def test_callback_pending_backfill_on_final() -> None:+ store = _mem_store()cb = make_history_callback(store)await cb("browser",- json.dumps({"type": "req", "id": "r1", "method": "chat.send", "params": {"query": "hi"}}),+ json.dumps(+ {+ "type": "req",+ "id": "r1",+ "method": "chat.send",+ "params": {"query": "在吗"},+ }+ ),)+ assert await store.list_sessions() == []await cb("uplink",json.dumps({"type": "event","event": "chat.delta",- "payload": {"session_id": "s1", "request_id": "r1", "content": "ok"},- },+ "request_id": "r1",+ "payload": {"session_id": "s1", "content": "在"},+ }+ ),+ )+ await cb(+ "uplink",+ json.dumps(+ {+ "type": "event",+ "event": "chat.delta",+ "request_id": "r1",+ "payload": {"session_id": "s1", "content": "的"},+ }),)await cb(@@ -124,31 +173,64 @@ async def test_callback_uplink_request_id_in_payload(tmp_path) -> None:{"type": "event","event": "chat.final",- "payload": {"session_id": "s1", "request_id": "r1", "content": ""},- },+ "request_id": "r1",+ "payload": {"session_id": "s1", "content": ""},+ }),)detail = await store.get_session_detail("s1")assert detail is not None- assert detail["messages"][-1]["content"] == "ok"+ roles = [m["role"] for m in detail["messages"]]+ assert roles == ["user", "assistant"]+ assert detail["messages"][1]["content"] == "在的"await store.close()@pytest.mark.asyncio-async def test_callback_ignores_delta_events(tmp_path) -> None:- store = ChatHistoryStore(tmp_path / "h.db")+async def test_callback_ignores_delta_events() -> None:+ store = _mem_store()cb = make_history_callback(store)- await cb("uplink", json.dumps({"type": "event", "event": "chat.tool_calls.delta", "request_id": "r1", "payload": {"session_id": "s1", "content": "增量"}}))+ await cb(+ "uplink",+ json.dumps(+ {+ "type": "event",+ "event": "chat.tool_calls.delta",+ "request_id": "r1",+ "payload": {"session_id": "s1", "content": "增量"},+ }+ ),+ )assert await store.list_sessions() == []await store.close()@pytest.mark.asyncio-async def test_callback_records_chat_error(tmp_path) -> None:- store = ChatHistoryStore(tmp_path / "h.db")+async def test_callback_records_chat_error() -> None:+ store = _mem_store()cb = make_history_callback(store)- await cb("browser", json.dumps({"type": "req", "id": "r1", "method": "chat.send", "params": {"session_id": "s1", "query": "出错了"}}))- await cb("uplink", json.dumps({"type": "event", "event": "chat.error", "request_id": "r1", "payload": {"session_id": "s1", "error": "内部错误"}}))+ await cb(+ "browser",+ json.dumps(+ {+ "type": "req",+ "id": "r1",+ "method": "chat.send",+ "params": {"session_id": "s1", "query": "出错了"},+ }+ ),+ )+ await cb(+ "uplink",+ json.dumps(+ {+ "type": "event",+ "event": "chat.error",+ "request_id": "r1",+ "payload": {"session_id": "s1", "error": "内部错误"},+ }+ ),+ )detail = await store.get_session_detail("s1")assert detail is not Noneassistant_msgs = [m for m in detail["messages"] if m["role"] == "assistant"]@@ -158,8 +240,8 @@ async def test_callback_records_chat_error(tmp_path) -> None:@pytest.mark.asyncio-async def test_callback_invalid_json_ignored(tmp_path) -> None:- store = ChatHistoryStore(tmp_path / "h.db")+async def test_callback_invalid_json_ignored() -> None:+ store = _mem_store()cb = make_history_callback(store)await cb("browser", "不是JSON", "conn1")assert await store.list_sessions() == []@@ -167,76 +249,128 @@ async def test_callback_invalid_json_ignored(tmp_path) -> None:@pytest.mark.asyncio-async def test_callback_final_without_session_id_dropped(tmp_path) -> None:- store = ChatHistoryStore(tmp_path / "h.db")+async def test_callback_final_without_session_id_dropped() -> None:+ store = _mem_store()cb = make_history_callback(store)- await cb("uplink", json.dumps({"type": "event", "event": "chat.final", "request_id": "r1", "payload": {"content": "缺 sid"}}))+ await cb(+ "uplink",+ json.dumps(+ {+ "type": "event",+ "event": "chat.final",+ "request_id": "r1",+ "payload": {"content": "缺 sid"},+ }+ ),+ )assert await store.list_sessions() == []await store.close()-# ---- 同步只读(供 http.server 的 _SpaStaticHandler 调用)-----@pytest.mark.asyncio-async def test_sync_read_after_write(tmp_path) -> None:- db = tmp_path / "h.db"- store = ChatHistoryStore(db)+async def test_sync_read_after_write() -> None:+ store = _mem_store()+ set_default_store(store)await store.record_user(request_id="r1", session_id="s1", query="问题", ts=1000.0)await store.record_assistant(- request_id="r1", session_id="s1", content="回答",- event_type="chat.final", ts=1001.0,+ request_id="r1",+ session_id="s1",+ content="回答",+ event_type="chat.final",+ ts=1001.0,)- await store.close() # 确保 aiosqlite 写入落盘- sessions = list_sessions_sync(db)+ sessions = list_sessions_sync(store)assert len(sessions) == 1assert sessions[0]["session_id"] == "s1"- detail = get_session_detail_sync(db, "s1")+ detail = get_session_detail_sync("s1", store)assert detail is not Noneassert len(detail["messages"]) == 2- assert get_session_detail_sync(db, "nope") is None- # db 不存在:返回空 / None,不抛- assert list_sessions_sync(tmp_path / "missing.db") == []- assert get_session_detail_sync(tmp_path / "missing.db", "x") is None+ assert get_session_detail_sync("nope", store) is None+ await store.close()-def test_default_enterprise_history_db_path_is_web_history_db() -> None:- path = default_enterprise_history_db_path()- assert path.endswith("web_history.db")+def test_mysql_without_host_unavailable(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("WEB_DB_HOST", raising=False)+ monkeypatch.setenv("WEB_DB_TYPE", "mysql")+ store = ChatHistoryStore.from_env()+ assert store.backend == "mysql"+ assert store.available is False-def test_resolve_history_db_type_mysql_when_host_set(monkeypatch) -> None:- from jiuwenswarm.channels.web.history_store import resolve_history_db_type+def test_resolve_history_db_type_prefers_web_db_type(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("WEB_DB_TYPE", "sqlite")+ monkeypatch.setenv("DB_TYPE", "mysql")+ monkeypatch.delenv("WEB_DB_HOST", raising=False)+ assert resolve_history_db_type() == "sqlite"++def test_resolve_history_db_type_host_implies_mysql(+ monkeypatch: pytest.MonkeyPatch,+) -> None:monkeypatch.delenv("WEB_DB_TYPE", raising=False)monkeypatch.delenv("DB_TYPE", raising=False)monkeypatch.setenv("WEB_DB_HOST", "127.0.0.1")assert resolve_history_db_type() == "mysql"-def test_mysql_store_unavailable_without_host(monkeypatch) -> None:- from jiuwenswarm.channels.web.history_store import ChatHistoryStore-+def test_resolve_history_db_type_follows_deployment_mode(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.delenv("WEB_DB_TYPE", raising=False)+ monkeypatch.delenv("DB_TYPE", raising=False)monkeypatch.delenv("WEB_DB_HOST", raising=False)- store = ChatHistoryStore.for_db_type("mysql")- assert store.backend == "mysql"- assert store.available is False-+ monkeypatch.setenv("DEPLOYMENT_MODE", "distributed")+ assert resolve_history_db_type() == "mysql"+ monkeypatch.setenv("DEPLOYMENT_MODE", "standalone")+ assert resolve_history_db_type() == "sqlite"@pytest.mark.asyncio-async def test_memory_backend_record_and_list() -> None:- store = ChatHistoryStore.memory()- await store.record_user(request_id="r1", session_id="s1", query="你好", ts=1000.0, user="u1")- await store.record_assistant(- request_id="r1", session_id="s1", content="答", event_type="chat.final", ts=1001.0,+async def test_callback_uplink_request_id_in_payload() -> None:+ store = _mem_store()+ cb = make_history_callback(store)+ await cb(+ "browser",+ json.dumps({"type": "req", "id": "r1", "method": "chat.send", "params": {"query": "hi"}}),)- sessions = store.list_sessions_blocking(limit=20, offset=0, user="u1")- assert len(sessions) == 1- detail = store.get_session_detail_blocking("s1", user="u1")+ await cb(+ "uplink",+ json.dumps(+ {+ "type": "event",+ "event": "chat.delta",+ "payload": {"session_id": "s1", "request_id": "r1", "content": "ok"},+ },+ ),+ )+ await cb(+ "uplink",+ json.dumps(+ {+ "type": "event",+ "event": "chat.final",+ "payload": {"session_id": "s1", "request_id": "r1", "content": ""},+ },+ ),+ )+ detail = await store.get_session_detail("s1")assert detail is not None- assert len(detail["messages"]) == 2- assert store.get_session_detail_blocking("s1", user="other") is None+ assert detail["messages"][-1]["content"] == "ok"+ await store.close()+++def test_default_enterprise_history_db_path_is_web_history_db() -> None:+ path = default_enterprise_history_db_path()+ assert path.endswith("web_history.db")+async def test_sync_read_missing_sqlite_file(tmp_path) -> None:+ missing = tmp_path / "missing.db"+ assert list_sessions_sync(missing) == []+ assert get_session_detail_sync(missing, "x") is None+