From 2a7235b4ae67faf83df7eafe593f08ac9e46bfcb Mon Sep 17 00:00:00 2001 From: John Tennant Date: Mon, 23 Nov 2026 10:48:54 -0500 Subject: [PATCH 1/6] feat(huddle): add development audio diagnostics Developer settings gains a Huddle audio panel. It counts frames, gaps and drops at each hop and can play an agent's decoded Codex voice on this device's speaker instead of sending it through the relay, so the two playback paths can be compared on one call. It keeps counts and timings, never audio, and does nothing outside development. Counted hops: Codex WebRTC receive (getStats loss and concealment), decoded frame cadence, the page's send queue drops and IPC time, the native encoder and socket queue drops, jitter buffer rejects and sequence gaps, and the listener's receive cadence, playout drops and underruns. Co-authored-by: Simone <0828be588d5c9c4d092c5b1cf01761d5aef63d6b104807fd8e8284d517dd1a99@buzz.block.builderlab.xyz> Co-Authored-By: Claude Opus 5.5 Signed-off-by: John Tennant --- src-tauri/build.rs | 1 + src-tauri/capabilities/default.json | 1 + src-tauri/src/lib.rs | 3 +- src-tauri/src/relay.rs | 4 +- src-tauri/src/relay/huddle.rs | 52 ++++++++++++- src-tauri/src/relay/huddle/audio.rs | 16 +++- src/app/DeveloperSettings.tsx | 2 + src/app/HuddleAudioPanel.tsx | 111 ++++++++++++++++++++++++++++ src/bundled/codex/voice.ts | 43 ++++++++++- src/features/huddle/audio.ts | 7 +- src/features/huddle/bridge.ts | 4 + src/features/huddle/diagnostics.ts | 66 +++++++++++++++++ src/features/huddle/playout.ts | 13 +++- src/features/huddle/sender.ts | 13 +++- src/features/huddle/service.ts | 3 + src/features/huddle/voice.ts | 1 + 16 files changed, 328 insertions(+), 12 deletions(-) create mode 100644 src/app/HuddleAudioPanel.tsx create mode 100644 src/features/huddle/diagnostics.ts diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 61bc511f3e..87994f12ac 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -73,6 +73,7 @@ fn main() { "huddle_open", "huddle_close", "huddle_pcm", + "huddle_stats", "huddle_touch", "pairing_account", "pairing_start", diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 8b44edb6f1..e603f872af 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -9,6 +9,7 @@ "allow-huddle-open", "allow-huddle-close", "allow-huddle-pcm", + "allow-huddle-stats", "allow-huddle-touch", "allow-pairing-account", "allow-pairing-start", diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index d6a60fc234..ceb919324a 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -119,7 +119,7 @@ use relay::{ relay_upload_begin, relay_upload_cancel, relay_upload_chunk, relay_verify_signatures, relay_workflow_runs, }; -use relay::{huddle_close, huddle_open, huddle_pcm, huddle_touch, Huddles}; +use relay::{huddle_close, huddle_open, huddle_pcm, huddle_stats, huddle_touch, Huddles}; mod terminal; #[cfg(all(test, unix))] mod test_executable; @@ -766,6 +766,7 @@ fn commands() -> impl Fn(tauri::ipc::Invoke) -> bool + Sen huddle_open, huddle_close, huddle_pcm, + huddle_stats, huddle_touch, pairing::pairing_account, pairing::pairing_start, diff --git a/src-tauri/src/relay.rs b/src-tauri/src/relay.rs index 4905aa80d2..662298d95b 100644 --- a/src-tauri/src/relay.rs +++ b/src-tauri/src/relay.rs @@ -11,7 +11,9 @@ pub(crate) use agent::{ relay_agent_resolve, }; use base64::{engine::general_purpose::STANDARD, Engine}; -pub(crate) use huddle::{huddle_close, huddle_open, huddle_pcm, huddle_touch, Huddles}; +pub(crate) use huddle::{ + huddle_close, huddle_open, huddle_pcm, huddle_stats, huddle_touch, Huddles, +}; use serde::Serialize; use sha2::{Digest, Sha256}; use std::{ diff --git a/src-tauri/src/relay/huddle.rs b/src-tauri/src/relay/huddle.rs index 2452c4a7d8..d58e3eb699 100644 --- a/src-tauri/src/relay/huddle.rs +++ b/src-tauri/src/relay/huddle.rs @@ -44,6 +44,54 @@ impl Huddles { Ok(()) } } +/// Audio each native hop discarded, for development diagnostics: index 0 is +/// the person's own call, 1 an agent's seat. Counts only, never audio. +pub(super) struct Drops { + /// Frames from the page while the encoder queue was full. + pcm: AtomicU64, + /// Encoded frames while the WebSocket write queue was full. + socket: AtomicU64, + /// Received packets the jitter buffer refused, such as late ones. + rejected: AtomicU64, + /// Sequence numbers skipped between received packets. + lost: AtomicU64, +} +pub(super) static DROPS: [Drops; 2] = [Drops::new(), Drops::new()]; +impl Drops { + const fn new() -> Self { + Self { + pcm: AtomicU64::new(0), + socket: AtomicU64::new(0), + rejected: AtomicU64::new(0), + lost: AtomicU64::new(0), + } + } + pub(super) fn add(counter: &AtomicU64, value: u64) { + counter.fetch_add(value, Ordering::Relaxed); + } +} + +/// Native drop counts by call kind; `reset` zeroes them after reading. +#[tauri::command] +pub(crate) fn huddle_stats(reset: bool) -> Value { + let read = |counter: &AtomicU64| { + if reset { + counter.swap(0, Ordering::Relaxed) + } else { + counter.load(Ordering::Relaxed) + } + }; + let [person, agent] = DROPS.each_ref().map(|d| { + json!({ + "pcm queue dropped": read(&d.pcm), + "socket queue dropped": read(&d.socket), + "jitter rejected": read(&d.rejected), + "packets lost": read(&d.lost), + }) + }); + json!({ "native you": person, "native agent": agent }) +} + struct Active { /// The agent this call seats, or `None` for the person's own call. agent: Option, @@ -596,7 +644,9 @@ pub(crate) fn huddle_pcm( } let calls = huddles.0.lock().map_err(|_| "Huddles unavailable")?; if let Some(a) = calls.get(&id).filter(|a| !*a.stop.borrow()) { - let _ = a.pcm.try_send(samples); + if a.pcm.try_send(samples).is_err() { + Drops::add(&DROPS[a.agent.is_some() as usize].pcm, 1); + } } Ok(()) } diff --git a/src-tauri/src/relay/huddle/audio.rs b/src-tauri/src/relay/huddle/audio.rs index 54136bf8f5..e7bb34c47f 100644 --- a/src-tauri/src/relay/huddle/audio.rs +++ b/src-tauri/src/relay/huddle/audio.rs @@ -267,6 +267,7 @@ async fn open( struct Receiver { jitter: PeerJitterBuffer, last_packet: tokio::time::Instant, + seq: Option, } struct Codec { encoder: AudioEncoder, @@ -274,12 +275,14 @@ struct Codec { /// The only pubkey decoded, if any. Indices are reused, so it is checked /// on every frame, by pubkey, before any decoder exists. only: Option, + drops: &'static super::Drops, } impl Codec { fn new(only: Option) -> Result { Ok(Self { encoder: AudioEncoder::new()?, receivers: BTreeMap::new(), + drops: &super::DROPS[only.is_some() as usize], only, }) } @@ -301,9 +304,16 @@ impl Codec { jitter: PeerJitterBuffer::new(index) .map_err(|e| format!("Audio decoder unavailable: {e}"))?, last_packet: tokio::time::Instant::now(), + seq: None, }); } if let Some(receiver) = self.receivers.get_mut(&index) { + // Forward skips are lost packets; a backward one is reordering. + let skipped = receiver.seq.map_or(1, |last| header.seq.wrapping_sub(last)); + if skipped < 1000 { + super::Drops::add(&self.drops.lost, u64::from(skipped.saturating_sub(1))); + receiver.seq = Some(header.seq); + } // Malformed or excessively late media must not end the call. if receiver .jitter @@ -311,6 +321,8 @@ impl Codec { .is_ok() { receiver.last_packet = tokio::time::Instant::now(); + } else { + super::Drops::add(&self.drops.rejected, 1); } } Ok(()) @@ -466,7 +478,9 @@ pub(super) async fn run( samples = pcm.recv() => { let Some(samples) = samples else { break; }; let frame = codec.encoder.encode(&samples)?; - let _ = out.try_send(Message::Binary(frame.into())); + if out.try_send(Message::Binary(frame.into())).is_err() { + super::Drops::add(&codec.drops.socket, 1); + } } } } diff --git a/src/app/DeveloperSettings.tsx b/src/app/DeveloperSettings.tsx index dbac5bc475..b350c6bb22 100644 --- a/src/app/DeveloperSettings.tsx +++ b/src/app/DeveloperSettings.tsx @@ -13,6 +13,7 @@ import { } from "../features/developer/logging"; import { clientMetrics } from "../features/developer/client-metrics"; import { ClientMetricsPanel } from "./ClientMetricsPanel"; +import { HuddleAudioPanel } from "./HuddleAudioPanel"; import { SwitchPreferenceRow } from "../shared/design-system/ui/SwitchPreferenceRow"; import { importScenario, @@ -217,6 +218,7 @@ export function DeveloperSettings() { /> + ); diff --git a/src/app/HuddleAudioPanel.tsx b/src/app/HuddleAudioPanel.tsx new file mode 100644 index 0000000000..32778ae073 --- /dev/null +++ b/src/app/HuddleAudioPanel.tsx @@ -0,0 +1,111 @@ +import styles from "./DeveloperSettings.module.css"; +import { useEffect, useState, useSyncExternalStore } from "react"; +import { isTauri } from "@tauri-apps/api/core"; +import { Button } from "../shared/design-system/ui/Button"; +import { InlineHeader } from "../shared/design-system/ui/Header"; +import { SettingsGroup } from "../shared/design-system/ui/SettingsGroup"; +import { SwitchPreferenceRow } from "../shared/design-system/ui/SwitchPreferenceRow"; +import { huddleAudio, type AudioReport } from "../features/huddle/diagnostics"; +import { nativeHuddleStats } from "../features/huddle/bridge"; +import { writeClipboardText } from "../shared/clipboard"; + +async function read(reset = false): Promise { + if (reset) huddleAudio.reset(); + const native = isTauri() + ? await nativeHuddleStats(reset).catch(() => ({})) + : {}; + return { ...huddleAudio.report(), ...native }; +} + +/** Live Huddle audio counts at each hop, and the agent playback switch. */ +export function HuddleAudioPanel() { + const playback = useSyncExternalStore( + huddleAudio.subscribe, + huddleAudio.playback, + ); + const [report, setReport] = useState({}); + useEffect(() => { + let alive = true; + const update = () => + void read().then((next) => { + if (alive) setReport(next); + }); + update(); + const timer = setInterval(update, 1000); + return () => { + alive = false; + clearInterval(timer); + }; + }, []); + const rows = Object.entries(report).sort(([a], [b]) => a.localeCompare(b)); + return ( +
+
+ + + +
+ } + /> + + + + huddleAudio.setPlayback(local ? "local" : "relay") + } + /> + {rows.length ? ( +
+ + + {rows.map(([stage, counters]) => ( + + + + + ))} + +
{stage} + {Object.entries(counters) + .map(([name, value]) => `${name} ${value}`) + .join(" · ")} +
+
+ ) : ( +

+ Join a Huddle to see counts. +

+ )} +
+
+ ); +} diff --git a/src/bundled/codex/voice.ts b/src/bundled/codex/voice.ts index f055404f21..1f9f192cc6 100644 --- a/src/bundled/codex/voice.ts +++ b/src/bundled/codex/voice.ts @@ -1,4 +1,5 @@ import captureUrl from "../../features/huddle/capture.worklet.js?url&no-inline"; +import { huddleAudio } from "../../features/huddle/diagnostics"; import { createPlayout } from "../../features/huddle/playout"; import type { AppServer } from "./rpc"; @@ -38,12 +39,47 @@ export async function openVoice( const wait = (operation: Promise) => Promise.race([operation, cancelled]); let off = () => {}; + // Development: the decoder element plays the voice here instead of the relay. + const local = () => huddleAudio.playback() === "local"; + const offPlayback = huddleAudio.subscribe(() => { + if (decoder) decoder.muted = !local(); + }); + const stats = huddleAudio.enabled + ? setInterval(() => void receiveStats().catch(() => {}), 1000) + : undefined; + const totals: Record = {}; + async function receiveStats() { + for (const report of (await peer.getStats()).values()) { + if (report.type !== "inbound-rtp" || report.kind !== "audio") continue; + for (const [counter, value] of [ + ["packets", report.packetsReceived], + ["packets lost", report.packetsLost], + ["concealments", report.concealmentEvents], + [ + "concealed ms", + ((report.concealedSamples ?? 0) - + (report.silentConcealedSamples ?? 0)) / + 48, + ], + ] as const) { + if (typeof value !== "number") continue; + huddleAudio.count( + "codex webrtc", + counter, + Math.round(value - (totals[counter] ?? value)), + ); + totals[counter] = value; + } + } + } let rejectConnected!: (error: Error) => void; const close = () => { if (closed) return closing; closed = true; signal.removeEventListener("abort", close); off(); + offPlayback(); + clearInterval(stats); cancel(new Error("Voice connection closed")); rejectConnected(new Error("Voice connection closed")); peer.close(); @@ -97,6 +133,8 @@ export async function openVoice( capture = new AudioWorkletNode(context, "buzz-huddle-capture"); capture.port.onmessage = ({ data }: MessageEvent) => { if (closed) return; + huddleAudio.frame("codex decoded", 50); + if (local()) return; // The Huddle seat owns bounded buffering and serial native sends. void output(Array.from(data)).catch(fail); }; @@ -106,9 +144,10 @@ export async function openVoice( remote?.disconnect(); const stream = new MediaStream([track]); // Keep WebRTC decoding active even though the worklet, rather than a - // media element, consumes the sound. The element itself stays muted. + // media element, consumes the sound. The element stays muted unless + // development playback is local. decoder ??= new Audio(); - decoder.muted = true; + decoder.muted = !local(); decoder.srcObject = stream; void decoder.play().catch(fail); remote = context.createMediaStreamSource(stream); diff --git a/src/features/huddle/audio.ts b/src/features/huddle/audio.ts index 103c118f68..cb82add16d 100644 --- a/src/features/huddle/audio.ts +++ b/src/features/huddle/audio.ts @@ -169,7 +169,12 @@ export const openHuddleAudio: OpenHuddleAudio = async (send, ended, signal) => { if (closed) return; let entry = playback.get(peer); if (!entry) { - entry = createPlayout(context, output, 0.06); + entry = createPlayout( + context, + output, + 0.06, + `play ${peer.slice(0, 8)}`, + ); playback.set(peer, entry); } entry.play(samples); diff --git a/src/features/huddle/bridge.ts b/src/features/huddle/bridge.ts index b1f7a72556..b70a7bd766 100644 --- a/src/features/huddle/bridge.ts +++ b/src/features/huddle/bridge.ts @@ -47,3 +47,7 @@ export const nativeHuddles: HuddleBridge = { touch: (id) => invoke("huddle_touch", { id }), send: (id, samples) => invoke("huddle_pcm", { id, samples }), }; + +/** Development: native drop counts by call kind; `reset` zeroes them. */ +export const nativeHuddleStats = (reset = false) => + invoke>>("huddle_stats", { reset }); diff --git a/src/features/huddle/diagnostics.ts b/src/features/huddle/diagnostics.ts new file mode 100644 index 0000000000..60f10b460c --- /dev/null +++ b/src/features/huddle/diagnostics.ts @@ -0,0 +1,66 @@ +import { developerMode } from "../developer/mode"; + +/** Where an agent's decoded Codex voice plays: sent through the relay as + * usual, or straight to this device's speaker, bypassing the relay. */ +export type AgentPlayback = "relay" | "local"; +export type AudioReport = Record>; + +const stages = new Map>(); +const arrivals = new Map(); +const listeners = new Set<() => void>(); +let playback: AgentPlayback = "relay"; + +function bump(stage: string, counter: string, value: number, peak = false) { + const counters = stages.get(stage) ?? {}; + stages.set(stage, counters); + counters[counter] = peak + ? Math.max(counters[counter] ?? 0, value) + : (counters[counter] ?? 0) + value; +} + +/** Development only: counts Huddle audio frames, gaps and drops at each hop, + * and switches agent playback. Keeps counts and timings, never audio. Every + * call without a stage, or outside development, does nothing. */ +export const huddleAudio = { + enabled: developerMode, + /** A frame arrived. A gap over `budget` ms is late; one over a second is a + * pause, not a dropout. */ + frame(stage: string | undefined, budget: number) { + if (!developerMode || !stage) return; + const now = performance.now(); + const gap = now - (arrivals.get(stage) ?? now); + arrivals.set(stage, now); + bump(stage, "frames", 1); + if (gap > 1000) return bump(stage, "pauses", 1); + if (gap > budget) bump(stage, "late", 1); + bump(stage, "max gap ms", Math.round(gap), true); + }, + /** An operation took `ms`; over `budget` ms is slow. */ + took(stage: string | undefined, ms: number, budget: number) { + if (!developerMode || !stage) return; + bump(stage, "calls", 1); + if (ms > budget) bump(stage, "slow", 1); + bump(stage, "max ms", Math.round(ms), true); + }, + count(stage: string | undefined, counter: string, value = 1) { + if (developerMode && stage && value) bump(stage, counter, value); + }, + report: (): AudioReport => + Object.fromEntries([...stages].map(([key, value]) => [key, { ...value }])), + reset() { + stages.clear(); + arrivals.clear(); + }, + playback: () => playback, + setPlayback(next: AgentPlayback) { + if (!developerMode || next === playback) return; + playback = next; + for (const listener of listeners) listener(); + }, + subscribe(listener: () => void) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, +}; diff --git a/src/features/huddle/playout.ts b/src/features/huddle/playout.ts index 471f38d0a6..4bd13d84b6 100644 --- a/src/features/huddle/playout.ts +++ b/src/features/huddle/playout.ts @@ -1,3 +1,5 @@ +import { huddleAudio } from "./diagnostics"; + /** * Plays 48 kHz mono PCM frames back to back into `output`. The first frame * starts `lead` seconds out; after a true underrun playback re-anchors 20 ms @@ -8,16 +10,21 @@ export function createPlayout( context: BaseAudioContext, output: AudioNode, lead: number, + stage?: string, ) { const sources = new Set(); let next: number | undefined; return { play(samples: readonly number[]) { const now = context.currentTime; - if (!samples.length || samples.length > 5760 || (next ?? 0) > now + 0.2) - return; + if (!samples.length || samples.length > 5760) return; + if ((next ?? 0) > now + 0.2) + return huddleAudio.count(stage, "dropped ahead"); if (next === undefined) next = now + lead; - else if (next < now) next = now + 0.02; + else if (next < now) { + if (now - next < 1) huddleAudio.count(stage, "underruns"); + next = now + 0.02; + } const buffer = context.createBuffer(1, samples.length, 48000); buffer.copyToChannel(Float32Array.from(samples), 0); const source = context.createBufferSource(); diff --git a/src/features/huddle/sender.ts b/src/features/huddle/sender.ts index 693866b288..2a06247623 100644 --- a/src/features/huddle/sender.ts +++ b/src/features/huddle/sender.ts @@ -1,3 +1,5 @@ +import { huddleAudio } from "./diagnostics"; + /** Serial PCM delivery shared by microphones and agent voices. Keep the newest * four waiting 20 ms frames (80 ms), plus one in flight. This bounds retained * media, not time spent waiting for IPC. Already submitted frames cannot be @@ -6,6 +8,7 @@ export function createPcmSender( send: (samples: number[]) => Promise, signal: AbortSignal, failed: (error: unknown) => void, + stage?: string, ) { const pending: number[][] = []; let sending = false; @@ -18,14 +21,20 @@ export function createPcmSender( clear, async send(samples: number[]) { if (signal.aborted || broken) return; - if (pending.length === 4) pending.shift(); + if (pending.length === 4) { + pending.shift(); + huddleAudio.count(stage, "dropped"); + } pending.push(samples); if (sending) return; sending = true; try { while (!signal.aborted && pending.length) { const frame = pending.shift(); - if (frame) await send(frame); + if (!frame) continue; + const start = performance.now(); + await send(frame); + huddleAudio.took(stage, performance.now() - start, 20); } } catch (error) { broken = true; diff --git a/src/features/huddle/service.ts b/src/features/huddle/service.ts index 2b192aa1be..392d74d051 100644 --- a/src/features/huddle/service.ts +++ b/src/features/huddle/service.ts @@ -8,6 +8,7 @@ import { discoverHuddles } from "./discovery"; import type { RelayData, RelaySnapshot } from "../relay/service"; import type { HuddleBridge, HuddleDestination, HuddleUpdate } from "./bridge"; import type { HuddleAudio, OpenHuddleAudio } from "./audio"; +import { huddleAudio } from "./diagnostics"; import type { Context } from "@deepseek-ai/cordis"; export type HuddleSnapshot = Readonly<{ @@ -291,6 +292,7 @@ export function createHuddles( (error) => { if (valid(attempt)) void leave(message(error)); }, + "mic send", ), }; current = attempt; @@ -376,6 +378,7 @@ export function createHuddles( return; } if (event.type === "audio") { + huddleAudio.frame(`receive ${event.peer.slice(0, 8)}`, 30); activity(event.peer, event.samples); attempt.audio?.play(event.peer, event.samples); return; diff --git a/src/features/huddle/voice.ts b/src/features/huddle/voice.ts index 1367e7f76d..bec89427ab 100644 --- a/src/features/huddle/voice.ts +++ b/src/features/huddle/voice.ts @@ -60,6 +60,7 @@ export function createHuddleVoices( (samples) => bridge.send(id, samples), abort.signal, fail, + "agent send", ); function stop() { if (closing) return closing; From bb92efa091f7e1d134625d45162e468ae6a7ab60 Mon Sep 17 00:00:00 2001 From: John Tennant Date: Mon, 23 Nov 2026 11:00:24 -0500 Subject: [PATCH 2/6] feat(huddle): report decoded Codex audio channels Co-authored-by: Aaron Signed-off-by: John Tennant --- src/app/HuddleAudioPanel.tsx | 2 +- src/bundled/codex/voice.ts | 20 ++++++- src/features/huddle/capture.worklet.js | 61 +++++++++++++++++++++ src/features/huddle/capture.worklet.test.ts | 57 +++++++++++++++++++ src/features/huddle/diagnostics.ts | 3 + 5 files changed, 140 insertions(+), 3 deletions(-) create mode 100644 src/features/huddle/capture.worklet.test.ts diff --git a/src/app/HuddleAudioPanel.tsx b/src/app/HuddleAudioPanel.tsx index 32778ae073..81ad6ffee2 100644 --- a/src/app/HuddleAudioPanel.tsx +++ b/src/app/HuddleAudioPanel.tsx @@ -44,7 +44,7 @@ export function HuddleAudioPanel() {