Skip to content

🀯 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.

✨ feat: support workspace-scoped notifications (#17587)

Rdmclin2c8e589b98f05
diff --git a/apps/server/src/routers/async/image.ts b/apps/server/src/routers/async/image.ts
index 9412b613427..06dbdff500b 100644
--- a/apps/server/src/routers/async/image.ts
+++ b/apps/server/src/routers/async/image.ts
@@ -280,6 +280,7 @@ export const imageRouter = router({
prompt: params.prompt,
topicId: generationTopicId,
userId: ctx.userId,
+ workspaceId,
});
} catch (err) {
console.error('[image-async] notification failed:', err);
diff --git a/apps/server/src/routers/lambda/notification.ts b/apps/server/src/routers/lambda/notification.ts
index 4c23323f251..371636077eb 100644
--- a/apps/server/src/routers/lambda/notification.ts
+++ b/apps/server/src/routers/lambda/notification.ts
@@ -11,7 +11,12 @@ const notificationProcedure = wsCompatProcedure.use(serverDatabase).use(async (o
return opts.next({
ctx: {
- notificationModel: new NotificationModel(ctx.serverDB, ctx.userId),
+ // Scope the inbox to the request context: workspace mode only sees that
+ // workspace's notifications, personal mode only sees personal ones
+ // (`workspace_id IS NULL`) β€” the two contexts never leak into each other.
+ notificationModel: new NotificationModel(ctx.serverDB, ctx.userId, {
+ workspaceId: ctx.workspaceId ?? null,
+ }),
},
});
});
diff --git a/packages/business-server/src/image-generation/notifyImageCompleted.ts b/packages/business-server/src/image-generation/notifyImageCompleted.ts
index a1999db04c0..9ce4cc2b450 100644
--- a/packages/business-server/src/image-generation/notifyImageCompleted.ts
+++ b/packages/business-server/src/image-generation/notifyImageCompleted.ts
@@ -5,6 +5,8 @@ interface NotifyImageCompletedParams {
prompt: string;
topicId?: string;
userId: string;
+ /** Present when the generation ran in a workspace β€” the notification then follows that context. */
+ workspaceId?: string;
}
export async function notifyImageCompleted(_params: NotifyImageCompletedParams): Promise<void> {}
diff --git a/packages/business-server/src/video-generation/notifyVideoCompleted.ts b/packages/business-server/src/video-generation/notifyVideoCompleted.ts
index 1d1f46f03a7..55decfd1fcf 100644
--- a/packages/business-server/src/video-generation/notifyVideoCompleted.ts
+++ b/packages/business-server/src/video-generation/notifyVideoCompleted.ts
@@ -4,6 +4,8 @@ interface NotifyVideoCompletedParams {
prompt: string;
topicId?: string;
userId: string;
+ /** Present when the generation ran in a workspace β€” the notification then follows that context. */
+ workspaceId?: string;
}
export async function notifyVideoCompleted(_params: NotifyVideoCompletedParams): Promise<void> {}
diff --git a/packages/database/src/models/__tests__/notification.test.ts b/packages/database/src/models/__tests__/notification.test.ts
index ce7ade993e1..c617079f9a2 100644
--- a/packages/database/src/models/__tests__/notification.test.ts
+++ b/packages/database/src/models/__tests__/notification.test.ts
@@ -5,6 +5,7 @@ import { getTestDB } from '../../core/getTestDB';
import { NotificationModel } from '../../models/notification';
import { notificationDeliveries, notifications } from '../../schemas/notification';
import { users } from '../../schemas/user';
+import { workspaces } from '../../schemas/workspace';
import type { LobeChatDatabase } from '../../type';
describe('NotificationModel', () => {
@@ -360,4 +361,85 @@ describe('NotificationModel (integration)', () => {
expect(persisted.providerMessageId).toBe('resend-123');
});
});
+
+ describe('workspace context scoping', () => {
+ const workspaceId = 'notification-ws-1';
+ const otherWorkspaceId = 'notification-ws-2';
+
+ const seedContexts = async () => {
+ await serverDB.insert(workspaces).values([
+ { id: workspaceId, name: 'WS One', primaryOwnerId: userId, slug: 'ws-one' },
+ { id: otherWorkspaceId, name: 'WS Two', primaryOwnerId: userId, slug: 'ws-two' },
+ ]);
+
+ const writer = new NotificationModel(serverDB, userId);
+ await writer.create(baseNotification({ title: 'personal' }));
+ await writer.create(baseNotification({ title: 'in-ws-1', workspaceId }));
+ await writer.create(baseNotification({ title: 'in-ws-2', workspaceId: otherWorkspaceId }));
+ };
+
+ it('personal context (null) sees only rows without a workspace', async () => {
+ await seedContexts();
+ const personal = new NotificationModel(serverDB, userId, { workspaceId: null });
+
+ const rows = await personal.list();
+ expect(rows.map((row) => row.title)).toEqual(['personal']);
+ expect(await personal.getUnreadCount()).toBe(1);
+ });
+
+ it('workspace context sees only that workspace rows', async () => {
+ await seedContexts();
+ const scoped = new NotificationModel(serverDB, userId, { workspaceId });
+
+ const rows = await scoped.list();
+ expect(rows.map((row) => row.title)).toEqual(['in-ws-1']);
+ expect(await scoped.getUnreadCount()).toBe(1);
+ });
+
+ it('context-free access spans both personal and workspace rows', async () => {
+ await seedContexts();
+ const unscoped = new NotificationModel(serverDB, userId);
+
+ const rows = await unscoped.list();
+ expect(rows).toHaveLength(3);
+ });
+
+ it('markAllAsRead only touches the current context', async () => {
+ await seedContexts();
+ const scoped = new NotificationModel(serverDB, userId, { workspaceId });
+ const personal = new NotificationModel(serverDB, userId, { workspaceId: null });
+
+ await scoped.markAllAsRead();
+
+ expect(await scoped.getUnreadCount()).toBe(0);
+ expect(await personal.getUnreadCount()).toBe(1);
+ });
+
+ it('markAsRead ignores ids from outside the current context', async () => {
+ await seedContexts();
+ const unscoped = new NotificationModel(serverDB, userId);
+ const scoped = new NotificationModel(serverDB, userId, { workspaceId });
+
+ // A stale client in workspace context replays a personal + foreign-workspace id.
+ const rows = await unscoped.list();
+ const outsideIds = rows.filter((row) => row.title !== 'in-ws-1').map((row) => row.id);
+ await scoped.markAsRead(outsideIds);
+
+ const personal = new NotificationModel(serverDB, userId, { workspaceId: null });
+ const other = new NotificationModel(serverDB, userId, { workspaceId: otherWorkspaceId });
+ expect(await personal.getUnreadCount()).toBe(1);
+ expect(await other.getUnreadCount()).toBe(1);
+ });
+
+ it('archive ignores an id from another context', async () => {
+ await seedContexts();
+ const scoped = new NotificationModel(serverDB, userId, { workspaceId });
+ const personal = new NotificationModel(serverDB, userId, { workspaceId: null });
+
+ const [personalRow] = await personal.list();
+ await scoped.archive(personalRow.id);
+
+ expect((await personal.list()).map((row) => row.title)).toEqual(['personal']);
+ });
+ });
});
diff --git a/packages/database/src/models/__tests__/workspaceUserSettings.test.ts b/packages/database/src/models/__tests__/workspaceUserSettings.test.ts
index 32963207979..d4568b3394a 100644
--- a/packages/database/src/models/__tests__/workspaceUserSettings.test.ts
+++ b/packages/database/src/models/__tests__/workspaceUserSettings.test.ts
@@ -165,6 +165,34 @@ describe('WorkspaceUserSettingsModel', () => {
});
});
+ it('deep-merges notification so a single-switch patch never drops other toggles', async () => {
+ const model = new WorkspaceUserSettingsModel(serverDB, userA, workspaceId);
+ await model.updatePreference({
+ notification: {
+ email: { items: { workspace: { workspace_member_joined: false } } },
+ inbox: { enabled: false },
+ },
+ });
+
+ // Patch a single other leaf β€” the earlier email item toggle and the inbox
+ // master switch must both survive the write.
+ await model.updatePreference({
+ notification: {
+ email: { items: { workspace: { workspace_payment_failed: false } } },
+ },
+ });
+
+ const preference = await model.getPreference();
+ expect(preference.notification).toEqual({
+ email: {
+ items: {
+ workspace: { workspace_member_joined: false, workspace_payment_failed: false },
+ },
+ },
+ inbox: { enabled: false },
+ });
+ });
+
it("isolates users' rows so one caller can never observe another's preference", async () => {
const modelA = new WorkspaceUserSettingsModel(serverDB, userA, workspaceId);
const modelB = new WorkspaceUserSettingsModel(serverDB, userB, workspaceId);
diff --git a/packages/database/src/models/notification.ts b/packages/database/src/models/notification.ts
index 47dd4015003..c51d5d46d6e 100644
--- a/packages/database/src/models/notification.ts
+++ b/packages/database/src/models/notification.ts
@@ -1,26 +1,46 @@
-import { and, count, desc, eq, inArray, lt, or } from 'drizzle-orm';
+import { and, count, desc, eq, inArray, isNull, lt, or, type SQL } from 'drizzle-orm';
import type { NewNotification, NewNotificationDelivery } from '../schemas/notification';
import { notificationDeliveries, notifications } from '../schemas/notification';
import type { LobeChatDatabase } from '../type';
+export interface NotificationModelOptions {
+ /**
+ * Inbox context scope. `null` = personal mode (only rows with
+ * `workspace_id IS NULL`); a workspace id = only that workspace's rows.
+ * Omit for context-free access (write side / ops tooling), where read
+ * queries span both personal and workspace notifications.
+ */
+ workspaceId?: string | null;
+}
+
export class NotificationModel {
private readonly userId: string;
private readonly db: LobeChatDatabase;
+ private readonly workspaceId?: string | null;
- constructor(db: LobeChatDatabase, userId: string) {
+ constructor(db: LobeChatDatabase, userId: string, options?: NotificationModelOptions) {
this.db = db;
this.userId = userId;
+ this.workspaceId = options?.workspaceId;
}
private ownership = () => eq(notifications.userId, this.userId);
+ /** Context conditions: ownership plus the workspace/personal scope when set */
+ private scope = (): SQL[] => {
+ const conditions: SQL[] = [this.ownership()];
+ if (this.workspaceId === null) conditions.push(isNull(notifications.workspaceId));
+ else if (this.workspaceId) conditions.push(eq(notifications.workspaceId, this.workspaceId));
+ return conditions;
+ };
+
async list(
opts: { category?: string; cursor?: string; limit?: number; unreadOnly?: boolean } = {},
) {
const { cursor, limit = 20, category, unreadOnly } = opts;
- const conditions = [this.ownership(), eq(notifications.isArchived, false)];
+ const conditions = [...this.scope(), eq(notifications.isArchived, false)];
if (unreadOnly) {
conditions.push(eq(notifications.isRead, false));
@@ -34,7 +54,7 @@ export class NotificationModel {
const cursorRow = await this.db
.select({ createdAt: notifications.createdAt, id: notifications.id })
.from(notifications)
- .where(and(eq(notifications.id, cursor), this.ownership()))
+ .where(and(eq(notifications.id, cursor), ...this.scope()))
.limit(1);
if (cursorRow[0]) {
@@ -62,7 +82,7 @@ export class NotificationModel {
.select({ count: count() })
.from(notifications)
.where(
- and(this.ownership(), eq(notifications.isRead, false), eq(notifications.isArchived, false)),
+ and(...this.scope(), eq(notifications.isRead, false), eq(notifications.isArchived, false)),
);
return result?.count ?? 0;
@@ -74,7 +94,7 @@ export class NotificationModel {
return this.db
.update(notifications)
.set({ isRead: true, updatedAt: new Date() })
- .where(and(this.ownership(), inArray(notifications.id, ids)));
+ .where(and(...this.scope(), inArray(notifications.id, ids)));
}
async markAllAsRead() {
@@ -82,7 +102,7 @@ export class NotificationModel {
.update(notifications)
.set({ isRead: true, updatedAt: new Date() })
.where(
- and(this.ownership(), eq(notifications.isRead, false), eq(notifications.isArchived, false)),
+ and(...this.scope(), eq(notifications.isRead, false), eq(notifications.isArchived, false)),
);
}
@@ -90,14 +110,14 @@ export class NotificationModel {
return this.db
.update(notifications)
.set({ isArchived: true, updatedAt: new Date() })
- .where(and(eq(notifications.id, id), this.ownership()));
+ .where(and(eq(notifications.id, id), ...this.scope()));
}
async archiveAll() {
return this.db
.update(notifications)
.set({ isArchived: true, updatedAt: new Date() })
- .where(and(this.ownership(), eq(notifications.isArchived, false)));
+ .where(and(...this.scope(), eq(notifications.isArchived, false)));
}
// ─── Write-side (used by NotificationService in cloud) ─────────
diff --git a/packages/database/src/models/workspaceUserSettings.ts b/packages/database/src/models/workspaceUserSettings.ts
index d918d428538..f4903b98d14 100644
--- a/packages/database/src/models/workspaceUserSettings.ts
+++ b/packages/database/src/models/workspaceUserSettings.ts
@@ -1,4 +1,5 @@
import type { WorkspaceUserPreference } from '@lobechat/types';
+import { mergeNotificationSettings } from '@lobechat/utils/mergeNotificationSettings';
import { and, eq } from 'drizzle-orm';
import { workspaceUserSettings } from '../schemas/workspace';
@@ -115,6 +116,9 @@ export class WorkspaceUserSettingsModel {
},
}
: {}),
+ ...(patch.notification
+ ? { notification: mergeNotificationSettings(current.notification, patch.notification) }
+ : {}),
...(patch.agentModeOverrides
? {
agentModeOverrides: {
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index d4bcdbc5ce5..40f8335b664 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -8,6 +8,7 @@ import type { TopicGroupMode, TopicSortBy } from '../topic';
import type { UserAgentOnboarding } from './agentOnboarding';
import type { UserOnboarding } from './onboarding';
import type { UserSettings } from './settings';
+import type { NotificationSettings } from './settings/notification';
/**
* Per-agent override for the device execution decision. Stored on
@@ -63,6 +64,14 @@ export interface WorkspaceUserPreference {
agentModelOverrides?: Record<string /* agentId */, AgentModelOverride>;
/** Per-member Agent/Chat runtime mode for shared workspace agents. */
agentModeOverrides?: Record<string /* agentId */, boolean>;
+ /**
+ * This member's notification preferences for workspace-scoped scenarios
+ * (the `workspace` category of the scenario registry). Same shape as the
+ * personal `user_settings.notification` bag; missing = every workspace
+ * notification enabled. Workspace notifications consult only this bag β€”
+ * personal notification settings no longer apply to them.
+ */
+ notification?: NotificationSettings;
/**
* Per-member sidebar sections layout (order + hidden sections). Written as
* a complete object on every update β€” partial patches would drop the
diff --git a/packages/utils/src/mergeNotificationSettings.ts b/packages/utils/src/mergeNotificationSettings.ts
new file mode 100644
index 00000000000..c1d9df682c2
--- /dev/null
+++ b/packages/utils/src/mergeNotificationSettings.ts
@@ -0,0 +1,41 @@
+import type { NotificationSettings } from '@lobechat/types';
+
+/**
+ * Merge a notification-settings patch over the stored bag without dropping
+ * sibling keys: clients patch a single switch at a time (one channel's
+ * `enabled`, or one `items[category][type]` leaf), so a shallow replace at
+ * any level would wipe the caller's other toggles for that channel.
+ *
+ * Used by both the server-side `WorkspaceUserSettingsModel.updatePreference`
+ * and the client store's optimistic update, so the optimistic cache always
+ * matches what the database will keep.
+ */
+export const mergeNotificationSettings = (
+ current: NotificationSettings | undefined,
+ patch: NotificationSettings,
+): NotificationSettings => {
+ const next: NotificationSettings = { ...current };
+ for (const [channel, channelPatch] of Object.entries(patch)) {
+ if (!channelPatch) continue;
+ const key = channel as keyof NotificationSettings;
+ const currentChannel = next[key];
+ const mergedItems: Record<string, Record<string, boolean>> = {
+ ...currentChannel?.items,
+ ...channelPatch.items,
+ };
+ const items = channelPatch.items
+ ? Object.fromEntries(
+ Object.keys(mergedItems).map((category) => [
+ category,
+ { ...currentChannel?.items?.[category], ...mergedItems[category] },
+ ]),
+ )
+ : currentChannel?.items;
+ next[key] = {
+ ...currentChannel,
+ ...channelPatch,
+ ...(items ? { items } : {}),
+ };
+ }
+ return next;
+};
diff --git a/src/app/(backend)/api/webhooks/video/[provider]/route.ts b/src/app/(backend)/api/webhooks/video/[provider]/route.ts
index 279a39aadee..fb3e8cb9d12 100644
--- a/src/app/(backend)/api/webhooks/video/[provider]/route.ts
+++ b/src/app/(backend)/api/webhooks/video/[provider]/route.ts
@@ -234,6 +234,7 @@ export const POST = async (req: Request, { params }: { params: Promise<{ provide
prompt: batch?.prompt ?? '',
topicId: batch?.generationTopicId,
userId: asyncTask.userId,
+ workspaceId: asyncTask.workspaceId ?? undefined,
});
} catch (err) {
console.error('[video-webhook] notification failed:', err);
diff --git a/src/business/client/BusinessSettingPages/WorkspaceNotification.tsx b/src/business/client/BusinessSettingPages/WorkspaceNotification.tsx
new file mode 100644
index 00000000000..81bd8c7c4ce
--- /dev/null
+++ b/src/business/client/BusinessSettingPages/WorkspaceNotification.tsx
@@ -0,0 +1,3 @@
+export default function WorkspaceNotification() {
+ return null;
+}
diff --git a/src/features/Workspace/workspaceAwarePath.ts b/src/features/Workspace/workspaceAwarePath.ts
index f0ea5f8b568..70532399f5d 100644
--- a/src/features/Workspace/workspaceAwarePath.ts
+++ b/src/features/Workspace/workspaceAwarePath.ts
@@ -42,6 +42,7 @@ export const WORKSPACE_SETTINGS_TABS: ReadonlySet<string> = new Set([
'devices',
'general',
'members',
+ 'notification',
'oauth-apps',
'plans',
'provider',
diff --git a/src/features/WorkspaceSetting/hooks/useCategory.tsx b/src/features/WorkspaceSetting/hooks/useCategory.tsx
index 5ee94f57fc5..797bfe9a36b 100644
--- a/src/features/WorkspaceSetting/hooks/useCategory.tsx
+++ b/src/features/WorkspaceSetting/hooks/useCategory.tsx
@@ -1,6 +1,7 @@
import { SkillsIcon } from '@lobehub/ui/icons';
import {
AppWindowIcon,
+ BellIcon,
Blocks,
Brain,
Building2,
@@ -72,6 +73,11 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =
key: WorkspaceSettingsTabs.Devices,
label: t('tab.devices'),
},
+ {
+ icon: BellIcon,
+ key: WorkspaceSettingsTabs.Notification,
+ label: t('tab.notification'),
+ },
{
icon: ChartColumnBigIcon,
key: WorkspaceSettingsTabs.Stats,
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index ce47b62fcde..ae854678dfd 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -814,13 +814,19 @@ export const verifyKeys = {
export const inboxKeys = {
notifications: def(
'inbox:notifications',
- (cursor: string | undefined, unreadOnly: boolean | undefined) => [
+ // Keyed by context: the server scopes the inbox to the active workspace
+ // (null = personal), so cached pages must never be reused across contexts.
+ (workspaceId: string | null, cursor: string | undefined, unreadOnly: boolean | undefined) => [
'inbox:notifications',
+ workspaceId,
cursor,
unreadOnly,
],
),
- unreadCount: def('inbox:unreadCount', () => ['inbox:unreadCount']),
+ unreadCount: def('inbox:unreadCount', (workspaceId: string | null) => [
+ 'inbox:unreadCount',
+ workspaceId,
+ ]),
};
// ---- share (shared topic / page) ----------------------------------------
diff --git a/src/routes/(main)/[workspaceSlug]/settings/notification/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/notification/index.tsx
new file mode 100644
index 00000000000..dcf32e073ed
--- /dev/null
+++ b/src/routes/(main)/[workspaceSlug]/settings/notification/index.tsx
@@ -0,0 +1,5 @@
+'use client';
+
+import WorkspaceNotification from '@/business/client/BusinessSettingPages/WorkspaceNotification';
+
+export default WorkspaceNotification;
diff --git a/src/routes/(main)/home/_layout/Header/components/InboxDrawer/Content.tsx b/src/routes/(main)/home/_layout/Header/components/InboxDrawer/Content.tsx
index 0ff0f969e57..2d2f5759d68 100644
--- a/src/routes/(main)/home/_layout/Header/components/InboxDrawer/Content.tsx
+++ b/src/routes/(main)/home/_layout/Header/components/InboxDrawer/Content.tsx
@@ -8,6 +8,7 @@ import { useTranslation } from 'react-i18next';
import useSWRInfinite from 'swr/infinite';
import { VList, type VListHandle } from 'virtua';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import { inboxKeys } from '@/libs/swr/keys';
import { notificationService } from '@/services/notification';
@@ -26,18 +27,19 @@ interface ContentProps {
const Content = memo<ContentProps>(({ open, unreadOnly, onMarkAsRead, onArchive }) => {
const { t } = useTranslation('notification');
const virtuaRef = useRef<VListHandle>(null);
+ const workspaceId = useActiveWorkspaceId();
const getKey = useCallback(
(pageIndex: number, previousPageData: any[] | null) => {
if (!open) return null;
if (previousPageData && previousPageData.length < PAGE_SIZE) return null;
- if (pageIndex === 0) return inboxKeys.notifications(undefined, unreadOnly);
+ if (pageIndex === 0) return inboxKeys.notifications(workspaceId, undefined, unreadOnly);
const lastItem = previousPageData?.at(-1);
- return inboxKeys.notifications(lastItem?.id, unreadOnly);
+ return inboxKeys.notifications(workspaceId, lastItem?.id, unreadOnly);
},
- [open, unreadOnly],
+ [open, unreadOnly, workspaceId],
);
const {
@@ -45,7 +47,7 @@ const Content = memo<ContentProps>(({ open, unreadOnly, onMarkAsRead, onArchive
isLoading,
isValidating,
setSize,
- } = useSWRInfinite(getKey, async ([, cursor, filterUnread]) => {
+ } = useSWRInfinite(getKey, async ([, , cursor, filterUnread]) => {
return notificationService.list({
cursor: cursor as string | undefined,
limit: PAGE_SIZE,
diff --git a/src/routes/(main)/home/_layout/Header/components/InboxDrawer/index.tsx b/src/routes/(main)/home/_layout/Header/components/InboxDrawer/index.tsx
index 40377110b8a..3db53ed0bdc 100644
--- a/src/routes/(main)/home/_layout/Header/components/InboxDrawer/index.tsx
+++ b/src/routes/(main)/home/_layout/Header/components/InboxDrawer/index.tsx
@@ -6,6 +6,7 @@ import { ArchiveIcon, CheckCheckIcon, ListFilterIcon, MoreHorizontalIcon } from
import { memo, useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { DESKTOP_HEADER_ICON_SMALL_SIZE } from '@/const/layoutTokens';
import SkeletonList from '@/features/NavPanel/components/SkeletonList';
import SideBarDrawer from '@/features/NavPanel/SideBarDrawer';
@@ -31,11 +32,12 @@ interface InboxDrawerProps {
const InboxDrawer = memo<InboxDrawerProps>(({ open, onClose }) => {
const { t } = useTranslation('notification');
const [unreadOnly, setUnreadOnly] = useState(false);
+ const workspaceId = useActiveWorkspaceId();
const refreshList = useCallback(() => {
mutate((key: unknown) => Array.isArray(key) && key[0] === inboxKeys.notifications.root);
- mutate(inboxKeys.unreadCount());
- }, []);
+ mutate(inboxKeys.unreadCount(workspaceId));
+ }, [workspaceId]);
const handleMarkAsRead = useCallback(
async (id: string) => {
diff --git a/src/routes/(main)/home/_layout/Header/components/useInboxUnreadCount.test.ts b/src/routes/(main)/home/_layout/Header/components/useInboxUnreadCount.test.ts
index f7918d9a867..b7245f040b1 100644
--- a/src/routes/(main)/home/_layout/Header/components/useInboxUnreadCount.test.ts
+++ b/src/routes/(main)/home/_layout/Header/components/useInboxUnreadCount.test.ts
@@ -73,7 +73,7 @@ describe('useInboxUnreadCount', () => {
expect(result.current.enabled).toBe(true);
expect(mocks.useClientPollingSWR).toHaveBeenCalledWith(
- inboxKeys.unreadCount(),
+ inboxKeys.unreadCount(null),
expect.any(Function),
{
dedupingInterval: INBOX_UNREAD_COUNT_DEDUPING_INTERVAL,
diff --git a/src/routes/(main)/home/_layout/Header/components/useInboxUnreadCount.ts b/src/routes/(main)/home/_layout/Header/components/useInboxUnreadCount.ts
index 6589826452a..0a12aa339da 100644
--- a/src/routes/(main)/home/_layout/Header/components/useInboxUnreadCount.ts
+++ b/src/routes/(main)/home/_layout/Header/components/useInboxUnreadCount.ts
@@ -1,3 +1,4 @@
+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
import { useClientPollingSWR } from '@/libs/swr';
import { inboxKeys } from '@/libs/swr/keys';
import { notificationService } from '@/services/notification';
@@ -11,10 +12,11 @@ export const INBOX_UNREAD_COUNT_REFRESH_INTERVAL = 60_000;
export const useInboxUnreadCount = () => {
const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);
const isLogin = useUserStore(authSelectors.isLogin);
+ const workspaceId = useActiveWorkspaceId();
const enabled = enableBusinessFeatures && isLogin === true;
const { data: unreadCount = 0 } = useClientPollingSWR<number>(
- enabled ? inboxKeys.unreadCount() : null,
+ enabled ? inboxKeys.unreadCount(workspaceId) : null,
() => notificationService.getUnreadCount(),
{
dedupingInterval: INBOX_UNREAD_COUNT_DEDUPING_INTERVAL,
diff --git a/src/spa/router/desktopRouter.config.desktop.tsx b/src/spa/router/desktopRouter.config.desktop.tsx
index d0e32b4cb57..d2767dcca2b 100644
--- a/src/spa/router/desktopRouter.config.desktop.tsx
+++ b/src/spa/router/desktopRouter.config.desktop.tsx
@@ -48,6 +48,7 @@ import WorkspaceSlugSettingsCreditsPage from '@/routes/(main)/[workspaceSlug]/se
import WorkspaceSlugSettingsDevicesPage from '@/routes/(main)/[workspaceSlug]/settings/devices';
import WorkspaceSlugSettingsGeneralPage from '@/routes/(main)/[workspaceSlug]/settings/general';
import WorkspaceSlugSettingsMembersPage from '@/routes/(main)/[workspaceSlug]/settings/members';
+import WorkspaceSlugSettingsNotificationPage from '@/routes/(main)/[workspaceSlug]/settings/notification';
import WorkspaceSlugSettingsOAuthAppsPage from '@/routes/(main)/[workspaceSlug]/settings/oauth-apps';
import WorkspaceSlugSettingsPlansPage from '@/routes/(main)/[workspaceSlug]/settings/plans';
import WorkspaceSlugSettingsProviderPage from '@/routes/(main)/[workspaceSlug]/settings/provider';
@@ -728,6 +729,7 @@ export const desktopRoutes: RouteObject[] = [
children: [
{ element: <WorkspaceSlugSettingsGeneralPage />, path: 'general' },
{ element: <WorkspaceSlugSettingsMembersPage />, path: 'members' },
+ { element: <WorkspaceSlugSettingsNotificationPage />, path: 'notification' },
{ element: <WorkspaceSlugSettingsStatsPage />, path: 'stats' },
{ element: <WorkspaceSlugSettingsPlansPage />, path: 'plans' },
{ element: <WorkspaceSlugSettingsBillingPage />, path: 'billing' },
diff --git a/src/spa/router/desktopRouter.config.tsx b/src/spa/router/desktopRouter.config.tsx
index 8cd2581133c..15545419358 100644
--- a/src/spa/router/desktopRouter.config.tsx
+++ b/src/spa/router/desktopRouter.config.tsx
@@ -877,6 +877,13 @@ export const desktopRoutes: RouteObject[] = [
),
path: 'members',
},
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/notification'),
+ 'Desktop > Workspace > Settings > Notification',
+ ),
+ path: 'notification',
+ },
{
element: dynamicElement(
() => import('@/routes/(main)/[workspaceSlug]/settings/stats'),
diff --git a/src/spa/router/mobileRouter.config.tsx b/src/spa/router/mobileRouter.config.tsx
index f62b45c8a46..5f922f7ff2f 100644
--- a/src/spa/router/mobileRouter.config.tsx
+++ b/src/spa/router/mobileRouter.config.tsx
@@ -445,6 +445,13 @@ export const mobileRoutes: RouteObject[] = [
),
path: 'members',
},
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/[workspaceSlug]/settings/notification'),
+ 'Mobile > Workspace > Settings > Notification',
+ ),
+ path: 'notification',
+ },
{
element: dynamicElement(
() => import('@/routes/(main)/[workspaceSlug]/settings/plans'),
diff --git a/src/store/user/slices/workspaceUserSettings/action.test.ts b/src/store/user/slices/workspaceUserSettings/action.test.ts
index 4a9b55ead11..154a04edc00 100644
--- a/src/store/user/slices/workspaceUserSettings/action.test.ts
+++ b/src/store/user/slices/workspaceUserSettings/action.test.ts
@@ -83,4 +83,36 @@ describe('WorkspaceUserSettingsActionImpl', () => {
selected: false,
});
});
+
+ it('optimistically deep-merges one notification switch without dropping sibling toggles', async () => {
+ const state = {
+ workspaceUserPreference: {
+ notification: {
+ email: { items: { workspace: { workspace_member_joined: false } } },
+ inbox: { enabled: false },
+ },
+ },
+ };
+ const set = vi.fn((patch: Partial<typeof state>) => Object.assign(state, patch));
+ const action = new WorkspaceUserSettingsActionImpl(set as never, () => state as never);
+ vi.spyOn(workspaceUserSettingsService, 'updatePreference').mockResolvedValue();
+
+ // Patch a single other leaf β€” the earlier email item toggle and the inbox
+ // master switch must both survive in the optimistic cache, mirroring what
+ // the server-side deep merge keeps in the DB.
+ await action.updateWorkspaceUserPreference({
+ notification: {
+ email: { items: { workspace: { workspace_payment_failed: false } } },
+ },
+ });
+
+ expect(state.workspaceUserPreference.notification).toEqual({
+ email: {
+ items: {
+ workspace: { workspace_member_joined: false, workspace_payment_failed: false },
+ },
+ },
+ inbox: { enabled: false },
+ });
+ });
});
diff --git a/src/store/user/slices/workspaceUserSettings/action.ts b/src/store/user/slices/workspaceUserSettings/action.ts
index c58c01e03e0..203fc4dea20 100644
--- a/src/store/user/slices/workspaceUserSettings/action.ts
+++ b/src/store/user/slices/workspaceUserSettings/action.ts
@@ -1,4 +1,5 @@
import type { WorkspaceUserPreference } from '@lobechat/types';
+import { mergeNotificationSettings } from '@lobechat/utils/mergeNotificationSettings';
import { useEffect } from 'react';
import {
@@ -106,6 +107,11 @@ export class WorkspaceUserSettingsActionImpl {
},
}
: {}),
+ // Mirror the server's deep merge (WorkspaceUserSettingsModel) so the
+ // optimistic cache never drops sibling notification toggles the DB keeps.
+ ...(patch.notification
+ ? { notification: mergeNotificationSettings(previous.notification, patch.notification) }
+ : {}),
...(patch.sidebarGroupAssignments
? {
sidebarGroupAssignments: {
diff --git a/src/types/workspaceSettings.ts b/src/types/workspaceSettings.ts
index cd80911f64c..60ccc506292 100644
--- a/src/types/workspaceSettings.ts
+++ b/src/types/workspaceSettings.ts
@@ -15,6 +15,7 @@ export enum WorkspaceSettingsTabs {
Devices = 'devices',
General = 'general',
Members = 'members',
+ Notification = 'notification',
OAuthApps = 'oauth-apps',
Plans = 'plans',
Provider = 'provider',