Skip to content

Commit 223b22b

Browse files
authored
Fix Webrtc connection errors (#138)
* add logging * fix attempt, use new url
1 parent c085c8d commit 223b22b

9 files changed

Lines changed: 476 additions & 64 deletions

‎app/RealtimeTranslation.tsx‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { LanguagePickerRow } from "../components/realtime/LanguagePickerRow";
1313
import { SessionFooter } from "../components/realtime/SessionFooter";
1414
import { TranscriptView } from "../components/realtime/TranscriptView";
1515
import { log } from "../lib/logger";
16+
import { getUserFacingRealtimeErrorMessage } from "../lib/realtimeUserError";
1617
import {
1718
DEFAULT_BIDIRECTIONAL_ENABLED,
1819
DEFAULT_BIDIRECTIONAL_LANGUAGE,
@@ -314,8 +315,7 @@ export function RealtimeTranslation({
314315
},
315316
error,
316317
);
317-
const message =
318-
error instanceof Error ? error.message : "Unexpected error";
318+
const message = getUserFacingRealtimeErrorMessage(error, "translation");
319319
Alert.alert("Translation", message);
320320
setIsSessionActive(false);
321321
} finally {
@@ -348,8 +348,7 @@ export function RealtimeTranslation({
348348
},
349349
error,
350350
);
351-
const message =
352-
error instanceof Error ? error.message : "Unexpected error";
351+
const message = getUserFacingRealtimeErrorMessage(error, "translation");
353352
Alert.alert("Translation", message);
354353
} finally {
355354
setIsStopping(false);

‎app/VoiceChat.tsx‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { VoiceSpeedCustomization } from "../components/VoiceSpeedCustomization";
1717
import { loadShowRealtimeErrorAlerts } from "../lib/developerSettings";
1818
import { log } from "../lib/logger";
1919
import { composeMainPrompt } from "../lib/mainPrompt";
20+
import { getUserFacingRealtimeErrorMessage } from "../lib/realtimeUserError";
2021
import { TokenUsageTracker } from "../lib/tokenUsageTracker";
2122
import { loadTranscriptionPreference } from "../lib/transcriptionPreference";
2223
import type { VadMode } from "../lib/vadPreference";
@@ -173,10 +174,10 @@ export function VoiceChat({
173174
},
174175
);
175176
const message =
176-
typeof payload?.error?.message === "string" &&
177-
payload.error.message.trim().length > 0
178-
? payload.error.message.trim()
179-
: "The voice session encountered an unexpected error.";
177+
getUserFacingRealtimeErrorMessage(
178+
payload?.error?.message,
179+
"voice",
180+
) || "The voice session encountered an unexpected error.";
180181

181182
// Only show alert if developer setting is enabled
182183
const shouldShowAlert = await loadShowRealtimeErrorAlerts();
@@ -396,15 +397,16 @@ export function VoiceChat({
396397
"Starting OpenAI voice session",
397398
{},
398399
{
399-
hasBaseUrl: Boolean(baseConnectionOptions.baseUrl),
400-
hasModel: Boolean(baseConnectionOptions.model),
400+
baseUrl: baseConnectionOptions.baseUrl ?? "default",
401+
model: baseConnectionOptions.model ?? "default",
401402
audioOutput,
402403
voice: selectedVoice,
403404
hasInstructions: finalPrompt.trim().length > 0,
404405
hasCustomAddition: mainPromptAddition.trim().length > 0,
405406
toolNames: voiceToolNames,
406407
transcriptionEnabled,
407408
selectedLanguage,
409+
hasMicPermission,
408410
},
409411
);
410412
const customConnectionOptions: OpenAIConnectionOptions = {
@@ -522,8 +524,7 @@ export function VoiceChat({
522524
},
523525
error,
524526
);
525-
const message =
526-
error instanceof Error ? error.message : "Unexpected error";
527+
const message = getUserFacingRealtimeErrorMessage(error, "voice");
527528

528529
// Emit error status
529530
emitVoiceSessionStatus(`Connection failed: ${message}`);

‎lib/realtimeUserError.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
const DEFAULT_MESSAGES = {
2+
voice: "The voice session could not be started.",
3+
translation: "The translation session could not be started.",
4+
} as const;
5+
6+
type RealtimeUserErrorContext = keyof typeof DEFAULT_MESSAGES;
7+
8+
const isNonEmptyString = (value: unknown): value is string =>
9+
typeof value === "string" && value.trim().length > 0;
10+
11+
const firstLine = (value: string) => value.split(/\r?\n/, 1)[0]?.trim() ?? "";
12+
13+
export function getUserFacingRealtimeErrorMessage(
14+
error: unknown,
15+
context: RealtimeUserErrorContext = "voice",
16+
): string {
17+
const fallback = DEFAULT_MESSAGES[context];
18+
const rawMessage = (() => {
19+
if (error instanceof Error) {
20+
return error.message;
21+
}
22+
if (isNonEmptyString(error)) {
23+
return error;
24+
}
25+
return fallback;
26+
})();
27+
28+
const message = rawMessage.trim();
29+
if (!message) {
30+
return fallback;
31+
}
32+
33+
if (message.includes("OpenAI Realtime endpoint rejected")) {
34+
return "OpenAI rejected the realtime connection setup.";
35+
}
36+
37+
if (message.includes("Timed out waiting for the WebRTC connection")) {
38+
return "Timed out while establishing the realtime connection.";
39+
}
40+
41+
if (message.includes("WebRTC connection failed with state:")) {
42+
return "The realtime connection failed before the session was ready.";
43+
}
44+
45+
if (
46+
message.includes("An OpenAI API key must be set") ||
47+
message.includes("Missing OpenAI API key")
48+
) {
49+
return "An OpenAI API key is required to start this session.";
50+
}
51+
52+
if (message.includes("Failed to build the OpenAI Realtime endpoint URL")) {
53+
return "The configured OpenAI endpoint is invalid.";
54+
}
55+
56+
if (message.includes("The local WebRTC session description is missing")) {
57+
return "The device could not prepare the realtime connection offer.";
58+
}
59+
60+
if (message.includes("Could not decode the SDP answer returned by OpenAI")) {
61+
return "OpenAI returned an invalid realtime connection response.";
62+
}
63+
64+
if (
65+
message.startsWith("{") ||
66+
message.startsWith("[") ||
67+
message.includes("Response body:")
68+
) {
69+
return fallback;
70+
}
71+
72+
const summary = firstLine(message);
73+
if (!summary) {
74+
return fallback;
75+
}
76+
77+
return summary.length > 140 ? `${summary.slice(0, 139).trimEnd()}…` : summary;
78+
}

‎modules/vm-webrtc/ios/OpenAIWebRTCClient.swift‎

Lines changed: 89 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ final class OpenAIWebRTCClient: OpenAIWebRTCBase {
1010

1111
// MARK: Subclass-provided endpoint constants
1212

13-
override var defaultEndpoint: String { "https://api.openai.com/v1/realtime" }
13+
override var defaultEndpoint: String { "https://api.openai.com/v1/realtime/calls" }
1414
override var defaultModel: String { "gpt-realtime" }
1515

1616
// MARK: Chat-specific stored properties
@@ -41,6 +41,7 @@ final class OpenAIWebRTCClient: OpenAIWebRTCBase {
4141
let audioMixPlayer = AudioMixPlayer()
4242

4343
var toolDefinitions: [[String: Any]] = []
44+
private var initialSessionConfiguration: [String: Any]?
4445
lazy var eventHandler = WebRTCEventHandler()
4546

4647
// MARK: Init / deinit
@@ -69,7 +70,7 @@ final class OpenAIWebRTCClient: OpenAIWebRTCBase {
6970
// MARK: Virtual hook overrides
7071

7172
override func dataChannelDidOpen() {
72-
sendInitialSessionConfiguration()
73+
handleDataChannelOpenAfterInitialSessionSetup()
7374
}
7475

7576
override func handleDataChannelMessage(_ event: [String: Any]) {
@@ -220,17 +221,31 @@ final class OpenAIWebRTCClient: OpenAIWebRTCBase {
220221
attributes: logAttributes(
221222
for: .info,
222223
metadata: [
223-
"hasModel": (model?.isEmpty == false),
224-
"hasBaseURL": (baseURL?.isEmpty == false),
224+
"resolvedModel": resolvedModelName(model),
225+
"baseURL": baseURL ?? "",
225226
"audioOutput": audioOutput.rawValue,
226227
"voice": sessionVoice,
227228
]))
228229

229-
let endpointURL = try buildEndpointURL(baseURL: baseURL, model: model)
230+
let endpointURL = try buildEndpointURL(
231+
baseURL: baseURL,
232+
model: model,
233+
appendModelQuery: false
234+
)
230235
self.logger.log(
231236
"[VmWebrtc] Resolved OpenAI endpoint",
232237
attributes: logAttributes(for: .debug, metadata: ["endpoint": endpointURL.absoluteString])
233238
)
239+
let sessionConfiguration = buildInitialRealtimeSessionConfiguration(model: model)
240+
initialSessionConfiguration = sessionConfiguration
241+
self.logger.log(
242+
"[VmWebrtc] Prepared initial realtime session configuration",
243+
attributes: logAttributes(
244+
for: .debug,
245+
metadata: [
246+
"session": sessionConfiguration,
247+
"sessionJSON": prettyJSONString(from: sessionConfiguration) ?? "<invalid_session_json>",
248+
]))
234249

235250
try configureAudioSession(for: audioOutput)
236251
self.logger.log(
@@ -282,12 +297,26 @@ final class OpenAIWebRTCClient: OpenAIWebRTCBase {
282297
attributes: logAttributes(for: .error))
283298
throw OpenAIWebRTCError.missingLocalDescription
284299
}
300+
self.logger.log(
301+
"[VmWebrtc] Final local SDP ready for OpenAI exchange",
302+
attributes: logAttributes(
303+
for: .debug,
304+
metadata: [
305+
"endpoint": endpointURL.absoluteString,
306+
"sdpLength": localSDP.count,
307+
"sdpSummary": analyzeSDP(localSDP),
308+
"sdp": localSDP,
309+
]))
285310

286311
emitModuleEvent(
287312
"onVoiceSessionStatus", payload: ["status_update": "Connecting to OpenAI endpoint..."])
288313

289-
let answerSDP = try await exchangeSDPWithOpenAI(
290-
apiKey: resolvedApiKey, endpointURL: endpointURL, offerSDP: localSDP)
314+
let answerSDP = try await exchangeRealtimeCallWithOpenAI(
315+
apiKey: resolvedApiKey,
316+
endpointURL: endpointURL,
317+
offerSDP: localSDP,
318+
session: sessionConfiguration
319+
)
291320
let remoteDescription = RTCSessionDescription(type: .answer, sdp: answerSDP)
292321
try await setRemoteDescription(remoteDescription, for: connection)
293322
self.logger.log(
@@ -324,22 +353,19 @@ final class OpenAIWebRTCClient: OpenAIWebRTCBase {
324353
eventHandler.resetAudioStreamingState()
325354
eventHandler.resetFunctionCallState()
326355
eventHandler.shadowObserve_reset(reason: "connection_closed")
356+
initialSessionConfiguration = nil
327357

328358
return super.closeConnection()
329359
}
330360

331-
// MARK: Session configuration (sent once data channel opens)
332-
333-
func sendInitialSessionConfiguration() {
334-
guard !hasSentInitialSessionConfig else { return }
361+
// MARK: Session configuration / startup
335362

336-
guard let dataChannel, dataChannel.readyState == .open else {
337-
self.logger.log(
338-
"[VmWebrtc] Data channel not ready for initial session configuration",
339-
attributes: logAttributes(for: .warn, metadata: ["hasChannel": dataChannel != nil]))
340-
return
341-
}
363+
private func resolvedModelName(_ model: String?) -> String {
364+
let trimmedModel = model?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
365+
return trimmedModel.isEmpty ? defaultModel : trimmedModel
366+
}
342367

368+
private func buildInitialRealtimeSessionConfiguration(model: String?) -> [String: Any] {
343369
let tools = buildTools()
344370

345371
if tools.isEmpty && !toolDefinitions.isEmpty {
@@ -349,52 +375,79 @@ final class OpenAIWebRTCClient: OpenAIWebRTCBase {
349375
for: .warn, metadata: ["definitionCount": toolDefinitions.count]))
350376
}
351377

352-
var session: [String: Any] = [
353-
"instructions": sessionInstructions,
354-
"voice": sessionVoice,
355-
"tools": tools,
356-
]
378+
var inputAudioConfig: [String: Any] = [:]
357379

358380
switch turnDetectionMode {
359381
case .semantic:
360-
session["turn_detection"] = [
382+
inputAudioConfig["turn_detection"] = [
361383
"type": "semantic_vad",
362384
"create_response": true,
363385
"eagerness": "low",
364386
]
365387
case .server:
366-
session["turn_detection"] = [
388+
inputAudioConfig["turn_detection"] = [
367389
"type": "server_vad",
368390
"create_response": true,
369391
]
370392
}
371393

394+
if transcriptionEnabled {
395+
inputAudioConfig["transcription"] = ["model": "whisper-1"]
396+
}
397+
398+
var audioConfig: [String: Any] = [
399+
"output": [
400+
"voice": sessionVoice,
401+
]
402+
]
403+
404+
if !inputAudioConfig.isEmpty {
405+
audioConfig["input"] = inputAudioConfig
406+
}
407+
408+
var session: [String: Any] = [
409+
"type": "realtime",
410+
"model": resolvedModelName(model),
411+
"instructions": sessionInstructions,
412+
"audio": audioConfig,
413+
"tools": tools,
414+
]
415+
372416
if let ratio = retentionRatio {
373417
session["truncation"] = [
374418
"type": "retention_ratio",
375419
"retention_ratio": quantizedRetentionRatio(ratio),
376420
]
377421
}
378422

379-
if transcriptionEnabled {
380-
session["input_audio_transcription"] = ["model": "whisper-1"]
423+
return session
424+
}
425+
426+
func handleDataChannelOpenAfterInitialSessionSetup() {
427+
guard !hasSentInitialSessionConfig else { return }
428+
429+
guard let dataChannel, dataChannel.readyState == .open else {
430+
self.logger.log(
431+
"[VmWebrtc] Data channel not ready for initial session configuration",
432+
attributes: logAttributes(for: .warn, metadata: ["hasChannel": dataChannel != nil]))
433+
return
381434
}
382435

383-
if let prettyData = try? JSONSerialization.data(
384-
withJSONObject: session, options: [.prettyPrinted]),
385-
let prettyString = String(data: prettyData, encoding: .utf8)
386-
{
436+
if let session = initialSessionConfiguration {
387437
self.logger.log(
388-
"📑 [VmWebrtc] Sending session.update payload",
389-
attributes: logAttributes(for: .debug, metadata: ["session": prettyString]))
438+
"📑 [VmWebrtc] Initial session already configured via /v1/realtime/calls",
439+
attributes: logAttributes(
440+
for: .debug,
441+
metadata: [
442+
"session": session,
443+
"sessionJSON": prettyJSONString(from: session) ?? "<invalid_session_json>",
444+
]))
390445
} else {
391446
self.logger.log(
392-
"📑 [VmWebrtc] Sending session.update payload (fallback formatting)",
393-
attributes: logAttributes(for: .debug, metadata: ["session": session]))
447+
"[VmWebrtc] Missing cached initial session configuration when data channel opened",
448+
attributes: logAttributes(for: .warn))
394449
}
395450

396-
_ = sendEvent(["type": "session.update", "session": session])
397-
398451
Task { @MainActor in
399452
self.emitModuleEvent(
400453
"onVoiceSessionStatus", payload: ["status_update": "Started Voice Session"])

‎modules/vm-webrtc/ios/OpenAIWebRTCCore.swift‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ enum OpenAIWebRTCError: LocalizedError {
88
case invalidEndpoint
99
case missingLocalDescription
1010
case missingAPIKey
11-
case openAIRejected(Int)
11+
case openAIRejected(status: Int, details: String?)
1212
case openAIResponseDecoding
1313
case connectionTimeout
1414
case connectionFailed(String)
@@ -23,7 +23,7 @@ enum OpenAIWebRTCError: LocalizedError {
2323
return "The local WebRTC session description is missing after ICE gathering."
2424
case .missingAPIKey:
2525
return "An OpenAI API key must be set before starting a session."
26-
case .openAIRejected(let status):
26+
case .openAIRejected(let status, _):
2727
return "OpenAI Realtime endpoint rejected the SDP offer with status code \(status)."
2828
case .openAIResponseDecoding:
2929
return "Could not decode the SDP answer returned by OpenAI."

0 commit comments

Comments
 (0)