Skip to content

Commit cc62f37

Browse files
committed
fix(google): own realtime connection attempts
1 parent bc4221a commit cc62f37

1 file changed

Lines changed: 146 additions & 62 deletions

File tree

‎extensions/google/realtime-voice-provider.ts‎

Lines changed: 146 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -450,6 +450,11 @@ function formatGoogleLiveCloseEvent(
450450
return `code=${code} reason=${reason}${clean}`;
451451
}
452452

453+
type GoogleLiveConnectionAttempt = {
454+
promise: Promise<void>;
455+
cancel: () => void;
456+
};
457+
453458
class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
454459
readonly supportsToolResultContinuation: boolean;
455460
readonly supportsToolResultSuppression = false;
@@ -470,7 +475,9 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
470475
private reconnectTimer: ReturnType<typeof setTimeout> | undefined;
471476
private hasConnectedSession = false;
472477
private terminalError: Error | undefined;
473-
private terminalCloseNotified = false;
478+
private closeNotified = false;
479+
private connectionOwner: GoogleLiveConnectionAttempt | undefined;
480+
private connectAttempt: GoogleLiveConnectionAttempt | undefined;
474481
private readonly pendingTranscripts: Record<RealtimeVoiceRole, string> = {
475482
user: "",
476483
assistant: "",
@@ -486,6 +493,32 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
486493
if (this.terminalError) {
487494
throw this.terminalError;
488495
}
496+
if (this.session) {
497+
return;
498+
}
499+
if (this.connectAttempt) {
500+
return this.connectAttempt.promise;
501+
}
502+
let cancel = () => {};
503+
const cancelled = new Promise<void>((resolve) => {
504+
cancel = resolve;
505+
});
506+
const attempt: GoogleLiveConnectionAttempt = {
507+
promise: cancelled,
508+
cancel,
509+
};
510+
this.connectionOwner = attempt;
511+
this.connectAttempt = attempt;
512+
const connection = this.connectOwned(attempt);
513+
attempt.promise = Promise.race([connection, cancelled]).finally(() => {
514+
if (this.connectAttempt === attempt) {
515+
this.connectAttempt = undefined;
516+
}
517+
});
518+
return attempt.promise;
519+
}
520+
521+
private async connectOwned(attempt: GoogleLiveConnectionAttempt): Promise<void> {
489522
const canResumeSession =
490523
this.config.sessionResumption !== false && Boolean(this.resumptionHandle);
491524
if (this.hasConnectedSession && !canResumeSession) {
@@ -494,6 +527,7 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
494527
this.resetPendingTranscripts();
495528
}
496529
this.intentionallyClosed = false;
530+
this.closeNotified = false;
497531
this.sessionConfigured = false;
498532
this.sessionReadyFired = false;
499533
this.consecutiveSilenceMs = 0;
@@ -506,63 +540,91 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
506540
},
507541
});
508542

