π€― 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
β¨ feat(desktop): show OS notification when a workspace member mentions you (#21436)
AmAzing-cec9bdebbc3c
diff --git a/src/features/Electron/WorkspaceMentionNotifier/index.tsx b/src/features/Electron/WorkspaceMentionNotifier/index.tsxnew file mode 100644index 00000000000..11a0099ca46--- /dev/null+++ b/src/features/Electron/WorkspaceMentionNotifier/index.tsx@@ -0,0 +1,16 @@+'use client';++import { memo } from 'react';++import { useWorkspaceMentionNotifier } from './useWorkspaceMentionNotifier';++/** Desktop-only: pops an OS notification when a workspace member @-mentions the user. */+const WorkspaceMentionNotifier = memo(() => {+ useWorkspaceMentionNotifier();++ return null;+});++WorkspaceMentionNotifier.displayName = 'WorkspaceMentionNotifier';++export default WorkspaceMentionNotifier;diff --git a/src/features/Electron/WorkspaceMentionNotifier/mentionNotification.test.ts b/src/features/Electron/WorkspaceMentionNotifier/mentionNotification.test.tsnew file mode 100644index 00000000000..a5dd1dde359--- /dev/null+++ b/src/features/Electron/WorkspaceMentionNotifier/mentionNotification.test.ts@@ -0,0 +1,150 @@+import { describe, expect, it } from 'vitest';++import {+ MAX_MENTION_BANNERS_PER_POLL,+ type MentionNotificationRow,+ pickNewMentions,+ toMentionNotificationParams,+} from './mentionNotification';++/** Ids sort by creation time: `a` is the oldest, one second apart. */+const createdAt = (id: string) => new Date(Date.UTC(2026, 0, 1, 0, 0, id.charCodeAt(0) - 96));++const row = (+ id: string,+ overrides: Partial<MentionNotificationRow> = {},+): MentionNotificationRow => ({+ actionUrl: null,+ content: `content ${id}`,+ createdAt: createdAt(id),+ id,+ title: `title ${id}`,+ ...overrides,+});++const ids = (rows: MentionNotificationRow[]) => rows.map((item) => item.id);++describe('pickNewMentions', () => {+ it('treats the first page of a workspace as a baseline', () => {+ const { fresh, watermark } = pickNewMentions([row('b'), row('a')], undefined);++ expect(fresh).toEqual([]);+ expect(watermark).toEqual({ createdAt: createdAt('b').getTime(), ids: new Set(['b']) });+ });++ it('announces only rows newer than the watermark, oldest first', () => {+ const baseline = pickNewMentions([row('b'), row('a')], undefined);+ const { fresh, watermark } = pickNewMentions(+ [row('d'), row('c'), row('b'), row('a')],+ baseline.watermark,+ );++ expect(ids(fresh)).toEqual(['c', 'd']);+ expect(watermark.createdAt).toBe(createdAt('d').getTime());+ });++ it('announces the first mention after an empty baseline', () => {+ const baseline = pickNewMentions([], undefined);+ const { fresh } = pickNewMentions([row('a')], baseline.watermark);++ expect(ids(fresh)).toEqual(['a']);+ });++ it('does not re-announce a row that was read and dropped off the unread page', () => {+ const first = pickNewMentions(+ [row('b'), row('a')],+ pickNewMentions([row('a')], undefined).watermark,+ );+ const second = pickNewMentions([row('a')], first.watermark);++ expect(ids(first.fresh)).toEqual(['b']);+ expect(second.fresh).toEqual([]);+ });++ it('does not announce older unread mentions that scroll into the page', () => {+ // Baseline page holds the newest two; `a` sits beyond the page size.+ const baseline = pickNewMentions([row('c'), row('b')], undefined);+ // `c` is read, so the older unread `a` now fits on the page.+ const { fresh, watermark } = pickNewMentions([row('b'), row('a')], baseline.watermark);++ expect(fresh).toEqual([]);+ expect(watermark).toEqual(baseline.watermark);+ });++ it('tells apart mentions that share the watermark timestamp', () => {+ const sameTime = { createdAt: createdAt('b') };+ const baseline = pickNewMentions([row('b1', sameTime)], undefined);+ const { fresh, watermark } = pickNewMentions(+ [row('b2', sameTime), row('b1', sameTime)],+ baseline.watermark,+ );++ expect(ids(fresh)).toEqual(['b2']);+ expect(watermark.ids).toEqual(new Set(['b1', 'b2']));+ });++ it('caps a burst to the newest mentions', () => {+ const baseline = pickNewMentions([], undefined);+ const rows = ['e', 'd', 'c', 'b', 'a'].map((id) => row(id));+ const { fresh, watermark } = pickNewMentions(rows, baseline.watermark);++ expect(fresh).toHaveLength(MAX_MENTION_BANNERS_PER_POLL);+ expect(ids(fresh)).toEqual(['c', 'd', 'e']);+ // The skipped ones sit below the watermark so the next poll doesn't announce them late.+ expect(pickNewMentions(rows, watermark).fresh).toEqual([]);+ });+});++describe('toMentionNotificationParams', () => {+ it('uses the inbox title and a plain-text body', () => {+ const params = toMentionNotificationParams(+ row('a', { content: '**Alice**: can you check `this`?', title: 'Alice mentioned you' }),+ null,+ );++ expect(params.title).toBe('Alice mentioned you');+ expect(params.body).toBe('Alice: can you check this?');+ expect(params.force).toBeUndefined();+ });++ it('falls back to the context when the content is empty', () => {+ const params = toMentionNotificationParams(row('a', { content: '', context: 'Roadmap' }), null);++ expect(params.body).toBe('Roadmap');+ });++ it('caps a long body', () => {+ const params = toMentionNotificationParams(row('a', { content: 'x'.repeat(300) }), null);++ expect(params.body).toBe(`${'x'.repeat(256)}β¦`);+ });++ it('pins an in-app action url to the mention workspace', () => {+ const params = toMentionNotificationParams(+ row('a', { actionUrl: '/agent/agt_1/tpc_1' }),+ 'acme',+ );++ expect(params.navigate).toEqual({ escape: true, path: '/acme/agent/agt_1/tpc_1' });+ });++ it('keeps an already-prefixed action url as is', () => {+ const params = toMentionNotificationParams(row('a', { actionUrl: '/acme/page/doc_1' }), 'acme');++ expect(params.navigate).toEqual({ escape: true, path: '/acme/page/doc_1' });+ });++ it('skips navigation for external or missing action urls', () => {+ expect(+ toMentionNotificationParams(row('a', { actionUrl: 'https://example.com/x' }), 'acme')+ .navigate,+ ).toBeUndefined();+ expect(toMentionNotificationParams(row('a'), 'acme').navigate).toBeUndefined();+ });++ it('skips navigation for protocol-relative or backslash action urls', () => {+ for (const actionUrl of ['//evil.example/x', '/\\evil.example/x']) {+ expect(toMentionNotificationParams(row('a', { actionUrl }), 'acme').navigate).toBeUndefined();+ }+ });+});diff --git a/src/features/Electron/WorkspaceMentionNotifier/mentionNotification.ts b/src/features/Electron/WorkspaceMentionNotifier/mentionNotification.tsnew file mode 100644index 00000000000..3d198b8c75d--- /dev/null+++ b/src/features/Electron/WorkspaceMentionNotifier/mentionNotification.ts@@ -0,0 +1,113 @@+import type { ShowDesktopNotificationParams } from '@lobechat/electron-client-ipc';++import { buildWorkspaceAwarePath } from '@/features/Workspace/workspaceAwarePath';+import { markdownToTxt } from '@/utils/markdownToTxt';+import { isSafeRedirectPath } from '@/utils/onboardingRedirect';++/** The inbox row fields the mention banner reads. */+export interface MentionNotificationRow {+ actionUrl?: string | null;+ content: string;+ context?: string | null;+ createdAt: Date;+ id: string;+ title: string;+}++/** Cap the banner body so a long comment doesn't overflow the OS notification. */+const NOTIFICATION_BODY_MAX_LENGTH = 256;+/** At most this many banners per poll, so a burst of mentions doesn't flood the OS tray. */+export const MAX_MENTION_BANNERS_PER_POLL = 3;++/**+ * The newest mention a workspace has seen. Only rows created after it are new;+ * `ids` breaks ties between rows that share its exact timestamp.+ */+export interface MentionWatermark {+ createdAt: number;+ ids: Set<string>;+}++export interface PickNewMentionsResult {+ /** Rows to announce, oldest first. */+ fresh: MentionNotificationRow[];+ watermark: MentionWatermark;+}++const isAfter = (row: MentionNotificationRow, watermark: MentionWatermark): boolean => {+ const createdAt = row.createdAt.getTime();+ return (+ createdAt > watermark.createdAt ||+ (createdAt === watermark.createdAt && !watermark.ids.has(row.id))+ );+};++const advanceWatermark = (+ rows: MentionNotificationRow[],+ watermark: MentionWatermark | undefined,+): MentionWatermark => {+ // An empty baseline page still counts: any mention after it is new.+ let next = { createdAt: watermark?.createdAt ?? -Infinity, ids: new Set(watermark?.ids) };+ for (const row of rows) {+ const createdAt = row.createdAt.getTime();+ if (createdAt > next.createdAt) next = { createdAt, ids: new Set([row.id]) };+ else if (createdAt === next.createdAt) next.ids.add(row.id);+ }+ return next;+};++/**+ * Diff the latest unread-mention page (newest first) against the newest+ * mention already seen in this workspace. The first page a workspace returns+ * is a baseline: mentions that were already waiting in the inbox are not+ * replayed as banners. Comparing by creation time rather than by id keeps+ * older unread mentions that only scroll into the page β once newer ones are+ * read or archived β from being announced as if they had just arrived.+ */+export const pickNewMentions = (+ rows: MentionNotificationRow[],+ watermark: MentionWatermark | undefined,+): PickNewMentionsResult => {+ const nextWatermark = advanceWatermark(rows, watermark);+ if (!watermark) return { fresh: [], watermark: nextWatermark };++ const fresh = rows+ .filter((row) => isAfter(row, watermark))+ .slice(0, MAX_MENTION_BANNERS_PER_POLL)+ .reverse();++ return { fresh, watermark: nextWatermark };+};++const buildBody = (row: MentionNotificationRow): string => {+ const text = markdownToTxt(row.content).trim() || row.context?.trim() || '';+ return text.length > NOTIFICATION_BODY_MAX_LENGTH+ ? `${text.slice(0, NOTIFICATION_BODY_MAX_LENGTH)}β¦`+ : text;+};++/**+ * Resolve the banner click target the same way the inbox does: in-app paths+ * get the workspace prefix (pinned to the workspace the mention belongs to, so+ * a later workspace switch can't redirect the click), external URLs are left+ * to the inbox since the banner can only drive SPA navigation. Protocol-relative+ * (`//host`) and backslash paths are rejected so a row can't steer the click+ * off-origin.+ */+const buildNavigate = (+ actionUrl: string | null | undefined,+ workspaceSlug: string | null,+): ShowDesktopNotificationParams['navigate'] => {+ if (!actionUrl || !isSafeRedirectPath(actionUrl)) return undefined;++ return { escape: true, path: buildWorkspaceAwarePath(actionUrl, workspaceSlug) };+};++export const toMentionNotificationParams = (+ row: MentionNotificationRow,+ workspaceSlug: string | null,+): ShowDesktopNotificationParams => ({+ body: buildBody(row),+ navigate: buildNavigate(row.actionUrl, workspaceSlug),+ title: row.title,+});diff --git a/src/features/Electron/WorkspaceMentionNotifier/useWorkspaceMentionNotifier.test.ts b/src/features/Electron/WorkspaceMentionNotifier/useWorkspaceMentionNotifier.test.tsnew file mode 100644index 00000000000..f37f48b327f--- /dev/null+++ b/src/features/Electron/WorkspaceMentionNotifier/useWorkspaceMentionNotifier.test.ts@@ -0,0 +1,111 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { useSyncExternalStore } from 'react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { MentionNotificationRow } from './mentionNotification';++const mocks = vi.hoisted(() => ({+ enableBusinessFeatures: true,+ list: vi.fn(),+ listeners: new Set<() => void>(),+ rows: [] as MentionNotificationRow[],+ showNotification: vi.fn(),+ swrKey: undefined as unknown,+ workspaceId: 'ws_1' as string | null,+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => mocks.workspaceId,+}));+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({+ getActiveWorkspaceSlug: () => 'acme',+}));+vi.mock('@/libs/swr', () => ({+ // Reactive like real SWR: a new poll result re-renders the subscriber.+ useClientPollingSWR: (key: unknown) => {+ mocks.swrKey = key;+ const rows = useSyncExternalStore(+ (listener) => {+ mocks.listeners.add(listener);+ return () => mocks.listeners.delete(listener);+ },+ () => mocks.rows,+ );+ return { data: key ? rows : undefined };+ },+}));+vi.mock('@/services/electron/desktopNotification', () => ({+ desktopNotificationService: { showNotification: mocks.showNotification },+}));+vi.mock('@/services/notification', () => ({ notificationService: { list: mocks.list } }));+vi.mock('@/store/serverConfig', () => ({+ serverConfigSelectors: { enableBusinessFeatures: () => mocks.enableBusinessFeatures },+ useServerConfigStore: (selector: (s: unknown) => unknown) => selector({}),+}));+vi.mock('@/store/user', () => ({+ useUserStore: (selector: (s: unknown) => unknown) => selector({}),+}));+vi.mock('@/store/user/selectors', () => ({ authSelectors: { isLogin: () => true } }));++const { useWorkspaceMentionNotifier } = await import('./useWorkspaceMentionNotifier');++const poll = (rows: MentionNotificationRow[]) =>+ act(() => {+ mocks.rows = rows;+ for (const listener of mocks.listeners) listener();+ });++const row = (id: string): MentionNotificationRow => ({+ actionUrl: `/page/${id}`,+ content: `Bob: ping ${id}`,+ // `n1` < `n2` < β¦: later ids were created later.+ createdAt: new Date(Date.UTC(2026, 0, 1, 0, 0, Number(id.slice(1)))),+ id,+ title: 'Bob mentioned you',+});++describe('useWorkspaceMentionNotifier', () => {+ beforeEach(() => {+ mocks.enableBusinessFeatures = true;+ mocks.listeners.clear();+ mocks.rows = [];+ mocks.showNotification.mockReset().mockResolvedValue({ success: true });+ mocks.swrKey = undefined;+ mocks.workspaceId = 'ws_1';+ });++ it('does not replay mentions already waiting when the watcher starts', () => {+ mocks.rows = [row('n1')];+ renderHook(() => useWorkspaceMentionNotifier());++ expect(mocks.showNotification).not.toHaveBeenCalled();+ });++ it('shows an OS notification for a mention that arrives after the baseline', async () => {+ mocks.rows = [row('n1')];+ renderHook(() => useWorkspaceMentionNotifier());++ poll([row('n2'), row('n1')]);++ await waitFor(() => expect(mocks.showNotification).toHaveBeenCalledTimes(1));+ expect(mocks.showNotification).toHaveBeenCalledWith({+ body: 'Bob: ping n2',+ navigate: { escape: true, path: '/acme/page/n2' },+ title: 'Bob mentioned you',+ });+ });++ it('stays idle outside a workspace', () => {+ mocks.workspaceId = null;+ renderHook(() => useWorkspaceMentionNotifier());++ expect(mocks.swrKey).toBeNull();+ });++ it('stays idle without business features', () => {+ mocks.enableBusinessFeatures = false;+ renderHook(() => useWorkspaceMentionNotifier());++ expect(mocks.swrKey).toBeNull();+ });+});diff --git a/src/features/Electron/WorkspaceMentionNotifier/useWorkspaceMentionNotifier.ts b/src/features/Electron/WorkspaceMentionNotifier/useWorkspaceMentionNotifier.tsnew file mode 100644index 00000000000..98dab4b5e0e--- /dev/null+++ b/src/features/Electron/WorkspaceMentionNotifier/useWorkspaceMentionNotifier.ts@@ -0,0 +1,71 @@+import { useEffect } from 'react';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import { getActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { useSingleton } from '@/hooks/useSingleton';+import { useClientPollingSWR } from '@/libs/swr';+import { inboxKeys } from '@/libs/swr/keys';+import { desktopNotificationService } from '@/services/electron/desktopNotification';+import { notificationService } from '@/services/notification';+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';+import { useUserStore } from '@/store/user';+import { authSelectors } from '@/store/user/selectors';++import {+ MAX_MENTION_BANNERS_PER_POLL,+ type MentionNotificationRow,+ type MentionWatermark,+ pickNewMentions,+ toMentionNotificationParams,+} from './mentionNotification';++export const MENTION_POLL_INTERVAL = 30_000;+/** Page size: comfortably above the per-poll banner cap so a burst is still diffed whole. */+const MENTION_PAGE_SIZE = MAX_MENTION_BANNERS_PER_POLL * 5;++/**+ * Raises an OS notification when another workspace member @-mentions the user.+ *+ * Mentions land in the active workspace's inbox under the `mention` category;+ * this polls the unread ones and announces each one created after the newest+ * mention it has already seen.+ * The main process decides whether to show the banner (only while the window+ * is hidden or unfocused), so a user already looking at the app is not pinged+ * twice β the inbox bell still carries the mention.+ */+export const useWorkspaceMentionNotifier = (): void => {+ const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);+ const isLogin = useUserStore(authSelectors.isLogin);+ const workspaceId = useActiveWorkspaceId();+ const enabled = enableBusinessFeatures && isLogin === true && !!workspaceId;++ // Per workspace, so switching away and back doesn't re-announce old mentions.+ const watermarkByWorkspace = useSingleton(() => new Map<string, MentionWatermark>());++ const { data } = useClientPollingSWR<MentionNotificationRow[]>(+ enabled ? inboxKeys.unreadMentions(workspaceId) : null,+ () =>+ notificationService.list({ category: 'mention', isRead: false, limit: MENTION_PAGE_SIZE }),+ {+ dedupingInterval: MENTION_POLL_INTERVAL / 2,+ refreshInterval: MENTION_POLL_INTERVAL,+ // The banner matters most while the window is minimized or in the background.+ refreshWhenHidden: true,+ },+ );++ useEffect(() => {+ if (!data || !workspaceId) return;++ const { fresh, watermark } = pickNewMentions(data, watermarkByWorkspace.get(workspaceId));+ watermarkByWorkspace.set(workspaceId, watermark);+ if (fresh.length === 0) return;++ const workspaceSlug = getActiveWorkspaceSlug();+ for (const row of fresh) {+ desktopNotificationService+ .showNotification(toMentionNotificationParams(row, workspaceSlug))+ .catch((error) => console.error('Workspace mention desktop notification failed:', error));+ }+ }, [data, watermarkByWorkspace, workspaceId]);+};diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex aebbbaf428a..a9939c7c301 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -728,6 +728,11 @@ export const inboxKeys = {'inbox:unreadCount',workspaceId,]),+ /** Desktop mention-banner watcher: unread `mention` rows of the active workspace. */+ unreadMentions: def('inbox:unreadMentions', (workspaceId: string | null) => [+ 'inbox:unreadMentions',+ workspaceId,+ ]),};// ---- share (shared agent / topic / page) ---------------------------------diff --git a/src/routes/(main)/_layout/index.desktop.tsx b/src/routes/(main)/_layout/index.desktop.tsxindex 5c0d9c8c9d5..c61bd11f6f5 100644--- a/src/routes/(main)/_layout/index.desktop.tsx+++ b/src/routes/(main)/_layout/index.desktop.tsx@@ -28,6 +28,7 @@ import ZoomHUD from '@/features/Electron/system/ZoomHUD';import { TabHost, useSeedTabsOnBoot } from '@/features/Electron/TabHost';import TabCacheBridges from '@/features/Electron/titlebar/TabBar/TabCacheBridges';import TitleBar from '@/features/Electron/titlebar/TitleBar';+import WorkspaceMentionNotifier from '@/features/Electron/WorkspaceMentionNotifier';import HotkeyHelperPanel from '@/features/HotkeyHelperPanel';import NavPanelShell from '@/features/NavPanel/Shell';import { DndContextWrapper } from '@/features/ResourceManager/DndContextWrapper';@@ -101,6 +102,7 @@ const Layout: FC = () => {<RegisterHotkeys /><CmdkLazy /><GlobalApprovalNotification />+ <WorkspaceMentionNotifier /></Suspense></WorkspaceContextSlot></HotkeysProvider>