feat(skills/notifications): 多租户阶段 4 — 测试 + 前端

后端:
tests/test_skills_multitenancy.py(12 个用例,全部通过)
- SkillStore: 可见性 / 全局重名拒绝 / owner-only update+delete /
  admin override / ensure_legacy 仅补 NULL owner
- 路由助手 _get_editable_skill_or_raise / _get_owned_skill_or_raise
  的 owner / admin / 403 / 404 分流
- cascade_skill_unpublished_or_deleted:
  · unpublish 同时扫两个用户的 agent,剥掉 skill;自己改自己不发
    通知,其他人收 agent_skill_removed
  · admin_takedown 额外给 skill owner 发 skill_taken_down
- NotificationStore CRUD + unread_count + 跨用户隔离
- 同步版 apply_automatic_transitions 用户隔离:A 跑 curator 不
  动 B 的 skill;curator_log per-user 分桶

前端 — core/notifications/{types,api,hooks,index}.ts
- 类型对齐 routers/notifications.py 的 NotificationItem
- listNotifications / getUnreadCount / markRead / markAllRead /
  deleteNotification
- useNotifications / useUnreadCount(refetchInterval=30s) / mutation 钩子

前端 — components/workspace/notification-bell.tsx
- 顶部铃铛图标 + 未读红点(>99 显示 99+)
- 复用 DropdownMenu 作为弹层(项目暂无 Popover 原语)
- 列表项:未读蓝点 + 标题 + body + 相对时间,悬停露出删除按钮
- 标记单条已读 / 全部已读 / 删除
- 接入 workspace-nav-menu.tsx,作为 SidebarMenuItem 放在设置入口上方

前端 — Skill 多租户字段
- core/skills/type.ts 加 owner_user_id / published / builtin
- core/skills/api.ts 加 setSkillPublished + deleteCustomSkill
- core/skills/hooks.ts 加 useSetSkillPublished + useDeleteCustomSkill

前端 — settings/skill-settings-page.tsx
- 抽出 SkillRow 子组件,每项渲染 owner badge(内置/我的/来自他人/
  已发布),样式抄自 agent-card.tsx 的 isBuiltin/isOwned/isFromOthers
- canManage = isOwned || isAdmin;canTogglePublish 同上但排除内置
- 发布/取消发布按钮(Eye / EyeOff),调用 setSkillPublished
- 删除按钮 + 二次确认 Dialog,调用 deleteCustomSkill
- 启用开关保持原样

前端 — i18n
- types.ts: 新增 NotificationsTranslations + Translations.notifications;
  settings.skills 加 badgeBuiltin/badgeMine/badgeFromOthers(+Title) /
  badgePublished(+Title) / publishAction / unpublishAction /
  publishSuccess / unpublishSuccess / deleteAction / deleteConfirm /
  deleteSuccess
- zh-CN.ts / en-US.ts 同步补齐对应文案

验证
- PYTHONPATH=. uv run pytest tests/test_skills_multitenancy.py -v →
  12 passed in 2.08s
- 与现有 test_agents_backend / test_skill_evolution_runtime /
  test_skills_install_upload 并行跑:41 通过 + 1 个 pre-existing 失败
  (test_validate_rejects_missing_skill_md 期望 "SKILL.md" 但收到
  "Skill archive is empty",与本期改动无关)
- pnpm typecheck:本次新增/修改的文件零新增错误;剩余报错全部为
  pre-existing 的 next/link、next/navigation 别名声明缺失、
  workspace-nav-menu.tsx 的 SettingsSection 类型不匹配、nextra
  缺失、markdown-docx 第三方库等

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
xuhdandClaude Opus 4.7 committed 2026-05-14 17:35:02 +08:00
1 parent 4ef96c7930
commit 99febda256
14 files changed
+1133 -21

No files matched your search

