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.

fix: race-free alert-sound storage (#289)

Erik Zwepe8e7bc8086b4
diff --git a/CLAUDE.md b/CLAUDE.md
index d75b24686..1d324bc70 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2592,8 +2592,10 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
`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
+ bytes and writes ONE format-independent name `<userData>/sounds/<kind>.sound` (`core/alert-sounds.ts`;
+ a name per format needed a delete-the-others step, and two tabs saving different formats at once
+ deleted each other's file — do not reintroduce per-format names); 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`,
diff --git a/src/core/alert-sounds.test.ts b/src/core/alert-sounds.test.ts
index c9c641d0f..f5884a508 100644
--- a/src/core/alert-sounds.test.ts
+++ b/src/core/alert-sounds.test.ts
@@ -51,18 +51,18 @@ describe('sniffAlertSound', () => {
})
describe('saveAlertSound', () => {
- it('writes the bytes under a FIXED per-kind name in <userData>/sounds, never the picked name', async () => {
+ it('writes the bytes under a FIXED, format-independent 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)
+ expect(files).toEqual(['done.sound'])
+ expect(await fs.readFile(path.join(alertSoundsDir(dir), 'done.sound'))).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(alertSoundsDir(dir))).toEqual(['needsYou.sound'])
expect(await fs.readdir(dir)).toEqual(['sounds'])
})
@@ -70,7 +70,7 @@ describe('saveAlertSound', () => {
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'])
+ expect((await fs.readdir(alertSoundsDir(dir))).sort()).toEqual(['done.sound', 'needsYou.sound'])
})
it('refuses an unknown kind, a non-audio extension, mismatched bytes, empty and oversized files', async () => {
@@ -104,6 +104,30 @@ describe('saveAlertSound', () => {
})
})
+describe('concurrent mutations of one kind (Server Edition: several tabs, one data dir)', () => {
+ it('two concurrent saves of DIFFERENT formats leave exactly one readable sound, never none', async () => {
+ for (let i = 0; i < 20; i++) {
+ const [a, b] = await Promise.all([
+ saveAlertSound(dir, 'done', 'a.mp3', b64(MP3_ID3)),
+ saveAlertSound(dir, 'done', 'b.wav', b64(WAV))
+ ])
+ expect(a.ok && b.ok).toBe(true)
+ const got = await readAlertSound(dir, 'done')
+ expect([b64(MP3_ID3), b64(WAV)]).toContain(got)
+ expect((await fs.readdir(alertSoundsDir(dir))).filter((f) => f.startsWith('done'))).toHaveLength(1)
+ }
+ })
+
+ it('a save racing a clear ends in one coherent state: the new sound, or none', async () => {
+ for (let i = 0; i < 20; i++) {
+ await saveAlertSound(dir, 'done', 'old.flac', b64(FLAC))
+ await Promise.all([saveAlertSound(dir, 'done', 'new.ogg', b64(OGG)), clearAlertSound(dir, 'done')])
+ const got = await readAlertSound(dir, 'done')
+ expect([null, b64(OGG)]).toContain(got)
+ }
+ })
+})
+
describe('readAlertSound', () => {
it('returns the stored bytes as base64 for a kind', async () => {
await saveAlertSound(dir, 'done', 'a.flac', b64(FLAC))
@@ -122,13 +146,13 @@ describe('readAlertSound', () => {
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'))
+ await fs.symlink(secret, path.join(alertSoundsDir(dir), 'done.sound'))
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)]))
+ await fs.writeFile(path.join(alertSoundsDir(dir), 'done.sound'), Buffer.concat([WAV, Buffer.alloc(ALERT_SOUND_MAX_BYTES)]))
expect(await readAlertSound(dir, 'done')).toBeNull()
})
})
@@ -138,7 +162,7 @@ describe('clearAlertSound', () => {
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 fs.readdir(alertSoundsDir(dir))).toEqual(['needsYou.sound'])
expect(await readAlertSound(dir, 'done')).toBeNull()
})
diff --git a/src/core/alert-sounds.ts b/src/core/alert-sounds.ts
index 0a91a6da8..0abb2b85b 100644
--- a/src/core/alert-sounds.ts
+++ b/src/core/alert-sounds.ts
@@ -9,8 +9,13 @@
// • 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.
+// The file is written under ONE fixed, format-independent name per kind, `<userData>/sounds/
+// <kind>.sound`. The user's name is only echoed back for display; it never becomes part of a path.
+// Format-independent on purpose: with a name per format (`done.mp3`, `done.wav`) a new pick had to
+// delete the other formats afterwards, and two Server Edition tabs saving different formats at
+// once could each delete the OTHER's freshly published file — both reporting success, no sound
+// left. One target means a save is a single atomic rename and concurrent saves/clears simply
+// resolve last-writer-wins. The format needs no record: the renderer's `decodeAudioData` sniffs it.
//
// 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
@@ -33,6 +38,10 @@ import {
/** `<userData>/sounds` — exported so tests (and messages) can name it. */
export const alertSoundsDir = (userDataDir: string): string => join(userDataDir, 'sounds')
+/** The one stored file for `kind`, whatever its format. Only ever called with a validated kind. */
+export const alertSoundFile = (userDataDir: string, kind: AlertSoundKind): string =>
+ join(alertSoundsDir(userDataDir), `${kind}.sound`)
+
const startsWith = (buf: Buffer, sig: string, at = 0): boolean =>
buf.length >= at + sig.length && buf.toString('latin1', at, at + sig.length) === sig
@@ -64,14 +73,6 @@ export function sniffAlertSound(buf: Buffer, ext: AlertSoundExtension): boolean
}
}
-/** 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,
@@ -96,16 +97,14 @@ export async function saveAlertSound(
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))
+ const target = alertSoundFile(userDataDir, kind)
+ const tmp = tempNameFor(target)
try {
- await fs.mkdir(dir, { recursive: true })
+ await fs.mkdir(alertSoundsDir(userDataDir), { 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)
+ await renameAtomic(tmp, target)
return { ok: true, name: displayName }
} catch {
await fs.rm(tmp, { force: true }).catch(() => {})
@@ -116,18 +115,14 @@ export async function saveAlertSound(
/** 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 */
- }
+ const file = alertSoundFile(userDataDir, kind)
+ 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 {
+ return null
}
- return null
}
/** Delete the custom sound for `kind` (Reset to default). True unless the kind is unknown or the
@@ -135,7 +130,7 @@ export async function readAlertSound(userDataDir: string, kind: AlertSoundKind):
export async function clearAlertSound(userDataDir: string, kind: AlertSoundKind): Promise<boolean> {
if (!isAlertSoundKind(kind)) return false
try {
- await removeVariants(alertSoundsDir(userDataDir), kind)
+ await fs.rm(alertSoundFile(userDataDir, kind), { force: true })
return true
} catch {
return false
diff --git a/src/server/handlers/fs-handlers.test.ts b/src/server/handlers/fs-handlers.test.ts
index 4098a1458..3bcc37a9a 100644
--- a/src/server/handlers/fs-handlers.test.ts
+++ b/src/server/handlers/fs-handlers.test.ts
@@ -103,7 +103,7 @@ describe('server fs handlers', () => {
ok: true,
name: 'ding.wav'
})
- expect(fs.readdirSync(path.join(dir, 'sounds'))).toEqual(['done.wav'])
+ expect(fs.readdirSync(path.join(dir, 'sounds'))).toEqual(['done.sound'])
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()