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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(voice): draw the browser voice overlay from real microphone samples
Ruben Lütke927379e70b69
diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsxindex 027cef9462..645dfe8e38 100644--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx@@ -373,8 +373,21 @@ export function Sidebar({ width = SIDEBAR_DEFAULT_WIDTH }: SidebarProps = {}) {<><div className="mt-3 min-h-[20px] rounded-md bg-background/40 px-2 py-1.5 text-xs text-muted-foreground">{transcription ? (- <span className={cn("font-mono", !transcriptionFinal && "italic")}>- {truncate(transcription, 48)}+ <span+ className={cn(+ "font-mono",+ !transcriptionFinal && "italic text-foreground/70",+ )}+ >+ {tailTruncate(transcription, 48)}+ {!transcriptionFinal && (+ <span+ className="ml-px animate-pulse motion-reduce:animate-none"+ aria-hidden="true"+ >+ ▍+ </span>+ )}</span>) : (<span className="text-muted-foreground/50">@@ -571,9 +584,15 @@ function NavRow({);}-function truncate(s: string, n: number): string {+/** Keep the NEWEST words of a growing transcript visible.+ *+ * Head truncation froze the line on the first 48 characters the moment a+ * sentence outgrew the box: the user kept talking and the display stopped+ * moving, which reads as "it stopped hearing me". Dropping the oldest end+ * instead makes the line scroll along with the speech. */+function tailTruncate(s: string, n: number): string {if (s.length <= n) return s;- return s.slice(0, n - 1) + "…";+ return "…" + s.slice(s.length - (n - 1));}function prettyProviderName(id: string): string {diff --git a/jarvis/ui/web/frontend/src/components/overlay/OverlayStylePreviews.tsx b/jarvis/ui/web/frontend/src/components/overlay/OverlayStylePreviews.tsxindex cb559c1626..faadb86e6b 100644--- a/jarvis/ui/web/frontend/src/components/overlay/OverlayStylePreviews.tsx+++ b/jarvis/ui/web/frontend/src/components/overlay/OverlayStylePreviews.tsx@@ -1,5 +1,19 @@import { MascotGigi } from "@/components/MascotGigi";import type { OverlayStyle } from "@/hooks/useOverlayStyle";+import {+ BAR_SPAN,+ PILL_CY,+ PILL_H,+ PILL_R,+ PILL_W,+ PILL_X,+ PILL_Y,+ PREVIEW_BAR_HEIGHTS,+ VIEW_H,+ VIEW_W,+ barWidth,+ evenlySpaced,+} from "./voiceBars";/*** Shared visual previews for the on-screen overlay styles (Bar / Mascot / None).@@ -7,8 +21,23 @@ import type { OverlayStyle } from "@/hooks/useOverlayStyle";* Lifted out of ``views/settings/OverlayTaskbarGroup.tsx`` so both the Settings* panel and the onboarding "System Style" step can render the same graphics* without one view importing the other. The mascot reuses the real Gigi SVG.+ *+ * The bar thumbnail draws its geometry from ``voiceBars`` — the same module the+ * live ``VoiceWaveform`` uses — so what the picker shows is the shape the user+ * actually gets. The PALETTE is deliberately not shared: this thumbnail is a+ * portrait of the DESKTOP overlay, which is gold on near-black whatever theme+ * the web UI runs in, so it keeps the renderer's literal colours. The live+ * visualizer sits inside the themed app and follows the theme instead.+ *+ * These are still previews, not instruments: they animate nothing. Three+ * thumbnails oscillating side by side on a settings screen is noise, and with+ * no microphone behind them any motion here would be invented.*/+const PREVIEW_BG = "#0e0d0c";+const PREVIEW_RIM = "#d7b669";+const PREVIEW_BAR = "#e7c46e";+/** Maps an overlay style to its preview graphic. */export function StylePreview({ style }: { style: OverlayStyle }) {if (style === "mascot") {@@ -19,43 +48,50 @@ export function StylePreview({ style }: { style: OverlayStyle }) {}export function BarPreview() {- const heights = [6, 11, 15, 8, 14, 9, 7];+ const w = barWidth(PREVIEW_BAR_HEIGHTS.length);return (- <svg viewBox="0 0 100 40" className="w-20" aria-hidden="true">+ <svg viewBox={`0 0 ${VIEW_W} ${VIEW_H}`} className="w-20" aria-hidden="true"><rect- x="6"- y="11"- width="88"- height="18"- rx="9"- fill="#0e0d0c"- stroke="#d7b669"+ x={PILL_X}+ y={PILL_Y}+ width={PILL_W}+ height={PILL_H}+ rx={PILL_R}+ fill={PREVIEW_BG}+ stroke={PREVIEW_RIM}strokeWidth="1.6"/>- {heights.map((h, i) => (- <rect- key={`bar-${i}`}- x={24 + i * 8}- y={20 - h / 2}- width="3"- height={h}- rx="1.5"- fill="#e7c46e"- />- ))}+ {evenlySpaced(VIEW_W / 2, BAR_SPAN, PREVIEW_BAR_HEIGHTS.length).map((x, i) => {+ const h = PREVIEW_BAR_HEIGHTS[i];+ return (+ <rect+ key={`bar-${x}`}+ x={x - w / 2}+ y={PILL_CY - h / 2}+ width={w}+ height={h}+ rx={w / 2}+ fill={PREVIEW_BAR}+ />+ );+ })}</svg>);}export function NonePreview() {return (- <svg viewBox="0 0 100 40" className="w-20 opacity-50" aria-hidden="true">+ <svg+ viewBox={`0 0 ${VIEW_W} ${VIEW_H}`}+ className="w-20 opacity-50"+ aria-hidden="true"+ ><rect- x="6"- y="11"- width="88"- height="18"- rx="9"+ x={PILL_X}+ y={PILL_Y}+ width={PILL_W}+ height={PILL_H}+ rx={PILL_R}fill="none"stroke="#7c766b"strokeWidth="1.6"diff --git a/jarvis/ui/web/frontend/src/components/overlay/VoiceWaveform.tsx b/jarvis/ui/web/frontend/src/components/overlay/VoiceWaveform.tsxnew file mode 100644index 0000000000..b0b9081a65--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/overlay/VoiceWaveform.tsx@@ -0,0 +1,281 @@+import { memo, useEffect, useRef, useState, type MutableRefObject } from "react";++import { cn } from "@/lib/utils";+import {+ BAR_MIN_H,+ BAR_SPAN,+ COLUMN_MS,+ LIVE_BAR_COUNT,+ PILL_CY,+ PILL_H,+ PILL_R,+ PILL_W,+ PILL_X,+ PILL_Y,+ SWEEP_PERIOD_S,+ VIEW_H,+ VIEW_W,+ barHeight,+ barWidth,+ clamp01,+ evenlySpaced,+ ringValue,+ smoothLevel,+ sweepGain,+} from "./voiceBars";++/**+ * The live voice visualizer — the same pill the desktop overlay draws, fed by+ * real microphone levels.+ *+ * Two looks, and which one is shown is a statement of fact rather than a+ * styling choice:+ *+ * - **waveform** (``listening``) — a scrolling history of MEASURED microphone+ * levels. The newest sample enters at the right edge and the row travels+ * left, so the shape on screen is what the user actually said a moment ago.+ * - **sweep** (``connecting`` / ``working`` / ``speaking``) — a travelling+ * highlight for activity that is real but NOT measured here: the socket+ * opening, the transcription and reply running after the turn was committed,+ * the assistant's own speech (the browser has no output level tap). It+ * promises motion and nothing more, so the visualizer can never imply a+ * microphone reading it does not have.+ *+ * Nothing in the animation goes through React state: the level arrives at+ * ~30 Hz from the capture worklet and is read from a ref inside one+ * ``requestAnimationFrame`` loop that writes SVG attributes directly. A+ * ``setState`` per level sample would re-render the whole control 30 times a+ * second to move seven pixels.+ */+export type WaveformPhase =+ | "idle"+ | "connecting"+ | "listening"+ | "working"+ | "speaking"+ | "error";++/** Phases whose bars come from real microphone samples. */+const MEASURED_PHASES: readonly WaveformPhase[] = ["listening"];++/** rAF hands out a huge delta after the tab was hidden; cap it so the row+ * resumes smoothly instead of snapping through a second of history. */+const MAX_FRAME_S = 0.1;++/** Repaint budget while motion is reduced — enough to follow a voice, slow+ * enough that the row reads as a level meter rather than an animation. */+const REDUCED_PAINT_MS = 66;++/** Per-phase colouring.+ *+ * The colour is a Tailwind class (so it follows the theme), the strength is an+ * inline opacity rather than a ``/70`` modifier: this build's Tailwind emits+ * ``fill-primary`` but NOT ``fill-primary/70``, because the theme colours are+ * plain ``hsl(var(--x))`` strings with no ``<alpha-value>`` slot — the faded+ * classes would silently resolve to nothing and the bars would vanish. */+const PHASE_TONE: Record<+ WaveformPhase,+ { bars: string; barsOpacity: number; rim: string; rimOpacity: number }+> = {+ idle: { bars: "fill-muted-foreground", barsOpacity: 0.5, rim: "stroke-border", rimOpacity: 1 },+ connecting: { bars: "fill-primary", barsOpacity: 0.6, rim: "stroke-border", rimOpacity: 1 },+ listening: { bars: "fill-primary", barsOpacity: 1, rim: "stroke-primary", rimOpacity: 0.7 },+ working: { bars: "fill-primary", barsOpacity: 0.85, rim: "stroke-primary", rimOpacity: 0.5 },+ speaking: { bars: "fill-primary", barsOpacity: 0.7, rim: "stroke-primary", rimOpacity: 0.35 },+ error: { bars: "fill-destructive", barsOpacity: 0.8, rim: "stroke-destructive", rimOpacity: 0.8 },+};++function prefersReducedMotion(): boolean {+ try {+ return window.matchMedia("(prefers-reduced-motion: reduce)").matches;+ } catch {+ // jsdom and older browsers without matchMedia — treat as "motion ok".+ return false;+ }+}++/** Track the OS "reduce motion" setting, including a live change. */+function useReducedMotion(): boolean {+ const [reduced, setReduced] = useState(prefersReducedMotion);+ useEffect(() => {+ const query = (() => {+ try {+ return window.matchMedia("(prefers-reduced-motion: reduce)");+ } catch {+ // jsdom and older browsers without matchMedia — nothing to track.+ return null;+ }+ })();+ if (typeof query?.addEventListener !== "function") return;+ const onChange = () => setReduced(query.matches);+ query.addEventListener("change", onChange);+ return () => query.removeEventListener("change", onChange);+ }, []);+ return reduced;+}++function VoiceWaveformImpl({+ levelRef,+ phase,+ count = LIVE_BAR_COUNT,+ className,+}: {+ /** Normalized 0..1 microphone level, written by the audio callback. */+ levelRef: MutableRefObject<number>;+ phase: WaveformPhase;+ count?: number;+ className?: string;+}) {+ // One ref on the group rather than one per bar: an inline ref callback is a+ // new function on every render, so React would detach and re-attach all+ // eighteen bars whenever the parent re-renders (a status word changing, an+ // interim transcript arriving) and the animation loop would be writing to+ // nulls for a frame.+ const row = useRef<SVGGElement>(null);+ const reduced = useReducedMotion();+ // Committed waveform history, kept across phase changes so the shape the+ // user just spoke is still on screen while the transcription runs.+ const history = useRef<number[]>([]);+ const head = useRef(0);+ const level = useRef(0);++ if (history.current.length !== count) {+ history.current = new Array<number>(count).fill(0);+ head.current = 0;+ }++ useEffect(() => {+ const group = row.current;+ if (!group) return;+ const rects = Array.from(group.children) as SVGRectElement[];+ const measured = MEASURED_PHASES.includes(phase);+ const sweepPeriod = SWEEP_PERIOD_S[phase] ?? 0;++ const paint = (heights: number[], opacities?: number[]) => {+ for (let i = 0; i < rects.length; i += 1) {+ const h = heights[i];+ if (h === undefined) continue;+ rects[i].setAttribute("y", String(PILL_CY - h / 2));+ rects[i].setAttribute("height", String(h));+ rects[i].setAttribute("opacity", String(opacities?.[i] ?? 1));+ }+ };++ // At rest nothing animates: "when nothing is happening, nothing is in the+ // bar" — the same rule the desktop overlay follows.+ if (phase === "idle" || phase === "error") {+ level.current = 0;+ paint(new Array<number>(count).fill(BAR_MIN_H));+ return;+ }++ let raf = 0;+ let last = performance.now();+ let painted = last;+ let carryMs = 0;+ let sweepPhase = 0;++ const frame = (now: number) => {+ raf = requestAnimationFrame(frame);+ const dt = Math.min((now - last) / 1000, MAX_FRAME_S);+ last = now;++ if (measured) {+ level.current = smoothLevel(level.current, clamp01(levelRef.current), dt);+ }++ if (reduced) {+ // Reduced motion keeps the INFORMATION (a level meter that follows the+ // voice) and drops the decoration: no scrolling and no sweep.+ if (now - painted < REDUCED_PAINT_MS) return;+ painted = now;+ paint(new Array<number>(count).fill(barHeight(measured ? level.current : 0.2)));+ return;+ }++ if (!measured) {+ sweepPhase = sweepPeriod > 0 ? (sweepPhase + dt / sweepPeriod) % 1 : 0;+ const heights: number[] = [];+ const opacities: number[] = [];+ for (let i = 0; i < count; i += 1) {+ const gain = sweepGain(i, count, sweepPhase);+ heights.push(barHeight(0.12 + 0.58 * gain));+ opacities.push(0.35 + 0.65 * gain);+ }+ paint(heights, opacities);+ return;+ }++ // Advance the scroll on a WALL-CLOCK cadence, not once per frame, so the+ // row travels at the same speed on a 60 Hz and a 144 Hz display.+ carryMs += dt * 1000;+ while (carryMs >= COLUMN_MS) {+ carryMs -= COLUMN_MS;+ history.current[head.current] = level.current;+ head.current = (head.current + 1) % count;+ }++ const heights: number[] = [];+ for (let i = 0; i < count; i += 1) {+ heights.push(barHeight(ringValue(history.current, head.current, i)));+ }+ // The newest column tracks the live level between advances, so the onset+ // of a word shows up on the frame its sample arrives instead of waiting+ // out the rest of the column.+ const newest = barHeight(level.current);+ if (newest > (heights[count - 1] ?? 0)) heights[count - 1] = newest;+ paint(heights);+ };++ raf = requestAnimationFrame(frame);+ return () => cancelAnimationFrame(raf);+ }, [count, levelRef, phase, reduced]);++ const tone = PHASE_TONE[phase];+ const w = barWidth(count);++ return (+ <svg+ viewBox={`0 0 ${VIEW_W} ${VIEW_H}`}+ className={cn("h-11 w-full", className)}+ data-testid="voice-waveform"+ data-phase={phase}+ aria-hidden="true"+ >+ <rect+ x={PILL_X}+ y={PILL_Y}+ width={PILL_W}+ height={PILL_H}+ rx={PILL_R}+ strokeWidth={1.6}+ className={cn("fill-card", tone.rim)}+ style={{+ strokeOpacity: tone.rimOpacity,+ transition: "stroke 300ms ease, stroke-opacity 300ms ease",+ }}+ />+ <g+ ref={row}+ className={tone.bars}+ style={{+ opacity: tone.barsOpacity,+ transition: "opacity 300ms ease, fill 300ms ease",+ }}+ >+ {evenlySpaced(VIEW_W / 2, BAR_SPAN, count).map((x) => (+ <rect+ key={x}+ x={x - w / 2}+ y={PILL_CY - BAR_MIN_H / 2}+ width={w}+ height={BAR_MIN_H}+ rx={w / 2}+ />+ ))}+ </g>+ </svg>+ );+}++export const VoiceWaveform = memo(VoiceWaveformImpl);diff --git a/jarvis/ui/web/frontend/src/components/overlay/voiceBars.test.ts b/jarvis/ui/web/frontend/src/components/overlay/voiceBars.test.tsnew file mode 100644index 0000000000..9f57ec686e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/overlay/voiceBars.test.ts@@ -0,0 +1,113 @@+import { describe, expect, it } from "vitest";++import {+ BAR_MAX_H,+ BAR_MIN_H,+ PILL_W,+ PILL_X,+ VIEW_W,+ barHeight,+ barWidth,+ clamp01,+ evenlySpaced,+ ringValue,+ smoothLevel,+ sweepGain,+} from "./voiceBars";++describe("evenlySpaced", () => {+ it("centres the row on the pill instead of drifting off to one side", () => {+ const xs = evenlySpaced(VIEW_W / 2, 62, 7);+ expect((xs[0] + xs[xs.length - 1]) / 2).toBeCloseTo(VIEW_W / 2, 6);+ });++ it("keeps every stroke inside the pill", () => {+ const count = 18;+ const half = barWidth(count) / 2;+ for (const x of evenlySpaced(VIEW_W / 2, 62, count)) {+ expect(x - half).toBeGreaterThan(PILL_X);+ expect(x + half).toBeLessThan(PILL_X + PILL_W);+ }+ });++ it("puts a single item exactly on the centre", () => {+ expect(evenlySpaced(50, 62, 1)).toEqual([50]);+ });+});++describe("barHeight", () => {+ it("stays within the pill for any input, including nonsense", () => {+ for (const v of [-5, 0, 0.5, 1, 12, NaN]) {+ const h = barHeight(v);+ expect(h).toBeGreaterThanOrEqual(BAR_MIN_H);+ expect(h).toBeLessThanOrEqual(BAR_MAX_H);+ }+ });+});++describe("smoothLevel", () => {+ it("rises faster than it falls", () => {+ const up = smoothLevel(0, 1, 0.016);+ const down = 1 - smoothLevel(1, 0, 0.016);+ expect(up).toBeGreaterThan(down);+ });++ it("reaches the same place in the same TIME regardless of frame rate", () => {+ // The whole point of the dt-based easing: a 144 Hz monitor must not make+ // the visualizer twitchier than a 60 Hz one.+ let slow = 0;+ for (let i = 0; i < 6; i += 1) slow = smoothLevel(slow, 1, 1 / 60);+ let fast = 0;+ for (let i = 0; i < 15; i += 1) fast = smoothLevel(fast, 1, 1 / 150);+ expect(fast).toBeCloseTo(slow, 3);+ });++ it("snaps to dead zero so the row cannot wiggle in silence", () => {+ let level = 1;+ for (let i = 0; i < 200; i += 1) level = smoothLevel(level, 0, 0.016);+ expect(level).toBe(0);+ });++ it("survives a zero or negative frame delta without moving", () => {+ expect(smoothLevel(0.4, 1, 0)).toBe(0.4);+ expect(smoothLevel(0.4, 1, -1)).toBe(0.4);+ });++ it("never leaves 0..1, whatever the meter reports", () => {+ expect(smoothLevel(0, 5, 1)).toBeLessThanOrEqual(1);+ expect(smoothLevel(0.5, -3, 1)).toBeGreaterThanOrEqual(0);+ });+});++describe("sweepGain", () => {+ it("peaks under the highlight and fades away from it", () => {+ expect(sweepGain(0, 10, 0)).toBeCloseTo(1, 6);+ expect(sweepGain(5, 10, 0)).toBeLessThan(0.1);+ });++ it("wraps around, so the highlight re-enters without a jump", () => {+ // Just past the right edge the leftmost bar must already be lighting up.+ expect(sweepGain(0, 10, 1.02)).toBeGreaterThan(sweepGain(5, 10, 1.02));+ expect(sweepGain(0, 10, 0)).toBeCloseTo(sweepGain(0, 10, 1), 6);+ });+});++describe("ringValue", () => {+ it("reads oldest-first so the newest sample sits at the right edge", () => {+ const history = [10, 20, 30];+ // head points at the slot to be overwritten next — the oldest one.+ expect([0, 1, 2].map((i) => ringValue(history, 1, i))).toEqual([20, 30, 10]);+ });++ it("is safe on an empty history and on out-of-range indices", () => {+ expect(ringValue([], 0, 0)).toBe(0);+ expect(ringValue([1, 2], -3, 0)).toBe(2);+ });+});++describe("clamp01", () => {+ it("treats a broken sample as silence rather than full scale", () => {+ expect(clamp01(NaN)).toBe(0);+ expect(clamp01(Infinity)).toBe(0);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/overlay/voiceBars.ts b/jarvis/ui/web/frontend/src/components/overlay/voiceBars.tsnew file mode 100644index 0000000000..41338224d5--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/overlay/voiceBars.ts@@ -0,0 +1,165 @@+/**+ * Geometry and smoothing math for the voice visualizer pill — pure, so both+ * the static style preview and the live visualizer draw the SAME graphic and+ * the animation math can be unit-tested without a DOM or an audio device.+ *+ * The numbers mirror the desktop JarvisBar renderer (``jarvis/ui/jarvisbar/+ * renderer.py``) so the web surface and the on-screen overlay read as one+ * product: a dark pill with a gold rim and a slim row of rounded strokes.+ * Only the palette differs — see ``OverlayStylePreviews`` for why.+ */++/** Preview/visualizer viewBox. Everything below is in these units. */+export const VIEW_W = 100;+export const VIEW_H = 40;++/** The pill: x 6..94, y 11..29 — a 88x18 rounded rectangle. */+export const PILL_X = 6;+export const PILL_Y = 11;+export const PILL_W = VIEW_W - 2 * PILL_X;+export const PILL_H = 18;+export const PILL_R = PILL_H / 2;+export const PILL_CY = PILL_Y + PILL_H / 2;++/** Bar row: centred in the pill, inset so no stroke ever touches the rim.+ *+ * 62 of the pill's 88 units — a touch wider than the desktop renderer's 0.62+ * fraction, because the desktop keeps that extra margin free for the hover+ * controls (close-X, mic toggle) it flanks the row with. The web pill carries+ * no controls, so the row may use the space. */+export const BAR_SPAN = 62;+export const BAR_MIN_H = 2.4;+export const BAR_MAX_H = 15;++/** Bar count of the live visualizer. Wide enough to read as a waveform, few+ * enough that every stroke stays a distinct ~2 px at the size the pill+ * renders in the sidebar. */+export const LIVE_BAR_COUNT = 18;++/** Static heights of the settings/onboarding thumbnail (unchanged look). */+export const PREVIEW_BAR_HEIGHTS = [6, 11, 15, 8, 14, 9, 7];++/** How often the live waveform advances by one column (ms).+ *+ * Time-based, NOT frame-based: the row must scroll at the same speed on a+ * 60 Hz laptop and a 144 Hz monitor. ~33 ms matches the capture worklet's+ * ~30 Hz level cadence, so every column is one real measurement rather than an+ * interpolated in-between. */+export const COLUMN_MS = 33;++/** Bar stroke width for a given count, sized so the gaps stay even. */+export function barWidth(count: number): number {+ if (count <= 1) return 3;+ // Half the pitch, capped so a short row does not turn into fat blocks.+ return Math.min(3, (BAR_SPAN / (count - 1)) * 0.5);+}++/** X-positions of ``n`` items centred on ``cx`` across ``span``.+ *+ * The direct counterpart of ``renderer.evenly_spaced``; the preview used to+ * hard-code ``24 + i * 8``, which left its row 2 units off the pill's centre. */+export function evenlySpaced(cx: number, span: number, n: number): number[] {+ if (n <= 1) return [cx];+ const x0 = cx - span / 2;+ const step = span / (n - 1);+ return Array.from({ length: n }, (_, i) => x0 + i * step);+}++export function clamp01(value: number): number {+ if (!Number.isFinite(value)) return 0;+ return value < 0 ? 0 : value > 1 ? 1 : value;+}++/** Map a 0..1 level to a bar height inside the pill. */+export function barHeight(value: number): number {+ return BAR_MIN_H + (BAR_MAX_H - BAR_MIN_H) * clamp01(value);+}++/** Attack/release time constants (seconds) of the displayed level. */+export const ATTACK_TAU_S = 0.045;+export const RELEASE_TAU_S = 0.18;++/**+ * Ease ``current`` toward ``target`` over ``dtS`` seconds.+ *+ * Frame-rate independent on purpose: the exponential is evaluated against the+ * REAL elapsed time, so the same voice produces the same visible rise on a+ * 60 Hz and a 144 Hz display. A fixed per-frame factor (what the desktop+ * renderer can afford, because it drives its own fixed-cadence loop) would+ * make the browser visualizer twice as twitchy on a high-refresh monitor.+ *+ * Asymmetric like the desktop bar: the rise is near-instant so a syllable+ * registers on the frame its sample arrives, the fall is slower so the row+ * does not flicker between words — and a target of zero snaps all the way+ * down, because a sub-visible tail otherwise keeps the bars wiggling in+ * silence.+ */+export function smoothLevel(+ current: number,+ target: number,+ dtS: number,+ attackTauS: number = ATTACK_TAU_S,+ releaseTauS: number = RELEASE_TAU_S,+): number {+ const to = clamp01(target);+ if (!Number.isFinite(dtS) || dtS <= 0) return clamp01(current);+ const tau = to > current ? attackTauS : releaseTauS;+ if (tau <= 0) return to;+ const next = current + (to - current) * (1 - Math.exp(-dtS / tau));+ return to <= 0 && next < 0.01 ? 0 : clamp01(next);+}++/** Gaussian width of the travelling activity highlight, in row fractions. */+export const SWEEP_WIDTH = 0.16;++/**+ * Brightness of bar ``index`` under a highlight sitting at ``phase`` (0..1).+ *+ * This is the "we are working on it" motion — used whenever there IS activity+ * but no measured level to draw: connecting, transcribing, and the assistant's+ * own reply. The distinction is deliberate and load-bearing: a scrolling+ * waveform claims "this is your voice, measured right now", so it is only ever+ * drawn from real microphone samples. Anything unmeasured gets the sweep+ * instead, which promises motion and nothing more.+ *+ * The distance is measured around a ring, so the highlight leaves on the right+ * and re-enters on the left without a visible jump.+ */+export function sweepGain(+ index: number,+ count: number,+ phase: number,+ width: number = SWEEP_WIDTH,+): number {+ if (count <= 1) return 1;+ const pos = index / (count - 1);+ const wrapped = phase - Math.floor(phase);+ let d = Math.abs(pos - wrapped);+ if (d > 0.5) d = 1 - d;+ return Math.exp(-(d * d) / (2 * width * width));+}++/** Seconds one sweep needs to cross the row, per phase. Each phase gets its+ * own tempo so the three unmeasured states stay distinguishable at a glance:+ * a brisk sweep while work is in flight, a calm one while the reply plays. */+export const SWEEP_PERIOD_S: Record<string, number> = {+ connecting: 1.6,+ working: 1.05,+ speaking: 2.2,+};++/**+ * Read a scrolling history ring so index 0 is the OLDEST column and+ * ``count - 1`` the newest — the newest sample enters at the right edge and+ * the row travels left, the way a voice memo draws itself.+ */+export function ringValue(+ history: readonly number[],+ head: number,+ index: number,+): number {+ const n = history.length;+ if (n === 0) return 0;+ const at = (((head + index) % n) + n) % n;+ return history[at] ?? 0;+}diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsxindex 94eead3e24..767ba78ca5 100644--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.test.tsx@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { useEventStore } from "@/store/events";-import { BrowserRealtimeControl } from "./BrowserRealtimeControl";+import { BrowserRealtimeControl, waveformPhase } from "./BrowserRealtimeControl";const fakes = vi.hoisted(() => ({native: false,@@ -60,7 +60,11 @@ describe("BrowserRealtimeControl", () => {fakes.disconnect.mockClear();fakes.supportIssue = null;fakes.callbacks = null;- useEventStore.setState({ voiceState: "idle" });+ useEventStore.setState({+ voiceState: "idle",+ transcription: "",+ transcriptionFinal: true,+ });});it("is hidden in the desktop shell to prevent a second microphone", () => {@@ -110,6 +114,58 @@ describe("BrowserRealtimeControl", () => {expect(fakes.connect).not.toHaveBeenCalled();});+ it("shows the live visualizer only once the microphone is actually open", async () => {+ render(<BrowserRealtimeControl />);+ expect(screen.queryByTestId("voice-waveform")).toBeNull();++ fireEvent.click(screen.getByRole("button", { name: "sidebar.realtime_start" }));+ await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(1));++ expect(screen.getByTestId("voice-waveform").getAttribute("data-phase")).toBe(+ "listening",+ );+ });++ it("swaps the measured waveform for the activity sweep once the turn is committed", async () => {+ render(<BrowserRealtimeControl />);+ fireEvent.click(screen.getByRole("button", { name: "sidebar.realtime_start" }));+ await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(1));++ act(() => fakes.callbacks?.onStatus?.("thinking", {}));++ expect(screen.getByTestId("voice-waveform").getAttribute("data-phase")).toBe(+ "working",+ );+ expect(screen.getByText(/sidebar\.realtime_working/)).toBeTruthy();+ });++ it("names the transcription while interim words are still arriving", async () => {+ render(<BrowserRealtimeControl />);+ fireEvent.click(screen.getByRole("button", { name: "sidebar.realtime_start" }));+ await waitFor(() => expect(fakes.connect).toHaveBeenCalledTimes(1));++ act(() => {+ useEventStore.setState({ transcription: "wie spät", transcriptionFinal: false });+ });++ expect(screen.getByText(/sidebar\.realtime_transcribing/)).toBeTruthy();+ // The microphone is still open, so the pill keeps drawing real samples.+ expect(screen.getByTestId("voice-waveform").getAttribute("data-phase")).toBe(+ "listening",+ );+ });++ it("maps every connection/voice combination onto exactly one look", () => {+ expect(waveformPhase("idle", "idle")).toBe("idle");+ expect(waveformPhase("connecting", "idle")).toBe("connecting");+ expect(waveformPhase("error", "listening")).toBe("error");+ // A voice-side error must reach the pill even when the socket is fine.+ expect(waveformPhase("connected", "error")).toBe("error");+ expect(waveformPhase("connected", "listening")).toBe("listening");+ expect(waveformPhase("connected", "thinking")).toBe("working");+ expect(waveformPhase("connected", "speaking")).toBe("speaking");+ });+it("disables browser voice with HTTPS guidance on an insecure origin", () => {fakes.supportIssue = "secure_context";render(<BrowserRealtimeControl />);diff --git a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsxindex 711e2fd144..1c2bde2e65 100644--- a/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx+++ b/jarvis/ui/web/frontend/src/components/voice/BrowserRealtimeControl.tsx@@ -1,6 +1,7 @@import { useCallback, useEffect, useRef, useState } from "react";import { Loader2, Mic, MicOff, RotateCcw } from "lucide-react";+import { VoiceWaveform, type WaveformPhase } from "@/components/overlay/VoiceWaveform";import { useCapabilities } from "@/hooks/useCapabilities";import { useVoiceMode } from "@/hooks/useVoiceMode";import { useT } from "@/i18n";@@ -10,11 +11,33 @@ import {RealtimeAudioSupportError,type BrowserRealtimeSupportIssue,} from "@/lib/realtimeAudio";-import { useEventStore } from "@/store/events";+import { useEventStore, type VoiceState } from "@/store/events";import { cn } from "@/lib/utils";type ConnectionState = "idle" | "connecting" | "connected" | "error";+/** Map the socket state plus the shared voice state onto one visualizer look.+ *+ * Kept as a pure function so the mapping is testable and lives in exactly one+ * place: which look the pill shows is a claim about what the microphone and+ * the session are doing, and a second copy of that logic would eventually+ * claim something different from this one. */+export function waveformPhase(+ state: ConnectionState,+ voiceState: VoiceState,+): WaveformPhase {+ if (state === "error") return "error";+ if (state === "connecting") return "connecting";+ if (state !== "connected") return "idle";+ if (voiceState === "error") return "error";+ // The turn was committed: the transcription and then the reply are in+ // flight, and the microphone feed has stopped — so there is nothing left to+ // measure and the pill switches from the waveform to the activity sweep.+ if (voiceState === "thinking") return "working";+ if (voiceState === "speaking") return "speaking";+ return "listening";+}+/** Browser-owned microphone control for remote/headless installations.** The desktop shell already owns the physical microphone through@@ -28,10 +51,17 @@ export function BrowserRealtimeControl() {const { mode, realtimeAvailable } = useVoiceMode();const setVoice = useEventStore((store) => store.setVoice);const setTranscription = useEventStore((store) => store.setTranscription);+ const voiceState = useEventStore((store) => store.voiceState);+ const transcriptionFinal = useEventStore((store) => store.transcriptionFinal);+ const transcription = useEventStore((store) => store.transcription);const [state, setState] = useState<ConnectionState>("idle");const [effectiveProvider, setEffectiveProvider] = useState("");const [error, setError] = useState("");- const [inputLevel, setInputLevel] = useState(0);+ // The microphone level lands in a ref, not in state: it arrives ~30 times a+ // second and only the animation loop consumes it. Routing it through+ // setState re-rendered this control (and everything it renders) at 30 Hz to+ // repaint a five-segment meter.+ const levelRef = useRef(0);const clientRef = useRef<RealtimeAudioClient | null>(null);const browserSurface = capabilities.data?.native_file_actions === false;const visible = browserSurface && mode === "realtime";@@ -56,7 +86,7 @@ export function BrowserRealtimeControl() {setState("idle");setEffectiveProvider("");setError("");- setInputLevel(0);+ levelRef.current = 0;setVoice("idle");}, [setVoice]);@@ -76,7 +106,9 @@ export function BrowserRealtimeControl() {setError("");setVoice("speaking");},- onInputLevel: setInputLevel,+ onInputLevel: (value) => {+ levelRef.current = value;+ },onStatus: (status, payload) => {if (status === "audio_ready") {const provider = typeof payload.provider === "string" ? payload.provider : "";@@ -154,6 +186,19 @@ export function BrowserRealtimeControl() {? t("sidebar.realtime_retry"): t("sidebar.realtime_start");const Icon = connecting ? Loader2 : connected ? MicOff : state === "error" ? RotateCcw : Mic;+ const phase = waveformPhase(state, voiceState);+ // Name what the pill is doing. The waveform says "something is happening";+ // this says WHICH something, which is the part a screen reader gets too —+ // the visualizer itself is aria-hidden because a scrolling row of bars has+ // nothing to announce.+ const progressKey =+ phase === "working"+ ? "sidebar.realtime_working"+ : phase === "speaking"+ ? "sidebar.realtime_speaking"+ : transcription && !transcriptionFinal+ ? "sidebar.realtime_transcribing"+ : "sidebar.realtime_listening";return (<div className="mt-2 rounded-md border border-border/70 bg-background/50 p-2">@@ -179,24 +224,16 @@ export function BrowserRealtimeControl() {/><span>{connecting ? t("sidebar.realtime_connecting") : label}</span></button>- {connected && (- <div className="mt-1.5 flex h-1.5 items-stretch gap-0.5" aria-hidden="true">- {[0.08, 0.24, 0.42, 0.6, 0.78].map((threshold) => (- <span- key={threshold}- className={cn(- "flex-1 rounded-sm transition-colors duration-75",- inputLevel >= threshold ? "bg-primary" : "bg-border/60",- )}- />- ))}+ {(connected || connecting) && (+ <div className="mt-1.5">+ <VoiceWaveform levelRef={levelRef} phase={phase} /></div>)}<div className="mt-1.5 min-h-4 text-[10px] text-muted-foreground" aria-live="polite">{error ||(supportIssue ? supportMessage(supportIssue) : "") ||(connected- ? `${t("sidebar.realtime_connected")} ${effectiveProvider}`.trim()+ ? [t(progressKey), effectiveProvider].filter(Boolean).join(" · "): t("sidebar.realtime_browser_hint"))}</div></div>diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex b545755fc4..48c9114b08 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -389,7 +389,10 @@"realtime_stop": "Realtime-Sprache beenden","realtime_retry": "Realtime-Sprache erneut versuchen","realtime_connecting": "Verbindung wird hergestellt…",- "realtime_connected": "Verbunden über",+ "realtime_listening": "Hört zu…",+ "realtime_transcribing": "Wird transkribiert…",+ "realtime_working": "Wird verarbeitet…",+ "realtime_speaking": "Spricht…","realtime_browser_hint": "Auf diesem Gerät verwendet dein Browser das Mikrofon.","realtime_browser_unavailable": "Realtime-Sprache ist in diesem Browser nicht verfügbar","realtime_https_required": "Browser-Sprache benötigt HTTPS (oder localhost). Öffne diesen Server über einen HTTPS-Reverse-Proxy.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex caaf88f72a..d13fc625ae 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -389,7 +389,10 @@"realtime_stop": "Stop Realtime Voice","realtime_retry": "Retry Realtime Voice","realtime_connecting": "Connecting…",- "realtime_connected": "Connected via",+ "realtime_listening": "Listening…",+ "realtime_transcribing": "Transcribing…",+ "realtime_working": "Working on it…",+ "realtime_speaking": "Speaking…","realtime_browser_hint": "Your browser owns the microphone on this device.","realtime_browser_unavailable": "Realtime Voice is unavailable in this browser","realtime_https_required": "Browser voice requires HTTPS (or localhost). Open this server through an HTTPS reverse proxy.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex ea07025780..d880e349ba 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -389,7 +389,10 @@"realtime_stop": "Detener Voz en Tiempo Real","realtime_retry": "Reintentar Voz en Tiempo Real","realtime_connecting": "Conectando…",- "realtime_connected": "Conectado mediante",+ "realtime_listening": "Escuchando…",+ "realtime_transcribing": "Transcribiendo…",+ "realtime_working": "Procesando…",+ "realtime_speaking": "Hablando…","realtime_browser_hint": "Tu navegador controla el micrófono en este dispositivo.","realtime_browser_unavailable": "La voz en tiempo real no está disponible en este navegador","realtime_https_required": "La voz del navegador requiere HTTPS (o localhost). Abre este servidor mediante un proxy inverso HTTPS.",