feat: add notification sounds (#44)
Security Scan and Upload / Security & DefectDojo Upload (push) Successful in 54s
CI / Lint & Test (push) Successful in 14m2s
CI / Build Linux (push) Successful in 16m38s
CI / Build Windows (cross-compile) (push) Successful in 26m27s

### Explanation

_No response_

### Issue

_No response_

### Attestations

- [ ] I have read and agree to the [Code of Conduct](https://docs.nhcarrigan.com/community/coc/)
- [ ] I have read and agree to the [Community Guidelines](https://docs.nhcarrigan.com/community/guide/).
- [ ] My contribution complies with the [Contributor Covenant](https://docs.nhcarrigan.com/dev/covenant/).

### Dependencies

- [ ] I have pinned the dependencies to a specific patch version.

### Style

- [ ] I have run the linter and resolved any errors.
- [ ] My pull request uses an appropriate title, matching the conventional commit standards.
- [ ] My scope of feat/fix/chore/etc. correctly matches the nature of changes in my pull request.

### Tests

- [ ] My contribution adds new code, and I have added tests to cover it.
- [ ] My contribution modifies existing code, and I have updated the tests to reflect these changes.
- [ ] All new and existing tests pass locally with my changes.
- [ ] Code coverage remains at or above the configured threshold.

### Documentation

_No response_

### Versioning

_No response_

Reviewed-on: #44
Co-authored-by: Naomi Carrigan <commits@nhcarrigan.com>
Co-committed-by: Naomi Carrigan <commits@nhcarrigan.com>
This commit was merged in pull request #44.
This commit is contained in:
2026-01-19 16:18:25 -08:00
committed by Naomi Carrigan
parent 0065bb4afc
commit a8f98406e1
32 changed files with 1512 additions and 29 deletions
+4
View File
@@ -0,0 +1,4 @@
export * from "./types";
export { soundPlayer } from "./soundPlayer";
export { notificationManager } from "./notificationManager";
export { initializeNotificationRules } from "./rules";
@@ -0,0 +1,121 @@
import { soundPlayer } from "./soundPlayer";
import { NotificationType, NOTIFICATION_SOUNDS } from "./types";
import { invoke } from "@tauri-apps/api/core";
import { sendTerminalNotification } from "./terminalNotifier";
class NotificationManager {
async notify(type: NotificationType, message?: string): Promise<void> {
// Always play sound (if enabled)
await soundPlayer.play(type);
const sound = NOTIFICATION_SOUNDS[type];
const title = sound.phrase;
const body = message || this.getDefaultMessage(type);
// Try multiple notification methods in order
const notificationMethods = [
// Method 1: Try Windows PowerShell (best for system tray notifications)
async () => {
console.log("Trying Windows PowerShell notifications...");
await invoke("send_windows_notification", { title, body });
},
// Method 2: Try native Windows toast (for Windows builds)
async () => {
console.log("Trying native Windows toast...");
await invoke("send_windows_toast", { title, body });
},
// Method 3: Try WSL-specific notification (Windows toast via PowerShell - for WSL)
async () => {
console.log("Trying WSL notification...");
await invoke("send_wsl_notification", { title, body });
},
// Method 4: Try native Tauri notifications
async () => {
console.log("Trying Tauri native notifications...");
const { sendNotification, isPermissionGranted, requestPermission } =
await import("@tauri-apps/plugin-notification");
let hasPermission = await isPermissionGranted();
if (!hasPermission) {
const permission = await requestPermission();
hasPermission = permission === "granted";
}
if (hasPermission) {
await sendNotification({ title, body });
} else {
throw new Error("Notification permission denied");
}
},
// Method 5: Try notify-send (for native Linux)
async () => {
console.log("Trying notify-send...");
await invoke("send_notify_send", { title, body });
},
// Skip VBScript and simple message as they create popup dialogs
// Only use them in the debugger for testing
];
// Try each method until one succeeds
for (const method of notificationMethods) {
try {
await method();
console.log("Notification sent successfully");
return; // Success, stop trying other methods
} catch (error) {
console.warn("Notification method failed:", error);
// Continue to next method
}
}
console.error("All notification methods failed, using terminal notification");
// Final fallback: Show in terminal
sendTerminalNotification(type, body);
}
private getDefaultMessage(type: NotificationType): string {
switch (type) {
case NotificationType.SUCCESS:
return "Task completed successfully!";
case NotificationType.ERROR:
return "Something went wrong...";
case NotificationType.PERMISSION:
return "Permission needed to continue";
case NotificationType.CONNECTION:
return "Successfully connected to Claude Code";
case NotificationType.TASK_START:
return "Starting task...";
default:
return "Notification";
}
}
// Helper methods for common notifications
async notifySuccess(message?: string): Promise<void> {
await this.notify(NotificationType.SUCCESS, message);
}
async notifyError(message?: string): Promise<void> {
await this.notify(NotificationType.ERROR, message);
}
async notifyPermission(message?: string): Promise<void> {
await this.notify(NotificationType.PERMISSION, message);
}
async notifyConnection(message?: string): Promise<void> {
await this.notify(NotificationType.CONNECTION, message);
}
async notifyTaskStart(message?: string): Promise<void> {
await this.notify(NotificationType.TASK_START, message);
}
}
// Export singleton instance
export const notificationManager = new NotificationManager();
+103
View File
@@ -0,0 +1,103 @@
import { characterState } from "$lib/stores/character";
import { notificationManager } from "./notificationManager";
import type { CharacterState } from "$lib/types/states";
import type { ConnectionStatus } from "$lib/types/messages";
// Track previous states to detect transitions
let previousCharacterState: CharacterState | null = null;
let previousConnectionStatus: ConnectionStatus | null = null;
let taskStartTime: number | null = null;
let hasNotifiedTaskStart = false;
export function handleCharacterStateChange(newState: CharacterState): void {
// Detect state transitions
if (previousCharacterState === newState) return;
// Task completion: any state -> success
if (newState === "success" && previousCharacterState !== null) {
const taskDuration = taskStartTime ? Date.now() - taskStartTime : 0;
// Only notify for tasks that took more than 2 seconds
if (taskDuration > 2000) {
notificationManager.notifySuccess();
}
taskStartTime = null;
}
// Error occurred
if (newState === "error" && previousCharacterState !== "error") {
notificationManager.notifyError();
}
// Permission needed
if (newState === "permission") {
notificationManager.notifyPermission();
}
// Starting long tasks - only notify once per response
if (
(newState === "coding" || newState === "searching") &&
previousCharacterState !== "coding" &&
previousCharacterState !== "searching" &&
!hasNotifiedTaskStart
) {
taskStartTime = Date.now();
hasNotifiedTaskStart = true;
notificationManager.notifyTaskStart();
}
previousCharacterState = newState;
}
export function handleConnectionStatusChange(newStatus: ConnectionStatus): void {
// Only notify on successful connection after being disconnected
if (
newStatus === "connected" &&
previousConnectionStatus &&
previousConnectionStatus !== "connected"
) {
notificationManager.notifyConnection();
}
previousConnectionStatus = newStatus;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function handleToolExecution(_toolName: string): void {
// For now, we don't notify on every tool execution
// But we could add specific rules here if needed
}
// Reset notification state for a new response
export function handleNewUserMessage(): void {
hasNotifiedTaskStart = false;
}
// Store unsubscribe functions
let unsubscribeCharacterState: (() => void) | null = null;
// Initialize listeners
export function initializeNotificationRules(): void {
// Clean up any existing subscriptions first
cleanupNotificationRules();
// Subscribe to character state changes
unsubscribeCharacterState = characterState.subscribe((state) => {
handleCharacterStateChange(state);
});
// We'll connect to connection status in the next step
}
// Cleanup function to prevent duplicate listeners
export function cleanupNotificationRules(): void {
if (unsubscribeCharacterState) {
unsubscribeCharacterState();
unsubscribeCharacterState = null;
}
// Reset state tracking
previousCharacterState = null;
previousConnectionStatus = null;
taskStartTime = null;
hasNotifiedTaskStart = false;
}
+61
View File
@@ -0,0 +1,61 @@
import { NOTIFICATION_SOUNDS, type NotificationType } from "./types";
class SoundPlayer {
private audioCache: Map<NotificationType, HTMLAudioElement> = new Map();
private enabled: boolean = true;
private globalVolume: number = 1.0;
constructor() {
// Preload all essential sounds
this.preloadSounds();
}
private preloadSounds(): void {
Object.entries(NOTIFICATION_SOUNDS).forEach(([type, sound]) => {
const audio = new Audio(`/sounds/${sound.filename}`);
audio.preload = "auto";
audio.volume = (sound.volume || 0.7) * this.globalVolume;
this.audioCache.set(type as NotificationType, audio);
});
}
async play(type: NotificationType): Promise<void> {
if (!this.enabled) return;
try {
const audio = this.audioCache.get(type);
if (!audio) {
console.warn(`No audio found for notification type: ${type}`);
return;
}
// Clone the audio to allow overlapping sounds
const audioClone = audio.cloneNode() as HTMLAudioElement;
audioClone.volume = audio.volume;
await audioClone.play();
} catch (error) {
console.error("Failed to play notification sound:", error);
}
}
setEnabled(enabled: boolean): void {
this.enabled = enabled;
}
setGlobalVolume(volume: number): void {
this.globalVolume = Math.max(0, Math.min(1, volume));
// Update all cached audio volumes
this.audioCache.forEach((audio, type) => {
const sound = NOTIFICATION_SOUNDS[type];
audio.volume = (sound.volume || 0.7) * this.globalVolume;
});
}
isEnabled(): boolean {
return this.enabled;
}
}
// Export singleton instance
export const soundPlayer = new SoundPlayer();
+50
View File
@@ -0,0 +1,50 @@
import { claudeStore } from "$lib/stores/claude";
import { NOTIFICATION_SOUNDS, type NotificationType } from "./types";
export function sendTerminalNotification(type: NotificationType, message?: string): void {
const sound = NOTIFICATION_SOUNDS[type];
const title = sound.phrase;
// Create a formatted notification message
const separator = "═".repeat(50);
const timestamp = new Date().toLocaleTimeString();
let emoji = "";
let color = "";
switch (type) {
case "success":
emoji = "✨";
color = "\x1b[32m"; // Green
break;
case "error":
emoji = "❌";
color = "\x1b[31m"; // Red
break;
case "permission":
emoji = "🔐";
color = "\x1b[33m"; // Yellow
break;
case "connection":
emoji = "🔗";
color = "\x1b[36m"; // Cyan
break;
case "task_start":
emoji = "🚀";
color = "\x1b[34m"; // Blue
break;
}
const reset = "\x1b[0m";
// Format the notification
const notification = `
${color}${separator}${reset}
${emoji} ${color}NOTIFICATION${reset} - ${timestamp}
${color}${title}${reset}
${message || ""}
${color}${separator}${reset}`;
// Add to terminal as a special system message
claudeStore.addLine("system", notification);
}
@@ -0,0 +1,42 @@
import { notificationManager } from "./notificationManager";
// Test function to trigger each notification type
export async function testAllNotifications() {
console.log("Testing all notification types...");
// Test success notification
setTimeout(async () => {
console.log("Testing SUCCESS notification");
await notificationManager.notifySuccess("Test task completed!");
}, 1000);
// Test error notification
setTimeout(async () => {
console.log("Testing ERROR notification");
await notificationManager.notifyError("Test error occurred!");
}, 3000);
// Test permission notification
setTimeout(async () => {
console.log("Testing PERMISSION notification");
await notificationManager.notifyPermission("Test permission request!");
}, 5000);
// Test connection notification
setTimeout(async () => {
console.log("Testing CONNECTION notification");
await notificationManager.notifyConnection("Test connection established!");
}, 7000);
// Test task start notification
setTimeout(async () => {
console.log("Testing TASK_START notification");
await notificationManager.notifyTaskStart("Test task starting!");
}, 9000);
}
// Make it available on window for easy testing
if (typeof window !== "undefined") {
(window as unknown as { testNotifications: typeof testAllNotifications }).testNotifications =
testAllNotifications;
}
+48
View File
@@ -0,0 +1,48 @@
export enum NotificationType {
SUCCESS = "success",
ERROR = "error",
PERMISSION = "permission",
CONNECTION = "connection",
TASK_START = "task_start",
}
export interface NotificationSound {
type: NotificationType;
filename: string;
phrase: string;
volume?: number;
}
// Essential notification sounds mapping
export const NOTIFICATION_SOUNDS: Record<NotificationType, NotificationSound> = {
[NotificationType.SUCCESS]: {
type: NotificationType.SUCCESS,
filename: "im-done.mp3",
phrase: "I'm done!",
volume: 0.7,
},
[NotificationType.ERROR]: {
type: NotificationType.ERROR,
filename: "oh-no.mp3",
phrase: "Oh no...",
volume: 0.8,
},
[NotificationType.PERMISSION]: {
type: NotificationType.PERMISSION,
filename: "access-please.mp3",
phrase: "Access please!",
volume: 0.9,
},
[NotificationType.CONNECTION]: {
type: NotificationType.CONNECTION,
filename: "connected.mp3",
phrase: "Connected!",
volume: 0.7,
},
[NotificationType.TASK_START]: {
type: NotificationType.TASK_START,
filename: "working-on-it.mp3",
phrase: "Working on it!",
volume: 0.6,
},
};
@@ -0,0 +1,16 @@
import { invoke } from "@tauri-apps/api/core";
import { platform } from "@tauri-apps/plugin-os";
export async function sendWSLNotification(title: string, body: string): Promise<void> {
const currentPlatform = await platform();
// Check if we're on Windows (WSL shows as 'windows')
if (currentPlatform === "windows") {
try {
// Use PowerShell to send Windows native notifications
await invoke("send_windows_notification", { title, body });
} catch (error) {
console.error("Failed to send Windows notification:", error);
}
}
}