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): paint voice mode's glow as a flowing aurora that rises with the voice
rubenluetke10-beep559a43da4196
diff --git a/jarvis/ui/web/frontend/src/components/home/VoiceGlow.test.tsx b/jarvis/ui/web/frontend/src/components/home/VoiceGlow.test.tsxnew file mode 100644index 0000000000..9f88bd7b5d--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/home/VoiceGlow.test.tsx@@ -0,0 +1,23 @@+import { render, screen } from "@testing-library/react";+import { describe, expect, it } from "vitest";++import { VoiceGlow } from "@/components/home/VoiceGlow";++describe("VoiceGlow", () => {+ it("falls back to the CSS light where WebGL does not exist", () => {+ // jsdom has no WebGLRenderingContext — the same as a GPU-less WebView.+ render(<VoiceGlow active />);+ const glow = screen.getByTestId("voice-glow");+ expect(glow.getAttribute("data-renderer")).toBe("css");+ expect(glow.hasAttribute("aria-hidden")).toBe(true);+ expect(glow.children).toHaveLength(3);+ });++ it("rests as a faint, still wash while no call is open", () => {+ render(<VoiceGlow active={false} />);+ for (const pool of Array.from(screen.getByTestId("voice-glow").children) as HTMLElement[]) {+ expect(pool.style.opacity).toBe("0.3");+ expect(pool.style.transform).toBe("translateX(-50%)");+ }+ });+});diff --git a/jarvis/ui/web/frontend/src/components/home/VoiceGlow.tsx b/jarvis/ui/web/frontend/src/components/home/VoiceGlow.tsxindex 54e985e3b0..ae80b1b104 100644--- a/jarvis/ui/web/frontend/src/components/home/VoiceGlow.tsx+++ b/jarvis/ui/web/frontend/src/components/home/VoiceGlow.tsx@@ -1,74 +1,262 @@-import { useEffect, useRef } from "react";+import { useEffect, useRef, useState } from "react";import { cn } from "@/lib/utils";import { readVoiceInputLevel } from "@/lib/voiceInputLevel";import { voiceOutputLevelRef } from "@/lib/voiceOutputLevel";+import { releaseWebglContext } from "@/hooks/useWebglSurface";+import { createGlowRenderer } from "@/components/home/voiceGlowRenderer";+import { createVoiceFollower } from "@/components/home/voiceFollower";/**- * The soft light behind voice mode's composer — the Claude app's voice glow,- * in this theme's one signal hue.+ * The light behind voice mode's composer — the Claude app's voice glow, in+ * this theme's one signal hue.*- * Three overlapping pools of accent light rise from the bottom edge, each- * drifting sideways on its own slow rhythm, so the light shimmers rather- * than sitting still. At rest (no call) it is a faint, motionless wash.- * While a call is open the pools drift gently; when someone speaks — you- * (the microphone level) or the assistant (the playback level), whichever- * is louder — they swell, brighten and sway wider, so the bottom of the- * page visibly moves with the voice. The levels are read on animation- * frames — no React state, no re-render per frame — and only while a call- * is open. Reduced motion keeps the light and drops the movement.+ * An aurora rises from the bottom edge: a soft haze with a flowing crest,+ * curtains of light drifting up through it, and a bright core along the+ * edge (components/home/voiceGlowRenderer, one WebGL shader). At rest (no+ * call) it is a faint, motionless wash. While a call is open it flows; when+ * someone speaks — you (the microphone level) or the assistant (the+ * playback level), whichever is louder — the light stands taller, flows+ * faster and its core flares with each syllable+ * (components/home/voiceFollower turns the raw level into those smooth+ * signals). Levels are read on animation frames — no React state, no+ * re-render per frame — and the loop stops once the light has settled after+ * a call. Reduced motion keeps the light and drops the movement.+ *+ * Where WebGL is unavailable, or the context is lost, the light falls back+ * to three CSS pools that move with the same signals.** Purely decorative: no pointer events, hidden from screen readers.*/export function VoiceGlow({ active }: { active: boolean }) {+ const [webgl, setWebgl] = useState(webglAvailable);+ return (+ <div+ aria-hidden+ data-testid="voice-glow"+ data-renderer={webgl ? "webgl" : "css"}+ className="pointer-events-none absolute inset-x-0 bottom-0 h-[38vh] overflow-hidden"+ >+ {webgl ? (+ <ShaderGlow active={active} onUnavailable={() => setWebgl(false)} />+ ) : (+ <CssGlow active={active} />+ )}+ </div>+ );+}++function webglAvailable(): boolean {+ return typeof window !== "undefined" && typeof window.WebGLRenderingContext !== "undefined";+}++function prefersReducedMotion(): boolean {+ return (+ typeof window.matchMedia === "function" &&+ window.matchMedia("(prefers-reduced-motion: reduce)").matches+ );+}++/** The loudest voice right now: the assistant's playback or your microphone. */+function currentVoiceLevel(now: number): number {+ return Math.max(voiceOutputLevelRef.current ?? 0, readVoiceInputLevel(now));+}++/** How long the light takes to come up when a call opens and to settle after. */+const POWER_TAU_S = 0.5;++/**+ * Contexts handed back one task after an unmount, so React's development+ * effect replay (same canvas, same context) can reclaim them first — the+ * same dance as hooks/useWebglSurface.+ */+const pendingReleases = new Map<HTMLCanvasElement, number>();++function ShaderGlow({ active, onUnavailable }: { active: boolean; onUnavailable: () => void }) {+ const canvasRef = useRef<HTMLCanvasElement | null>(null);+ const activeRef = useRef(active);+ const wakeRef = useRef<() => void>(() => {});+ const unavailableRef = useRef(onUnavailable);++ useEffect(() => {+ unavailableRef.current = onUnavailable;+ }, [onUnavailable]);++ useEffect(() => {+ activeRef.current = active;+ wakeRef.current();+ }, [active]);++ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ const pending = pendingReleases.get(canvas);+ if (pending !== undefined) {+ window.clearTimeout(pending);+ pendingReleases.delete(canvas);+ }+ const renderer = createGlowRenderer(canvas);+ if (!renderer) {+ unavailableRef.current();+ return;+ }++ const reduced = prefersReducedMotion();+ const follower = createVoiceFollower();+ let signals = { level: 0, pulse: 0 };+ // Flow time is ACCUMULATED (faster while someone speaks), never+ // computed as clock * speed(level): that form turned every change in+ // loudness into a jump of the whole pattern.+ let time = 12;+ let power = 0;+ let color: [number, number, number] = [61, 139, 255];+ let light = false;+ let sinceTheme = 0;+ let last = -1;+ let frame = 0;+ let running = false;++ const readTheme = () => {+ const channels = getComputedStyle(canvas)+ .getPropertyValue("--accent-rgb")+ .trim()+ .split(/[\s,]+/)+ .map(Number);+ if (channels.length >= 3 && channels.slice(0, 3).every(Number.isFinite)) {+ color = [channels[0], channels[1], channels[2]];+ }+ light = canvas.closest(".dark") === null;+ };+ const draw = () =>+ renderer.render({ time, level: signals.level, pulse: signals.pulse, power, light, color });++ const tick = (now: number) => {+ const dt = last < 0 ? 0 : Math.min(0.1, (now - last) / 1000);+ last = now;+ const live = activeRef.current;+ signals = follower.step(dt, live ? currentVoiceLevel(now) : 0);+ power += ((live ? 1 : 0) - power) * (1 - Math.exp(-dt / POWER_TAU_S));+ time += dt * (0.55 + signals.level * 1.4);+ sinceTheme += dt;+ if (sinceTheme > 0.5) {+ sinceTheme = 0;+ readTheme();+ }+ if (!live && power < 0.002 && signals.level < 0.002 && signals.pulse < 0.002) {+ // Settled after a call: one last resting frame, then no loop at all.+ power = 0;+ signals = { level: 0, pulse: 0 };+ draw();+ running = false;+ return;+ }+ draw();+ frame = requestAnimationFrame(tick);+ };++ const wake = () => {+ if (reduced || typeof requestAnimationFrame === "undefined") {+ power = activeRef.current ? 1 : 0;+ readTheme();+ draw();+ return;+ }+ if (running) return;+ running = true;+ last = -1;+ frame = requestAnimationFrame(tick);+ };+ wakeRef.current = wake;++ const fit = () => {+ const box = canvas.getBoundingClientRect();+ if (renderer.resize(box.width, box.height) && !running) draw();+ };+ readTheme();+ fit();+ draw();+ wake();++ const resizeObserver = typeof ResizeObserver !== "undefined" ? new ResizeObserver(fit) : null;+ resizeObserver?.observe(canvas);+ // A theme switch while the light rests must repaint the resting frame.+ const themeObserver =+ typeof MutationObserver !== "undefined"+ ? new MutationObserver(() => {+ readTheme();+ if (!running) draw();+ })+ : null;+ themeObserver?.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ["class", "style", "data-theme"],+ });++ // A lost context (GPU reset, the page out of contexts) would otherwise+ // leave Chromium's broken-canvas placeholder on screen. Claim the event+ // and hand over to the CSS light; a decorative glow is not worth a+ // rebuild dance.+ const onLost = (event: Event) => {+ event.preventDefault();+ cancelAnimationFrame(frame);+ running = false;+ unavailableRef.current();+ };+ canvas.addEventListener("webglcontextlost", onLost);++ return () => {+ wakeRef.current = () => {};+ cancelAnimationFrame(frame);+ running = false;+ resizeObserver?.disconnect();+ themeObserver?.disconnect();+ canvas.removeEventListener("webglcontextlost", onLost);+ renderer.dispose();+ pendingReleases.set(+ canvas,+ window.setTimeout(() => {+ pendingReleases.delete(canvas);+ releaseWebglContext(canvas);+ }, 0),+ );+ };+ }, []);++ return <canvas ref={canvasRef} className="absolute inset-0 h-full w-full" />;+}++/** The fallback: three pools of accent light that move with the same signals. */+function CssGlow({ active }: { active: boolean }) {const blobRefs = useRef<(HTMLDivElement | null)[]>([]);useEffect(() => {const blobs = blobRefs.current.filter((b): b is HTMLDivElement => b !== null);- const reduced =- typeof window.matchMedia === "function" &&- window.matchMedia("(prefers-reduced-motion: reduce)").matches;- if (!active || reduced || typeof requestAnimationFrame === "undefined") {+ if (!active || prefersReducedMotion() || typeof requestAnimationFrame === "undefined") {blobs.forEach((el) => {el.style.opacity = active ? "0.7" : "0.3";el.style.transform = "translateX(-50%)";});return;}- // Two cascaded smoothers: an envelope (quick rise, slow fall — a voice,- // not a meter) and a short glide on top of it, so the ~30 Hz level- // samples never reach the light as steps. Both are time-based, so the- // motion feels the same at 60 Hz, 144 Hz or after a dropped frame.- let envelope = 0;- let level = 0;+ const follower = createVoiceFollower();let last = -1;let frame = 0;- // Each pool's sway position is ACCUMULATED, never computed as- // sin(time * speed(level)). That form multiplied the level by the time- // since page load (thousands of seconds), so the smallest change in- // loudness threw every pool to a random spot on each frame — the- // jumping, glitching light. Accumulating keeps the path continuous: the- // voice only changes how fast the pools travel, never where they are.+ // Each pool's sway position is accumulated, for the same reason as the+ // shader's flow time: the voice changes how fast it travels, never where.const sway = BLOBS.map((b) => b.phase);const breath = BLOBS.map((b) => b.phase * 2);const tick = (now: number) => {const dt = last < 0 ? 0 : Math.min(0.1, (now - last) / 1000);last = now;- const target = Math.max(voiceOutputLevelRef.current ?? 0, readVoiceInputLevel(now));- envelope += (target - envelope) * (1 - Math.exp(-dt / (target > envelope ? 0.06 : 0.45)));- level += (envelope - level) * (1 - Math.exp(-dt / 0.12));- // Lift quiet speech so a normal voice visibly moves the light.- const voice = Math.min(1, Math.pow(level, 0.7));+ const voice = follower.step(dt, currentVoiceLevel(now)).level;BLOBS.forEach((b, i) => {const el = blobs[i];if (!el) return;- // Sway: a slow drift always, a little quicker and wider with the voice.sway[i] += dt * b.speed * (1 + voice * 1.2);breath[i] += dt * b.speed * 1.3;const x = Math.sin(sway[i]) * (b.drift + voice * 5);- // Breathing: each pool brightens and dims softly on its own.const glow = 0.5 + 0.5 * Math.sin(breath[i]);- el.style.opacity = String(Math.min(1, 0.5 + voice * 0.45 + glow * 0.08).toFixed(3));+ el.style.opacity = Math.min(1, 0.5 + voice * 0.45 + glow * 0.08).toFixed(3);el.style.transform =`translateX(calc(-50% + ${x.toFixed(2)}%)) ` +`scale(${(1 + voice * 0.1).toFixed(3)}, ${(1 + voice * b.lift).toFixed(3)})`;@@ -80,7 +268,7 @@ export function VoiceGlow({ active }: { active: boolean }) {}, [active]);return (- <div aria-hidden data-testid="voice-glow" className="pointer-events-none absolute inset-x-0 bottom-0 h-[38vh] overflow-hidden">+ <>{BLOBS.map((b, i) => (<divkey={i}@@ -106,7 +294,7 @@ export function VoiceGlow({ active }: { active: boolean }) {}}/>))}- </div>+ </>);}diff --git a/jarvis/ui/web/frontend/src/components/home/voiceFollower.test.ts b/jarvis/ui/web/frontend/src/components/home/voiceFollower.test.tsnew file mode 100644index 0000000000..bb42235832--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/home/voiceFollower.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";++import { createVoiceFollower } from "@/components/home/voiceFollower";++/** Feed `seconds` of a constant level at `hz` and return the last signals. */+function run(level: number, seconds: number, hz: number, follower = createVoiceFollower()) {+ let out = { level: 0, pulse: 0 };+ for (let i = 0; i < Math.round(seconds * hz); i++) out = follower.step(1 / hz, level);+ return out;+}++describe("createVoiceFollower", () => {+ it("rises quickly when someone starts speaking", () => {+ const out = run(0.5, 0.4, 60);+ expect(out.level).toBeGreaterThan(0.5);+ expect(out.pulse).toBeGreaterThan(0.6);+ });++ it("falls slower than it rises, so pauses between words do not drop the light", () => {+ const follower = createVoiceFollower();+ run(0.6, 1, 60, follower);+ const after = run(0, 0.15, 60, follower);+ expect(after.level).toBeGreaterThan(0.4);+ // The pulse tracks syllables and has already let go.+ expect(after.pulse).toBeLessThan(after.level);+ });++ it("moves the same at 60 Hz and 144 Hz", () => {+ const slow = run(0.4, 0.5, 60);+ const fast = run(0.4, 0.5, 144);+ expect(Math.abs(slow.level - fast.level)).toBeLessThan(0.01);+ expect(Math.abs(slow.pulse - fast.pulse)).toBeLessThan(0.01);+ });++ it("never steps by more than a sliver per frame on choppy input", () => {+ const follower = createVoiceFollower();+ let prev = follower.step(0, 0).level;+ let worst = 0;+ for (let i = 0; i < 600; i++) {+ const raw = i % 4 < 2 ? 0.8 : 0; // a level flipping every two frames+ const { level } = follower.step(1 / 60, raw);+ worst = Math.max(worst, Math.abs(level - prev));+ prev = level;+ }+ expect(worst).toBeLessThan(0.12);+ });++ it("treats a broken sample as silence", () => {+ const out = run(Number.NaN, 0.5, 60);+ expect(out).toEqual({ level: 0, pulse: 0 });+ });+});diff --git a/jarvis/ui/web/frontend/src/components/home/voiceFollower.ts b/jarvis/ui/web/frontend/src/components/home/voiceFollower.tsnew file mode 100644index 0000000000..513ba3bd9e--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/home/voiceFollower.ts@@ -0,0 +1,45 @@+/**+ * Turns the raw voice level (microphone or playback, ~30 samples a second)+ * into the two smooth signals voice mode's glow moves with.+ *+ * - `level` — the slow one: an envelope that rises quickly and falls slowly+ * (a voice, not a meter), then a short glide so sample steps never show.+ * It decides how high the light stands.+ * - `pulse` — the fast one: follows syllables, so the light's core flares+ * on each word and settles in the gaps.+ *+ * Every constant is a time constant in seconds and every step is+ * `1 - exp(-dt / tau)`, so the motion is the same at 60 Hz, 144 Hz or right+ * after a dropped frame. Quiet speech is lifted (`^0.7`) so a normal voice+ * visibly moves the light.+ */+export interface VoiceSignals {+ level: number;+ pulse: number;+}++const ATTACK_S = 0.06;+const RELEASE_S = 0.45;+const GLIDE_S = 0.12;+const PULSE_ATTACK_S = 0.03;+const PULSE_RELEASE_S = 0.18;++const approach = (from: number, to: number, dt: number, tau: number) =>+ from + (to - from) * (1 - Math.exp(-dt / tau));++export function createVoiceFollower(): {+ step(dt: number, target: number): VoiceSignals;+} {+ let envelope = 0;+ let glide = 0;+ let pulse = 0;+ return {+ step(dt, raw) {+ const target = Number.isFinite(raw) ? Math.min(1, Math.max(0, raw)) : 0;+ envelope = approach(envelope, target, dt, target > envelope ? ATTACK_S : RELEASE_S);+ glide = approach(glide, envelope, dt, GLIDE_S);+ pulse = approach(pulse, target, dt, target > pulse ? PULSE_ATTACK_S : PULSE_RELEASE_S);+ return { level: Math.pow(glide, 0.7), pulse: Math.pow(pulse, 0.7) };+ },+ };+}diff --git a/jarvis/ui/web/frontend/src/components/home/voiceGlowRenderer.ts b/jarvis/ui/web/frontend/src/components/home/voiceGlowRenderer.tsnew file mode 100644index 0000000000..c6a1ad0864--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/home/voiceGlowRenderer.ts@@ -0,0 +1,264 @@+/**+ * The WebGL half of voice mode's glow (components/home/VoiceGlow): one+ * full-surface fragment shader that paints an aurora rising from the bottom+ * edge.+ *+ * Layers, bottom to top of the maths:+ * - a HAZE whose crest is a domain-warped noise line, tallest in the middle+ * and sinking toward the sides; the voice lifts it;+ * - soft vertical CURTAINS drifting upward through the haze — the shimmer;+ * - a hot CORE hugging the bottom edge that flares with each syllable+ * (`pulse`, the fast envelope) while the haze follows the slower `level`.+ *+ * Colour is the theme's accent: deep in the haze, lifted toward white in the+ * core. On paper (light themes) the lift is smaller and the whole light+ * fainter, because there a glow reads as a tint, not a light source.+ *+ * The output is premultiplied alpha with a 1/255 dither, so the long dark+ * gradient never bands. It renders into a small backing store (the light is+ * soft, the browser's upscale costs nothing) — a few hundred thousand pixels+ * of cheap noise per frame.+ *+ * Built on raw WebGL 1 rather than three.js: one quad and one program do not+ * need a scene graph, and a WebGL 1 context exists on every GPU a WebView+ * runs on.+ */++const VERTEX = `+attribute vec2 aPos;+varying vec2 vUv;+void main() {+ vUv = aPos * 0.5 + 0.5;+ gl_Position = vec4(aPos, 0.0, 1.0);+}+`;++const FRAGMENT = `+#ifdef GL_FRAGMENT_PRECISION_HIGH+precision highp float;+#else+precision mediump float;+#endif+varying vec2 vUv;+uniform vec2 uRes;+uniform float uTime;+uniform float uLevel;+uniform float uPulse;+uniform float uPower;+uniform float uLight;+uniform float uSpan;+uniform vec3 uColor;++float hash(vec2 p) {+ p = fract(p * vec2(123.34, 456.21));+ p += dot(p, p + 45.32);+ return fract(p.x * p.y);+}++// Value noise over a lattice wrapped at 289 cells: still continuous (the+// wrap happens on whole lattice points), and the hash never sees a number+// large enough to lose its precision, however long a call runs.+float noise(vec2 p) {+ vec2 i = floor(p);+ vec2 f = p - i;+ i = mod(i, 289.0);+ vec2 u = f * f * (3.0 - 2.0 * f);+ float a = hash(i);+ float b = hash(mod(i + vec2(1.0, 0.0), 289.0));+ float c = hash(mod(i + vec2(0.0, 1.0), 289.0));+ float d = hash(mod(i + vec2(1.0, 1.0), 289.0));+ return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);+}++float fbm(vec2 p) {+ float v = 0.0;+ float a = 0.5;+ for (int i = 0; i < 4; i++) {+ v += a * noise(p);+ p = p * 2.03 + vec2(1.7, 9.2);+ a *= 0.5;+ }+ return v;+}++void main() {+ vec2 uv = vUv;+ float aspect = uRes.x / max(uRes.y, 1.0);+ float x = (uv.x - 0.5) * aspect;+ float y = uv.y;+ float t = uTime;++ vec2 q = vec2(+ fbm(vec2(x * 0.9 - t * 0.11, t * 0.07)),+ fbm(vec2(x * 0.9 + 3.1 + t * 0.09, 1.7 - t * 0.05))+ );+ float crest = fbm(vec2(x * 1.1 + q.x * 1.6 - t * 0.06, q.y * 1.4 + t * 0.12));++ float dx = (uv.x - 0.5) / uSpan;+ float dome = exp(-dx * dx * 1.4);++ float h = (0.34 + 0.42 * uLevel) * (0.6 + 0.8 * crest) * (0.3 + 0.7 * dome);+ float body = exp(-pow(y / max(h, 0.02), 1.35) * 1.7);++ float rays = smoothstep(0.2, 0.85, fbm(vec2(x * 2.6 + q.x * 2.2, y * 0.9 - t * 0.35)));+ float shimmer = 0.75 + 0.5 * rays;++ float core = exp(-y / (0.05 + 0.1 * uPulse)) * dome;++ float a = body * shimmer * (0.3 + 0.7 * dome) + core * (0.2 + 0.6 * uPulse);+ a *= (0.3 + 0.7 * uPower) * (0.65 + 0.55 * uLevel);+ a *= smoothstep(0.0, 0.12, uv.x) * (1.0 - smoothstep(0.88, 1.0, uv.x)) * (1.0 - smoothstep(0.45, 1.0, y));++ float lift = clamp(core * 0.8 + rays * body * 0.35, 0.0, 1.0);+ vec3 deep = uColor * (0.75 + 0.25 * uLight);+ vec3 bright = mix(uColor, vec3(1.0), 0.55 - 0.35 * uLight);+ vec3 col = mix(deep, bright, lift);++ a = a * (0.55 - 0.2 * uLight);+ a += (hash(gl_FragCoord.xy + fract(t)) - 0.5) / 255.0;+ a = clamp(a, 0.0, 1.0);+ gl_FragColor = vec4(col * a, a);+}+`;++export interface GlowFrame {+ /** Seconds of flow — accumulated by the caller, faster while someone speaks. */+ time: number;+ /** Slow voice level 0..1: how high the light stands. */+ level: number;+ /** Fast voice envelope 0..1: how hard the core flares. */+ pulse: number;+ /** 0 = resting wash, 1 = call open. */+ power: number;+ /** True on a light theme. */+ light: boolean;+ /** The accent, as 0..255 channels. */+ color: readonly [number, number, number];+}++export interface GlowRenderer {+ /** Match the backing store to the element's size. Returns true when it changed. */+ resize(cssWidth: number, cssHeight: number): boolean;+ render(frame: GlowFrame): void;+ /** Delete the GPU objects. The context itself is released by the caller. */+ dispose(): void;+}++/** Backing-store pixels per CSS pixel. The light is soft; the upscale is free. */+const RESOLUTION = 0.5;+/** Cap on the backing store's width, for very wide windows. */+const MAX_WIDTH = 900;+/** Half-width of the light's brightest part, in CSS pixels. */+const SPAN_PX = 520;++function compile(gl: WebGLRenderingContext, type: number, source: string): WebGLShader | null {+ const shader = gl.createShader(type);+ if (!shader) return null;+ gl.shaderSource(shader, source);+ gl.compileShader(shader);+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS) && !gl.isContextLost()) {+ console.warn("[voice-glow] shader failed to compile:", gl.getShaderInfoLog(shader));+ gl.deleteShader(shader);+ return null;+ }+ return shader;+}++/**+ * Build the renderer on `canvas`, or return null where WebGL is unavailable+ * (no GPU, a blocklisted driver, the page out of contexts) — the caller then+ * paints the CSS fallback.+ */+export function createGlowRenderer(canvas: HTMLCanvasElement): GlowRenderer | null {+ let gl: WebGLRenderingContext | null = null;+ try {+ gl = canvas.getContext("webgl", {+ alpha: true,+ premultipliedAlpha: true,+ antialias: false,+ depth: false,+ stencil: false,+ preserveDrawingBuffer: false,+ powerPreference: "low-power",+ });+ } catch (err) {+ console.warn("[voice-glow] WebGL context unavailable:", err);+ return null;+ }+ if (!gl || gl.isContextLost()) return null;++ const vs = compile(gl, gl.VERTEX_SHADER, VERTEX);+ const fs = compile(gl, gl.FRAGMENT_SHADER, FRAGMENT);+ const program = gl.createProgram();+ if (!vs || !fs || !program) return null;+ gl.attachShader(program, vs);+ gl.attachShader(program, fs);+ gl.linkProgram(program);+ gl.deleteShader(vs);+ gl.deleteShader(fs);+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {+ if (!gl.isContextLost()) {+ console.warn("[voice-glow] shader program failed to link:", gl.getProgramInfoLog(program));+ }+ gl.deleteProgram(program);+ return null;+ }++ // One triangle that covers the whole surface.+ const buffer = gl.createBuffer();+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);+ const aPos = gl.getAttribLocation(program, "aPos");++ const ctx = gl;+ const u = (name: string) => ctx.getUniformLocation(program, name);+ const uRes = u("uRes");+ const uTime = u("uTime");+ const uLevel = u("uLevel");+ const uPulse = u("uPulse");+ const uPower = u("uPower");+ const uLight = u("uLight");+ const uSpan = u("uSpan");+ const uColor = u("uColor");++ let cssWidth = 1;+ let cssHeight = 1;++ return {+ resize(width, height) {+ const scale = Math.min(RESOLUTION, MAX_WIDTH / Math.max(width, 1));+ const w = Math.max(1, Math.round(width * scale));+ const h = Math.max(1, Math.round(height * scale));+ cssWidth = Math.max(width, 1);+ cssHeight = Math.max(height, 1);+ if (canvas.width === w && canvas.height === h) return false;+ canvas.width = w;+ canvas.height = h;+ return true;+ },+ render(frame) {+ if (!gl || gl.isContextLost()) return;+ gl.viewport(0, 0, canvas.width, canvas.height);+ gl.useProgram(program);+ gl.bindBuffer(gl.ARRAY_BUFFER, buffer);+ gl.enableVertexAttribArray(aPos);+ gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);+ gl.uniform2f(uRes, cssWidth, cssHeight);+ gl.uniform1f(uTime, frame.time);+ gl.uniform1f(uLevel, frame.level);+ gl.uniform1f(uPulse, frame.pulse);+ gl.uniform1f(uPower, frame.power);+ gl.uniform1f(uLight, frame.light ? 1 : 0);+ gl.uniform1f(uSpan, Math.min(0.45, SPAN_PX / cssWidth));+ gl.uniform3f(uColor, frame.color[0] / 255, frame.color[1] / 255, frame.color[2] / 255);+ gl.clearColor(0, 0, 0, 0);+ gl.clear(gl.COLOR_BUFFER_BIT);+ gl.drawArrays(gl.TRIANGLES, 0, 3);+ },+ dispose() {+ if (!gl || gl.isContextLost()) return;+ gl.deleteBuffer(buffer);+ gl.deleteProgram(program);+ },+ };+}