🤯 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): support macOS communication notifications with agent avatars (#18441)
Innei67058d0f9614
diff --git a/.github/workflows/manual-build-desktop.yml b/.github/workflows/manual-build-desktop.ymlindex 539098f9b85..38541282d1f 100644--- a/.github/workflows/manual-build-desktop.yml+++ b/.github/workflows/manual-build-desktop.yml@@ -110,6 +110,16 @@ jobs:- name: Set package versionrun: npm run workflow:set-desktop-version ${{ needs.version.outputs.version }} ${{ inputs.channel }}+ - name: Prepare macOS provisioning profile+ if: runner.os == 'macOS'+ env:+ MAC_PROVISIONING_PROFILE_BASE64: ${{ secrets.MAC_PROVISIONING_PROFILE_BASE64 }}+ run: |+ if [ -n "$MAC_PROVISIONING_PROFILE_BASE64" ]; then+ printf '%s' "$MAC_PROVISIONING_PROFILE_BASE64" | base64 --decode > "$RUNNER_TEMP/lobehub.provisionprofile"+ echo "MAC_PROVISIONING_PROFILE=$RUNNER_TEMP/lobehub.provisionprofile" >> "$GITHUB_ENV"+ fi+- name: Build artifact on macOSrun: npm run desktop:package:appenv:diff --git a/.github/workflows/pr-build-desktop.yml b/.github/workflows/pr-build-desktop.ymlindex 9a05339af1b..7ff3a888a3b 100644--- a/.github/workflows/pr-build-desktop.yml+++ b/.github/workflows/pr-build-desktop.yml@@ -113,6 +113,16 @@ jobs:- name: Set package versionrun: npm run workflow:set-desktop-version ${{ needs.version.outputs.version }} nightly+ - name: Prepare macOS provisioning profile+ if: runner.os == 'macOS'+ env:+ MAC_PROVISIONING_PROFILE_BASE64: ${{ secrets.MAC_PROVISIONING_PROFILE_BASE64 }}+ run: |+ if [ -n "$MAC_PROVISIONING_PROFILE_BASE64" ]; then+ printf '%s' "$MAC_PROVISIONING_PROFILE_BASE64" | base64 --decode > "$RUNNER_TEMP/lobehub.provisionprofile"+ echo "MAC_PROVISIONING_PROFILE=$RUNNER_TEMP/lobehub.provisionprofile" >> "$GITHUB_ENV"+ fi+# macOS 构建处理# 注意:fork 的 PR 无法访问 secrets,会构建未签名版本- name: Build artifact on macOSdiff --git a/.github/workflows/release-desktop-beta.yml b/.github/workflows/release-desktop-beta.ymlindex 13faafa0a09..9512226eb39 100644--- a/.github/workflows/release-desktop-beta.yml+++ b/.github/workflows/release-desktop-beta.yml@@ -93,6 +93,16 @@ jobs:- name: Set package versionrun: npm run workflow:set-desktop-version ${{ needs.check-beta.outputs.version }} beta+ - name: Prepare macOS provisioning profile+ if: runner.os == 'macOS'+ env:+ MAC_PROVISIONING_PROFILE_BASE64: ${{ secrets.MAC_PROVISIONING_PROFILE_BASE64 }}+ run: |+ if [ -n "$MAC_PROVISIONING_PROFILE_BASE64" ]; then+ printf '%s' "$MAC_PROVISIONING_PROFILE_BASE64" | base64 --decode > "$RUNNER_TEMP/lobehub.provisionprofile"+ echo "MAC_PROVISIONING_PROFILE=$RUNNER_TEMP/lobehub.provisionprofile" >> "$GITHUB_ENV"+ fi+# macOS 构建- name: Build artifact on macOSif: runner.os == 'macOS'diff --git a/.github/workflows/release-desktop-canary.yml b/.github/workflows/release-desktop-canary.ymlindex 134ea5f551a..37e3da74d31 100644--- a/.github/workflows/release-desktop-canary.yml+++ b/.github/workflows/release-desktop-canary.yml@@ -237,6 +237,16 @@ jobs:sudo rm -rf apps/desktop/dist || truesudo rm -rf /tmp/electron-builder* || true+ - name: Prepare macOS provisioning profile+ if: runner.os == 'macOS'+ env:+ MAC_PROVISIONING_PROFILE_BASE64: ${{ secrets.MAC_PROVISIONING_PROFILE_BASE64 }}+ run: |+ if [ -n "$MAC_PROVISIONING_PROFILE_BASE64" ]; then+ printf '%s' "$MAC_PROVISIONING_PROFILE_BASE64" | base64 --decode > "$RUNNER_TEMP/lobehub.provisionprofile"+ echo "MAC_PROVISIONING_PROFILE=$RUNNER_TEMP/lobehub.provisionprofile" >> "$GITHUB_ENV"+ fi+# macOS 构建- name: Build artifact on macOSif: runner.os == 'macOS'diff --git a/.github/workflows/release-desktop-stable.yml b/.github/workflows/release-desktop-stable.ymlindex 9a5236b22d3..a61155bf79b 100644--- a/.github/workflows/release-desktop-stable.yml+++ b/.github/workflows/release-desktop-stable.yml@@ -194,6 +194,16 @@ jobs:sudo rm -rf apps/desktop/dist || truesudo rm -rf /tmp/electron-builder* || true+ - name: Prepare macOS provisioning profile+ if: runner.os == 'macOS'+ env:+ MAC_PROVISIONING_PROFILE_BASE64: ${{ secrets.MAC_PROVISIONING_PROFILE_BASE64 }}+ run: |+ if [ -n "$MAC_PROVISIONING_PROFILE_BASE64" ]; then+ printf '%s' "$MAC_PROVISIONING_PROFILE_BASE64" | base64 --decode > "$RUNNER_TEMP/lobehub.provisionprofile"+ echo "MAC_PROVISIONING_PROFILE=$RUNNER_TEMP/lobehub.provisionprofile" >> "$GITHUB_ENV"+ fi+# macOS 构建- name: Build artifact on macOSif: runner.os == 'macOS'diff --git a/apps/desktop/.gitignore b/apps/desktop/.gitignoreindex fe69a3276f0..2e7aaf4e87a 100644--- a/apps/desktop/.gitignore+++ b/apps/desktop/.gitignore@@ -7,4 +7,6 @@ outstandalonerelease-bin\ No newline at end of file+bin++build/entitlements.mac.comm.generated.plist\ No newline at end of filediff --git a/apps/desktop/electron-builder.mjs b/apps/desktop/electron-builder.mjsindex fdc3e419484..23b6b06be88 100644--- a/apps/desktop/electron-builder.mjs+++ b/apps/desktop/electron-builder.mjs@@ -11,6 +11,7 @@ import {getExternalRuntimeModulesFilesConfig,} from './external-runtime-deps.config.mjs';import {+ buildFirstPartyNativeAddons,copyNativeModulesToSource,getAsarUnpackPatterns,getNativeModulesFilesConfig,@@ -27,6 +28,46 @@ const channel = process.env.UPDATE_CHANNEL;const arch = os.arch();const hasAppleCertificate = Boolean(process.env.CSC_LINK);+const macAppId = 'com.lobehub.lobehub-desktop';+// Communication notifications need the restricted+// `com.apple.developer.usernotifications.communication` entitlement, and+// macOS refuses to launch an app carrying it without a provisioning profile+// that authorizes it — so both must be applied together, and only when a+// profile is provided.+const macProvisioningProfile = process.env.MAC_PROVISIONING_PROFILE;+const macTeamId = process.env.APPLE_TEAM_ID;+const macCommunicationEntitlements =+ macProvisioningProfile && macTeamId+ ? path.join(__dirname, 'build', 'entitlements.mac.comm.generated.plist')+ : undefined;++if (macProvisioningProfile && !macTeamId) {+ console.warn(+ '⚠️ MAC_PROVISIONING_PROFILE is set but APPLE_TEAM_ID is missing — building without communication notification entitlements',+ );+}++if (macCommunicationEntitlements) {+ const baseEntitlements = await fs.readFile(+ path.join(__dirname, 'build', 'entitlements.mac.plist'),+ 'utf8',+ );+ const communicationKeys = [+ ' <key>com.apple.application-identifier</key>',+ ` <string>${macTeamId}.${macAppId}</string>`,+ ' <key>com.apple.developer.team-identifier</key>',+ ` <string>${macTeamId}</string>`,+ ' <key>com.apple.developer.usernotifications.communication</key>',+ ' <true/>',+ ' </dict>',+ ].join('\n');+ await fs.writeFile(+ macCommunicationEntitlements,+ baseEntitlements.replace('</dict>', communicationKeys),+ );+ console.info('🔔 Communication notification entitlements + provisioning profile enabled');+}+// 自定义更新服务器 URL (用于 stable 频道)const updateServerUrl = process.env.UPDATE_SERVER_URL;@@ -105,6 +146,8 @@ const config = {* This ensures native modules are properly included in the asar archive.*/beforePack: async () => {+ buildFirstPartyNativeAddons();+await copyNativeModulesToSource();await copyExternalRuntimeModulesToSource();@@ -167,7 +210,7 @@ const config = {}},afterSign: verifyFontListSignature,- appId: 'com.lobehub.lobehub-desktop',+ appId: macAppId,appImage: {artifactName: '${productName}-${version}.${ext}',},@@ -232,6 +275,12 @@ const config = {binaries: ['Contents/Resources/app.asar.unpacked/node_modules/font-list/libs/darwin/fontlist'],compression: 'maximum',entitlementsInherit: 'build/entitlements.mac.plist',+ ...(macCommunicationEntitlements+ ? {+ entitlements: macCommunicationEntitlements,+ provisioningProfile: macProvisioningProfile,+ }+ : {}),extendInfo: {CFBundleIconName: 'AppIcon',CFBundleURLTypes: [@@ -250,6 +299,7 @@ const config = {NSMicrophoneUsageDescription: "Application requests access to the device's microphone.",NSScreenCaptureUsageDescription:'Application requests access to record and analyze screen content for AI assistance.',+ NSUserActivityTypes: ['INSendMessageIntent'],},gatekeeperAssess: false,hardenedRuntime: hasAppleCertificate,diff --git a/apps/desktop/native-deps.config.mjs b/apps/desktop/native-deps.config.mjsindex 6d635fe046a..b5f1a332f7e 100644--- a/apps/desktop/native-deps.config.mjs+++ b/apps/desktop/native-deps.config.mjs@@ -8,7 +8,11 @@** This module automatically resolves the full dependency tree.*/+import { execSync } from 'node:child_process';+import fs from 'node:fs';import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';import {copyModulesToSource,@@ -16,6 +20,8 @@ import {getModuleFilesConfig,} from './module-deps.config.mjs';+const configDir = path.dirname(fileURLToPath(import.meta.url));+/*** Get the current target platform* During build, electron-builder sets npm_config_platform@@ -31,6 +37,60 @@ const isDarwin = getTargetPlatform() === 'darwin';// chain, neither of which is required in a macOS application artifact.const dependencyOptions = isDarwin ? { skipOptionalDependenciesFor: new Set(['get-windows']) } : {};+/**+ * First-party native addon packages are discovered instead of being listed by+ * hand: any `@lobechat/*` workspace package carrying a `binding.gyp` is one.+ * Per-platform gating comes from the package's own+ * `lobechat.nativeAddonPlatforms` field (absent = every platform), and its+ * `build:native` script is what the packaging pipeline invokes — so renaming+ * or adding an addon package never requires touching this file.+ */+export function discoverFirstPartyNativeAddons() {+ const scopeDir = path.join(configDir, 'node_modules', '@lobechat');+ let entries;+ try {+ entries = fs.readdirSync(scopeDir);+ } catch {+ return [];+ }++ const targetPlatform = getTargetPlatform();+ const addons = [];+ for (const entry of entries) {+ // pnpm renames displaced real directories (e.g. earlier copyModulesToSource+ // output) to `.ignored_*` on reinstall — they shadow the live symlink.+ if (entry.startsWith('.')) continue;+ const packageDir = path.join(scopeDir, entry);+ if (!fs.existsSync(path.join(packageDir, 'binding.gyp'))) continue;++ let packageJson;+ try {+ packageJson = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8'));+ } catch {+ continue;+ }++ const platforms = packageJson.lobechat?.nativeAddonPlatforms;+ if (Array.isArray(platforms) && !platforms.includes(targetPlatform)) continue;++ addons.push({+ hasBuildScript: Boolean(packageJson.scripts?.['build:native']),+ name: packageJson.name,+ });+ }+ return addons;+}++const firstPartyNativeAddons = discoverFirstPartyNativeAddons();++export function buildFirstPartyNativeAddons() {+ for (const addon of firstPartyNativeAddons) {+ if (!addon.hasBuildScript) continue;+ console.info(`🔧 Building native addon ${addon.name}...`);+ execSync(`pnpm --filter ${addon.name} build:native`, { cwd: configDir, stdio: 'inherit' });+ }+}+/*** List of native modules that need special handling* Only add the top-level native modules here - dependencies are resolved automatically@@ -38,6 +98,7 @@ const dependencyOptions = isDarwin ? { skipOptionalDependenciesFor: new Set(['ge* Platform-specific modules are only included when building for their target platform*/export const nativeModules = [+ ...firstPartyNativeAddons.map((addon) => addon.name),// macOS-only native modules...(isDarwin ? ['node-mac-permissions'] : []),'@lydell/node-pty',@@ -68,6 +129,7 @@ export function getNativeModulesFilesConfig() {*/export function getAsarUnpackPatterns() {return [+ ...firstPartyNativeAddons.map((addon) => `node_modules/${addon.name}/build/Release/*.node`),'node_modules/@lydell/node-pty-*/prebuilds/**/*.node','node_modules/@lydell/node-pty-*/prebuilds/*/spawn-helper','node_modules/font-list/libs/darwin/fontlist',diff --git a/apps/desktop/native-deps.config.test.ts b/apps/desktop/native-deps.config.test.tsnew file mode 100644index 00000000000..a831e7b8854--- /dev/null+++ b/apps/desktop/native-deps.config.test.ts@@ -0,0 +1,21 @@+import { readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { describe, expect, it } from 'vitest';++const macNotificationsPackage = JSON.parse(+ readFileSync(+ path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../packages/electron-mac-notifications/package.json',+ ),+ 'utf8',+ ),+) as { scripts?: Record<string, string> };++describe('first-party native addon install scripts', () => {+ it('overrides implicit node-gyp rebuild for the darwin-only notifications addon', () => {+ expect(macNotificationsPackage.scripts?.install).toBe('node scripts/build-native.mjs');+ });+});diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 0d8904cb376..9abab35f91f 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -68,10 +68,12 @@"@lobechat/device-identity": "workspace:*","@lobechat/device-sandbox": "workspace:*","@lobechat/electron-client-ipc": "workspace:*",+ "@lobechat/electron-mac-notifications": "workspace:*","@lobechat/electron-server-ipc": "workspace:*","@lobechat/file-loaders": "workspace:*","@lobechat/heterogeneous-agents": "workspace:*","@lobechat/local-file-shell": "workspace:*",+ "@lobechat/napi-loader": "workspace:*","@lobechat/tool-runtime": "workspace:*","@lobechat/utils": "workspace:*","@lobehub/i18n-cli": "^1.27.0",diff --git a/apps/desktop/pnpm-workspace.yaml b/apps/desktop/pnpm-workspace.yamlindex 89d6a6c45ef..9a9c8cb4aea 100644--- a/apps/desktop/pnpm-workspace.yaml+++ b/apps/desktop/pnpm-workspace.yaml@@ -6,6 +6,8 @@ packages:- '../../packages/const'- '../../packages/electron-server-ipc'- '../../packages/electron-client-ipc'+ - '../../packages/electron-mac-notifications'+ - '../../packages/napi-loader'- '../../packages/file-loaders'- '../../packages/desktop-bridge'- '../../packages/device-control'diff --git a/apps/desktop/src/main/controllers/NotificationCtr.mac.ts b/apps/desktop/src/main/controllers/NotificationCtr.mac.tsnew file mode 100644index 00000000000..06a92306243--- /dev/null+++ b/apps/desktop/src/main/controllers/NotificationCtr.mac.ts@@ -0,0 +1,200 @@+import type {+ DesktopNotificationResult,+ ShowDesktopNotificationParams,+} from '@lobechat/electron-client-ipc';+import {+ getAuthorizationStatus as getMacAuthorizationStatus,+ isSupported as isMacNotificationsSupported,+ onNotificationEvent as onMacNotificationEvent,+ requestAuthorization as requestMacAuthorization,+ showNotification as showMacNotification,+} from '@lobechat/electron-mac-notifications';+import { app, Notification } from 'electron';++import { getIpcContext } from '@/utils/ipc';+import { createLogger } from '@/utils/logger';++import { ControllerModule, IpcMethod } from './index';+import {+ isMainWindowHidden,+ openNotificationTarget,+ rememberNavigate,+ showElectronNotification,+ toLoggableNotificationParams,+} from './notificationShared';++const logger = createLogger('controllers:NotificationCtr');++export { toLoggableNotificationParams };++export default class NotificationCtr extends ControllerModule {+ static override readonly groupName = 'notification';++ private readonly navigateByNotificationId = new Map<+ string,+ ShowDesktopNotificationParams['navigate']+ >();++ @IpcMethod()+ async getNotificationPermissionStatus(): Promise<string> {+ if (isMacNotificationsSupported()) {+ const status = await getMacAuthorizationStatus();+ if (status !== 'unsupported') {+ if (status === 'authorized' || status === 'provisional') return 'authorized';+ return status;+ }+ }++ if (!Notification.isSupported()) return 'denied';++ const context = getIpcContext();+ const sender = context?.sender;+ if (!sender) return 'notDetermined';+ const permission = await sender.executeJavaScript('Notification.permission', true);+ return permission === 'granted' ? 'authorized' : 'denied';+ }++ @IpcMethod()+ async requestNotificationPermission(): Promise<void> {+ if (isMacNotificationsSupported()) {+ const granted = await requestMacAuthorization();+ logger.debug('macOS notification authorization requested, granted:', granted);+ return;+ }++ logger.debug('Requesting notification permission by sending a test notification');++ if (!Notification.isSupported()) {+ logger.warn('System does not support desktop notifications');+ return;+ }++ try {+ const mainWindow = this.app.browserManager.getMainWindow().browserWindow;+ await mainWindow.webContents.executeJavaScript('Notification.requestPermission()', true);+ } catch (error) {+ logger.debug(+ 'Notification.requestPermission() failed or is unavailable, continuing with test notification',+ error,+ );+ }++ const notification = new Notification({+ body: 'LobeHub can now send you notifications.',+ title: 'Notification Permission',+ });++ notification.show();+ }++ afterAppReady() {+ this.setupMacNotificationClicks();+ }++ private setupMacNotificationClicks() {+ if (!isMacNotificationsSupported()) return;++ onMacNotificationEvent((event) => {+ if (event.type !== 'clicked') return;+ logger.debug('macOS notification clicked:', event.id);+ const navigate = this.navigateByNotificationId.get(event.id);+ this.navigateByNotificationId.delete(event.id);+ openNotificationTarget(this.app, navigate);+ });+ }++ private async showViaMacNotifications(+ params: ShowDesktopNotificationParams,+ ): Promise<DesktopNotificationResult | undefined> {+ try {+ const result = await showMacNotification({+ body: params.body,+ sender: params.sender,+ silent: params.silent,+ title: params.title,+ });++ if (!result.ok) {+ logger.warn('macOS notification addon failed, falling back to Electron:', result.reason);+ return undefined;+ }++ rememberNavigate(this.navigateByNotificationId, result.id, params.navigate);+ logger.info('macOS notification shown via native addon:', result.id);+ return { success: true };+ } catch (error) {+ logger.error('macOS notification addon threw, falling back to Electron:', error);+ return undefined;+ }+ }++ @IpcMethod()+ async showDesktopNotification(+ params: ShowDesktopNotificationParams,+ ): Promise<DesktopNotificationResult> {+ logger.debug('Received desktop notification request:', toLoggableNotificationParams(params));++ try {+ const hidden = isMainWindowHidden(this.app);++ if (!params.force && !hidden) {+ logger.debug('Main window is visible, skipping desktop notification');+ return { reason: 'Window is visible', skipped: true, success: true };+ }++ if (params.requestAttention && hidden) {+ this.requestUserAttention();+ }++ if (isMacNotificationsSupported()) {+ const macResult = await this.showViaMacNotifications(params);+ if (macResult) return macResult;+ }++ if (!Notification.isSupported()) {+ logger.warn('System does not support desktop notifications');+ return { error: 'Desktop notifications not supported', success: false };+ }++ logger.info('Showing desktop notification:', params.title);++ return showElectronNotification({+ onClick: () => openNotificationTarget(this.app, params.navigate),+ params,+ urgency: 'normal',+ });+ } catch (error) {+ logger.error('Failed to show desktop notification:', error);+ return {+ error: error instanceof Error ? error.message : 'Unknown error',+ success: false,+ };+ }+ }++ private requestUserAttention(): void {+ try {+ const mainWindow = this.app.browserManager.getMainWindow().browserWindow;+ if (mainWindow.isDestroyed()) return;+ app.dock?.bounce?.('informational');+ } catch (error) {+ logger.error('Failed to request user attention:', error);+ }+ }++ @IpcMethod()+ setBadgeCount(count: number): void {+ try {+ const next = Math.max(0, Math.floor(count));+ app.setBadgeCount(next);+ app.dock?.setBadge(next > 0 ? String(next) : '');+ } catch (error) {+ logger.error('Failed to set badge count:', error);+ }+ }++ @IpcMethod()+ isMainWindowHidden(): boolean {+ return isMainWindowHidden(this.app);+ }+}diff --git a/apps/desktop/src/main/controllers/NotificationCtr.ts b/apps/desktop/src/main/controllers/NotificationCtr.tsindex e01c4a2cb76..00c7009fdae 100644--- a/apps/desktop/src/main/controllers/NotificationCtr.ts+++ b/apps/desktop/src/main/controllers/NotificationCtr.ts@@ -4,32 +4,28 @@ import type {} from '@lobechat/electron-client-ipc';import { app, Notification } from 'electron';-import { getIpcContext } from '@/utils/ipc';import { createLogger } from '@/utils/logger';import * as electronIs from '@/utils/platform';import { ControllerModule, IpcMethod } from './index';+import {+ isMainWindowHidden,+ openNotificationTarget,+ showElectronNotification,+ toLoggableNotificationParams,+} from './notificationShared';const logger = createLogger('controllers:NotificationCtr');+export { toLoggableNotificationParams };+export default class NotificationCtr extends ControllerModule {static override readonly groupName = 'notification';@IpcMethod()async getNotificationPermissionStatus(): Promise<string> {if (!Notification.isSupported()) return 'denied';- // Keep a stable status string for renderer-side UI mapping.- // Screen3 expects macOS to return 'authorized' when granted.- if (!electronIs.macOS()) return 'authorized';-- // Electron 38 no longer exposes `systemPreferences.getNotificationSettings()` in types,- // and some runtimes don't provide it at all. Use the renderer's Notification.permission- // as a reliable fallback.- const context = getIpcContext();- const sender = context?.sender;- if (!sender) return 'notDetermined';- const permission = await sender.executeJavaScript('Notification.permission', true);- return permission === 'granted' ? 'authorized' : 'denied';+ return 'authorized';}@IpcMethod()@@ -41,20 +37,6 @@ export default class NotificationCtr extends ControllerModule {return;}- // On macOS, ask permission via Web Notification API first when possible.- // This helps keep `Notification.permission` in sync for subsequent status checks.- if (electronIs.macOS()) {- try {- const mainWindow = this.app.browserManager.getMainWindow().browserWindow;- await mainWindow.webContents.executeJavaScript('Notification.requestPermission()', true);- } catch (error) {- logger.debug(- 'Notification.requestPermission() failed or is unavailable, continuing with test notification',- error,- );- }- }-const notification = new Notification({body: 'LobeHub can now send you notifications.',title: 'Notification Permission',@@ -62,32 +44,20 @@ export default class NotificationCtr extends ControllerModule {notification.show();}- /**- * Set up desktop notifications after the application is ready- */+afterAppReady() {this.setupNotifications();}- /**- * Set up desktop notification permissions and configuration- */private setupNotifications() {logger.debug('Setting up desktop notifications');try {- // Check notification supportif (!Notification.isSupported()) {logger.warn('Desktop notifications are not supported on this platform');return;}- // On macOS, we may need to explicitly request notification permissions- if (electronIs.macOS()) {- logger.debug('macOS detected, notification permissions should be handled by system');- }-- // Set app user model ID on Windowsif (electronIs.windows()) {app.setAppUserModelId('com.lobehub.chat');logger.debug('Set Windows App User Model ID for notifications');@@ -98,88 +68,37 @@ export default class NotificationCtr extends ControllerModule {logger.error('Failed to setup desktop notifications:', error);}}- /**- * Show system desktop notification.- * By default notifications only appear when the main window is hidden or unfocused.- * High-priority callers can pass `force` to surface a banner even while focused.- */+@IpcMethod()async showDesktopNotification(params: ShowDesktopNotificationParams,): Promise<DesktopNotificationResult> {- logger.debug('Received desktop notification request:', params);+ logger.debug('Received desktop notification request:', toLoggableNotificationParams(params));try {- // Check notification supportif (!Notification.isSupported()) {logger.warn('System does not support desktop notifications');return { error: 'Desktop notifications not supported', success: false };}- // Check if window is hidden- const isWindowHidden = this.isMainWindowHidden();+ const hidden = isMainWindowHidden(this.app);- if (!params.force && !isWindowHidden) {+ if (!params.force && !hidden) {logger.debug('Main window is visible, skipping desktop notification');return { reason: 'Window is visible', skipped: true, success: true };}- if (params.requestAttention && isWindowHidden) {+ if (params.requestAttention && hidden) {this.requestUserAttention();}logger.info('Showing desktop notification:', params.title);- const notification = new Notification({- body: params.body,- // Add more configuration to ensure notifications display properly- hasReply: false,- silent: params.silent || false,- timeoutType: 'default',- title: params.title,- // On Linux/GNOME Shell, urgency 'normal' causes notifications to appear as banners.- // Clicking the dismiss (X) button on such banners can freeze the system for 30-45 seconds- // due to heavy gnome-shell processing. Using 'low' urgency routes notifications to the- // message tray instead, preventing the banner's X button from being shown.- // The urgency option is ignored on macOS and Windows.+ return showElectronNotification({+ onClick: () => openNotificationTarget(this.app, params.navigate),+ params,urgency: electronIs.linux() ? 'low' : 'normal',});-- // Add more event listeners for debugging- notification.on('show', () => {- logger.info('Notification shown');- });-- notification.on('click', () => {- logger.debug('User clicked notification, showing main window');- // Reuse the shared show path so a *minimized* window is restored first.- // A bare `Browser.show()` cannot un-minimize on macOS, which made the- // notification intermittently fail to surface the app (worked only when- // the window was hidden, not when minimized to the Dock).- this.app.browserManager.showMainWindow();- if (params.navigate?.path) {- this.app.browserManager.getMainWindow().broadcast('navigate', params.navigate);- }- });-- notification.on('close', () => {- logger.debug('Notification closed');- });-- notification.on('failed', (error) => {- logger.error('Notification display failed:', error);- });-- // Use Promise to ensure notification is shown- return new Promise((resolve) => {- notification.show();-- // Give the notification some time to display, then check the result- setTimeout(() => {- logger.info('Notification display call completed');- resolve({ success: true });- }, 100);- });} catch (error) {logger.error('Failed to show desktop notification:', error);return {@@ -192,68 +111,24 @@ export default class NotificationCtr extends ControllerModule {private requestUserAttention(): void {try {const mainWindow = this.app.browserManager.getMainWindow().browserWindow;-if (mainWindow.isDestroyed()) return;-- if (electronIs.macOS()) {- app.dock?.bounce?.('informational');- return;- }-mainWindow.flashFrame(true);} catch (error) {logger.error('Failed to request user attention:', error);}}- /**- * Set the app-level badge count (dock red dot on macOS, Unity counter on Linux,- * overlay icon on Windows). Pass 0 to clear.- *- * On macOS we pair `app.setBadgeCount` with `app.dock.setBadge` — the former- * keeps Electron's internal count (cross-platform), the latter is the- * reliable Dock repaint trigger. Note: macOS Focus Mode / DND suppresses the- * badge visually until the user exits Focus.- */@IpcMethod()setBadgeCount(count: number): void {try {- const next = Math.max(0, Math.floor(count));- app.setBadgeCount(next);- if (electronIs.macOS() && app.dock) {- app.dock.setBadge(next > 0 ? String(next) : '');- }+ app.setBadgeCount(Math.max(0, Math.floor(count)));} catch (error) {logger.error('Failed to set badge count:', error);}}- /**- * Check if the main window is hidden- */@IpcMethod()isMainWindowHidden(): boolean {- try {- const mainWindow = this.app.browserManager.getMainWindow();- const browserWindow = mainWindow.browserWindow;-- // If window is destroyed, consider it hidden- if (browserWindow.isDestroyed()) {- return true;- }-- // Check if window is visible and focused- const isVisible = browserWindow.isVisible();- const isFocused = browserWindow.isFocused();- const isMinimized = browserWindow.isMinimized();-- logger.debug('Window state check:', { isFocused, isMinimized, isVisible });-- // Window is hidden if: not visible, minimized, or not focused- return !isVisible || isMinimized || !isFocused;- } catch (error) {- logger.error('Failed to check window state:', error);- return true; // Consider window hidden on error to ensure notifications can be shown- }+ return isMainWindowHidden(this.app);}}diff --git a/apps/desktop/src/main/controllers/__tests__/NotificationCtr.mac.test.ts b/apps/desktop/src/main/controllers/__tests__/NotificationCtr.mac.test.tsnew file mode 100644index 00000000000..7f66d41e2c9--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/NotificationCtr.mac.test.ts@@ -0,0 +1,194 @@+import type { ShowDesktopNotificationParams } from '@lobechat/electron-client-ipc';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';++import NotificationCtr from '../NotificationCtr.mac';++const { ipcMainHandleMock, loggerMock, macNotificationsMock } = vi.hoisted(() => ({+ ipcMainHandleMock: vi.fn(),+ loggerMock: {+ debug: vi.fn(),+ error: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ },+ macNotificationsMock: {+ getAuthorizationStatus: vi.fn(async () => 'authorized'),+ isSupported: vi.fn(() => true),+ onNotificationEvent: vi.fn(+ (_listener: (event: { id: string; type: string }) => void) => () => {},+ ),+ requestAuthorization: vi.fn(async () => true),+ showNotification: vi.fn(async (): Promise<{ id: string; ok: boolean; reason?: string }> => ({+ id: 'lobehub-test-id',+ ok: true,+ })),+ },+}));++vi.mock('@lobechat/electron-mac-notifications', () => macNotificationsMock);++vi.mock('@/utils/logger', () => ({+ createLogger: () => loggerMock,+}));++vi.mock('electron', () => {+ const mockNotificationInstance = {+ on: vi.fn(),+ show: vi.fn(),+ };+ const MockNotification = vi.fn(() => mockNotificationInstance) as any;+ MockNotification.isSupported = vi.fn(() => true);++ return {+ ipcMain: {+ handle: ipcMainHandleMock,+ },+ Notification: MockNotification,+ app: {+ dock: {+ bounce: vi.fn(),+ setBadge: vi.fn(),+ },+ setAppUserModelId: vi.fn(),+ setBadgeCount: vi.fn(),+ },+ };+});++const mockBrowserWindow = {+ flashFrame: vi.fn(),+ isDestroyed: vi.fn(() => false),+ isFocused: vi.fn(() => true),+ isMinimized: vi.fn(() => false),+ isVisible: vi.fn(() => true),+ webContents: {+ executeJavaScript: vi.fn(),+ },+};++const mockMainWindow = {+ broadcast: vi.fn(),+ browserWindow: mockBrowserWindow,+};++const mockBrowserManager = {+ getMainWindow: vi.fn(() => mockMainWindow),+ showMainWindow: vi.fn(),+};++const mockApp = {+ browserManager: mockBrowserManager,+} as unknown as App;++describe('NotificationCtr.mac', () => {+ let controller: NotificationCtr;++ beforeEach(() => {+ vi.clearAllMocks();+ vi.useFakeTimers();+ macNotificationsMock.isSupported.mockReturnValue(true);+ controller = new NotificationCtr(mockApp);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ const params: ShowDesktopNotificationParams = {+ body: 'Reply body',+ sender: { conversationId: 'agent-1:topic-1', name: 'My Agent' },+ title: 'My Agent',+ };++ it('routes notifications through the native addon instead of Electron', async () => {+ const { Notification } = await import('electron');+ mockBrowserWindow.isVisible.mockReturnValue(false);++ const result = await controller.showDesktopNotification(params);++ expect(macNotificationsMock.showNotification).toHaveBeenCalledWith({+ body: 'Reply body',+ sender: params.sender,+ silent: undefined,+ title: 'My Agent',+ });+ expect(Notification).not.toHaveBeenCalled();+ expect(result).toEqual({ success: true });+ });++ it('falls back to the Electron notification when the addon reports failure', async () => {+ const { Notification } = await import('electron');+ mockBrowserWindow.isVisible.mockReturnValue(false);+ macNotificationsMock.showNotification.mockResolvedValueOnce({+ id: 'lobehub-x',+ ok: false,+ reason: 'denied',+ });++ const promise = controller.showDesktopNotification(params);+ await vi.advanceTimersByTimeAsync(200);+ const result = await promise;++ expect(Notification).toHaveBeenCalled();+ expect(result).toEqual({ success: true });+ });++ it('navigates when a mac notification is clicked', async () => {+ mockBrowserWindow.isVisible.mockReturnValue(false);+ let handler: (event: { id: string; type: string }) => void = () => {};+ macNotificationsMock.onNotificationEvent.mockImplementation((listener) => {+ handler = listener;+ return () => {};+ });+ macNotificationsMock.showNotification.mockResolvedValueOnce({ id: 'lobehub-nav', ok: true });+ const navigate = { escape: true, path: '/agent/a1/t1' };++ controller.afterAppReady();+ await controller.showDesktopNotification({ ...params, navigate });++ handler({ id: 'lobehub-nav', type: 'clicked' });++ expect(mockBrowserManager.showMainWindow).toHaveBeenCalled();+ expect(mockMainWindow.broadcast).toHaveBeenCalledWith('navigate', navigate);+ });++ it('reports permission status from the addon', async () => {+ macNotificationsMock.getAuthorizationStatus.mockResolvedValueOnce('denied');+ expect(await controller.getNotificationPermissionStatus()).toBe('denied');++ macNotificationsMock.getAuthorizationStatus.mockResolvedValueOnce('provisional');+ expect(await controller.getNotificationPermissionStatus()).toBe('authorized');+ });++ it('requests permission through the addon without showing a test notification', async () => {+ const { Notification } = await import('electron');++ await controller.requestNotificationPermission();++ expect(macNotificationsMock.requestAuthorization).toHaveBeenCalled();+ expect(Notification).not.toHaveBeenCalled();+ });++ it('bounces the dock when attention is requested', async () => {+ const { app } = await import('electron');+ mockBrowserWindow.isVisible.mockReturnValue(false);++ await controller.showDesktopNotification({+ ...params,+ requestAttention: true,+ });++ expect(app.dock.bounce).toHaveBeenCalledWith('informational');+ });++ it('pairs setBadgeCount with the dock badge', async () => {+ const { app } = await import('electron');++ controller.setBadgeCount(3);++ expect(app.setBadgeCount).toHaveBeenCalledWith(3);+ expect(app.dock.setBadge).toHaveBeenCalledWith('3');+ });+});diff --git a/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.tsindex 420c305dbae..d8e83146bc8 100644--- a/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/NotificationCtr.test.ts@@ -5,18 +5,18 @@ import type { App } from '@/core/App';import NotificationCtr from '../NotificationCtr';-const { ipcMainHandleMock } = vi.hoisted(() => ({+const { ipcMainHandleMock, loggerMock } = vi.hoisted(() => ({ipcMainHandleMock: vi.fn(),-}));--// Mock logger-vi.mock('@/utils/logger', () => ({- createLogger: () => ({+ loggerMock: {debug: vi.fn(),error: vi.fn(),info: vi.fn(),warn: vi.fn(),- }),+ },+}));++vi.mock('@/utils/logger', () => ({+ createLogger: () => loggerMock,}));// Mock electron@@ -119,18 +119,6 @@ describe('NotificationCtr', () => {vi.mocked(windows).mockReturnValue(false);});-- it('should handle macOS platform', async () => {- const { macOS } = await import('@/utils/platform');- const { Notification } = await import('electron');- vi.mocked(macOS).mockReturnValue(true);- vi.mocked(Notification.isSupported).mockReturnValue(true);-- // Should not throw- expect(() => controller.afterAppReady()).not.toThrow();-- vi.mocked(macOS).mockReturnValue(false);- });});describe('showDesktopNotification', () => {@@ -151,6 +139,28 @@ describe('NotificationCtr', () => {});});+ it('does not log the avatar data URL', async () => {+ const { Notification } = await import('electron');+ vi.mocked(Notification.isSupported).mockReturnValue(true);+ mockBrowserWindow.isVisible.mockReturnValue(true);+ mockBrowserWindow.isFocused.mockReturnValue(true);+ mockBrowserWindow.isMinimized.mockReturnValue(false);++ const avatarDataUrl = `data:image/png;base64,${'A'.repeat(80)}`;+ await controller.showDesktopNotification({+ ...params,+ sender: { avatarDataUrl, conversationId: 'a1', name: 'Agent' },+ });++ expect(loggerMock.debug).toHaveBeenCalledWith(+ 'Received desktop notification request:',+ expect.objectContaining({+ sender: { avatarDataUrl: '[redacted]', conversationId: 'a1', name: 'Agent' },+ }),+ );+ expect(JSON.stringify(loggerMock.debug.mock.calls)).not.toContain(avatarDataUrl);+ });+it('should skip notification when window is visible and focused', async () => {const { Notification } = await import('electron');vi.mocked(Notification.isSupported).mockReturnValue(true);@@ -291,25 +301,6 @@ describe('NotificationCtr', () => {expect(mockBrowserWindow.flashFrame).toHaveBeenCalledWith(true);});- it('should bounce dock on macOS when attention is requested', async () => {- const { app, Notification } = await import('electron');- const { macOS } = await import('@/utils/platform');- vi.mocked(macOS).mockReturnValue(true);- vi.mocked(Notification.isSupported).mockReturnValue(true);- mockBrowserWindow.isVisible.mockReturnValue(false);-- const promise = controller.showDesktopNotification({- ...params,- requestAttention: true,- });- vi.advanceTimersByTime(100);- await promise;-- expect(app.dock.bounce).toHaveBeenCalledWith('informational');-- vi.mocked(macOS).mockReturnValue(false);- });-it('should register click handler to show main window', async () => {const { Notification } = await import('electron');vi.mocked(Notification.isSupported).mockReturnValue(true);diff --git a/apps/desktop/src/main/controllers/notificationShared.ts b/apps/desktop/src/main/controllers/notificationShared.tsnew file mode 100644index 00000000000..37e32172fb2--- /dev/null+++ b/apps/desktop/src/main/controllers/notificationShared.ts@@ -0,0 +1,102 @@+import type {+ DesktopNotificationResult,+ ShowDesktopNotificationParams,+} from '@lobechat/electron-client-ipc';+import { Notification } from 'electron';++import type { App } from '@/core/App';+import { createLogger } from '@/utils/logger';++const logger = createLogger('controllers:NotificationCtr');++export const NAVIGATE_MAP_LIMIT = 100;++export const toLoggableNotificationParams = (params: ShowDesktopNotificationParams) => {+ if (!params.sender?.avatarDataUrl) return params;+ return {+ ...params,+ sender: { ...params.sender, avatarDataUrl: '[redacted]' },+ };+};++export const isMainWindowHidden = (app: App): boolean => {+ try {+ const browserWindow = app.browserManager.getMainWindow().browserWindow;+ if (browserWindow.isDestroyed()) return true;++ const isVisible = browserWindow.isVisible();+ const isFocused = browserWindow.isFocused();+ const isMinimized = browserWindow.isMinimized();+ logger.debug('Window state check:', { isFocused, isMinimized, isVisible });+ return !isVisible || isMinimized || !isFocused;+ } catch (error) {+ logger.error('Failed to check window state:', error);+ return true;+ }+};++export const openNotificationTarget = (+ app: App,+ navigate?: ShowDesktopNotificationParams['navigate'],+) => {+ app.browserManager.showMainWindow();+ if (navigate?.path) {+ app.browserManager.getMainWindow().broadcast('navigate', navigate);+ }+};++export const rememberNavigate = (+ map: Map<string, ShowDesktopNotificationParams['navigate']>,+ id: string,+ navigate: ShowDesktopNotificationParams['navigate'],+) => {+ if (!navigate?.path) return;+ map.set(id, navigate);+ if (map.size <= NAVIGATE_MAP_LIMIT) return;+ const oldest = map.keys().next().value;+ if (oldest) map.delete(oldest);+};++export const showElectronNotification = ({+ onClick,+ params,+ urgency,+}: {+ onClick: () => void;+ params: ShowDesktopNotificationParams;+ urgency: 'low' | 'normal';+}): Promise<DesktopNotificationResult> => {+ const notification = new Notification({+ body: params.body,+ hasReply: false,+ silent: params.silent || false,+ timeoutType: 'default',+ title: params.title,+ urgency,+ });++ notification.on('show', () => {+ logger.info('Notification shown');+ });++ notification.on('click', () => {+ logger.debug('User clicked notification, showing main window');+ onClick();+ });++ notification.on('close', () => {+ logger.debug('Notification closed');+ });++ notification.on('failed', (error) => {+ logger.error('Notification display failed:', error);+ });++ return new Promise((resolve) => {+ notification.show();+ setTimeout(() => {+ logger.info('Notification display call completed');+ resolve({ success: true });+ }, 100);+ });+};diff --git a/apps/desktop/vite.main.config.ts b/apps/desktop/vite.main.config.tsindex 2e61be7f800..d722c57f8d4 100644--- a/apps/desktop/vite.main.config.ts+++ b/apps/desktop/vite.main.config.ts@@ -2,6 +2,7 @@ import path from 'node:path';import { defineConfig, type UserConfig } from 'vite';+import { viteOsPlatformResolve } from '../../plugins/vite/osPlatformResolve';import { externalRuntimeModules } from './external-runtime-deps.config.mjs';import { getNativeExternalDependencies } from './native-deps.config.mjs';import {@@ -112,6 +113,7 @@ export default defineConfig(async (env) => {'process.env.UPDATE_CHANNEL': JSON.stringify(process.env.UPDATE_CHANNEL),'process.env.UPDATE_SERVER_URL': JSON.stringify(process.env.UPDATE_SERVER_URL),},+ plugins: [viteOsPlatformResolve()],publicDir: false,resolve: {alias: mainProcessAlias,diff --git a/apps/desktop/vite.preload.config.ts b/apps/desktop/vite.preload.config.tsindex e4153c97ba6..4865a62b0dd 100644--- a/apps/desktop/vite.preload.config.ts+++ b/apps/desktop/vite.preload.config.ts@@ -2,6 +2,7 @@ import path from 'node:path';import { defineConfig, type UserConfig } from 'vite';+import { viteOsPlatformResolve } from '../../plugins/vite/osPlatformResolve';import {applyDesktopViteConfigExtension,loadDesktopEnv,@@ -39,6 +40,7 @@ export default defineConfig(async (env) => {target: MAIN_NODE_TARGET,},define: { ...processEnvDefine },+ plugins: [viteOsPlatformResolve()],publicDir: false,resolve: {alias: mainProcessAlias,diff --git a/packages/electron-client-ipc/src/types/notification.ts b/packages/electron-client-ipc/src/types/notification.tsindex c96a11e5998..457e3c71380 100644--- a/packages/electron-client-ipc/src/types/notification.ts+++ b/packages/electron-client-ipc/src/types/notification.ts@@ -1,3 +1,13 @@+export interface DesktopNotificationSender {+ /**+ * PNG data URL rendered by the caller; when present on macOS the+ * notification is styled as a communication notification with this avatar.+ */+ avatarDataUrl?: string;+ conversationId: string;+ name: string;+}+export interface ShowDesktopNotificationParams {body: string;force?: boolean;@@ -11,6 +21,7 @@ export interface ShowDesktopNotificationParams {*/navigate?: { escape?: boolean; path: string; replace?: boolean };requestAttention?: boolean;+ sender?: DesktopNotificationSender;silent?: boolean;title: string;}diff --git a/packages/electron-mac-notifications/.gitignore b/packages/electron-mac-notifications/.gitignorenew file mode 100644index 00000000000..567609b1234--- /dev/null+++ b/packages/electron-mac-notifications/.gitignore@@ -0,0 +1 @@+build/diff --git a/packages/electron-mac-notifications/README.md b/packages/electron-mac-notifications/README.mdnew file mode 100644index 00000000000..278bf74449b--- /dev/null+++ b/packages/electron-mac-notifications/README.md@@ -0,0 +1,43 @@+# @lobechat/electron-mac-notifications++Native N-API addon that posts macOS notifications through+`UNUserNotificationCenter`, styling them as communication notifications+(sender avatar as the primary icon, via `INSendMessageIntent`) when a sender+is provided. Consumed by the desktop main process; falls back gracefully+everywhere it can't run.++## Build++```bash+pnpm --filter @lobechat/electron-mac-notifications build:native+```++No-op on non-darwin platforms. The desktop packaging pipeline runs this+automatically in `beforePack`.++## Runtime requirements (all empirically verified)++The avatar treatment only renders when the host app satisfies all of:++1. Signed with a real certificate and launched as a regular app. Adhoc-signed+ dev Electron gets `UNErrorDomain Code=1` from the notification center, and+ this package then reports `isSupported()` but fails at show-time — callers+ fall back to Electron's `Notification`.+2. `com.apple.developer.usernotifications.communication` entitlement in the+ signature. Never add it without requirement 3: launchd refuses to spawn+ the app (POSIX 163).+3. An Apple provisioning profile authorizing the entitlement, embedded at+ `Contents/embedded.provisionprofile`. Wired through+ `MAC_PROVISIONING_PROFILE` + `APPLE_TEAM_ID` in `electron-builder.mjs`.+4. `NSUserActivityTypes = [INSendMessageIntent]` in Info.plist (set+ unconditionally via `mac.extendInfo`).++Without 2–3 the notification still shows as a plain banner — macOS silently+drops the communication styling — so profile-less channels keep working.++## Delegate ownership++The addon takes over the process-global `UNUserNotificationCenter` delegate.+Notifications whose identifier lacks the `lobehub-` prefix are forwarded to+whatever delegate was installed before (Electron's own `Notification`+module), so the two paths can coexist during fallback.diff --git a/packages/electron-mac-notifications/binding.gyp b/packages/electron-mac-notifications/binding.gypnew file mode 100644index 00000000000..00ca56cb790--- /dev/null+++ b/packages/electron-mac-notifications/binding.gyp@@ -0,0 +1,27 @@+{+ "targets": [+ {+ "target_name": "lobehub_mac_notifications",+ "sources": ["native/addon.mm"],+ "include_dirs": ["<!@(node -p \"require('node-addon-api').include\")"],+ "dependencies": ["<!(node -p \"require('node-addon-api').gyp\")"],+ "defines": ["NAPI_DISABLE_CPP_EXCEPTIONS"],+ "conditions": [+ [+ "OS=='mac'",+ {+ "xcode_settings": {+ "OTHER_CPLUSPLUSFLAGS": ["-fobjc-arc", "-std=c++17"],+ "OTHER_LDFLAGS": [+ "-framework Foundation",+ "-framework UserNotifications",+ "-framework Intents"+ ],+ "MACOSX_DEPLOYMENT_TARGET": "12.0"+ }+ }+ ]+ ]+ }+ ]+}diff --git a/packages/electron-mac-notifications/index.d.ts b/packages/electron-mac-notifications/index.d.tsnew file mode 100644index 00000000000..2c26e797f18--- /dev/null+++ b/packages/electron-mac-notifications/index.d.ts@@ -0,0 +1,36 @@+export interface MacNotificationSender {+ avatarDataUrl?: string;+ conversationId: string;+ name: string;+}++export interface ShowMacNotificationOptions {+ body: string;+ id?: string;+ sender?: MacNotificationSender;+ silent?: boolean;+ title: string;+}++export interface ShowMacNotificationResult {+ id: string;+ ok: boolean;+ reason?: string;+}++export interface MacNotificationEvent {+ error?: string;+ id: string;+ type: 'clicked' | 'failed' | 'shown';+}++export type MacNotificationAuthorizationStatus =+ 'authorized' | 'denied' | 'notDetermined' | 'provisional' | 'unsupported';++export function isSupported(): boolean;+export function showNotification(+ options: ShowMacNotificationOptions,+): Promise<ShowMacNotificationResult>;+export function onNotificationEvent(listener: (event: MacNotificationEvent) => void): () => void;+export function getAuthorizationStatus(): Promise<MacNotificationAuthorizationStatus>;+export function requestAuthorization(): Promise<boolean>;diff --git a/packages/electron-mac-notifications/index.js b/packages/electron-mac-notifications/index.jsnew file mode 100644index 00000000000..884e0dfab95--- /dev/null+++ b/packages/electron-mac-notifications/index.js@@ -0,0 +1,126 @@+/* eslint-disable @typescript-eslint/no-require-imports */+'use strict';++const { loadNativeBinding } = require('@lobechat/napi-loader');+const { randomUUID } = require('node:crypto');++const ID_PREFIX = 'lobehub-';+const SHOW_TIMEOUT_MS = 5000;++const binding =+ process.platform === 'darwin' && process.type !== 'renderer'+ ? loadNativeBinding({ dirname: __dirname, packageName: require('./package.json').name })+ : null;++const listeners = new Set();+let setupDone = false;++const ensureSetup = () => {+ if (!binding) return false;+ if (setupDone) return true;+ setupDone = binding.setup((eventJson) => {+ let event;+ try {+ event = JSON.parse(eventJson);+ } catch (error) {+ console.error('[electron-mac-notifications] invalid event payload:', error);+ return;+ }+ for (const listener of listeners) {+ try {+ listener(event);+ } catch (error) {+ console.error('[electron-mac-notifications] event listener failed:', error);+ }+ }+ });+ return setupDone;+};++const decodeAvatar = (avatarDataUrl) => {+ if (!avatarDataUrl || typeof avatarDataUrl !== 'string') return undefined;+ const base64 = avatarDataUrl.replace(/^data:image\/[a-z+]+;base64,/, '');+ if (base64 === avatarDataUrl) return undefined;+ try {+ return Buffer.from(base64, 'base64');+ } catch (error) {+ console.error('[electron-mac-notifications] failed to decode avatar:', error);+ return undefined;+ }+};++const isSupported = () => !!binding;++const onNotificationEvent = (listener) => {+ ensureSetup();+ listeners.add(listener);+ return () => listeners.delete(listener);+};++const showNotification = (options) => {+ const id = options.id?.startsWith(ID_PREFIX) ? options.id : `${ID_PREFIX}${randomUUID()}`;+ if (!ensureSetup()) return Promise.resolve({ id, ok: false, reason: 'unsupported' });++ const { sender, ...rest } = options;+ const payload = { ...rest, id };+ if (sender?.name) payload.sender = { conversationId: sender.conversationId, name: sender.name };+ const avatar = decodeAvatar(sender?.avatarDataUrl);++ return new Promise((resolve) => {+ let timer;+ const off = onNotificationEvent((event) => {+ if (event.id !== id) return;+ if (event.type === 'shown') {+ cleanup();+ resolve({ id, ok: true });+ } else if (event.type === 'failed') {+ cleanup();+ resolve({ id, ok: false, reason: event.error || 'failed' });+ }+ });+ const cleanup = () => {+ off();+ clearTimeout(timer);+ };+ // A pending first-run authorization prompt can delay the outcome+ // indefinitely; report the notification as handled instead of failing, so+ // callers don't fall back and double-notify once the user grants access.+ timer = setTimeout(() => {+ cleanup();+ resolve({ id, ok: true, reason: 'pending' });+ }, SHOW_TIMEOUT_MS);++ try {+ binding.show(JSON.stringify(payload), avatar);+ } catch (error) {+ cleanup();+ resolve({ id, ok: false, reason: error.message });+ }+ });+};++const AUTHORIZATION_STATUS = ['notDetermined', 'denied', 'authorized', 'provisional'];++const getAuthorizationStatus = () => {+ if (!binding) return Promise.resolve('unsupported');+ return new Promise((resolve) => {+ binding.getAuthorizationStatus((status) => {+ resolve(AUTHORIZATION_STATUS[status] || 'notDetermined');+ });+ });+};++const requestAuthorization = () => {+ if (!ensureSetup()) return Promise.resolve(false);+ return new Promise((resolve) => {+ binding.requestAuthorization((granted) => resolve(granted));+ });+};++module.exports = {+ getAuthorizationStatus,+ isSupported,+ onNotificationEvent,+ requestAuthorization,+ showNotification,+};diff --git a/packages/electron-mac-notifications/native/addon.mm b/packages/electron-mac-notifications/native/addon.mmnew file mode 100644index 00000000000..e05293bcdcd--- /dev/null+++ b/packages/electron-mac-notifications/native/addon.mm@@ -0,0 +1,247 @@+#include <napi.h>++#import <Foundation/Foundation.h>+#import <Intents/Intents.h>+#import <UserNotifications/UserNotifications.h>++static NSString *const kNotificationIdPrefix = @"lobehub-";++static Napi::ThreadSafeFunction gEventTsfn;+static bool gEventTsfnActive = false;++static void EmitEvent(NSDictionary *payload) {+ if (!gEventTsfnActive) return;+ NSError *error = nil;+ NSData *data = [NSJSONSerialization dataWithJSONObject:payload options:0 error:&error];+ if (!data) return;+ std::string json((const char *)data.bytes, data.length);+ gEventTsfn.NonBlockingCall(+ [json](Napi::Env env, Napi::Function cb) { cb.Call({Napi::String::New(env, json)}); });+}++static void EmitForId(NSString *type, NSString *identifier, NSString *errorMessage) {+ NSMutableDictionary *payload = [NSMutableDictionary dictionary];+ payload[@"type"] = type;+ payload[@"id"] = identifier ?: @"";+ if (errorMessage) payload[@"error"] = errorMessage;+ EmitEvent(payload);+}++static bool IsOwnedIdentifier(NSString *identifier) {+ return identifier != nil && [identifier hasPrefix:kNotificationIdPrefix];+}++@interface LobeNotificationDelegate : NSObject <UNUserNotificationCenterDelegate>+@property (nonatomic, weak) id<UNUserNotificationCenterDelegate> previousDelegate;+@end++@implementation LobeNotificationDelegate++- (void)userNotificationCenter:(UNUserNotificationCenter *)center+ willPresentNotification:(UNNotification *)notification+ withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {+ if (IsOwnedIdentifier(notification.request.identifier)) {+ completionHandler(UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionList |+ UNNotificationPresentationOptionSound);+ return;+ }+ if ([self.previousDelegate+ respondsToSelector:@selector(userNotificationCenter:willPresentNotification:withCompletionHandler:)]) {+ [self.previousDelegate userNotificationCenter:center+ willPresentNotification:notification+ withCompletionHandler:completionHandler];+ return;+ }+ completionHandler(UNNotificationPresentationOptionBanner | UNNotificationPresentationOptionList);+}++- (void)userNotificationCenter:(UNUserNotificationCenter *)center+ didReceiveNotificationResponse:(UNNotificationResponse *)response+ withCompletionHandler:(void (^)(void))completionHandler {+ NSString *identifier = response.notification.request.identifier;+ if (IsOwnedIdentifier(identifier)) {+ if ([response.actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier]) {+ EmitForId(@"clicked", identifier, nil);+ }+ completionHandler();+ return;+ }+ if ([self.previousDelegate+ respondsToSelector:@selector(userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:)]) {+ [self.previousDelegate userNotificationCenter:center+ didReceiveNotificationResponse:response+ withCompletionHandler:completionHandler];+ return;+ }+ completionHandler();+}++@end++static LobeNotificationDelegate *gDelegate = nil;++static void EnsureDelegateInstalled() {+ dispatch_async(dispatch_get_main_queue(), ^{+ UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];+ if (center.delegate == gDelegate && gDelegate != nil) return;+ LobeNotificationDelegate *delegate = [LobeNotificationDelegate new];+ delegate.previousDelegate = center.delegate;+ gDelegate = delegate;+ center.delegate = delegate;+ });+}++static Napi::Value Setup(const Napi::CallbackInfo &info) {+ Napi::Env env = info.Env();+ if (gEventTsfnActive) return Napi::Boolean::New(env, true);+ Napi::Function cb = info[0].As<Napi::Function>();+ gEventTsfn = Napi::ThreadSafeFunction::New(env, cb, "lobehub-mac-notifications", 0, 1);+ gEventTsfn.Unref(env);+ gEventTsfnActive = true;+ EnsureDelegateInstalled();+ return Napi::Boolean::New(env, true);+}++static void ShowWithAuthorization(NSString *identifier, NSString *title, NSString *body, bool silent,+ NSString *senderName, NSString *conversationId, NSData *avatarData) {+ UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];+ [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound |+ UNAuthorizationOptionBadge)+ completionHandler:^(BOOL granted, NSError *authError) {+ if (!granted) {+ EmitForId(@"failed", identifier,+ authError ? authError.localizedDescription : @"notifications not authorized");+ return;+ }++ UNMutableNotificationContent *content = [UNMutableNotificationContent new];+ content.title = title ?: @"";+ content.body = body ?: @"";+ if (!silent) content.sound = [UNNotificationSound defaultSound];++ UNNotificationContent *finalContent = content;+ if (senderName.length > 0) {+ if (@available(macOS 12.0, *)) {+ INImage *avatar = avatarData.length > 0 ? [INImage imageWithImageData:avatarData] : nil;+ NSPersonNameComponents *nameComponents = [NSPersonNameComponents new];+ nameComponents.nickname = senderName;+ INPersonHandle *handle =+ [[INPersonHandle alloc] initWithValue:conversationId ?: senderName+ type:INPersonHandleTypeUnknown];+ INPerson *sender = [[INPerson alloc] initWithPersonHandle:handle+ nameComponents:nameComponents+ displayName:senderName+ image:avatar+ contactIdentifier:nil+ customIdentifier:conversationId];+ INSendMessageIntent *intent =+ [[INSendMessageIntent alloc] initWithRecipients:nil+ outgoingMessageType:INOutgoingMessageTypeOutgoingMessageText+ content:body+ speakableGroupName:nil+ conversationIdentifier:conversationId ?: identifier+ serviceName:nil+ sender:sender+ attachments:nil];+ if (avatar) [intent setImage:avatar forParameterNamed:@"sender"];++ INInteraction *interaction = [[INInteraction alloc] initWithIntent:intent response:nil];+ interaction.direction = INInteractionDirectionIncoming;+ [interaction donateInteractionWithCompletion:nil];++ NSError *updateError = nil;+ UNNotificationContent *updated = [content contentByUpdatingWithProvider:intent+ error:&updateError];+ if (updated) finalContent = updated;+ }+ }++ UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier+ content:finalContent+ trigger:nil];+ [center addNotificationRequest:request+ withCompletionHandler:^(NSError *addError) {+ if (addError) {+ EmitForId(@"failed", identifier, addError.localizedDescription);+ } else {+ EmitForId(@"shown", identifier, nil);+ }+ }];+ }];+}++static Napi::Value Show(const Napi::CallbackInfo &info) {+ Napi::Env env = info.Env();+ std::string json = info[0].As<Napi::String>().Utf8Value();++ NSData *avatarData = nil;+ if (info.Length() > 1 && info[1].IsBuffer()) {+ Napi::Buffer<uint8_t> buffer = info[1].As<Napi::Buffer<uint8_t>>();+ avatarData = [NSData dataWithBytes:buffer.Data() length:buffer.Length()];+ }++ NSData *jsonData = [NSData dataWithBytes:json.data() length:json.size()];+ NSError *parseError = nil;+ NSDictionary *options = [NSJSONSerialization JSONObjectWithData:jsonData+ options:0+ error:&parseError];+ if (![options isKindOfClass:[NSDictionary class]]) {+ Napi::TypeError::New(env, "invalid options payload").ThrowAsJavaScriptException();+ return env.Undefined();+ }++ NSString *identifier = options[@"id"];+ NSString *title = options[@"title"];+ NSString *body = options[@"body"];+ bool silent = [options[@"silent"] boolValue];+ NSDictionary *senderDict =+ [options[@"sender"] isKindOfClass:[NSDictionary class]] ? options[@"sender"] : nil;+ NSString *senderName = senderDict[@"name"];+ NSString *conversationId = senderDict[@"conversationId"];++ EnsureDelegateInstalled();+ dispatch_async(dispatch_get_main_queue(), ^{+ ShowWithAuthorization(identifier, title, body, silent, senderName, conversationId, avatarData);+ });+ return env.Undefined();+}++static Napi::Value GetAuthorizationStatus(const Napi::CallbackInfo &info) {+ Napi::Env env = info.Env();+ Napi::Function cb = info[0].As<Napi::Function>();+ auto tsfn = Napi::ThreadSafeFunction::New(env, cb, "lobehub-mac-notifications-status", 0, 1);+ UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];+ [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {+ long status = (long)settings.authorizationStatus;+ tsfn.NonBlockingCall(+ [status](Napi::Env env, Napi::Function fn) { fn.Call({Napi::Number::New(env, status)}); });+ tsfn.Release();+ }];+ return env.Undefined();+}++static Napi::Value RequestAuthorization(const Napi::CallbackInfo &info) {+ Napi::Env env = info.Env();+ Napi::Function cb = info[0].As<Napi::Function>();+ auto tsfn = Napi::ThreadSafeFunction::New(env, cb, "lobehub-mac-notifications-request", 0, 1);+ UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];+ [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound |+ UNAuthorizationOptionBadge)+ completionHandler:^(BOOL granted, NSError *error) {+ bool ok = granted;+ tsfn.NonBlockingCall(+ [ok](Napi::Env env, Napi::Function fn) { fn.Call({Napi::Boolean::New(env, ok)}); });+ tsfn.Release();+ }];+ return env.Undefined();+}++static Napi::Object Init(Napi::Env env, Napi::Object exports) {+ exports.Set("setup", Napi::Function::New(env, Setup));+ exports.Set("show", Napi::Function::New(env, Show));+ exports.Set("getAuthorizationStatus", Napi::Function::New(env, GetAuthorizationStatus));+ exports.Set("requestAuthorization", Napi::Function::New(env, RequestAuthorization));+ return exports;+}++NODE_API_MODULE(lobehub_mac_notifications, Init)diff --git a/packages/electron-mac-notifications/package.json b/packages/electron-mac-notifications/package.jsonnew file mode 100644index 00000000000..7ac65f30888--- /dev/null+++ b/packages/electron-mac-notifications/package.json@@ -0,0 +1,23 @@+{+ "name": "@lobechat/electron-mac-notifications",+ "version": "1.0.0",+ "private": true,+ "main": "index.js",+ "types": "index.d.ts",+ "scripts": {+ "build:native": "node scripts/build-native.mjs",+ "install": "node scripts/build-native.mjs"+ },+ "dependencies": {+ "@lobechat/napi-loader": "workspace:*"+ },+ "devDependencies": {+ "node-addon-api": "^8.5.0",+ "node-gyp": "^11.4.2"+ },+ "lobechat": {+ "nativeAddonPlatforms": [+ "darwin"+ ]+ }+}diff --git a/packages/electron-mac-notifications/scripts/build-native.mjs b/packages/electron-mac-notifications/scripts/build-native.mjsnew file mode 100644index 00000000000..deb0225fb34--- /dev/null+++ b/packages/electron-mac-notifications/scripts/build-native.mjs@@ -0,0 +1,24 @@+import { execFile } from 'node:child_process';+import { createRequire } from 'node:module';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { promisify } from 'node:util';++const execFileAsync = promisify(execFile);++if (process.platform !== 'darwin') {+ console.info('[electron-mac-notifications] non-darwin platform, skipping native build');+ process.exit(0);+}++const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const require = createRequire(import.meta.url);+const nodeGyp = require.resolve('node-gyp/bin/node-gyp.js');++const { stdout, stderr } = await execFileAsync(process.execPath, [nodeGyp, 'rebuild'], {+ cwd: packageRoot,+ maxBuffer: 16 * 1024 * 1024,+});+if (stdout) console.info(stdout);+if (stderr) console.info(stderr);+console.info('[electron-mac-notifications] native build completed');diff --git a/packages/napi-loader/index.d.ts b/packages/napi-loader/index.d.tsnew file mode 100644index 00000000000..14b975ba31e--- /dev/null+++ b/packages/napi-loader/index.d.ts@@ -0,0 +1,8 @@+export interface LoadNativeBindingOptions {+ /** The consuming package's `__dirname`. */+ dirname: string;+ /** The consuming package's name, as published in its package.json. */+ packageName: string;+}++export function loadNativeBinding(options: LoadNativeBindingOptions): unknown;diff --git a/packages/napi-loader/index.js b/packages/napi-loader/index.jsnew file mode 100644index 00000000000..8fa4afb07b9--- /dev/null+++ b/packages/napi-loader/index.js@@ -0,0 +1,55 @@+/* eslint-disable @typescript-eslint/no-require-imports */+'use strict';++const fs = require('node:fs');+const path = require('node:path');++const RELEASE_DIR = 'build/Release';++// Whether an addon's wrapper stays external (loaded from its package dir) or+// gets inlined into the app bundle depends on the bundler's workspace+// resolution, which has proven unstable across invocation paths — so loading+// must work in both shapes: `dirname` for the external case, and the+// asar-unpacked absolute path for the inlined-in-packaged-app case.+const candidateDirs = (packageName, dirname) => {+ const dirs = [path.join(dirname, RELEASE_DIR)];+ if (process.resourcesPath) {+ dirs.push(+ path.join(process.resourcesPath, 'app.asar.unpacked/node_modules', packageName, RELEASE_DIR),+ );+ }+ return dirs;+};++const findNodeBinary = (dir) => {+ try {+ return fs+ .readdirSync(dir)+ .filter((file) => file.endsWith('.node'))+ .map((file) => path.join(dir, file));+ } catch {+ return [];+ }+};++const loadNativeBinding = ({ dirname, packageName }) => {+ const errors = [];+ for (const dir of candidateDirs(packageName, dirname)) {+ const binaries = findNodeBinary(dir);+ if (binaries.length === 0) {+ errors.push(`${dir}: no .node binary`);+ continue;+ }+ for (const binary of binaries) {+ try {+ return require(binary);+ } catch (error) {+ errors.push(`${binary}: ${error.message}`);+ }+ }+ }+ console.error(`[napi-loader] failed to load ${packageName}:`, errors.join('; '));+ return null;+};++module.exports = { loadNativeBinding };diff --git a/packages/napi-loader/package.json b/packages/napi-loader/package.jsonnew file mode 100644index 00000000000..c34d24b9b5e--- /dev/null+++ b/packages/napi-loader/package.json@@ -0,0 +1,7 @@+{+ "name": "@lobechat/napi-loader",+ "version": "1.0.0",+ "private": true,+ "main": "index.js",+ "types": "index.d.ts"+}diff --git a/plugins/vite/osPlatformResolve.test.ts b/plugins/vite/osPlatformResolve.test.tsnew file mode 100644index 00000000000..117e2fe504f--- /dev/null+++ b/plugins/vite/osPlatformResolve.test.ts@@ -0,0 +1,96 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++import { afterEach, describe, expect, it, vi } from 'vitest';++import { resolveOsPlatform, viteOsPlatformResolve } from './osPlatformResolve';++const temporaryDirectories: string[] = [];++const createFixture = async (files: Record<string, string>) => {+ const directory = await mkdtemp(join(tmpdir(), 'vite-os-platform-resolve-'));+ temporaryDirectories.push(directory);+ await Promise.all(+ Object.entries(files).map(([name, contents]) => writeFile(join(directory, name), contents)),+ );+ return directory;+};++const resolveWithPlugin = async (+ os: 'linux' | 'mac' | 'windows',+ source: string,+ importer: string,+ resolvedId: string,+) => {+ const plugin = viteOsPlatformResolve(os);+ const resolve = vi.fn().mockResolvedValue({ id: resolvedId });+ return plugin.resolveId?.call({ resolve } as never, source, importer, {});+};++afterEach(async () => {+ await Promise.all(+ temporaryDirectories+ .splice(0)+ .map((directory) => rm(directory, { force: true, recursive: true })),+ );+});++describe('resolveOsPlatform', () => {+ it('maps node and electron-builder platforms onto file suffixes', () => {+ expect(resolveOsPlatform('darwin')).toBe('mac');+ expect(resolveOsPlatform('win32')).toBe('windows');+ expect(resolveOsPlatform('linux')).toBe('linux');+ expect(resolveOsPlatform('freebsd')).toBe('linux');+ });+});++describe('viteOsPlatformResolve', () => {+ it('rewrites a base import to the matching os suffix when that file exists', async () => {+ const directory = await createFixture({+ 'widget.mac.ts': 'export const platform = "mac";\n',+ 'widget.ts': 'export const platform = "base";\n',+ });++ await expect(+ resolveWithPlugin(+ 'mac',+ './widget',+ join(directory, 'entry.ts'),+ join(directory, 'widget.ts'),+ ),+ ).resolves.toBe(join(directory, 'widget.mac.ts'));+ });++ it('keeps the base file when the current os has no overlay', async () => {+ const directory = await createFixture({+ 'widget.mac.ts': 'export const platform = "mac";\n',+ 'widget.ts': 'export const platform = "base";\n',+ });++ await expect(+ resolveWithPlugin(+ 'windows',+ './widget',+ join(directory, 'entry.ts'),+ join(directory, 'widget.ts'),+ ),+ ).resolves.toBeNull();+ });++ it('does not rewrite an overlay that imports the base module', async () => {+ const directory = await createFixture({+ 'widget.mac.ts': 'export { platform } from "./widget";\n',+ 'widget.ts': 'export const platform = "base";\n',+ });++ await expect(+ resolveWithPlugin(+ 'mac',+ './widget',+ join(directory, 'widget.mac.ts'),+ join(directory, 'widget.ts'),+ ),+ ).resolves.toBeNull();+ });+});diff --git a/plugins/vite/osPlatformResolve.ts b/plugins/vite/osPlatformResolve.tsnew file mode 100644index 00000000000..ceafd3f690b--- /dev/null+++ b/plugins/vite/osPlatformResolve.ts@@ -0,0 +1,51 @@+import { access } from 'node:fs/promises';++import type { Plugin } from 'vite';++export type OsPlatform = 'linux' | 'mac' | 'windows';++const NODE_TO_OS = {+ darwin: 'mac',+ linux: 'linux',+ win32: 'windows',+} as const satisfies Record<string, OsPlatform>;++export const resolveOsPlatform = (+ nodePlatform = process.env.npm_config_platform || process.platform,+): OsPlatform => NODE_TO_OS[nodePlatform as keyof typeof NODE_TO_OS] ?? 'linux';++const EXT_RE = /\.(ts|tsx|js|jsx|mts|mjs|cts|cjs)$/;+const OS_FILE_RE = /\.(?:linux|mac|windows)\.(?:ts|tsx|js|jsx|mts|mjs|cts|cjs)$/;++export function viteOsPlatformResolve(os: OsPlatform = resolveOsPlatform()): Plugin {+ const suffix = `.${os}`;++ return {+ enforce: 'pre',+ name: 'vite-os-platform-resolve',+ async resolveId(source, importer, options) {+ if (!importer || importer.includes('node_modules')) return null;++ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });+ if (!resolved) return null;++ const id = resolved.id.split('?')[0];+ if (OS_FILE_RE.test(id)) return null;++ const extMatch = id.match(EXT_RE);+ if (!extMatch) return null;++ const candidate = `${id.slice(0, -extMatch[0].length)}${suffix}${extMatch[0]}`;+ if (importer.split('?')[0].replaceAll('\\', '/') === candidate.replaceAll('\\', '/')) {+ return null;+ }++ try {+ await access(candidate);+ return candidate;+ } catch {+ return null;+ }+ },+ };+}diff --git a/src/store/chat/utils/desktopNotification.test.ts b/src/store/chat/utils/desktopNotification.test.tsindex 4abbbe8b3d1..ac82f8644d7 100644--- a/src/store/chat/utils/desktopNotification.test.ts+++ b/src/store/chat/utils/desktopNotification.test.ts@@ -10,19 +10,24 @@ import type { ChatStore } from '@/store/chat/store';import {buildNotificationBody,+ buildNotificationSender,resolveNotificationNavigate,resolveNotificationNavigatePath,resolveNotificationTitle,} from './desktopNotification';+import { renderAvatarToDataUrl } from './notificationAvatar';import { topicMapKey } from './topicMapKey';vi.mock('@/store/agent', () => ({ getAgentStoreState: () => ({}) }));vi.mock('@/store/agent/selectors', () => ({agentSelectors: {getAgentMetaById: (agentId: string) => () =>- agentId === 'agent-named' ? { title: 'My Agent' } : undefined,+ agentId === 'agent-named' ? { avatar: '🤖', title: 'My Agent' } : undefined,},}));+vi.mock('./notificationAvatar', () => ({+ renderAvatarToDataUrl: vi.fn(async () => 'data:image/png;base64,MOCK'),+}));const FALLBACK = 'fallback';@@ -140,3 +145,41 @@ describe('buildNotificationBody', () => {expect(buildNotificationBody(' ', FALLBACK)).toBe(FALLBACK);});});++describe('buildNotificationSender', () => {+ it('returns undefined without an agent context', async () => {+ expect(await buildNotificationSender({ topicId: 't1' })).toBeUndefined();+ });++ it('returns undefined when the agent has no display name', async () => {+ expect(await buildNotificationSender({ agentId: 'agent-unknown' })).toBeUndefined();+ });++ it('builds the sender from agent meta with a rendered avatar', async () => {+ expect(await buildNotificationSender({ agentId: 'agent-named', topicId: 't1' })).toEqual({+ avatarDataUrl: 'data:image/png;base64,MOCK',+ conversationId: 'agent-named:t1',+ name: 'My Agent',+ });+ });++ it('scopes the conversation to the group when present', async () => {+ const sender = await buildNotificationSender({+ agentId: 'agent-named',+ groupId: 'g1',+ topicId: 't1',+ });++ expect(sender?.conversationId).toBe('g1:t1');+ });++ it('keeps the sender when avatar rendering fails', async () => {+ vi.mocked(renderAvatarToDataUrl).mockRejectedValueOnce(new Error('render failed'));++ expect(await buildNotificationSender({ agentId: 'agent-named' })).toEqual({+ avatarDataUrl: undefined,+ conversationId: 'agent-named',+ name: 'My Agent',+ });+ });+});diff --git a/src/store/chat/utils/desktopNotification.ts b/src/store/chat/utils/desktopNotification.tsindex ba76877795f..c2cfe4b7689 100644--- a/src/store/chat/utils/desktopNotification.ts+++ b/src/store/chat/utils/desktopNotification.ts@@ -5,6 +5,7 @@ import {GROUP_CHAT_URL,isDesktop,} from '@lobechat/const';+import type { DesktopNotificationSender } from '@lobechat/electron-client-ipc';import type { ConversationContext } from '@lobechat/types';import { agentDisplayName } from '@lobechat/types';import { t } from 'i18next';@@ -14,6 +15,7 @@ import { agentSelectors } from '@/store/agent/selectors';import type { ChatStore } from '@/store/chat/store';import { markdownToTxt } from '@/utils/markdownToTxt';+import { renderAvatarToDataUrl } from './notificationAvatar';import { topicMapKey } from './topicMapKey';export interface DesktopNotificationContext {@@ -89,6 +91,34 @@ export const resolveNotificationTitle = (return fallbackTitle;};+/**+ * Build the communication-notification sender (agent name + avatar) for the+ * conversation context. Returns undefined outside agent conversations so the+ * notification stays a plain banner.+ */+export const buildNotificationSender = async (+ context: DesktopNotificationContext,+): Promise<DesktopNotificationSender | undefined> => {+ if (!context.agentId) return undefined;++ const agentMeta = agentSelectors.getAgentMetaById(context.agentId)(getAgentStoreState());+ const name = agentDisplayName(agentMeta);+ if (!name) return undefined;++ const conversationId = [context.groupId ?? context.agentId, context.topicId]+ .filter(Boolean)+ .join(':');++ let avatarDataUrl: string | undefined;+ try {+ avatarDataUrl = await renderAvatarToDataUrl(context.agentId, agentMeta);+ } catch (error) {+ console.error('Notification avatar render failed:', error);+ }++ return { avatarDataUrl, conversationId, name };+};+/** Convert the assistant's markdown reply to a length-capped plain-text body. */export const buildNotificationBody = (content: string | undefined,@@ -116,6 +146,7 @@ export const notifyDesktopHumanApprovalRequired = async ();const navigate = resolveNotificationNavigate(context);+ const sender = await buildNotificationSender(context);await Promise.allSettled([desktopNotificationService.setBadgeCount(1),@@ -124,6 +155,7 @@ export const notifyDesktopHumanApprovalRequired = async (force: true,navigate,requestAttention: true,+ sender,title,}),]);@@ -162,11 +194,13 @@ export const notifyDesktopAgentCompleted = async (const { desktopNotificationService } = await import('@/services/electron/desktopNotification');const fallback = t('notification.finishChatGeneration', { ns: 'electron' });const navigate = resolveNotificationNavigate(context);+ const sender = await buildNotificationSender(context);const tasks: Promise<unknown>[] = [desktopNotificationService.showNotification({body: buildNotificationBody(content, fallback),navigate,+ sender,title: resolveNotificationTitle(get, context, fallback),}),];diff --git a/src/store/chat/utils/notificationAvatar.test.ts b/src/store/chat/utils/notificationAvatar.test.tsnew file mode 100644index 00000000000..6e047a2d25e--- /dev/null+++ b/src/store/chat/utils/notificationAvatar.test.ts@@ -0,0 +1,167 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ NOTIFICATION_AVATAR_CACHE_LIMIT,+ NOTIFICATION_AVATAR_LOAD_TIMEOUT_MS,+ renderAvatarToDataUrl,+} from './notificationAvatar';++const create2dContext = () => ({+ drawImage: vi.fn(),+ fillRect: vi.fn(),+ fillStyle: '',+ fillText: vi.fn(),+ font: '',+ textAlign: '',+ textBaseline: '',+});++let context2d: ReturnType<typeof create2dContext>;+let toDataURL: ReturnType<typeof vi.fn>;++class MockImage {+ static hang = false;+ crossOrigin = '';+ private listeners = new Map<string, () => void>();++ addEventListener(type: string, listener: () => void) {+ this.listeners.set(type, listener);+ }++ set src(value: string) {+ if (MockImage.hang || value.includes('stall')) return;+ queueMicrotask(() => {+ this.listeners.get(value.includes('broken') ? 'error' : 'load')?.();+ });+ }+}++beforeEach(() => {+ context2d = create2dContext();+ toDataURL = vi.fn(() => 'data:image/png;base64,CANVAS');+ const originalCreateElement = document.createElement.bind(document);+ vi.spyOn(document, 'createElement').mockImplementation((tag: string) =>+ tag === 'canvas'+ ? ({ getContext: () => context2d, height: 0, toDataURL, width: 0 } as any)+ : originalCreateElement(tag),+ );+ vi.stubGlobal('Image', MockImage);+});++afterEach(() => {+ MockImage.hang = false;+ vi.useRealTimers();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe('renderAvatarToDataUrl', () => {+ it('returns undefined without an avatar', async () => {+ expect(await renderAvatarToDataUrl('no-avatar', {})).toBeUndefined();+ });++ it('draws emoji avatars onto the agent background color', async () => {+ const result = await renderAvatarToDataUrl('emoji-1', {+ avatar: '🤖',+ backgroundColor: '#123456',+ });++ expect(result).toBe('data:image/png;base64,CANVAS');+ expect(context2d.fillStyle).toBe('#123456');+ expect(context2d.fillRect).toHaveBeenCalled();+ expect(context2d.fillText).toHaveBeenCalledWith('🤖', expect.any(Number), expect.any(Number));+ });++ it('draws image avatars from a URL', async () => {+ const result = await renderAvatarToDataUrl('image-1', {+ avatar: 'https://example.com/avatar.png',+ });++ expect(result).toBe('data:image/png;base64,CANVAS');+ expect(context2d.drawImage).toHaveBeenCalled();+ });++ it('resolves undefined when the image fails to load', async () => {+ expect(+ await renderAvatarToDataUrl('image-broken', { avatar: 'https://example.com/broken.png' }),+ ).toBeUndefined();+ });++ it('caches renders per agent and avatar', () => {+ const meta = { avatar: '🐱', backgroundColor: '#fff' };++ const first = renderAvatarToDataUrl('cache-1', meta);+ const second = renderAvatarToDataUrl('cache-1', meta);++ expect(second).toBe(first);+ });++ it('resolves undefined when the canvas context is unavailable', async () => {+ vi.mocked(document.createElement).mockImplementation(+ () => ({ getContext: () => null, height: 0, toDataURL, width: 0 }) as any,+ );++ expect(await renderAvatarToDataUrl('no-context', { avatar: '🤖' })).toBeUndefined();+ });++ it('resolves undefined when the image load times out', async () => {+ vi.useFakeTimers();+ vi.spyOn(console, 'error').mockImplementation(() => {});++ const pending = renderAvatarToDataUrl('stall-1', {+ avatar: 'https://example.com/stall.png',+ });+ await vi.advanceTimersByTimeAsync(NOTIFICATION_AVATAR_LOAD_TIMEOUT_MS);++ expect(await pending).toBeUndefined();+ });++ it('retries after a timed-out avatar load', async () => {+ vi.useFakeTimers();+ vi.spyOn(console, 'error').mockImplementation(() => {});+ MockImage.hang = true;++ const pending = renderAvatarToDataUrl('retry-1', {+ avatar: 'https://example.com/retry.png',+ });+ await vi.advanceTimersByTimeAsync(NOTIFICATION_AVATAR_LOAD_TIMEOUT_MS);+ expect(await pending).toBeUndefined();++ MockImage.hang = false;+ vi.useRealTimers();++ expect(+ await renderAvatarToDataUrl('retry-1', { avatar: 'https://example.com/retry.png' }),+ ).toBe('data:image/png;base64,CANVAS');+ });++ it('evicts the oldest cached avatar once the cache is full', async () => {+ const firstMeta = { avatar: 'https://example.com/0.png' };+ const first = renderAvatarToDataUrl('agent-0', firstMeta);+ await first;++ for (let i = 1; i <= NOTIFICATION_AVATAR_CACHE_LIMIT; i += 1) {+ await renderAvatarToDataUrl(`agent-${i}`, { avatar: `https://example.com/${i}.png` });+ }++ const again = renderAvatarToDataUrl('agent-0', firstMeta);+ expect(again).not.toBe(first);+ expect(await again).toBe('data:image/png;base64,CANVAS');+ });++ it('keeps a recently reused avatar when the cache is full', async () => {+ const firstMeta = { avatar: 'https://example.com/keep.png' };+ const first = renderAvatarToDataUrl('keep', firstMeta);+ await first;++ for (let i = 0; i < NOTIFICATION_AVATAR_CACHE_LIMIT - 1; i += 1) {+ await renderAvatarToDataUrl(`fill-${i}`, { avatar: `https://example.com/fill-${i}.png` });+ }++ expect(renderAvatarToDataUrl('keep', firstMeta)).toBe(first);++ await renderAvatarToDataUrl('overflow', { avatar: 'https://example.com/overflow.png' });++ expect(renderAvatarToDataUrl('keep', firstMeta)).toBe(first);+ });+});diff --git a/src/store/chat/utils/notificationAvatar.ts b/src/store/chat/utils/notificationAvatar.tsnew file mode 100644index 00000000000..0e206821fcf--- /dev/null+++ b/src/store/chat/utils/notificationAvatar.ts@@ -0,0 +1,113 @@+const AVATAR_SIZE = 256;+const FALLBACK_BACKGROUND = '#EBEBEB';+const EMOJI_FONT_RATIO = 0.62;++export const NOTIFICATION_AVATAR_LOAD_TIMEOUT_MS = 2000;+export const NOTIFICATION_AVATAR_CACHE_LIMIT = 32;++const avatarCache = new Map<string, Promise<string | undefined>>();++const isImageAvatar = (avatar: string) =>+ avatar.startsWith('http') || avatar.startsWith('data:') || avatar.startsWith('/');++const rememberAvatar = (key: string, value: Promise<string | undefined>) => {+ if (avatarCache.has(key)) {+ avatarCache.delete(key);+ } else if (avatarCache.size >= NOTIFICATION_AVATAR_CACHE_LIMIT) {+ const oldest = avatarCache.keys().next().value;+ if (oldest !== undefined) avatarCache.delete(oldest);+ }+ avatarCache.set(key, value);+};++const createCanvas = () => {+ const canvas = document.createElement('canvas');+ canvas.width = AVATAR_SIZE;+ canvas.height = AVATAR_SIZE;+ return { canvas, context: canvas.getContext('2d') };+};++const loadImage = (src: string) =>+ new Promise<HTMLImageElement>((resolve, reject) => {+ const image = new Image();+ image.crossOrigin = 'anonymous';+ let settled = false;++ const finish = (action: () => void) => {+ if (settled) return;+ settled = true;+ clearTimeout(timer);+ action();+ };++ const timer = setTimeout(() => {+ finish(() => {+ image.src = '';+ reject(new Error(`avatar load timed out: ${src}`));+ });+ }, NOTIFICATION_AVATAR_LOAD_TIMEOUT_MS);++ image.addEventListener('load', () => finish(() => resolve(image)));+ image.addEventListener('error', () =>+ finish(() => reject(new Error(`failed to load avatar: ${src}`))),+ );+ image.src = src;+ });++const renderImageAvatar = async (avatar: string): Promise<string | undefined> => {+ const image = await loadImage(avatar);+ const { canvas, context } = createCanvas();+ if (!context) return undefined;+ context.drawImage(image, 0, 0, AVATAR_SIZE, AVATAR_SIZE);+ return canvas.toDataURL('image/png');+};++const renderEmojiAvatar = (avatar: string, backgroundColor?: string): string | undefined => {+ const { canvas, context } = createCanvas();+ if (!context) return undefined;+ context.fillStyle = backgroundColor || FALLBACK_BACKGROUND;+ context.fillRect(0, 0, AVATAR_SIZE, AVATAR_SIZE);+ context.font = `${Math.round(AVATAR_SIZE * EMOJI_FONT_RATIO)}px sans-serif`;+ context.textAlign = 'center';+ context.textBaseline = 'middle';+ context.fillText(avatar, AVATAR_SIZE / 2, AVATAR_SIZE / 2 + AVATAR_SIZE * 0.04);+ return canvas.toDataURL('image/png');+};++export interface NotificationAvatarMeta {+ avatar?: string;+ backgroundColor?: string;+}++export const renderAvatarToDataUrl = (+ cacheKey: string,+ meta: NotificationAvatarMeta,+): Promise<string | undefined> => {+ const { avatar, backgroundColor } = meta;+ if (!avatar || typeof document === 'undefined') return Promise.resolve(undefined);++ const key = [cacheKey, avatar, backgroundColor].join('|');+ const cached = avatarCache.get(key);+ if (cached) {+ rememberAvatar(key, cached);+ return cached;+ }++ const work = (async () => {+ return isImageAvatar(avatar)+ ? await renderImageAvatar(avatar)+ : renderEmojiAvatar(avatar, backgroundColor);+ })();++ const pending = work.catch((error: unknown) => {+ console.error('Notification avatar render failed:', error);+ return undefined;+ });++ void work.catch(() => {+ if (avatarCache.get(key) === pending) avatarCache.delete(key);+ });++ rememberAvatar(key, pending);+ return pending;+};