@@ -22,6 +22,9 @@ const OPENAI_AUDIO_CHUNK_BYTES = 960;
2222const OPENAI_AUDIO_CHUNK_DELAY_MS = 5 ;
2323const OPENAI_AUDIO_ROUNDTRIP_TIMEOUT_MS = 60_000 ;
2424const OPENAI_AUDIO_TRAILING_SILENCE_MS = 750 ;
25+ // Match the shared TalkAudioLevel meter's -50 dBFS floor (TalkPlaybackLevelMeters.swift).
26+ const OPENAI_BROWSER_SPEECH_MIN_RMS = 10 ** ( - 50 / 20 ) ;
27+ const OPENAI_BROWSER_SPEECH_MIN_SECONDS = 0.1 ;
2528const GOOGLE_REALTIME_MODEL =
2629 process . env . OPENCLAW_REALTIME_GOOGLE_MODEL ?. trim ( ) || "gemini-3.1-flash-live-preview" ;
2730const GOOGLE_REALTIME_VOICE = process . env . OPENCLAW_REALTIME_GOOGLE_VOICE ?. trim ( ) || "Kore" ;
@@ -320,6 +323,8 @@ async function createOpenAIClientSecret(
320323 type : "realtime" ,
321324 model : OPENAI_REALTIME_MODEL ,
322325 audio : {
326+ // Synthetic microphone input must not compete with the requested spoken marker.
327+ input : { turn_detection : null } ,
323328 output : { voice : OPENAI_REALTIME_VOICE } ,
324329 } ,
325330 } ,
@@ -582,7 +587,14 @@ async function smokeOpenAIWebRtc(browser: Browser, apiKey: string): Promise<Smok
582587 await page . evaluate ( "globalThis.__name = (fn) => fn" ) ;
583588 await page . evaluate ( openAIRealtimeBrowserResponseReaderInitScript ( ) ) ;
584589 const result = await page . evaluate (
585- async ( { clientSecret : secret , sdpAnswerMaxBytes, timeoutMs } ) => {
590+ async ( {
591+ clientSecret : secret ,
592+ sdpAnswerMaxBytes,
593+ timeoutMs,
594+ audioTimeoutMs,
595+ minSpeechRms,
596+ minSpeechSeconds,
597+ } ) => {
586598 const readBoundedTextLocal = ( globalThis as OpenAIWebRtcSmokeGlobal )
587599 . openclawReadBoundedRealtimeResponseText ;
588600 if ( ! readBoundedTextLocal ) {
@@ -591,15 +603,16 @@ async function smokeOpenAIWebRtc(browser: Browser, apiKey: string): Promise<Smok
591603 const withBrowserTimeout = async < T > (
592604 label : string ,
593605 run : ( signal : AbortSignal ) => Promise < T > ,
606+ durationMs = timeoutMs ,
594607 ) : Promise < T > => {
595608 const controller = new AbortController ( ) ;
596609 let timeout : number | undefined ;
597610 const timeoutPromise = new Promise < T > ( ( _resolve , reject ) => {
598611 timeout = window . setTimeout ( ( ) => {
599- const error = new Error ( `${ label } exceeded timeout of ${ timeoutMs } ms` ) ;
612+ const error = new Error ( `${ label } exceeded timeout of ${ durationMs } ms` ) ;
600613 reject ( error ) ;
601614 controller . abort ( error ) ;
602- } , timeoutMs ) ;
615+ } , durationMs ) ;
603616 } ) ;
604617 try {
605618 return await Promise . race ( [ run ( controller . signal ) , timeoutPromise ] ) ;
@@ -611,37 +624,61 @@ async function smokeOpenAIWebRtc(browser: Browser, apiKey: string): Promise<Smok
611624 } ;
612625 let media : MediaStream | undefined ;
613626 let peer : RTCPeerConnection | undefined ;
627+ let audioContext : AudioContext | undefined ;
628+ let oscillator : OscillatorNode | undefined ;
629+ const playback = new Audio ( ) ;
630+ let providerError : string | undefined ;
631+ let transcriptMarker = false ;
632+ let responseDone = false ;
614633 try {
615634 if ( navigator . mediaDevices ?. getUserMedia ) {
616635 media = await navigator . mediaDevices . getUserMedia ( { audio : true } ) ;
617636 } else {
618- const audioContext = new AudioContext ( ) ;
637+ audioContext = new AudioContext ( ) ;
619638 const destination = audioContext . createMediaStreamDestination ( ) ;
620- const oscillator = audioContext . createOscillator ( ) ;
639+ oscillator = audioContext . createOscillator ( ) ;
621640 oscillator . connect ( destination ) ;
622641 oscillator . start ( ) ;
623642 media = destination . stream ;
624643 }
625644 peer = new RTCPeerConnection ( ) ;
645+ peer . addEventListener ( "track" , ( event ) => {
646+ playback . srcObject = event . streams [ 0 ] ?? new MediaStream ( [ event . track ] ) ;
647+ void playback . play ( ) . catch ( ( error : unknown ) => {
648+ providerError = error instanceof Error ? error . message : String ( error ) ;
649+ } ) ;
650+ } ) ;
626651 for ( const track of media . getAudioTracks ( ) ) {
627652 peer . addTrack ( track , media ) ;
628653 }
629654 const channel = peer . createDataChannel ( "oai-events" ) ;
630- const connectionState = new Promise < string > ( ( resolve ) => {
631- const timeout = window . setTimeout (
632- ( ) => resolve ( peer ?. connectionState ?? "timeout" ) ,
633- 12_000 ,
655+ channel . addEventListener ( "open" , ( ) => {
656+ channel . send (
657+ JSON . stringify ( {
658+ type : "response.create" ,
659+ response : { instructions : "Say only the word glacier." } ,
660+ } ) ,
634661 ) ;
635- peer ?. addEventListener ( "connectionstatechange" , ( ) => {
636- if ( peer ?. connectionState === "connected" || peer ?. connectionState === "failed" ) {
637- window . clearTimeout ( timeout ) ;
638- resolve ( peer . connectionState ) ;
662+ } ) ;
663+ channel . addEventListener ( "message" , ( event : MessageEvent < string > ) => {
664+ const message = JSON . parse ( event . data ) as {
665+ type ?: string ;
666+ transcript ?: string ;
667+ response ?: { status ?: string } ;
668+ error ?: { message ?: string } ;
669+ } ;
670+ if ( message . type === "response.output_audio_transcript.done" ) {
671+ transcriptMarker = / \b g l a c i e r \b / iu. test ( message . transcript ?? "" ) ;
672+ }
673+ if ( message . type === "response.done" ) {
674+ responseDone = message . response ?. status === "completed" ;
675+ if ( ! responseDone ) {
676+ providerError = `OpenAI browser response ${ message . response ?. status ?? "missing status" } ` ;
639677 }
640- } ) ;
641- channel . addEventListener ( "open" , ( ) => {
642- window . clearTimeout ( timeout ) ;
643- resolve ( peer ?. connectionState || "data-channel-open" ) ;
644- } ) ;
678+ }
679+ if ( message . type === "error" ) {
680+ providerError = message . error ?. message ?? "OpenAI browser realtime error" ;
681+ }
645682 } ) ;
646683 const offer = await peer . createOffer ( ) ;
647684 await peer . setLocalDescription ( offer ) ;
@@ -672,31 +709,114 @@ async function smokeOpenAIWebRtc(browser: Browser, apiKey: string): Promise<Smok
672709 } ,
673710 ) ;
674711 await peer . setRemoteDescription ( { type : "answer" , sdp : answer } ) ;
675- const state = await connectionState ;
712+ let outputAudioBytes = 0 ;
713+ let outputAudioEnergy = 0 ;
714+ let outputAudioSamplesDuration = 0 ;
715+ let outputAudioSpeechDuration = 0 ;
716+ let outputAudioPeakRms = 0 ;
717+ const mediaPeer = peer ;
718+ await withBrowserTimeout (
719+ "OpenAI Realtime browser audio" ,
720+ async ( signal ) => {
721+ while ( ! signal . aborted ) {
722+ if ( providerError ) {
723+ throw new Error ( providerError ) ;
724+ }
725+ if ( [ "failed" , "closed" ] . includes ( mediaPeer . connectionState ) ) {
726+ return ;
727+ }
728+ const stats = await mediaPeer . getStats ( ) ;
729+ const previousEnergy = outputAudioEnergy ;
730+ const previousDuration = outputAudioSamplesDuration ;
731+ outputAudioBytes = 0 ;
732+ outputAudioEnergy = 0 ;
733+ outputAudioSamplesDuration = 0 ;
734+ stats . forEach ( ( entry : RTCInboundRtpStreamStats ) => {
735+ if ( entry . type === "inbound-rtp" && entry . kind === "audio" ) {
736+ outputAudioBytes += entry . bytesReceived ?? 0 ;
737+ outputAudioEnergy += entry . totalAudioEnergy ?? 0 ;
738+ outputAudioSamplesDuration += entry . totalSamplesDuration ?? 0 ;
739+ }
740+ } ) ;
741+ const energyDelta = outputAudioEnergy - previousEnergy ;
742+ const durationDelta = outputAudioSamplesDuration - previousDuration ;
743+ if ( energyDelta >= 0 && durationDelta > 0 ) {
744+ const rms = Math . sqrt ( energyDelta / durationDelta ) ;
745+ outputAudioPeakRms = Math . max ( outputAudioPeakRms , rms ) ;
746+ if ( rms >= minSpeechRms ) {
747+ outputAudioSpeechDuration += durationDelta ;
748+ }
749+ }
750+ if (
751+ mediaPeer . connectionState === "connected" &&
752+ transcriptMarker &&
753+ responseDone &&
754+ outputAudioBytes > 512 &&
755+ outputAudioSpeechDuration >= minSpeechSeconds
756+ ) {
757+ return ;
758+ }
759+ await new Promise ( ( resolve ) => {
760+ window . setTimeout ( resolve , 50 ) ;
761+ } ) ;
762+ }
763+ signal . throwIfAborted ( ) ;
764+ } ,
765+ audioTimeoutMs ,
766+ ) ;
676767 return {
677768 answerHasAudio : answer . includes ( "m=audio" ) ,
678769 remoteDescriptionApplied : peer . remoteDescription ?. type === "answer" ,
679- connectionState : state ,
770+ connectionState : peer . connectionState ,
771+ transcriptMarker,
772+ responseDone,
773+ outputAudioBytes,
774+ outputAudioEnergy,
775+ outputAudioSamplesDuration,
776+ outputAudioSpeechDuration,
777+ outputAudioPeakRms,
680778 } ;
681779 } finally {
780+ playback . pause ( ) ;
781+ playback . srcObject = null ;
682782 peer ?. close ( ) ;
683783 media ?. getTracks ( ) . forEach ( ( track ) => track . stop ( ) ) ;
784+ oscillator ?. stop ( ) ;
785+ await audioContext ?. close ( ) ;
684786 }
685787 } ,
686788 {
687789 clientSecret,
688790 sdpAnswerMaxBytes : OPENAI_HTTP_RESPONSE_MAX_BYTES ,
689791 timeoutMs : openAIHttpTimeoutMs ,
792+ audioTimeoutMs : OPENAI_AUDIO_ROUNDTRIP_TIMEOUT_MS ,
793+ minSpeechRms : OPENAI_BROWSER_SPEECH_MIN_RMS ,
794+ minSpeechSeconds : OPENAI_BROWSER_SPEECH_MIN_SECONDS ,
690795 } ,
691796 ) ;
692797 return {
693798 name : "openai-webrtc-browser" ,
694- ok : result . answerHasAudio && result . remoteDescriptionApplied ,
799+ ok :
800+ result . answerHasAudio &&
801+ result . remoteDescriptionApplied &&
802+ result . connectionState === "connected" &&
803+ result . transcriptMarker &&
804+ result . responseDone &&
805+ result . outputAudioBytes > 512 &&
806+ result . outputAudioSpeechDuration >= OPENAI_BROWSER_SPEECH_MIN_SECONDS ,
695807 details : {
696808 model : OPENAI_REALTIME_MODEL ,
809+ protocol : "ga-realtime" ,
697810 answerHasAudio : result . answerHasAudio ,
698811 remoteDescriptionApplied : result . remoteDescriptionApplied ,
699812 connectionState : result . connectionState ,
813+ transcriptMarker : result . transcriptMarker ,
814+ responseDone : result . responseDone ,
815+ outputAudioBytes : result . outputAudioBytes ,
816+ outputAudioEnergy : result . outputAudioEnergy ,
817+ outputAudioSamplesDuration : result . outputAudioSamplesDuration ,
818+ outputAudioSpeechDuration : result . outputAudioSpeechDuration ,
819+ outputAudioPeakRms : result . outputAudioPeakRms ,
700820 } ,
701821 } ;
702822 } finally {
0 commit comments