diff --git a/app/api/endpoints/message.py b/app/api/endpoints/message.py index 968e510cb..a00eaa6a4 100644 --- a/app/api/endpoints/message.py +++ b/app/api/endpoints/message.py @@ -34,7 +34,6 @@ from app.schemas.message import MessageClearScope as _SchemaMessageClearScope from app.schemas.message import MessageHistoryItem as _SchemaMessageHistoryItem from app.schemas.message import Subscription as _SchemaSubscription from app.schemas.message import SubscriptionMessage as _SchemaSubscriptionMessage -from app.schemas.message import WebMessageItem as _SchemaWebMessageItem from app.schemas.message import WebPushPublicKeyData as _SchemaWebPushPublicKeyData from app.schemas.response import Response as _SchemaResponse from app.schemas.token import TokenPayload as _SchemaTokenPayload @@ -214,20 +213,38 @@ async def web_message( return _SchemaResponse(success=True) -@router.get("/web", summary="获取WEB消息", response_model=List[_SchemaWebMessageItem]) -async def get_web_message( +@router.get( + "/web", + summary="获取消息历史(兼容入口)", + response_model=List[_SchemaMessageHistoryItem], + deprecated=True, +) +@router.get( + "/history", + summary="获取消息历史", + response_model=List[_SchemaMessageHistoryItem], +) +async def get_message_history( _: _SchemaTokenPayload = Depends(verify_token), service: MessageQueryService = Depends(get_message_query_service), page: Optional[int] = 1, count: Optional[int] = 20, -) -> List[dict[str, Any]]: +) -> List[_SchemaMessageHistoryItem]: """ - 获取WEB消息列表 + 分页获取消息表中的全部历史记录,包含接收消息与发送通知。 + + 旧路径 GET /api/v1/message/web 作为兼容入口保留相同行为;仅查询系统已发送通知时使用 GET /api/v1/message/notification。 + + :param service: 消息历史查询服务 + :param page: 页码,从 1 开始,传 None 时默认第 1 页 + :param count: 每页最多返回条数,传 None 时默认 20 条 + :return: 按登记时间和主键倒序排列的消息历史列表 """ - return await service.list_web( + messages = await service.list_history( page=page if page is not None else 1, count=count if count is not None else 20, ) + return [_SchemaMessageHistoryItem(**message) for message in messages] @router.get("/notification", summary="获取通知消息", response_model=List[_SchemaMessageHistoryItem]) @@ -238,7 +255,12 @@ async def get_notification_message( count: Optional[int] = 20, ) -> List[_SchemaMessageHistoryItem]: """ - 获取系统发送的通知消息列表。 + 获取清理水位之后系统发送的通知消息列表,仅包含发送方向(action=1)记录。 + + :param service: 消息历史查询服务 + :param page: 页码,从 1 开始,传 None 时默认第 1 页 + :param count: 每页最多返回条数,传 None 时默认 20 条 + :return: 按登记时间和主键倒序排列的系统通知消息列表 """ clear_before = _get_notification_clear_before() messages = await service.list_notifications( diff --git a/app/application/messaging/message.py b/app/application/messaging/message.py index 88b06365f..c1c4dbec0 100644 --- a/app/application/messaging/message.py +++ b/app/application/messaging/message.py @@ -55,7 +55,7 @@ class AsyncMessageQueryRepository(Protocol): self, page: int = 1, count: int = 30 ) -> list[Any]: """ - 分页读取 Web 消息。 + 分页读取全部消息历史记录,不区分渠道与收发方向。 :param page: 页码,从 1 开始 :param count: 每页最多返回的消息数,默认 30 @@ -92,12 +92,18 @@ class MessageQueryService: def __init__(self, repository: AsyncMessageQueryRepository): """ 使用显式消息查询端口初始化服务。 + + :param repository: 消息历史与通知查询持久化端口 """ self._repository = repository - async def list_web(self, page: int = 1, count: int = 20) -> list[dict[str, Any]]: + async def list_history(self, page: int = 1, count: int = 20) -> list[dict[str, Any]]: """ - 分页返回可由 API schema 消费的 Web 消息字典。 + 分页返回可由 API 模型消费的全部消息历史字典,包含接收消息与发送通知。 + + :param page: 页码,从 1 开始 + :param count: 每页最多返回的消息数,默认 20 + :return: 按记录时间和主键降序排列的消息字典列表 """ messages = await self._repository.async_list_by_page(page=page, count=count) result: list[dict[str, Any]] = [] @@ -105,7 +111,7 @@ class MessageQueryService: try: result.append(message.to_dict()) except Exception as error: - logger.error(f"获取WEB消息列表失败: {str(error)}") + logger.error(f"获取消息历史列表失败: {str(error)}") return result async def list_notifications( @@ -117,7 +123,14 @@ class MessageQueryService: media_clear_before: Optional[str] = None, ) -> list[dict[str, Any]]: """ - 分页返回清理水位之后的通知消息字典。 + 分页返回清理水位之后的系统已发送通知消息字典。 + + :param page: 页码,从 1 开始 + :param count: 每页最多返回的消息数,默认 20 + :param all_clear_before: 全部通知的清理时间水位,None 表示不限制 + :param system_clear_before: 无图片系统通知的清理时间水位,None 表示不限制 + :param media_clear_before: 含图片媒体通知的清理时间水位,None 表示不限制 + :return: 仅包含已发送通知(action=1)且晚于相应清理水位的消息字典列表 """ messages = await self._repository.async_list_sent_by_page( page=page, diff --git a/app/db/models/message.py b/app/db/models/message.py index f014255ff..647ed246a 100644 --- a/app/db/models/message.py +++ b/app/db/models/message.py @@ -38,7 +38,7 @@ class Message(Base): userid: Mapped[Optional[str]] = mapped_column(String) # 登记时间 reg_time: Mapped[Optional[str]] = mapped_column(String) - # 消息方向:0-接收息,1-发送消息 + # 消息方向:0-接收消息,1-发送消息 action: Mapped[Optional[int]] = mapped_column(Integer) # 附件json note: Mapped[Optional[Any]] = mapped_column(JSON) diff --git a/app/db/oper/message.py b/app/db/oper/message.py index 360b3405e..f55ccb873 100644 --- a/app/db/oper/message.py +++ b/app/db/oper/message.py @@ -45,7 +45,7 @@ class MessageOper(DbOper): :param image: 图片 :param link: 链接 :param userid: 用户ID - :param action: 消息方向:0-接收息,1-发送消息 + :param action: 消息方向:0-接收消息,1-发送消息 :param note: 附件json """ kwargs.update({ @@ -139,7 +139,11 @@ class MessageOper(DbOper): self, page: int = 1, count: int = 30 ) -> list[Message]: """ - 分页获取消息记录。 + 异步分页获取全部消息记录,不区分渠道与收发方向。 + + :param page: 页码,从 1 开始 + :param count: 每页最多返回的消息数,默认 30 + :return: 按登记时间和主键倒序排列的消息记录列表 """ async def query(session: AsyncSession) -> list[Message]: """ diff --git a/app/runtime/compat/manifest.py b/app/runtime/compat/manifest.py index 9de3f7953..80d10b7fe 100644 --- a/app/runtime/compat/manifest.py +++ b/app/runtime/compat/manifest.py @@ -774,6 +774,11 @@ _MESSAGE_NOTIFICATION_SYMBOL_ALIASES: Dict[str, SymbolAlias] = { target_name="MessageHistoryItem", replacement="app.schemas.message.MessageHistoryItem", ), + "WebMessageItem": SymbolAlias( + target_module="app.schemas.message", + target_name="MessageHistoryItem", + replacement="app.schemas.message.MessageHistoryItem", + ), **{ old: SymbolAlias( target_module="app.schemas.message", diff --git a/app/schemas/exports.py b/app/schemas/exports.py index e9aa30c1e..4583913eb 100644 --- a/app/schemas/exports.py +++ b/app/schemas/exports.py @@ -614,7 +614,6 @@ SCHEMA_EXPORTS = { 'ValidationIssue': ('app.schemas.response', 'ValidationIssue'), 'ValueData': ('app.schemas.common', 'ValueData'), 'WINDOWS_DRIVE_PATTERN': ('app.schemas.file', 'WINDOWS_DRIVE_PATTERN'), - 'WebMessageItem': ('app.schemas.message', 'WebMessageItem'), 'WebPushPublicKeyData': ('app.schemas.message', 'WebPushPublicKeyData'), 'WebhookEventInfo': ('app.schemas.mediaserver', 'WebhookEventInfo'), 'WechatClawBotData': ('app.schemas.notification', 'WechatClawBotData'), diff --git a/app/schemas/message.py b/app/schemas/message.py index 6088f774a..76314be7a 100644 --- a/app/schemas/message.py +++ b/app/schemas/message.py @@ -58,7 +58,7 @@ class MessageResponse(BaseModel): class MessageHistoryItem(BaseModel): """ - 通知历史记录。 + 消息历史记录,覆盖各渠道接收的用户消息与系统发送的通知消息。 """ id: Optional[int] = Field(default=None, description="消息ID") @@ -76,12 +76,6 @@ class MessageHistoryItem(BaseModel): note: Optional[JsonData] = Field(default=None, description="附件json") -class WebMessageItem(MessageHistoryItem): - """ - Web 消息历史记录。 - """ - - class MessageClearData(BaseModel): """ 消息中心各范围的清理时间。 diff --git a/docs/mcp-api.md b/docs/mcp-api.md index 17662c160..331469db3 100644 --- a/docs/mcp-api.md +++ b/docs/mcp-api.md @@ -331,7 +331,10 @@ Web 影视精确与标题 SSE 的 `manual_paging=true` 模式在最终 `done` Web 会话沿用当前用户;无渠道调用不携带收件人,插件回执按既有管理员通知目标路由, 没有可用目标时不发送。 -`GET /api/v1/message/notification` 的可空 `poster` 字段提供独立媒体海报。 +`GET /api/v1/message/history` 分页返回消息表中的全部历史记录(包含 `action=0` 的接收消息与 +`action=1` 的发送消息,`GET /api/v1/message/web` 作为兼容入口保留相同行为); +`GET /api/v1/message/notification` 仅返回清理水位之后的系统已发送通知(`action=1`), +其可空 `poster` 字段提供独立媒体海报。 新通知从已有媒体上下文提取海报;`image` 继续保留原有渠道图片语义。 旧通知及没有海报的通知返回 `poster: null`,客户端不应将背景图裁切成海报。 diff --git a/tests/fixtures/architecture/runtime-contract-baseline.json b/tests/fixtures/architecture/runtime-contract-baseline.json index d8d8d6f98..a6fe4457c 100644 --- a/tests/fixtures/architecture/runtime-contract-baseline.json +++ b/tests/fixtures/architecture/runtime-contract-baseline.json @@ -1192,6 +1192,11 @@ "replacement": "app.application.transfer.workflow.TransferTask", "target_module": "app.sdk._legacy.transfer", "target_name": "TransferTask" + }, + "WebMessageItem": { + "replacement": "app.schemas.message.MessageHistoryItem", + "target_module": "app.schemas.message", + "target_name": "MessageHistoryItem" } }, "app.schemas.agent": { @@ -1261,6 +1266,11 @@ "replacement": "app.schemas.types.MessageType", "target_module": "app.schemas.types", "target_name": "MessageType" + }, + "WebMessageItem": { + "replacement": "app.schemas.message.MessageHistoryItem", + "target_module": "app.schemas.message", + "target_name": "MessageHistoryItem" } }, "app.schemas.transfer": { diff --git a/tests/test_api_optional_inputs.py b/tests/test_api_optional_inputs.py index eb1a1ecd5..16070f5da 100644 --- a/tests/test_api_optional_inputs.py +++ b/tests/test_api_optional_inputs.py @@ -57,9 +57,9 @@ def test_history_and_web_message_optional_pagination(): response = asyncio.run(history.transfer_history(page=None, count=None, query=query, _=None)) query.list_transfer.assert_awaited_once_with(title=None, page=1, count=30, status=None) assert response.success is True - messages = SimpleNamespace(list_web=AsyncMock(return_value=[])) - assert asyncio.run(message.get_web_message(service=messages, page=None, count=None, _=None)) == [] - messages.list_web.assert_awaited_once_with(page=1, count=20) + messages = SimpleNamespace(list_history=AsyncMock(return_value=[])) + assert asyncio.run(message.get_message_history(service=messages, page=None, count=None, _=None)) == [] + messages.list_history.assert_awaited_once_with(page=1, count=20) @pytest.mark.parametrize("season", [None, 2]) diff --git a/tests/test_message_notification_naming_compat.py b/tests/test_message_notification_naming_compat.py index 9c2df99f8..bb325f87c 100644 --- a/tests/test_message_notification_naming_compat.py +++ b/tests/test_message_notification_naming_compat.py @@ -30,6 +30,7 @@ _EXPECTED_RESOLUTIONS = { ("app.schemas.message", "Notification"): Message, ("app.schemas.message", "CommingMessage"): IncomingMessage, ("app.schemas.message", "NotificationHistoryItem"): MessageHistoryItem, + ("app.schemas.message", "WebMessageItem"): MessageHistoryItem, ("app.schemas.message", "NotificationClearScope"): MessageClearScope, ("app.schemas.message", "NotificationClearBefore"): MessageClearBefore, ("app.schemas.message", "NotificationClearData"): MessageClearData, @@ -52,6 +53,7 @@ def test_canonical_modules_do_not_define_legacy_names(): "Notification", "CommingMessage", "NotificationHistoryItem", + "WebMessageItem", "NotificationClearScope", "NotificationClearBefore", "NotificationClearData", @@ -89,6 +91,7 @@ def test_schemas_package_level_legacy_imports_resolve(): assert schemas_package.Notification is Message assert schemas_package.CommingMessage is IncomingMessage assert schemas_package.NotificationHistoryItem is MessageHistoryItem + assert schemas_package.WebMessageItem is MessageHistoryItem assert schemas_package.ChannelCapabilityManager is ChannelCapabilityManager diff --git a/tests/test_message_notifications.py b/tests/test_message_notifications.py index f1f110441..322ece79d 100644 --- a/tests/test_message_notifications.py +++ b/tests/test_message_notifications.py @@ -4,10 +4,17 @@ import asyncio import json +from collections.abc import Iterator from unittest.mock import Mock +import pytest + from app.api.endpoints import message as message_endpoint -from app.api.endpoints.message import clear_notification_message, get_notification_message +from app.api.endpoints.message import ( + clear_notification_message, + get_message_history, + get_notification_message, +) from app.api.endpoints.system import get_message from app.application.messaging.message import _SSE_QUEUE_MAXSIZE, MessageHelper, MessageQueryService from app.chain.base import ChainBase @@ -31,6 +38,18 @@ def _clear_messages() -> None: SystemConfigOper().delete(SystemConfigKey.NotificationClearBefore) +@pytest.fixture(autouse=True) +def _isolate_message_state() -> Iterator[None]: + """ + 在每条用例前后清理默认消息表与通知清理水位,避免跨测试文件残留。 + + :yields: 测试执行上下文 + """ + _clear_messages() + yield + _clear_messages() + + def _reset_message_helper(helper: MessageHelper) -> None: """ 清空单例消息队列和去重缓存,避免用例间互相影响。 @@ -51,7 +70,7 @@ def _set_message_time(title: str, reg_time: str) -> None: def test_notification_history_only_lists_sent_messages() -> None: """ - 通知历史应返回已发送消息,包含通过消息链登记的智能体消息。 + 通知历史接口仅返回已发送消息(action=1),不混入用户发来的接收消息(action=0)。 """ _clear_messages() oper = MessageOper() @@ -59,22 +78,202 @@ def test_notification_history_only_lists_sent_messages() -> None: oper.add(title="用户消息", text="帮我搜索", action=0) oper.add(title="智能体回复", text="已处理", action=1, mtype=MessageType.Agent) - messages = MessageOper().list_by_page(page=1, count=10) - assert [message.title for message in messages if message.action == 1] == ["智能体回复", "系统通知"] + async def _load_notifications() -> list[tuple[str | None, int | None]]: + """ + 通过通知历史端点读取已发送消息列表。 + """ + async with AsyncSessionFactory() as db: + items = await get_notification_message( + service=MessageQueryService(MessageOper(db)), + page=1, + count=10, + ) + return [(item.title, item.action) for item in items] + + assert asyncio.run(_load_notifications()) == [ + ("智能体回复", 1), + ("系统通知", 1), + ] -def test_web_message_history_returns_all_messages() -> None: +def test_message_history_endpoint_returns_all_directions_and_keeps_web_compat() -> None: """ - Web 消息历史返回消息表中的全部记录。 + 消息历史接口返回接收与发送全部记录,同时保留 /web 兼容路由并隐藏其公开文档。 """ + from fastapi import FastAPI + from fastapi.testclient import TestClient + + from app.adapters.web.security.access import verify_token + from app.api.dependencies.agent import get_message_query_service + from app.schemas.token import TokenPayload + _clear_messages() oper = MessageOper() oper.add(title="智能体回复", text="已处理", action=1, mtype=MessageType.Agent) oper.add(title="用户消息", text="/ai 帮我处理", action=0) oper.add(title="普通通知", text="下载完成", action=1, mtype=MessageType.Download) - messages = MessageOper().list_by_page(page=1, count=10) - assert [message.title for message in messages] == ["普通通知", "用户消息", "智能体回复"] + async def _load_history() -> list[tuple[str | None, int | None]]: + """ + 通过消息历史端点读取全部方向记录。 + """ + async with AsyncSessionFactory() as db: + items = await get_message_history( + service=MessageQueryService(MessageOper(db)), + page=1, + count=10, + ) + return [(item.title, item.action) for item in items] + + assert asyncio.run(_load_history()) == [ + ("普通通知", 1), + ("用户消息", 0), + ("智能体回复", 1), + ] + + app = FastAPI() + app.include_router(message_endpoint.router, prefix="/api/v1/message") + app.dependency_overrides[verify_token] = lambda: TokenPayload(sub="1", super_user=True) + + async def _override_service() -> MessageQueryService: + """ + 在测试请求内提供绑定异步会话的消息历史查询服务。 + """ + async with AsyncSessionFactory() as db: + items = await MessageOper(db).async_list_by_page(page=1, count=20) + + class _SnapshotRepository: + """ + 回放预取消息对象的内存测试仓储。 + """ + + async def async_list_by_page(self, page: int = 1, count: int = 30) -> list[MessageModel]: + """ + 返回当前测试批次中的消息快照。 + + :param page: 页码 + :param count: 每页数量 + :return: 切片后的消息列表 + """ + start = (page - 1) * count + return items[start:start + count] + + async def async_list_sent_by_page( + self, + page: int = 1, + count: int = 30, + all_clear_before: str | None = None, + system_clear_before: str | None = None, + media_clear_before: str | None = None, + ) -> list[MessageModel]: + """ + 返回当前测试批次中发送方向的通知消息快照。 + + :param page: 页码 + :param count: 每页数量 + :param all_clear_before: 全部清理水位 + :param system_clear_before: 系统通知清理水位 + :param media_clear_before: 媒体通知清理水位 + :return: 仅包含发送方向的消息列表 + """ + sent = [item for item in items if item.action == 1] + start = (page - 1) * count + return sent[start:start + count] + + return MessageQueryService(_SnapshotRepository()) + + app.dependency_overrides[get_message_query_service] = _override_service + with TestClient(app) as client: + history_res = client.get("/api/v1/message/history?page=1&count=10") + compat_res = client.get("/api/v1/message/web?page=1&count=10") + notification_res = client.get("/api/v1/message/notification?page=1&count=10") + openapi_paths = client.get("/openapi.json").json()["paths"] + + assert history_res.status_code == 200 + assert compat_res.status_code == 200 + assert history_res.json() == compat_res.json() + assert [(row["title"], row["action"]) for row in history_res.json()["data"]] == [ + ("普通通知", 1), + ("用户消息", 0), + ("智能体回复", 1), + ] + assert [(row["title"], row["action"]) for row in notification_res.json()["data"]] == [ + ("普通通知", 1), + ("智能体回复", 1), + ] + assert "get" in openapi_paths["/api/v1/message/history"] + assert not openapi_paths["/api/v1/message/history"]["get"].get("deprecated") + assert openapi_paths["/api/v1/message/web"]["get"].get("deprecated") is True + + +def test_message_query_service_skips_broken_row_projection() -> None: + """ + 单条历史记录序列化异常时,查询服务记录错误并继续返回其余有效消息。 + """ + + class _BrokenRow: + """ + 模拟 to_dict 抛出异常的损坏持久化对象。 + """ + + def to_dict(self) -> dict[str, object]: + """ + 抛出序列化错误以验证容错分支。 + + :raises RuntimeError: 始终抛出模拟异常 + """ + raise RuntimeError("corrupted row") + + class _ValidRow: + """ + 模拟正常序列化为字典的消息持久化对象。 + """ + + def to_dict(self) -> dict[str, object]: + """ + 返回最小有效消息字典。 + + :return: 包含标题与方向的字典 + """ + return {"title": "正常消息", "action": 0} + + class _StubRepository: + """ + 混合返回损坏记录与有效记录的测试仓储。 + """ + + async def async_list_by_page(self, page: int = 1, count: int = 30) -> list[object]: + """ + 返回一条损坏记录与一条有效记录。 + + :param page: 页码 + :param count: 每页数量 + :return: 混合测试记录列表 + """ + return [_BrokenRow(), _ValidRow()] + + async def async_list_sent_by_page( + self, + page: int = 1, + count: int = 30, + all_clear_before: str | None = None, + system_clear_before: str | None = None, + media_clear_before: str | None = None, + ) -> list[object]: + """ + 满足协议签名的空通知查询实现。 + + :param page: 页码 + :param count: 每页数量 + :param all_clear_before: 全部清理水位 + :param system_clear_before: 系统通知清理水位 + :param media_clear_before: 媒体通知清理水位 + :return: 空列表 + """ + return [] + + result = asyncio.run(MessageQueryService(_StubRepository()).list_history(page=1, count=10)) + assert result == [{"title": "正常消息", "action": 0}] def test_notification_clear_marker_filters_history_across_requests() -> None: