🤯 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): add chat completion sound settings (#19280)
Inneiac000cc0a666
diff --git a/apps/desktop/resources/sounds/lobehub-complete.aiff b/apps/desktop/resources/sounds/lobehub-complete.aiffnew file mode 100644index 00000000000..f057fdd03b9Binary files /dev/null and b/apps/desktop/resources/sounds/lobehub-complete.aiff differdiff --git a/apps/desktop/src/main/controllers/CompletionSoundCtr.ts b/apps/desktop/src/main/controllers/CompletionSoundCtr.tsnew file mode 100644index 00000000000..b4d25bbfceb--- /dev/null+++ b/apps/desktop/src/main/controllers/CompletionSoundCtr.ts@@ -0,0 +1,164 @@+import { copyFile, mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';+import pathUtils from 'node:path';++import type { CompletionSoundSettings } from '@lobechat/electron-client-ipc';+import { app, dialog } from 'electron';+import { z } from 'zod';++import { resourcesDir } from '@/const/dir';+import { readCompletionSoundImport } from '@/modules/completionSound';+import { macOS } from '@/utils/platform';++import { ControllerModule, IpcMethod } from './index';++const settingsSchema = z+ .object({+ enabled: z.boolean().optional(),+ notificationSound: z.enum(['lobehub', 'system']).optional(),+ reset: z.boolean().optional(),+ volume: z.number().min(0).max(1).optional(),+ })+ .strict();++/**+ * UNNotificationSound resolves a name only against `~/Library/Sounds`, and only AIFF —+ * the app bundle is never searched, and a WAV there falls back to the system alert sound.+ * So the banner sound has to be installed into the user's own Sounds folder.+ */+const BANNER_SOUND_FILE = 'lobehub-complete.aiff';++export default class CompletionSoundCtr extends ControllerModule {+ static override readonly groupName = 'completionSound';+ private lastFile?: string;++ @IpcMethod()+ async getSettings(): Promise<CompletionSoundSettings> {+ return { ...this.readSettings(), systemSoundDisabled: await this.isSystemSoundDisabled() };+ }++ @IpcMethod()+ async setSettings(input: {+ enabled?: boolean;+ notificationSound?: CompletionSoundSettings['notificationSound'];+ reset?: boolean;+ volume?: number;+ }): Promise<CompletionSoundSettings> {+ const { reset, ...changes } = settingsSchema.parse(input);+ const previous = this.app.storeManager.get('completionSound');+ this.app.storeManager.set('completionSound', {+ ...(reset+ ? { ...this.readSettings(), name: undefined }+ : { ...this.readSettings(), ...previous }),+ ...changes,+ });+ if (reset && previous?.directory) await this.removeImportedDirectory(previous.directory);+ return this.getSettings();+ }++ @IpcMethod()+ async importSound(): Promise<CompletionSoundSettings> {+ const result = await dialog.showOpenDialog({+ filters: [{ extensions: ['wav', 'mp3', 'ogg', 'json'], name: 'Audio / OpenPeon' }],+ properties: ['openFile'],+ });+ if (result.canceled || !result.filePaths[0]) return this.getSettings();+ const imported = await readCompletionSoundImport(result.filePaths[0]);+ const root = pathUtils.join(app.getPath('userData'), 'completion-sounds');+ await mkdir(root, { recursive: true });+ const directory = await mkdtemp(pathUtils.join(root, 'pack-'));+ try {+ const files = [];+ for (const [index, sound] of imported.sounds.entries()) {+ const file = `${index}${sound.extension}`;+ await writeFile(pathUtils.join(directory, file), sound.data);+ files.push({ file, mime: sound.mime });+ }+ const previous = this.app.storeManager.get('completionSound');+ this.app.storeManager.set('completionSound', {+ ...this.readSettings(),+ directory,+ files,+ name: imported.name,+ });+ if (previous?.directory) await this.removeImportedDirectory(previous.directory);+ } catch (error) {+ await this.removeImportedDirectory(directory);+ throw error;+ }+ return this.getSettings();+ }++ /** Sound file the background banner carries; absent means the macOS default sound. */+ @IpcMethod()+ async getNotificationSoundFile(): Promise<string | undefined> {+ if (!macOS() || this.readSettings().notificationSound !== 'lobehub') return undefined;+ try {+ const source = pathUtils.join(resourcesDir, 'sounds', BANNER_SOUND_FILE);+ const target = pathUtils.join(app.getPath('home'), 'Library', 'Sounds', BANNER_SOUND_FILE);+ const [installed, existing] = await Promise.all([+ stat(source),+ stat(target).catch(() => undefined),+ ]);+ if (installed.size !== existing?.size) {+ await mkdir(pathUtils.dirname(target), { recursive: true });+ await copyFile(source, target);+ }+ return BANNER_SOUND_FILE;+ } catch (error) {+ console.error('Failed to install the notification sound:', error);+ return undefined;+ }+ }++ @IpcMethod()+ async getPlayback(input?: {+ preview?: boolean;+ }): Promise<{ dataUrl?: string; play: boolean; volume: number }> {+ const settings = this.readSettings();+ const play = (settings.enabled || !!input?.preview) && settings.volume > 0;+ if (!play) return { play: false, volume: settings.volume };+ const saved = this.app.storeManager.get('completionSound');+ if (!saved?.directory || !saved.files?.length) return { play, volume: settings.volume };+ const candidates =+ saved.files.length > 1+ ? saved.files.filter(({ file }) => file !== this.lastFile)+ : saved.files;+ const sound = candidates[Math.floor(Math.random() * candidates.length)];+ const data = await readFile(pathUtils.join(saved.directory, sound.file));+ this.lastFile = sound.file;+ return {+ dataUrl: `data:${sound.mime};base64,${data.toString('base64')}`,+ play,+ volume: settings.volume,+ };+ }++ private readSettings(): CompletionSoundSettings {+ const settings = this.app.storeManager.get('completionSound');+ return {+ enabled: settings?.enabled ?? false,+ name: settings?.name,+ notificationSound: settings?.notificationSound ?? 'system',+ volume: settings?.volume ?? 0.7,+ };+ }++ private async isSystemSoundDisabled(): Promise<boolean> {+ if (!macOS()) return false;+ try {+ const { getSoundSetting } = await import('@lobechat/electron-mac-notifications');+ return (await getSoundSetting()) === 'disabled';+ } catch (error) {+ console.error('Failed to read macOS notification sound setting:', error);+ return false;+ }+ }++ private async removeImportedDirectory(directory: string) {+ try {+ await rm(directory, { force: true, recursive: true });+ } catch (error) {+ console.error('Failed to remove old completion sounds:', error);+ }+ }+}diff --git a/apps/desktop/src/main/controllers/NotificationCtr.mac.ts b/apps/desktop/src/main/controllers/NotificationCtr.mac.tsindex 06a92306243..3b1d4774caa 100644--- a/apps/desktop/src/main/controllers/NotificationCtr.mac.ts+++ b/apps/desktop/src/main/controllers/NotificationCtr.mac.ts@@ -111,6 +111,7 @@ export default class NotificationCtr extends ControllerModule {body: params.body,sender: params.sender,silent: params.silent,+ soundName: params.soundName,title: params.title,});diff --git a/apps/desktop/src/main/controllers/__tests__/CompletionSoundCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/CompletionSoundCtr.test.tsnew file mode 100644index 00000000000..b2921a3cb51--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/CompletionSoundCtr.test.ts@@ -0,0 +1,165 @@+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { App } from '@/core/App';+import type { ElectronMainStore } from '@/types/store';++import CompletionSoundCtr from '../CompletionSoundCtr';++const mocks = vi.hoisted(() => {+ let resources = '';+ return {+ getPath: vi.fn(),+ getSoundSetting: vi.fn(),+ resourcesDir: () => resources,+ setResourcesDir: (value: string) => {+ resources = value;+ },+ showOpenDialog: vi.fn(),+ };+});+vi.mock('@/const/dir', () => ({+ get resourcesDir() {+ return mocks.resourcesDir();+ },+}));+vi.mock('electron', () => ({+ app: { getPath: mocks.getPath },+ dialog: { showOpenDialog: mocks.showOpenDialog },+ ipcMain: { handle: vi.fn() },+}));+vi.mock('@lobechat/electron-mac-notifications', () => ({+ getSoundSetting: mocks.getSoundSetting,+}));+vi.mock('@/utils/platform', () => ({ macOS: () => true }));++describe('local completion sound settings', () => {+ let directory: string;+ let saved: ElectronMainStore['completionSound'];+ let controller: CompletionSoundCtr;+ const application = {+ storeManager: {+ get: () => saved,+ set: (_key: string, value: ElectronMainStore['completionSound']) => {+ saved = value;+ },+ },+ } as unknown as App;++ beforeEach(async () => {+ directory = await mkdtemp(path.join(tmpdir(), 'completion-sound-ctr-'));+ mocks.getPath.mockReturnValue(directory);+ mocks.setResourcesDir(directory);+ await mkdir(path.join(directory, 'sounds'), { recursive: true });+ await writeFile(path.join(directory, 'sounds', 'lobehub-complete.aiff'), 'FORM');+ mocks.getSoundSetting.mockResolvedValue('enabled');+ saved = undefined;+ controller = new CompletionSoundCtr(application);+ });+ afterEach(async () => {+ await rm(directory, { recursive: true, force: true });+ });++ it('copies selected sound into app storage and preserves it across controller restart and source removal', async () => {+ await controller.setSettings({ enabled: true });+ const source = path.join(directory, 'original.wav');+ const audio = Buffer.from('RIFF0000WAVEfmt ');+ await writeFile(source, audio);+ mocks.showOpenDialog.mockResolvedValue({ filePaths: [source] });+ await controller.importSound();+ await controller.setSettings({ volume: 0.3 });+ await rm(source);+ controller = new CompletionSoundCtr(application);+ expect(await controller.getPlayback()).toEqual({+ dataUrl: `data:audio/wav;base64,${audio.toString('base64')}`,+ play: true,+ volume: 0.3,+ });+ const oldDirectory = saved!.directory!;+ await controller.setSettings({ reset: true });+ expect(await controller.getSettings()).toEqual({+ enabled: true,+ name: undefined,+ notificationSound: 'system',+ systemSoundDisabled: false,+ volume: 0.3,+ });+ await expect(readFile(path.join(oldDirectory, '0.wav'))).rejects.toThrow();+ });++ it('keeps prior settings when the picker is canceled or a new import is invalid', async () => {+ await controller.setSettings({ enabled: false, volume: 0.2 });+ const previous = saved;+ mocks.showOpenDialog.mockResolvedValue({ canceled: true, filePaths: [] });+ await controller.importSound();+ const source = path.join(directory, 'bad.mp3');+ await writeFile(source, 'not an mp3');+ mocks.showOpenDialog.mockResolvedValue({ filePaths: [source] });+ await expect(controller.importSound()).rejects.toThrow();+ expect(saved).toBe(previous);+ });++ it('validates settings at the IPC boundary without changing stored settings', async () => {+ await controller.setSettings({ volume: 0.5 });+ await expect(controller.setSettings({ volume: 2 })).rejects.toThrow();+ await expect(controller.setSettings({ volume: Number.NaN })).rejects.toThrow();+ expect((await controller.getSettings()).volume).toBe(0.5);+ });++ it('keeps the in-app chime off by default while a preview still plays', async () => {+ expect(await controller.getPlayback()).toEqual({ play: false, volume: 0.7 });+ expect(await controller.getPlayback({ preview: true })).toEqual({ play: true, volume: 0.7 });+ await controller.setSettings({ volume: 0 });+ expect(await controller.getPlayback({ preview: true })).toEqual({ play: false, volume: 0 });+ });++ it('reports the system sound state without muting the in-app chime', async () => {+ mocks.getSoundSetting.mockResolvedValue('disabled');+ await controller.setSettings({ enabled: true });+ expect(await controller.getSettings()).toMatchObject({ systemSoundDisabled: true });+ expect(await controller.getPlayback()).toMatchObject({ play: true });+ });++ it('installs the banner sound into the user Sounds folder only when our chime is picked', async () => {+ const target = path.join(directory, 'Library', 'Sounds', 'lobehub-complete.aiff');+ expect(await controller.getNotificationSoundFile()).toBeUndefined();+ await expect(readFile(target)).rejects.toThrow();++ await controller.setSettings({ notificationSound: 'lobehub' });+ expect(await controller.getNotificationSoundFile()).toBe('lobehub-complete.aiff');+ expect(await readFile(target, 'utf8')).toBe('FORM');+ });++ it('falls back to the system sound when the bundled file is missing', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ await rm(path.join(directory, 'sounds'), { force: true, recursive: true });+ await controller.setSettings({ notificationSound: 'lobehub' });+ expect(await controller.getNotificationSoundFile()).toBeUndefined();+ } finally {+ consoleError.mockRestore();+ }+ });++ it('selects completion sounds without immediate repeats', async () => {+ await writeFile(path.join(directory, 'a.wav'), 'RIFF0000WAVEa');+ await writeFile(path.join(directory, 'b.wav'), 'RIFF0000WAVEb');+ const source = path.join(directory, 'openpeon.json');+ await writeFile(+ source,+ JSON.stringify({+ categories: { 'task.complete': { sounds: [{ file: 'a.wav' }, { file: 'b.wav' }] } },+ cesp_version: '1.0',+ display_name: 'Two sounds',+ }),+ );+ mocks.showOpenDialog.mockResolvedValue({ filePaths: [source] });+ await controller.importSound();+ const first = await controller.getPlayback({ preview: true });+ const second = await controller.getPlayback({ preview: true });+ expect(first.dataUrl).not.toBe(second.dataUrl);+ });+});diff --git a/apps/desktop/src/main/controllers/__tests__/controllerDefaultExport.test.ts b/apps/desktop/src/main/controllers/__tests__/controllerDefaultExport.test.tsnew file mode 100644index 00000000000..f4cc86faafb--- /dev/null+++ b/apps/desktop/src/main/controllers/__tests__/controllerDefaultExport.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from 'vitest';++const controllerModules = import.meta.glob('../*Ctr.ts', { eager: true }) as Record<+ string,+ { default?: unknown }+>;++describe('controller default exports', () => {+ it('every *Ctr.ts module has a constructor default export for App.importAll', () => {+ const entries = Object.entries(controllerModules);+ expect(entries.length).toBeGreaterThan(0);+ for (const [file, mod] of entries) {+ expect(typeof mod.default, file).toBe('function');+ }+ });+});diff --git a/apps/desktop/src/main/controllers/notificationShared.ts b/apps/desktop/src/main/controllers/notificationShared.tsindex 37e32172fb2..aafaffe68b3 100644--- a/apps/desktop/src/main/controllers/notificationShared.ts+++ b/apps/desktop/src/main/controllers/notificationShared.ts@@ -70,6 +70,7 @@ export const showElectronNotification = ({body: params.body,hasReply: false,silent: params.silent || false,+ sound: params.soundName,timeoutType: 'default',title: params.title,urgency,diff --git a/apps/desktop/src/main/controllers/registry.ts b/apps/desktop/src/main/controllers/registry.tsindex 5819e31fa8b..fa11058840b 100644--- a/apps/desktop/src/main/controllers/registry.ts+++ b/apps/desktop/src/main/controllers/registry.ts@@ -6,6 +6,7 @@ import BrowserControlCtr from './BrowserControlCtr';import BrowserSidebarCtr from './BrowserSidebarCtr';import BrowserWindowsCtr from './BrowserWindowsCtr';import CliCtr from './CliCtr';+import CompletionSoundCtr from './CompletionSoundCtr';import DevtoolsCtr from './DevtoolsCtr';import GatewayConnectionCtr from './GatewayConnectionCtr';import GitCtr from './GitCtr';@@ -38,6 +39,7 @@ export const controllerIpcConstructors = [BrowserSidebarCtr,BrowserWindowsCtr,CliCtr,+ CompletionSoundCtr,DevtoolsCtr,GatewayConnectionCtr,GitCtr,diff --git a/apps/desktop/src/main/modules/completionSound.test.ts b/apps/desktop/src/main/modules/completionSound.test.tsnew file mode 100644index 00000000000..ea62ddd61f7--- /dev/null+++ b/apps/desktop/src/main/modules/completionSound.test.ts@@ -0,0 +1,86 @@+import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import pathUtils from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { readCompletionSoundImport } from './completionSound';++describe('completion sound import', () => {+ let directory: string;+ const audio = Buffer.from('RIFF0000WAVEfmt ');+ const manifest = (file = 'done.wav', sha256?: string) =>+ JSON.stringify({+ categories: { 'task.complete': { sounds: [{ file, sha256 }] } },+ cesp_version: '1.0',+ display_name: 'Test pack',+ });++ beforeEach(async () => {+ directory = await mkdtemp(pathUtils.join(tmpdir(), 'completion-sound-test-'));+ await writeFile(pathUtils.join(directory, 'done.wav'), audio);+ });+ afterEach(async () => {+ await rm(directory, { force: true, recursive: true });+ });++ it('loads standalone audio and OpenPeon completion audio', async () => {+ expect(await readCompletionSoundImport(pathUtils.join(directory, 'done.wav'))).toMatchObject({+ name: 'done.wav',+ sounds: [{ data: audio, mime: 'audio/wav' }],+ });+ await writeFile(pathUtils.join(directory, 'openpeon.json'), manifest());+ expect(+ await readCompletionSoundImport(pathUtils.join(directory, 'openpeon.json')),+ ).toMatchObject({+ name: 'Test pack',+ sounds: [{ data: audio }],+ });+ });++ it('rejects traversal and symlinks outside the selected pack', async () => {+ const pack = pathUtils.join(directory, 'pack');+ await mkdir(pack);+ await writeFile(pathUtils.join(pack, 'openpeon.json'), manifest('../done.wav'));+ await expect(readCompletionSoundImport(pathUtils.join(pack, 'openpeon.json'))).rejects.toThrow(+ 'Invalid sound path',+ );+ await symlink(pathUtils.join(directory, 'done.wav'), pathUtils.join(pack, 'done.wav'));+ await writeFile(pathUtils.join(pack, 'openpeon.json'), manifest());+ await expect(readCompletionSoundImport(pathUtils.join(pack, 'openpeon.json'))).rejects.toThrow(+ 'escapes pack',+ );+ });++ it('rejects disguised audio, oversize files and checksum mismatches', async () => {+ await writeFile(pathUtils.join(directory, 'bad.mp3'), 'this is not audio');+ await expect(readCompletionSoundImport(pathUtils.join(directory, 'bad.mp3'))).rejects.toThrow(+ 'Unsupported audio',+ );+ await writeFile(pathUtils.join(directory, 'large.wav'), Buffer.alloc(1024 * 1024 + 1));+ await expect(readCompletionSoundImport(pathUtils.join(directory, 'large.wav'))).rejects.toThrow(+ 'size limit',+ );+ await writeFile(+ pathUtils.join(directory, 'openpeon.json'),+ manifest('done.wav', '0'.repeat(64)),+ );+ await expect(+ readCompletionSoundImport(pathUtils.join(directory, 'openpeon.json')),+ ).rejects.toThrow('checksum');+ });++ it('rejects packs without completion sounds without falling back to other events', async () => {+ await writeFile(+ pathUtils.join(directory, 'openpeon.json'),+ JSON.stringify({+ categories: { 'session.end': { sounds: [{ file: 'done.wav' }] } },+ cesp_version: '1.0',+ display_name: 'Wrong event',+ }),+ );+ await expect(+ readCompletionSoundImport(pathUtils.join(directory, 'openpeon.json')),+ ).rejects.toThrow();+ });+});diff --git a/apps/desktop/src/main/modules/completionSound.ts b/apps/desktop/src/main/modules/completionSound.tsnew file mode 100644index 00000000000..eb7816549d3--- /dev/null+++ b/apps/desktop/src/main/modules/completionSound.ts@@ -0,0 +1,89 @@+import { createHash } from 'node:crypto';+import { readFile, realpath, stat } from 'node:fs/promises';+import pathUtils from 'node:path';++import { z } from 'zod';++const MAX_SOUND_BYTES = 1024 * 1024;+const MAX_PACK_BYTES = 50 * MAX_SOUND_BYTES;++const packSchema = z.object({+ categories: z.object({+ 'task.complete': z.object({+ sounds: z+ .array(+ z.object({+ file: z.string().min(1),+ sha256: z+ .string()+ .regex(/^[a-f0-9]{64}$/i)+ .optional(),+ }),+ )+ .min(1)+ .max(200),+ }),+ }),+ cesp_version: z.literal('1.0'),+ display_name: z.string().min(1).max(128),+});++const readBoundedFile = async (path: string, maxBytes: number) => {+ const info = await stat(path);+ if (!info.isFile() || info.size > maxBytes) throw new Error('Sound file exceeds size limit');+ const data = await readFile(path);+ if (data.length > maxBytes) throw new Error('Sound file exceeds size limit');+ return data;+};++const readSound = async (path: string) => {+ const data = await readBoundedFile(path, MAX_SOUND_BYTES);+ const extension = pathUtils.extname(path).toLowerCase();+ const header = data.toString('ascii', 0, 4);+ let mime: string | undefined;+ if (extension === '.wav' && header === 'RIFF' && data.toString('ascii', 8, 12) === 'WAVE')+ mime = 'audio/wav';+ if (extension === '.ogg' && header === 'OggS') mime = 'audio/ogg';+ if (+ extension === '.mp3' &&+ (data.toString('ascii', 0, 3) === 'ID3' || (data[0] === 0xff && (data[1] & 0xe0) === 0xe0))+ )+ mime = 'audio/mpeg';+ if (!mime) throw new Error('Unsupported audio file');+ return { data, extension, mime };+};++/** Import only task.complete audio; never execute scripts supplied by a sound pack. */+export const readCompletionSoundImport = async (path: string) => {+ if (pathUtils.extname(path).toLowerCase() !== '.json') {+ return { name: pathUtils.basename(path), sounds: [await readSound(path)] };+ }++ if (pathUtils.basename(path) !== 'openpeon.json') throw new Error('Select openpeon.json');+ const manifest = packSchema.parse(+ JSON.parse((await readBoundedFile(path, MAX_SOUND_BYTES)).toString('utf8')),+ );+ const root = await realpath(pathUtils.dirname(path));+ const sounds: Awaited<ReturnType<typeof readSound>>[] = [];+ let bytes = 0;+ for (const entry of manifest.categories['task.complete'].sounds) {+ if (+ entry.file.split('/').some((part) => !/^[\w.-]+$/.test(part) || part === '..' || part === '.')+ )+ throw new Error('Invalid sound path');+ const source = await realpath(pathUtils.resolve(root, entry.file));+ const withinRoot = pathUtils.relative(root, source);+ if (pathUtils.isAbsolute(withinRoot) || withinRoot.startsWith('..'))+ throw new Error('Sound path escapes pack');+ const sound = await readSound(source);+ if (+ entry.sha256 &&+ createHash('sha256').update(sound.data).digest('hex') !== entry.sha256.toLowerCase()+ )+ throw new Error('Sound checksum mismatch');+ bytes += sound.data.length;+ if (bytes > MAX_PACK_BYTES) throw new Error('Sound pack exceeds size limit');+ sounds.push(sound);+ }+ return { name: manifest.display_name, sounds };+};diff --git a/apps/desktop/src/main/types/store.ts b/apps/desktop/src/main/types/store.tsindex c0e41fb1513..8536c7a7869 100644--- a/apps/desktop/src/main/types/store.ts+++ b/apps/desktop/src/main/types/store.ts@@ -1,4 +1,5 @@import type {+ CompletionSoundSettings,DataSyncConfig,ImessageBridgeConfig,NetworkProxySettings,@@ -9,6 +10,10 @@ import type { HeteroSessionDirPref } from '@lobechat/types';export interface ElectronMainStore {appTrayVisible: boolean;+ completionSound?: Partial<Omit<CompletionSoundSettings, 'systemSoundDisabled'>> & {+ directory?: string;+ files?: { file: string; mime: string }[];+ };dataSyncConfig: DataSyncConfig;/*** Explicit completion state for the multi-step desktop onboarding flow.diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 799852493af..f63fe987fc5 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -275,6 +275,26 @@"artworkStudio.uploadSpec.fullBody": "3:4 · transparent PNG ≤ 1 MB","checking": "Checking...","checkingPermissions": "Checking permissions...",+ "completionSound.banner.desc": "Sound the notification banner carries when a chat finishes while LobeHub is in the background. macOS Focus and per-app notification settings still apply.",+ "completionSound.banner.label": "Notification sound",+ "completionSound.banner.lobehub": "LobeHub chime",+ "completionSound.banner.previewBody": "This is how a finished chat will sound in the background.",+ "completionSound.banner.previewTitle": "Notification preview",+ "completionSound.banner.system": "System default",+ "completionSound.banner.systemMuted": "macOS has notification sounds turned off for LobeHub, so background notifications stay silent. Turn them back on in System Settings › Notifications › LobeHub.",+ "completionSound.banner.title": "Background notification",+ "completionSound.default": "LobeHub chime",+ "completionSound.desc": "Play a chime when a chat finishes while LobeHub is in the foreground. The sound, volume and imports stay on this device and are not synced.",+ "completionSound.enabled": "Play completion sound",+ "completionSound.error": "Could not load, save or play the sound. Check the audio file or OpenPeon pack and try again.",+ "completionSound.import": "Import sound",+ "completionSound.importHint": "Choose WAV, MP3 or OGG (up to 1 MB), or openpeon.json from an extracted OpenPeon pack. Only task completion sounds are imported.",+ "completionSound.preview": "Preview",+ "completionSound.reset": "Use default",+ "completionSound.retry": "Reload settings",+ "completionSound.sound": "Sound",+ "completionSound.title": "In-app completion sound",+ "completionSound.volume": "Volume","creds.actions.delete": "Delete","creds.actions.deleteConfirm.cancel": "Cancel","creds.actions.deleteConfirm.content": "This credential will be permanently deleted. This action cannot be undone.",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex cb8636552ea..d68f4401352 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -275,6 +275,26 @@"artworkStudio.uploadSpec.fullBody": "3:4 · 透明底 PNG ≤ 1 MB","checking": "检查中…","checkingPermissions": "检查权限中…",+ "completionSound.banner.desc": "LobeHub 处于后台时,对话完成的通知横幅所带的声音。macOS 专注模式和应用级通知设置依然生效。",+ "completionSound.banner.label": "通知提示音",+ "completionSound.banner.lobehub": "LobeHub 提示音",+ "completionSound.banner.previewBody": "应用在后台时,对话完成的通知就是这个声音。",+ "completionSound.banner.previewTitle": "通知提示音预览",+ "completionSound.banner.system": "系统默认",+ "completionSound.banner.systemMuted": "macOS 已关闭 LobeHub 的通知声音,后台通知不会发声。可在「系统设置 › 通知 › LobeHub」中重新开启。",+ "completionSound.banner.title": "后台通知",+ "completionSound.default": "LobeHub 提示音",+ "completionSound.desc": "LobeHub 处于前台时,对话完成后播放提示音。声音、音量和导入的音频仅保存在此设备,不会同步。",+ "completionSound.enabled": "播放完成提示音",+ "completionSound.error": "无法加载、保存或播放声音。请检查音频文件或 OpenPeon 语音包后重试。",+ "completionSound.import": "导入声音",+ "completionSound.importHint": "选择 WAV、MP3 或 OGG 音频(不超过 1 MB),或已解压 OpenPeon 语音包中的 openpeon.json。仅导入任务完成提示音。",+ "completionSound.preview": "试听",+ "completionSound.reset": "恢复默认",+ "completionSound.retry": "重新加载设置",+ "completionSound.sound": "声音",+ "completionSound.title": "应用内完成提示音",+ "completionSound.volume": "音量","creds.actions.delete": "删除","creds.actions.deleteConfirm.cancel": "取消","creds.actions.deleteConfirm.content": "此凭证将被永久删除,此操作无法撤销。",diff --git a/packages/electron-client-ipc/src/types/notification.ts b/packages/electron-client-ipc/src/types/notification.tsindex 457e3c71380..57fe7412dcd 100644--- a/packages/electron-client-ipc/src/types/notification.ts+++ b/packages/electron-client-ipc/src/types/notification.ts@@ -1,3 +1,17 @@+export type CompletionNotificationSound = 'lobehub' | 'system';++export interface CompletionSoundSettings {+ /** In-app chime, played only while the window has focus. */+ enabled: boolean;+ /** Imported audio or sound pack display name; absent for the built-in sound. */+ name?: string;+ /** Sound the background notification banner carries. */+ notificationSound: CompletionNotificationSound;+ /** macOS System Settings has notification sounds off for the app. */+ systemSoundDisabled?: boolean;+ volume: number;+}+export interface DesktopNotificationSender {/*** PNG data URL rendered by the caller; when present on macOS the@@ -23,6 +37,11 @@ export interface ShowDesktopNotificationParams {requestAttention?: boolean;sender?: DesktopNotificationSender;silent?: boolean;+ /**+ * macOS only: a file name registered under the bundle's `Library/Sounds`. Falls back to+ * the system default sound when absent — an unbundled name would silence the banner.+ */+ soundName?: string;title: string;}diff --git a/packages/electron-mac-notifications/index.d.ts b/packages/electron-mac-notifications/index.d.tsindex 2c26e797f18..f20a7b39b9c 100644--- a/packages/electron-mac-notifications/index.d.ts+++ b/packages/electron-mac-notifications/index.d.ts@@ -9,6 +9,8 @@ export interface ShowMacNotificationOptions {id?: string;sender?: MacNotificationSender;silent?: boolean;+ /** File name registered under the bundle's `Library/Sounds`; system default when absent. */+ soundName?: string;title: string;}@@ -32,5 +34,8 @@ export function showNotification(options: ShowMacNotificationOptions,): Promise<ShowMacNotificationResult>;export function onNotificationEvent(listener: (event: MacNotificationEvent) => void): () => void;+export type MacNotificationSoundSetting = 'disabled' | 'enabled' | 'unsupported';+export function getAuthorizationStatus(): Promise<MacNotificationAuthorizationStatus>;+export function getSoundSetting(): Promise<MacNotificationSoundSetting>;export function requestAuthorization(): Promise<boolean>;diff --git a/packages/electron-mac-notifications/index.js b/packages/electron-mac-notifications/index.jsindex 884e0dfab95..3904fdee105 100644--- a/packages/electron-mac-notifications/index.js+++ b/packages/electron-mac-notifications/index.js@@ -110,6 +110,17 @@ const getAuthorizationStatus = () => {});};+const SOUND_SETTING = ['unsupported', 'disabled', 'enabled'];++const getSoundSetting = () => {+ if (!binding) return Promise.resolve('unsupported');+ return new Promise((resolve) => {+ binding.getAuthorizationStatus((_status, sound) => {+ resolve(SOUND_SETTING[sound] || 'unsupported');+ });+ });+};+const requestAuthorization = () => {if (!ensureSetup()) return Promise.resolve(false);return new Promise((resolve) => {@@ -119,6 +130,7 @@ const requestAuthorization = () => {module.exports = {getAuthorizationStatus,+ getSoundSetting,isSupported,onNotificationEvent,requestAuthorization,diff --git a/packages/electron-mac-notifications/native/addon.mm b/packages/electron-mac-notifications/native/addon.mmindex e05293bcdcd..10ca48ee6c1 100644--- a/packages/electron-mac-notifications/native/addon.mm+++ b/packages/electron-mac-notifications/native/addon.mm@@ -103,7 +103,8 @@ static Napi::Value Setup(const Napi::CallbackInfo &info) {}static void ShowWithAuthorization(NSString *identifier, NSString *title, NSString *body, bool silent,- NSString *senderName, NSString *conversationId, NSData *avatarData) {+ NSString *soundName, NSString *senderName,+ NSString *conversationId, NSData *avatarData) {UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound |UNAuthorizationOptionBadge)@@ -117,7 +118,11 @@ static void ShowWithAuthorization(NSString *identifier, NSString *title, NSStrinUNMutableNotificationContent *content = [UNMutableNotificationContent new];content.title = title ?: @"";content.body = body ?: @"";- if (!silent) content.sound = [UNNotificationSound defaultSound];+ if (!silent) {+ content.sound = soundName.length > 0+ ? [UNNotificationSound soundNamed:soundName]+ : [UNNotificationSound defaultSound];+ }UNNotificationContent *finalContent = content;if (senderName.length > 0) {@@ -194,6 +199,9 @@ static Napi::Value Show(const Napi::CallbackInfo &info) {NSString *title = options[@"title"];NSString *body = options[@"body"];bool silent = [options[@"silent"] boolValue];+ NSString *soundName = [options[@"soundName"] isKindOfClass:[NSString class]]+ ? options[@"soundName"]+ : nil;NSDictionary *senderDict =[options[@"sender"] isKindOfClass:[NSDictionary class]] ? options[@"sender"] : nil;NSString *senderName = senderDict[@"name"];@@ -201,7 +209,8 @@ static Napi::Value Show(const Napi::CallbackInfo &info) {EnsureDelegateInstalled();dispatch_async(dispatch_get_main_queue(), ^{- ShowWithAuthorization(identifier, title, body, silent, senderName, conversationId, avatarData);+ ShowWithAuthorization(identifier, title, body, silent, soundName, senderName, conversationId,+ avatarData);});return env.Undefined();}@@ -213,8 +222,10 @@ static Napi::Value GetAuthorizationStatus(const Napi::CallbackInfo &info) {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)}); });+ long sound = (long)settings.soundSetting;+ tsfn.NonBlockingCall([status, sound](Napi::Env env, Napi::Function fn) {+ fn.Call({Napi::Number::New(env, status), Napi::Number::New(env, sound)});+ });tsfn.Release();}];return env.Undefined();diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex b13e63b015e..c766d70ee27 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1,4 +1,30 @@export default {+ 'completionSound.title': 'In-app completion sound',+ 'completionSound.enabled': 'Play completion sound',+ 'completionSound.desc':+ 'Play a chime when a chat finishes while LobeHub is in the foreground. The sound, volume and imports stay on this device and are not synced.',+ 'completionSound.sound': 'Sound',+ 'completionSound.default': 'LobeHub chime',+ 'completionSound.import': 'Import sound',+ 'completionSound.importHint':+ 'Choose WAV, MP3 or OGG (up to 1 MB), or openpeon.json from an extracted OpenPeon pack. Only task completion sounds are imported.',+ 'completionSound.preview': 'Preview',+ 'completionSound.reset': 'Use default',+ 'completionSound.volume': 'Volume',+ 'completionSound.error':+ 'Could not load, save or play the sound. Check the audio file or OpenPeon pack and try again.',+ 'completionSound.retry': 'Reload settings',+ 'completionSound.banner.title': 'Background notification',+ 'completionSound.banner.label': 'Notification sound',+ 'completionSound.banner.desc':+ 'Sound the notification banner carries when a chat finishes while LobeHub is in the background. macOS Focus and per-app notification settings still apply.',+ 'completionSound.banner.system': 'System default',+ 'completionSound.banner.lobehub': 'LobeHub chime',+ 'completionSound.banner.previewTitle': 'Notification preview',+ 'completionSound.banner.previewBody': 'This is how a finished chat will sound in the background.',+ 'completionSound.banner.systemMuted':+ 'macOS has notification sounds turned off for LobeHub, so background notifications stay silent. Turn them back on in System Settings › Notifications › LobeHub.',+'_cloud.officialProvider': '{{name}} Official Model Service','about.title': 'About','agentImport.action': 'Copy to Workspace...',diff --git a/public/sounds/chat-complete.wav b/public/sounds/chat-complete.wavnew file mode 100644index 00000000000..a0e084f32f4Binary files /dev/null and b/public/sounds/chat-complete.wav differdiff --git a/scripts/generateCompletionSound.mts b/scripts/generateCompletionSound.mtsnew file mode 100644index 00000000000..877de883fb8--- /dev/null+++ b/scripts/generateCompletionSound.mts@@ -0,0 +1,173 @@+import { mkdirSync, writeFileSync } from 'node:fs';+import path from 'node:path';++const SAMPLE_RATE = 24_000;+const DURATION = 0.8;+const PEAK = 0.72;+const FADE_OUT = 0.012;++/** Rosewood marimba bar: the second partial is tuned to the 4th harmonic, not a whole ratio. */+const WOOD: Partial[] = [+ { amp: 1, decay: 9, ratio: 1 },+ { amp: 0.28, decay: 21.6, ratio: 3.99 },+];++/** Glass bell partials are deliberately inharmonic — whole ratios read as a synth, not a bell. */+const GLASS: Partial[] = [+ { amp: 1, decay: 3.2, ratio: 1 },+ { amp: 0.3, decay: 5.12, ratio: 2.01 },+ { amp: 0.12, decay: 8, ratio: 3.02 },+];++const NOTES = [+ { freq: 698.5, gain: 1, seed: 7, start: 0 },+ { freq: 1046.5, gain: 0.88, seed: 11, start: 0.09 },+];++interface Partial {+ amp: number;+ decay: number;+ ratio: number;+}++const mulberry32 = (seed: number) => () => {+ seed = (seed + 0x6d_2b_79_f5) | 0;+ let t = seed;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return (((t ^ (t >>> 14)) >>> 0) / 4_294_967_296) * 2 - 1;+};++const addVoice = (+ buffer: Float64Array,+ {+ attack = 0.004,+ freq,+ gain,+ partials,+ start,+ tail,+ }: {+ attack?: number;+ freq: number;+ gain: number;+ partials: Partial[];+ start: number;+ tail: number;+ },+) => {+ const offset = Math.round(SAMPLE_RATE * start);+ const length = Math.min(buffer.length - offset, Math.round(SAMPLE_RATE * tail));+ for (let i = 0; i < length; i += 1) {+ const t = i / SAMPLE_RATE;+ let sample = 0;+ for (const { amp, decay, ratio } of partials) {+ sample += amp * Math.exp(-decay * t) * Math.sin(2 * Math.PI * freq * ratio * t);+ }+ buffer[offset + i] += gain * Math.min(1, t / attack) * sample;+ }+};++const addMallet = (buffer: Float64Array, start: number, gain: number, seed: number) => {+ const random = mulberry32(seed);+ const offset = Math.round(SAMPLE_RATE * start);+ const coefficient = 1800 / SAMPLE_RATE;+ let lowpass = 0;+ for (let i = 0; i < Math.round(SAMPLE_RATE * 0.02); i += 1) {+ lowpass += coefficient * (random() - lowpass);+ buffer[offset + i] += gain * lowpass * Math.exp((-260 * i) / SAMPLE_RATE);+ }+};++const render = () => {+ const buffer = new Float64Array(Math.round(SAMPLE_RATE * DURATION));++ for (const { freq, gain, seed, start } of NOTES) {+ addVoice(buffer, { freq, gain, partials: WOOD, start, tail: 0.7 });+ addMallet(buffer, start, 0.14 * gain, seed);+ addVoice(buffer, {+ attack: 0.02,+ freq: freq * 2,+ gain: 0.14 * gain,+ partials: GLASS,+ start: start + 0.02,+ tail: 0.95,+ });+ }++ let peak = 0;+ for (const value of buffer) peak = Math.max(peak, Math.abs(value));++ // The glass tail is still audible at the cut; the fade only kills the step, a longer+ // taper would swallow the bloom that gives the chime its depth.+ const fadeLength = Math.round(SAMPLE_RATE * FADE_OUT);+ const fadeStart = buffer.length - fadeLength;+ const samples = new Int16Array(buffer.length);+ for (const [i, element] of buffer.entries()) {+ let value = (element / peak) * PEAK;+ if (i > fadeStart) value *= (buffer.length - i) / fadeLength;+ samples[i] = Math.round(Math.max(-1, Math.min(1, value)) * 32_767);+ }+ return samples;+};++// UNNotificationSound resolves names only from ~/Library/Sounds, and only AIFF — a WAV+// there silently falls back to the system alert sound.+const toAiff = (samples: Int16Array) => {+ const data = Buffer.alloc(samples.length * 2);+ for (const [i, sample] of samples.entries()) data.writeInt16BE(sample, i * 2);++ const rate = Buffer.alloc(10);+ const exponent = Math.floor(Math.log2(SAMPLE_RATE));+ rate.writeUInt16BE(16_383 + exponent, 0);+ rate.writeBigUInt64BE(BigInt(Math.round((SAMPLE_RATE / 2 ** exponent) * 2 ** 31)) << 32n, 2);++ const comm = Buffer.alloc(26);+ comm.write('COMM', 0);+ comm.writeUInt32BE(18, 4);+ comm.writeUInt16BE(1, 8);+ comm.writeUInt32BE(samples.length, 10);+ comm.writeUInt16BE(16, 14);+ rate.copy(comm, 16);++ const ssnd = Buffer.alloc(16);+ ssnd.write('SSND', 0);+ ssnd.writeUInt32BE(data.length + 8, 4);++ const form = Buffer.alloc(12);+ form.write('FORM', 0);+ form.writeUInt32BE(4 + comm.length + ssnd.length + data.length, 4);+ form.write('AIFF', 8);+ return Buffer.concat([form, comm, ssnd, data]);+};++const toWav = (samples: Int16Array) => {+ const data = Buffer.from(samples.buffer, samples.byteOffset, samples.byteLength);+ const header = Buffer.alloc(44);+ header.write('RIFF', 0);+ header.writeUInt32LE(36 + data.length, 4);+ header.write('WAVEfmt ', 8);+ header.writeUInt32LE(16, 16);+ header.writeUInt16LE(1, 20);+ header.writeUInt16LE(1, 22);+ header.writeUInt32LE(SAMPLE_RATE, 24);+ header.writeUInt32LE(SAMPLE_RATE * 2, 28);+ header.writeUInt16LE(2, 32);+ header.writeUInt16LE(16, 34);+ header.write('data', 36);+ header.writeUInt32LE(data.length, 40);+ return Buffer.concat([header, data]);+};++const samples = render();+const outputs: [string, Buffer][] = [+ ['public/sounds/chat-complete.wav', toWav(samples)],+ ['apps/desktop/resources/sounds/lobehub-complete.aiff', toAiff(samples)],+];++for (const [file, content] of outputs) {+ const output = path.resolve(process.cwd(), file);+ mkdirSync(path.dirname(output), { recursive: true });+ writeFileSync(output, content);+ console.log(`Wrote ${output} (${DURATION}s, ${SAMPLE_RATE}Hz mono)`);+}diff --git a/src/features/Settings/features/componentMap.desktop.ts b/src/features/Settings/features/componentMap.desktop.tsindex 7b73f44517a..98dc3bc93a2 100644--- a/src/features/Settings/features/componentMap.desktop.ts+++ b/src/features/Settings/features/componentMap.desktop.ts@@ -1,6 +1,5 @@import Billing from '@/business/client/BusinessSettingPages/Billing';import Credits from '@/business/client/BusinessSettingPages/Credits';-import Notification from '@/business/client/BusinessSettingPages/Notification';import Plans from '@/business/client/BusinessSettingPages/Plans';import Referral from '@/business/client/BusinessSettingPages/Referral';import Usage from '@/business/client/BusinessSettingPages/Usage';@@ -18,6 +17,7 @@ import Labels from '../labels';import Labs from '../labs';import Memory from '../memory';import Messenger from '../messenger';+import { DesktopNotificationSettings } from '../notification';import OAuthApps from '../oauth-apps';import Profile from '../profile';import Provider from '../provider';@@ -37,7 +37,7 @@ export const componentMap = {[SettingsTabs.ServiceModel]: ServiceModel,[SettingsTabs.Memory]: Memory,[SettingsTabs.Messenger]: Messenger,- [SettingsTabs.Notification]: Notification,+ [SettingsTabs.Notification]: DesktopNotificationSettings,[SettingsTabs.About]: About,[SettingsTabs.Hotkey]: Hotkey,[SettingsTabs.Proxy]: Proxy,diff --git a/src/features/Settings/hooks/useCategory.tsx b/src/features/Settings/hooks/useCategory.tsxindex 760bf9fdff1..2a3f2014448 100644--- a/src/features/Settings/hooks/useCategory.tsx+++ b/src/features/Settings/hooks/useCategory.tsx@@ -118,7 +118,7 @@ export const useCategory = () => {key: SettingsTabs.Hotkey,label: t('tab.hotkey'),},- enableBusinessFeatures && {+ (enableBusinessFeatures || isDesktop) && {icon: BellIcon,key: SettingsTabs.Notification,label: t('tab.notification'),diff --git a/src/features/Settings/notification/index.tsx b/src/features/Settings/notification/index.tsxnew file mode 100644index 00000000000..77454954be5--- /dev/null+++ b/src/features/Settings/notification/index.tsx@@ -0,0 +1,218 @@+import type { CompletionSoundSettings } from '@lobechat/electron-client-ipc';+import { Flexbox, Form } from '@lobehub/ui';+import {+ ActionIcon,+ Alert,+ Button,+ Segmented,+ Skeleton,+ Slider,+ Switch,+ Text,+} from '@lobehub/ui/base-ui';+import { Play } from 'lucide-react';+import { useCallback, useEffect, useId, useState } from 'react';+import { useTranslation } from 'react-i18next';++import BusinessNotification from '@/business/client/BusinessSettingPages/Notification';+import { FORM_STYLE } from '@/const/layoutTokens';+import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';+import { completionSoundService } from '@/services/electron/completionSound';+import { desktopNotificationService } from '@/services/electron/desktopNotification';+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';++export const DesktopNotificationSettings = () => {+ const { t } = useTranslation('setting');+ const soundToggleId = useId();+ const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);+ const [settings, setSettings] = useState<CompletionSoundSettings>();+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState(false);++ const report = useCallback(async (action: () => Promise<CompletionSoundSettings | void>) => {+ setError(false);+ try {+ const next = await action();+ if (next) setSettings(next);+ } catch (error) {+ console.error('Completion sound setting failed:', error);+ setError(true);+ }+ }, []);++ /** Only state-changing actions lock the form; playing a sound changes nothing. */+ const run = async (action: () => Promise<CompletionSoundSettings | void>) => {+ setBusy(true);+ try {+ await report(action);+ } finally {+ setBusy(false);+ }+ };++ useEffect(() => {+ void report(completionSoundService.getSettings);+ }, [report]);++ const previewBanner = () =>+ report(async () => {+ const result = await desktopNotificationService.showNotification({+ body: t('completionSound.banner.previewBody'),+ // Settings is open, so the window has focus and the banner would be skipped.+ force: true,+ soundName: await completionSoundService.getNotificationSoundFile(),+ title: t('completionSound.banner.previewTitle'),+ });+ // A refused banner resolves instead of throwing, so an undelivered preview would+ // otherwise look like a dead button.+ if (!result?.success) throw new Error(result?.error ?? result?.reason ?? 'not delivered');+ });++ return (+ <>+ {error && (+ <Alert+ description={t('completionSound.error')}+ type={'error'}+ action={+ <Button onClick={() => run(completionSoundService.getSettings)}>+ {t('completionSound.retry')}+ </Button>+ }+ />+ )}+ {!settings ? (+ !error && <Skeleton.Text rows={3} />+ ) : (+ <Form+ collapsible={false}+ itemMinWidth={FORM_STYLE.itemMinWidth}+ itemsType={'group'}+ style={FORM_STYLE.style}+ variant={'filled'}+ items={[+ {+ children: [+ {+ children: (+ <Flexbox horizontal justify={'flex-end'}>+ <Switch+ checked={settings.enabled}+ disabled={busy}+ id={soundToggleId}+ onChange={(enabled) =>+ run(() => completionSoundService.setSettings({ enabled }))+ }+ />+ </Flexbox>+ ),+ desc: t('completionSound.desc'),+ htmlFor: soundToggleId,+ label: (+ <SettingsSearchAnchor id={'notification-completion-sound'}>+ {t('completionSound.enabled')}+ </SettingsSearchAnchor>+ ),+ },+ {+ children: (+ <Flexbox horizontal align={'center'} gap={8} justify={'flex-end'}>+ <Text ellipsis type={'secondary'}>+ {settings.name ?? t('completionSound.default')}+ </Text>+ <ActionIcon+ disabled={settings.volume === 0}+ icon={Play}+ size={'small'}+ title={t('completionSound.preview')}+ onClick={() => report(() => completionSoundService.play({ preview: true }))}+ />+ <Button+ disabled={busy}+ size={'small'}+ onClick={() => run(completionSoundService.importSound)}+ >+ {t('completionSound.import')}+ </Button>+ {settings.name && (+ <Button+ disabled={busy}+ size={'small'}+ type={'text'}+ onClick={() =>+ run(() => completionSoundService.setSettings({ reset: true }))+ }+ >+ {t('completionSound.reset')}+ </Button>+ )}+ </Flexbox>+ ),+ desc: t('completionSound.importHint'),+ label: t('completionSound.sound'),+ },+ {+ children: (+ <Slider+ aria-label={t('completionSound.volume')}+ disabled={busy}+ max={1}+ min={0}+ step={0.1}+ style={{ width: '100%' }}+ value={settings.volume}+ onChange={(volume) => setSettings({ ...settings, volume })}+ onChangeComplete={(volume) =>+ run(() => completionSoundService.setSettings({ volume }))+ }+ />+ ),+ label: t('completionSound.volume'),+ },+ ],+ title: t('completionSound.title'),+ },+ {+ children: [+ {+ children: (+ <Flexbox horizontal align={'center'} gap={8} justify={'flex-end'}>+ <ActionIcon+ icon={Play}+ size={'small'}+ title={t('completionSound.preview')}+ onClick={previewBanner}+ />+ <Segmented<CompletionSoundSettings['notificationSound']>+ disabled={busy}+ size={'small'}+ value={settings.notificationSound}+ options={[+ { label: t('completionSound.banner.system'), value: 'system' },+ { label: t('completionSound.banner.lobehub'), value: 'lobehub' },+ ]}+ onChange={(notificationSound) =>+ run(() => completionSoundService.setSettings({ notificationSound }))+ }+ />+ </Flexbox>+ ),+ desc: settings.systemSoundDisabled+ ? t('completionSound.banner.systemMuted')+ : t('completionSound.banner.desc'),+ label: (+ <SettingsSearchAnchor id={'notification-banner-sound'}>+ {t('completionSound.banner.label')}+ </SettingsSearchAnchor>+ ),+ },+ ],+ title: t('completionSound.banner.title'),+ },+ ]}+ />+ )}+ {enableBusinessFeatures && <BusinessNotification />}+ </>+ );+};diff --git a/src/features/SettingsSearch/items.ts b/src/features/SettingsSearch/items.tsindex f9cf52d6fd0..62362c50eb3 100644--- a/src/features/SettingsSearch/items.ts+++ b/src/features/SettingsSearch/items.ts@@ -661,6 +661,22 @@ export const SETTINGS_SEARCH_ITEMS: SettingsSearchItem[] = [tab: SettingsTabs.Usage,},// Notification+ {+ anchor: 'notification-completion-sound',+ descKey: 'completionSound.desc',+ keywords: ['sound', 'audio', 'OpenPeon', 'completion'],+ labelKey: 'completionSound.title',+ tab: SettingsTabs.Notification,+ visible: (ctx) => ctx.isDesktop,+ },+ {+ anchor: 'notification-banner-sound',+ descKey: 'completionSound.banner.desc',+ keywords: ['sound', 'notification', 'banner', 'background'],+ labelKey: 'completionSound.banner.title',+ tab: SettingsTabs.Notification,+ visible: (ctx) => ctx.isDesktop,+ },{anchor: 'notification-inbox',keywords: ['inbox', 'in-app notification'],diff --git a/src/services/electron/completionSound.test.ts b/src/services/electron/completionSound.test.tsnew file mode 100644index 00000000000..151b19970d8--- /dev/null+++ b/src/services/electron/completionSound.test.ts@@ -0,0 +1,71 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const { getPlayback } = vi.hoisted(() => ({ getPlayback: vi.fn() }));+vi.mock('@/utils/electron/ipc', () => ({+ ensureElectronIpc: () => ({ completionSound: { getPlayback } }),+}));++describe('completion sound playback', () => {+ const play = vi.fn();+ let audio: { ended: boolean; paused: boolean; play: typeof play; volume: number };+ let AudioMock: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ vi.resetModules();+ play.mockReset().mockResolvedValue(undefined);+ audio = { ended: false, paused: false, play, volume: 1 };+ AudioMock = vi.fn(function () {+ return audio;+ });+ vi.stubGlobal('Audio', AudioMock);+ getPlayback.mockReset().mockResolvedValue({ play: true, volume: 0.4 });+ });+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('plays default and imported audio at the locally saved volume', async () => {+ const { completionSoundService } = await import('./completionSound');+ await completionSoundService.play();+ expect(AudioMock).toHaveBeenCalledWith('/sounds/chat-complete.wav');+ expect(audio.volume).toBe(0.4);+ audio.ended = true;+ getPlayback.mockResolvedValue({+ dataUrl: 'data:audio/ogg;base64,TEST',+ play: true,+ volume: 0.8,+ });+ await completionSoundService.play();+ expect(AudioMock).toHaveBeenLastCalledWith('data:audio/ogg;base64,TEST');+ expect(audio.volume).toBe(0.8);+ });++ it('stays silent when the main process declines playback', async () => {+ const { completionSoundService } = await import('./completionSound');+ getPlayback.mockResolvedValue({ play: false, volume: 1 });+ await completionSoundService.play();+ expect(AudioMock).not.toHaveBeenCalled();+ });++ it('forwards the preview flag so an explicit click plays while the chime is off', async () => {+ const { completionSoundService } = await import('./completionSound');+ await completionSoundService.play({ preview: true });+ expect(getPlayback).toHaveBeenCalledWith({ preview: true });+ });++ it('coalesces concurrent completions and does not overlap a playing sound', async () => {+ const { completionSoundService } = await import('./completionSound');+ await Promise.all([completionSoundService.play(), completionSoundService.play()]);+ await completionSoundService.play();+ expect(play).toHaveBeenCalledTimes(1);+ });++ it('allows retry after playback fails', async () => {+ const { completionSoundService } = await import('./completionSound');+ audio.paused = true;+ play.mockRejectedValueOnce(new Error('decode failed'));+ await expect(completionSoundService.play()).rejects.toThrow('decode failed');+ await completionSoundService.play();+ expect(play).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/services/electron/completionSound.ts b/src/services/electron/completionSound.tsnew file mode 100644index 00000000000..44444857508--- /dev/null+++ b/src/services/electron/completionSound.ts@@ -0,0 +1,38 @@+import type { CompletionSoundSettings } from '@lobechat/electron-client-ipc';++import { ensureElectronIpc } from '@/utils/electron/ipc';++class CompletionSoundService {+ private audio?: HTMLAudioElement;+ private playing?: Promise<void>;++ getSettings = () => ensureElectronIpc().completionSound.getSettings();++ setSettings = (settings: Partial<CompletionSoundSettings> & { reset?: boolean }) =>+ ensureElectronIpc().completionSound.setSettings(settings);++ importSound = () => ensureElectronIpc().completionSound.importSound();++ getNotificationSoundFile = () => ensureElectronIpc().completionSound.getNotificationSoundFile();++ /** Start audio once, even when several runs finish together. Resolves when playback starts. */+ play = async (options?: { preview?: boolean }): Promise<void> => {+ if (this.playing) return this.playing;+ if (this.audio && !this.audio.paused && !this.audio.ended) return;+ const start = async () => {+ const playback = await ensureElectronIpc().completionSound.getPlayback(options ?? {});+ if (!playback.play) return;+ this.audio = new Audio(playback.dataUrl ?? '/sounds/chat-complete.wav');+ this.audio.volume = playback.volume;+ await this.audio.play();+ };+ this.playing = start();+ try {+ await this.playing;+ } finally {+ this.playing = undefined;+ }+ };+}++export const completionSoundService = new CompletionSoundService();diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 14789af5fb9..b19e6484718 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -128,12 +128,20 @@ vi.mock('@lobechat/const', async (importOriginal) => {// Desktop notification IPC — dynamically imported inside `notifyCompletion`.const mockShowNotification = vi.fn(async (..._args: any[]) => {});const mockSetBadgeCount = vi.fn(async (..._args: any[]) => {});+const mockGetNotificationSoundFile = vi.fn(async (..._args: any[]) => undefined);+const mockPlayCompletionSound = vi.fn(async (..._args: any[]) => {});vi.mock('@/services/electron/desktopNotification', () => ({desktopNotificationService: {setBadgeCount: (...args: any[]) => mockSetBadgeCount(...args),showNotification: (...args: any[]) => mockShowNotification(...args),},}));+vi.mock('@/services/electron/completionSound', () => ({+ completionSoundService: {+ getNotificationSoundFile: (...args: any[]) => mockGetNotificationSoundFile(...args),+ play: (...args: any[]) => mockPlayCompletionSound(...args),+ },+}));// ─── Helpers ───@@ -523,6 +531,8 @@ describe('heterogeneousAgentExecutor DB persistence', () => {beforeEach(() => {vi.clearAllMocks();+ mockGetNotificationSoundFile.mockResolvedValue(undefined);+ mockPlayCompletionSound.mockResolvedValue(undefined);ipc = setupIpcCapture();// Register the IPC session's agent type from the params the executor// hands to startSession, so the helper picks the right adapter when thediff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.tsindex 1f4a691d091..70c56e2a8e2 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts@@ -102,6 +102,10 @@ vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () =// the notification branch. The service is dynamically imported inside executeClientAgent.const desktopFlag = vi.hoisted(() => ({ value: false }));const desktopNotificationMock = vi.hoisted(() => ({ showNotification: vi.fn() }));+const completionSoundMock = vi.hoisted(() => ({+ getNotificationSoundFile: vi.fn(),+ play: vi.fn(),+}));vi.mock('@lobechat/const', async (importOriginal) => {const actual = await importOriginal<typeof LobeChatConst>();return {@@ -114,6 +118,9 @@ vi.mock('@lobechat/const', async (importOriginal) => {vi.mock('@/services/electron/desktopNotification', () => ({desktopNotificationService: desktopNotificationMock,}));+vi.mock('@/services/electron/completionSound', () => ({+ completionSoundService: completionSoundMock,+}));vi.mock('@/store/serverConfig', () => ({getServerConfigStoreState: () => ({serverConfig: { enableMultimodalUnderstanding: serverConfigMock.enableMultimodalUnderstanding },@@ -188,6 +195,8 @@ beforeEach(() => {setupMockSelectors();spyOnMessageService();desktopFlag.value = false;+ completionSoundMock.getNotificationSoundFile.mockReset().mockResolvedValue(undefined);+ completionSoundMock.play.mockReset().mockResolvedValue(undefined);serverConfigMock.enableMultimodalUnderstanding = false;act(() => {diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.tsindex b9fbacd53de..e6ca6bfd751 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.test.ts@@ -491,6 +491,7 @@ describe('buildRunLifecycle.afterRunComplete — client desktop notification bodawait lifecycle('client', get).afterRunComplete(completeEvent('client', { runtimeStatus }));expect(store.summaryTopicTitle).not.toHaveBeenCalled();+ expect(desktopNotificationMock.notifyDesktopAgentCompleted).not.toHaveBeenCalled();},);diff --git a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.tsindex 8c73b8e3adb..21352ec10f2 100644--- a/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/lifecycle/buildRunLifecycle.ts@@ -283,16 +283,15 @@ export const buildRunLifecycle = (}},afterRunComplete: async (event: RunCompleteEvent) => {- if (adapter.runScope === 'sub_agent') return;+ if (adapter.runScope === 'sub_agent' || resolveTerminalDisposition(event) !== 'success')+ return;// A voice-only first message cannot be summarized at the post-persist seam:// its content is empty and the assistant row is still a loading placeholder.// Once the reply completes, use the now-textual conversation to generate a// meaningful title. This also leaves the visible default title intact if the// title request fails instead of turning the sidebar row blank.- if (resolveTerminalDisposition(event) === 'success') {- summarizeVoiceTopicTitleAfterCompletion();- }+ summarizeVoiceTopicTitleAfterCompletion();// Desktop notification + dock badge. Single home for all runtimes'// completion notification — every transport funnels through the shareddiff --git a/src/store/chat/utils/desktopNotification.test.ts b/src/store/chat/utils/desktopNotification.test.tsindex ac82f8644d7..3cb06ec790e 100644--- a/src/store/chat/utils/desktopNotification.test.ts+++ b/src/store/chat/utils/desktopNotification.test.ts@@ -1,16 +1,18 @@+import type * as Constants from '@lobechat/const';import {AGENT_CHAT_TOPIC_URL,AGENT_CHAT_URL,GROUP_CHAT_TOPIC_URL,GROUP_CHAT_URL,} from '@lobechat/const';-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';import type { ChatStore } from '@/store/chat/store';import {buildNotificationBody,buildNotificationSender,+ notifyDesktopAgentCompleted,resolveNotificationNavigate,resolveNotificationNavigatePath,resolveNotificationTitle,@@ -18,6 +20,22 @@ import {import { renderAvatarToDataUrl } from './notificationAvatar';import { topicMapKey } from './topicMapKey';+const { getNotificationSoundFile, playSound, showNotification } = vi.hoisted(() => ({+ getNotificationSoundFile: vi.fn(),+ playSound: vi.fn(),+ showNotification: vi.fn(),+}));+vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal<typeof Constants>()),+ isDesktop: true,+}));+vi.mock('@/services/electron/completionSound', () => ({+ completionSoundService: { getNotificationSoundFile, play: playSound },+}));+vi.mock('@/services/electron/desktopNotification', () => ({+ desktopNotificationService: { showNotification },+}));+vi.mock('@/store/agent', () => ({ getAgentStoreState: () => ({}) }));vi.mock('@/store/agent/selectors', () => ({agentSelectors: {@@ -31,6 +49,50 @@ vi.mock('./notificationAvatar', () => ({const FALLBACK = 'fallback';+describe('completion sound and desktop banner', () => {+ beforeEach(() => {+ getNotificationSoundFile.mockReset().mockResolvedValue(undefined);+ playSound.mockReset().mockResolvedValue(undefined);+ showNotification.mockReset().mockResolvedValue({ success: true });+ });++ it('leaves a delivered banner to carry the sound alone', async () => {+ await notifyDesktopAgentCompleted(() => ({}) as ChatStore, { context: {}, content: 'Done' });+ expect(showNotification).toHaveBeenCalledWith(expect.objectContaining({ body: 'Done' }));+ expect(playSound).not.toHaveBeenCalled();+ });++ it.each([+ ['skipped because the window has focus', { skipped: true, success: true }],+ ['failed to display', { success: false }],+ ])('plays the in-app chime when the banner %s', async (_case, result) => {+ showNotification.mockResolvedValue(result);+ await notifyDesktopAgentCompleted(() => ({}) as ChatStore, { context: {} });+ expect(playSound).toHaveBeenCalledTimes(1);+ });++ it('hands the picked banner sound to the main process', async () => {+ getNotificationSoundFile.mockResolvedValue('lobehub-complete.wav');+ await notifyDesktopAgentCompleted(() => ({}) as ChatStore, { context: {} });+ expect(showNotification).toHaveBeenCalledWith(+ expect.objectContaining({ soundName: 'lobehub-complete.wav' }),+ );+ });++ it('swallows a failing chime so the notification path still completes', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ showNotification.mockResolvedValue({ skipped: true, success: true });+ playSound.mockRejectedValue(new Error('Unavailable audio'));+ await expect(+ notifyDesktopAgentCompleted(() => ({}) as ChatStore, { context: {} }),+ ).resolves.toBeUndefined();+ } finally {+ consoleError.mockRestore();+ }+ });+});+describe('resolveNotificationNavigatePath', () => {it('deep-links a 1:1 agent + topic to the specific topic', () => {expect(resolveNotificationNavigatePath({ agentId: 'a1', topicId: 't1' })).toBe(diff --git a/src/store/chat/utils/desktopNotification.ts b/src/store/chat/utils/desktopNotification.tsindex c2cfe4b7689..96e38f2c315 100644--- a/src/store/chat/utils/desktopNotification.ts+++ b/src/store/chat/utils/desktopNotification.ts@@ -192,21 +192,35 @@ export const notifyDesktopAgentCompleted = async (try {const { desktopNotificationService } = await import('@/services/electron/desktopNotification');+ const { completionSoundService } = await import('@/services/electron/completionSound');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),- }),- ];- if (badge) tasks.push(desktopNotificationService.setBadgeCount(1));+ const [sender, soundName] = await Promise.all([+ buildNotificationSender(context),+ completionSoundService.getNotificationSoundFile(),+ ]);- await Promise.allSettled(tasks);+ if (badge) void desktopNotificationService.setBadgeCount(1);++ // The main process owns the window-focus decision, so it also decides which of the two+ // sounds fires: a delivered banner carries the system sound, and only a banner that was+ // skipped (or failed) hands the completion chime back to the renderer. Asking here+ // instead of checking focus twice is what keeps them from doubling up.+ const result = await desktopNotificationService.showNotification({+ body: buildNotificationBody(content, fallback),+ navigate,+ sender,+ soundName,+ title: resolveNotificationTitle(get, context, fallback),+ });++ if (result?.success && !result.skipped) return;++ try {+ await completionSoundService.play();+ } catch (error) {+ console.error('Completion sound playback failed:', error);+ }} catch (error) {console.error('Agent completion desktop notification failed:', error);}