@@ -439,6 +439,20 @@ export const enUS: Translations = {
emptyDescription:
"Put your agent skill folders under the `/skills/custom` folder under the root folder of CM Assistant.",
emptyButton: "Create Your First Skill",
badgeBuiltin: "Built-in",
badgeMine: "Mine",
badgeFromOthers: "From others",
badgeFromOthersTitle: "Owned by user {user_id}",
badgePublished: "Published",
badgePublishedTitle: "Visible to all users",
publishAction: "Publish",
unpublishAction: "Unpublish",
publishSuccess: "Skill published",
unpublishSuccess: "Skill unpublished",
deleteAction: "Delete skill",
deleteConfirm:
"Delete skill \"{name}\"? This cannot be undone and the skill will be removed from any agent that referenced it.",
deleteSuccess: "Skill deleted",
installDialog: {
title: "Install skill",
dropHint: "Drop a .zip or .skill archive here, or",
@@ -539,4 +553,13 @@ export const enUS: Translations = {
emptyDescription: "Credits and acknowledgements will show here.",
},
},
notifications: {
title: "Notifications",
bellAria: "Open notifications",
unreadShort: "{count} unread",
markAllRead: "Mark all read",
empty: "No notifications",
deleteAria: "Delete notification",
},
};
@@ -1,5 +1,14 @@
import type { LucideIcon } from "lucide-react";
export interface NotificationsTranslations {
title: string;
bellAria: string;
unreadShort: string;
markAllRead: string;
empty: string;
deleteAria: string;
}
export interface Translations {
// Locale meta
locale: {
@@ -359,6 +368,19 @@ export interface Translations {
emptyTitle: string;
emptyDescription: string;
emptyButton: string;
badgeBuiltin: string;
badgeMine: string;
badgeFromOthers: string;
badgeFromOthersTitle: string;
badgePublished: string;
badgePublishedTitle: string;
publishAction: string;
unpublishAction: string;
publishSuccess: string;
unpublishSuccess: string;
deleteAction: string;
deleteConfirm: string;
deleteSuccess: string;
installDialog: {
title: string;
dropHint: string;
@@ -446,4 +468,7 @@ export interface Translations {
emptyDescription: string;
};
};
// In-app notification inbox (bell in the workspace sidebar)
notifications: NotificationsTranslations;
}
@@ -420,6 +420,19 @@ export const zhCN: Translations = {
emptyDescription:
"将你的 Agent Skill 文件夹放在 CM 助手 根目录下的 `/skills/custom` 文件夹中。",
emptyButton: "创建你的第一个技能",
badgeBuiltin: "内置",
badgeMine: "我的",
badgeFromOthers: "来自他人",
badgeFromOthersTitle: "来自用户 {user_id}",
badgePublished: "已发布",
badgePublishedTitle: "该技能已对所有用户可见",
publishAction: "发布",
unpublishAction: "取消发布",
publishSuccess: "已发布",
unpublishSuccess: "已取消发布",
deleteAction: "删除技能",
deleteConfirm: "确认删除技能 “{name}”?该操作不可恢复,且会从引用它的所有专家中自动移除。",
deleteSuccess: "技能已删除",
installDialog: {
title: "安装技能",
dropHint: "拖拽 .zip 或 .skill 文件到此处,或者",
@@ -512,4 +525,13 @@ export const zhCN: Translations = {
emptyDescription: "相关的致谢信息会展示在这里。",
},
},
notifications: {
title: "通知",
bellAria: "打开通知",
unreadShort: "{count} 条未读",
markAllRead: "全部已读",
empty: "暂无通知",
deleteAria: "删除通知",
},
};
@@ -0,0 +1,60 @@
import { apiFetch } from "@/core/api";
import { getBackendBaseURL } from "@/core/config";
import type {
NotificationItem,
NotificationListResponse,
NotificationUnreadCountResponse,
} from "./types";
async function parseDetail(res: Response, fallback: string): Promise<Error> {
const data = (await res.json().catch(() => ({}))) as { detail?: unknown };
const detail = typeof data.detail === "string" && data.detail ? data.detail : null;
return new Error(detail ?? `${fallback} (HTTP ${res.status})`);
}
export async function listNotifications(
options: { unreadOnly?: boolean; limit?: number } = {},
): Promise<NotificationItem[]> {
const params = new URLSearchParams();
if (options.unreadOnly) params.set("unread_only", "true");
if (options.limit) params.set("limit", String(options.limit));
const query = params.toString();
const url = `${getBackendBaseURL()}/api/notifications${query ? `?${query}` : ""}`;
const res = await apiFetch(url);
if (!res.ok) throw await parseDetail(res, "Failed to list notifications");
const data = (await res.json()) as NotificationListResponse;
return data.items;
}
export async function getUnreadCount(): Promise<number> {
const res = await apiFetch(`${getBackendBaseURL()}/api/notifications/unread_count`);
if (!res.ok) throw await parseDetail(res, "Failed to load unread count");
const data = (await res.json()) as NotificationUnreadCountResponse;
return data.unread;
}
export async function markNotificationRead(id: string): Promise<void> {
const res = await apiFetch(
`${getBackendBaseURL()}/api/notifications/${encodeURIComponent(id)}/read`,
{ method: "POST" },
);
if (!res.ok) throw await parseDetail(res, "Failed to mark notification read");
}
export async function markAllNotificationsRead(): Promise<number> {
const res = await apiFetch(`${getBackendBaseURL()}/api/notifications/read_all`, {
method: "POST",
});
if (!res.ok) throw await parseDetail(res, "Failed to mark all read");
const data = (await res.json()) as { updated: number };
return data.updated;
}
export async function deleteNotification(id: string): Promise<void> {
const res = await apiFetch(
`${getBackendBaseURL()}/api/notifications/${encodeURIComponent(id)}`,
{ method: "DELETE" },
);
if (!res.ok) throw await parseDetail(res, "Failed to delete notification");
}
@@ -0,0 +1,62 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
deleteNotification,
getUnreadCount,
listNotifications,
markAllNotificationsRead,
markNotificationRead,
} from "./api";
const ROOT_KEY = ["notifications"] as const;
const COUNT_KEY = [...ROOT_KEY, "unread-count"] as const;
export function useNotifications(options: { limit?: number; unreadOnly?: boolean } = {}) {
const { limit = 20, unreadOnly = false } = options;
return useQuery({
queryKey: [...ROOT_KEY, "list", { limit, unreadOnly }],
queryFn: () => listNotifications({ limit, unreadOnly }),
});
}
export function useUnreadCount(refetchInterval = 30000) {
return useQuery({
queryKey: COUNT_KEY,
queryFn: () => getUnreadCount(),
refetchInterval,
// Keep the badge fresh when the user comes back to the tab without
// waiting for the next interval tick.
refetchOnWindowFocus: true,
});
}
function useInvalidateNotifications() {
const queryClient = useQueryClient();
return () => {
void queryClient.invalidateQueries({ queryKey: ROOT_KEY });
};
}
export function useMarkNotificationRead() {
const invalidate = useInvalidateNotifications();
return useMutation({
mutationFn: (id: string) => markNotificationRead(id),
onSuccess: invalidate,
});
}
export function useMarkAllNotificationsRead() {
const invalidate = useInvalidateNotifications();
return useMutation({
mutationFn: () => markAllNotificationsRead(),
onSuccess: invalidate,
});
}
export function useDeleteNotification() {
const invalidate = useInvalidateNotifications();
return useMutation({
mutationFn: (id: string) => deleteNotification(id),
onSuccess: invalidate,
});
}
@@ -0,0 +1,3 @@
export * from "./api";
export * from "./hooks";
export * from "./types";
@@ -0,0 +1,18 @@
export interface NotificationItem {
id: string;
user_id: string;
type: string;
title: string;
body: string;
payload: Record<string, unknown>;
read: boolean;
created_at: string | null;
}
export interface NotificationListResponse {
items: NotificationItem[];
}
export interface NotificationUnreadCountResponse {
unread: number;
}
+34
View File
@@ -110,3 +110,37 @@ export async function installSkillUpload(
}
return response.json() as Promise<InstallSkillResponse>;
}
export interface SetSkillPublishedResponse {
name: string;
owner_user_id: string | null;
published: boolean;
}
export async function setSkillPublished(
skillName: string,
published: boolean,
): Promise<SetSkillPublishedResponse> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/skills/custom/${encodeURIComponent(skillName)}/published`,
{
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ published }),
},
);
if (!response.ok) {
throw await parseDetailedError(response, "Failed to update published state");
}
return response.json() as Promise<SetSkillPublishedResponse>;
}
export async function deleteCustomSkill(skillName: string): Promise<void> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/skills/custom/${encodeURIComponent(skillName)}`,
{ method: "DELETE" },
);
if (!response.ok) {
throw await parseDetailedError(response, "Failed to delete skill");
}
}
+33 -1
View File
@@ -1,6 +1,12 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { enableSkill, installSkillUpload, validateSkillUpload } from "./api";
import {
deleteCustomSkill,
enableSkill,
installSkillUpload,
setSkillPublished,
validateSkillUpload,
} from "./api";
import { loadSkills } from ".";
@@ -46,3 +52,29 @@ export function useInstallSkillUpload() {
},
});
}
export function useSetSkillPublished() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
skillName,
published,
}: {
skillName: string;
published: boolean;
}) => setSkillPublished(skillName, published),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["skills"] });
},
});
}
export function useDeleteCustomSkill() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (skillName: string) => deleteCustomSkill(skillName),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["skills"] });
},
});
}
+5
View File
@@ -4,4 +4,9 @@ export interface Skill {
category: string;
license: string;
enabled: boolean;
// Multitenancy fields — owner_user_id is null for built-in / public skills.
// ``builtin`` mirrors that nullness for explicit branching on the UI side.
owner_user_id?: string | null;
published?: boolean;
builtin?: boolean;
}