509-
this.session = await ai.live.connect({
510-
model: this.model,
511-
config: {
512-
...buildGoogleLiveConnectConfig(this.config, this.model),
513-
...(this.config.sessionResumption === false
514-
? {}
515-
: {
516-
sessionResumption: this.resumptionHandle ? { handle: this.resumptionHandle } : {},
517-
}),
518-
...(this.config.contextWindowCompression === false
519-
? {}
520-
: { contextWindowCompression: { slidingWindow: {} } }),
521-
},
522-
callbacks: {
523-
onopen: () => {
524-
this.connected = true;
525-
},
526-
onmessage: (message) => {
527-
this.handleMessage(message);
528-
},
529-
onerror: (event) => {
530-
const error =
531-
event.error instanceof Error
532-
? event.error
533-
: new Error(
534-
typeof event.message === "string" ? event.message : "Google Live API error",
535-
);
536-
this.config.onError?.(error);
543+
try {
544+
const session = await ai.live.connect({
545+
model: this.model,
546+
config: {
547+
...buildGoogleLiveConnectConfig(this.config, this.model),
548+
...(this.config.sessionResumption === false
549+
? {}
550+
: {
551+
sessionResumption: this.resumptionHandle ? { handle: this.resumptionHandle } : {},
552+
}),
553+
...(this.config.contextWindowCompression === false
554+
? {}
555+
: { contextWindowCompression: { slidingWindow: {} } }),
537556
},
538-
onclose: (event) => {
539-
this.connected = false;
540-
this.sessionConfigured = false;
541-
this.pendingFunctionNames.clear();
542-
this.session = null;
543-
if (this.terminalError) {
544-
this.notifyTerminalClose();
545-
return;
546-
}
547-
if (this.intentionallyClosed) {
548-
this.config.onClose?.("completed");
549-
return;
550-
}
551-
const closeDetails = formatGoogleLiveCloseEvent(event);
552-
if (this.scheduleReconnect(closeDetails)) {
553-
return;
554-
}
555-
// Transport failure is not an utterance boundary. Preserve transcript
556-
// fragments across reconnects and finalize only when recovery is exhausted.
557-
this.flushPendingTranscripts();
558-
this.config.onError?.(
559-
new Error(`Google Live session closed after reconnect attempts: ${closeDetails}`),
560-
);
561-
this.config.onClose?.("error");
557+
callbacks: {
558+
onopen: () => {
559+
if (this.connectionOwner !== attempt) {
560+
return;
561+
}
562+
this.connected = true;
563+
},
564+
onmessage: (message) => {
565+
if (this.connectionOwner !== attempt) {
566+
return;
567+
}
568+
this.handleMessage(message);
569+
},
570+
onerror: (event) => {
571+
if (this.connectionOwner !== attempt) {
572+
return;
573+
}
574+
const error =
575+
event.error instanceof Error
576+
? event.error
577+
: new Error(
578+
typeof event.message === "string" ? event.message : "Google Live API error",
579+
);
580+
this.config.onError?.(error);
581+
},
582+
onclose: (event) => {
583+
if (this.connectionOwner !== attempt) {
584+
return;
585+
}
586+
this.connectionOwner = undefined;
587+
this.cancelConnectAttempt(attempt);
588+
this.connected = false;
589+
this.sessionConfigured = false;
590+
this.pendingFunctionNames.clear();
591+
this.session = null;
592+
if (this.terminalError) {
593+
this.notifyClose("error");
594+
return;
595+
}
596+
if (this.intentionallyClosed) {
597+
this.notifyClose("completed");
598+
return;
599+
}
600+
const closeDetails = formatGoogleLiveCloseEvent(event);
601+
if (this.scheduleReconnect(closeDetails)) {
602+
return;
603+
}
604+
// Transport failure is not an utterance boundary. Preserve transcript
605+
// fragments across reconnects and finalize only when recovery is exhausted.
606+
this.flushPendingTranscripts();
607+
this.config.onError?.(
608+
new Error(`Google Live session closed after reconnect attempts: ${closeDetails}`),
609+
);
610+
this.notifyClose("error");
611+
},
562612
},
563-
},
564-
});
565-
this.hasConnectedSession = true;
613+
});
614+
if (this.connectionOwner !== attempt) {
615+
session.close();
616+
return;
617+
}
618+
this.session = session;
619+
this.hasConnectedSession = true;
620+
} catch (error) {
621+
if (this.connectionOwner === attempt) {
622+
this.connectionOwner = undefined;
623+
this.connected = false;
624+
this.sessionConfigured = false;
625+
}
626+
throw error;
627+
}
566628
}
567629

568630
sendAudio(audio: Buffer): void {
@@ -692,6 +754,9 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
692754
acknowledgeMark(_markName?: string): void {}
693755

694756
close(): void {
757+
const hadConnection = Boolean(
758+
this.connectionOwner || this.connectAttempt || this.session || this.reconnectTimer,
759+
);
695760
this.intentionallyClosed = true;
696761
this.connected = false;
697762
this.sessionConfigured = false;
@@ -704,9 +769,15 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
704769
this.audioStreamEnded = false;
705770
this.pendingFunctionNames.clear();
706771
this.flushPendingTranscripts();
772+
const owner = this.connectionOwner;
773+
this.connectionOwner = undefined;
774+
this.cancelConnectAttempt(owner);
707775
const session = this.session;
708776
this.session = null;
709777
session?.close();
778+
if (hadConnection) {
779+
this.notifyClose("completed");
780+
}
710781
}
711782

712783
isConnected(): boolean {
@@ -874,6 +945,9 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
874945
}
875946
this.pendingFunctionNames.clear();
876947
this.flushPendingTranscripts();
948+
const owner = this.connectionOwner;
949+
this.connectionOwner = undefined;
950+
this.cancelConnectAttempt(owner);
877951
const session = this.session;
878952
this.session = null;
879953
try {
@@ -882,17 +956,27 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
882956
try {
883957
session?.close();
884958
} finally {
885-
this.notifyTerminalClose();
959+
this.notifyClose("error");
886960
}
887961
}
888962
}
889963

890-
private notifyTerminalClose(): void {
891-
if (this.terminalCloseNotified) {
964+
private notifyClose(reason: "completed" | "error"): void {
965+
if (this.closeNotified) {
966+
return;
967+
}
968+
this.closeNotified = true;
969+
this.config.onClose?.(reason);
970+
}
971+
972+
private cancelConnectAttempt(attempt: GoogleLiveConnectionAttempt | undefined): void {
973+
if (!attempt) {
892974
return;
893975
}
894-
this.terminalCloseNotified = true;
895-
this.config.onClose?.("error");
976+
if (this.connectAttempt === attempt) {
977+
this.connectAttempt = undefined;
978+
}
979+
attempt.cancel();
896980
}
897981

898982
private handleToolCall(toolCall: LiveServerToolCall): void {
@@ -936,7 +1020,7 @@ class GoogleRealtimeVoiceBridge implements RealtimeVoiceBridge {
9361020
this.config.onError?.(error instanceof Error ? error : new Error(message));
9371021
if (!this.scheduleReconnect(`connect failed: ${message}`)) {
9381022
this.flushPendingTranscripts();
939-
this.config.onClose?.("error");
1023+
this.notifyClose("error");
9401024
}
9411025
});
9421026
}, delayMs);

0 commit comments

Comments
 (0)