🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: notify topic comment participants (#17603)
AmAzing-de7e406bed11
diff --git a/apps/server/src/routers/lambda/__tests__/integration/topicComment.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/topicComment.integration.test.tsindex 795b34d5e61..ac30ecbbdfe 100644--- a/apps/server/src/routers/lambda/__tests__/integration/topicComment.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/topicComment.integration.test.ts@@ -277,7 +277,7 @@ describe('topicCommentRouter integration', () => {expect(notifyTopicCommentModeration).not.toHaveBeenCalled();});- it('notifies topic owners, reply authors, and newly mentioned active members once', async () => {+ it('notifies topic participants, message owners, reply authors, and mentions once', async () => {const member = topicCommentRouter.createCaller(context(memberId, workspaceId));const owner = topicCommentRouter.createCaller(context(ownerId, workspaceId));@@ -285,6 +285,34 @@ describe('topicCommentRouter integration', () => {await flushAfterResponse();expect(notifyTopicCommentActivity).not.toHaveBeenCalled();+ const adminMessageId = 'topic-comment-admin-message';+ await db.insert(messages).values([+ {+ content: 'admin participated',+ id: adminMessageId,+ role: 'user',+ topicId,+ userId: adminId,+ workspaceId,+ },+ {+ content: 'admin participated again',+ id: 'topic-comment-admin-message-2',+ role: 'assistant',+ topicId,+ userId: adminId,+ workspaceId,+ },+ {+ content: 'comment actor participated',+ id: 'topic-comment-member-message',+ role: 'user',+ topicId,+ userId: memberId,+ workspaceId,+ },+ ]);+const topLevel = await member.create({clientId: 'member-top-level',content: 'comment',@@ -294,7 +322,10 @@ describe('topicCommentRouter integration', () => {expect(notifyTopicCommentActivity).toHaveBeenLastCalledWith({actorUserId: memberId,commentId: topLevel.comment.id,- recipients: [{ kind: 'commented', userId: ownerId }],+ recipients: [+ { kind: 'commented', userId: ownerId },+ { kind: 'commented', userId: adminId },+ ],rootCommentId: topLevel.comment.id,topicId,workspaceId,@@ -304,6 +335,30 @@ describe('topicCommentRouter integration', () => {await flushAfterResponse();expect(notifyTopicCommentActivity).toHaveBeenCalledTimes(1);+ const anchored = await member.create({+ clientId: 'member-anchored',+ content: 'comment on a message with a mention',+ editorData: {+ root: {+ children: [{ metadata: { id: viewerId, type: 'member' }, type: 'mention' }],+ },+ },+ messageId: adminMessageId,+ topicId,+ });+ await flushAfterResponse();+ expect(notifyTopicCommentActivity).toHaveBeenLastCalledWith({+ actorUserId: memberId,+ commentId: anchored.comment.id,+ recipients: [+ { kind: 'commentedOnMessage', userId: adminId },+ { kind: 'mentioned', userId: viewerId },+ ],+ rootCommentId: anchored.comment.id,+ topicId,+ workspaceId,+ });+const reply = await member.create({clientId: 'member-reply',content: 'reply with mentions',diff --git a/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.test.ts b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.test.tsindex 7aeb3b61100..aa18e5f1485 100644--- a/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.test.ts+++ b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.test.ts@@ -2,8 +2,10 @@import { TRPCError } from '@trpc/server';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { RbacModel } from '@/database/models/rbac';import {assertCanPerformResourceAction,+ canPerformResourceAction,getResourceMeta,} from '@/server/services/resourcePermission';@@ -14,11 +16,13 @@ import {assertCanUseSessionTargets,assertCanUseTopicTargets,assertCanViewTopicTargets,+ filterUserIdsByTopicViewAccess,} from './conversationResourceGuard';import { getWorkspaceAgentParentGroupIds } from './workspaceAgentGuard';vi.mock('@/server/services/resourcePermission', () => ({assertCanPerformResourceAction: vi.fn(),+ canPerformResourceAction: vi.fn(),getResourceMeta: vi.fn(),}));vi.mock('./workspaceAgentGuard', () => ({@@ -27,17 +31,18 @@ vi.mock('./workspaceAgentGuard', () => ({const getResourceMetaMock = vi.mocked(getResourceMeta);const assertActionMock = vi.mocked(assertCanPerformResourceAction);+const canPerformActionMock = vi.mocked(canPerformResourceAction);const getParentGroupIdsMock = vi.mocked(getWorkspaceAgentParentGroupIds);/** Minimal drizzle stub: every select().from().where() resolves `rows`. */const createDb = (rowsPerCall: any[][]) => {let call = 0;return {- select: () => ({+ select: vi.fn(() => ({from: () => ({where: async () => rowsPerCall[call++] ?? [],}),- }),+ })),} as any;};@@ -195,6 +200,42 @@ describe('assertCanUseTopicTargets', () => {});});+describe('filterUserIdsByTopicViewAccess', () => {+ it('resolves topic metadata and recipient grants once before evaluating users', async () => {+ const db = createDb([[{ agentId: 'agent-1', groupId: null, sessionId: null }]]);+ const grants = new Map([+ ['user-1', ['agent:read:all']],+ ['user-2', ['agent:read:all']],+ ]);+ const permissionsSpy = vi+ .spyOn(RbacModel, 'getWorkspaceUsersPermissions')+ .mockResolvedValueOnce(grants);+ canPerformActionMock.mockImplementation(async ({ userId }) => userId === 'user-1');++ await expect(+ filterUserIdsByTopicViewAccess(+ { db, workspaceId: 'ws-1' },+ ['topic-1'],+ ['user-1', 'user-2', 'former-user'],+ ),+ ).resolves.toEqual(['user-1']);++ expect(db.select).toHaveBeenCalledTimes(1);+ expect(getResourceMetaMock).toHaveBeenCalledTimes(1);+ expect(permissionsSpy).toHaveBeenCalledTimes(1);+ expect(permissionsSpy).toHaveBeenCalledWith({+ db,+ requireMembership: true,+ userIds: ['user-1', 'user-2', 'former-user'],+ workspaceId: 'ws-1',+ });+ expect(canPerformActionMock).toHaveBeenCalledTimes(2);+ expect(canPerformActionMock).toHaveBeenCalledWith(+ expect.objectContaining({ effectiveAccessLevel: 'view', userId: 'user-1' }),+ );+ });+});+describe('assertCanUseSessionTargets', () => {it('resolves the linked agent from agentsToSessions and asserts use', async () => {const db = createDb([[{ agentId: 'agent-1' }]]);diff --git a/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.ts b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.tsindex efdaaea66aa..bd00b716a4e 100644--- a/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.ts+++ b/apps/server/src/routers/lambda/_helpers/conversationResourceGuard.ts@@ -1,9 +1,11 @@import { inArray } from 'drizzle-orm';+import { RbacModel } from '@/database/models/rbac';import { agentsToSessions, messages, topics } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import {assertCanPerformResourceAction,+ canPerformResourceAction,getResourceMeta,} from '@/server/services/resourcePermission';@@ -26,6 +28,12 @@ export interface CreateMessageTarget extends ConversationTarget {topicId?: string | null;}+interface ResolvedConversationTarget {+ meta: NonNullable<Awaited<ReturnType<typeof getResourceMeta>>>;+ resourceId: string;+ resourceType: 'agent' | 'agentGroup';+}+/*** Workspace General-access guard for conversations.*@@ -39,13 +47,12 @@ export interface CreateMessageTarget extends ConversationTarget {* cross-workspace ids) fall through — the models' workspace ownership WHERE* already keeps those writes scoped.*/-const assertCanAccessConversationTargets = async (- ctx: ConversationGuardCtx,+const resolveConversationTargets = async (+ ctx: Pick<ConversationGuardCtx, 'db' | 'workspaceId'>,targets: ConversationTarget[],- action: 'use' | 'view',-): Promise<void> => {+): Promise<ResolvedConversationTarget[]> => {const workspaceId = ctx.workspaceId ?? undefined;- if (!workspaceId || targets.length === 0) return;+ if (!workspaceId || targets.length === 0) return [];// A conversation belongs to its group when it has one, otherwise its agent.const refs = new Map<string, { resourceId: string; resourceType: 'agent' | 'agentGroup' }>();@@ -74,12 +81,29 @@ const assertCanAccessConversationTargets = async (refs.set(`agentGroup:${groupId}`, { resourceId: groupId, resourceType: 'agentGroup' });}+ const resolved: ResolvedConversationTarget[] = [];for (const { resourceId, resourceType } of refs.values()) {const meta = await getResourceMeta(ctx.db, resourceType, resourceId);// Not a resource of the current workspace — nothing to guard at this// layer; the ownership WHERE keeps foreign ids unreachable anyway.if (!meta || meta.workspaceId !== workspaceId) continue;+ resolved.push({ meta, resourceId, resourceType });+ }++ return resolved;+};++const assertCanAccessConversationTargets = async (+ ctx: ConversationGuardCtx,+ targets: ConversationTarget[],+ action: 'use' | 'view',+): Promise<void> => {+ const workspaceId = ctx.workspaceId ?? undefined;+ if (!workspaceId) return;++ const resolved = await resolveConversationTargets(ctx, targets);+ for (const { meta, resourceId, resourceType } of resolved) {await assertCanPerformResourceAction({action,db: ctx.db,@@ -127,12 +151,11 @@ export const assertCanUseMessageTargets = async (}};-const assertCanAccessTopicTargets = async (- ctx: ConversationGuardCtx,+const resolveTopicTargets = async (+ ctx: Pick<ConversationGuardCtx, 'db' | 'workspaceId'>,topicIds: string[],- action: 'use' | 'view',-): Promise<void> => {- if (!ctx.workspaceId || topicIds.length === 0) return;+): Promise<ResolvedConversationTarget[]> => {+ if (!ctx.workspaceId || topicIds.length === 0) return [];const rows = await ctx.db.select({ agentId: topics.agentId, groupId: topics.groupId, sessionId: topics.sessionId })@@ -157,7 +180,30 @@ const assertCanAccessTopicTargets = async (.where(inArray(agentsToSessions.sessionId, unresolvedSessionIds)): [];- await assertCanAccessConversationTargets(ctx, [...rows, ...sessionTargets], action);+ return resolveConversationTargets(ctx, [...rows, ...sessionTargets]);+};++const assertCanAccessTopicTargets = async (+ ctx: ConversationGuardCtx,+ topicIds: string[],+ action: 'use' | 'view',+): Promise<void> => {+ const workspaceId = ctx.workspaceId ?? undefined;+ if (!workspaceId) return;++ const resolved = await resolveTopicTargets(ctx, topicIds);+ for (const { meta, resourceId, resourceType } of resolved) {+ await assertCanPerformResourceAction({+ action,+ db: ctx.db,+ grantedPermissions: ctx.grantedPermissions,+ meta,+ resourceId,+ resourceType,+ userId: ctx.userId,+ workspaceId,+ });+ }};/** Resolve topic ids to their owning agent/group and assert `use` access. */@@ -172,6 +218,55 @@ export const assertCanViewTopicTargets = async (topicIds: string[],): Promise<void> => assertCanAccessTopicTargets(ctx, topicIds, 'view');+/**+ * Resolve one set of topic resources, then evaluate every active recipient+ * against that shared metadata. `view` is the minimum resource access level,+ * so supplying it avoids re-reading the same General-access row per user.+ */+export const filterUserIdsByTopicViewAccess = async (+ ctx: Pick<ConversationGuardCtx, 'db' | 'workspaceId'>,+ topicIds: string[],+ userIds: string[],+): Promise<string[]> => {+ const workspaceId = ctx.workspaceId ?? undefined;+ const uniqueUserIds = [...new Set(userIds)];+ if (!workspaceId || uniqueUserIds.length === 0) return [];++ const [resolvedTargets, permissionsByUserId] = await Promise.all([+ resolveTopicTargets(ctx, topicIds),+ RbacModel.getWorkspaceUsersPermissions({+ db: ctx.db,+ requireMembership: true,+ userIds: uniqueUserIds,+ workspaceId,+ }),+ ]);+ const activeUserIds = uniqueUserIds.filter((userId) => permissionsByUserId.has(userId));+ const access = await Promise.all(+ activeUserIds.map(async (userId) => {+ const grantedPermissions = permissionsByUserId.get(userId)!;+ const checks = await Promise.all(+ resolvedTargets.map(({ meta, resourceId, resourceType }) =>+ canPerformResourceAction({+ action: 'view',+ db: ctx.db,+ effectiveAccessLevel: 'view',+ grantedPermissions,+ meta,+ resourceId,+ resourceType,+ userId,+ workspaceId,+ }),+ ),+ );+ return checks.every(Boolean);+ }),+ );++ return activeUserIds.filter((_, index) => access[index]);+};+/*** Resolve session ids to their linked agents via `agentsToSessions` and assert* `use` access — for session-scoped bulk writes that never see a topic id.diff --git a/apps/server/src/routers/lambda/topicComment.ts b/apps/server/src/routers/lambda/topicComment.tsindex 789b35d7c1b..79005f120db 100644--- a/apps/server/src/routers/lambda/topicComment.ts+++ b/apps/server/src/routers/lambda/topicComment.ts@@ -30,6 +30,7 @@ import {assertCanUseMessageTargets,assertCanUseTopicTargets,assertCanViewTopicTargets,+ filterUserIdsByTopicViewAccess,} from './_helpers/conversationResourceGuard';const MAX_EDITOR_DATA_BYTES = 128 * 1024;@@ -294,18 +295,6 @@ interface NotificationCtx {workspaceId: string;}-const canViewTopic = async (ctx: NotificationCtx, userId: string, topicId: string) => {- try {- await assertCanViewTopicTargets({ db: ctx.serverDB, userId, workspaceId: ctx.workspaceId }, [- topicId,- ]);- return true;- } catch (error) {- if (error instanceof TRPCError && error.code === 'FORBIDDEN') return false;- throw error;- }-};-/*** Recipients come from stored rows (topic owner, root author, mention targets),* which can outlive access: a cross-workspace transfer keeps comments whose@@ -320,26 +309,14 @@ const filterRecipientsByTopicAccess = async (): Promise<TopicCommentActivityRecipient[]> => {if (recipients.length === 0) return [];- const activeMemberships = await ctx.serverDB- .select({ userId: workspaceMembers.userId })- .from(workspaceMembers)- .where(- and(- eq(workspaceMembers.workspaceId, ctx.workspaceId),- inArray(- workspaceMembers.userId,- recipients.map(({ userId }) => userId),- ),- isNull(workspaceMembers.deletedAt),- ),- );- const activeUserIds = new Set(activeMemberships.map(({ userId }) => userId));- const members = recipients.filter(({ userId }) => activeUserIds.has(userId));- const canView = await Promise.all(- members.map(({ userId }) => canViewTopic(ctx, userId, topicId)),+ const accessibleUserIds = new Set(+ await filterUserIdsByTopicViewAccess(+ { db: ctx.serverDB, workspaceId: ctx.workspaceId },+ [topicId],+ recipients.map(({ userId }) => userId),+ ),);-- return members.filter((_, index) => canView[index]);+ return recipients.filter(({ userId }) => accessibleUserIds.has(userId));};const notifyActivityBestEffort = (@@ -451,14 +428,19 @@ export const topicCommentRouter = router({if (!result.isDuplicate) {const recipientsByUserId = new Map<string, TopicCommentActivityRecipient>();- const conversationRecipientUserId = input.parentCommentId+ const conversationRecipients: TopicCommentActivityRecipient[] = input.parentCommentId? result.parentAuthorUserId- : result.topicOwnerUserId;- if (conversationRecipientUserId && conversationRecipientUserId !== ctx.userId) {- recipientsByUserId.set(conversationRecipientUserId, {- kind: input.parentCommentId ? 'replied' : 'commented',- userId: conversationRecipientUserId,- });+ ? [{ kind: 'replied', userId: result.parentAuthorUserId }]+ : []+ : input.messageId+ ? result.messageOwnerUserId+ ? [{ kind: 'commentedOnMessage', userId: result.messageOwnerUserId }]+ : []+ : result.topicParticipantUserIds.map((userId) => ({ kind: 'commented', userId }));+ for (const recipient of conversationRecipients) {+ if (recipient.userId !== ctx.userId) {+ recipientsByUserId.set(recipient.userId, recipient);+ }}for (const userId of result.addedMentionUserIds) {recipientsByUserId.set(userId, { kind: 'mentioned', userId });diff --git a/apps/server/src/services/resourcePermission/index.test.ts b/apps/server/src/services/resourcePermission/index.test.tsindex cb4ccdb001f..eca814e05f3 100644--- a/apps/server/src/services/resourcePermission/index.test.ts+++ b/apps/server/src/services/resourcePermission/index.test.ts@@ -181,6 +181,49 @@ describe('canPerformResourceAction', () => {]);});+ it('uses a pre-resolved effective access level without querying it again', async () => {+ permissionMatchesMock+ .mockResolvedValueOnce({ hasAllScope: true, hasOwnerScope: false })+ .mockResolvedValueOnce({ hasAllScope: false, hasOwnerScope: true });++ await expect(+ canPerformResourceAction({+ action: 'view',+ db,+ effectiveAccessLevel: 'view',+ grantedPermissions: ['agent:read:all'],+ meta,+ resourceId: 'agent-1',+ resourceType: 'agent',+ userId: 'member',+ workspaceId: 'ws-1',+ }),+ ).resolves.toBe(true);+ expect(effectiveAccessMock).not.toHaveBeenCalled();+ });++ it('does not let pre-resolved levels bypass General access for stronger actions', async () => {+ permissionMatchesMock+ .mockResolvedValueOnce({ hasAllScope: true, hasOwnerScope: false })+ .mockResolvedValueOnce({ hasAllScope: false, hasOwnerScope: true });+ effectiveAccessMock.mockResolvedValue('view');++ await expect(+ canPerformResourceAction({+ action: 'use',+ db,+ effectiveAccessLevel: 'edit',+ grantedPermissions: ['ai_model:invoke:all'],+ meta,+ resourceId: 'agent-1',+ resourceType: 'agent',+ userId: 'member',+ workspaceId: 'ws-1',+ }),+ ).resolves.toBe(false);+ expect(effectiveAccessMock).toHaveBeenCalledTimes(1);+ });+it('reads the caller grants once even when two actions are matched', async () => {permissionMatchesMock.mockResolvedValueOnce({ hasAllScope: true, hasOwnerScope: false })diff --git a/apps/server/src/services/resourcePermission/index.ts b/apps/server/src/services/resourcePermission/index.tsindex 1f8aeb55e39..4a9f4358881 100644--- a/apps/server/src/services/resourcePermission/index.ts+++ b/apps/server/src/services/resourcePermission/index.ts@@ -109,6 +109,8 @@ const getRequiredAccessLevel = (action: ResourceAccessAction): ResourceAccessLevexport const canPerformResourceAction = async (params: {action: ResourceAccessAction;db: LobeChatDatabase;+ /** A shared minimum level may skip duplicate reads only for the `view` action. */+ effectiveAccessLevel?: ResourceAccessLevel;grantedPermissions?: readonly string[];meta: ResourceMeta;resourceId: string;@@ -116,8 +118,17 @@ export const canPerformResourceAction = async (params: {userId: string;workspaceId: string;}): Promise<boolean> => {- const { action, db, grantedPermissions, meta, resourceId, resourceType, userId, workspaceId } =- params;+ const {+ action,+ db,+ effectiveAccessLevel,+ grantedPermissions,+ meta,+ resourceId,+ resourceType,+ userId,+ workspaceId,+ } = params;if (meta.workspaceId !== workspaceId) return false;const isCreator = meta.userId === userId;@@ -171,10 +182,13 @@ export const canPerformResourceAction = async (params: {).hasAllScope;if (hasResourceAdminScope) return true;- const accessLevel = await new ResourcePermissionModel(db, workspaceId).getEffectiveAccessLevel(- resourceType,- resourceId,- );+ const accessLevel =+ action === 'view' && effectiveAccessLevel+ ? effectiveAccessLevel+ : await new ResourcePermissionModel(db, workspaceId).getEffectiveAccessLevel(+ resourceType,+ resourceId,+ );const requiredAccessLevel = getRequiredAccessLevel(action);return ACCESS_LEVEL_RANK[accessLevel] >= ACCESS_LEVEL_RANK[requiredAccessLevel];};diff --git a/locales/en-US/notification.json b/locales/en-US/notification.jsonindex 8a4f3a275e9..782b9f25ffb 100644--- a/locales/en-US/notification.json+++ b/locales/en-US/notification.json@@ -42,9 +42,11 @@"subscription_payment_failed": "Your subscription renewal payment failed. Please update your payment method to keep your subscription active.","subscription_payment_failed_action": "Update payment method","subscription_payment_failed_title": "Subscription renewal payment failed",- "topic_comment_activity": "{{actorLabel}} commented on your topic.",+ "topic_comment_activity": "{{actorLabel}} commented in a topic you participate in.","topic_comment_activity_mentioned": "{{actorLabel}} mentioned you in a comment.","topic_comment_activity_mentioned_title": "You were mentioned in a comment",+ "topic_comment_activity_message": "{{actorLabel}} commented on your message.",+ "topic_comment_activity_message_title": "New comment on your message","topic_comment_activity_replied": "{{actorLabel}} replied to your comment.","topic_comment_activity_replied_title": "New reply to your comment","topic_comment_activity_title": "New topic comment",diff --git a/locales/zh-CN/notification.json b/locales/zh-CN/notification.jsonindex aeaf052a04e..683a80f5f98 100644--- a/locales/zh-CN/notification.json+++ b/locales/zh-CN/notification.json@@ -42,9 +42,11 @@"subscription_payment_failed": "您的订阅续费扣款失败。请更新您的付款方式以保持订阅有效。","subscription_payment_failed_action": "更新付款方式","subscription_payment_failed_title": "订阅续费扣款失败",- "topic_comment_activity": "{{actorLabel}} 评论了你的话题。",+ "topic_comment_activity": "{{actorLabel}} 在你参与的话题中发表了评论。","topic_comment_activity_mentioned": "{{actorLabel}} 在评论中提到了你。","topic_comment_activity_mentioned_title": "你在评论中被提及",+ "topic_comment_activity_message": "{{actorLabel}} 评论了你的消息。",+ "topic_comment_activity_message_title": "你的消息有新评论","topic_comment_activity_replied": "{{actorLabel}} 回复了你的评论。","topic_comment_activity_replied_title": "你的评论有新回复","topic_comment_activity_title": "话题有新评论",diff --git a/packages/business-server/src/topic-comment/notifyActivity.ts b/packages/business-server/src/topic-comment/notifyActivity.tsindex 47a775286e0..e893a5305ad 100644--- a/packages/business-server/src/topic-comment/notifyActivity.ts+++ b/packages/business-server/src/topic-comment/notifyActivity.ts@@ -1,4 +1,4 @@-export type TopicCommentActivityKind = 'commented' | 'mentioned' | 'replied';+export type TopicCommentActivityKind = 'commented' | 'commentedOnMessage' | 'mentioned' | 'replied';export interface TopicCommentActivityRecipient {kind: TopicCommentActivityKind;diff --git a/packages/database/src/models/__tests__/rbac.test.ts b/packages/database/src/models/__tests__/rbac.test.tsindex e201335c563..93613b5d2b8 100644--- a/packages/database/src/models/__tests__/rbac.test.ts+++ b/packages/database/src/models/__tests__/rbac.test.ts@@ -247,6 +247,30 @@ describe('RbacModel — workspace mode (membership.role is the source of truth)'globalOnlyCode,]);});++ it('resolves multiple active members and their global grants in one batch', async () => {+ const globalOnlyCode = 'test:global:all';+ await Promise.all([+ addMembership(userId, workspaceAId, 'member'),+ addMembership(otherUserId, workspaceAId, 'owner'),+ ]);+ await grantGlobalRole(userId, 'super_admin', [globalOnlyCode]);++ const permissionsByUserId = await RbacModel.getWorkspaceUsersPermissions({+ db: serverDB,+ requireMembership: true,+ userIds: [userId, otherUserId, 'not-a-member'],+ workspaceId: workspaceAId,+ });++ expect(permissionsByUserId.has('not-a-member')).toBe(false);+ expect(permissionsByUserId.get(userId)).toEqual(+ expect.arrayContaining([`${PERMISSION_ACTIONS.AGENT_READ}:all`, globalOnlyCode]),+ );+ expect(permissionsByUserId.get(otherUserId)).toEqual(+ expect.arrayContaining([billingManageCode]),+ );+ });});describe('hasAnyPermission / hasAllPermissions', () => {diff --git a/packages/database/src/models/__tests__/topicComment.test.ts b/packages/database/src/models/__tests__/topicComment.test.tsindex 2780f4bbc29..e40aa2bd807 100644--- a/packages/database/src/models/__tests__/topicComment.test.ts+++ b/packages/database/src/models/__tests__/topicComment.test.ts@@ -93,6 +93,25 @@ afterEach(cleanup);describe('TopicCommentModel', () => {describe('createWithMentions', () => {it('should create a topic-level comment stamped with the topic workspaceId', async () => {+ await serverDB.insert(messages).values([+ {+ content: 'member message',+ id: 'tc-msg-participant-1',+ role: 'user',+ topicId: workspaceTopicId,+ userId: memberId,+ workspaceId: workspaceAId,+ },+ {+ content: 'another member message',+ id: 'tc-msg-participant-2',+ role: 'assistant',+ topicId: workspaceTopicId,+ userId: memberId,+ workspaceId: workspaceAId,+ },+ ]);+const result = await authorModel.createWithMentions({clientId: 'client-1',content: 'a topic-level comment',@@ -101,6 +120,8 @@ describe('TopicCommentModel', () => {expect(result.isDuplicate).toBe(false);expect(result.addedMentionUserIds).toEqual([]);+ expect(result.topicParticipantUserIds).toHaveLength(2);+ expect(result.topicParticipantUserIds).toEqual(expect.arrayContaining([authorId, memberId]));expect(result.topicOwnerUserId).toBe(authorId);expect(result.comment).toMatchObject({anchorPreview: null,@@ -124,6 +145,8 @@ describe('TopicCommentModel', () => {expect(result.comment.anchorPreview?.role).toBe('assistant');expect(result.comment.anchorPreview?.excerpt).toHaveLength(200);expect(result.comment.anchorPreview?.excerpt.startsWith('anchor message content')).toBe(true);+ expect(result.messageOwnerUserId).toBe(authorId);+ expect(result.topicParticipantUserIds).toEqual([]);});it('should not split a surrogate pair at the excerpt cut (jsonb rejects lone surrogates)', async () => {diff --git a/packages/database/src/models/rbac.ts b/packages/database/src/models/rbac.tsindex abfab4436af..6e5fdfc543e 100644--- a/packages/database/src/models/rbac.ts+++ b/packages/database/src/models/rbac.ts@@ -52,6 +52,84 @@ export class RbacModel {this.db = db;}+ /** Resolve several users' effective workspace grants in two batched queries. */+ static getWorkspaceUsersPermissions = async ({+ db,+ requireMembership = false,+ userIds,+ workspaceId,+ }: {+ db: LobeChatDatabase;+ requireMembership?: boolean;+ userIds: string[];+ workspaceId: string;+ }): Promise<Map<string, string[]>> => {+ const uniqueUserIds = [...new Set(userIds)];+ if (uniqueUserIds.length === 0) return new Map();++ const [memberships, globalPermissions] = await Promise.all([+ db+ .select({+ primaryOwnerId: workspaces.primaryOwnerId,+ role: workspaceMembers.role,+ userId: workspaceMembers.userId,+ })+ .from(workspaceMembers)+ .innerJoin(workspaces, eq(workspaces.id, workspaceMembers.workspaceId))+ .where(+ and(+ eq(workspaceMembers.workspaceId, workspaceId),+ inArray(workspaceMembers.userId, uniqueUserIds),+ isNull(workspaceMembers.deletedAt),+ ),+ ),+ db+ .select({ permissionCode: permissions.code, userId: userRoles.userId })+ .from(userRoles)+ .innerJoin(roles, eq(userRoles.roleId, roles.id))+ .innerJoin(rolePermissions, eq(roles.id, rolePermissions.roleId))+ .innerJoin(permissions, eq(rolePermissions.permissionId, permissions.id))+ .where(+ and(+ inArray(userRoles.userId, uniqueUserIds),+ isNull(userRoles.workspaceId),+ eq(roles.isActive, true),+ eq(permissions.isActive, true),+ sql`(${userRoles.expiresAt} IS NULL OR ${userRoles.expiresAt} > NOW())`,+ ),+ ),+ ]);++ const membershipByUserId = new Map(+ memberships.map((membership) => [membership.userId, membership]),+ );+ const globalPermissionsByUserId = new Map<string, string[]>();+ for (const { permissionCode, userId } of globalPermissions) {+ const codes = globalPermissionsByUserId.get(userId) ?? [];+ codes.push(permissionCode);+ globalPermissionsByUserId.set(userId, codes);+ }++ const permissionsByUserId = new Map<string, string[]>();+ for (const userId of uniqueUserIds) {+ const membership = membershipByUserId.get(userId);+ if (requireMembership && !membership) continue;++ const role =+ membership?.role === 'owner' && membership.primaryOwnerId !== userId+ ? 'admin'+ : membership?.role;+ permissionsByUserId.set(userId, [+ ...new Set([+ ...(role ? getWorkspaceRolePermissionCodes(role) : []),+ ...(globalPermissionsByUserId.get(userId) ?? []),+ ]),+ ]);+ }++ return permissionsByUserId;+ };+/*** Active membership role of a user in a workspace, or null for non-members.* `workspace_members.role` is the single source of truth for built-in@@ -125,12 +203,12 @@ export class RbacModel {const targetUserId = opts.userId || this.userId;if (opts.workspaceId) {- const [membershipRole, globalCodes] = await Promise.all([- this.getWorkspaceMembershipRole(targetUserId, opts.workspaceId),- this.getGlobalPermissionCodes(targetUserId),- ]);- const matrixCodes = membershipRole ? getWorkspaceRolePermissionCodes(membershipRole) : [];- return [...new Set([...matrixCodes, ...globalCodes])];+ const permissionsByUserId = await RbacModel.getWorkspaceUsersPermissions({+ db: this.db,+ userIds: [targetUserId],+ workspaceId: opts.workspaceId,+ });+ return permissionsByUserId.get(targetUserId) ?? [];}const result = await this.dbdiff --git a/packages/database/src/models/topicComment.ts b/packages/database/src/models/topicComment.tsindex eea373ce8bd..a374d95f368 100644--- a/packages/database/src/models/topicComment.ts+++ b/packages/database/src/models/topicComment.ts@@ -102,10 +102,14 @@ export interface CreateTopicCommentResult {comment: TopicCommentItem;/** true when the insert hit the (topicId, authorUserId, clientId) idempotency key and the existing row is returned */isDuplicate: boolean;+ /** User who owns an anchored message; used for post-commit activity delivery. */+ messageOwnerUserId?: string;/** Author of the root when this is a reply; used for post-commit activity delivery. */parentAuthorUserId?: string | null;- /** User who owns the topic; used for post-commit activity delivery. */+ /** User who owns the topic. */topicOwnerUserId: string;+ /** Topic owner plus distinct message owners for a topic-level comment. */+ topicParticipantUserIds: string[];}export interface UpdateTopicCommentParams {@@ -304,6 +308,7 @@ export class TopicCommentModel {}let anchorPreview: TopicCommentAnchorPreview | undefined;+ let messageOwnerUserId: string | undefined;if (params.messageId) {const [message] = await tx.select({@@ -311,6 +316,7 @@ export class TopicCommentModel {id: messages.id,role: messages.role,topicId: messages.topicId,+ userId: messages.userId,}).from(messages).where(eq(messages.id, params.messageId))@@ -323,8 +329,20 @@ export class TopicCommentModel {excerpt: truncateSurrogateSafe(message.content ?? '', ANCHOR_PREVIEW_MAX_LENGTH),role: message.role,};+ messageOwnerUserId = message.userId;}+ let topicParticipantUserIds: string[] = [];+ if (!params.parentCommentId && !params.messageId) {+ const messageOwners = await tx+ .select({ userId: messages.userId })+ .from(messages)+ .where(eq(messages.topicId, params.topicId))+ .groupBy(messages.userId);+ topicParticipantUserIds = [+ ...new Set([topic.userId, ...messageOwners.map(({ userId }) => userId)]),+ ];+ }const mentionedUserIds = [...new Set(params.mentionedUserIds ?? [])];const [inserted] = await tx@@ -367,7 +385,9 @@ export class TopicCommentModel {addedMentionUserIds: [],comment: existing,isDuplicate: true,+ messageOwnerUserId,parentAuthorUserId,+ topicParticipantUserIds,topicOwnerUserId: topic.userId,};}@@ -389,7 +409,9 @@ export class TopicCommentModel {addedMentionUserIds: mentionedUserIds,comment: inserted,isDuplicate: false,+ messageOwnerUserId,parentAuthorUserId,+ topicParticipantUserIds,topicOwnerUserId: topic.userId,};});diff --git a/packages/locales/src/default/notification.ts b/packages/locales/src/default/notification.tsindex 7849ce25dee..c2c8a8b3f26 100644--- a/packages/locales/src/default/notification.ts+++ b/packages/locales/src/default/notification.ts@@ -50,7 +50,9 @@ export default {'Your subscription renewal payment failed. Please update your payment method to keep your subscription active.','subscription_payment_failed_action': 'Update payment method','subscription_payment_failed_title': 'Subscription renewal payment failed',- 'topic_comment_activity': '{{actorLabel}} commented on your topic.',+ 'topic_comment_activity': '{{actorLabel}} commented in a topic you participate in.',+ 'topic_comment_activity_message': '{{actorLabel}} commented on your message.',+ 'topic_comment_activity_message_title': 'New comment on your message','topic_comment_activity_mentioned': '{{actorLabel}} mentioned you in a comment.','topic_comment_activity_mentioned_title': 'You were mentioned in a comment','topic_comment_activity_replied': '{{actorLabel}} replied to your comment.',