Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(desktop): add built-in completion sound choices (#19480)

Inneief6e3b1fe506
diff --git a/.gitignore b/.gitignore
index 24ad37c4db5..aa9bd3fa2ef 100644
--- a/.gitignore
+++ b/.gitignore
@@ -169,3 +169,7 @@ docs/superpowers/
# Amp agent runtime
.amp/
+
+# synthesized by plugins/vite/completionSounds.ts
+public/sounds/
+apps/desktop/resources/sounds/
diff --git a/apps/desktop/resources/sounds/lobehub-complete.aiff b/apps/desktop/resources/sounds/lobehub-complete.aiff
deleted file mode 100644
index f057fdd03b9..00000000000
Binary files a/apps/desktop/resources/sounds/lobehub-complete.aiff and /dev/null differ
diff --git a/apps/desktop/src/main/controllers/CompletionSoundCtr.ts b/apps/desktop/src/main/controllers/CompletionSoundCtr.ts
index b4d25bbfceb..a5900ffdd1c 100644
--- a/apps/desktop/src/main/controllers/CompletionSoundCtr.ts
+++ b/apps/desktop/src/main/controllers/CompletionSoundCtr.ts
@@ -1,7 +1,11 @@
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 {
+ COMPLETION_BUILTIN_SOUNDS,
+ type CompletionSoundPlayback,
+ type CompletionSoundSettings,
+} from '@lobechat/electron-client-ipc';
import { app, dialog } from 'electron';
import { z } from 'zod';
@@ -13,9 +17,9 @@ import { ControllerModule, IpcMethod } from './index';
const settingsSchema = z
.object({
+ builtin: z.enum(COMPLETION_BUILTIN_SOUNDS).optional(),
enabled: z.boolean().optional(),
notificationSound: z.enum(['lobehub', 'system']).optional(),
- reset: z.boolean().optional(),
volume: z.number().min(0).max(1).optional(),
})
.strict();
@@ -36,22 +40,24 @@ export default class CompletionSoundCtr extends ControllerModule {
return { ...this.readSettings(), systemSoundDisabled: await this.isSystemSoundDisabled() };
}
+ /** Picking a built-in sound drops the imported pack so the two never compete. */
@IpcMethod()
async setSettings(input: {
+ builtin?: CompletionSoundSettings['builtin'];
enabled?: boolean;
notificationSound?: CompletionSoundSettings['notificationSound'];
- reset?: boolean;
volume?: number;
}): Promise<CompletionSoundSettings> {
- const { reset, ...changes } = settingsSchema.parse(input);
+ const changes = settingsSchema.parse(input);
const previous = this.app.storeManager.get('completionSound');
this.app.storeManager.set('completionSound', {
- ...(reset
+ ...(changes.builtin
? { ...this.readSettings(), name: undefined }
: { ...this.readSettings(), ...previous }),
...changes,
});
- if (reset && previous?.directory) await this.removeImportedDirectory(previous.directory);
+ if (changes.builtin && previous?.directory)
+ await this.removeImportedDirectory(previous.directory);
return this.getSettings();
}
@@ -111,14 +117,13 @@ export default class CompletionSoundCtr extends ControllerModule {
}
@IpcMethod()
- async getPlayback(input?: {
- preview?: boolean;
- }): Promise<{ dataUrl?: string; play: boolean; volume: number }> {
+ async getPlayback(input?: { preview?: boolean }): Promise<CompletionSoundPlayback> {
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 };
+ if (!saved?.directory || !saved.files?.length)
+ return { builtin: settings.builtin, play, volume: settings.volume };
const candidates =
saved.files.length > 1
? saved.files.filter(({ file }) => file !== this.lastFile)
@@ -136,6 +141,7 @@ export default class CompletionSoundCtr extends ControllerModule {
private readSettings(): CompletionSoundSettings {
const settings = this.app.storeManager.get('completionSound');
return {
+ builtin: settings?.builtin ?? 'lobehub',
enabled: settings?.enabled ?? false,
name: settings?.name,
notificationSound: settings?.notificationSound ?? 'system',
diff --git a/apps/desktop/src/main/controllers/__tests__/CompletionSoundCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/CompletionSoundCtr.test.ts
index b2921a3cb51..76c60db0ae9 100644
--- a/apps/desktop/src/main/controllers/__tests__/CompletionSoundCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/CompletionSoundCtr.test.ts
@@ -79,8 +79,9 @@ describe('local completion sound settings', () => {
volume: 0.3,
});
const oldDirectory = saved!.directory!;
- await controller.setSettings({ reset: true });
+ await controller.setSettings({ builtin: 'glassBell' });
expect(await controller.getSettings()).toEqual({
+ builtin: 'glassBell',
enabled: true,
name: undefined,
notificationSound: 'system',
@@ -88,6 +89,22 @@ describe('local completion sound settings', () => {
volume: 0.3,
});
await expect(readFile(path.join(oldDirectory, '0.wav'))).rejects.toThrow();
+ expect(await controller.getPlayback()).toEqual({
+ builtin: 'glassBell',
+ play: true,
+ volume: 0.3,
+ });
+ });
+
+ it('keeps the chosen built-in sound while other settings change', async () => {
+ await controller.setSettings({ builtin: 'xylophone' });
+ await controller.setSettings({ enabled: true, volume: 0.5 });
+ expect(await controller.getPlayback()).toEqual({
+ builtin: 'xylophone',
+ play: true,
+ volume: 0.5,
+ });
+ await expect(controller.setSettings({ builtin: 'missing' as never })).rejects.toThrow();
});
it('keeps prior settings when the picker is canceled or a new import is invalid', async () => {
@@ -111,7 +128,11 @@ describe('local completion sound settings', () => {
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 });
+ expect(await controller.getPlayback({ preview: true })).toEqual({
+ builtin: 'lobehub',
+ play: true,
+ volume: 0.7,
+ });
await controller.setSettings({ volume: 0 });
expect(await controller.getPlayback({ preview: true })).toEqual({ play: false, volume: 0 });
});
diff --git a/apps/desktop/vite.main.config.ts b/apps/desktop/vite.main.config.ts
index 58b80d86295..9bb34b1916b 100644
--- a/apps/desktop/vite.main.config.ts
+++ b/apps/desktop/vite.main.config.ts
@@ -3,6 +3,7 @@ import path from 'node:path';
import { defineConfig, type UserConfig } from 'vite';
import zodCompiler from 'zod-compiler/vite';
+import { viteCompletionSounds } from '../../plugins/vite/completionSounds';
import { viteOsPlatformResolve } from '../../plugins/vite/osPlatformResolve';
import { externalRuntimeModules } from './external-runtime-deps.config.mjs';
import { getNativeExternalDependencies } from './native-deps.config.mjs';
@@ -122,7 +123,12 @@ 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(), zodCompiler(), rendererMainHashArtifact(mainHash)],
+ plugins: [
+ viteOsPlatformResolve(),
+ zodCompiler(),
+ rendererMainHashArtifact(mainHash),
+ viteCompletionSounds({ aiffDir: path.resolve(__dirname, 'resources/sounds') }),
+ ],
publicDir: false,
resolve: {
alias: mainProcessAlias,
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 86e60f53c90..c5370fa5919 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -283,14 +283,16 @@
"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.builtin.glassBell": "Glass bell",
+ "completionSound.builtin.lobehub": "LobeHub chime",
+ "completionSound.builtin.softTone": "Soft tone",
+ "completionSound.builtin.xylophone": "Xylophone",
"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.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",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 72ac187eb14..cdfad8d8917 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -283,14 +283,16 @@
"completionSound.banner.system": "系统默认",
"completionSound.banner.systemMuted": "macOS 已关闭 LobeHub 的通知声音,后台通知不会发声。可在「系统设置 › 通知 › LobeHub」中重新开启。",
"completionSound.banner.title": "后台通知",
- "completionSound.default": "LobeHub 提示音",
+ "completionSound.builtin.glassBell": "玻璃铃",
+ "completionSound.builtin.lobehub": "LobeHub 提示音",
+ "completionSound.builtin.softTone": "柔和音",
+ "completionSound.builtin.xylophone": "木琴",
"completionSound.desc": "LobeHub 处于前台时,对话完成后播放提示音。声音、音量和导入的音频仅保存在此设备,不会同步。",
"completionSound.enabled": "播放完成提示音",
"completionSound.error": "无法加载、保存或播放声音。请检查音频文件或 OpenPeon 语音包后重试。",
- "completionSound.import": "导入声音",
+ "completionSound.import": "导入声音…",
"completionSound.importHint": "选择 WAV、MP3 或 OGG 音频(不超过 1 MB),或已解压 OpenPeon 语音包中的 openpeon.json。仅导入任务完成提示音。",
"completionSound.preview": "试听",
- "completionSound.reset": "恢复默认",
"completionSound.retry": "重新加载设置",
"completionSound.sound": "声音",
"completionSound.title": "应用内完成提示音",
diff --git a/packages/electron-client-ipc/src/types/notification.ts b/packages/electron-client-ipc/src/types/notification.ts
index 57fe7412dcd..32996d54c59 100644
--- a/packages/electron-client-ipc/src/types/notification.ts
+++ b/packages/electron-client-ipc/src/types/notification.ts
@@ -1,6 +1,17 @@
export type CompletionNotificationSound = 'lobehub' | 'system';
+export type CompletionBuiltinSound = 'glassBell' | 'lobehub' | 'softTone' | 'xylophone';
+
+export const COMPLETION_BUILTIN_SOUNDS = [
+ 'lobehub',
+ 'glassBell',
+ 'softTone',
+ 'xylophone',
+] as const satisfies readonly CompletionBuiltinSound[];
+
export interface CompletionSoundSettings {
+ /** Bundled chime used while nothing is imported. */
+ builtin: CompletionBuiltinSound;
/** 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. */
@@ -12,6 +23,13 @@ export interface CompletionSoundSettings {
volume: number;
}
+export interface CompletionSoundPlayback {
+ builtin?: CompletionBuiltinSound;
+ dataUrl?: string;
+ play: boolean;
+ volume: number;
+}
+
export interface DesktopNotificationSender {
/**
* PNG data URL rendered by the caller; when present on macOS the
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index a9cb3aa5920..b6dbaf88e71 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -19,12 +19,14 @@ export default {
'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.builtin.lobehub': 'LobeHub chime',
+ 'completionSound.builtin.glassBell': 'Glass bell',
+ 'completionSound.builtin.softTone': 'Soft tone',
+ 'completionSound.builtin.xylophone': 'Xylophone',
+ '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.',
diff --git a/plugins/vite/completionSounds.test.ts b/plugins/vite/completionSounds.test.ts
new file mode 100644
index 00000000000..4f0d13d7b18
--- /dev/null
+++ b/plugins/vite/completionSounds.test.ts
@@ -0,0 +1,69 @@
+import { createHash } from 'node:crypto';
+import { mkdtemp, readdir, rm, stat } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ renderCompletionSounds,
+ viteCompletionSounds,
+ writeCompletionSounds,
+} from './completionSounds';
+
+const sha256 = (data: Buffer) => createHash('sha256').update(data).digest('hex');
+
+describe('completion sounds', () => {
+ const directories: string[] = [];
+ afterEach(async () => {
+ await Promise.all(
+ directories.map((directory) => rm(directory, { force: true, recursive: true })),
+ );
+ });
+
+ it('renders the shipped default chime unchanged', () => {
+ const { aiff, wavs } = renderCompletionSounds();
+ expect(sha256(wavs['chat-complete'])).toBe(
+ '2c7fb55ffa283824e83d1157079ad5ba631d3b3505d6189c4b5235914ac8af2c',
+ );
+ expect(sha256(aiff)).toBe('680ffeee96312acbf73711b0538c77fe044cd4b1a5a5c3987e47118b9de94764');
+ });
+
+ it('renders every built-in as a 24 kHz mono WAV under 100 KB', () => {
+ const { wavs } = renderCompletionSounds();
+ expect(Object.keys(wavs).sort()).toEqual([
+ 'chat-complete',
+ 'glass-bell',
+ 'soft-tone',
+ 'xylophone',
+ ]);
+ for (const wav of Object.values(wavs)) {
+ expect(wav.toString('ascii', 0, 4)).toBe('RIFF');
+ expect(wav.readUInt32LE(24)).toBe(24_000);
+ expect(wav.readUInt16LE(22)).toBe(1);
+ expect(wav.length).toBeLessThan(100 * 1024);
+ }
+ });
+
+ it('writes into the public dir and the aiff dir, leaving unchanged files untouched', async () => {
+ const root = await mkdtemp(path.join(tmpdir(), 'completion-sounds-'));
+ directories.push(root);
+ const publicDir = path.join(root, 'public');
+ const aiffDir = path.join(root, 'resources', 'sounds');
+ const plugin = viteCompletionSounds({ aiffDir });
+ (plugin.configResolved as (config: { publicDir: string }) => void)({ publicDir });
+ await (plugin.buildStart as () => Promise<void>)();
+
+ expect((await readdir(path.join(publicDir, 'sounds'))).sort()).toEqual([
+ 'chat-complete.wav',
+ 'glass-bell.wav',
+ 'soft-tone.wav',
+ 'xylophone.wav',
+ ]);
+ const aiff = path.join(aiffDir, 'lobehub-complete.aiff');
+ const before = (await stat(aiff)).mtimeMs;
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ await writeCompletionSounds({ aiffDir, wavDir: path.join(publicDir, 'sounds') });
+ expect((await stat(aiff)).mtimeMs).toBe(before);
+ });
+});
diff --git a/plugins/vite/completionSounds.ts b/plugins/vite/completionSounds.ts
new file mode 100644
index 00000000000..f878061c992
--- /dev/null
+++ b/plugins/vite/completionSounds.ts
@@ -0,0 +1,324 @@
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+import type { Plugin } from 'vite';
+
+const SAMPLE_RATE = 24_000;
+const PEAK = 0.72;
+const FADE_OUT = 0.012;
+const ROOT = 698.5;
+
+interface Partial {
+ amp: number;
+ decay: number;
+ ratio: number;
+}
+
+interface Note {
+ gain: number;
+ ratio: number;
+ start: number;
+}
+
+interface Instrument {
+ attack?: number;
+ body: Partial[];
+ mallet?: { cutoff: number; decay: number; gain: number };
+ shimmer?: {
+ attack: number;
+ delay: number;
+ gain: number;
+ mul: number;
+ partials: Partial[];
+ tail: number;
+ };
+ tail: number;
+ transpose: number;
+}
+
+/** 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 MARIMBA: Instrument = {
+ body: WOOD,
+ mallet: { cutoff: 1800, decay: 260, gain: 0.14 },
+ shimmer: { attack: 0.02, delay: 0.02, gain: 0.14, mul: 2, partials: GLASS, tail: 0.95 },
+ tail: 0.7,
+ transpose: 1,
+};
+
+const GLASS_BELL: Instrument = {
+ attack: 0.005,
+ body: [
+ { amp: 1, decay: 2.8, ratio: 1 },
+ { amp: 0.35, decay: 4.5, ratio: 2.01 },
+ { amp: 0.15, decay: 7, ratio: 3.02 },
+ { amp: 0.07, decay: 10, ratio: 4.2 },
+ ],
+ mallet: { cutoff: 4000, decay: 400, gain: 0.05 },
+ tail: 1.4,
+ transpose: 1.5,
+};
+
+const SOFT_TONE: Instrument = {
+ attack: 0.012,
+ body: [
+ { amp: 1, decay: 5, ratio: 1 },
+ { amp: 0.08, decay: 8, ratio: 2 },
+ ],
+ tail: 0.8,
+ transpose: 1,
+};
+
+/** Hard-mallet xylophone bar, quint-tuned (1 : 3 : 6). */
+const XYLOPHONE: Instrument = {
+ body: [
+ { amp: 1, decay: 16, ratio: 1 },
+ { amp: 0.4, decay: 30, ratio: 3 },
+ { amp: 0.15, decay: 45, ratio: 6.02 },
+ ],
+ mallet: { cutoff: 3500, decay: 300, gain: 0.22 },
+ tail: 0.45,
+ transpose: 1,
+};
+
+const RISE: Note[] = [
+ { gain: 1, ratio: 1, start: 0 },
+ { gain: 0.88, ratio: 1046.5 / 698.5, start: 0.09 },
+];
+const KNOCK: Note[] = [
+ { gain: 1, ratio: 1, start: 0 },
+ { gain: 0.8, ratio: 1, start: 0.13 },
+];
+const ARPEGGIO: Note[] = [
+ { gain: 1, ratio: 1, start: 0 },
+ { gain: 0.9, ratio: 1.26, start: 0.09 },
+ { gain: 0.85, ratio: 1.498, start: 0.18 },
+];
+const DOORBELL: Note[] = [
+ { gain: 1, ratio: 1.26, start: 0 },
+ { gain: 0.9, ratio: 1, start: 0.28 },
+];
+
+const SOUNDS: Record<string, { duration: number; instrument: Instrument; notes: Note[] }> = {
+ 'chat-complete': { duration: 0.8, instrument: MARIMBA, notes: RISE },
+ 'glass-bell': { duration: 1.5, instrument: GLASS_BELL, notes: KNOCK },
+ 'soft-tone': { duration: 1, instrument: SOFT_TONE, notes: ARPEGGIO },
+ 'xylophone': { duration: 0.75, instrument: XYLOPHONE, notes: DOORBELL },
+};
+
+// UNNotificationSound resolves names only from ~/Library/Sounds, and only AIFF — a WAV
+// there silently falls back to the system alert sound.
+export const BANNER_SOUND = { aiff: 'lobehub-complete.aiff', source: 'chat-complete' };
+
+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,
+ { cutoff, decay }: { cutoff: number; decay: number },
+) => {
+ const random = mulberry32(seed);
+ const offset = Math.round(SAMPLE_RATE * start);
+ const coefficient = cutoff / 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((-decay * i) / SAMPLE_RATE);
+ }
+};
+
+const render = (instrument: Instrument, notes: Note[], duration: number) => {
+ const buffer = new Float64Array(Math.round(SAMPLE_RATE * duration));
+
+ for (const [index, { gain, ratio, start }] of notes.entries()) {
+ const freq = ROOT * ratio * instrument.transpose;
+ addVoice(buffer, {
+ attack: instrument.attack,
+ freq,
+ gain,
+ partials: instrument.body,
+ start,
+ tail: instrument.tail,
+ });
+ if (instrument.mallet)
+ addMallet(buffer, start, instrument.mallet.gain * gain, 7 + 4 * index, instrument.mallet);
+ if (instrument.shimmer) {
+ const { attack, delay, gain: shimmerGain, mul, partials, tail } = instrument.shimmer;
+ addVoice(buffer, {
+ attack,
+ freq: freq * mul,
+ gain: shimmerGain * gain,
+ partials,
+ start: start + delay,
+ tail,
+ });
+ }
+ }
+
+ let peak = 0;
+ for (const value of buffer) peak = Math.max(peak, Math.abs(value));
+
+ // The 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;
+};
+
+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]);
+};
+
+let rendered: { aiff: Buffer; wavs: Record<string, Buffer> } | undefined;
+
+export const renderCompletionSounds = () => {
+ if (rendered) return rendered;
+ const samples = Object.fromEntries(
+ Object.entries(SOUNDS).map(([name, { duration, instrument, notes }]) => [
+ name,
+ render(instrument, notes, duration),
+ ]),
+ );
+ rendered = {
+ aiff: toAiff(samples[BANNER_SOUND.source]),
+ wavs: Object.fromEntries(Object.entries(samples).map(([name, s]) => [name, toWav(s)])),
+ };
+ return rendered;
+};
+
+const writeIfChanged = async (file: string, content: Buffer) => {
+ const existing = await readFile(file).catch(() => undefined);
+ if (existing?.equals(content)) return;
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, content);
+};
+
+export const writeCompletionSounds = async ({
+ aiffDir,
+ wavDir,
+}: {
+ aiffDir?: string;
+ wavDir?: string;
+}) => {
+ const { aiff, wavs } = renderCompletionSounds();
+ const writes = [];
+ if (wavDir)
+ for (const [name, wav] of Object.entries(wavs))
+ writes.push(writeIfChanged(path.join(wavDir, `${name}.wav`), wav));
+ if (aiffDir) writes.push(writeIfChanged(path.join(aiffDir, BANNER_SOUND.aiff), aiff));
+ await Promise.all(writes);
+};
+
+/**
+ * The chimes are synthesized rather than checked in: the renderer gets WAVs under
+ * `<publicDir>/sounds`, the desktop main build gets the AIFF the macOS banner installs.
+ */
+export const viteCompletionSounds = (options: { aiffDir?: string } = {}): Plugin => {
+ let wavDir: string | undefined;
+ return {
+ async buildStart() {
+ await writeCompletionSounds({ aiffDir: options.aiffDir, wavDir });
+ },
+ configResolved(config) {
+ if (config.publicDir) wavDir = path.join(config.publicDir, 'sounds');
+ },
+ name: 'lobe-completion-sounds',
+ };
+};
diff --git a/plugins/vite/sharedRendererConfig.ts b/plugins/vite/sharedRendererConfig.ts
index eef12a95ffe..c7cc84496d6 100644
--- a/plugins/vite/sharedRendererConfig.ts
+++ b/plugins/vite/sharedRendererConfig.ts
@@ -2,6 +2,7 @@ import react from '@vitejs/plugin-react';
import { codeInspectorPlugin } from 'code-inspector-plugin';
import type { ModulePreloadOptions, Plugin } from 'vite';
+import { viteCompletionSounds } from './completionSounds';
import { viteEmotionSpeedy } from './emotionSpeedy';
import { lobeIconImports } from './lobeIconImports';
import { lobeUiImports } from './lobeUiImports';
@@ -403,6 +404,7 @@ interface SharedRendererOptions {
export function sharedRendererPlugins(options: SharedRendererOptions) {
return [
+ viteCompletionSounds(),
viteEmotionSpeedy(),
viteMarkdownImport(),
viteNodeModuleStub(),
diff --git a/public/sounds/chat-complete.wav b/public/sounds/chat-complete.wav
deleted file mode 100644
index a0e084f32f4..00000000000
Binary files a/public/sounds/chat-complete.wav and /dev/null differ
diff --git a/scripts/generateCompletionSound.mts b/scripts/generateCompletionSound.mts
deleted file mode 100644
index 877de883fb8..00000000000
--- a/scripts/generateCompletionSound.mts
+++ /dev/null
@@ -1,173 +0,0 @@
-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/notification/index.tsx b/src/features/Settings/notification/index.tsx
index 77454954be5..81bd161b738 100644
--- a/src/features/Settings/notification/index.tsx
+++ b/src/features/Settings/notification/index.tsx
@@ -1,15 +1,9 @@
-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';
+ COMPLETION_BUILTIN_SOUNDS,
+ type CompletionSoundSettings,
+} from '@lobechat/electron-client-ipc';
+import { Flexbox, Form } from '@lobehub/ui';
+import { Alert, Button, Segmented, Select, Skeleton, Slider, Switch } from '@lobehub/ui/base-ui';
import { Play } from 'lucide-react';
import { useCallback, useEffect, useId, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -21,6 +15,9 @@ import { completionSoundService } from '@/services/electron/completionSound';
import { desktopNotificationService } from '@/services/electron/desktopNotification';
import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
+const IMPORTED = 'imported';
+const IMPORT = 'import';
+
export const DesktopNotificationSettings = () => {
const { t } = useTranslation('setting');
const soundToggleId = useId();
@@ -117,35 +114,29 @@ export const DesktopNotificationSettings = () => {
{
children: (
<Flexbox horizontal align={'center'} gap={8} justify={'flex-end'}>
- <Text ellipsis type={'secondary'}>
- {settings.name ?? t('completionSound.default')}
- </Text>
- <ActionIcon
+ <Select
+ disabled={busy}
+ value={settings.name ? IMPORTED : settings.builtin}
+ options={[
+ ...(settings.name ? [{ label: settings.name, value: IMPORTED }] : []),
+ ...COMPLETION_BUILTIN_SOUNDS.map((value) => ({
+ label: t(`completionSound.builtin.${value}`),
+ value,
+ })),
+ { label: t('completionSound.import'), value: IMPORT },
+ ]}
+ onChange={(value) => {
+ if (value === IMPORT) return run(completionSoundService.importSound);
+ const builtin = COMPLETION_BUILTIN_SOUNDS.find((id) => id === value);
+ if (builtin) run(() => completionSoundService.setSettings({ builtin }));
+ }}
+ />
+ <Button
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'),
@@ -177,15 +168,13 @@ export const DesktopNotificationSettings = () => {
{
children: (
<Flexbox horizontal align={'center'} gap={8} justify={'flex-end'}>
- <ActionIcon
+ <Button
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' },
diff --git a/src/services/electron/completionSound.test.ts b/src/services/electron/completionSound.test.ts
index 151b19970d8..9bbbf68cbb6 100644
--- a/src/services/electron/completionSound.test.ts
+++ b/src/services/electron/completionSound.test.ts
@@ -40,6 +40,13 @@ describe('completion sound playback', () => {
expect(audio.volume).toBe(0.8);
});
+ it('maps each built-in sound to its bundled file', async () => {
+ const { completionSoundService } = await import('./completionSound');
+ getPlayback.mockResolvedValue({ builtin: 'xylophone', play: true, volume: 0.4 });
+ await completionSoundService.play();
+ expect(AudioMock).toHaveBeenCalledWith('/sounds/xylophone.wav');
+ });
+
it('stays silent when the main process declines playback', async () => {
const { completionSoundService } = await import('./completionSound');
getPlayback.mockResolvedValue({ play: false, volume: 1 });
diff --git a/src/services/electron/completionSound.ts b/src/services/electron/completionSound.ts
index 44444857508..509b7546b90 100644
--- a/src/services/electron/completionSound.ts
+++ b/src/services/electron/completionSound.ts
@@ -1,14 +1,25 @@
-import type { CompletionSoundSettings } from '@lobechat/electron-client-ipc';
+import type {
+ CompletionBuiltinSound,
+ CompletionSoundPlayback,
+ CompletionSoundSettings,
+} from '@lobechat/electron-client-ipc';
import { ensureElectronIpc } from '@/utils/electron/ipc';
+const BUILTIN_FILES: Record<CompletionBuiltinSound, string> = {
+ glassBell: '/sounds/glass-bell.wav',
+ lobehub: '/sounds/chat-complete.wav',
+ softTone: '/sounds/soft-tone.wav',
+ xylophone: '/sounds/xylophone.wav',
+};
+
class CompletionSoundService {
private audio?: HTMLAudioElement;
private playing?: Promise<void>;
getSettings = () => ensureElectronIpc().completionSound.getSettings();
- setSettings = (settings: Partial<CompletionSoundSettings> & { reset?: boolean }) =>
+ setSettings = (settings: Partial<CompletionSoundSettings>) =>
ensureElectronIpc().completionSound.setSettings(settings);
importSound = () => ensureElectronIpc().completionSound.importSound();
@@ -20,9 +31,10 @@ class CompletionSoundService {
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 ?? {});
+ const playback: CompletionSoundPlayback =
+ await ensureElectronIpc().completionSound.getPlayback(options ?? {});
if (!playback.play) return;
- this.audio = new Audio(playback.dataUrl ?? '/sounds/chat-complete.wav');
+ this.audio = new Audio(playback.dataUrl ?? BUILTIN_FILES[playback.builtin ?? 'lobehub']);
this.audio.volume = playback.volume;
await this.audio.play();
};