1- import type { WebSocketEvents } from 'vitest' ;
1+ import type { W } from 'vitest/dist/chunks/worker.CIpff8Eg.js ' ;
22
33interface AG2InitMessage {
44 type : 'ag2.init' ;
@@ -19,30 +19,32 @@ export class WebRTC {
1919 private microphone ?: MediaStreamTrack ;
2020 private ws : WebSocket | null ;
2121 private pc : RTCPeerConnection | null ;
22- public onAG2SocketClose : ( ev : CloseEvent ) => void ;
23- public onWebRTCClose : ( ev : Event ) => void ;
22+ public onDisconnect : ( ) => void ;
2423
2524 constructor ( ag2SocketUrl : string , microphone ?: MediaStreamTrack ) {
2625 this . ag2SocketUrl = ag2SocketUrl ;
2726 this . microphone = microphone ;
2827 this . ws = null ;
2928 this . pc = null ;
30- this . onAG2SocketClose = ( ev : CloseEvent ) => {
31- console . log ( 'AG2 Websocket closed' ) ;
32- } ;
33- this . onWebRTCClose = ( ev : Event ) => {
34- console . log ( 'WebRTC closed' ) ;
29+ this . onDisconnect = ( ) => {
30+ console . log ( 'WebRTC disconnected' ) ;
3531 } ;
3632 }
3733
3834 async close ( ) : Promise < void > {
35+ if ( this . microphone ) {
36+ this . microphone ?. stop ( ) ;
37+ this . microphone = undefined ;
38+ }
3939 if ( this . ws ) {
40- this . ws . close ( ) ;
40+ const ws = this . ws ;
4141 this . ws = null ;
42+ ws . close ( ) ;
4243 }
4344 if ( this . pc ) {
44- this . pc . close ( ) ;
45+ const pc = this . pc ;
4546 this . pc = null ;
47+ pc . close ( ) ;
4648 }
4749 }
4850
@@ -82,11 +84,14 @@ export class WebRTC {
8284 mic . enabled = false ;
8385 pc . addTrack ( mic ) ;
8486
87+ pc . onconnectionstatechange = ( e ) => {
88+ if ( pc . connectionState === 'disconnected' ) {
89+ webRTC . close ( ) ;
90+ webRTC . onDisconnect ( ) ;
91+ }
92+ } ;
8593 // Set up data channel for sending and receiving events
8694 const _dc = pc . createDataChannel ( 'oai-events' ) ;
87- _dc . addEventListener ( 'close' , ( e ) => {
88- webRTC . onWebRTCClose ( e ) ;
89- } ) ;
9095
9196 _dc . addEventListener ( 'message' , ( e ) => {
9297 // Realtime server events appear here!
@@ -167,7 +172,8 @@ export class WebRTC {
167172 } ;
168173
169174 this . ws . onclose = ( event ) => {
170- this . onAG2SocketClose ( event ) ;
175+ this . close ( ) ;
176+ this . onDisconnect ( ) ;
171177 } ;
172178
173179 this . ws . onmessage = async ( event ) => {
0 commit comments