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..c9a69aa646 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, @@ -64,6 +112,8 @@ pub(crate) struct Call { /// An agent of `viewer` to seat in the existing `room`, signing as itself. #[serde(default)] agent: Option, + #[serde(default)] + diagnostics: bool, } #[derive(Clone, Serialize)] @@ -80,6 +130,13 @@ pub(crate) enum Update { peer: String, samples: Vec, }, + Diagnostic { + peer: String, + #[serde(rename = "packetsSkipped")] + packets_skipped: u64, + #[serde(rename = "jitterRejected")] + jitter_rejected: u64, + }, Ended { error: Option, }, @@ -462,7 +519,7 @@ async fn seat_agent( participants: connection.peers.values().cloned().collect(), }) .map_err(|_| "Huddle view closed")?; - audio::run(connection, pcm, stop.clone(), updates, &touched).await + audio::run(connection, pcm, stop.clone(), updates, &touched, false).await } async fn run( @@ -534,6 +591,7 @@ async fn run( stop.clone(), updates, &touched, + call.diagnostics, ) .await }.await; @@ -596,7 +654,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(()) } @@ -622,6 +682,7 @@ mod tests { parent: uuid::Uuid::new_v4().to_string(), room: None, agent: None, + diagnostics: false, }; let _ = admit_membership(&community.host, &community.fi, &call).await; let heads = server.heads().await; @@ -726,6 +787,7 @@ mod tests { parent: uuid::Uuid::new_v4().to_string(), room: None, agent: None, + diagnostics: false, }; let updates = Channel::new(|_| panic!("Cancelled admission must not connect")); let (stop, cancelled) = watch::channel(false); @@ -918,6 +980,7 @@ mod tests { parent: uuid::Uuid::new_v4().to_string(), room: Some(uuid::Uuid::new_v4().to_string()), agent: Some(agent.pubkey.clone()), + diagnostics: false, }; validate(&call).unwrap(); let (_stop, stop) = watch::channel(false); @@ -971,6 +1034,7 @@ mod tests { parent: uuid::Uuid::new_v4().to_string(), room: None, agent: None, + diagnostics: false, }; assert!(validate(&call).is_ok()); call.community = "https://relay.example/other".into(); diff --git a/src-tauri/src/relay/huddle/audio.rs b/src-tauri/src/relay/huddle/audio.rs index 54136bf8f5..9d30630ea9 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,36 +275,52 @@ 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, }) } - fn insert(&mut self, frame: &[u8], peers: &Peers) -> Result<()> { + fn insert<'a>( + &mut self, + frame: &[u8], + peers: &'a Peers, + ) -> Result> { if frame.len() > 4009 { - return Ok(()); + return Ok(None); } let Some((index, header, payload)) = parse_relay_frame(frame) else { - return Ok(()); + return Ok(None); }; let Some(peer) = peers.get(&index) else { - return Ok(()); + return Ok(None); }; if self.only.as_ref().is_some_and(|only| only != peer) { - return Ok(()); + return Ok(None); } if let std::collections::btree_map::Entry::Vacant(entry) = self.receivers.entry(index) { entry.insert(Receiver { jitter: PeerJitterBuffer::new(index) .map_err(|e| format!("Audio decoder unavailable: {e}"))?, last_packet: tokio::time::Instant::now(), + seq: None, }); } + let mut lost = 0; + let mut rejected = false; 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 { + lost = u64::from(skipped.saturating_sub(1)); + super::Drops::add(&self.drops.lost, lost); + receiver.seq = Some(header.seq); + } // Malformed or excessively late media must not end the call. if receiver .jitter @@ -311,9 +328,12 @@ impl Codec { .is_ok() { receiver.last_packet = tokio::time::Instant::now(); + } else { + rejected = true; + super::Drops::add(&self.drops.rejected, 1); } } - Ok(()) + Ok((lost > 0 || rejected).then_some((peer.as_str(), lost, rejected))) } fn play( &mut self, @@ -372,6 +392,7 @@ pub(super) async fn run( mut stop: watch::Receiver, updates: &Channel, touched: &std::sync::atomic::AtomicU64, + diagnostics: bool, ) -> Result<()> { ensure_authorized(connection.expires_at, &connection.cancellation)?; let (mut sink, mut socket) = connection @@ -388,6 +409,9 @@ pub(super) async fn run( heartbeat.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); let mut playout = tokio::time::interval(Duration::from_millis(10)); playout.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Burst); + let mut diagnostic_samples = BTreeMap::::new(); + let mut flush_diagnostics = tokio::time::interval(Duration::from_secs(1)); + flush_diagnostics.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); let mut last_received = tokio::time::Instant::now(); authorization_guard(expires_at, &authorization_cancellation, async { // Writes queue to their own future, so a stalled send never blocks @@ -419,11 +443,23 @@ pub(super) async fn run( if last_received.elapsed() > Duration::from_secs(30) { return Err("Huddle connection timed out. You can join again.".into()); } let _ = out.try_send(Message::Ping(now().to_be_bytes().to_vec().into())); } + _ = flush_diagnostics.tick(), if diagnostics => { + for (peer, (packets_skipped, jitter_rejected)) in std::mem::take(&mut diagnostic_samples) { + // Diagnostics are optional and never end a Huddle. + let _ = updates.send(Update::Diagnostic { peer, packets_skipped, jitter_rejected }); + } + } packet = socket.next() => { last_received = tokio::time::Instant::now(); match packet { Some(Ok(Message::Binary(frame))) => { - codec.insert(&frame, &peers)?; + if let Some((peer, packets_skipped, jitter_rejected)) = + codec.insert(&frame, &peers)?.filter(|_| diagnostics) + { + let sample = diagnostic_samples.entry(peer.to_owned()).or_default(); + sample.0 += packets_skipped; + sample.1 += u64::from(jitter_rejected); + } } Some(Ok(Message::Text(text))) => { let value: Value = serde_json::from_str(&text).map_err(|_| "Invalid Huddle update")?; @@ -466,7 +502,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); + } } } } @@ -647,6 +685,7 @@ mod tests { stop, &updates, &touched, + false, ) .await }); @@ -723,7 +762,14 @@ mod tests { }; let ended = tokio::time::timeout( Duration::from_secs(5), - run(connection, pcm, stop, &Channel::new(|_| Ok(())), &touched), + run( + connection, + pcm, + stop, + &Channel::new(|_| Ok(())), + &touched, + false, + ), ) .await .expect("a removed agent kept its seat"); @@ -822,6 +868,7 @@ mod tests { parent: uuid::Uuid::new_v4().to_string(), room: None, agent: None, + diagnostics: false, }; ( Relay(listener, acceptor), @@ -1036,7 +1083,7 @@ mod tests { super::super::super::lease_time(), )); let mut relay = socket; - let playing = run(seated, pcm, stopped, &updates, &touched); + let playing = run(seated, pcm, stopped, &updates, &touched, false); let relay_side = async { send( &mut relay, @@ -1195,7 +1242,13 @@ mod tests { codec.encoder.encode(&vec![0.1; FRAME_SAMPLES]).unwrap(), ] .concat(); - codec.insert(&frame, &peers).unwrap(); + assert!(codec.insert(&frame, &peers).unwrap().is_none()); + let _skipped = spoken(&mut codec, 1); + let next = spoken(&mut codec, 1); + assert_eq!( + codec.insert(&next, &peers).unwrap(), + Some((peers[&1].as_str(), 1, false)), + ); codec.joined( &mut peers, roster(&json!({"peers":[{"peer_index":3,"pubkey":"c".repeat(64)}]})).unwrap(), @@ -1329,7 +1382,7 @@ mod tests { let (resume, resuming) = oneshot::channel(); let owner = tokio::spawn(async move { let touched = std::sync::atomic::AtomicU64::new(super::super::lease_time()); - let running = run(connection, pcm, stopped, &updates, &touched); + let running = run(connection, pcm, stopped, &updates, &touched, false); tokio::pin!(running); // Suspend at an observable startup boundary without exposing a new // production pause hook. Network input has not been pre-peeked. @@ -1453,7 +1506,7 @@ mod tests { cancellation: CancellationToken::new(), seat: None, }; - let running = run(connection, pcm, stopped, &updates, &touched); + let running = run(connection, pcm, stopped, &updates, &touched, false); tokio::pin!(running); let _ = tokio::time::timeout(Duration::from_secs(1), &mut running).await; let pulls = heard.load(std::sync::atomic::Ordering::SeqCst); @@ -1492,7 +1545,7 @@ mod tests { cancellation: CancellationToken::new(), seat: None, }; - run(connection, pcm, stopped, &updates, &touched).await + run(connection, pcm, stopped, &updates, &touched, false).await }); let wire = |frame: &[u8]| { let (header, _) = FrameHeader::parse(frame).unwrap(); 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..81ad6ffee2 --- /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/runtime.ts b/src/bundled/codex/runtime.ts index aa10fb9c31..9e47c6d1b7 100644 --- a/src/bundled/codex/runtime.ts +++ b/src/bundled/codex/runtime.ts @@ -2183,6 +2183,7 @@ export class CodexRuntime { thinking(); }, settings.voice, + seat.diagnostic, ); signal.throwIfAborted(); if (settings.scope === "community") diff --git a/src/bundled/codex/voice.test.ts b/src/bundled/codex/voice.test.ts index cea3190cef..244cb1a3d5 100644 --- a/src/bundled/codex/voice.test.ts +++ b/src/bundled/codex/voice.test.ts @@ -71,6 +71,7 @@ function fixture(resume = Promise.resolve()) { onconnectionstatechange: () => {}, ontrack: (_event: { track: { kind: string } }) => {}, close: vi.fn(), + getStats: vi.fn(async (): Promise> => new Map()), addTrack: vi.fn(), createDataChannel: vi.fn(() => events), createOffer: async () => ({ type: "offer", sdp: "offer" }), @@ -130,6 +131,7 @@ function fixture(resume = Promise.resolve()) { const open = ( send: (samples: number[]) => Promise = output, voice?: string, + diagnostic?: (event: unknown) => void, ) => openVoice( rpc as unknown as AppServer, @@ -140,6 +142,7 @@ function fixture(resume = Promise.resolve()) { "instructions", thinking, voice, + diagnostic, ); return { open, @@ -169,6 +172,40 @@ it("keeps incoming WebRTC audio decoding and releases its muted sink on close", expect(f.decoder.pause).toHaveBeenCalledOnce(); expect(f.decoder.srcObject).toBeNull(); }); +it("reports new Codex audio concealment with its sampling window", async () => { + vi.useFakeTimers(); + const f = fixture(); + const diagnostic = vi.fn(); + const inbound = (concealmentEvents: number, concealedSamples: number) => + new Map([ + [ + "audio", + { + type: "inbound-rtp", + kind: "audio", + concealmentEvents, + concealedSamples, + }, + ], + ]); + f.peer.getStats + .mockResolvedValueOnce(inbound(3, 4800)) + .mockResolvedValueOnce(inbound(5, 5760)); + const connection = await f.open(f.output, undefined, diagnostic); + await vi.advanceTimersByTimeAsync(1000); + expect(diagnostic).not.toHaveBeenCalled(); + const fromMs = Date.now(); + await vi.advanceTimersByTimeAsync(1000); + expect(diagnostic).toHaveBeenCalledExactlyOnceWith({ + kind: "codex-webrtc", + fromMs, + detectedAtMs: fromMs + 1000, + concealmentEvents: 2, + concealedMs: 20, + packetsLost: 0, + }); + await connection.close(); +}); it("forwards output while the seat is busy and cuts it on close", async () => { const f = fixture(); const connection = await f.open(); diff --git a/src/bundled/codex/voice.ts b/src/bundled/codex/voice.ts index f055404f21..3a2ed387f1 100644 --- a/src/bundled/codex/voice.ts +++ b/src/bundled/codex/voice.ts @@ -1,4 +1,8 @@ import captureUrl from "../../features/huddle/capture.worklet.js?url&no-inline"; +import { + huddleAudio, + type VoiceDiagnostic, +} from "../../features/huddle/diagnostics"; import { createPlayout } from "../../features/huddle/playout"; import type { AppServer } from "./rpc"; @@ -12,6 +16,7 @@ export async function openVoice( instructions: string, thinking?: (active: boolean) => void, voice?: string, + diagnostic?: (event: VoiceDiagnostic) => void, ) { signal.throwIfAborted(); const peer = new RTCPeerConnection(); @@ -38,12 +43,88 @@ 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(); + }); + let readingStats = false; + let stats: ReturnType | undefined; + const totals = new Map< + string, + { + atMs: number; + packets: number; + packetsLost: number; + concealmentEvents: number; + concealedSamples: number; + } + >(); + async function receiveStats() { + if (readingStats) return; + readingStats = true; + try { + const reports = await peer.getStats(); + if (closed) return; + const atMs = Date.now(); + for (const [id, report] of reports.entries()) { + if (report.type !== "inbound-rtp" || report.kind !== "audio") continue; + const next = { + atMs, + packets: report.packetsReceived ?? 0, + packetsLost: report.packetsLost ?? 0, + concealmentEvents: report.concealmentEvents ?? 0, + concealedSamples: + (report.concealedSamples ?? 0) - + (report.silentConcealedSamples ?? 0), + }; + const previous = totals.get(id); + totals.set(id, next); + if (!previous) continue; + const packetsLost = Math.max( + 0, + next.packetsLost - previous.packetsLost, + ); + const concealmentEvents = Math.max( + 0, + next.concealmentEvents - previous.concealmentEvents, + ); + const concealedMs = Math.max( + 0, + Math.round((next.concealedSamples - previous.concealedSamples) / 48), + ); + huddleAudio.count( + "codex webrtc", + "packets", + next.packets - previous.packets, + ); + huddleAudio.count("codex webrtc", "packets lost", packetsLost); + huddleAudio.count("codex webrtc", "concealments", concealmentEvents); + huddleAudio.count("codex webrtc", "concealed ms", concealedMs); + if (packetsLost || concealmentEvents || concealedMs) + diagnostic?.({ + kind: "codex-webrtc", + fromMs: previous.atMs, + detectedAtMs: atMs, + packetsLost, + concealmentEvents, + concealedMs, + }); + } + } finally { + readingStats = false; + } + } + if (huddleAudio.enabled || diagnostic) + stats = setInterval(() => void receiveStats().catch(() => {}), 1000); 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(); @@ -94,9 +175,39 @@ export async function openVoice( if (closed) throw new Error("Voice connection closed"); if (context.sampleRate !== 48000) throw new Error("Agent voice requires 48 kHz audio"); - capture = new AudioWorkletNode(context, "buzz-huddle-capture"); - capture.port.onmessage = ({ data }: MessageEvent) => { + capture = new AudioWorkletNode(context, "buzz-huddle-capture", { + processorOptions: { measureChannels: huddleAudio.enabled }, + }); + let decodedChannels: number | undefined; + let lastFrame: number | undefined; + capture.port.onmessage = ({ + data, + }: MessageEvent>) => { if (closed) return; + if (!(data instanceof Float32Array)) { + if (data.channels !== decodedChannels) { + decodedChannels = data.channels; + console.debug( + "[huddle audio] Codex decoded channels", + decodedChannels, + ); + } + huddleAudio.measure("codex decoded channels", data); + return; + } + huddleAudio.frame("codex decoded", 50); + if (diagnostic) { + const now = performance.now(); + const gap = now - (lastFrame ?? now); + lastFrame = now; + if (gap > 50 && gap <= 1000) + diagnostic({ + kind: "codex-decoded-gap", + detectedAtMs: Date.now(), + durationMs: Math.round(gap), + }); + } + if (local()) return; // The Huddle seat owns bounded buffering and serial native sends. void output(Array.from(data)).catch(fail); }; @@ -106,9 +217,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/bundled/huddles/index.tsx b/src/bundled/huddles/index.tsx index 8e2f7013ec..cbe99fee32 100644 --- a/src/bundled/huddles/index.tsx +++ b/src/bundled/huddles/index.tsx @@ -9,6 +9,7 @@ import { createHuddleRing } from "../../features/huddle/ring"; import type { PluginModule } from "../../plugins/api"; import { nativeHuddles } from "../../features/huddle/bridge"; import { openHuddleAudio } from "../../features/huddle/audio"; +import { registerHuddlePlayoutTool } from "../../features/huddle/playout-tool"; import { createHuddles, provideHuddleStatus, @@ -35,6 +36,7 @@ export const apply: PluginModule["apply"] = (ctx) => { (connection, destination) => dmVoiceAgent(connection, destination, ctx.agents)?.pubkey, ); + registerHuddlePlayoutTool(ctx.agents, huddles); const remoteVoices = remoteDmVoiceCalls(ctx.relay, ctx.agents); const stopVoices = createHuddleVoices( withRemoteDmVoiceCalls(huddles, remoteVoices), @@ -45,6 +47,7 @@ export const apply: PluginModule["apply"] = (ctx) => { if (remoteVoices.snapshot().id === call) huddles.remoteVoiceError(error); else huddles.voiceError(call, error); }, + huddles.voiceDiagnostic, ); provideHuddleStatus(ctx, huddles); const stopRing = createHuddleRing(huddles); diff --git a/src/features/agents/service.ts b/src/features/agents/service.ts index 67792984ee..57680dc8ef 100644 --- a/src/features/agents/service.ts +++ b/src/features/agents/service.ts @@ -1,3 +1,4 @@ +import type { VoiceDiagnostic } from "../huddle/diagnostics"; import type { PublishOptions } from "../../buzz-mcp/client"; import { followUpQueue } from "../messages/follow-up-queue"; import type { @@ -1093,6 +1094,7 @@ export type AgentVoiceSeat = Readonly< ended(error?: Error): void; /** Presentation only; never authorizes work. */ thinking?(active: boolean): void; + diagnostic?(event: VoiceDiagnostic): void; } & Pick, "config" | "revisions" | "synced" | "team"> >; diff --git a/src/features/huddle/audio.ts b/src/features/huddle/audio.ts index 103c118f68..0ca929d682 100644 --- a/src/features/huddle/audio.ts +++ b/src/features/huddle/audio.ts @@ -3,7 +3,7 @@ import { type HuddleAudioSettings, } from "./audio-settings"; import workletUrl from "./capture.worklet.js?url&no-inline"; -import { createPlayout } from "./playout"; +import { createPlayout, type PlayoutEvent } from "./playout"; export type HuddleAudio = { settings?: HuddleAudioSettings; @@ -16,9 +16,15 @@ export type OpenHuddleAudio = ( send: (samples: number[]) => void, ended: () => void, signal: AbortSignal, + report?: (peer: string, event: PlayoutEvent) => void, ) => Promise; -export const openHuddleAudio: OpenHuddleAudio = async (send, ended, signal) => { +export const openHuddleAudio: OpenHuddleAudio = async ( + send, + ended, + signal, + report, +) => { if (!navigator.mediaDevices?.getUserMedia) throw new Error("Microphone access is unavailable in this app."); const context = new AudioContext({ @@ -169,7 +175,13 @@ 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)}`, + report && ((event) => report(peer, event)), + ); playback.set(peer, entry); } entry.play(samples); diff --git a/src/features/huddle/bridge.ts b/src/features/huddle/bridge.ts index b1f7a72556..bc97281b4f 100644 --- a/src/features/huddle/bridge.ts +++ b/src/features/huddle/bridge.ts @@ -1,4 +1,5 @@ import { Channel, invoke, isTauri } from "@tauri-apps/api/core"; +import { huddleAudio } from "./diagnostics"; import { relayOrigin } from "../communities/destination"; export type HuddleDestination = Readonly<{ @@ -12,6 +13,12 @@ export type HuddleUpdate = | { type: "connected"; room: string; participants: string[] } | { type: "participants"; participants: string[] } | { type: "audio"; peer: string; samples: number[] } + | { + type: "diagnostic"; + peer: string; + packetsSkipped: number; + jitterRejected: number; + } | { type: "ended"; error: string | null }; export type HuddleBridge = { available: boolean; @@ -39,6 +46,7 @@ export const nativeHuddles: HuddleBridge = { parent: destination.channelId, room: room ?? null, agent: agent ?? null, + diagnostics: huddleAudio.enabled && !agent, }, updates, }); @@ -47,3 +55,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/capture.worklet.js b/src/features/huddle/capture.worklet.js index 5ff0f9dffd..79265f5be9 100644 --- a/src/features/huddle/capture.worklet.js +++ b/src/features/huddle/capture.worklet.js @@ -2,7 +2,68 @@ class HuddleCapture extends AudioWorkletProcessor { frame = new Float32Array(960); offset = 0; + + constructor(options) { + super(); + if (options?.processorOptions?.measureChannels) this.resetLevels(0); + } + + resetLevels(channels) { + this.levels = { + channels, + samples: 0, + left: 0, + right: 0, + average: 0, + difference: 0, + }; + } + + measure(input) { + const channels = input.length; + if (this.levels.channels !== channels) this.resetLevels(channels); + const levels = this.levels; + const [left, right] = input; + if (!left) return; + for (let i = 0; i < left.length; i++) { + const l = left[i]; + levels.left += l * l; + if (right) { + const r = right[i]; + const average = (l + r) / 2; + const difference = (l - r) / 2; + levels.right += r * r; + levels.average += average * average; + levels.difference += difference * difference; + } + } + levels.samples += left.length; + if (levels.samples < 12000) return; + const db = (energy) => + Math.round(10 * Math.log10(Math.max(1e-12, energy / levels.samples))); + const leftLevel = db(levels.left); + const rightLevel = right ? db(levels.right) : -120; + // Hold the latest speech levels through pauses so they can be read after a reply. + if ( + channels !== this.reportedChannels || + Math.max(leftLevel, rightLevel) > -70 + ) { + this.port.postMessage({ + channels, + "channel 1 dBFS": leftLevel, + ...(right && { + "channel 2 dBFS": rightLevel, + "average dBFS": db(levels.average), + "difference dBFS": db(levels.difference), + }), + }); + this.reportedChannels = channels; + } + this.resetLevels(channels); + } + process(inputs) { + if (this.levels && inputs[0]?.length) this.measure(inputs[0]); const input = inputs[0]?.[0]; if (input) { for (const value of input) { diff --git a/src/features/huddle/capture.worklet.test.ts b/src/features/huddle/capture.worklet.test.ts new file mode 100644 index 0000000000..6317f3b9df --- /dev/null +++ b/src/features/huddle/capture.worklet.test.ts @@ -0,0 +1,57 @@ +import { expect, it } from "vitest"; +import { runInNewContext } from "node:vm"; +import source from "./capture.worklet.js?raw"; + +type Levels = Record; + +function capture(channels: number[][]) { + const levels: Levels[] = []; + const frames: number[][] = []; + runInNewContext(source, { + AudioWorkletProcessor: class { + port = { + postMessage: (message: Float32Array | Levels) => { + if (ArrayBuffer.isView(message)) frames.push(Array.from(message)); + else levels.push(message); + }, + }; + }, + registerProcessor: ( + _name: string, + Capture: new (options: { + processorOptions: { measureChannels: boolean }; + }) => { process(inputs: Float32Array[][]): void }, + ) => { + const worklet = new Capture({ + processorOptions: { measureChannels: true }, + }); + for (const input of channels) { + const block = input.map((value) => new Float32Array(128).fill(value)); + for (let i = 0; i < 94; i++) worklet.process([block]); + } + }, + }); + return { levels, frames }; +} + +it("reports cancellation in an average while continuing to send channel one", () => { + const { levels, frames } = capture([ + [0.5, -0.5], + [0, 0], + ]); + expect(levels).toEqual([ + { + channels: 2, + "channel 1 dBFS": -6, + "channel 2 dBFS": -6, + "average dBFS": -120, + "difference dBFS": -6, + }, + ]); + expect(frames[0]).toEqual(Array(960).fill(0.5)); +}); + +it("measures the decoded mono channel without reporting a stereo average", () => { + const { levels } = capture([[0.5]]); + expect(levels).toEqual([{ channels: 1, "channel 1 dBFS": -6 }]); +}); diff --git a/src/features/huddle/diagnostics.ts b/src/features/huddle/diagnostics.ts new file mode 100644 index 0000000000..b71051e2b8 --- /dev/null +++ b/src/features/huddle/diagnostics.ts @@ -0,0 +1,84 @@ +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>; + +export type VoiceDiagnostic = Readonly< + { detectedAtMs: number } & ( + | { + kind: "codex-webrtc"; + fromMs: number; + packetsLost: number; + concealmentEvents: number; + concealedMs: number; + } + | { kind: "codex-decoded-gap"; durationMs: number } + | { kind: "agent-send-drop" } + | { kind: "native-relay"; packetsSkipped: number; jitterRejected: number } + ) +>; + +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); + }, + measure(stage: string, values: Record) { + if (developerMode) stages.set(stage, values); + }, + 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-tool.ts b/src/features/huddle/playout-tool.ts new file mode 100644 index 0000000000..17e9d2fbbf --- /dev/null +++ b/src/features/huddle/playout-tool.ts @@ -0,0 +1,53 @@ +import type { Agents } from "../agents/service"; +import { relayOrigin } from "../communities/destination"; +import { huddleAudio } from "./diagnostics"; +import type { Huddles } from "./service"; + +export const huddlePlayoutToolName = "huddles_playout_events"; + +export function registerHuddlePlayoutTool( + agents: Pick, + huddles: Pick, +) { + if (!huddleAudio.enabled) return; + agents.addTool({ + name: huddlePlayoutToolName, + description: + "Read the last minute of audio diagnostics for your own voice in your owner's active Huddle. events lists relay playback underruns and queue discards. voiceEvents lists gaps in decoded Codex frames, WebRTC loss and audio concealment, sender queue drops, and native relay sequence skips and jitter rejections. Times are Unix milliseconds. The report includes the active playback mode and carries timing and counts only.", + inputSchema: { + type: "object", + properties: {}, + additionalProperties: false, + }, + async call(client, context, args) { + if (Object.keys(args).length) + throw new Error("This tool takes no arguments."); + const { destination, room } = huddles.snapshot(); + const agentsHere = agents.snapshot(); + const agent = + agentsHere.status === "ready" && + agentsHere.running.find( + (candidate) => + candidate.key === client.key && candidate.pubkey === client.pubkey, + ); + if ( + !destination || + !room || + context.channel !== room || + !agent || + agent.place !== "here" || + agent.owner !== destination.viewer || + relayOrigin(agent.relay) !== relayOrigin(destination.relayUrl) + ) + throw new Error( + "Playback events are only available in your owner's active Huddle.", + ); + const report = huddles.recentPlayout(room, client.pubkey); + if (!report) + throw new Error( + "Playback events are unavailable for your seat in this Huddle.", + ); + return JSON.stringify({ ...report, playback: huddleAudio.playback() }); + }, + }); +} diff --git a/src/features/huddle/playout.ts b/src/features/huddle/playout.ts index 471f38d0a6..009d6d6d58 100644 --- a/src/features/huddle/playout.ts +++ b/src/features/huddle/playout.ts @@ -1,3 +1,15 @@ +import { huddleAudio } from "./diagnostics"; + +export type PlayoutEvent = Readonly< + { + detectedAtMs: number; + durationMs: number; + } & ( + | { kind: "queue-limit"; queuedMs: number } + | { kind: "underrun"; estimatedGapStartMs: number } + ) +>; + /** * 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 +20,38 @@ export function createPlayout( context: BaseAudioContext, output: AudioNode, lead: number, + stage?: string, + report?: (event: PlayoutEvent) => void, ) { 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 !== undefined && next > now + 0.2) { + report?.({ + kind: "queue-limit", + detectedAtMs: Date.now(), + durationMs: samples.length / 48, + queuedMs: Math.round((next - now) * 1000), + }); + 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"); + const detectedAtMs = Date.now(); + report?.({ + kind: "underrun", + detectedAtMs, + estimatedGapStartMs: detectedAtMs - Math.round((now - next) * 1000), + durationMs: Math.round((now + 0.02 - next) * 1000), + }); + } + 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..2101da8441 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,8 @@ export function createPcmSender( send: (samples: number[]) => Promise, signal: AbortSignal, failed: (error: unknown) => void, + stage?: string, + dropped?: () => void, ) { const pending: number[][] = []; let sending = false; @@ -18,14 +22,21 @@ 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"); + 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.test.ts b/src/features/huddle/service.test.ts index e5f531db2b..041ac2e89d 100644 --- a/src/features/huddle/service.test.ts +++ b/src/features/huddle/service.test.ts @@ -13,6 +13,7 @@ import { createRelaySession } from "../relay/session"; import type { HuddleAudio, OpenHuddleAudio } from "./audio"; import type { HuddleBridge, HuddleDestination, HuddleUpdate } from "./bridge"; import { createHuddles, provideHuddleStatus } from "./service"; +import { huddleAudio } from "./diagnostics"; const viewerKey = keypair(); const relayKey = keypair(); @@ -199,6 +200,57 @@ describe("Huddle lifetime", () => { ]); await h.dispose(); }); + it("returns diagnostics for the requested voice in the active call only", async () => { + const restore = huddleAudio.enabled; + huddleAudio.enabled = true; + const h = harness(); + try { + await h.service.join(destination); + h.receive({ + type: "connected", + room: "room", + participants: ["agent", "other"], + }); + const call = h.service.snapshot().id; + if (!call) throw new Error("Expected an active call"); + const detectedAtMs = Date.now(); + h.service.voiceDiagnostic(call, "agent", { + kind: "codex-decoded-gap", + detectedAtMs, + durationMs: 85, + }); + h.service.voiceDiagnostic(call, "agent", { + kind: "agent-send-drop", + detectedAtMs: detectedAtMs - 61_000, + }); + h.service.voiceDiagnostic("stale", "agent", { + kind: "agent-send-drop", + detectedAtMs, + }); + h.receive({ + type: "diagnostic", + peer: "other", + packetsSkipped: 3, + jitterRejected: 1, + }); + expect(h.service.recentPlayout("room", "agent")?.voiceEvents).toEqual([ + { kind: "codex-decoded-gap", detectedAtMs, durationMs: 85 }, + ]); + expect(h.service.recentPlayout("room", "other")?.voiceEvents).toEqual([ + expect.objectContaining({ + kind: "native-relay", + packetsSkipped: 3, + jitterRejected: 1, + }), + ]); + expect(h.service.recentPlayout("wrong-room", "agent")).toBeUndefined(); + await h.service.leave(); + expect(h.service.recentPlayout("room", "agent")).toBeUndefined(); + } finally { + huddleAudio.enabled = restore; + await h.dispose(); + } + }); it.each(["not a member", "huddle has ended"])( "removes an unavailable candidate after relay admission rejection: %s", async (error) => { diff --git a/src/features/huddle/service.ts b/src/features/huddle/service.ts index 2b192aa1be..50b4f97737 100644 --- a/src/features/huddle/service.ts +++ b/src/features/huddle/service.ts @@ -8,6 +8,8 @@ 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, type VoiceDiagnostic } from "./diagnostics"; +import type { PlayoutEvent } from "./playout"; import type { Context } from "@deepseek-ai/cordis"; export type HuddleSnapshot = Readonly<{ @@ -36,7 +38,11 @@ type Attempt = { stopAccess?: () => void; stopAudioSettings?: () => void; sender: ReturnType; + playoutEvents?: { peer: string; event: PlayoutEvent }[]; + voiceEvents?: { peer: string; event: VoiceDiagnostic }[]; }; +const playoutWindowMs = 60_000; +const maxPlayoutEvents = 256; const idle: HuddleSnapshot = { phase: "idle", muted: false, participants: [] }; const message = (error: unknown) => error instanceof Error ? error.message : String(error); @@ -63,6 +69,18 @@ export function createHuddles( let closing: Promise | undefined; const listeners = new Set<() => void>(); const unavailable = new Set(); + function voiceDiagnostic(call: string, peer: string, event: VoiceDiagnostic) { + const voiceEvents = current?.voiceEvents; + if ( + !voiceEvents || + snapshot.id !== call || + snapshot.phase !== "connected" || + !snapshot.participants.includes(peer) + ) + return; + if (voiceEvents.length === maxPlayoutEvents) voiceEvents.shift(); + voiceEvents.push({ peer, event }); + } const update = (next: HuddleSnapshot) => { snapshot = next; if (next.phase !== "incoming") requests?.resetSelection(); @@ -281,16 +299,21 @@ export function createHuddles( : undefined; const id = crypto.randomUUID(); const abort = new AbortController(); + const playoutEvents: Attempt["playoutEvents"] = huddleAudio.enabled + ? [] + : undefined; const attempt: Attempt = { id, connection, abort, + ...(playoutEvents && { playoutEvents, voiceEvents: [] }), sender: createPcmSender( (samples) => bridge.send(id, samples), abort.signal, (error) => { if (valid(attempt)) void leave(message(error)); }, + "mic send", ), }; current = attempt; @@ -375,7 +398,17 @@ export function createHuddles( void leave(event.error ?? undefined, true); return; } + if (event.type === "diagnostic") { + voiceDiagnostic(attempt.id, event.peer, { + kind: "native-relay", + detectedAtMs: Date.now(), + packetsSkipped: event.packetsSkipped, + jitterRejected: event.jitterRejected, + }); + 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; @@ -434,6 +467,13 @@ export function createHuddles( ); }, attempt.abort.signal, + playoutEvents && + ((peer, event) => { + if (!valid(attempt) || snapshot.phase !== "connected") return; + if (playoutEvents.length === maxPlayoutEvents) + playoutEvents.shift(); + playoutEvents.push({ peer, event }); + }), ); if (!valid(attempt)) { audio.close(); @@ -501,6 +541,45 @@ export function createHuddles( }; return { snapshot: () => snapshot, + voiceDiagnostic, + recentPlayout(room: string | undefined, peer: string) { + if ( + !room || + snapshot.room !== room || + snapshot.phase !== "connected" || + !snapshot.participants.includes(peer) || + !current?.playoutEvents + ) + return undefined; + const readAtMs = Date.now(); + const events = current.playoutEvents + .filter( + (entry) => + entry.peer === peer && + entry.event.detectedAtMs >= readAtMs - playoutWindowMs, + ) + .map((entry) => entry.event); + const voiceEvents = (current.voiceEvents ?? []) + .filter( + (entry) => + entry.peer === peer && + entry.event.detectedAtMs >= readAtMs - playoutWindowMs, + ) + .map(({ event }) => event) + .sort((a, b) => a.detectedAtMs - b.detectedAtMs); + return { + readAtMs, + windowMs: playoutWindowMs, + events: events.slice(-40), + voiceEvents: voiceEvents.slice(-40), + voiceEventsTruncated: + current.voiceEvents?.length === maxPlayoutEvents || + voiceEvents.length > 40, + truncated: + current.playoutEvents.length === maxPlayoutEvents || + events.length > 40, + }; + }, voiceListening: voiceSeat("listening"), voiceThinking: voiceSeat("thinking"), remoteVoiceError(error: string) { diff --git a/src/features/huddle/voice.ts b/src/features/huddle/voice.ts index 1367e7f76d..61d5ea1615 100644 --- a/src/features/huddle/voice.ts +++ b/src/features/huddle/voice.ts @@ -9,6 +9,7 @@ import { relayOrigin } from "../communities/destination"; import type { RelayData } from "../relay/service"; import type { HuddleBridge, HuddleDestination } from "./bridge"; import type { Huddles } from "./service"; +import { huddleAudio, type VoiceDiagnostic } from "./diagnostics"; type Seat = { call: string; @@ -28,6 +29,7 @@ export function createHuddleVoices( relay: RelayData, bridge: HuddleBridge, report: (call: string, error: string) => void, + record?: Huddles["voiceDiagnostic"], ) { const seats = new Map(); let session = relay.snapshot().session; @@ -56,10 +58,20 @@ export function createHuddleVoices( `${agent.name}: ${error instanceof Error ? error.message : error || "Voice disconnected"}. Leave and rejoin the Huddle to retry.`, ); }; + const diagnostic = + huddleAudio.enabled && record + ? (event: VoiceDiagnostic) => { + if (!abort.signal.aborted) record(call, agent.pubkey, event); + } + : undefined; const sender = createPcmSender( (samples) => bridge.send(id, samples), abort.signal, fail, + "agent send", + diagnostic && + (() => + diagnostic({ kind: "agent-send-drop", detectedAtMs: Date.now() })), ); function stop() { if (closing) return closing; @@ -123,6 +135,7 @@ export function createHuddleVoices( huddles.voiceThinking(call, agent.pubkey, active); }, output: sender.send, + ...(diagnostic && { diagnostic }), }); if (abort.signal.aborted) await opened.close(); else { diff --git a/src/features/huddle/window.test.ts b/src/features/huddle/window.test.ts index 609525d79c..2ec151b71a 100644 --- a/src/features/huddle/window.test.ts +++ b/src/features/huddle/window.test.ts @@ -31,6 +31,8 @@ function harness() { voiceListening() {}, voiceThinking() {}, snapshot: () => snapshot, + recentPlayout: () => undefined, + voiceDiagnostic() {}, subscribe(fn) { listeners.add(fn); return () => {