mirror of
https://github.com/hansjone/oclaw.git
synced 2026-10-10 14:23:17 +08:00
fix(chat,channels): admin session delete, weixin inbound, PG and docs
- List/delete chat sessions for administrator by username (cross-tenant UUID) - Return 404 when delete does not remove a session; add tests - Weixin: dispatch lang, inbound attachments, reply persist, native reply timeout - PG compat scrub and administrator session delete repo path - RUNBOOK: WhatsApp re-bind with Remove-Item auth; weixin poll diag scripts Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
39fd1905b6
commit
bc1b45a8fd
20 changed files with 1056 additions and 86 deletions
|
|
@ -10,7 +10,7 @@ from fastapi.testclient import TestClient
|
|||
from interfaces.http.fastapi_app import create_app
|
||||
from svc.persistence.db.engine import clear_assistant_engine_cache
|
||||
from svc.persistence.sqlite_store import SqliteStore
|
||||
from svc.persistence.assistant_store import get_assistant_store
|
||||
from svc.persistence.assistant_store import get_assistant_store, reset_assistant_store_singleton
|
||||
|
||||
|
||||
class AdminAuthRBACTests(unittest.TestCase):
|
||||
|
|
@ -21,6 +21,10 @@ class AdminAuthRBACTests(unittest.TestCase):
|
|||
import os
|
||||
|
||||
os.environ["OPS_ASSISTANT_DB_PATH"] = str(db)
|
||||
os.environ["AIA_ASSISTANT_DB_PATH"] = str(db)
|
||||
os.environ["AIA_ASSISTANT_DB_BACKEND"] = "sqlite"
|
||||
os.environ.pop("AIA_ASSISTANT_DATABASE_URL", None)
|
||||
reset_assistant_store_singleton()
|
||||
os.environ["OPS_ASSISTANT_PASSWORD"] = "test-admin-pass"
|
||||
store = SqliteStore(str(db))
|
||||
t = store.create_tenant("Team")
|
||||
|
|
@ -38,6 +42,7 @@ class AdminAuthRBACTests(unittest.TestCase):
|
|||
|
||||
def tearDown(self) -> None:
|
||||
clear_assistant_engine_cache()
|
||||
reset_assistant_store_singleton()
|
||||
self._tmp.cleanup()
|
||||
|
||||
def _login(self, username: str = "administrator", password: str = "test-admin-pass") -> str:
|
||||
|
|
@ -123,6 +128,31 @@ class AdminAuthRBACTests(unittest.TestCase):
|
|||
self.assertTrue(data.get("ok"), data)
|
||||
self.assertEqual(str((data.get("session") or {}).get("username") or ""), "carol")
|
||||
|
||||
def test_administrator_login_without_tenant_id_prefers_team(self) -> None:
|
||||
store = get_assistant_store()
|
||||
newer = store.create_tenant("pg-smoke-newer")
|
||||
store.create_user_account(
|
||||
tenant_id=str(newer["id"]),
|
||||
username="administrator",
|
||||
display_name="Admin",
|
||||
role="admin",
|
||||
password_hash=hashlib.sha256("test-admin-pass".encode("utf-8")).hexdigest(),
|
||||
is_active=True,
|
||||
)
|
||||
self.client.post("/admin/api/auth/bootstrap", json={})
|
||||
resp = self.client.post(
|
||||
"/admin/api/auth/login",
|
||||
json={
|
||||
"tenant_id": "",
|
||||
"username": "administrator",
|
||||
"password": "test-admin-pass",
|
||||
"purpose": "chat",
|
||||
},
|
||||
)
|
||||
data = resp.json()
|
||||
self.assertTrue(data.get("ok"), data)
|
||||
self.assertEqual(str((data.get("session") or {}).get("tenant_id") or ""), self.tenant_id)
|
||||
|
||||
def test_console_login_allows_member_username_with_admin_read(self) -> None:
|
||||
store = get_assistant_store()
|
||||
store.create_user_account(
|
||||
|
|
|
|||
|
|
@ -15,9 +15,10 @@ class _DummyStore:
|
|||
|
||||
def test_channel_dispatch_defaults_to_expert_and_generalist() -> None:
|
||||
store = _DummyStore()
|
||||
interaction_mode, specialist = _resolve_channel_dispatch(store, channel="weixin", account=None)
|
||||
interaction_mode, specialist, lang = _resolve_channel_dispatch(store, channel="weixin", account=None)
|
||||
assert interaction_mode == "expert"
|
||||
assert specialist == "generalist"
|
||||
assert lang == "auto"
|
||||
|
||||
|
||||
def test_channel_dispatch_uses_global_settings() -> None:
|
||||
|
|
@ -25,11 +26,13 @@ def test_channel_dispatch_uses_global_settings() -> None:
|
|||
{
|
||||
"channel.dispatch.interaction_mode.whatsapp": "comprehensive",
|
||||
"channel.dispatch.specialist.whatsapp": "ops",
|
||||
"channel.dispatch.lang.whatsapp": "en",
|
||||
}
|
||||
)
|
||||
interaction_mode, specialist = _resolve_channel_dispatch(store, channel="whatsapp", account=None)
|
||||
interaction_mode, specialist, lang = _resolve_channel_dispatch(store, channel="whatsapp", account=None)
|
||||
assert interaction_mode == "comprehensive"
|
||||
assert specialist == "ops"
|
||||
assert lang == "en"
|
||||
|
||||
|
||||
def test_channel_dispatch_account_config_overrides_global() -> None:
|
||||
|
|
@ -37,15 +40,18 @@ def test_channel_dispatch_account_config_overrides_global() -> None:
|
|||
{
|
||||
"channel.dispatch.interaction_mode.weixin": "comprehensive",
|
||||
"channel.dispatch.specialist.weixin": "ops",
|
||||
"channel.dispatch.lang.weixin": "zh",
|
||||
}
|
||||
)
|
||||
account = {
|
||||
"config": {
|
||||
"interaction_mode": "expert",
|
||||
"specialist": "generalist",
|
||||
"lang": "en",
|
||||
}
|
||||
}
|
||||
interaction_mode, specialist = _resolve_channel_dispatch(store, channel="weixin", account=account)
|
||||
interaction_mode, specialist, lang = _resolve_channel_dispatch(store, channel="weixin", account=account)
|
||||
assert interaction_mode == "expert"
|
||||
assert specialist == "generalist"
|
||||
assert lang == "en"
|
||||
|
||||
|
|
|
|||
78
tests/test_chat_administrator_cross_tenant_sessions.py
Normal file
78
tests/test_chat_administrator_cross_tenant_sessions.py
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
import pytest
|
||||
|
||||
from svc.persistence.db.engine import clear_assistant_engine_cache
|
||||
from svc.persistence.sqlite_store import SqliteStore
|
||||
from svc.persistence.assistant_store import reset_assistant_store_singleton
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def store_two_tenants(monkeypatch: pytest.MonkeyPatch, tmp_path) -> SqliteStore:
|
||||
monkeypatch.delenv("AIA_ASSISTANT_DATABASE_URL", raising=False)
|
||||
monkeypatch.setenv("AIA_ASSISTANT_DB_BACKEND", "sqlite")
|
||||
dbfile = tmp_path / "admin_xtenant.sqlite"
|
||||
monkeypatch.setenv("AIA_ASSISTANT_DB_PATH", str(dbfile))
|
||||
clear_assistant_engine_cache()
|
||||
reset_assistant_store_singleton()
|
||||
s = SqliteStore(str(dbfile))
|
||||
pwd_hash = hashlib.sha256(b"pass").hexdigest()
|
||||
t1 = s.create_tenant("Team")
|
||||
t2 = s.create_tenant("Other")
|
||||
u1 = s.create_user_account(
|
||||
tenant_id=str(t1["id"]),
|
||||
username="administrator",
|
||||
display_name="Admin",
|
||||
role="admin",
|
||||
password_hash=pwd_hash,
|
||||
is_active=True,
|
||||
)
|
||||
s.create_user_account(
|
||||
tenant_id=str(t2["id"]),
|
||||
username="administrator",
|
||||
display_name="Admin",
|
||||
role="admin",
|
||||
password_hash=pwd_hash,
|
||||
is_active=True,
|
||||
)
|
||||
s.create_session_for_user(title="team-sess", tenant_id=str(t1["id"]), user_id=str(u1["id"]))
|
||||
s.create_session_for_user(
|
||||
title="other-sess",
|
||||
tenant_id=str(t2["id"]),
|
||||
user_id=str(s.get_user_by_username(tenant_id=str(t2["id"]), username="administrator")["id"]),
|
||||
)
|
||||
yield s
|
||||
clear_assistant_engine_cache()
|
||||
reset_assistant_store_singleton()
|
||||
|
||||
|
||||
def test_list_sessions_for_administrator_username_cross_tenant(
|
||||
store_two_tenants: SqliteStore,
|
||||
) -> None:
|
||||
s = store_two_tenants
|
||||
rows = s.list_sessions_for_administrator_username(username="administrator", limit=50)
|
||||
titles = {x.title for x in rows}
|
||||
assert "team-sess" in titles
|
||||
assert "other-sess" in titles
|
||||
meta = s.get_sessions_list_meta_for_administrator_username(username="administrator")
|
||||
assert int(meta.session_count or 0) == 2
|
||||
|
||||
|
||||
def test_delete_session_for_administrator_username_cross_tenant(
|
||||
store_two_tenants: SqliteStore,
|
||||
) -> None:
|
||||
s = store_two_tenants
|
||||
rows = s.list_sessions_for_administrator_username(username="administrator", limit=50)
|
||||
other = next(x for x in rows if x.title == "other-sess")
|
||||
team = next(x for x in rows if x.title == "team-sess")
|
||||
team_owner = s.get_ui_session_owner(session_id=str(team.id))
|
||||
login_tid = str((team_owner or {}).get("tenant_id") or "")
|
||||
assert login_tid
|
||||
assert s.delete_session_in_tenant(session_id=str(other.id), tenant_id=login_tid) is False
|
||||
assert s.get_session_for_administrator_username(session_id=str(other.id), username="administrator") is not None
|
||||
assert s.delete_session_for_administrator_username(session_id=str(other.id), username="administrator") is True
|
||||
assert s.get_session_for_administrator_username(session_id=str(other.id), username="administrator") is None
|
||||
meta = s.get_sessions_list_meta_for_administrator_username(username="administrator")
|
||||
assert int(meta.session_count or 0) == 1
|
||||
|
|
@ -5,10 +5,15 @@ from dataclasses import dataclass
|
|||
from runtime.application.gateway.inbound_service import (
|
||||
_collect_reply_attachments_from_history,
|
||||
_collect_recent_tool_attachments,
|
||||
_get_channel_dispatch_setting,
|
||||
_latest_user_turn_uuid,
|
||||
_maybe_add_media_path_for_wechat_reply,
|
||||
_maybe_expand_reply_attachments_for_channel,
|
||||
_parse_message_attachments,
|
||||
_persist_channel_assistant_if_turn_missing,
|
||||
_resolve_channel_dispatch,
|
||||
_should_suppress_channel_reply,
|
||||
_user_facing_wechat_reply,
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -23,6 +28,88 @@ def test_should_not_suppress_non_weixin_channel() -> None:
|
|||
assert _should_suppress_channel_reply(channel="admin_chat", text=text) is False
|
||||
|
||||
|
||||
def test_user_facing_wechat_reply_maps_empty_and_api_key_errors() -> None:
|
||||
assert _user_facing_wechat_reply(reply="") == "暂时无法回复,请稍后再试。"
|
||||
assert "API" in _user_facing_wechat_reply(
|
||||
reply='Missing API key for provider "openai". Configure the gateway auth for that provider.'
|
||||
)
|
||||
assert _user_facing_wechat_reply(reply="你好") == "你好"
|
||||
|
||||
|
||||
def test_persist_channel_assistant_if_turn_missing_inserts_once() -> None:
|
||||
class _Msg:
|
||||
def __init__(self, role: str, turn_uuid: str) -> None:
|
||||
self.role = role
|
||||
self.turn_uuid = turn_uuid
|
||||
|
||||
class _Store:
|
||||
def __init__(self) -> None:
|
||||
self.rows: list[_Msg] = [_Msg("user", "turn-1")]
|
||||
self.added: list[tuple[str, str, str]] = []
|
||||
|
||||
def get_messages(self, *, session_id: str, limit: int = 80) -> list[_Msg]:
|
||||
_ = (session_id, limit)
|
||||
return list(self.rows)
|
||||
|
||||
def add_message(self, **kwargs: object) -> None:
|
||||
self.added.append(
|
||||
(
|
||||
str(kwargs.get("session_id") or ""),
|
||||
str(kwargs.get("turn_uuid") or ""),
|
||||
str(kwargs.get("content") or ""),
|
||||
)
|
||||
)
|
||||
self.rows.append(_Msg("assistant", str(kwargs.get("turn_uuid") or "")))
|
||||
|
||||
store = _Store()
|
||||
_persist_channel_assistant_if_turn_missing(
|
||||
store=store,
|
||||
session_id="s1",
|
||||
turn_uuid="",
|
||||
final_text="暂时无法回复,请稍后再试。",
|
||||
)
|
||||
assert len(store.added) == 1
|
||||
assert store.added[0] == ("s1", "turn-1", "暂时无法回复,请稍后再试。")
|
||||
_persist_channel_assistant_if_turn_missing(
|
||||
store=store,
|
||||
session_id="s1",
|
||||
turn_uuid="turn-1",
|
||||
final_text="暂时无法回复,请稍后再试。",
|
||||
)
|
||||
assert len(store.added) == 1
|
||||
|
||||
|
||||
def test_latest_user_turn_uuid() -> None:
|
||||
class _Msg:
|
||||
def __init__(self, role: str, turn_uuid: str) -> None:
|
||||
self.role = role
|
||||
self.turn_uuid = turn_uuid
|
||||
|
||||
class _Store:
|
||||
def get_messages(self, *, session_id: str, limit: int = 80) -> list[_Msg]:
|
||||
_ = (session_id, limit)
|
||||
return [_Msg("assistant", "a1"), _Msg("user", "u2")]
|
||||
|
||||
assert _latest_user_turn_uuid(_Store(), session_id="s") == "u2"
|
||||
|
||||
|
||||
def test_channel_dispatch_wechat_reads_weixin_settings() -> None:
|
||||
class _Store:
|
||||
def get_setting(self, key: str) -> str:
|
||||
data = {
|
||||
"channel.dispatch.interaction_mode.weixin": "comprehensive",
|
||||
"channel.dispatch.specialist.weixin": "ops",
|
||||
"channel.dispatch.lang.weixin": "zh",
|
||||
}
|
||||
return str(data.get(key) or "")
|
||||
|
||||
mode, spec, lang = _resolve_channel_dispatch(_Store(), channel="wechat", account=None)
|
||||
assert mode == "comprehensive"
|
||||
assert spec == "ops"
|
||||
assert lang == "zh"
|
||||
assert _get_channel_dispatch_setting(_Store(), "channel.dispatch.specialist.", "wechat") == "ops"
|
||||
|
||||
|
||||
def test_parse_message_attachments_accepts_json_string() -> None:
|
||||
out = _parse_message_attachments('[{"type":"image_ref","attachment_id":"a1"}]')
|
||||
assert len(out) == 1
|
||||
|
|
@ -55,16 +142,38 @@ def test_collect_reply_attachments_prefers_matching_assistant_text() -> None:
|
|||
assert out[0].get("attachment_id") == "new"
|
||||
|
||||
|
||||
def test_collect_reply_attachments_does_not_reuse_stale_images_on_text_only_reply() -> None:
|
||||
rows = [
|
||||
_Row(role="assistant", content="here is a chart", attachments='[{"attachment_id":"old"}]'),
|
||||
_Row(role="assistant", content="ok", attachments=None),
|
||||
]
|
||||
out = _collect_reply_attachments_from_history(store=_FakeStore(rows), session_id="s1", reply_text="ok")
|
||||
assert out == []
|
||||
|
||||
|
||||
def test_collect_recent_tool_attachments_falls_back_to_tool_media() -> None:
|
||||
rows = [
|
||||
_Row(role="assistant", content="x", attachments=None),
|
||||
_Row(role="user", content="draw", attachments=None),
|
||||
_Row(role="tool", content="{}", attachments='[{"type":"image_ref","attachment_id":"a1"}]'),
|
||||
_Row(role="assistant", content="x", attachments=None),
|
||||
]
|
||||
out = _collect_recent_tool_attachments(store=_FakeStore(rows), session_id="s1")
|
||||
assert len(out) == 1
|
||||
assert out[0].get("attachment_id") == "a1"
|
||||
|
||||
|
||||
def test_collect_recent_tool_attachments_ignores_media_from_prior_turn() -> None:
|
||||
rows = [
|
||||
_Row(role="user", content="old question", attachments=None),
|
||||
_Row(role="tool", content="{}", attachments='[{"type":"image_ref","attachment_id":"stale"}]'),
|
||||
_Row(role="assistant", content="old answer", attachments=None),
|
||||
_Row(role="user", content="new question", attachments=None),
|
||||
_Row(role="assistant", content="new answer", attachments=None),
|
||||
]
|
||||
out = _collect_recent_tool_attachments(store=_FakeStore(rows), session_id="s1")
|
||||
assert out == []
|
||||
|
||||
|
||||
def test_maybe_add_media_path_for_wechat_reply_sets_media_path(monkeypatch) -> None:
|
||||
# Avoid touching disk: stub AttachmentAssetStore.get_local_path.
|
||||
from pathlib import Path
|
||||
|
|
|
|||
|
|
@ -44,3 +44,9 @@ def test_scrub_nul_bytes_from_text() -> None:
|
|||
|
||||
def test_scrub_nul_bytes_from_jsonable_nested() -> None:
|
||||
assert pg_compat.scrub_nul_bytes_from_jsonable({"x": "y\x00z"}) == {"x": "yz"}
|
||||
|
||||
|
||||
def test_escape_percent_in_sql_literals_for_like_b64_prefix() -> None:
|
||||
sql = "SELECT 1 FROM llm_profile WHERE api_key LIKE 'b64:%'"
|
||||
adapted = pg_compat.adapt_sql_for_postgres(sql)
|
||||
assert "LIKE 'b64:%%'" in adapted
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import time
|
||||
import unittest
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
|
@ -132,6 +134,36 @@ class WeixinIlinkApiTests(unittest.TestCase):
|
|||
finally:
|
||||
weixin_ilink_api._process_inbound_payload_usecase = old_usecase # type: ignore[assignment]
|
||||
|
||||
def test_native_reply_timeout_returns_user_message(self) -> None:
|
||||
old_usecase = weixin_ilink_api._process_inbound_payload_usecase
|
||||
old_timeout = weixin_ilink_api._native_reply_timeout_sec
|
||||
|
||||
def _slow_usecase(payload: dict[str, object]) -> dict[str, object]:
|
||||
_ = payload
|
||||
time.sleep(1.2)
|
||||
return {"ok": True, "replies": [{"text": "late"}]}
|
||||
|
||||
try:
|
||||
weixin_ilink_api._process_inbound_payload_usecase = _slow_usecase # type: ignore[assignment]
|
||||
weixin_ilink_api._native_reply_timeout_sec = lambda: 0.2 # type: ignore[assignment]
|
||||
r = self.client.post(
|
||||
"/weixin/native/reply",
|
||||
headers=self.headers,
|
||||
json={
|
||||
"channel": "wechat",
|
||||
"account_id": "bot-1",
|
||||
"ctx": {"From": "wxid_u4", "To": "wxid_u4", "Body": "hi"},
|
||||
},
|
||||
)
|
||||
self.assertEqual(r.status_code, 200, r.text)
|
||||
data = r.json() or {}
|
||||
replies = data.get("replies") if isinstance(data.get("replies"), list) else []
|
||||
self.assertEqual(len(replies), 1, data)
|
||||
self.assertIn("超时", str((replies[0] or {}).get("text") or ""))
|
||||
finally:
|
||||
weixin_ilink_api._process_inbound_payload_usecase = old_usecase # type: ignore[assignment]
|
||||
weixin_ilink_api._native_reply_timeout_sec = old_timeout # type: ignore[assignment]
|
||||
|
||||
def test_whatsapp_native_reply_returns_sync_replies(self) -> None:
|
||||
old_usecase = weixin_ilink_api._process_inbound_payload_usecase
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue