SLOPSHOPPER

chime

Plays a sound when Claude finishes, needs your input, or hits an error. Ten original sounds, your own files, volume, quiet hours and snooze.

paneguardcommandtoaststatusprocess
v0.1.0MITupdated 2026-10-10oguz-hd/claude-code-chime/plugins/chime
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · chime
│ ┃ Chime ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ Chime │ chime │ │ ┃ Sounds for when Claude finishes or needs ⏺ Read(src/auth.ts) │ Chime could not play a sound: sound file │ │ ┃ you. ⎿ Read 6 lines │ not found: /plugins/chime/sounds/tada.wav │ │ ┃ ⏺ Update(src/auth.ts) ╰────────────────────────────────────────────╯ │ ┃ 1: Done Ta-da ⎿ Added 2 lines, removed 1 line │ ┃ 2: Waiting Doorbell ⏺ Bash(bun test) │ ┃ 3: Error Sad trombone ⎿ 3 pass, 1 fail │ ┃ 4: Idle off │ ┃ 5: Volume 60 ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ 6: Chime on │ ┃ 7: Snooze off ✻ Worked for 42s · done 4:20 PM │ ┃ 8: Test play every sound │ ┃ › /chime │ ┃ ↑↓ move · Enter open · 1-8 jump · Esc close │ ┃ · /chime help for more │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Chime
Chime Sounds for when Claude finishes or needs you. 1: Done Ta-da 2: Waiting Doorbell 3: Error Sad trombone 4: Idle off 5: Volume 60 6: Chime on 7: Snooze off 8: Test play every sound ↑↓ move · Enter open · 1-8 jump · Esc close · /chime help for more
README

Chime for Claude Code

Chime plays a sound when Claude Code finishes a turn, stops to wait for you, or hits an error. Start a long task, switch to another window, and come back when you hear it.

  • 32 original sounds in six categories (Victory, Retro, Bells, Cartoon, Tech, Calm), synthesized from scratch and free to use (CC0). Run /chime list to see them all.
  • Your own sound files for any event.
  • A picker pane to try each sound and keep it, plus a /chime command for everything else.
  • Volume, snooze, quiet hours, and a minimum turn length so quick replies stay silent.
  • Windows, macOS and Linux, with nothing to install beyond Claude Code.

Install

Chime is a Claude Code mod: a plugin built on function hooks. In Claude Code, run:

/plugin marketplace add oguz-hd/claude-code-chime
/plugin install chime@claude-code-chime

Restart Claude Code. Type /chime test to hear the current sounds.

Mods use Claude Code's function hooks, which are in early access and may change between releases. If /chime is not listed after a restart, update Claude Code (claude update) and check /plugin for an error next to Chime.

When it plays

EventDefault soundPlays when
DoneTa-daClaude finishes and hands the turn back to you
WaitingDoorbellClaude needs a permission, asks you a question (AskUserQuestion), or wants a plan approved
ErrorSad tromboneThe turn ends on an API error, such as a rate limit or an overloaded server
IdleoffThe prompt has sat unanswered for a while (Claude Code's idle reminder)

Chime stays silent:

  • after a turn that a Stop hook sent back to work (it waits for the real end of the turn);
  • for subagents (only the main conversation counts);
  • in non-interactive runs (claude -p, the SDK);
  • in sessions reached over SSH, where the sound would play on the remote machine (turn it on with /chime ssh on);
  • while snoozed, during quiet hours, or when turned off;
  • when two events arrive within 1.5 seconds of each other, which plays one sound instead of two.

Changing sounds

Type /chime to open the picker. It works from the keyboard like Claude Code's own menus:

KeyDoes
↑ ↓move between rows
Enteropen a row, or keep the highlighted choice
1–9, 0jump straight to a numbered row
bback to the main screen
Escclose the picker

Each event opens a list of categories; pick one to see its sounds. In a sound list, resting on a sound plays it, so you can browse by ear and press Enter on the one you like. The volume list does the same at each level.

Chime
Sounds for when Claude finishes or needs you.

1: Done      Ta-da
2: Waiting   Doorbell
3: Error     Sad trombone
4: Idle      off
5: Volume    60
6: Chime     on
7: Snooze    off
8: Test      play every sound

↑↓ move · Enter open · 1-8 jump · Esc close · /chime help for more

Or use the command directly:

/chime done coin                  bundled sound
/chime waiting ~/sounds/ping.wav  your own file
/chime error off                  silence one event
/chime volume 40                  0-100
/chime snooze 45m                 also 2h, 1h30m, off
/chime quiet 22:00-08:00          no sounds at night (local time); off to clear
/chime min 20                     "done" only after turns of 20 s or more
/chime list [category]            bundled sounds by category
/chime test                       play every event's sound
/chime status                     show the settings
/chime help                       everything else

Settings are kept per user across sessions and projects.

Your own sounds

Give an absolute path or one starting with ~/.

  • Windows plays .wav files only (8-, 16-, 24- or 32-bit PCM, or 32-bit float).
  • macOS plays anything afplay does: .wav, .mp3, .m4a, .aiff and more.
  • Linux plays what your player supports; .wav works everywhere.

Short sounds (under two seconds) work best.

How it plays sound

PlatformPlayerVolume
WindowsPowerShell and System.Media.SoundPlayer, part of every WindowsChime scales the samples itself and caches the result in %TEMP%\claude-chime
macOSafplayafplay -v
Linuxthe first that works of pw-play, paplay, ffplay, aplaythe player's own volume flag (aplay has none)
WSLthe Linux players (WSLg provides PulseAudio), else Windows through powershell.exeas above

If no player works, Chime shows the reason once as a notice and keeps quiet.

Troubleshooting

  • No sound and no notice. Check /chime status: Chime may be off, snoozed, in quiet hours or in an SSH session. Then run /chime test.
  • "no working audio player" on Linux. Install PipeWire (pw-play) or PulseAudio utilities (paplay), for example sudo apt install pulseaudio-utils.
  • "Windows plays .wav files only". Convert the file, for example ffmpeg -i ping.mp3 ping.wav.
  • Sounds play twice. You probably still have a Stop or Notification sound hook in ~/.claude/settings.json from an earlier setup. Remove it; Chime covers both.
  • Every quick reply chimes. Use /chime min 15 so only longer turns play the done sound.

Development

plugins/chime/
  .claude-plugin/plugin.json   manifest
  hooks/hooks.json             names the hooks module
  hooks/register.tsx           hooks, /chime command, picker pane, players
  hooks/settings.ts            sound catalog, defaults, parsing
  hooks/wav.ts                 WAV scaling and other pure helpers
  types/index.d.ts             the plugin's state contract
  sounds/*.wav                 the bundled sounds
tools/render_sounds.py         renders sounds/*.wav (numpy)

Load your working copy into one session with claude --plugin-dir plugins/chime, or let Claude Code hot-reload it as a mod.

Check your changes:

claude plugin validate plugins/chime   # what the engine will load and refuse
claude plugin validate .               # the marketplace manifest

To type-check, run /plugin-types plugins/chime/.claude/types in Claude Code once, then npx -p typescript tsc -p plugins/chime.

To change or add a sound, edit tools/render_sounds.py, then pip install numpy && python tools/render_sounds.py. Add the new id to BUNDLED in hooks/settings.ts with one of the CATEGORIES ids.

License

Code: MIT. Sounds: CC0 1.0 (public domain). See LICENSE.

Source 4 files
hooks/register.tsx 765 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, Timer } from 'claude-code'
3
4import type { ChimeEvent, ChimeSettings, ChimeSound } from '../types'
5import {
6  CATEGORIES,
7  DEFAULTS,
8  EVENTS,
9  EVENT_INFO,
10  categoryOf,
11  clampVolume,
12  describeDuration,
13  findCategory,
14  isBundled,
15  isFilePath,
16  isInQuietHours,
17  normalize,
18  parseDuration,
19  parseQuietHours,
20  soundLabel,
21  soundsIn,
22} from './settings'
23import { POWERSHELL, PS_PLAY, PS_WRITE_AND_PLAY, fnv1a, fromBase64, posixPlayers, scaleWav, toBase64 } from './wav'
24
25type Engine = EngineInterface
26type Platform = 'windows' | 'mac' | 'linux' | 'wsl'
27type PlayResult = { isPlayed: true } | { isPlayed: false; reason: string }
28
29const PANE = 'chime'
30const COMMAND = 'chime'
31/** Two announcements closer than this are one: a permission prompt can raise
32 *  both a tool hook and a Notification, and a turn can end with both. */
33const DEBOUNCE_MS = 1500
34
35const settingsAtom = atom({ plugin: 'chime', key: 'settings' } as const, DEFAULTS)
36const snoozeAtom = atom({ plugin: 'chime', key: 'snoozeUntil' } as const, 0)
37/** The picker's screen: `main`, an event's category list (`done`), a category's sounds (`done/retro`), `volume` or `snooze`. */
38const screenAtom = atom({ plugin: 'chime', key: 'screen' } as const, 'main')
39
40const VOLUME_STEPS = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] as const
41/** How long the ring must rest on a sound before it plays, so arrowing past is quiet. */
42const PREVIEW_DELAY_MS = 250
43
44// Module state: a hot reload resets these, which is harmless.
45let isInteractive = true
46let turnStartedAt = 0
47let lastPlayedAt = 0
48const reportedFailures = new Set<string>()
49let previewTimer: Timer | undefined
50let lastPreview = { sound: '', volume: -1, at: 0 }
51
52// ------------------------------------------------------------------ settings
53
54async function saveSettings($: Engine, change: (s: ChimeSettings) => ChimeSettings): Promise<ChimeSettings> {
55  const next = await update($, settingsAtom, s => normalize(change(s)))
56  await $.store.set('settings', next)
57  await refreshStatus($)
58  return next
59}
60
61async function setSnooze($: Engine, until: number): Promise<void> {
62  await update($, snoozeAtom, () => until)
63  await $.store.set('snoozeUntil', until)
64  await refreshStatus($)
65  if (until > 0) {
66    const left = until - (await $.clock.now())
67    if (left > 0) $.clock.after(left + 500, () => void refreshStatus($))
68  }
69}
70
71const clockTime = (ms: number) => new Date(ms).toTimeString().slice(0, 5)
72
73/** The status line says something only when Chime is not simply on. */
74async function refreshStatus($: Engine): Promise<void> {
75  const s = await read($, settingsAtom)
76  const snoozeUntil = await read($, snoozeAtom)
77  const now = await $.clock.now()
78  if (!s.isEnabled) $.ui.status('chime off')
79  else if (snoozeUntil > now) $.ui.status(`chime snoozed until ${clockTime(snoozeUntil)}`)
80  else if (isInQuietHours(s.quietHours, new Date(now))) $.ui.status('chime quiet hours')
81  else $.ui.status(undefined)
82}
83
84// ------------------------------------------------------------------ playing
85
86/** Plays the sound set for `event`, unless something says to stay silent. */
87async function announce($: Engine, event: ChimeEvent): Promise<void> {
88  const s = await read($, settingsAtom)
89  const now = await $.clock.now()
90  if (!isInteractive || !s.isEnabled) return
91  if ((await read($, snoozeAtom)) > now) return
92  if (isInQuietHours(s.quietHours, new Date(now))) return
93  if (now - lastPlayedAt < DEBOUNCE_MS) return
94  if (!s.isPlayingOverSsh && (await isOverSsh($))) return
95  lastPlayedAt = now
96  await playSound($, s.sounds[event], s.volume)
97}
98
99async function playSound($: Engine, sound: string, volume: number): Promise<void> {
100  const path = await resolveSound($, sound)
101  if (!path) return
102  const result = await play($, path, volume)
103  if (!result.isPlayed && !reportedFailures.has(result.reason)) {
104    reportedFailures.add(result.reason)
105    $.ui.toast(`Chime could not play a sound: ${result.reason}`)
106  }
107}
108
109/** Fire and forget: a hook never waits for a sound to finish. */
110const later = (work: Promise<unknown>) => void work.catch(() => undefined)
111
112// ------------------------------------------------------------------ platform and players
113
114let platform: Promise<Platform> | undefined
115
116function detectPlatform($: Engine): Promise<Platform> {
117  platform ??= (async (): Promise<Platform> => {
118    if ((await $.env.get('OS')) === 'Windows_NT') return 'windows'
119    if ((await $.env.get('WSL_DISTRO_NAME')) !== undefined) return 'wsl'
120    if (await $.fs.exists('/usr/bin/afplay')) return 'mac'
121    return 'linux'
122  })()
123  return platform
124}
125
126/** True when the session was reached over SSH, so a sound would play on the remote machine. */
127async function isOverSsh($: Engine): Promise<boolean> {
128  return (
129    (await $.env.get('SSH_CONNECTION')) !== undefined ||
130    (await $.env.get('SSH_TTY')) !== undefined ||
131    (await $.env.get('SSH_CLIENT')) !== undefined
132  )
133}
134
135async function homeDir($: Engine): Promise<string> {
136  return (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE')) ?? ''
137}
138
139async function tempDir($: Engine): Promise<string> {
140  return (await $.env.get('TEMP')) ?? (await $.env.get('TMP')) ?? (await $.env.get('TMPDIR')) ?? '/tmp'
141}
142
143/** The file a sound setting points at, or null for `off`. */
144async function resolveSound($: Engine, sound: ChimeSound): Promise<string | null> {
145  if (sound === 'off') return null
146  if (isBundled(sound)) return `${$.plugin.root}/sounds/${sound}.wav`
147  if (/^~[\\/]/.test(sound)) return `${await homeDir($)}${sound.slice(1)}`
148  return sound
149}
150
151
152/**
153 * Plays `path` at `volume` (0-100) and resolves once the sound has finished.
154 * Never rejects: a failure comes back as `{ isPlayed: false, reason }`.
155 */
156async function play($: Engine, path: string, volume: number): Promise<PlayResult> {
157  const gain = Math.min(1, Math.max(0, volume / 100))
158  if (gain === 0) return { isPlayed: true }
159  try {
160    if (!(await $.fs.exists(path))) return { isPlayed: false, reason: `sound file not found: ${path}` }
161    switch (await detectPlatform($)) {
162      case 'windows':
163        return await playOnWindows($, path, gain)
164      case 'mac':
165        return await runPlayer($, ['afplay', '-v', gain.toFixed(2), path])
166      case 'linux':
167        return await playOnPosix($, path, gain)
168      case 'wsl': {
169        const posix = await playOnPosix($, path, gain)
170        return posix.isPlayed ? posix : await playOnWindowsFromWsl($, path)
171      }
172    }
173  } catch (error) {
174    return { isPlayed: false, reason: error instanceof Error ? error.message : String(error) }
175  }
176}
177
178async function runPlayer($: Engine, argv: string[], stdin?: string): Promise<PlayResult> {
179  const { exitCode, stderr } = await $.process.run(argv, { stdin, timeoutMs: 20_000 })
180  if (exitCode === 0) return { isPlayed: true }
181  const detail = stderr.trim().split(/\r?\n/)[0] ?? ''
182  return { isPlayed: false, reason: `${argv[0]} exited with ${exitCode}${detail ? `: ${detail}` : ''}` }
183}
184
185async function playOnWindows($: Engine, path: string, gain: number): Promise<PlayResult> {
186  if (!/\.wav$/i.test(path)) {
187    return { isPlayed: false, reason: `Windows plays .wav files only; convert ${path} to .wav` }
188  }
189  if (gain >= 0.999) return runPlayer($, [...POWERSHELL, PS_PLAY, path])
190
191  const stat = await $.fs.stat(path)
192  const key = fnv1a(`${path}|${stat.size}|${stat.mtimeMs}|${gain.toFixed(3)}`)
193  const cached = `${await tempDir($)}\\claude-chime\\${key}.wav`
194  if (await $.fs.exists(cached)) return runPlayer($, [...POWERSHELL, PS_PLAY, cached])
195
196  const { base64 } = await $.fs.read(path, { as: 'bytes' })
197  const scaled = scaleWav(fromBase64(base64), gain)
198  if (!scaled) return runPlayer($, [...POWERSHELL, PS_PLAY, path]) // a WAV encoding we cannot scale
199  return runPlayer($, [...POWERSHELL, PS_WRITE_AND_PLAY, cached], toBase64(scaled))
200}
201
202let posixPlayer: number | undefined
203
204async function playOnPosix($: Engine, path: string, gain: number): Promise<PlayResult> {
205  const players = posixPlayers(path, gain)
206  const order = posixPlayer === undefined ? players.map((_, i) => i) : [posixPlayer]
207  const failures: string[] = []
208  for (const i of order) {
209    const argv = players[i]
210    if (!argv) continue
211    try {
212      const result = await runPlayer($, argv)
213      if (result.isPlayed) {
214        posixPlayer = i
215        return result
216      }
217      failures.push(result.reason)
218    } catch {
219      failures.push(`${argv[0]} not found`)
220    }
221  }
222  if (posixPlayer !== undefined) {
223    posixPlayer = undefined // the remembered player broke; search again next time
224    return playOnPosix($, path, gain)
225  }
226  return {
227    isPlayed: false,
228    reason: `no working audio player (tried pw-play, paplay, ffplay, aplay): ${failures.join('; ')}`,
229  }
230}
231
232async function playOnWindowsFromWsl($: Engine, path: string): Promise<PlayResult> {
233  if (!/\.wav$/i.test(path)) return { isPlayed: false, reason: 'no Linux audio player, and Windows plays .wav only' }
234  const { exitCode, stdout } = await $.process.run(['wslpath', '-w', path])
235  if (exitCode !== 0) return { isPlayed: false, reason: 'wslpath could not translate the sound path' }
236  return runPlayer($, [...POWERSHELL, PS_PLAY, stdout.trim()])
237}
238
239// ------------------------------------------------------------------ picker helpers
240
241const pad = (text: string, width: number) => (text.length >= width ? `${text} ` : text.padEnd(width))
242
243const nearestStep = (volume: number) => Math.min(100, Math.max(10, Math.round(volume / 10) * 10))
244
245/** The ring's landing key in an event's category list, for the sound the event has now. */
246const focusKeyForCategory = (sound: string) =>
247  sound === 'off' ? 'sound:off' : `cat:${categoryOf(sound) ?? CATEGORIES[0]?.id ?? 'victory'}`
248
249/** The ring's landing key in a category's sound list. */
250const focusKeyForSound = (sound: string, category: string) =>
251  isBundled(sound) && categoryOf(sound) === category ? `sound:${sound}` : `sound:${soundsIn(category)[0]?.id}`
252
253/** Splits a screen name like `done/retro` into its event and category. */
254function parseScreen(screen: string): { event?: ChimeEvent; category?: string } {
255  const [head = '', category] = screen.split('/')
256  return EVENTS.includes(head as ChimeEvent) ? { event: head as ChimeEvent, category } : {}
257}
258
259/** What the volume screen plays: the done sound, or the first event's that is not silent. */
260function previewSoundFor(s: ChimeSettings): string {
261  const sound = [s.sounds.done, s.sounds.waiting, s.sounds.error, s.sounds.idle].find(x => x !== 'off')
262  return sound ?? 'tada'
263}
264
265function cancelPreview(): void {
266  previewTimer?.cancel()
267  previewTimer = undefined
268}
269
270function schedulePreview($: Engine, key: string): void {
271  cancelPreview()
272  previewTimer = $.clock.after(PREVIEW_DELAY_MS, () => later(runPreview($, key)))
273}
274
275async function runPreview($: Engine, key: string): Promise<void> {
276  const s = await read($, settingsAtom)
277  let sound: string
278  let volume = s.volume
279  if (key.startsWith('sound:')) sound = key.slice('sound:'.length)
280  else if (key.startsWith('vol:')) {
281    sound = previewSoundFor(s)
282    volume = Number(key.slice('vol:'.length))
283  } else return
284  if (sound === 'off') return
285  lastPreview = { sound, volume, at: Date.now() }
286  await playSound($, sound, volume)
287}
288
289/** True when the browse preview just played this, so Enter need not play it again. */
290const wasJustPreviewed = (sound: string, volume: number) =>
291  lastPreview.sound === sound && lastPreview.volume === volume && Date.now() - lastPreview.at < 3000
292
293async function testSounds($: Engine, only?: ChimeEvent): Promise<void> {
294  const s = await read($, settingsAtom)
295  for (const event of only ? [only] : EVENTS) {
296    if (s.sounds[event] === 'off') continue
297    await playSound($, s.sounds[event], s.volume)
298    await $.clock.sleep(400)
299  }
300}
301
302// ------------------------------------------------------------------ hooks
303
304export const register: Register = on => {
305  on('session.start', async ($, e, next) => {
306    isInteractive = e.isInteractive
307    const stored = await $.store.get('settings')
308    await update($, settingsAtom, () => normalize(stored))
309    const snoozeUntil = Number((await $.store.get('snoozeUntil')) ?? 0)
310    await update($, snoozeAtom, () => (Number.isFinite(snoozeUntil) ? snoozeUntil : 0))
311    await $.command.register({
312      name: COMMAND,
313      description: 'Sounds for when Claude finishes or needs you: pick sounds, volume, snooze',
314      argumentHint: '[status|test|volume N|done SOUND|on|off|snooze 1h|help]',
315      immediate: true,
316    })
317    await refreshStatus($)
318    return next(e)
319  })
320
321  // The turn's start, for the minimum-length rule. The earliest start since
322  // the last stop counts, so a subagent's turn starting mid-way changes nothing.
323  on('turn.start', async ($, e, next) => {
324    if (turnStartedAt === 0) turnStartedAt = await $.clock.now()
325    return next(e)
326  })
327
328  // Done: the main agent stopped and no Stop hook sent it back to work.
329  on('classic.Stop', async ($, e, next) => {
330    const result = await next(e)
331    if (result.block !== undefined) return result
332
333    const startedAt = turnStartedAt
334    turnStartedAt = 0
335    const s = await read($, settingsAtom)
336    const seconds = startedAt ? ((await $.clock.now()) - startedAt) / 1000 : Infinity
337    if (seconds >= s.minTurnSeconds) later(announce($, 'done'))
338    return result
339  })
340
341  // Error: the turn ended on an API error instead of a reply.
342  on('classic.StopFailure', async ($, e, next) => {
343    turnStartedAt = 0
344    later(announce($, 'error'))
345    return next(e)
346  })
347
348  // Waiting / idle: Claude Code's own notifications.
349  on('classic.Notification', async ($, e, next) => {
350    const type = e.notification_type
351    if (type === 'idle_prompt') later(announce($, 'idle'))
352    else if (type !== 'auth_success') later(announce($, 'waiting'))
353    return next(e)
354  })
355
356  // Waiting, also for the dialogs that raise no notification of their own.
357  on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
358    later(announce($, 'waiting'))
359    return next(e)
360  })
361  on('tool.call', { tool: 'ExitPlanMode' }, async ($, e, next) => {
362    later(announce($, 'waiting'))
363    return next(e)
364  })
365
366  on('command.run', { command: COMMAND }, async ($, e) => {
367    const text = await runCommand($, e.args)
368    return text ? { text } : {}
369  })
370
371  // Moving the ring onto a sound or a volume previews it, as a theme picker
372  // previews themes: the person browses by ear and presses Enter to keep one.
373  on('ui.focus', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
374    const moved = await next(e)
375    if (moved.deny === undefined && e.origin.kind === 'person' && e.element) {
376      schedulePreview($, e.element)
377    }
378    return moved
379  })
380
381  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
382    const { Box, Button, Text } = $.ui.resolve(e)
383    const s = await read($, settingsAtom)
384    const screen = await read($, screenAtom)
385    const snoozeUntil = await read($, snoozeAtom)
386    const now = await $.clock.now()
387    const isSnoozed = snoozeUntil > now
388
389    /** Switch screens and put the ring on `key` in the new one. */
390    const go = (to: string, key: string) => async () => {
391      cancelPreview()
392      await update($, screenAtom, () => to)
393      // Best effort: the ring cannot move while the pane does not hold the keys.
394      await $.ui.focus({ requestId: PANE, key }).catch(() => undefined)
395    }
396    const footer = (keys: string) => (
397      <Box marginTop={1}>
398        <Text dimColor>{keys}</Text>
399      </Box>
400    )
401
402    const { event, category: categoryId } = parseScreen(screen)
403
404    // ---- the sounds of one category, for one event
405    if (event && categoryId) {
406      const category = CATEGORIES.find(c => c.id === categoryId)
407      const current = s.sounds[event]
408      const keep = (sound: string) => async () => {
409        cancelPreview()
410        await saveSettings($, x => ({ ...x, sounds: { ...x.sounds, [event]: sound } }))
411        if (!wasJustPreviewed(sound, s.volume)) later(playSound($, sound, s.volume))
412        await go('main', `event:${event}`)()
413      }
414      return (
415        <Box flexDirection="column">
416          <Text bold>
417            {EVENT_INFO[event].label} sound · {category?.label ?? categoryId}
418          </Text>
419          <Text dimColor>Plays when {EVENT_INFO[event].when}.</Text>
420          <Box flexDirection="column" marginTop={1}>
421            {soundsIn(categoryId).map((sound, i) => (
422              <Button
423                key={`sound:${sound.id}`}
424                plain
425                hotkey={String((i + 1) % 10)}
426                autoFocus={current === sound.id ? true : undefined}
427                label={`${pad(sound.label + (current === sound.id ? ' ✓' : ''), 16)}${sound.note}`}
428                onPress={keep(sound.id)}
429              />
430            ))}
431          </Box>
432          <Box marginTop={1} flexDirection="column">
433            <Button key="back" plain hotkey="b" label="Back to categories" onPress={go(event, `cat:${categoryId}`)} />
434          </Box>
435          {footer('↑↓ listen · Enter keep · b back · Esc close')}
436        </Box>
437      )
438    }
439
440    // ---- an event's categories
441    if (event) {
442      const current = s.sounds[event]
443      const keepOff = async () => {
444        cancelPreview()
445        await saveSettings($, x => ({ ...x, sounds: { ...x.sounds, [event]: 'off' } }))
446        await go('main', `event:${event}`)()
447      }
448      return (
449        <Box flexDirection="column">
450          <Text bold>{EVENT_INFO[event].label} sound</Text>
451          <Text dimColor>Plays when {EVENT_INFO[event].when}.</Text>
452          <Box flexDirection="column" marginTop={1}>
453            {CATEGORIES.map((c, i) => (
454              <Button
455                key={`cat:${c.id}`}
456                plain
457                hotkey={String(i + 1)}
458                autoFocus={categoryOf(current) === c.id ? true : undefined}
459                label={`${pad(c.label + (categoryOf(current) === c.id ? ' ✓' : ''), 11)}${pad(`${soundsIn(c.id).length} sounds`, 11)}${c.note}`}
460                onPress={go(`${event}/${c.id}`, focusKeyForSound(current, c.id))}
461              />
462            ))}
463            <Button
464              key="sound:off"
465              plain
466              hotkey="s"
467              label={`${pad('Silent' + (current === 'off' ? ' ✓' : ''), 22)}no sound for this event`}
468              onPress={keepOff}
469            />
470          </Box>
471          <Box marginTop={1}>
472            <Text>{isFilePath(current) ? `Using your file: ${current}` : `Now: ${soundLabel(current)}`}</Text>
473          </Box>
474          <Box marginTop={1} flexDirection="column">
475            <Button key="back" plain hotkey="b" label="Back" onPress={go('main', `event:${event}`)} />
476          </Box>
477          {footer(`↑↓ move · Enter open · b back · Esc close · own file: /chime ${event} ~/sound.wav`)}
478        </Box>
479      )
480    }
481
482    // ---- volume
483    if (screen === 'volume') {
484      const keep = (volume: number) => async () => {
485        cancelPreview()
486        const saved = await saveSettings($, x => ({ ...x, volume }))
487        const sample = previewSoundFor(saved)
488        if (!wasJustPreviewed(sample, volume)) later(playSound($, sample, volume))
489        await go('main', 'open:volume')()
490      }
491      return (
492        <Box flexDirection="column">
493          <Text bold>Volume</Text>
494          <Text dimColor>Move to hear each level; your done sound plays at it.</Text>
495          <Box flexDirection="column" marginTop={1}>
496            {VOLUME_STEPS.map((v, i) => (
497              <Button
498                key={`vol:${v}`}
499                plain
500                hotkey={String((i + 1) % 10)}
501                autoFocus={nearestStep(s.volume) === v ? true : undefined}
502                label={`${pad(String(v), 5)}${'█'.repeat(v / 10)}${'░'.repeat(10 - v / 10)}${s.volume === v ? '  ✓' : ''}`}
503                onPress={keep(v)}
504              />
505            ))}
506          </Box>
507          <Box marginTop={1} flexDirection="column">
508            <Button key="back" plain hotkey="b" label="Back" onPress={go('main', 'open:volume')} />
509          </Box>
510          {footer('↑↓ listen · Enter keep · b back · Esc close')}
511        </Box>
512      )
513    }
514
515    // ---- snooze
516    if (screen === 'snooze') {
517      const choose = (until: () => number) => async () => {
518        await setSnooze($, until())
519        await go('main', 'open:snooze')()
520      }
521      const tomorrowAt8 = () => {
522        const d = new Date(now)
523        d.setDate(d.getDate() + 1)
524        d.setHours(8, 0, 0, 0)
525        return d.getTime()
526      }
527      const options: { key: string; label: string; until: () => number }[] = [
528        { key: 'snooze:15', label: 'For 15 minutes', until: () => now + 15 * 60_000 },
529        { key: 'snooze:30', label: 'For 30 minutes', until: () => now + 30 * 60_000 },
530        { key: 'snooze:60', label: 'For 1 hour', until: () => now + 60 * 60_000 },
531        { key: 'snooze:120', label: 'For 2 hours', until: () => now + 120 * 60_000 },
532        { key: 'snooze:tomorrow', label: 'Until tomorrow 08:00', until: tomorrowAt8 },
533      ]
534      return (
535        <Box flexDirection="column">
536          <Text bold>Snooze</Text>
537          <Text dimColor>{isSnoozed ? `Silent until ${clockTime(snoozeUntil)}.` : 'Stay silent for a while.'}</Text>
538          <Box flexDirection="column" marginTop={1}>
539            {options.map((o, i) => (
540              <Button
541                key={o.key}
542                plain
543                hotkey={String(i + 1)}
544                autoFocus={i === 2 ? true : undefined}
545                label={o.label}
546                onPress={choose(o.until)}
547              />
548            ))}
549            {isSnoozed && <Button key="snooze:off" plain hotkey="w" label="Wake up now" onPress={choose(() => 0)} />}
550          </Box>
551          <Box marginTop={1} flexDirection="column">
552            <Button key="back" plain hotkey="b" label="Back" onPress={go('main', 'open:snooze')} />
553          </Box>
554          {footer('↑↓ move · Enter choose · b back · Esc close')}
555        </Box>
556      )
557    }
558
559    // ---- main
560    const notes: string[] = []
561    if (s.quietHours) notes.push(`Quiet hours ${s.quietHours}`)
562    if (s.minTurnSeconds) notes.push(`"Done" after turns of ${s.minTurnSeconds} s or more`)
563    if (!s.isPlayingOverSsh && (await isOverSsh($))) notes.push('SSH session: silent (/chime ssh on)')
564    return (
565      <Box flexDirection="column">
566        <Text bold>Chime</Text>
567        <Text dimColor>Sounds for when Claude finishes or needs you.</Text>
568        <Box flexDirection="column" marginTop={1}>
569          {EVENTS.map((event, i) => (
570            <Button
571              key={`event:${event}`}
572              plain
573              hotkey={String(i + 1)}
574              autoFocus={i === 0 ? true : undefined}
575              label={`${pad(EVENT_INFO[event].label, 10)}${soundLabel(s.sounds[event])}`}
576              onPress={go(event, focusKeyForCategory(s.sounds[event]))}
577            />
578          ))}
579          <Button
580            key="open:volume"
581            plain
582            hotkey="5"
583            label={`${pad('Volume', 10)}${s.volume}`}
584            onPress={go('volume', `vol:${nearestStep(s.volume)}`)}
585          />
586          <Button
587            key="toggle"
588            plain
589            hotkey="6"
590            label={`${pad('Chime', 10)}${s.isEnabled ? 'on' : 'off'}`}
591            onPress={() => saveSettings($, x => ({ ...x, isEnabled: !x.isEnabled }))}
592          />
593          <Button
594            key="open:snooze"
595            plain
596            hotkey="7"
597            label={`${pad('Snooze', 10)}${isSnoozed ? `until ${clockTime(snoozeUntil)}` : 'off'}`}
598            onPress={go('snooze', 'snooze:60')}
599          />
600          <Button
601            key="test"
602            plain
603            hotkey="8"
604            label={`${pad('Test', 10)}play every sound`}
605            onPress={() => later(testSounds($))}
606          />
607        </Box>
608        {notes.length > 0 && (
609          <Box marginTop={1}>
610            <Text dimColor>{notes.join(' · ')}</Text>
611          </Box>
612        )}
613        {footer('↑↓ move · Enter open · 1-8 jump · Esc close · /chime help for more')}
614      </Box>
615    )
616  })
617}
618
619// ------------------------------------------------------------------ /chime
620
621const HELP = `Chime plays a sound when Claude finishes, needs you, or fails.
622
623  /chime                      open the sound picker
624  /chime status               show the settings
625  /chime test [event]         play one event's sound, or all of them
626  /chime list [CATEGORY]      list the bundled sounds by category
627                              (victory, retro, bells, cartoon, tech, calm)
628  /chime play SOUND           preview a sound
629  /chime EVENT SOUND          set a sound: EVENT is done, waiting, error or idle;
630                              SOUND is a bundled name, off, or a file path
631  /chime volume 0-100         set the volume
632  /chime on | off             turn Chime on or off
633  /chime snooze 30m | 2h | off   stay silent for a while
634  /chime quiet 22:00-08:00 | off   no sounds during these hours (local time)
635  /chime min SECONDS          only chime "done" after turns at least this long
636  /chime ssh on | off         also play in sessions reached over SSH
637  /chime reset                back to the defaults`
638
639async function runCommand($: Engine, args: string): Promise<string> {
640  const [verb = '', ...rest] = args.trim().split(/\s+/).filter(Boolean)
641  const value = args.trim().slice(verb.length).trim()
642  const word = verb.toLowerCase()
643
644  if (word === '') {
645    cancelPreview()
646    await update($, screenAtom, () => 'main')
647    await $.ui.open({ id: PANE, title: 'Chime', focus: true, closeOnEscape: true, holdToasts: true, rows: 18 })
648    return ''
649  }
650  if (word === 'help') return HELP
651  if (word === 'status') return statusText($)
652
653  if (word === 'list' || word === 'sounds') {
654    const only = value ? findCategory(value) : undefined
655    if (value && !only) return `Unknown category "${value}". Categories: ${CATEGORIES.map(c => c.id).join(', ')}.`
656    const lines = ['Bundled sounds:']
657    for (const c of only ? [only] : CATEGORIES) {
658      lines.push('', `${c.label} (${c.id}): ${c.note}`)
659      lines.push(...soundsIn(c.id).map(b => `  ${b.id.padEnd(14)} ${b.note}`))
660    }
661    lines.push('', '  off            silence')
662    return lines.join('\n')
663  }
664
665  if (word === 'play') {
666    if (!isBundled(value) && !isFilePath(value)) return `Unknown sound "${value}". Try /chime list.`
667    const s = await read($, settingsAtom)
668    later(playSound($, value, s.volume))
669    return `Playing ${soundLabel(value)} at volume ${s.volume}.`
670  }
671
672  if (word === 'test') {
673    const s = await read($, settingsAtom)
674    const only = EVENTS.includes(value as ChimeEvent) ? (value as ChimeEvent) : undefined
675    const events = only ? [only] : EVENTS
676    later(testSounds($, only))
677    return events.map(ev => `${EVENT_INFO[ev].label}: ${soundLabel(s.sounds[ev])}`).join(', ')
678  }
679
680  if (EVENTS.includes(word as ChimeEvent)) {
681    const event = word as ChimeEvent
682    if (!value) return `${EVENT_INFO[event].label} plays ${soundLabel((await read($, settingsAtom)).sounds[event])}.`
683    const sound = isBundled(value.toLowerCase()) || value.toLowerCase() === 'off' ? value.toLowerCase() : value
684    if (sound !== 'off' && !isBundled(sound)) {
685      if (!isFilePath(sound)) return `Unknown sound "${value}". Use a name from /chime list, off, or an absolute file path.`
686      const path = await resolveSound($, sound)
687      if (!path || !(await $.fs.exists(path))) return `No file at ${sound}.`
688    }
689    const s = await saveSettings($, x => ({ ...x, sounds: { ...x.sounds, [event]: sound } }))
690    later(playSound($, sound, s.volume))
691    return `${EVENT_INFO[event].label} now plays ${soundLabel(sound)}.`
692  }
693
694  if (word === 'volume' || word === 'vol') {
695    const n = Number(value)
696    if (!value || !Number.isFinite(n)) return `Volume is ${(await read($, settingsAtom)).volume}. Set it with /chime volume 0-100.`
697    const s = await saveSettings($, x => ({ ...x, volume: clampVolume(n) }))
698    later(playSound($, s.sounds.done === 'off' ? 'tada' : s.sounds.done, s.volume))
699    return `Volume set to ${s.volume}.`
700  }
701
702  if (word === 'on' || word === 'off') {
703    await saveSettings($, x => ({ ...x, isEnabled: word === 'on' }))
704    return word === 'on' ? 'Chime is on.' : 'Chime is off. Turn it back on with /chime on.'
705  }
706
707  if (word === 'snooze') {
708    if (value === 'off' || value === '0') {
709      await setSnooze($, 0)
710      return 'Snooze cleared.'
711    }
712    const ms = parseDuration(value || '1h')
713    if (!ms) return 'Give a duration such as 30m, 2h or 1h30m.'
714    await setSnooze($, (await $.clock.now()) + ms)
715    return `Snoozed for ${describeDuration(ms)}.`
716  }
717
718  if (word === 'quiet') {
719    if (value === 'off' || value === '') {
720      await saveSettings($, x => ({ ...x, quietHours: '' }))
721      return 'Quiet hours cleared.'
722    }
723    if (!parseQuietHours(value)) return 'Give the hours as HH:MM-HH:MM, for example 22:00-08:00.'
724    await saveSettings($, x => ({ ...x, quietHours: value.replace(/\s+/g, '') }))
725    return `No sounds from ${value.replace(/\s+/g, '').replace('-', ' to ')} (local time).`
726  }
727
728  if (word === 'min') {
729    const n = Number(value)
730    if (!value || !Number.isFinite(n) || n < 0) return 'Give a number of seconds, for example /chime min 20 (0 = every turn).'
731    const s = await saveSettings($, x => ({ ...x, minTurnSeconds: Math.round(n) }))
732    return s.minTurnSeconds ? `"Done" now plays only after turns of ${s.minTurnSeconds} s or more.` : '"Done" plays after every turn.'
733  }
734
735  if (word === 'ssh') {
736    if (value !== 'on' && value !== 'off') return 'Use /chime ssh on or /chime ssh off.'
737    await saveSettings($, x => ({ ...x, isPlayingOverSsh: value === 'on' }))
738    return value === 'on' ? 'Chime also plays in SSH sessions (on the remote machine).' : 'Chime stays silent in SSH sessions.'
739  }
740
741  if (word === 'reset') {
742    await saveSettings($, () => DEFAULTS)
743    await setSnooze($, 0)
744    return 'Chime is back to its defaults.'
745  }
746
747  return `Unknown option "${verb}".\n\n${HELP}`
748}
749
750async function statusText($: Engine): Promise<string> {
751  const s = await read($, settingsAtom)
752  const snoozeUntil = await read($, snoozeAtom)
753  const now = await $.clock.now()
754  const lines = [
755    `Chime is ${s.isEnabled ? 'on' : 'off'}, volume ${s.volume}.`,
756    ...EVENTS.map(ev => `  ${EVENT_INFO[ev].label.padEnd(8)} ${soundLabel(s.sounds[ev])}`),
757  ]
758  if (snoozeUntil > now) lines.push(`Snoozed until ${clockTime(snoozeUntil)}.`)
759  if (s.quietHours) lines.push(`Quiet hours: ${s.quietHours}.`)
760  if (s.minTurnSeconds) lines.push(`"Done" only after turns of ${s.minTurnSeconds} s or more.`)
761  if (await isOverSsh($)) lines.push(s.isPlayingOverSsh ? 'SSH session: playing on the remote machine.' : 'SSH session: silent (/chime ssh on to change).')
762  if (!isInteractive) lines.push('Not an interactive session: silent.')
763  return lines.join('\n')
764}
765
hooks/settings.ts 156 lines
1import type { ChimeEvent, ChimeSettings, ChimeSound } from '../types'
2
3export const EVENTS: readonly ChimeEvent[] = ['done', 'waiting', 'error', 'idle']
4
5export const EVENT_INFO: Record<ChimeEvent, { label: string; when: string }> = {
6  done: { label: 'Done', when: 'Claude finished and handed the turn back to you' },
7  waiting: { label: 'Waiting', when: 'Claude needs a permission, an answer or a plan approval' },
8  error: { label: 'Error', when: 'the turn ended on an API error (rate limit, overload, auth)' },
9  idle: { label: 'Idle', when: 'the prompt has sat unanswered for a while (a reminder)' },
10}
11
12/** The bundled sounds are grouped into these categories, in the order the picker lists them. */
13export const CATEGORIES: readonly { id: string; label: string; note: string }[] = [
14  { id: 'victory', label: 'Victory', note: 'fanfares and "all done" flourishes' },
15  { id: 'retro', label: 'Retro', note: '8-bit game sounds' },
16  { id: 'bells', label: 'Bells', note: 'doorbells, chimes and mallets' },
17  { id: 'cartoon', label: 'Cartoon', note: 'silly and playful' },
18  { id: 'tech', label: 'Tech', note: 'beeps, pings and sci-fi' },
19  { id: 'calm', label: 'Calm', note: 'soft and unobtrusive' },
20]
21
22type Bundled = { id: string; label: string; note: string; category: string }
23
24/** The bundled sounds, grouped by category in the order the picker lists them. */
25export const BUNDLED: readonly Bundled[] = [
26  { id: 'tada', label: 'Ta-da', note: 'a short pickup note, then a bright chord', category: 'victory' },
27  { id: 'fanfare', label: 'Fanfare', note: 'three brass hits, then a chord', category: 'victory' },
28  { id: 'success', label: 'Success', note: 'pleasant rising two-note ding', category: 'victory' },
29
30  { id: 'coin', label: 'Coin', note: '8-bit coin pickup', category: 'retro' },
31  { id: 'level-up', label: 'Level up', note: 'rising 8-bit arpeggio', category: 'retro' },
32  { id: 'power-up', label: 'Power up', note: 'stepped upward sweep', category: 'retro' },
33  { id: 'one-up', label: '1-up', note: 'extra-life jingle', category: 'retro' },
34  { id: 'blip', label: 'Blip', note: 'one tiny menu beep', category: 'retro' },
35  { id: 'laser', label: 'Laser', note: 'zap sliding down', category: 'retro' },
36  { id: 'game-over', label: 'Game over', note: 'descending 8-bit sigh', category: 'retro' },
37
38  { id: 'doorbell', label: 'Doorbell', note: 'ding-dong', category: 'bells' },
39  { id: 'ding', label: 'Ding', note: 'a single bright bell', category: 'bells' },
40  { id: 'glockenspiel', label: 'Glockenspiel', note: 'four rising bell notes', category: 'bells' },
41  { id: 'wind-chimes', label: 'Wind chimes', note: 'scattered high bells', category: 'bells' },
42  { id: 'gong', label: 'Gong', note: 'deep, slow-fading strike', category: 'bells' },
43  { id: 'music-box', label: 'Music box', note: 'tinkling six-note tune', category: 'bells' },
44
45  { id: 'boing', label: 'Boing', note: 'cartoon spring', category: 'cartoon' },
46  { id: 'rubber-duck', label: 'Rubber duck', note: 'two squeaks', category: 'cartoon' },
47  { id: 'slide-whistle', label: 'Slide whistle', note: 'whistle sliding up', category: 'cartoon' },
48  { id: 'sad-trombone', label: 'Sad trombone', note: 'wah wah wah waaah', category: 'cartoon' },
49  { id: 'bubble-pop', label: 'Bubble pop', note: 'three quick bubbles', category: 'cartoon' },
50  { id: 'cuckoo', label: 'Cuckoo', note: 'cuckoo-clock call, twice', category: 'cartoon' },
51  { id: 'whoosh', label: 'Whoosh', note: 'airy swoosh', category: 'cartoon' },
52
53  { id: 'microwave', label: 'Microwave', note: 'beep beep beep', category: 'tech' },
54  { id: 'robot', label: 'Robot', note: 'beep-boop chirps', category: 'tech' },
55  { id: 'sonar', label: 'Sonar', note: 'ping with fading echoes', category: 'tech' },
56  { id: 'scanner', label: 'Scanner', note: 'wobbling radar sweep', category: 'tech' },
57  { id: 'computer', label: 'Computer', note: 'four two-tone beeps', category: 'tech' },
58
59  { id: 'singing-bowl', label: 'Singing bowl', note: 'long, soft ring', category: 'calm' },
60  { id: 'water-drop', label: 'Water drop', note: 'two soft drips', category: 'calm' },
61  { id: 'harp', label: 'Harp', note: 'gentle rising strum', category: 'calm' },
62  { id: 'marimba', label: 'Marimba', note: 'three warm wooden notes', category: 'calm' },
63]
64
65/** The bundled sounds of one category, in listing order. */
66export const soundsIn = (category: string) => BUNDLED.filter(b => b.category === category)
67
68/** The category a sound belongs to, or undefined for `off` and file paths. */
69export const categoryOf = (sound: ChimeSound) => BUNDLED.find(b => b.id === sound)?.category
70
71/** Finds a category by id or label, ignoring case. */
72export const findCategory = (text: string) => {
73  const t = text.trim().toLowerCase()
74  return CATEGORIES.find(c => c.id === t || c.label.toLowerCase() === t)
75}
76
77export const DEFAULTS: ChimeSettings = {
78  isEnabled: true,
79  volume: 60,
80  sounds: { done: 'tada', waiting: 'doorbell', error: 'sad-trombone', idle: 'off' },
81  minTurnSeconds: 0,
82  quietHours: '',
83  isPlayingOverSsh: false,
84}
85
86export const isBundled = (sound: ChimeSound) => BUNDLED.some(b => b.id === sound)
87
88/** True for `/x`, `~/x`, `C:\x`, `C:/x` and `\\server\share`. */
89export const isFilePath = (sound: ChimeSound) =>
90  /^(\/|~[\\/]|[A-Za-z]:[\\/]|\\\\)/.test(sound)
91
92export const soundLabel = (sound: ChimeSound) =>
93  sound === 'off' ? 'off' : (BUNDLED.find(b => b.id === sound)?.label ?? sound)
94
95export const clampVolume = (n: number) => Math.round(Math.min(100, Math.max(0, n)))
96
97/**
98 * Fills in what a stored value lacks and drops what no longer fits, so a
99 * settings file from an older or newer version still loads.
100 */
101export function normalize(raw: unknown): ChimeSettings {
102  const s = (raw && typeof raw === 'object' ? raw : {}) as Partial<ChimeSettings>
103  const sounds = { ...DEFAULTS.sounds }
104  for (const event of EVENTS) {
105    const value = s.sounds?.[event]
106    if (typeof value === 'string' && (value === 'off' || isBundled(value) || isFilePath(value))) {
107      sounds[event] = value
108    }
109  }
110  return {
111    isEnabled: typeof s.isEnabled === 'boolean' ? s.isEnabled : DEFAULTS.isEnabled,
112    volume: typeof s.volume === 'number' && Number.isFinite(s.volume) ? clampVolume(s.volume) : DEFAULTS.volume,
113    sounds,
114    minTurnSeconds:
115      typeof s.minTurnSeconds === 'number' && s.minTurnSeconds >= 0 ? Math.round(s.minTurnSeconds) : 0,
116    quietHours: typeof s.quietHours === 'string' && parseQuietHours(s.quietHours) ? s.quietHours : '',
117    isPlayingOverSsh: s.isPlayingOverSsh === true,
118  }
119}
120
121/** `22:00-07:30` to minutes after midnight, or null when malformed. */
122export function parseQuietHours(text: string): { from: number; to: number } | null {
123  const m = /^\s*(\d{1,2}):(\d{2})\s*-\s*(\d{1,2}):(\d{2})\s*$/.exec(text)
124  if (!m) return null
125  const [h1 = 0, m1 = 0, h2 = 0, m2 = 0] = m.slice(1).map(Number)
126  if (h1 > 23 || h2 > 23 || m1 > 59 || m2 > 59) return null
127  return { from: h1 * 60 + m1, to: h2 * 60 + m2 }
128}
129
130/** Whether `date` (local time) falls inside the range; a range may wrap midnight. */
131export function isInQuietHours(text: string, date: Date): boolean {
132  const range = parseQuietHours(text)
133  if (!range || range.from === range.to) return false
134  const now = date.getHours() * 60 + date.getMinutes()
135  return range.from < range.to
136    ? now >= range.from && now < range.to
137    : now >= range.from || now < range.to
138}
139
140/** `30`, `30m`, `2h`, `1h30m` to milliseconds, or null. A bare number is minutes. */
141export function parseDuration(text: string): number | null {
142  const t = text.trim().toLowerCase()
143  if (/^\d+$/.test(t)) return Number(t) * 60_000
144  const m = /^(?:(\d+)h)?\s*(?:(\d+)m(?:in)?)?$/.exec(t)
145  if (!m || (!m[1] && !m[2])) return null
146  return (Number(m[1] ?? 0) * 60 + Number(m[2] ?? 0)) * 60_000
147}
148
149export function describeDuration(ms: number): string {
150  const minutes = Math.max(1, Math.round(ms / 60_000))
151  if (minutes < 60) return `${minutes} min`
152  const h = Math.floor(minutes / 60)
153  const m = minutes % 60
154  return m ? `${h} h ${m} min` : `${h} h`
155}
156
hooks/wav.ts 105 lines
1// Pure helpers for playing sounds: no engine calls here (`$` stays in register.tsx).
2
3// Windows: System.Media.SoundPlayer ships with every Windows and needs nothing
4// installed, but it plays .wav only and has no volume control. So the volume is
5// applied to the samples, and the scaled copy is cached in %TEMP%.
6
7export const POWERSHELL = ['powershell.exe', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command']
8export const PS_PLAY = '& { (New-Object Media.SoundPlayer $args[0]).PlaySync() }'
9export const PS_WRITE_AND_PLAY =
10  '& { $o = $args[0]; [void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($o)); ' +
11  '[IO.File]::WriteAllBytes($o, [Convert]::FromBase64String([Console]::In.ReadToEnd())); ' +
12  '(New-Object Media.SoundPlayer $o).PlaySync() }'
13
14// Linux (and WSL with WSLg): the first player that is installed and works wins.
15export const posixPlayers = (path: string, gain: number): string[][] => [
16  ['pw-play', `--volume=${gain.toFixed(2)}`, path],
17  ['paplay', `--volume=${Math.round(gain * 65536)}`, path],
18  ['ffplay', '-nodisp', '-autoexit', '-loglevel', 'quiet', '-volume', String(Math.round(gain * 100)), path],
19  ['aplay', '-q', path], // no volume control
20]
21
22// --------------------------------------------------------------------- WAV
23
24/**
25 * Returns a copy of a RIFF/WAVE file with every sample multiplied by `gain`,
26 * or null for an encoding it does not handle (compressed WAV). Handles 8-, 16-,
27 * 24- and 32-bit PCM and 32-bit float, including WAVE_FORMAT_EXTENSIBLE.
28 */
29export function scaleWav(bytes: Uint8Array, gain: number): Uint8Array | null {
30  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
31  const tag = (at: number) => String.fromCharCode(...bytes.subarray(at, at + 4))
32  if (bytes.length < 12 || tag(0) !== 'RIFF' || tag(8) !== 'WAVE') return null
33
34  let format = 0
35  let bits = 0
36  let dataStart = -1
37  let dataEnd = -1
38  for (let at = 12; at + 8 <= bytes.length; ) {
39    const id = tag(at)
40    const size = view.getUint32(at + 4, true)
41    const body = at + 8
42    if (id === 'fmt ') {
43      format = view.getUint16(body, true)
44      bits = view.getUint16(body + 14, true)
45      if (format === 0xfffe && size >= 26) format = view.getUint16(body + 24, true)
46    } else if (id === 'data') {
47      dataStart = body
48      dataEnd = Math.min(bytes.length, body + size)
49    }
50    at = body + size + (size % 2)
51  }
52  if (dataStart < 0 || bits === 0) return null
53
54  const out = bytes.slice()
55  const o = new DataView(out.buffer)
56  const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, Math.round(v)))
57  if (format === 1 && bits === 16) {
58    for (let i = dataStart; i + 1 < dataEnd; i += 2) o.setInt16(i, clamp(o.getInt16(i, true) * gain, -32768, 32767), true)
59  } else if (format === 1 && bits === 8) {
60    for (let i = dataStart; i < dataEnd; i++) o.setUint8(i, clamp((o.getUint8(i) - 128) * gain + 128, 0, 255))
61  } else if (format === 1 && bits === 24) {
62    for (let i = dataStart; i + 2 < dataEnd; i += 3) {
63      let v = o.getUint8(i) | (o.getUint8(i + 1) << 8) | (o.getUint8(i + 2) << 16)
64      if (v & 0x800000) v -= 0x1000000
65      v = clamp(v * gain, -0x800000, 0x7fffff)
66      o.setUint8(i, v & 0xff)
67      o.setUint8(i + 1, (v >> 8) & 0xff)
68      o.setUint8(i + 2, (v >> 16) & 0xff)
69    }
70  } else if (format === 1 && bits === 32) {
71    for (let i = dataStart; i + 3 < dataEnd; i += 4) o.setInt32(i, clamp(o.getInt32(i, true) * gain, -2147483648, 2147483647), true)
72  } else if (format === 3 && bits === 32) {
73    for (let i = dataStart; i + 3 < dataEnd; i += 4) o.setFloat32(i, o.getFloat32(i, true) * gain, true)
74  } else {
75    return null
76  }
77  return out
78}
79
80// --------------------------------------------------------------------- helpers
81
82export function fnv1a(text: string): string {
83  let h = 0x811c9dc5
84  for (let i = 0; i < text.length; i++) {
85    h ^= text.charCodeAt(i)
86    h = Math.imul(h, 0x01000193)
87  }
88  return (h >>> 0).toString(16).padStart(8, '0')
89}
90
91export function fromBase64(base64: string): Uint8Array {
92  const binary = atob(base64)
93  const bytes = new Uint8Array(binary.length)
94  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
95  return bytes
96}
97
98export function toBase64(bytes: Uint8Array): string {
99  let binary = ''
100  for (let i = 0; i < bytes.length; i += 0x8000) {
101    binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
102  }
103  return btoa(binary)
104}
105
types/index.d.ts 35 lines
1/** A moment Chime can announce. */
2export type ChimeEvent = 'done' | 'waiting' | 'error' | 'idle'
3
4/**
5 * What plays for one event: a bundled sound's id (`tada`), `off`, or the
6 * absolute path of an audio file of the user's own.
7 */
8export type ChimeSound = string
9
10export type ChimeSettings = {
11  /** Master switch. */
12  isEnabled: boolean
13  /** 0 to 100. */
14  volume: number
15  sounds: Record<ChimeEvent, ChimeSound>
16  /** The done sound plays only for turns at least this long (0 = always). */
17  minTurnSeconds: number
18  /** `HH:MM-HH:MM` in local time, or empty for none. */
19  quietHours: string
20  /** Whether to play in a session reached over SSH (the sound plays on the remote machine). */
21  isPlayingOverSsh: boolean
22}
23
24declare module 'claude-code' {
25  interface PluginState {
26    chime: {
27      settings: ChimeSettings
28      /** The picker's screen: `main`, an event's sound list, `volume` or `snooze`. */
29      screen: string
30      /** Epoch ms until which Chime stays silent; 0 when not snoozed. */
31      snoozeUntil: number
32    }
33  }
34}
35