Skip to content

Commit 2646fea

Browse files
authored
fix: voice smoke passes without receiving speech (#133020)
1 parent 5d2bed1 commit 2646fea

5 files changed

Lines changed: 338 additions & 34 deletions

File tree

‎docs/channels/discord.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1266,6 +1266,7 @@ Auto-join example:
12661266

12671267
Notes:
12681268

1269+
- The OpenAI `agent-proxy` response and wake-name policies below require a GA realtime model, such as `gpt-realtime-2.1`. GPT-Live currently responds to audio autonomously and does not enforce those policies; do not rely on wake-name gating with GPT-Live in a shared voice channel.
12691270
- Discord voice is opt-in for text-only configs; set `channels.discord.voice.enabled=true` (or keep an existing `channels.discord.voice` block) to enable `/vc` commands, the voice runtime, and the `GuildVoiceStates` gateway intent. `channels.discord.intents.voiceStates` can explicitly override the intent subscription; leave it unset to follow effective voice enablement.
12701271
- `voice.mode` controls the conversation path. The default is `agent-proxy`: a realtime voice front end handles turn timing, interruption, and playback, delegates substantive work to the routed OpenClaw agent through `openclaw_agent_consult`, and treats the result like a typed Discord prompt from that speaker. `stt-tts` keeps the older batch STT plus TTS flow. `bidi` lets the realtime model converse directly while exposing `openclaw_agent_consult` for the OpenClaw brain.
12711272
- `voice.agentSession` controls which OpenClaw conversation receives voice turns. Leave it unset for the voice channel's own session, or set `{ mode: "target", target: "channel:<text-channel-id>" }` to make the voice channel act as the microphone/speaker extension of an existing Discord text channel session such as `#maintainers`.

‎docs/nodes/talk.md‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -216,9 +216,15 @@ overloaded: an invalid voice returns the same response. The legacy
216216
| Gateway-relay Talk | Supported with Gateway-owned WebRTC and sideband |
217217
| Discord bidirectional voice | Supported with the Platform-key backend WebSocket |
218218
| Voice Call and telephony | Supported with the Platform-key backend WebSocket |
219-
| iOS client-owned Talk | Pending |
219+
| iOS client-owned Talk | Implemented; GPT-Live device live verification pending |
220220
| Android realtime Talk | Pending an Android device live-proof flip; Android stays on native Talk |
221221

222+
These rows describe implemented transport paths, not account entitlement or a
223+
successful live call on every device. iOS implements frameless transcripts and
224+
the Gateway offer exchange; Android retains an explicit GPT-Live model gate.
225+
For model capability limits, see [Discord voice policies](/channels/discord#voice-channels)
226+
and [Voice Call tools](/plugins/voice-call#realtime-voice-conversations).
227+
222228
The Gateway-owned WebRTC route keeps OAuth and Platform credentials away from
223229
relay clients. Backend WebSocket paths keep the Platform key on the Gateway;
224230
OpenClaw converts telephony G.711 u-law audio to and from GPT-Live's 24 kHz PCM

‎docs/providers/openai.md‎

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -167,16 +167,17 @@ explicit runtime config.
167167
| Embeddings | memory embedding provider | Yes |
168168

169169
<Note>
170-
GA OpenAI Realtime voice goes through the public **OpenAI Platform Realtime
171-
API** and requires a Platform API key. Browser and Gateway-relay GPT-Live are
172-
the exceptions: their native `api.openai.com/v1/live` route prefers a ChatGPT
170+
GA OpenAI Realtime backend voice bridges require a Platform API key. GA browser
171+
Talk can also use an OpenClaw ChatGPT OAuth profile when no Platform credential
172+
is configured. Browser and Gateway-relay GPT-Live use the native
173+
`api.openai.com/v1/live` route, which prefers a ChatGPT
173174
OAuth profile and falls back to Platform API-key auth when that account has
174175
waitlist-gated access. Other GPT-Live backend voice bridges use the Frameless
175176
Bidi WebSocket and require Platform API-key auth.
176177

177178
Platform auth is resolved in this order: configured realtime API key, `openai`
178-
API-key profile, then `OPENAI_API_KEY`. ChatGPT OAuth does not configure GA
179-
Talk, Voice Call, Discord realtime voice, or realtime transcription.
179+
API-key profile, then `OPENAI_API_KEY`. Voice Call, Discord realtime voice,
180+
GA Gateway relay, and realtime transcription still require Platform auth.
180181

181182
If API-key auth reports missing billing, top up Platform credits at
182183
[platform.openai.com/account/billing](https://platform.openai.com/account/billing)
@@ -909,12 +910,12 @@ value into `plugins.entries.openai.config.personality` when that key is unset.
909910

910911
<Note>
911912
Set `OPENAI_TTS_BASE_URL` to override the TTS base URL without affecting
912-
the chat API endpoint. OpenAI TTS and GA Realtime voice are configured
913-
through an OpenAI Platform API key. OAuth-only installs can use
914-
Codex-backed chat models plus GPT-Live and GA Realtime browser Talk over a
915-
ChatGPT subscription (see the Realtime accordion). They cannot use OpenAI
916-
TTS, iOS Realtime WebRTC, Voice Call, Gateway relay, or Discord realtime
917-
voice without a Platform API key.
913+
the chat API endpoint. OpenAI TTS requires an OpenAI Platform API key.
914+
OAuth-only installs can use Codex-backed chat models, GPT-Live browser
915+
and Gateway-relay Talk, and GA Realtime browser Talk over a ChatGPT
916+
subscription when the account has access (see the Realtime accordion).
917+
OpenAI TTS, Voice Call, GA Gateway relay, and Discord realtime voice still
918+
require a Platform API key.
918919
</Note>
919920

920921
</Accordion>
@@ -1100,8 +1101,14 @@ value into `plugins.entries.openai.config.personality` when that key is unset.
11001101
| Gateway-relay Talk | Supported with Gateway-owned WebRTC and sideband |
11011102
| Discord bidirectional voice | Supported with the Platform-key backend WebSocket |
11021103
| Voice Call and telephony | Supported with the Platform-key backend WebSocket |
1103-
| iOS client-owned Talk | Pending |
1104+
| iOS client-owned Talk | Implemented; GPT-Live device live verification pending |
11041105
| Android realtime Talk | Pending an Android device live-proof flip; Android stays on native Talk |
1106+
1107+
These rows describe implemented transports, not account entitlement or
1108+
complete model capability parity. See the [Discord voice policy limits](/channels/discord#voice-channels)
1109+
and [Voice Call tool limits](/plugins/voice-call#realtime-voice-conversations) before
1110+
selecting GPT-Live for those consumers.
1111+
11051112
<Warning>
11061113
Platform API-key access to `/v1/live` is waitlist-gated and commonly returns
11071114
`400 model_not_found` without enrollment. Use a ChatGPT OAuth profile, or request Platform access with the

‎scripts/dev/realtime-talk-live-smoke.ts‎

Lines changed: 141 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ const OPENAI_AUDIO_CHUNK_BYTES = 960;
2222
const OPENAI_AUDIO_CHUNK_DELAY_MS = 5;
2323
const OPENAI_AUDIO_ROUNDTRIP_TIMEOUT_MS = 60_000;
2424
const 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;
2528
const GOOGLE_REALTIME_MODEL =
2629
process.env.OPENCLAW_REALTIME_GOOGLE_MODEL?.trim() || "gemini-3.1-flash-live-preview";
2730
const 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 = /\bglacier\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

Comments
 (0)