Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat: custom sounds for agent sound alerts (#289)

Erik Zwep128584628d23
diff --git a/CLAUDE.md b/CLAUDE.md
index 7a11ead8b..d75b24686 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2587,6 +2587,19 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
Settings (`notifyOnClaudeDone`). Selecting, focusing, dwelling into, or opening a session card
clears `unread` and ACKs the finish across phone/notch surfaces — existing read-on-view behavior.
This NEVER changes the workflow bucket: read state is independent from agent state.
+- **Sound alerts + custom sounds** (issue #289) — the `done` / `needsYou` alert (`SfxKind`) is a
+ synthesized WebAudio chime (`renderer/lib/sfx.ts`, fired from Canvas's `alert` closure, gated by
+ `soundEffects`, 5 s/node cooldown). Settings → Notifications lets the user replace either with their
+ own file. The picked file's BYTES (never its path) go to `files.saveAlertSound`, a core handler in
+ `registerFsHandlers` (both shells), which validates kind / extension allow-list / 5 MB cap / magic
+ bytes and writes a FIXED name `<userData>/sounds/<kind>.<ext>` (`core/alert-sounds.ts`); reads and
+ Reset take only the kind (no path from the renderer, symlinks refused). Settings keep only
+ `customAlertSounds[kind] = {name, stamp}`. Playback decodes the bytes with `decodeAudioData` — no
+ `<audio>`, so CSP `media-src` is untouched on both surfaces — and **any failure (missing file,
+ refused read, decode/playback error) falls back to the chime without throwing** (`lib/customSfx.ts`,
+ failures not cached). Every `playSfx` caller must pass `customAlertSounds` (source-pinned in
+ `customSfx.wiring.test.ts`). Server Edition: full — the browser's `<input type=file>` bytes are
+ stored in the SERVER's data dir. Mobile: N/A (own notification sounds).
- **Status-grouped sessions** — three always-visible sections: **Waiting for your response** maps
internal `done`, `waiting`, and `blocked` together (a completed turn, question, or approval all
need the user); **Running** maps `working`; **Unknown** means no live hook state is available.
diff --git a/src/core/alert-sounds.test.ts b/src/core/alert-sounds.test.ts
new file mode 100644
index 000000000..c9c641d0f
--- /dev/null
+++ b/src/core/alert-sounds.test.ts
@@ -0,0 +1,149 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { promises as fs } from 'fs'
+import os from 'os'
+import path from 'path'
+import {
+ alertSoundsDir,
+ clearAlertSound,
+ readAlertSound,
+ saveAlertSound,
+ sniffAlertSound
+} from './alert-sounds'
+import { ALERT_SOUND_MAX_BYTES } from '../shared/alert-sound'
+
+const WAV = Buffer.concat([Buffer.from('RIFF'), Buffer.from([0x24, 0, 0, 0]), Buffer.from('WAVEfmt '), Buffer.alloc(24)])
+const MP3_ID3 = Buffer.concat([Buffer.from('ID3'), Buffer.alloc(29)])
+const MP3_SYNC = Buffer.concat([Buffer.from([0xff, 0xfb, 0x90, 0x44]), Buffer.alloc(28)])
+const OGG = Buffer.concat([Buffer.from('OggS'), Buffer.alloc(28)])
+const FLAC = Buffer.concat([Buffer.from('fLaC'), Buffer.alloc(28)])
+const M4A = Buffer.concat([Buffer.from([0, 0, 0, 0x20]), Buffer.from('ftypM4A '), Buffer.alloc(20)])
+const WEBM = Buffer.concat([Buffer.from([0x1a, 0x45, 0xdf, 0xa3]), Buffer.alloc(28)])
+const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(24)])
+
+const b64 = (b: Buffer): string => b.toString('base64')
+
+let dir: string
+beforeEach(async () => {
+ dir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-alert-sounds-'))
+})
+afterEach(async () => {
+ await fs.rm(dir, { recursive: true, force: true })
+})
+
+describe('sniffAlertSound', () => {
+ it('accepts each allow-listed format by its magic bytes', () => {
+ expect(sniffAlertSound(WAV, 'wav')).toBe(true)
+ expect(sniffAlertSound(MP3_ID3, 'mp3')).toBe(true)
+ expect(sniffAlertSound(MP3_SYNC, 'mp3')).toBe(true)
+ expect(sniffAlertSound(OGG, 'ogg')).toBe(true)
+ expect(sniffAlertSound(OGG, 'opus')).toBe(true)
+ expect(sniffAlertSound(FLAC, 'flac')).toBe(true)
+ expect(sniffAlertSound(M4A, 'm4a')).toBe(true)
+ expect(sniffAlertSound(WEBM, 'webm')).toBe(true)
+ })
+
+ it('refuses bytes that do not match the extension (a renamed image, a mislabelled format)', () => {
+ expect(sniffAlertSound(PNG, 'mp3')).toBe(false)
+ expect(sniffAlertSound(PNG, 'wav')).toBe(false)
+ expect(sniffAlertSound(OGG, 'wav')).toBe(false)
+ expect(sniffAlertSound(Buffer.alloc(2), 'mp3')).toBe(false)
+ })
+})
+
+describe('saveAlertSound', () => {
+ it('writes the bytes under a FIXED per-kind name in <userData>/sounds, never the picked name', async () => {
+ const res = await saveAlertSound(dir, 'done', 'My Ding.WAV', b64(WAV))
+ expect(res).toEqual({ ok: true, name: 'My Ding.WAV' })
+ const files = await fs.readdir(alertSoundsDir(dir))
+ expect(files).toEqual(['done.wav'])
+ expect(await fs.readFile(path.join(alertSoundsDir(dir), 'done.wav'))).toEqual(WAV)
+ })
+
+ it('reduces a path-shaped name to its base name — traversal never steers the write', async () => {
+ const res = await saveAlertSound(dir, 'needsYou', '../../etc/evil.mp3', b64(MP3_ID3))
+ expect(res).toEqual({ ok: true, name: 'evil.mp3' })
+ expect(await fs.readdir(alertSoundsDir(dir))).toEqual(['needsYou.mp3'])
+ expect(await fs.readdir(dir)).toEqual(['sounds'])
+ })
+
+ it('replaces a previous pick of another format for the same kind, and leaves the other kind alone', async () => {
+ await saveAlertSound(dir, 'done', 'a.wav', b64(WAV))
+ await saveAlertSound(dir, 'needsYou', 'b.ogg', b64(OGG))
+ await saveAlertSound(dir, 'done', 'c.mp3', b64(MP3_SYNC))
+ expect((await fs.readdir(alertSoundsDir(dir))).sort()).toEqual(['done.mp3', 'needsYou.ogg'])
+ })
+
+ it('refuses an unknown kind, a non-audio extension, mismatched bytes, empty and oversized files', async () => {
+ const bad = [
+ await saveAlertSound(dir, 'evil' as never, 'a.wav', b64(WAV)),
+ await saveAlertSound(dir, 'done', 'a.exe', b64(WAV)),
+ await saveAlertSound(dir, 'done', 'noext', b64(WAV)),
+ await saveAlertSound(dir, 'done', 'image.mp3', b64(PNG)),
+ await saveAlertSound(dir, 'done', 'empty.wav', ''),
+ await saveAlertSound(dir, 'done', 'huge.wav', b64(Buffer.concat([WAV, Buffer.alloc(ALERT_SOUND_MAX_BYTES)]))),
+ await saveAlertSound(dir, 'done', 'x.wav', 42 as never)
+ ]
+ for (const r of bad) {
+ expect(r.ok).toBe(false)
+ if (!r.ok) expect(r.error).toMatch(/\S/)
+ }
+ // Nothing was written for any refusal.
+ expect(await fs.readdir(alertSoundsDir(dir)).catch(() => [])).toEqual([])
+ })
+
+ it('refuses a hostile oversized base64 string before decoding it', async () => {
+ const r = await saveAlertSound(dir, 'done', 'a.wav', 'A'.repeat(Math.ceil(ALERT_SOUND_MAX_BYTES * 1.4) + 8))
+ expect(r.ok).toBe(false)
+ })
+
+ it('never throws — an unwritable data dir is an { ok: false }', async () => {
+ const file = path.join(dir, 'not-a-dir')
+ await fs.writeFile(file, 'x')
+ const r = await saveAlertSound(file, 'done', 'a.wav', b64(WAV))
+ expect(r.ok).toBe(false)
+ })
+})
+
+describe('readAlertSound', () => {
+ it('returns the stored bytes as base64 for a kind', async () => {
+ await saveAlertSound(dir, 'done', 'a.flac', b64(FLAC))
+ expect(await readAlertSound(dir, 'done')).toBe(b64(FLAC))
+ })
+
+ it('answers null for no custom sound, an unknown kind, or a traversal-shaped kind', async () => {
+ await saveAlertSound(dir, 'done', 'a.wav', b64(WAV))
+ expect(await readAlertSound(dir, 'needsYou')).toBeNull()
+ expect(await readAlertSound(dir, 'nope' as never)).toBeNull()
+ expect(await readAlertSound(dir, '../done' as never)).toBeNull()
+ expect(await readAlertSound(path.join(dir, 'missing'), 'done')).toBeNull()
+ })
+
+ it('refuses to follow a symlink planted at the fixed name', async () => {
+ const secret = path.join(dir, 'secret.txt')
+ await fs.writeFile(secret, 'ID3 top secret')
+ await fs.mkdir(alertSoundsDir(dir), { recursive: true })
+ await fs.symlink(secret, path.join(alertSoundsDir(dir), 'done.mp3'))
+ expect(await readAlertSound(dir, 'done')).toBeNull()
+ })
+
+ it('refuses a stored file over the size cap (hand-placed into the data dir)', async () => {
+ await fs.mkdir(alertSoundsDir(dir), { recursive: true })
+ await fs.writeFile(path.join(alertSoundsDir(dir), 'done.wav'), Buffer.concat([WAV, Buffer.alloc(ALERT_SOUND_MAX_BYTES)]))
+ expect(await readAlertSound(dir, 'done')).toBeNull()
+ })
+})
+
+describe('clearAlertSound', () => {
+ it('deletes every stored variant for the kind and nothing else', async () => {
+ await saveAlertSound(dir, 'done', 'a.wav', b64(WAV))
+ await saveAlertSound(dir, 'needsYou', 'b.wav', b64(WAV))
+ expect(await clearAlertSound(dir, 'done')).toBe(true)
+ expect(await fs.readdir(alertSoundsDir(dir))).toEqual(['needsYou.wav'])
+ expect(await readAlertSound(dir, 'done')).toBeNull()
+ })
+
+ it('is a successful no-op when nothing is stored, and refuses an unknown kind', async () => {
+ expect(await clearAlertSound(dir, 'done')).toBe(true)
+ expect(await clearAlertSound(dir, 'nope' as never)).toBe(false)
+ })
+})
diff --git a/src/core/alert-sounds.ts b/src/core/alert-sounds.ts
new file mode 100644
index 000000000..0a91a6da8
--- /dev/null
+++ b/src/core/alert-sounds.ts
@@ -0,0 +1,143 @@
+// Custom alert sounds (issue #289), core side — registered by BOTH shells through
+// `registerFsHandlers`, so desktop and the Server Edition store and serve the file the same way.
+//
+// The renderer hands over BYTES (base64) plus the picked file's name, never a path: on desktop
+// that keeps path handling out of the renderer entirely, and in the Server Edition the file sits
+// on the BROWSER's machine, so bytes are the only thing that can reach this core at all (the same
+// reasoning as core/uploads.ts). Everything is validated here, before anything is written:
+// • `kind` against the allow-list — it names the file, so it must never be free text;
+// • the extension against the audio allow-list;
+// • the size (encoded length first, then decoded) against ALERT_SOUND_MAX_BYTES;
+// • the magic bytes against the claimed extension, so a renamed image/executable is refused.
+// The file is written under a FIXED name, `<userData>/sounds/<kind>.<ext>`. The user's name is
+// only echoed back for display; it never becomes part of a path.
+//
+// Reading back takes only a `kind`, so no caller can aim it at another file, and a symlink planted
+// at the fixed name is refused (lstat) rather than followed. Every function resolves — none
+// throws — because a broken custom sound must degrade to the built-in chime, never to an error in
+// the agent-status path that plays it.
+
+import { promises as fs } from 'fs'
+import { basename, join } from 'path'
+import { renameAtomic, tempNameFor } from './fs-atomic'
+import {
+ ALERT_SOUND_EXTENSIONS,
+ ALERT_SOUND_MAX_BYTES,
+ alertSoundExtension,
+ isAlertSoundKind,
+ type AlertSoundExtension,
+ type AlertSoundKind,
+ type AlertSoundSaveResult
+} from '../shared/alert-sound'
+
+/** `<userData>/sounds` — exported so tests (and messages) can name it. */
+export const alertSoundsDir = (userDataDir: string): string => join(userDataDir, 'sounds')
+
+const startsWith = (buf: Buffer, sig: string, at = 0): boolean =>
+ buf.length >= at + sig.length && buf.toString('latin1', at, at + sig.length) === sig
+
+/** MPEG audio frame sync (11 set bits) — a bare mp3 / ADTS aac without an ID3 header. */
+const frameSync = (buf: Buffer): boolean => buf.length >= 2 && buf[0] === 0xff && (buf[1] & 0xe0) === 0xe0
+
+/**
+ * Do `buf`'s leading bytes look like the format its extension claims? Deliberately a sniff, not a
+ * decode (core has no audio decoder): it stops a renamed non-audio file at the door, and anything
+ * that passes but still does not decode falls back to the chime at playback.
+ */
+export function sniffAlertSound(buf: Buffer, ext: AlertSoundExtension): boolean {
+ switch (ext) {
+ case 'wav':
+ return startsWith(buf, 'RIFF') && startsWith(buf, 'WAVE', 8)
+ case 'mp3':
+ case 'aac':
+ return startsWith(buf, 'ID3') || frameSync(buf)
+ case 'ogg':
+ case 'oga':
+ case 'opus':
+ return startsWith(buf, 'OggS')
+ case 'flac':
+ return startsWith(buf, 'fLaC')
+ case 'm4a':
+ return startsWith(buf, 'ftyp', 4)
+ case 'webm':
+ return buf.length >= 4 && buf[0] === 0x1a && buf[1] === 0x45 && buf[2] === 0xdf && buf[3] === 0xa3
+ }
+}
+
+/** Remove every stored variant of `kind` except `keep` (a pick of another format replaces it). */
+async function removeVariants(dir: string, kind: AlertSoundKind, keep?: string): Promise<void> {
+ for (const ext of ALERT_SOUND_EXTENSIONS) {
+ const name = `${kind}.${ext}`
+ if (name !== keep) await fs.rm(join(dir, name), { force: true })
+ }
+}
+
+/** Validate and store a custom sound for `kind`. Never throws. */
+export async function saveAlertSound(
+ userDataDir: string,
+ kind: AlertSoundKind,
+ name: string,
+ dataBase64: string
+): Promise<AlertSoundSaveResult> {
+ if (!isAlertSoundKind(kind)) return { ok: false, error: 'Unknown alert sound.' }
+ const displayName = basename(String(name ?? '').replace(/\\/g, '/')).trim()
+ const ext = alertSoundExtension(displayName)
+ if (!ext) {
+ return { ok: false, error: `Use an audio file: ${ALERT_SOUND_EXTENSIONS.join(', ')}.` }
+ }
+ const tooLarge = `That file is too large — the limit is ${ALERT_SOUND_MAX_BYTES / (1024 * 1024)} MB.`
+ // Guard on the ENCODED length first: decoding a hostile huge string to measure it is the
+ // allocation this limit exists to prevent.
+ if (typeof dataBase64 !== 'string') return { ok: false, error: 'That file could not be read.' }
+ if (dataBase64.length > Math.ceil(ALERT_SOUND_MAX_BYTES * 1.4)) return { ok: false, error: tooLarge }
+ const buf = Buffer.from(dataBase64, 'base64')
+ if (!buf.length) return { ok: false, error: 'That file is empty.' }
+ if (buf.length > ALERT_SOUND_MAX_BYTES) return { ok: false, error: tooLarge }
+ if (!sniffAlertSound(buf, ext)) {
+ return { ok: false, error: `That file does not look like ${ext.toUpperCase()} audio.` }
+ }
+ const dir = alertSoundsDir(userDataDir)
+ const target = `${kind}.${ext}`
+ const tmp = tempNameFor(join(dir, target))
+ try {
+ await fs.mkdir(dir, { recursive: true })
+ // `wx` refuses a pre-planted temp (symlink) instead of writing through it; the rename then
+ // swaps the file in whole, so a concurrent read never sees half a sound.
+ await fs.writeFile(tmp, buf, { flag: 'wx' })
+ await renameAtomic(tmp, join(dir, target))
+ await removeVariants(dir, kind, target)
+ return { ok: true, name: displayName }
+ } catch {
+ await fs.rm(tmp, { force: true }).catch(() => {})
+ return { ok: false, error: 'Could not save the sound — is the data folder writable?' }
+ }
+}
+
+/** The stored custom sound for `kind` as base64, or null (none, unreadable, refused). Never throws. */
+export async function readAlertSound(userDataDir: string, kind: AlertSoundKind): Promise<string | null> {
+ if (!isAlertSoundKind(kind)) return null
+ const dir = alertSoundsDir(userDataDir)
+ for (const ext of ALERT_SOUND_EXTENSIONS) {
+ const file = join(dir, `${kind}.${ext}`)
+ try {
+ const st = await fs.lstat(file)
+ if (!st.isFile() || st.size === 0 || st.size > ALERT_SOUND_MAX_BYTES) return null
+ return (await fs.readFile(file)).toString('base64')
+ } catch {
+ /* not this extension — try the next */
+ }
+ }
+ return null
+}
+
+/** Delete the custom sound for `kind` (Reset to default). True unless the kind is unknown or the
+ * delete failed. Never throws. */
+export async function clearAlertSound(userDataDir: string, kind: AlertSoundKind): Promise<boolean> {
+ if (!isAlertSoundKind(kind)) return false
+ try {
+ await removeVariants(alertSoundsDir(userDataDir), kind)
+ return true
+ } catch {
+ return false
+ }
+}
diff --git a/src/core/fs-handlers.ts b/src/core/fs-handlers.ts
index 0e908faaa..b28bd9abc 100644
--- a/src/core/fs-handlers.ts
+++ b/src/core/fs-handlers.ts
@@ -4,6 +4,8 @@ import type { CorePlatform } from './platform'
import * as fsOps from './fs-ops'
import { saveUpload } from './uploads'
import { saveCanvasImage } from './canvas-images'
+import { clearAlertSound, readAlertSound, saveAlertSound } from './alert-sounds'
+import type { AlertSoundKind } from '../shared/alert-sound'
import { IPC } from '../shared/ipc'
import type { DownloadTicket } from '../shared/types'
@@ -77,6 +79,20 @@ export function registerFsHandlers(
dataBase64
})
)
+ // Custom alert sounds (issue #289): bytes in, a FIXED per-kind file under this core's data dir
+ // out. Reads and deletes take only a kind, so no caller can aim them at another file. See
+ // core/alert-sounds.ts for the validation.
+ platform.handle(
+ IPC.filesSaveAlertSound,
+ (kind: AlertSoundKind, name: string, dataBase64: string) =>
+ saveAlertSound(platform.userDataDir, kind, name, dataBase64)
+ )
+ platform.handle(IPC.filesReadAlertSound, (kind: AlertSoundKind) =>
+ readAlertSound(platform.userDataDir, kind)
+ )
+ platform.handle(IPC.filesClearAlertSound, (kind: AlertSoundKind) =>
+ clearAlertSound(platform.userDataDir, kind)
+ )
platform.handle(IPC.filesDownloadTicket, (p: string) =>
deps.issueDownloadTicket ? deps.issueDownloadTicket(p) : Promise.resolve(null)
)
diff --git a/src/preload/index.ts b/src/preload/index.ts
index b0adc1272..d080ae783 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -1,6 +1,7 @@
import { subscribeAgentReplay } from '../shared/agent-replay-subscription'
import { contextBridge, ipcRenderer, webFrame, webUtils } from 'electron'
import { IPC } from '../shared/ipc'
+import type { AlertSoundKind } from '../shared/alert-sound'
import { resolveUiScale } from '../shared/ui-scale'
import type {
CanvasMutation,
@@ -424,7 +425,11 @@ const api: NodeTerminalApi = {
saveUpload: (name: string, dataBase64: string) =>
ipcRenderer.invoke(IPC.filesSaveUpload, name, dataBase64),
saveCanvasImage: (projectId: string, name: string, dataBase64: string) =>
- ipcRenderer.invoke(IPC.filesSaveCanvasImage, projectId, name, dataBase64)
+ ipcRenderer.invoke(IPC.filesSaveCanvasImage, projectId, name, dataBase64),
+ saveAlertSound: (kind: AlertSoundKind, name: string, dataBase64: string) =>
+ ipcRenderer.invoke(IPC.filesSaveAlertSound, kind, name, dataBase64),
+ readAlertSound: (kind: AlertSoundKind) => ipcRenderer.invoke(IPC.filesReadAlertSound, kind),
+ clearAlertSound: (kind: AlertSoundKind) => ipcRenderer.invoke(IPC.filesClearAlertSound, kind)
},
updates: {
onAvailable: (listener) => {
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index c4f7c7a38..6ac74cf04 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -1,6 +1,7 @@
import type { NormalizedAgentEvent } from '../../shared/agents/normalize'
import { subscribeAgentReplay } from '../../shared/agent-replay-subscription'
import type { DesktopWallpaper, WallpaperStill } from '../../shared/wallpaper'
+import type { AlertSoundSaveResult } from '../../shared/alert-sound'
// WebSocket bridge that reconstructs `window.nodeTerminal` in the browser (Server Edition).
//
// Under Electron the preload already defines `window.nodeTerminal`; this module only runs when
@@ -622,7 +623,14 @@ export function buildFilesApi(
saveCanvasImage: (projectId, name, dataBase64) =>
client.request(IPC.filesSaveCanvasImage, projectId, name, dataBase64) as Promise<
string | null
- >
+ >,
+ // Real: the browser holds the picked sound's bytes and the data dir is the server's, so the
+ // server stores it and serves it back by kind (issue #289). The browser's own path never leaves
+ // the browser — a host-local path would not exist on the server anyway.
+ saveAlertSound: (kind, name, dataBase64) =>
+ client.request(IPC.filesSaveAlertSound, kind, name, dataBase64) as Promise<AlertSoundSaveResult>,
+ readAlertSound: (kind) => client.request(IPC.filesReadAlertSound, kind) as Promise<string | null>,
+ clearAlertSound: (kind) => client.request(IPC.filesClearAlertSound, kind) as Promise<boolean>
}
const context: ContextApi = {
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 511f221a8..2ffdaf76f 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -14035,7 +14035,7 @@ export function Canvas() {
const t = Date.now()
if (t - (sfxCooldownRef.current[e.nodeId] ?? 0) >= 5000) {
sfxCooldownRef.current[e.nodeId] = t
- playSfx(sound, snd.soundVolume)
+ playSfx(sound, snd.soundVolume, snd.customAlertSounds)
}
}
// OS notification only when the whole window is in the background.
diff --git a/src/renderer/components/settings/sections/NotificationsSection.tsx b/src/renderer/components/settings/sections/NotificationsSection.tsx
index de8d5201b..d0856f21c 100644
--- a/src/renderer/components/settings/sections/NotificationsSection.tsx
+++ b/src/renderer/components/settings/sections/NotificationsSection.tsx
@@ -1,11 +1,21 @@
-import { useState } from 'react'
+import { useRef, useState } from 'react'
import { useSettings } from '../../../state/settings'
import { SettingsSection } from '../SettingsSection'
import { SearchableRow } from '../SearchableRow'
import { FieldRow } from '../FieldRow'
import { Switch } from '@renderer/ui/Switch'
import { Button } from '@renderer/ui/Button'
-import { playSfx } from '@renderer/lib/sfx'
+import { checkCustomSfx, playSfx } from '@renderer/lib/sfx'
+import { readAsBase64 } from '@renderer/terminal/file-drop'
+import {
+ ALERT_SOUND_ACCEPT,
+ ALERT_SOUND_KINDS,
+ ALERT_SOUND_MAX_BYTES,
+ customAlertSoundFor,
+ type AlertSoundKind,
+ type CustomAlertSound,
+ type CustomAlertSounds
+} from '@shared/alert-sound'
const ROWS = {
notify: {
@@ -14,7 +24,7 @@ const ROWS = {
},
sound: {
title: 'Play a sound when a turn finishes or needs you',
- keywords: ['sound', 'audio', 'sfx', 'effect', 'chime', 'beep', 'retro', '8-bit', 'chiptune', 'volume', 'mute', 'finished', 'needs you']
+ keywords: ['sound', 'audio', 'sfx', 'effect', 'chime', 'beep', 'retro', '8-bit', 'chiptune', 'volume', 'mute', 'finished', 'needs you', 'custom', 'file', 'mp3', 'wav', 'own sound']
},
mobilePush: {
title: 'Send push notifications to your paired phone',
@@ -23,10 +33,125 @@ const ROWS = {
}
const ENTRIES = Object.values(ROWS)
+const SOUND_LABELS: Record<AlertSoundKind, string> = { done: 'Finished sound', needsYou: 'Needs-you sound' }
+
+/**
+ * One alert kind's sound (issue #289): the built-in chime or the user's own file. The picked file's
+ * BYTES go to the core, which validates them and stores a fixed per-kind copy in its data dir —
+ * the original path is never sent or kept, so this works the same in the Server Edition, where
+ * the file is on the browser's machine. Settings keep only the display name + a stamp.
+ */
+function CustomSoundRow({ kind, volume }: { kind: AlertSoundKind; volume: number }): React.JSX.Element {
+ const customAlertSounds = useSettings((s) => s.settings.customAlertSounds)
+ const update = useSettings((s) => s.update)
+ const current = customAlertSoundFor(customAlertSounds, kind)
+ const inputRef = useRef<HTMLInputElement>(null)
+ const [busy, setBusy] = useState(false)
+ const [note, setNote] = useState<string | undefined>()
+
+ // Rebuilt from the validated entries (never spread from the raw, hand-editable value), so a
+ // malformed entry for the other kind is dropped rather than carried forward.
+ const withEntry = (entry: CustomAlertSound | undefined): CustomAlertSounds => {
+ const base = useSettings.getState().settings.customAlertSounds
+ const next: CustomAlertSounds = {}
+ for (const k of ALERT_SOUND_KINDS) {
+ const e = k === kind ? entry : customAlertSoundFor(base, k)
+ if (e) next[k] = e
+ }
+ return next
+ }
+
+ const onPick = async (file: File | undefined): Promise<void> => {
+ if (!file) return
+ setNote(undefined)
+ // A fast answer for the obvious case; the core re-checks everything (size, type, magic bytes).
+ if (file.size > ALERT_SOUND_MAX_BYTES) {
+ setNote(`That file is too large — the limit is ${ALERT_SOUND_MAX_BYTES / (1024 * 1024)} MB.`)
+ return
+ }
+ setBusy(true)
+ try {
+ const b64 = await readAsBase64(file)
+ if (!b64) {
+ setNote('That file could not be read.')
+ return
+ }
+ const res = await window.nodeTerminal.files.saveAlertSound(kind, file.name, b64)
+ if (!res.ok) {
+ setNote(res.error)
+ return
+ }
+ const stamp = Date.now()
+ update({ customAlertSounds: withEntry({ name: res.name, stamp }) })
+ if (await checkCustomSfx(kind, stamp)) {
+ playSfx(kind, volume, useSettings.getState().settings.customAlertSounds)
+ } else {
+ setNote('Saved, but this file could not be decoded — the built-in chime will play instead.')
+ }
+ } catch {
+ setNote('Could not save the sound.')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ const onReset = async (): Promise<void> => {
+ setNote(undefined)
+ setBusy(true)
+ try {
+ await window.nodeTerminal.files.clearAlertSound(kind)
+ } catch {
+ // The entry is dropped below regardless: a stale file on disk is never played without it.
+ } finally {
+ update({ customAlertSounds: withEntry(undefined) })
+ setBusy(false)
+ }
+ }
+
+ return (
+ <FieldRow
+ label={SOUND_LABELS[kind]}
+ description={current ? current.name : 'Built-in chime'}
+ note={note}
+ control={
+ <div className="flex items-center gap-2">
+ <Button
+ onClick={() => playSfx(kind, volume, useSettings.getState().settings.customAlertSounds)}
+ aria-label={`Preview ${SOUND_LABELS[kind].toLowerCase()}`}
+ >
+ Preview
+ </Button>
+ <Button disabled={busy} onClick={() => inputRef.current?.click()}>
+ {busy ? 'Saving…' : 'Choose file…'}
+ </Button>
+ <Button variant="ghost" disabled={busy || !current} onClick={() => void onReset()}>
+ Reset
+ </Button>
+ <input
+ ref={inputRef}
+ type="file"
+ accept={ALERT_SOUND_ACCEPT}
+ hidden
+ tabIndex={-1}
+ aria-hidden="true"
+ onChange={(e) => {
+ const f = e.target.files?.[0]
+ // Reset so picking the same file again still fires `change`.
+ e.target.value = ''
+ void onPick(f)
+ }}
+ />
+ </div>
+ }
+ />
+ )
+}
+
export function NotificationsSection({ isActive }: { isActive: boolean }): React.JSX.Element {
const notifyOnClaudeDone = useSettings((s) => s.settings.notifyOnClaudeDone)
const soundEffects = useSettings((s) => s.settings.soundEffects)
const soundVolume = useSettings((s) => s.settings.soundVolume)
+ const customAlertSounds = useSettings((s) => s.settings.customAlertSounds)
const mobilePushEnabled = useSettings((s) => s.settings.mobilePushEnabled)
const mobilePushNeedsYou = useSettings((s) => s.settings.mobilePushNeedsYou)
const mobilePushDone = useSettings((s) => s.settings.mobilePushDone)
@@ -82,7 +207,7 @@ export function NotificationsSection({ isActive }: { isActive: boolean }): React
<SearchableRow {...ROWS.sound}>
<FieldRow
label="Play a sound when a turn finishes or needs you"
- description="A short retro chirp for a finished turn and a crackly one when a session needs you. Plays whether or not the window is focused, so you catch a finish while looking at another node."
+ description="A short retro chirp for a finished turn and a crackly one when a session needs you — or your own sound file for either. Plays whether or not the window is focused, so you catch a finish while looking at another node."
control={
<Switch
checked={soundEffects}
@@ -91,7 +216,7 @@ export function NotificationsSection({ isActive }: { isActive: boolean }): React
update({ soundEffects: on })
// Enabling plays the finish chirp — it doubles as the volume preview AND as the
// user gesture a browser needs before it will let us make noise at all.
- if (on) playSfx('done', soundVolume)
+ if (on) playSfx('done', soundVolume, customAlertSounds)
}}
/>
}
@@ -115,7 +240,7 @@ export function NotificationsSection({ isActive }: { isActive: boolean }): React
value={Math.round(soundVolume * 100)}
aria-label="Sound effect volume"
onChange={(e) => update({ soundVolume: Number(e.target.value) / 100 })}
- onMouseUp={() => playSfx('done', soundVolume)}
+ onMouseUp={() => playSfx('done', soundVolume, customAlertSounds)}
className="w-40 accent-[var(--accent)]"
/>
<span className="w-9 text-right text-[12px] text-muted tabular-nums">
@@ -124,15 +249,8 @@ export function NotificationsSection({ isActive }: { isActive: boolean }): React
</div>
}
/>
- <FieldRow
- label="Preview"
- control={
- <div className="flex items-center gap-2">
- <Button onClick={() => playSfx('done', soundVolume)}>Finished</Button>
- <Button onClick={() => playSfx('needsYou', soundVolume)}>Needs you</Button>
- </div>
- }
- />
+ <CustomSoundRow kind="done" volume={soundVolume} />
+ <CustomSoundRow kind="needsYou" volume={soundVolume} />
</div>
</SearchableRow>
<SearchableRow {...ROWS.mobilePush}>
diff --git a/src/renderer/lib/customSfx.test.ts b/src/renderer/lib/customSfx.test.ts
new file mode 100644
index 000000000..50f51969a
--- /dev/null
+++ b/src/renderer/lib/customSfx.test.ts
@@ -0,0 +1,127 @@
+import { describe, it, expect, vi } from 'vitest'
+import { createCustomSfxPlayer, playAlert, type CustomSfxPlayer } from './customSfx'
+
+type Buf = { id: string }
+
+function player(over: Partial<Parameters<typeof createCustomSfxPlayer<Buf>>[0]> = {}) {
+ const deps = {
+ read: vi.fn(async (kind: string) => `b64-${kind}`),
+ decode: vi.fn(async (b64: string): Promise<Buf> => ({ id: b64 })),
+ play: vi.fn((_buf: Buf, _gain: number) => {}),
+ ...over
+ }
+ return { deps, p: createCustomSfxPlayer<Buf>(deps) }
+}
+
+const flush = () => new Promise((r) => setTimeout(r, 0))
+
+describe('createCustomSfxPlayer', () => {
+ it('reads, decodes and plays the stored sound, and reports success', async () => {
+ const { deps, p } = player()
+ expect(await p.play('done', 1, 0.4)).toBe(true)
+ expect(deps.read).toHaveBeenCalledWith('done')
+ expect(deps.play).toHaveBeenCalledWith({ id: 'b64-done' }, 0.4)
+ })
+
+ it('decodes once per stamp and re-loads when the stamp changes (a new pick)', async () => {
+ const { deps, p } = player()
+ await p.play('done', 1, 0.5)
+ await p.play('done', 1, 0.5)
+ expect(deps.read).toHaveBeenCalledTimes(1)
+ await p.play('done', 2, 0.5)
+ expect(deps.read).toHaveBeenCalledTimes(2)
+ })
+
+ it('answers false — never throws — for a missing file, a decode error, or a playback error', async () => {
+ const missing = player({ read: vi.fn(async () => null) })
+ expect(await missing.p.play('done', 1, 0.5)).toBe(false)
+
+ const corrupt = player({ decode: vi.fn(async () => { throw new Error('EncodingError') }) })
+ expect(await corrupt.p.play('done', 1, 0.5)).toBe(false)
+
+ const readThrows = player({ read: vi.fn(async () => { throw new Error('E_UNSUPPORTED') }) })
+ expect(await readThrows.p.play('done', 1, 0.5)).toBe(false)
+
+ const playThrows = player({ play: vi.fn(() => { throw new Error('InvalidStateError') }) })
+ expect(await playThrows.p.play('done', 1, 0.5)).toBe(false)
+ })
+
+ it('does not cache a failure — the next alert retries (a dropped WS must not pin the chime)', async () => {
+ let fail = true
+ const { deps, p } = player({ read: vi.fn(async () => (fail ? null : 'b64')) })
+ expect(await p.play('done', 1, 0.5)).toBe(false)
+ fail = false
+ expect(await p.play('done', 1, 0.5)).toBe(true)
+ expect(deps.read).toHaveBeenCalledTimes(2)
+ })
+
+ it('preload decodes without playing', async () => {
+ const { deps, p } = player()
+ expect(await p.preload('needsYou', 3)).toBe(true)
+ expect(deps.play).not.toHaveBeenCalled()
+ await p.play('needsYou', 3, 0.5)
+ expect(deps.read).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('playAlert — the fail-to-chime guarantee', () => {
+ const custom = (result: Promise<boolean>): CustomSfxPlayer =>
+ ({ play: vi.fn(() => result), preload: vi.fn() }) as unknown as CustomSfxPlayer
+
+ it('plays the built-in chime synchronously when no custom sound is set', () => {
+ const chime = vi.fn()
+ const c = custom(Promise.resolve(true))
+ playAlert('done', 0.5, {}, { chime, custom: c })
+ expect(chime).toHaveBeenCalledWith('done', 0.5)
+ expect(c.play).not.toHaveBeenCalled()
+ })
+
+ it('plays the custom sound instead of the chime when it loads', async () => {
+ const chime = vi.fn()
+ const c = custom(Promise.resolve(true))
+ playAlert('needsYou', 0.8, { needsYou: { name: 'x.wav', stamp: 7 } }, { chime, custom: c })
+ await flush()
+ expect(c.play).toHaveBeenCalledWith('needsYou', 7, 0.8)
+ expect(chime).not.toHaveBeenCalled()
+ })
+
+ it('falls back to the chime when the custom sound fails or rejects', async () => {
+ const chime = vi.fn()
+ playAlert('done', 0.5, { done: { name: 'x', stamp: 1 } }, { chime, custom: custom(Promise.resolve(false)) })
+ playAlert('done', 0.5, { done: { name: 'x', stamp: 1 } }, { chime, custom: custom(Promise.reject(new Error('x'))) })
+ await flush()
+ expect(chime).toHaveBeenCalledTimes(2)
+ })
+
+ it('only the matching kind is replaced, and a malformed settings entry reads as no custom sound', () => {
+ const chime = vi.fn()
+ const c = custom(Promise.resolve(true))
+ playAlert('done', 0.5, { needsYou: { name: 'x', stamp: 1 } }, { chime, custom: c })
+ playAlert('done', 0.5, { done: { name: 'x' } } as never, { chime, custom: c })
+ playAlert('done', 0.5, 'garbage' as never, { chime, custom: c })
+ expect(chime).toHaveBeenCalledTimes(3)
+ expect(c.play).not.toHaveBeenCalled()
+ })
+
+ it('is silent at volume 0 and clamps the volume', async () => {
+ const chime = vi.fn()
+ const c = custom(Promise.resolve(true))
+ playAlert('done', 0, { done: { name: 'x', stamp: 1 } }, { chime, custom: c })
+ playAlert('done', -3, {}, { chime, custom: c })
+ expect(chime).not.toHaveBeenCalled()
+ expect(c.play).not.toHaveBeenCalled()
+ playAlert('done', 7, {}, { chime, custom: c })
+ expect(chime).toHaveBeenCalledWith('done', 1)
+ })
+
+ it('never throws into the caller, even when the chime itself throws', async () => {
+ const chime = vi.fn(() => {
+ throw new Error('boom')
+ })
+ expect(() => playAlert('done', 0.5, {}, { chime, custom: custom(Promise.resolve(false)) })).not.toThrow()
+ expect(() =>
+ playAlert('done', 0.5, { done: { name: 'x', stamp: 1 } }, { chime, custom: custom(Promise.resolve(false)) })
+ ).not.toThrow()
+ await flush() // the async fallback's throw must not surface as an unhandled rejection
+ })
+})
diff --git a/src/renderer/lib/customSfx.ts b/src/renderer/lib/customSfx.ts
new file mode 100644
index 000000000..000874bad
--- /dev/null
+++ b/src/renderer/lib/customSfx.ts
@@ -0,0 +1,119 @@
+// Custom alert sounds (issue #289), renderer half: WHICH sound an alert plays, and the guarantee
+// that choosing one can never cost the user the alert — or break the agent-status path that fires
+// it. Pure over injected deps (no WebAudio, no IPC) so the fallback rules are unit-tested; sfx.ts
+// wires the real ones.
+//
+// Rules:
+// • No custom sound for the kind (or a malformed settings entry) ⇒ the built-in chime, played
+// synchronously exactly as before this feature.
+// • A custom sound is loaded by KIND from the core (never by path), decoded once per `stamp`,
+// and played at the user's volume. Anything that goes wrong — missing file, a read the bridge
+// refuses, a decode error, a playback error — answers `false`, and the caller plays the chime.
+// • A failure is NOT cached: the next alert retries, so a transiently dropped Server Edition
+// socket does not pin the chime for the rest of the run.
+// • Nothing here throws into the caller, synchronously or as an unhandled rejection.
+
+import { customAlertSoundFor, type AlertSoundKind } from '@shared/alert-sound'
+
+export interface CustomSfxDeps<B> {
+ /** The stored sound's bytes (base64), or null when there is none. May reject. */
+ read(kind: AlertSoundKind): Promise<string | null>
+ /** Decode base64 audio into something `play` accepts. Rejects on a corrupt file. */
+ decode(dataBase64: string): Promise<B>
+ /** Start playback at `gain` (0..1, the user's volume). May throw. */
+ play(buf: B, gain: number): void
+}
+
+export interface CustomSfxPlayer {
+ /** Play the custom sound for `kind` at `stamp`. True when it started; false on ANY failure. */
+ play(kind: AlertSoundKind, stamp: number, gain: number): Promise<boolean>
+ /** Load + decode without playing (the Settings check after a pick). True when it decodes. */
+ preload(kind: AlertSoundKind, stamp: number): Promise<boolean>
+}
+
+export function createCustomSfxPlayer<B>(deps: CustomSfxDeps<B>): CustomSfxPlayer {
+ const cache = new Map<AlertSoundKind, { stamp: number; buf: Promise<B | null> }>()
+
+ const load = (kind: AlertSoundKind, stamp: number): Promise<B | null> => {
+ const hit = cache.get(kind)
+ if (hit && hit.stamp === stamp) return hit.buf
+ const buf = (async (): Promise<B | null> => {
+ try {
+ const b64 = await deps.read(kind)
+ if (!b64) return null
+ return await deps.decode(b64)
+ } catch {
+ return null
+ }
+ })()
+ const entry = { stamp, buf }
+ cache.set(kind, entry)
+ // Only a success stays cached; a failure is forgotten so the next alert asks again.
+ void buf.then((b) => {
+ if (b === null && cache.get(kind) === entry) cache.delete(kind)
+ })
+ return buf
+ }
+
+ return {
+ async play(kind, stamp, gain) {
+ const buf = await load(kind, stamp)
+ if (buf === null) return false
+ try {
+ deps.play(buf, gain)
+ return true
+ } catch {
+ return false
+ }
+ },
+ async preload(kind, stamp) {
+ return (await load(kind, stamp)) !== null
+ }
+ }
+}
+
+export interface PlayAlertDeps {
+ /** The built-in synthesized chime. */
+ chime(kind: AlertSoundKind, volume: number): void
+ custom: CustomSfxPlayer
+}
+
+const safeChime = (deps: PlayAlertDeps, kind: AlertSoundKind, volume: number): void => {
+ try {
+ deps.chime(kind, volume)
+ } catch {
+ // Losing a chirp is never worth surfacing.
+ }
+}
+
+/**
+ * Play the alert for `kind`: the user's custom sound when one is set and loads, else the built-in
+ * chime. `custom` is `settings.customAlertSounds` as read (validated here, not trusted). Never
+ * throws and never blocks.
+ */
+export function playAlert(
+ kind: AlertSoundKind,
+ volume: number,
+ custom: unknown,
+ deps: PlayAlertDeps
+): void {
+ const vol = Number.isFinite(volume) ? Math.max(0, Math.min(1, volume)) : 0
+ if (vol <= 0) return
+ const ref = customAlertSoundFor(custom, kind)
+ if (!ref) {
+ safeChime(deps, kind, vol)
+ return
+ }
+ let started: Promise<boolean>
+ try {
+ started = deps.custom.play(kind, ref.stamp, vol)
+ } catch {
+ started = Promise.resolve(false)
+ }
+ void started.then(
+ (ok) => {
+ if (!ok) safeChime(deps, kind, vol)
+ },
+ () => safeChime(deps, kind, vol)
+ )
+}
diff --git a/src/renderer/lib/customSfx.wiring.test.ts b/src/renderer/lib/customSfx.wiring.test.ts
new file mode 100644
index 000000000..8a72d928d
--- /dev/null
+++ b/src/renderer/lib/customSfx.wiring.test.ts
@@ -0,0 +1,42 @@
+// Source pins for the custom-alert-sound wiring (issue #289). The agent-status listener lives in a
+// Canvas.tsx `useEffect` no harness can dispatch at (see fanout-chime.test.ts), and the fallback
+// logic itself is behaviourally tested in customSfx.test.ts — what only the source can show is that
+// every caller hands the user's custom sounds to playSfx. A caller that forgets compiles fine
+// (the argument is optional) and silently plays the chime forever.
+
+import { describe, it, expect } from 'vitest'
+import fs from 'fs'
+import path from 'path'
+
+const read = (rel: string): string =>
+ fs.readFileSync(path.resolve(__dirname, rel), 'utf8').replace(/\r\n/g, '\n')
+
+describe('custom alert sound wiring', () => {
+ it('the agent-status alert passes settings.customAlertSounds to playSfx', () => {
+ const src = read('../canvas/Canvas.tsx')
+ const start = src.indexOf('const alert = (')
+ const end = src.indexOf('const an = useAgentNodes.getState()', start)
+ const body = src.slice(start, end)
+ expect(body).toContain('playSfx(sound, snd.soundVolume, snd.customAlertSounds)')
+ })
+
+ it('every playSfx call in Settings → Notifications passes the custom sounds too', () => {
+ const src = read('../components/settings/sections/NotificationsSection.tsx')
+ // To end of line, not to the first `)`: an argument may itself be a call.
+ const calls = [...src.matchAll(/playSfx\(([^\n]*)/g)].map((m) => m[1])
+ expect(calls.length).toBeGreaterThan(0)
+ for (const args of calls) expect(args).toMatch(/customAlertSounds/)
+ })
+
+ it('the settings default carries an empty custom-sound map (an update changes nothing)', () => {
+ const src = read('../../shared/types.ts')
+ expect(src).toMatch(/customAlertSounds: \{\},/)
+ })
+
+ it('the Settings picker stores bytes through files.saveAlertSound, never a path', () => {
+ const src = read('../components/settings/sections/NotificationsSection.tsx')
+ expect(src).toContain('files.saveAlertSound(')
+ expect(src).toContain('files.clearAlertSound(')
+ expect(src).not.toMatch(/readBinary|selectFile|\.path\b/)
+ })
+})
diff --git a/src/renderer/lib/sfx.ts b/src/renderer/lib/sfx.ts
index 069731a67..2d41e5458 100644
--- a/src/renderer/lib/sfx.ts
+++ b/src/renderer/lib/sfx.ts
@@ -8,8 +8,16 @@
//
// Three surfaces: this is pure renderer, so desktop AND the browser Server Edition get it for free.
// The mobile companion is a separate app with its own notification sounds — not applicable here.
+//
+// A user may replace either chime with their own file (issue #289, Settings → Notifications). The
+// file lives in the core's data dir and is fetched by KIND over `files.readAlertSound`, then decoded
+// with WebAudio (`decodeAudioData` on the bytes — no <audio> element, so no CSP `media-src` change on
+// either surface). The fallback rules live in lib/customSfx.ts: any failure plays the chime below.
+
+import type { AlertSoundKind } from '@shared/alert-sound'
+import { createCustomSfxPlayer, playAlert, type CustomSfxPlayer } from './customSfx'
-export type SfxKind = 'done' | 'needsYou'
+export type SfxKind = AlertSoundKind
/** One scheduled voice. `noise` is a filtered white-noise burst; everything else is an oscillator. */
export interface SfxVoice {
@@ -98,10 +106,10 @@ function noise(c: AudioContext): AudioBuffer {
}
/**
- * Play an effect. Never throws and never blocks: an unavailable/blocked audio context is simply
- * silence — a sound effect must not be able to break the agent-status path that calls it.
+ * Play the built-in synthesized chime. `volume` is the user's 0..1 volume (already clamped by the
+ * caller). Never throws: an unavailable/blocked audio context is simply silence.
*/
-export function playSfx(kind: SfxKind, volume = 0.5): void {
+function playChime(kind: SfxKind, volume: number): void {
const c = audio()
if (!c) return
if (c.state === 'suspended') void c.resume()
@@ -142,3 +150,71 @@ export function playSfx(kind: SfxKind, volume = 0.5): void {
// Nothing to do — losing a chirp is never worth surfacing.
}
}
+
+/** Trim for a user's own sound. Lighter than MASTER: the chimes are raw full-scale square/saw waves,
+ * while a picked file is (usually) already mastered — the volume slider still scales it. */
+const CUSTOM_MASTER = 0.5
+/** A notification, not a song: a long file is cut off here. */
+const CUSTOM_MAX_SECONDS = 10
+
+function base64ToArrayBuffer(b64: string): ArrayBuffer {
+ const bin = atob(b64)
+ const out = new Uint8Array(bin.length)
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)
+ return out.buffer
+}
+
+let customPlayer: CustomSfxPlayer | null = null
+
+function custom(): CustomSfxPlayer {
+ if (customPlayer) return customPlayer
+ customPlayer = createCustomSfxPlayer<AudioBuffer>({
+ read: async (kind) => {
+ const files = typeof window === 'undefined' ? undefined : window.nodeTerminal?.files
+ return files?.readAlertSound ? files.readAlertSound(kind) : null
+ },
+ decode: async (b64) => {
+ const c = audio()
+ if (!c) throw new Error('no audio context')
+ return c.decodeAudioData(base64ToArrayBuffer(b64))
+ },
+ play: (buf, gain) => {
+ const c = audio()
+ if (!c) throw new Error('no audio context')
+ if (c.state === 'suspended') void c.resume()
+ const g = c.createGain()
+ g.gain.value = gain * CUSTOM_MASTER
+ g.connect(c.destination)
+ const src = c.createBufferSource()
+ src.buffer = buf
+ src.connect(g)
+ const t0 = c.currentTime + 0.01
+ src.start(t0)
+ src.stop(t0 + CUSTOM_MAX_SECONDS)
+ }
+ })
+ return customPlayer
+}
+
+/**
+ * Play an alert: the user's custom sound for `kind` when `customSounds` (settings.customAlertSounds)
+ * names one and it loads, else the built-in chime. Never throws and never blocks — a sound effect
+ * must not be able to break the agent-status path that calls it.
+ */
+export function playSfx(kind: SfxKind, volume = 0.5, customSounds?: unknown): void {
+ try {
+ playAlert(kind, volume, customSounds, { chime: playChime, custom: custom() })
+ } catch {
+ // Nothing to do — losing a chirp is never worth surfacing.
+ }
+}
+
+/** Decode the stored custom sound for `kind` without playing it — Settings' post-pick check.
+ * True when it decodes; false (never a throw) when it will fall back to the chime. */
+export function checkCustomSfx(kind: SfxKind, stamp: number): Promise<boolean> {
+ try {
+ return custom().preload(kind, stamp).catch(() => false)
+ } catch {
+ return Promise.resolve(false)
+ }
+}
diff --git a/src/renderer/terminal/file-drop.ts b/src/renderer/terminal/file-drop.ts
index 2953340c6..df6a9e317 100644
--- a/src/renderer/terminal/file-drop.ts
+++ b/src/renderer/terminal/file-drop.ts
@@ -119,7 +119,7 @@ export async function clipboardImages(): Promise<File[]> {
}
}
-const readAsBase64 = (file: File): Promise<string | null> =>
+export const readAsBase64 = (file: File): Promise<string | null> =>
new Promise((resolve) => {
const reader = new FileReader()
reader.onerror = () => resolve(null)
diff --git a/src/server/handlers/fs-handlers.test.ts b/src/server/handlers/fs-handlers.test.ts
index a66c2eb67..4098a1458 100644
--- a/src/server/handlers/fs-handlers.test.ts
+++ b/src/server/handlers/fs-handlers.test.ts
@@ -95,6 +95,26 @@ describe('server fs handlers', () => {
)
})
+ // Custom alert sounds (issue #289): the SAME core handlers serve desktop and the Server Edition,
+ // and the stored file lives in THIS core's data dir — the browser's own path means nothing here.
+ it('saves, reads back and clears a custom alert sound in the data dir', async () => {
+ const wav = Buffer.concat([Buffer.from('RIFF'), Buffer.alloc(4), Buffer.from('WAVE'), Buffer.alloc(20)])
+ expect(await call(IPC.filesSaveAlertSound, 'done', 'ding.wav', wav.toString('base64'))).toEqual({
+ ok: true,
+ name: 'ding.wav'
+ })
+ expect(fs.readdirSync(path.join(dir, 'sounds'))).toEqual(['done.wav'])
+ expect(await call(IPC.filesReadAlertSound, 'done')).toBe(wav.toString('base64'))
+ expect(await call(IPC.filesClearAlertSound, 'done')).toBe(true)
+ expect(await call(IPC.filesReadAlertSound, 'done')).toBeNull()
+ })
+
+ it('never reads a path the caller names — an unknown kind is null', async () => {
+ fs.writeFileSync(path.join(dir, 'secret.wav'), 'RIFFxxxxWAVE')
+ expect(await call(IPC.filesReadAlertSound, '../secret')).toBeNull()
+ expect(await call(IPC.filesReadAlertSound, path.join(dir, 'secret.wav'))).toBeNull()
+ })
+
it('quickOpen lists files under the root', async () => {
fs.writeFileSync(path.join(dir, 'q.txt'), 'x')
const files = (await call(IPC.filesQuickOpen, dir)) as string[]
diff --git a/src/shared/alert-sound.ts b/src/shared/alert-sound.ts
new file mode 100644
index 000000000..77bc64cdc
--- /dev/null
+++ b/src/shared/alert-sound.ts
@@ -0,0 +1,60 @@
+// Custom sounds for the agent alerts (issue #289). The built-in chimes are synthesized in
+// `renderer/lib/sfx.ts`; a user may replace either one with their own audio file.
+//
+// The FILE lives in the data dir of the machine that owns the core (`<userData>/sounds/<kind>.<ext>`
+// — see core/alert-sounds.ts), never at the user's original path: in the Server Edition that path
+// names a disk on another machine. What rides in settings is only the display name and a stamp,
+// so every window/client can tell a new pick from the one it already decoded.
+
+/** The alert kinds a user can hear — and therefore replace. Mirrors `SfxKind`. */
+export const ALERT_SOUND_KINDS = ['done', 'needsYou'] as const
+export type AlertSoundKind = (typeof ALERT_SOUND_KINDS)[number]
+
+/** A notification sound, not an album: anything bigger is refused before it is written. Also keeps
+ * the base64 round-trip (~4/3 of the bytes) under the Server Edition's 8 MiB WS frame cap. */
+export const ALERT_SOUND_MAX_BYTES = 5 * 1024 * 1024
+
+/** Extension allow-list. Each is a format Chromium's `decodeAudioData` handles. */
+export const ALERT_SOUND_EXTENSIONS = ['mp3', 'wav', 'ogg', 'oga', 'opus', 'm4a', 'aac', 'flac', 'webm'] as const
+export type AlertSoundExtension = (typeof ALERT_SOUND_EXTENSIONS)[number]
+
+/** `accept` for the file input — the same list, dotted. */
+export const ALERT_SOUND_ACCEPT = ALERT_SOUND_EXTENSIONS.map((e) => `.${e}`).join(',')
+
+/** What settings remember about a custom sound: never a path. */
+export interface CustomAlertSound {
+ /** The picked file's base name, for display only. */
+ name: string
+ /** Changes on every pick — the renderer's decode-cache key. */
+ stamp: number
+}
+
+export type CustomAlertSounds = Partial<Record<AlertSoundKind, CustomAlertSound>>
+
+export type AlertSoundSaveResult = { ok: true; name: string } | { ok: false; error: string }
+
+export function isAlertSoundKind(v: unknown): v is AlertSoundKind {
+ return typeof v === 'string' && (ALERT_SOUND_KINDS as readonly string[]).includes(v)
+}
+
+/** The lower-cased, allow-listed extension of `name`, or null. */
+export function alertSoundExtension(name: unknown): AlertSoundExtension | null {
+ if (typeof name !== 'string') return null
+ const m = /\.([A-Za-z0-9]+)$/.exec(name.trim())
+ if (!m) return null
+ const ext = m[1].toLowerCase()
+ return (ALERT_SOUND_EXTENSIONS as readonly string[]).includes(ext) ? (ext as AlertSoundExtension) : null
+}
+
+/**
+ * The custom sound settings hold for `kind`, or undefined. settings.json is hand-editable, so the
+ * shape is checked rather than trusted — a malformed entry reads as "no custom sound" (the chime).
+ */
+export function customAlertSoundFor(v: unknown, kind: AlertSoundKind): CustomAlertSound | undefined {
+ if (!v || typeof v !== 'object') return undefined
+ const e = (v as Record<string, unknown>)[kind]
+ if (!e || typeof e !== 'object') return undefined
+ const { name, stamp } = e as Record<string, unknown>
+ if (typeof name !== 'string' || typeof stamp !== 'number' || !Number.isFinite(stamp)) return undefined
+ return { name, stamp }
+}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 3954812cc..6c11975d6 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -445,6 +445,10 @@ export const IPC = {
filesSaveUpload: 'files:save-upload',
/** Write a canvas image into the project's own `.nodeterm/images/` (see core/canvas-images.ts). */
filesSaveCanvasImage: 'files:save-canvas-image',
+ /** Custom agent-alert sounds (issue #289) — stored under the core's data dir, addressed by kind. */
+ filesSaveAlertSound: 'files:save-alert-sound',
+ filesReadAlertSound: 'files:read-alert-sound',
+ filesClearAlertSound: 'files:clear-alert-sound',
settingsLoad: 'settings:load',
settingsSave: 'settings:save',
sshList: 'ssh:list',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 92217b1f5..485fadaec 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -23,6 +23,7 @@ import type { KanbanPullAutoMove, KanbanPullLinks } from './kanban-pull-links'
import type { CodexAccount } from './codex-account'
import type { NotchAlign } from './notch-hud'
import type { ProjectIcon, ProjectIconPickResult } from './project-icon'
+import type { AlertSoundKind, AlertSoundSaveResult, CustomAlertSounds } from './alert-sound'
import type { CanvasLayout, LayoutViewports } from './canvas-layout'
import type {
ModelDiscoveryResult,
@@ -1369,6 +1370,17 @@ export interface FilesApi {
* Resolves null when it could not be written; callers drop that file like a failed drop.
*/
saveCanvasImage(projectId: string, name: string, dataBase64: string): Promise<string | null>
+ /**
+ * Store a custom sound for an agent alert (issue #289). The core validates kind, extension,
+ * size and magic bytes, then writes a FIXED per-kind file under its own data dir — the picked
+ * file's path is never sent, only its bytes and base name. Resolves `{ ok: false, error }` for a
+ * refusal; never rejects on a bad file.
+ */
+ saveAlertSound(kind: AlertSoundKind, name: string, dataBase64: string): Promise<AlertSoundSaveResult>
+ /** The stored custom sound for `kind` as base64, or null when there is none (or it is unreadable). */
+ readAlertSound(kind: AlertSoundKind): Promise<string | null>
+ /** Delete the custom sound for `kind` (Reset to default). */
+ clearAlertSound(kind: AlertSoundKind): Promise<boolean>
}
export interface MediaApi {
@@ -1791,6 +1803,11 @@ export interface Settings {
soundEffects: boolean
/** Sound-effect volume, 0..1. */
soundVolume: number
+ /** User-picked replacements for the built-in chimes, per alert kind (issue #289). Holds only a
+ * display name + a stamp — the FILE lives in the core's data dir (`<userData>/sounds/`), never
+ * at the user's original path. Read through `customAlertSoundFor` (hand-editable JSON); an
+ * absent/malformed entry, or a file that is gone or will not decode, plays the built-in chime. */
+ customAlertSounds: CustomAlertSounds
/** User-defined agents (BYO CLI) appended to the Add menus. */
customAgents: CustomAgent[]
/** One gateway root + non-secret credential reference used by model-switch-capable harnesses. */
@@ -2071,6 +2088,7 @@ export const DEFAULT_SETTINGS: Settings = {
notifyConsentAsked: false,
soundEffects: true,
soundVolume: 0.5,
+ customAlertSounds: {},
customAgents: [],
modelGateway: { baseUrl: '', apiKey: '' },
// No default gateway model until the user picks one in Settings → Model gateway. Absent ⇒