diff --git a/backend/app/api/notify.py b/backend/app/api/notify.py index f5e4ddbb..8702528a 100644 --- a/backend/app/api/notify.py +++ b/backend/app/api/notify.py @@ -21,7 +21,7 @@ from app.core.crypto import encrypt from app.db.base import SessionLocal from app.db.models import NotifyChannel, NotifyDelivery from app.notify import core -from app.notify.service import EVENTS, EVENT_LABEL, channel_out +from app.notify.service import EVENTS, channel_out, subscribe_problem router = APIRouter(prefix="/api/notify", tags=["notify"]) @@ -61,12 +61,14 @@ async def _safe_personal(scope: str, url: str) -> None: raise HTTPException(422, problem) -def _validated(payload: ChannelIn, *, url: str | None) -> None: +def _validated(payload: ChannelIn, *, url: str | None, saved: list[str] | None = None) -> None: + """saved 是渠道已经订阅着的事件:只核对这次新勾的(notify/service.subscribe_problem)。以前存下的照旧——当时界面对 + 哪种渠道都列全部事件,现在才按事件推给哪几条路核对,不能让这些渠道连开关、改名都 422。""" if payload.format not in core.FORMATS: raise HTTPException(422, f"消息格式只能是{'、'.join(core.FORMAT_LABEL.values())}之一") - unknown = [e for e in payload.events if e not in EVENTS] - if unknown: - raise HTTPException(422, f"不认识的通知事件:{'、'.join(unknown)}。可选:{'、'.join(EVENT_LABEL.values())}") + for event in dict.fromkeys(payload.events): + if event not in (saved or ()) and (problem := subscribe_problem(event, payload.scope)): + raise HTTPException(422, problem) if url is not None and (problem := core.format_problem(payload.format, url)): raise HTTPException(422, problem) @@ -84,8 +86,10 @@ async def list_channels() -> dict[str, Any]: @router.get("/events") -async def list_events() -> list[dict[str, str]]: - return [{"event": e, "label": EVENT_LABEL[e]} for e in EVENTS] +async def list_events() -> list[dict[str, Any]]: + """登记的通知事件和推给哪几条路(typesApp.ts 的 NotifyEventRow):设置页、应用的通知按 scopes 列可订阅的事件。 + scopes 是空的,是登记了、还没有推送的,照实给出来,由界面不列。""" + return [{"event": name, "label": event.label, "scopes": list(event.scopes)} for name, event in EVENTS.items()] @router.post("/channels", status_code=201) @@ -150,9 +154,9 @@ async def update_channel(channel_id: str, payload: ChannelIn) -> dict[str, Any]: from app.core.crypto import decrypt current = decrypt(row.url) or "" - _validated(payload, url=current or None) + _validated(payload, url=current or None, saved=list(row.events or [])) else: - _validated(payload, url=url) + _validated(payload, url=url, saved=list(row.events or [])) await _safe_personal(row.scope, url) row.url = encrypt(url) row.name, row.format = payload.name.strip(), payload.format diff --git a/backend/app/notify/service.py b/backend/app/notify/service.py index a836574a..e896af9f 100644 --- a/backend/app/notify/service.py +++ b/backend/app/notify/service.py @@ -10,12 +10,26 @@ (搭图时起的),不用按运行数据渲染出来的那一句。链接要设了对外访问地址(设置里的 notify)才有。 推送放在后台(spawn):接收端挂住时超时加重试要几十秒,不能拖着开待办、运行收尾。测试用 drain 等它们推完。 + +事件只在这里登记(EVENTS,总方案 X6):每个事件一行,名字、界面上的叫法(前端 lib/terms.ts 的 NOTIFY_TEXT.eventLabel +逐字一致,test_notify_events 对照)、推给哪几条路(scopes:global 全局渠道自己订阅、user 相关的人自己的个人渠道、app 应用 +版本 spec.notify 的订阅)。_channels 只走登记了的路,没登记的事件推不出去;接口按 scopes 收订阅,设置页和应用的通知按 +GET /api/notify/events 列。scopes 是空的,是登记了、还没有推送的事件:不收订阅、界面上不列——勾了却收不到,就是「看着 +生效、其实没生效」(个人渠道勾了实例结束、失败却收不到,04-对外集成与触达 B1,就是这么错的)。本轮第 1 波把六个新事件 +一次登记好;实现推送的那一块写自己的 notify_*,只改自己那一行的 scopes,不再改这张表的别处、也不再改前端的叫法表:几块 +并行改同一处必然冲突。以前存下的订阅不按 scopes 重新核对(api/notify._validated 只核对新勾的)。 + +消息的结构,新事件一律照这个写(P4、D9):标题、状态、条数、链接,外加编号(#前 6 位)和搭建时起的名字(应用、工作流、 +节点在图上的名字,题集、数据源、访问密钥的名字)。条数说的是有几件事要处理(几个变化、通过几题、几条待办),可以放。 +不放:报告和答案里的数(金额、比例、差值、期望值),表名、列名、取值(码值、样例行),SQL,按运行数据渲染出来的句子。 +接收端是群机器人、外部系统,消息出了这个服务就不归遮罩管了。 """ from __future__ import annotations import asyncio import logging from collections.abc import Coroutine +from dataclasses import dataclass from typing import Any from sqlalchemy import select @@ -26,12 +40,60 @@ from app.notify.core import Message, Outcome, host_of logger = logging.getLogger(__name__) -#: 可以订阅的事件 -EVENTS = ("task.opened", "run.finished", "run.failed", "action.unknown", "review.done") -EVENT_LABEL = {"task.opened": "有待办派给我", "run.finished": "实例完成", "run.failed": "实例失败", - "action.unknown": "写入结果未知", - # 个人应用提交审核之后,搭建者发布了或退回了(docs/design/normal-user-apps.md N7) - "review.done": "我提交审核的应用有结果"} +@dataclass(frozen=True) +class Event: + """一个可订阅的通知事件(见模块说明「事件只在这里登记」)。""" + + #: 界面上的叫法:和前端 NOTIFY_TEXT.eventLabel 同一句 + label: str + #: 推给哪几条路(_channels):global 全局渠道自己订阅,user 相关的人自己的个人渠道,app 应用版本 spec.notify 的订阅。 + #: 空的:登记了、还没有推送 + scopes: tuple[str, ...] + + +_EVERY = ("global", "user", "app") +#: 渠道范围在说法里怎么叫(同前端 NOTIFY_TEXT.scopes) +SCOPE_TEXT = {"global": "全局", "user": "个人", "app": "应用"} + +#: 可以订阅的事件,只在这里登记 +EVENTS: dict[str, Event] = { + # 待办派出、改派、升级、催办(_AS):全局渠道、派给的人自己的个人渠道、应用的订阅 + "task.opened": Event("待办打开", _EVERY), + # 应用实例结束、失败:个人渠道是发起人自己的(04-对外集成与触达 B1) + "run.finished": Event("运行结束", _EVERY), + "run.failed": Event("运行失败", _EVERY), + # 写入外部系统的结果未知:个人渠道是核实待办派给的人 + "action.unknown": Event("动作结果未知", _EVERY), + # 个人应用提交审核之后,搭建者发布了或退回了(docs/design/normal-user-apps.md N7):发给提交人,不归哪个应用 + "review.done": Event("我提交审核的应用有结果", ("global", "user")), + # ---- 本轮登记、还没有推送(总方案 X6):实现推送的那一块只改自己这一行的 scopes,消息照模块说明的规矩 ---- + # 数据源有要处理的结构 / 取值变化(03 B3):只推 severity 为 action 的,按源汇总;源名、各级别条数、链接 + "source.changed": Event("数据源有变化要处理", ()), + # 口径升版后召回重算,数真变了(02 第 7 项):答案的主人有 recall 待办;口径名、版本、链接,不放新旧值和差值 + "ledger.recall": Event("口径升版,答案的数变了", ()), + # 定时评测有题从通过变成不通过 / 评测没跑完(01 第 15 项):题集名、通过数、退步题数、链接;不放期望值和答案里的数 + "eval.regressed": Event("评测有退步", ()), + "eval.failed": Event("评测失败", ()), + # 每天一条待办汇总(04 B3):只推个人渠道;条数、最早的时限、最多 5 条(节点在图上的名字)、去待办箱的链接 + "task.digest": Event("每天的待办汇总", ()), + # 访问密钥到期前 7 天、1 天各一次(04 B3):个人密钥推本人,服务账号的推全局渠道;密钥名、到期日、链接 + "key.expiring": Event("访问密钥快到期", ()), +} +EVENT_LABEL = {name: event.label for name, event in EVENTS.items()} + + +def subscribe_problem(event: str, scope: str) -> str | None: + """范围是 scope 的渠道能不能订阅 event:不能的回一句为什么(接口原样回 422),能的是 None。""" + spec = EVENTS.get(event) + if spec is None: + offered = "、".join(e.label for e in EVENTS.values() if scope in e.scopes) + return f"不认识的通知事件:{event}。可选:{offered}" + if not spec.scopes: + return f"「{spec.label}」的通知还没有推送,暂时不能订阅" + if scope not in spec.scopes: + return f"「{spec.label}」不推给范围是「{SCOPE_TEXT.get(scope, scope)}」的渠道" + return None + #: 这几种也是「有一条待办要你处理」,按 task.opened 的订阅推 _AS = {"task.reassigned": "task.opened", "task.escalated": "task.opened", "task.reminded": "task.opened"} _TASK_HEAD = {"task.opened": "新的待办", "task.reassigned": "待办已改派给你", "task.escalated": "待办已超时,升级处理", @@ -98,8 +160,11 @@ async def _base_url(session: Any) -> str | None: async def _channels(session: Any, event: str, run: Run | None, users: list[str]) -> list[NotifyChannel]: wanted = _AS.get(event, event) + if (registered := EVENTS.get(wanted)) is None: + raise ValueError(f"通知事件 {wanted} 没有登记:先在 notify/service.EVENTS 登记,再推送") + paths = registered.scopes found: dict[str, NotifyChannel] = {} - if run is not None and run.app_id and run.app_version is not None: + if "app" in paths and run is not None and run.app_id and run.app_version is not None: row = (await session.execute(select(AppVersion.spec, AppVersion.bindings).where( AppVersion.app_id == run.app_id, AppVersion.version == run.app_version))).first() spec, bindings = (row[0], row[1]) if row is not None else ({}, {}) @@ -115,11 +180,12 @@ async def _channels(session: Any, event: str, run: Run | None, users: list[str]) for row in (await session.execute(select(NotifyChannel).where( NotifyChannel.id.in_(subscribed), NotifyChannel.enabled.is_(True)))).scalars(): found[row.id] = row - for row in (await session.execute(select(NotifyChannel).where( - NotifyChannel.scope == "global", NotifyChannel.enabled.is_(True)))).scalars(): - if wanted in (row.events or []): - found.setdefault(row.id, row) - if users: + if "global" in paths: + for row in (await session.execute(select(NotifyChannel).where( + NotifyChannel.scope == "global", NotifyChannel.enabled.is_(True)))).scalars(): + if wanted in (row.events or []): + found.setdefault(row.id, row) + if "user" in paths and users: owners = list((await session.execute(select(User.id).where(User.username.in_(users)))).scalars()) if owners: for row in (await session.execute(select(NotifyChannel).where( diff --git a/backend/tests/test_notify_events.py b/backend/tests/test_notify_events.py new file mode 100644 index 00000000..211d4dc1 --- /dev/null +++ b/backend/tests/test_notify_events.py @@ -0,0 +1,164 @@ +"""通知事件的登记表(app/notify/service.EVENTS;总方案 X6)。 + +本轮新增的六个事件(数据源变化、口径召回、评测退步 / 失败、待办汇总、密钥到期)在第 1 波一次登记好:名字、界面上的叫法、 +推给哪几条路都在 EVENTS 一处,前端的叫法在 lib/terms.ts 的 NOTIFY_TEXT 一处。第 2、3 波实现推送的那一块只改自己那一行 +的范围,不再去改同一个元组、同一张叫法表(几块并行改同一处必然冲突)。这里守: + +- 登记表:六个事件都在,叫法不空;推给哪几条路是空的就是「登记了、还没有推送」——接口不收这种订阅、GET /api/notify/events + 照实给空的 scopes,设置页和应用的通知里都不列(勾了收不到就是「看着生效、其实没生效」,个人渠道「实例完成」的老问题); +- 前后端对照:terms.ts 的 eventLabel 和 EVENTS 一一对应、逐字一致;投递记录才有的事件(改派、升级、催办、测试消息)另有一张 + 叫法表,和服务端 _AS 对上(写法同 test_chat_turn_policy.py,两边一改就对不上); +- 推给哪几条路是真的:_channels 只走事件登记了的路;没登记的事件推不出去,直接报错; +- 订阅的范围不对(全局渠道勾只推个人的事件)拒收,但只核对这次新勾的:以前存下的照旧,开关、改名不会因此 422。 + +渠道名、地址都是虚构的。 +""" +from __future__ import annotations + +import re +from pathlib import Path + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import delete + +from app.core.crypto import encrypt +from app.db.base import SessionLocal +from app.db.models import NotifyChannel +from app.notify import service + +TERMS_TS = Path(__file__).resolve().parents[2] / "frontend" / "src" / "lib" / "terms.ts" +URL = "https://hooks.example.com/agentlab/notify-events-5d1c" + +#: 本轮登记的六个(总方案 X6):都还没有推送 +THIS_ROUND = ("source.changed", "ledger.recall", "eval.regressed", "eval.failed", "task.digest", "key.expiring") + + +@pytest.fixture +async def client(): + from app.main import app + + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: + yield c + async with SessionLocal() as session: + await session.execute(delete(NotifyChannel).where(NotifyChannel.name.like("事件登记-%"))) + await session.commit() + + +# -------------------------------------------------------------------------- +# 登记表 +# -------------------------------------------------------------------------- + + +def test_this_rounds_events_are_registered_once_and_not_pushed_yet(): + for name in THIS_ROUND: + assert name in service.EVENTS, f"{name} 没有登记" + assert service.EVENTS[name].label, name + assert service.EVENTS[name].scopes == (), f"{name} 还没有推送:不该有人订阅得到" + assert len({e.label for e in service.EVENTS.values()}) == len(service.EVENTS), "两个事件叫成了同一句" + assert service.EVENT_LABEL == {k: v.label for k, v in service.EVENTS.items()} + + +def test_events_that_are_pushed_today_keep_their_audience(): + """现有五个事件推给哪几条路,照 _channels 和各个 notify_* 现在的做法登记(行为不变)。""" + every = {"global", "user", "app"} + assert {k: set(v.scopes) for k, v in service.EVENTS.items() if v.scopes} == { + "task.opened": every, "run.finished": every, "run.failed": every, "action.unknown": every, + # 发给提交人自己(和订阅了它的全局渠道),不归哪个应用 + "review.done": {"global", "user"}, + } + for event in service.EVENTS.values(): + assert set(event.scopes) <= every + + +def _object_block(source: str, name: str) -> str: + """terms.ts 里 NOTIFY_TEXT 下面名叫 name 的那个对象字面量(到配对的右花括号为止)。""" + head = source.index("export const NOTIFY_TEXT = {") + start = source.index(f"{name}: {{", head) + len(name) + 2 + depth, i = 1, start + 1 + while depth: + depth += {"{": 1, "}": -1}.get(source[i], 0) + i += 1 + return source[start:i] + + +def _entries(block: str) -> dict[str, str]: + return dict(re.findall(r"'?([a-z]+(?:\.[a-z_]+)?)'?:\s*'([^']*)'", block)) + + +def test_frontend_labels_match_the_registry_word_for_word(): + source = TERMS_TS.read_text(encoding="utf-8") + labels = _entries(_object_block(source, "eventLabel")) + assert labels == service.EVENT_LABEL, "设置页的叫法和服务端登记的对不上(一种说法)" + delivery = _entries(_object_block(source, "deliveryEventLabel")) + assert set(delivery) == set(service._AS) | {"test"}, "投递记录里会出现的事件都要有叫法" + assert not set(delivery) & set(labels) + + +# -------------------------------------------------------------------------- +# 接口 +# -------------------------------------------------------------------------- + + +async def test_events_endpoint_says_who_receives_each_event(client): + rows = (await client.get("/api/notify/events")).json() + assert [r["event"] for r in rows] == list(service.EVENTS) + by = {r["event"]: r for r in rows} + assert by["eval.regressed"] == {"event": "eval.regressed", "label": "评测有退步", "scopes": []} + assert by["review.done"]["scopes"] == ["global", "user"] + + +async def test_events_not_pushed_yet_cannot_be_subscribed(client): + resp = await client.post("/api/notify/channels", json={ + "name": "事件登记-评测", "url": URL, "events": ["task.opened", "eval.regressed"]}) + assert resp.status_code == 422, resp.text + detail = resp.json()["detail"] + assert "评测有退步" in detail and "还没有推送" in detail + unknown = await client.post("/api/notify/channels", json={"name": "事件登记-未知", "url": URL, "events": ["nope"]}) + assert unknown.status_code == 422 + assert "评测有退步" not in unknown.json()["detail"], "可选的里面不列还没有推送的" + assert "待办打开" in unknown.json()["detail"] + + +async def test_scope_mismatch_is_refused_only_for_newly_ticked_events(client): + refused = await client.post("/api/notify/channels", json={ + "name": "事件登记-应用", "scope": "app", "url": URL, "events": ["review.done"]}) + assert refused.status_code == 422, refused.text + assert "我提交审核的应用有结果" in refused.json()["detail"] and "应用" in refused.json()["detail"] + # 以前存下的(当时界面对哪种渠道都列这一项):开关、改名照旧,不因此 422 + async with SessionLocal() as session: + row = NotifyChannel(name="事件登记-旧", scope="app", url=encrypt(URL), events=["task.opened", "review.done"]) + session.add(row) + await session.commit() + channel_id = row.id + toggled = await client.patch(f"/api/notify/channels/{channel_id}", json={"enabled": False}) + assert toggled.status_code == 200, toggled.text + assert toggled.json()["events"] == ["task.opened", "review.done"] + again = await client.patch(f"/api/notify/channels/{channel_id}", json={"events": ["review.done", "run.failed"]}) + assert again.status_code == 200, again.text + added = await client.patch(f"/api/notify/channels/{channel_id}", json={"events": ["review.done", "eval.failed"]}) + assert added.status_code == 422 and "评测失败" in added.json()["detail"] + + +# -------------------------------------------------------------------------- +# 推送只走登记了的路 +# -------------------------------------------------------------------------- + + +async def test_channels_only_walk_the_paths_the_event_is_registered_for(monkeypatch): + monkeypatch.setitem(service.EVENTS, "demo.personal", service.Event("只推个人的演示事件", ("user",))) + async with SessionLocal() as session: + row = NotifyChannel(name="事件登记-全局", scope="global", url=encrypt(URL), + events=["demo.personal", "task.opened", "eval.failed"]) + session.add(row) + await session.commit() + try: + ids = lambda found: [c.id for c in found] # noqa: E731 + assert row.id not in ids(await service._channels(session, "demo.personal", None, [])), "全局渠道这条路没登记" + assert row.id in ids(await service._channels(session, "task.opened", None, [])) + assert await service._channels(session, "eval.failed", None, []) == [], "还没有推送的:谁都不推" + with pytest.raises(ValueError, match="没有登记"): + await service._channels(session, "demo.unregistered", None, []) + finally: + await session.delete(row) + await session.commit() diff --git a/frontend/src/api/capabilities.ts b/frontend/src/api/capabilities.ts index 3f2af1bd..08fde911 100644 --- a/frontend/src/api/capabilities.ts +++ b/frontend/src/api/capabilities.ts @@ -5,6 +5,7 @@ import type { CatalogReviewAction, CatalogSource, CatalogStatus } from '../types' import type { CapabilityEffect, CapabilityReviewOutcome, CapabilityReviewRow, CapabilityRow, EndpointRow, NotifyChannelRow, + NotifyEventRow, } from '../typesApp' import { del, get, patch, post, put, qs, type RequestOptions } from './http' @@ -128,4 +129,6 @@ export const notify = { removeChannel: (id: string) => del(`/notify/channels/${encodeURIComponent(id)}`), testChannel: (id: string) => post<{ ok: boolean; message: string }>(`/notify/channels/${encodeURIComponent(id)}/test`), deliveries: (params?: { channel_id?: string; limit?: number }) => get<{ items: any[] }>(`/notify/deliveries${qs(params)}`), + /** 登记的事件和推给哪几条路:哪种渠道能订阅哪些由服务端说,界面不自己猜 */ + events: () => get('/notify/events'), } diff --git a/frontend/src/lib/terms.ts b/frontend/src/lib/terms.ts index 0beb188e..e209176a 100644 --- a/frontend/src/lib/terms.ts +++ b/frontend/src/lib/terms.ts @@ -5396,13 +5396,26 @@ export const NOTIFY_TEXT = { scope: '范围', scopes: { global: '全局', app: '应用', user: '个人' } as Record, events: '订阅的事件', + /** + * 通知事件的叫法:和服务端 notify/service.EVENTS 一一对应、逐字一致(test_notify_events 对照),事件只在那里登记(总方案 + * X6)。哪种渠道能订阅哪些、推没推,由服务端说(GET /api/notify/events 的 scopes):本轮登记了、还没有推送的几个这里 + * 先有叫法,界面上不列,实现推送的那一块不用再改这张表 + */ eventLabel: { - 'task.opened': '待办打开', 'task.escalated': '待办升级', 'task.expired': '待办超时', 'task.resolved': '待办处理完', - 'action.unknown': '动作结果未知', 'action.failed': '动作失败', 'action.confirmed': '动作已生效', - 'run.failed': '运行失败', 'run.finished': '运行结束', + 'task.opened': '待办打开', 'run.finished': '运行结束', 'run.failed': '运行失败', 'action.unknown': '动作结果未知', // 个人应用提交审核有了结果(发布了或退回了),通知提交人:只对个人渠道、全局渠道有意义(服务端 notify/service.notify_review) 'review.done': '我提交审核的应用有结果', + 'source.changed': '数据源有变化要处理', 'ledger.recall': '口径升版,答案的数变了', + 'eval.regressed': '评测有退步', 'eval.failed': '评测失败', + 'task.digest': '每天的待办汇总', 'key.expiring': '访问密钥快到期', } as Record, + /** 投递记录里才有的事件:改派、升级、催办按「待办打开」的订阅推,记录里照实写是哪一种(服务端 notify/service._AS) */ + deliveryEventLabel: { + 'task.reassigned': '待办改派', 'task.escalated': '待办升级', 'task.reminded': '待办催办', test: '测试消息', + } as Record, + /** 渠道编辑框、应用的通知:可订阅的事件还没取到 / 没取到 */ + eventsLoading: '正在读取可订阅的事件…', + eventsError: '没能读取可订阅的事件,请刷新页面后重试', enabled: '启用', signed: '已签名', test: '发送测试消息', diff --git a/frontend/src/pages/apps/edit/AccessSections.tsx b/frontend/src/pages/apps/edit/AccessSections.tsx index d29cf615..9791ee04 100644 --- a/frontend/src/pages/apps/edit/AccessSections.tsx +++ b/frontend/src/pages/apps/edit/AccessSections.tsx @@ -8,7 +8,7 @@ import { import { PrincipalPicker, type Principal as Picked } from '../../../components/PrincipalPicker' import { APP_EDITOR_TEXT as T, GRANT_ROLE_HINT, GRANT_ROLE_LABEL, NOTIFY_TEXT } from '../../../lib/terms' import { useLoginOn } from '../../../store/auth' -import type { AppGrant, GrantRole, NotifyChannelRow } from '../../../typesApp' +import type { AppGrant, GrantRole, NotifyChannelRow, NotifyEventRow } from '../../../typesApp' import { applyAppOp } from './appOps' import { useEditor } from './context' @@ -343,9 +343,16 @@ export function NotifySection() { const { draft, setDraft } = useEditor() const [channels, setChannels] = useState(null) useEffect(() => { api.notify.channels().then(({ items }) => setChannels(items)).catch(() => setChannels([])) }, []) + const [registry, setRegistry] = useState(null) + const [registryFailed, setRegistryFailed] = useState(false) + useEffect(() => { api.notify.events().then(setRegistry).catch(() => setRegistryFailed(true)) }, []) const set = (notify: typeof draft.notify) => setDraft((s) => ({ ...s, notify })) - // 「我提交审核的应用有结果」是发给提交人的,不归哪个应用:应用的通知里不列 - const events = Object.keys(NOTIFY_TEXT.eventLabel).filter((e) => e !== 'review.done') + // 应用能订阅哪些由服务端说(notify/service.EVENTS 推给「应用的订阅」这条路的):「我提交审核的应用有结果」发给提交人、 + // 登记了还没推送的都不列。这条订阅里已经勾着的照样列出来(以前界面列过、其实推不到的也在内),看得到、能取消 + const appEvents = new Set((registry ?? []).filter((r) => r.scopes.includes('app')).map((r) => r.event)) + const known = Object.keys(NOTIFY_TEXT.eventLabel) + const eventsOf = (subscribed: string[]) => [...known.filter((e) => appEvents.has(e) || subscribed.includes(e)), + ...subscribed.filter((e) => !known.includes(e))] return (
@@ -372,12 +379,12 @@ export function NotifySection() { set(draft.notify.filter((_, j) => j !== i))} />
- {events.map((ev) => ( + {eventsOf(n.events).map((ev) => ( ))}
@@ -385,6 +392,7 @@ export function NotifySection() { ))} )} + {registryFailed &&

{NOTIFY_TEXT.eventsError}

} ) } diff --git a/frontend/src/pages/settings/NotifyTab.tsx b/frontend/src/pages/settings/NotifyTab.tsx index d30ffda5..6aeca83d 100644 --- a/frontend/src/pages/settings/NotifyTab.tsx +++ b/frontend/src/pages/settings/NotifyTab.tsx @@ -7,7 +7,7 @@ import { import { formatDateTime } from '../../lib/format' import { NOTIFY_TEXT as T, SETTINGS_ROLE_TEXT } from '../../lib/terms' import { useAtLeast } from '../../store/auth' -import type { NotifyChannelRow } from '../../typesApp' +import type { NotifyChannelRow, NotifyEventRow } from '../../typesApp' /* * 设置 → 通知(A4 第 7 条):待办、动作的事件推送到哪些地址。格式只有 Webhook 的四种(Q6),发送核心和定时任务的 @@ -120,7 +120,7 @@ function Deliveries() {
{rows.map((d) => (
- {T.eventLabel[d.event] ?? d.event} + {T.deliveryEventLabel[d.event] ?? T.eventLabel[d.event] ?? d.event} {d.error ?? (d.http_status ? `HTTP ${d.http_status}` : '')} {d.status === 'ok' ? '已送达' : d.status === 'failed' ? '失败' : d.status} @@ -144,6 +144,13 @@ function ChannelEditor({ row, onClose, onSaved }: { url: '', secret: '', events: row?.events ?? ['task.opened', 'action.unknown'], }) const [busy, setBusy] = useState(false) + // 列哪些事件由服务端说(notify/service.EVENTS 的 scopes):这种范围的渠道收得到的才列,登记了还没推送的不列(勾了收不到)。 + // 已经订阅着的、刚勾上的照样列出来,看得到、能取消 + const [registry, setRegistry] = useState(null) + const [registryFailed, setRegistryFailed] = useState(false) + useEffect(() => { api.notify.events().then(setRegistry).catch(() => setRegistryFailed(true)) }, []) + const offered = EVENTS.filter((ev) => form.events.includes(ev) || row?.events.includes(ev) + || registry?.some((r) => r.event === ev && r.scopes.includes(form.scope))) const save = async () => { setBusy(true) try { @@ -206,15 +213,17 @@ function ChannelEditor({ row, onClose, onSaved }: {
{T.events} -
- {EVENTS.map((ev) => ( -
diff --git a/frontend/src/typesApp.ts b/frontend/src/typesApp.ts index 949d192a..292b4ce6 100644 --- a/frontend/src/typesApp.ts +++ b/frontend/src/typesApp.ts @@ -695,6 +695,16 @@ export interface NotifyChannelRow { enabled: boolean } +/** + * 登记的通知事件(GET /api/notify/events,服务端 notify/service.EVENTS,总方案 X6)。scopes 是推给哪几条路:global + * 全局渠道自己订阅,user 相关的人自己的个人渠道,app 应用版本里的订阅;空的是登记了、还没有推送的,界面上不列 + */ +export interface NotifyEventRow { + event: string + label: string + scopes: ('global' | 'user' | 'app')[] +} + // --------------------------------------------------------------------------- // 运行来源(§2.10 X3)与助手查看(§2.9 L2) // --------------------------------------------------------------------------- diff --git a/scripts/check-capabilities.mjs b/scripts/check-capabilities.mjs index af0b3955..abcbcfc1 100644 --- a/scripts/check-capabilities.mjs +++ b/scripts/check-capabilities.mjs @@ -299,6 +299,31 @@ await section('设置:身份、通知、审计', async () => { check('审计照实标自报署名', await row.count() === 1 && (await row.innerText()).includes('自报署名')) }) +await section('设置 → 通知:可订阅的事件照服务端登记列(总方案 X6)', async () => { + // 列表从真后端的 GET /api/notify/events 来(GET 放行):这种范围的渠道收得到的才列;从来推不到的(以前列着、一勾就 422 + // 的「待办升级」「动作已生效」……)和登记了还没推送的(评测、召回、待办汇总……)都不列 + const { page, errors } = await open('/settings/notify') + await page.getByRole('button', { name: '添加渠道' }).first().click() + const dlg = page.locator('[role="dialog"]') + const listed = () => dlg.locator('[data-notify-event]').evaluateAll((els) => els.map((e) => e.getAttribute('data-notify-event'))) + const scope = async (value) => { + await dlg.getByLabel('范围', { exact: true }).selectOption(value) + return waitFor(page, async () => await dlg.locator(`[data-notify-events="${value}"]`).count() === 1) + } + const every = ['task.opened', 'run.finished', 'run.failed', 'action.unknown'] + check('全局渠道:推给全局渠道的五项', await waitFor(page, async () => await dlg.locator('[data-notify-events="global"]').count() === 1) + && JSON.stringify(await listed()) === JSON.stringify([...every, 'review.done']), JSON.stringify(await listed())) + const text = await dlg.innerText() + check('从来推不到的不列', !['待办升级', '待办超时', '待办处理完', '动作失败', '动作已生效'].some((t) => text.includes(t)), text) + check('登记了还没推送的不列', !['评测有退步', '评测失败', '每天的待办汇总', '访问密钥快到期', '数据源有变化要处理', '口径升版,答案的数变了'] + .some((t) => text.includes(t)), text) + check('应用的渠道:不列只发给提交人的「我提交审核的应用有结果」', await scope('app') + && JSON.stringify(await listed()) === JSON.stringify(every), JSON.stringify(await listed())) + check('个人渠道:五项都列', await scope('user') && JSON.stringify(await listed()) === JSON.stringify([...every, 'review.done']), + JSON.stringify(await listed())) + check('没有运行时报错', errors.length === 0, errors.slice(0, 2).join(' | ')) +}) + await section('能力:待审阅复用数据目录的审阅队列,成批确认逐项带能力的治理版本', async () => { const { page, state, errors } = await open('/tools/capabilities?view=review') check('左栏换成待审阅视图', await page.locator('[data-capability-views="review"]').count() === 1)