Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(tts): add master output volume control (0-100%) in Settings

Ruben Lütkef754bd3f1217
diff --git a/jarvis/audio/player.py b/jarvis/audio/player.py
index 2f46192d54..7758f7b230 100644
--- a/jarvis/audio/player.py
+++ b/jarvis/audio/player.py
@@ -253,6 +253,20 @@ def _resolve_output_device(device: int | str | None) -> int | str | None:
return None
+def _clamp_volume(volume: float) -> float:
+ """Clamp a requested master gain into the safe attenuation range [0.0, 1.0].
+
+ A value >1.0 would push samples past full-scale and clip; a negative value
+ would invert the waveform. Both are silently pinned to the bounds so no
+ caller (config, REST, runtime setter) can over-drive playback. A non-numeric
+ value falls back to full volume rather than muting.
+ """
+ try:
+ return max(0.0, min(1.0, float(volume)))
+ except (TypeError, ValueError):
+ return 1.0
+
+
class AudioPlayer:
"""Thread-safe async player for int16 PCM audio."""
@@ -262,12 +276,17 @@ class AudioPlayer:
sample_rate: int = TTS_SAMPLE_RATE,
channels: int = 1,
bus: Any = None,
+ volume: float = 1.0,
) -> None:
# Resolve "auto-headset" / similar strings to the actual device index.
# Integer values are not resolved — the user specifies those explicitly.
self._device = _resolve_output_device(device)
self._sample_rate = sample_rate
self._channels = channels
+ # Master output gain in [0.0, 1.0] (1.0 = full, historical behaviour).
+ # Applied per sub-block in _write_samples. Clamped so a stray config /
+ # runtime value can never over-drive (>1.0 would clip) or invert (<0).
+ self._volume = _clamp_volume(volume)
self._device_logged = False # logged once on the first play call
# Optional bus reference. When set, play_chunks() publishes
# AudioOutFirst on the first audible sample so UI subscribers
@@ -374,6 +393,16 @@ class AudioPlayer:
self._device_logged = False # re-log the new device on next play
self.invalidate_device_cache()
+ def set_volume(self, volume: float) -> None:
+ """Live-apply a new master output gain (0.0–1.0) — no stream restart.
+
+ The value is read per sub-block in ``_write_samples``, so a change made
+ mid-utterance takes effect on the next ~60 ms block. Clamped to the safe
+ attenuation range; the open PortAudio stream is untouched (gain rides on
+ top of it, orthogonal to device/rate/lifecycle state).
+ """
+ self._volume = _clamp_volume(volume)
+
def _log_device_once(self) -> None:
"""Log the active output device once per AudioPlayer instance.
@@ -558,10 +587,19 @@ class AudioPlayer:
# write still provides back-pressure. ~60 ms blocks are large enough to
# never starve the buffer.
feed_level = level_tap.has_subscribers()
+ # Master output volume (0.0–1.0). ``gain >= 1.0`` is the fast path — no
+ # copy, so full-volume playback stays byte-identical to before. Below
+ # full we attenuate a per-block copy for the speaker but feed the
+ # PRE-gain RMS to the visualizer, so the orb/equalizer keeps showing
+ # that Jarvis is speaking even at a low volume (bars track speech, not
+ # loudness). ``getattr`` default keeps ``__new__``-built test/hot-reload
+ # instances (which skip ``__init__``) at full volume instead of crashing.
+ gain = getattr(self, "_volume", 1.0)
block = max(1, int(device_rate * 0.06))
for start in range(0, arr_f.shape[0], block):
chunk = arr_f[start:start + block]
- underflowed = stream.write(chunk)
+ out = chunk if gain >= 1.0 else chunk * gain
+ underflowed = stream.write(out)
# Playback progress for the pipeline stall watchdog: a healthy
# ~60 ms sub-block returns well inside the watchdog's stall window;
# only a wedged device leaves ``last_write_ns`` frozen. ``getattr``
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 286f9c9b79..8e834c700f 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -309,6 +309,13 @@ class TTSConfig(BaseModel):
style_prompt: str | None = None
voice_auto_switch: bool = True
speed: float = 1.0
+ # Master output volume 0.0–1.0 (1.0 = full, unattenuated — the historical
+ # behaviour). Applied as a pure amplitude multiplier on the final PCM in the
+ # shared AudioPlayer, so it is provider-independent and can never clip (a
+ # 0–1 factor only attenuates). Editable live from the Settings "Volume"
+ # slider; on a headless host with no audio device it is simply never
+ # exercised (playback never opens a stream) — no crash.
+ volume: float = Field(default=1.0, ge=0.0, le=1.0)
streaming: bool = True
# ElevenLabs-specific VoiceSettings (ignored by other providers).
stability: float = 0.5
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index a36b8aa2d9..b9712d0d00 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -237,6 +237,24 @@ def set_tts_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
log.warning("Could not sync tts.model to config-soll.json: %s", exc) # i18n-allow
+def set_tts_volume(volume: float, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Set the master TTS output volume (``[tts] volume``), a 0.0–1.0 gain.
+
+ Clamped to the same bounds the config field enforces (``ge=0.0, le=1.0``) so
+ a stray value can never over-drive (>1.0 clips) or invert (<0) playback. The
+ ``[tts]`` block is drift-guard pinned (its reference snapshot already tracks
+ other ``[tts]`` keys), so a TOML-only write would be reverted — we sync that
+ snapshot too, exactly like :func:`set_tts_voice`. The Settings route applies
+ the change live to the running player; this persists the boot default.
+ """
+ v = max(0.0, min(1.0, float(volume)))
+ _patch_table(path, "tts", "volume", v)
+ try:
+ _update_config_soll_section("tts", {"volume": v}) # i18n-allow
+ except Exception as exc: # noqa: BLE001 — best-effort, must not propagate
+ log.warning("Could not sync tts.volume to config-soll.json: %s", exc) # i18n-allow
+
+
def set_stt_model(model: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Set the global STT model (``[stt] model``) across all THREE layers.
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 475595d9e5..ca282c4713 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -1298,7 +1298,11 @@ class SpeechPipeline:
# Bus injected so AudioPlayer publishes AudioOutFirst on the first
# audible sample — UI subscribers (orb mouth animation + SPEAKING
# bubble) sync to actual audio start, not the early SPEAKING state.
- self._player = AudioPlayer(device=output_device, bus=bus)
+ # Master output volume (0.0–1.0) from [tts].volume. Defensive getattr
+ # chain: ``config`` may be None (test fixtures) and older TOMLs predate
+ # the field — both fall back to full volume.
+ _tts_volume = getattr(getattr(config, "tts", None), "volume", 1.0)
+ self._player = AudioPlayer(device=output_device, bus=bus, volume=_tts_volume)
# Kept so warm-up can re-resolve the output device against a freshly
# re-enumerated PortAudio table (post-reboot idx-drift cure, BUG-014).
self._output_device = output_device
@@ -1573,6 +1577,19 @@ class SpeechPipeline:
if callable(setter):
setter(int(ms))
+ def set_tts_volume(self, volume: float) -> None:
+ """Live-apply a new master TTS output volume (0.0–1.0) — no restart.
+
+ Delegates to ``AudioPlayer.set_volume`` so a Settings change is audible
+ on the next spoken sub-block. No-op-safe when the player is absent
+ (headless / not yet started) — the value still persisted and applies on
+ the next start.
+ """
+ player = getattr(self, "_player", None)
+ setter = getattr(player, "set_volume", None)
+ if callable(setter):
+ setter(float(volume))
+
def _wake_poll_interval(self) -> float:
"""The stt_match wake poll interval, derived from the user's Sensitivity
slider (``[trigger.wake_word].sensitivity``). Higher sensitivity polls
diff --git a/jarvis/ui/web/frontend/src/hooks/useTtsVolume.ts b/jarvis/ui/web/frontend/src/hooks/useTtsVolume.ts
new file mode 100644
index 0000000000..7bd193cb2f
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useTtsVolume.ts
@@ -0,0 +1,65 @@
+import { useCallback, useEffect, useState } from "react";
+
+/**
+ * Master TTS output volume (how loudly Jarvis speaks) from
+ * GET /api/settings/tts-volume. The value is a 0.0–1.0 amplitude gain
+ * (1.0 = full); the UI renders it as a 0–100% slider. Mirrors useSilenceWindow.
+ */
+export interface TtsVolumeConfig {
+ volume: number;
+ default: number;
+ min: number;
+ max: number;
+}
+
+export interface TtsVolumeSaveResult {
+ ok: boolean;
+ volume: number;
+ default: number;
+ persisted: boolean;
+ applied_live: boolean;
+ restart_required: boolean;
+}
+
+/** Loads /api/settings/tts-volume and exposes setVolume(). */
+export function useTtsVolume() {
+ const [config, setConfig] = useState<TtsVolumeConfig | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ const refetch = useCallback(async () => {
+ setError(null);
+ try {
+ const res = await fetch("/api/settings/tts-volume");
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data: TtsVolumeConfig = await res.json();
+ setConfig(data);
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void refetch();
+ }, [refetch]);
+
+ const setVolume = useCallback(
+ async (volume: number): Promise<TtsVolumeSaveResult> => {
+ const res = await fetch("/api/settings/tts-volume", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ volume, persist: true }),
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(body.detail ?? `HTTP ${res.status}`);
+ const result = body as TtsVolumeSaveResult;
+ setConfig((prev) => (prev ? { ...prev, volume: result.volume } : prev));
+ return result;
+ },
+ [],
+ );
+
+ return { config, loading, error, refetch, setVolume };
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 7df8d99564..359d64b733 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -916,6 +916,13 @@
"saved_toast": "Denkpause auf {0} gesetzt.",
"restart_caption": "Gespeichert — wird beim nächsten Start aktiv."
},
+ "volume": {
+ "title": "Lautstärke",
+ "description": "Wie laut {name} seine Antworten ausgibt. 100% ist volle Lautstärke; niedriger stellen, um {name} leiser zu machen. Wenn es bei 100% noch zu leise ist, die System- oder Lautsprecher-Lautstärke erhöhen.",
+ "reset": "Auf Standard zurücksetzen (100%)",
+ "saved_toast": "Lautstärke auf {0} gesetzt.",
+ "restart_caption": "Gespeichert — wird beim nächsten Start aktiv."
+ },
"title": "Einstellungen",
"subtitle": "Wake-Word, Hotkeys, Safety-Policies, Autostart.",
"overlay_taskbar_group_title": "Leiste & Overlay",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index c51b16c16b..21bf4dd7ae 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -917,6 +917,13 @@
"saved_toast": "Thinking pause set to {0}.",
"restart_caption": "Saved — applies on next start."
},
+ "volume": {
+ "title": "Volume",
+ "description": "How loudly {name} speaks its answers. 100% is full volume; lower it to make {name} quieter. If it is still too quiet at 100%, raise your system or speaker volume.",
+ "reset": "Reset to default (100%)",
+ "saved_toast": "Volume set to {0}.",
+ "restart_caption": "Saved — applies on next start."
+ },
"title": "Settings",
"subtitle": "Wake-word, hotkeys, safety policies, autostart.",
"overlay_taskbar_group_title": "Bar & Overlay",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 4af701b23a..cd716dbe65 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -916,6 +916,13 @@
"saved_toast": "Pausa para pensar fijada en {0}.",
"restart_caption": "Guardado — se aplica en el próximo inicio."
},
+ "volume": {
+ "title": "Volumen",
+ "description": "Qué tan alto habla {name} sus respuestas. 100% es el volumen máximo; bájalo para que {name} suene más bajo. Si sigue siendo demasiado bajo al 100%, sube el volumen del sistema o del altavoz.",
+ "reset": "Restablecer al valor predeterminado (100%)",
+ "saved_toast": "Volumen fijado en {0}.",
+ "restart_caption": "Guardado — se aplica en el próximo inicio."
+ },
"title": "Ajustes",
"subtitle": "Palabra de activación, atajos, políticas de seguridad, inicio automático.",
"overlay_taskbar_group_title": "Barra y superposición",
diff --git a/jarvis/ui/web/frontend/src/views/SettingsView.tsx b/jarvis/ui/web/frontend/src/views/SettingsView.tsx
index b35aa83a63..85718e15f6 100644
--- a/jarvis/ui/web/frontend/src/views/SettingsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/SettingsView.tsx
@@ -12,6 +12,7 @@ import { OverlayTaskbarGroup } from "@/views/settings/OverlayTaskbarGroup";
import { LanguagesGroup } from "@/views/settings/LanguagesGroup";
import { AppSettingsGroup } from "@/views/settings/AppSettingsGroup";
import { SilenceWindowGroup } from "@/views/settings/SilenceWindowGroup";
+import { VolumeGroup } from "@/views/settings/VolumeGroup";
import { SystemPromptGroup } from "@/views/settings/SystemPromptGroup";
import { useWakeWord, type WakeWordSaveResult } from "@/hooks/useWakeWord";
import {
@@ -66,6 +67,7 @@ export function SettingsView() {
<SystemPromptGroup />
<WakeWordPanel />
<SilenceWindowGroup />
+ <VolumeGroup />
<KeybindsPanel />
<ul className="mt-2 space-y-2">
diff --git a/jarvis/ui/web/frontend/src/views/settings/VolumeGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/VolumeGroup.tsx
new file mode 100644
index 0000000000..5cc10592f8
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/settings/VolumeGroup.tsx
@@ -0,0 +1,114 @@
+import { useEffect, useRef, useState } from "react";
+import { Volume2 } from "lucide-react";
+import { useTtsVolume } from "@/hooks/useTtsVolume";
+import { useEventStore } from "@/store/events";
+import { useT } from "@/i18n";
+
+/**
+ * "Volume" slider inside the Settings view. Tunes how loudly Jarvis speaks
+ * (master TTS output gain). The backend value is a 0.0–1.0 amplitude factor;
+ * this slider presents it as 0–100% (100% = full, the historical loudness).
+ * The label tracks the slider live; the PUT fires on release (pointer/key up)
+ * so a drag does not storm the backend. The change persists to jarvis.toml and
+ * applies live to the running player — no restart (a headless host falls back
+ * to "applies on next start").
+ */
+export function VolumeGroup() {
+ const t = useT();
+ const { config, loading, setVolume } = useTtsVolume();
+ const pushToast = useEventStore((s) => s.pushToast);
+
+ // Local slider value in PERCENT (0–100). Mirrors the server 0.0–1.0 factor
+ // once GET resolves; the label follows it instantly on drag while the PUT
+ // waits for commit.
+ const [pct, setLocalPct] = useState(100);
+ const [saving, setSaving] = useState(false);
+ // The last percent we actually committed — guards an idle mouseUp (no drag)
+ // from firing a redundant PUT.
+ const committedRef = useRef(100);
+
+ useEffect(() => {
+ if (config) {
+ const p = Math.round(config.volume * 100);
+ setLocalPct(p);
+ committedRef.current = p;
+ }
+ }, [config]);
+
+ async function commit(nextPct: number) {
+ if (nextPct === committedRef.current) return; // no change → no PUT
+ committedRef.current = nextPct;
+ setSaving(true);
+ try {
+ const res = await setVolume(nextPct / 100);
+ pushToast(
+ "success",
+ t("settings_view.volume.saved_toast").replace(
+ "{0}",
+ `${Math.round(res.volume * 100)}%`,
+ ),
+ );
+ if (res.restart_required) {
+ pushToast("warning", t("settings_view.volume.restart_caption"));
+ }
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ // Revert the local value to the last known-good so the UI does not lie.
+ setLocalPct(committedRef.current);
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ function onReset() {
+ const def = Math.round((config?.default ?? 1) * 100);
+ setLocalPct(def);
+ void commit(def);
+ }
+
+ const showReset = pct !== Math.round((config?.default ?? 1) * 100);
+
+ return (
+ <div className="mt-2 rounded-lg border border-border bg-card/60 p-4">
+ <div className="flex items-start gap-3">
+ <Volume2 className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center justify-between gap-4">
+ <h4 className="font-display text-sm font-semibold">
+ {t("settings_view.volume.title")}
+ </h4>
+ <span className="font-mono text-sm text-primary">{`${pct}%`}</span>
+ </div>
+ <p className="mt-1 text-xs text-muted-foreground">
+ {t("settings_view.volume.description")}
+ </p>
+
+ <input
+ type="range"
+ min={0}
+ max={100}
+ step={1}
+ value={pct}
+ disabled={loading || saving}
+ onChange={(e) => setLocalPct(Number(e.target.value))}
+ onMouseUp={() => void commit(pct)}
+ onKeyUp={() => void commit(pct)}
+ onTouchEnd={() => void commit(pct)}
+ className="mt-4 w-full accent-primary disabled:opacity-50"
+ />
+
+ {showReset && (
+ <button
+ type="button"
+ onClick={onReset}
+ disabled={saving}
+ className="mt-3 text-[11px] text-muted-foreground underline hover:text-foreground disabled:opacity-50"
+ >
+ {t("settings_view.volume.reset")}
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index 481461ac88..a89f8d3683 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -1572,3 +1572,87 @@ async def put_silence_window(body: SilenceWindowBody, request: Request) -> dict[
"applied_live": applied_live,
"restart_required": not applied_live,
}
+
+
+# ---------------------------------------------------------------------------
+# Master TTS output volume — how loudly Jarvis speaks.
+#
+# GET to read, PUT to change. A 0.0–1.0 amplitude gain (1.0 = full, the
+# historical unattenuated behaviour), the same unit as [tts].volume; the UI
+# renders it as a 0–100% slider. Persisted to jarvis.toml [tts].volume AND
+# live-applied to the running SpeechPipeline (set_tts_volume → AudioPlayer), so
+# a change is audible immediately without a restart; a headless/down pipeline
+# falls back to "applies on next start". Provider-independent (applied in the
+# shared player, so it covers every TTS provider and ack chimes alike).
+# ---------------------------------------------------------------------------
+
+_TTS_VOLUME_DEFAULT = 1.0
+
+
+class TtsVolumeBody(BaseModel):
+ volume: float = Field(..., ge=0.0, le=1.0)
+ persist: bool = Field(default=True, description="Persist as boot default in jarvis.toml")
+
+
+def _current_tts_volume(request: Request) -> float:
+ cfg = _config(request)
+ tts = getattr(cfg, "tts", None)
+ try:
+ return max(0.0, min(1.0, float(getattr(tts, "volume", _TTS_VOLUME_DEFAULT))))
+ except (TypeError, ValueError):
+ return _TTS_VOLUME_DEFAULT
+
+
[email protected]("/tts-volume")
+async def get_tts_volume(request: Request) -> dict[str, object]:
+ return {
+ "volume": _current_tts_volume(request),
+ "default": _TTS_VOLUME_DEFAULT,
+ "min": 0.0,
+ "max": 1.0,
+ }
+
+
[email protected]("/tts-volume")
+async def put_tts_volume(body: TtsVolumeBody, request: Request) -> dict[str, object]:
+ volume = float(body.volume) # already range-validated by the Pydantic Field
+
+ # Best-effort in-memory cfg update so a later cfg read agrees pre-restart.
+ cfg = _config(request)
+ if cfg is not None and getattr(cfg, "tts", None) is not None:
+ try:
+ cfg.tts.volume = volume # type: ignore[attr-defined]
+ except Exception as exc: # noqa: BLE001 — frozen model is not an error
+ log.debug("in-memory tts.volume update skipped: %s", exc)
+
+ persisted = False
+ if body.persist:
+ try:
+ from jarvis.core import config_writer
+ from jarvis.core.config import resolve_config_path
+
+ config_writer.set_tts_volume(volume, path=resolve_config_path())
+ persisted = True
+ except Exception as exc: # noqa: BLE001 — persist is best-effort
+ log.warning("tts-volume persist failed (live apply still attempted): %s", exc)
+
+ # Live-apply to the running voice pipeline so the new volume is audible
+ # immediately — no app restart. Best-effort: a headless/down pipeline just
+ # means it applies on next start.
+ applied_live = False
+ pipeline = getattr(request.app.state, "speech_pipeline", None)
+ if pipeline is not None and hasattr(pipeline, "set_tts_volume"):
+ try:
+ pipeline.set_tts_volume(volume)
+ applied_live = True
+ except Exception as exc: # noqa: BLE001 — never fail the save on a live-apply hiccup
+ log.warning("tts-volume live-apply failed (persisted; applies on restart): %s", exc)
+
+ return {
+ "ok": True,
+ "volume": volume,
+ "default": _TTS_VOLUME_DEFAULT,
+ "persisted": persisted,
+ "applied_live": applied_live,
+ "restart_required": not applied_live,
+ }
diff --git a/scripts/config-soll.json b/scripts/config-soll.json
index 67cf95f529..66e024cbfd 100644
--- a/scripts/config-soll.json
+++ b/scripts/config-soll.json
@@ -18,7 +18,8 @@
"vertex_project": "",
"vertex_location": "us-central1",
"service_account_path": "~/.config/jarvis/vertex-sa.json",
- "model": "sonic-2"
+ "model": "sonic-2",
+ "volume": 1.0
},
"tts.cartesia": {
"model_id": "sonic-3.5",
diff --git a/tests/unit/audio/test_player_volume.py b/tests/unit/audio/test_player_volume.py
new file mode 100644
index 0000000000..c06f187643
--- /dev/null
+++ b/tests/unit/audio/test_player_volume.py
@@ -0,0 +1,86 @@
+"""AudioPlayer master output volume — a 0.0–1.0 gain applied in _write_samples.
+
+Drives the REAL _write_samples with a capturing fake stream (no PortAudio), so
+these assert the exact samples that would reach the speaker. Covers: full volume
+is byte-identical (unattenuated), fractional volume scales the amplitude, zero is
+silent, out-of-range is clamped, and — crucially — the visualizer (level_tap)
+keeps seeing the PRE-gain loudness so the orb/equalizer still shows speech when
+Jarvis is turned down.
+"""
+from __future__ import annotations
+
+import numpy as np
+
+from jarvis.audio import level_tap
+from jarvis.audio import player as P
+
+
+class _CapturingStream:
+ """Stand-in for sd.OutputStream that records every written sub-block."""
+
+ def __init__(self) -> None:
+ self.writes: list[np.ndarray] = []
+
+ def write(self, arr) -> bool:
+ self.writes.append(np.asarray(arr).copy())
+ return False # no underflow
+
+
+def _bare_player(volume: float) -> P.AudioPlayer:
+ pl = P.AudioPlayer.__new__(P.AudioPlayer) # bypass device init
+ pl._volume = volume
+ pl._init_progress()
+ return pl
+
+
+def _play(volume: float, amplitude: int, n: int = 4000) -> np.ndarray:
+ """Run _write_samples for a constant-amplitude mono int16 signal, return the
+ concatenated float32 stereo samples handed to the stream."""
+ pl = _bare_player(volume)
+ stream = _CapturingStream()
+ arr = np.full(n, amplitude, dtype=np.int16)
+ pl._write_samples(stream, arr, 24000, 24000) # source_rate == device_rate
+ return np.concatenate(stream.writes, axis=0)
+
+
+def test_full_volume_is_unattenuated():
+ level_tap.reset() # no subscriber → feed path off
+ out = _play(1.0, 20000)
+ assert np.allclose(out, 20000 / 32768.0, atol=1e-4)
+
+
+def test_half_volume_halves_amplitude():
+ level_tap.reset()
+ out = _play(0.5, 20000)
+ assert np.allclose(out, 0.5 * 20000 / 32768.0, atol=1e-4)
+
+
+def test_zero_volume_is_silent():
+ level_tap.reset()
+ out = _play(0.0, 20000)
+ assert np.allclose(out, 0.0, atol=1e-6)
+
+
+def test_out_of_range_volume_is_clamped_to_full():
+ # A >1.0 gain would clip; the player clamps on construction, but even a
+ # raw over-driven value here must not amplify past the input.
+ level_tap.reset()
+ pl = P.AudioPlayer.__new__(P.AudioPlayer)
+ pl.set_volume(5.0) # clamped to 1.0
+ assert pl._volume == 1.0
+
+
+def test_low_volume_keeps_visualizer_full_scale():
+ """At 10% volume the audio is attenuated but the equalizer/orb still sees
+ the pre-gain RMS — so the user sees Jarvis is speaking even when quiet."""
+ level_tap.reset()
+ got: list[float] = []
+ level_tap.subscribe(got.append)
+ try:
+ out = _play(0.1, 30000)
+ finally:
+ level_tap.reset()
+ # Audio is attenuated to ~10%.
+ assert np.allclose(out, 0.1 * 30000 / 32768.0, atol=1e-4)
+ # But the visualizer saw near-full-scale loudness (30000/32768 ≈ 0.92).
+ assert got and max(got) > 0.5