feat(webui): add completion notification sound preference
When a turn finishes while the user is watching the page there is no audible cue; the existing browser notifications only cover the background case. Add a `notificationSound` local preference (off by default, next to `browserNotifications`) and play a short bundled chime from the `turn_end` handler only while the page is visible, so background tabs stay silent. - webui/src/lib/notification-sound.ts: visibility- and preference-gated playback of the bundled /notification.wav, one reused Audio element - Overview settings toggle with localized copy in all 10 locales - Tests cover the default-off, visible, hidden, reuse and playback-rejection paths
This commit is contained in:
1 parent
3ecc3d3556
commit
7c2bf8949c
17 files changed
+156
No files matched your search
Binary file not shown.
@@ -384,6 +384,23 @@ export function AppearanceSettings({
|
||||
: tx("settings.values.off", "Off")}
|
||||
/>
|
||||
</SettingsRow>
|
||||
<SettingsRow
|
||||
title={tx("settings.rows.notificationSound", "Completion sound")}
|
||||
description={tx(
|
||||
"settings.help.notificationSound",
|
||||
"Play a short chime when a turn finishes while this page is in the foreground. Off by default.",
|
||||
)}
|
||||
>
|
||||
<ToggleButton
|
||||
checked={localPrefs.notificationSound}
|
||||
onChange={(notificationSound) =>
|
||||
onChangeLocalPrefs((prev) => ({ ...prev, notificationSound }))}
|
||||
ariaLabel={tx("settings.rows.notificationSound", "Completion sound")}
|
||||
label={localPrefs.notificationSound
|
||||
? tx("settings.values.on", "On")
|
||||
: tx("settings.values.off", "Off")}
|
||||
/>
|
||||
</SettingsRow>
|
||||
</SettingsGroup>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -23,6 +23,7 @@ import type {
|
||||
} from "@/lib/thread-event-projection";
|
||||
import { formatQuotedUserMessage } from "@/lib/user-message-quote";
|
||||
import { readLocalPreferences } from "@/lib/local-preferences";
|
||||
import { playTurnCompleteSound } from "@/lib/notification-sound";
|
||||
import type {
|
||||
InboundEvent,
|
||||
OutboundCliAppMention,
|
||||
@@ -812,6 +813,7 @@ export function useNanobotStream(
|
||||
? ev.failure_message || "This turn failed and has ended."
|
||||
: t("recovery.completed", { defaultValue: "Task completed" }),
|
||||
);
|
||||
playTurnCompleteSound();
|
||||
onTurnEnd?.();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -516,6 +516,7 @@
|
||||
"codeWrap": "Code wrapping",
|
||||
"brandLogos": "Brand logos",
|
||||
"browserNotifications": "Task notifications",
|
||||
"notificationSound": "Completion sound",
|
||||
"maxResults": "Max results",
|
||||
"timeout": "Timeout",
|
||||
"jinaReader": "Jina reader",
|
||||
@@ -561,6 +562,7 @@
|
||||
"codeWrap": "Keep long code lines readable on smaller screens.",
|
||||
"brandLogos": "Show third-party provider and CLI logos in Settings.",
|
||||
"browserNotifications": "Notify only when this page is in the background. Off by default.",
|
||||
"notificationSound": "Play a short chime when a turn finishes while this page is in the foreground. Off by default.",
|
||||
"maxResults": "Maximum number of results returned by each web search.",
|
||||
"timeout": "How long to wait for a search request to finish.",
|
||||
"jinaReader": "Use Jina Reader to read web pages when available.",
|
||||
|
||||
@@ -288,6 +288,7 @@
|
||||
"currentModel": "Configuración actual",
|
||||
"brandLogos": "Logos de marca",
|
||||
"browserNotifications": "Notificaciones de tareas",
|
||||
"notificationSound": "Sonido de finalización",
|
||||
"cliAppsCatalog": "Catálogo",
|
||||
"cliAppsFilter": "Filtro",
|
||||
"engine": "Motor",
|
||||
@@ -331,6 +332,7 @@
|
||||
"selectedModelValue": "Definido por el modelo seleccionado.",
|
||||
"brandLogos": "Muestra logos de proveedores de terceros y CLI en Ajustes.",
|
||||
"browserNotifications": "Notifica solo cuando esta página está en segundo plano. Desactivado de forma predeterminada.",
|
||||
"notificationSound": "Reproduce un breve sonido cuando un turno termina mientras esta página está en primer plano. Desactivado por defecto.",
|
||||
"cliAppsCatalog": "Instala las herramientas de línea de comandos que nanobot puede usar en este equipo. Las aplicaciones de escritorio no se modifican.",
|
||||
"cliAppsFilter": "Busca por aplicación, categoría o capacidad.",
|
||||
"logs": "Abre la carpeta de registros de la aplicación de escritorio.",
|
||||
|
||||
@@ -288,6 +288,7 @@
|
||||
"currentModel": "Configuration actuelle",
|
||||
"brandLogos": "Logos de marque",
|
||||
"browserNotifications": "Notifications de tâches",
|
||||
"notificationSound": "Son de fin de tâche",
|
||||
"cliAppsCatalog": "Catalogue",
|
||||
"cliAppsFilter": "Filtre",
|
||||
"engine": "Moteur",
|
||||
@@ -331,6 +332,7 @@
|
||||
"selectedModelValue": "Défini par le modèle sélectionné.",
|
||||
"brandLogos": "Affiche les logos de fournisseurs tiers et CLI dans les Réglages.",
|
||||
"browserNotifications": "Notifier uniquement lorsque cette page est en arrière-plan. Désactivé par défaut.",
|
||||
"notificationSound": "Joue un bref carillon lorsqu'un tour se termine pendant que cette page est au premier plan. Désactivé par défaut.",
|
||||
"cliAppsCatalog": "Installe les outils en ligne de commande que nanobot peut utiliser sur cette machine. Les applications de bureau ne sont pas modifiées.",
|
||||
"cliAppsFilter": "Recherchez par application, catégorie ou capacité.",
|
||||
"logs": "Ouvre le dossier des journaux de l’application de bureau.",
|
||||
|
||||
@@ -288,6 +288,7 @@
|
||||
"currentModel": "Konfigurasi saat ini",
|
||||
"brandLogos": "Logo merek",
|
||||
"browserNotifications": "Notifikasi tugas",
|
||||
"notificationSound": "Suara penyelesaian",
|
||||
"cliAppsCatalog": "Katalog",
|
||||
"cliAppsFilter": "Saring",
|
||||
"engine": "Mesin",
|
||||
@@ -331,6 +332,7 @@
|
||||
"selectedModelValue": "Ditentukan oleh model yang dipilih.",
|
||||
"brandLogos": "Tampilkan logo penyedia pihak ketiga dan CLI di Pengaturan.",
|
||||
"browserNotifications": "Beri tahu hanya saat halaman ini di latar belakang. Nonaktif secara bawaan.",
|
||||
"notificationSound": "Putar dentang singkat saat giliran selesai ketika halaman ini berada di latar depan. Nonaktif secara default.",
|
||||
"cliAppsCatalog": "Memasang alat baris perintah yang dapat digunakan nanobot di komputer ini. Aplikasi desktop tidak diubah.",
|
||||
"cliAppsFilter": "Cari berdasarkan aplikasi, kategori, atau kemampuan.",
|
||||
"logs": "Membuka folder log aplikasi desktop.",
|
||||
|
||||
@@ -288,6 +288,7 @@
|
||||
"currentModel": "現在の設定",
|
||||
"brandLogos": "ブランドロゴ",
|
||||
"browserNotifications": "タスク通知",
|
||||
"notificationSound": "完了音",
|
||||
"cliAppsCatalog": "カタログ",
|
||||
"cliAppsFilter": "フィルター",
|
||||
"engine": "エンジン",
|
||||
@@ -331,6 +332,7 @@
|
||||
"selectedModelValue": "選択したモデルによって設定されます。",
|
||||
"brandLogos": "設定で第三者プロバイダーと CLI のロゴを表示します。",
|
||||
"browserNotifications": "このページがバックグラウンドにある場合のみ通知します。既定ではオフです。",
|
||||
"notificationSound": "このページがフォアグラウンドにあるときにターンが完了したら短いチャイムを再生します。既定ではオフです。",
|
||||
"cliAppsCatalog": "nanobot がこのマシンで使用できるコマンドラインツールをインストールします。デスクトップアプリは変更しません。",
|
||||
"cliAppsFilter": "アプリ、カテゴリ、機能で検索します。",
|
||||
"logs": "デスクトップアプリのログフォルダーを開きます。",
|
||||
|
||||
@@ -288,6 +288,7 @@
|
||||
"currentModel": "현재 설정",
|
||||
"brandLogos": "브랜드 로고",
|
||||
"browserNotifications": "작업 알림",
|
||||
"notificationSound": "완료 알림음",
|
||||
"cliAppsCatalog": "카탈로그",
|
||||
"cliAppsFilter": "필터",
|
||||
"engine": "엔진",
|
||||
@@ -331,6 +332,7 @@
|
||||
"selectedModelValue": "선택한 모델에 의해 설정됩니다.",
|
||||
"brandLogos": "설정에서 타사 제공업체와 CLI 로고를 표시합니다.",
|
||||
"browserNotifications": "이 페이지가 백그라운드에 있을 때만 알립니다. 기본값은 꺼짐입니다.",
|
||||
"notificationSound": "이 페이지가 포그라운드에 있을 때 턴이 끝나면 짧은 알림음을 재생합니다. 기본적으로 꺼져 있습니다.",
|
||||
"cliAppsCatalog": "nanobot이 이 컴퓨터에서 사용할 수 있는 명령줄 도구를 설치합니다. 데스크톱 앱은 변경하지 않습니다.",
|
||||
"cliAppsFilter": "앱, 카테고리 또는 기능으로 검색합니다.",
|
||||
"logs": "데스크톱 앱의 로그 폴더를 엽니다.",
|
||||
|
||||
@@ -330,6 +330,7 @@
|
||||
"codeWrap": "Quebra de linha no código",
|
||||
"brandLogos": "Logos de marca",
|
||||
"browserNotifications": "Notificações de tarefas",
|
||||
"notificationSound": "Som de conclusão",
|
||||
"maxResults": "Máx. de resultados",
|
||||
"timeout": "Tempo limite",
|
||||
"jinaReader": "Leitor Jina",
|
||||
@@ -375,6 +376,7 @@
|
||||
"codeWrap": "Mantém linhas longas de código legíveis em telas menores.",
|
||||
"brandLogos": "Mostra logotipos de provedores terceiros e de CLIs em Configurações.",
|
||||
"browserNotifications": "Notifica somente quando esta página está em segundo plano. Desativado por padrão.",
|
||||
"notificationSound": "Toca um breve sinal sonoro quando um turno termina enquanto esta página está em primeiro plano. Desativado por padrão.",
|
||||
"maxResults": "Número máximo de resultados por busca na web.",
|
||||
"timeout": "Segundos antes de uma requisição de busca expirar.",
|
||||
"jinaReader": "Usa o Jina Reader para ler páginas web quando disponível.",
|
||||
|
||||
@@ -288,6 +288,7 @@
|
||||
"currentModel": "Cấu hình hiện tại",
|
||||
"brandLogos": "Logo thương hiệu",
|
||||
"browserNotifications": "Thông báo tác vụ",
|
||||
"notificationSound": "Âm báo hoàn thành",
|
||||
"cliAppsCatalog": "Danh mục",
|
||||
"cliAppsFilter": "Bộ lọc",
|
||||
"engine": "Bộ máy",
|
||||
@@ -331,6 +332,7 @@
|
||||
"selectedModelValue": "Được đặt bởi mô hình đã chọn.",
|
||||
"brandLogos": "Hiển thị logo nhà cung cấp bên thứ ba và CLI trong Cài đặt.",
|
||||
"browserNotifications": "Chỉ thông báo khi trang này ở nền. Mặc định tắt.",
|
||||
"notificationSound": "Phát một tiếng chuông ngắn khi lượt kết thúc trong lúc trang này đang ở phía trước. Tắt theo mặc định.",
|
||||
"cliAppsCatalog": "Cài các công cụ dòng lệnh mà nanobot có thể dùng trên máy này. Các ứng dụng trên máy tính không bị thay đổi.",
|
||||
"cliAppsFilter": "Tìm theo ứng dụng, danh mục hoặc khả năng.",
|
||||
"logs": "Mở thư mục nhật ký của ứng dụng trên máy tính.",
|
||||
|
||||
@@ -516,6 +516,7 @@
|
||||
"codeWrap": "代码换行",
|
||||
"brandLogos": "品牌图标",
|
||||
"browserNotifications": "任务通知",
|
||||
"notificationSound": "完成提示音",
|
||||
"maxResults": "搜索结果数量上限",
|
||||
"timeout": "搜索超时(秒)",
|
||||
"jinaReader": "Jina Reader",
|
||||
@@ -561,6 +562,7 @@
|
||||
"codeWrap": "让长代码行在小屏幕上也易读。",
|
||||
"brandLogos": "在设置中显示提供商和命令行应用的品牌图标。",
|
||||
"browserNotifications": "仅在页面位于后台时通知,默认关闭。",
|
||||
"notificationSound": "回合结束且页面处于前台时播放短促提示音,默认关闭。",
|
||||
"maxResults": "每次网络搜索最多返回多少条结果。",
|
||||
"timeout": "每次搜索请求最长等待多久。",
|
||||
"jinaReader": "读取网页时,优先使用可用的 Jina Reader。",
|
||||
|
||||
@@ -288,6 +288,7 @@
|
||||
"currentModel": "目前設定",
|
||||
"brandLogos": "品牌圖示",
|
||||
"browserNotifications": "任務通知",
|
||||
"notificationSound": "完成提示音",
|
||||
"cliAppsCatalog": "應用程式清單",
|
||||
"cliAppsFilter": "篩選",
|
||||
"engine": "引擎",
|
||||
@@ -331,6 +332,7 @@
|
||||
"selectedModelValue": "由選取的模型決定。",
|
||||
"brandLogos": "在設定中顯示第三方供應商與 CLI 圖示。",
|
||||
"browserNotifications": "僅在頁面位於背景時通知,預設關閉。",
|
||||
"notificationSound": "回合結束且頁面處於前景時播放短促提示音,預設關閉。",
|
||||
"cliAppsCatalog": "安裝供 nanobot 使用的命令列工具,不會安裝或修改對應的桌面應用程式。",
|
||||
"cliAppsFilter": "依應用程式、類別或功能搜尋。",
|
||||
"logs": "開啟原生引擎日誌資料夾。",
|
||||
|
||||
@@ -6,6 +6,7 @@ export interface LocalPreferences {
|
||||
codeWrap: boolean;
|
||||
brandLogos: boolean;
|
||||
browserNotifications: boolean;
|
||||
notificationSound: boolean;
|
||||
fileEditDisplayMode: FileEditDisplayMode;
|
||||
}
|
||||
|
||||
@@ -22,6 +23,7 @@ export const DEFAULT_LOCAL_PREFS: LocalPreferences = {
|
||||
codeWrap: true,
|
||||
brandLogos: true,
|
||||
browserNotifications: false,
|
||||
notificationSound: false,
|
||||
fileEditDisplayMode: "summary",
|
||||
};
|
||||
|
||||
@@ -41,6 +43,7 @@ export function readLocalPreferences(): LocalPreferences {
|
||||
? parsed.brandLogos !== false
|
||||
: true,
|
||||
browserNotifications: parsed.browserNotifications === true,
|
||||
notificationSound: parsed.notificationSound === true,
|
||||
fileEditDisplayMode: normalizeFileEditDisplayMode(parsed.fileEditDisplayMode),
|
||||
};
|
||||
} catch {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// The short chime played when an agent turn completes while the page is
|
||||
// visible (#5524). The asset ships with the WebUI's static files; playback is
|
||||
// gated by the `notificationSound` local preference — off by default — and
|
||||
// by page visibility: the chime is for someone actively watching the tab, so
|
||||
// a background tab stays silent (browserNotifications covers that case).
|
||||
|
||||
import { readLocalPreferences } from "@/lib/local-preferences";
|
||||
|
||||
export const TURN_COMPLETE_SOUND_PATH = "/notification.wav";
|
||||
|
||||
let audio: HTMLAudioElement | null = null;
|
||||
|
||||
export function playTurnCompleteSound(): void {
|
||||
try {
|
||||
if (document.visibilityState !== "visible") return;
|
||||
if (!readLocalPreferences().notificationSound) return;
|
||||
if (audio === null) audio = new Audio(TURN_COMPLETE_SOUND_PATH);
|
||||
audio.currentTime = 0;
|
||||
void audio.play().catch(() => {
|
||||
// Autoplay policies or a missing asset must never surface as an error.
|
||||
});
|
||||
} catch {
|
||||
// A notification chime must never break the stream.
|
||||
}
|
||||
}
|
||||
@@ -164,6 +164,7 @@ const LOCALIZED_SETTINGS_COPY_KEYS = [
|
||||
"settings.rows.codeWrap",
|
||||
"settings.rows.brandLogos",
|
||||
"settings.rows.browserNotifications",
|
||||
"settings.rows.notificationSound",
|
||||
"settings.rows.currentModel",
|
||||
"settings.rows.localServiceAccess",
|
||||
"settings.rows.webuiDefaultAccess",
|
||||
@@ -175,6 +176,7 @@ const LOCALIZED_SETTINGS_COPY_KEYS = [
|
||||
"settings.help.codeWrap",
|
||||
"settings.help.brandLogos",
|
||||
"settings.help.browserNotifications",
|
||||
"settings.help.notificationSound",
|
||||
"settings.help.currentModel",
|
||||
"settings.help.localServiceAccess",
|
||||
"settings.help.webuiDefaultAccess",
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
DEFAULT_LOCAL_PREFS,
|
||||
writeLocalPreferences,
|
||||
} from "@/lib/local-preferences";
|
||||
import { TURN_COMPLETE_SOUND_PATH } from "@/lib/notification-sound";
|
||||
|
||||
class MockAudio {
|
||||
static instances: MockAudio[] = [];
|
||||
src: string;
|
||||
currentTime = 0;
|
||||
play = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
constructor(src: string) {
|
||||
this.src = src;
|
||||
MockAudio.instances.push(this);
|
||||
}
|
||||
}
|
||||
|
||||
function setVisibility(state: DocumentVisibilityState): void {
|
||||
Object.defineProperty(document, "visibilityState", {
|
||||
configurable: true,
|
||||
get: () => state,
|
||||
});
|
||||
}
|
||||
|
||||
describe("playTurnCompleteSound", () => {
|
||||
beforeEach(() => {
|
||||
MockAudio.instances = [];
|
||||
vi.stubGlobal("Audio", MockAudio);
|
||||
vi.resetModules();
|
||||
setVisibility("visible");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
setVisibility("visible");
|
||||
window.localStorage.clear();
|
||||
});
|
||||
|
||||
// Fresh module per test: the module keeps one HTMLAudioElement cached for
|
||||
// the page's lifetime, and the cache must not leak across cases.
|
||||
async function play(): Promise<void> {
|
||||
const { playTurnCompleteSound } = await import("@/lib/notification-sound");
|
||||
playTurnCompleteSound();
|
||||
}
|
||||
|
||||
it("stays silent by default", async () => {
|
||||
await play();
|
||||
expect(MockAudio.instances).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("plays the bundled chime when enabled and the page is visible", async () => {
|
||||
writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, notificationSound: true });
|
||||
await play();
|
||||
expect(MockAudio.instances).toHaveLength(1);
|
||||
expect(MockAudio.instances[0].src).toBe(TURN_COMPLETE_SOUND_PATH);
|
||||
expect(MockAudio.instances[0].play).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("stays silent when the page is in the background", async () => {
|
||||
writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, notificationSound: true });
|
||||
setVisibility("hidden");
|
||||
await play();
|
||||
expect(MockAudio.instances).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("reuses one audio element across turns and restarts it", async () => {
|
||||
writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, notificationSound: true });
|
||||
await play();
|
||||
await play();
|
||||
expect(MockAudio.instances).toHaveLength(1);
|
||||
const first = MockAudio.instances[0];
|
||||
expect(first.currentTime).toBe(0);
|
||||
expect(first.play).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("swallows playback rejections", async () => {
|
||||
class RejectingAudio extends MockAudio {
|
||||
play = vi.fn().mockRejectedValue(new Error("autoplay blocked"));
|
||||
}
|
||||
vi.stubGlobal("Audio", RejectingAudio);
|
||||
writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, notificationSound: true });
|
||||
await expect(play()).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user