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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
import asyncio
import json
import threading
from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from elevenlabs.conversational_ai.conversation import (
    AsyncAudioInterface,
    AsyncConversation,
    ConversationInitiationData,
)


class MockAsyncAudioInterface(AsyncAudioInterface):
    async def start(self, input_callback):
        print("Async audio interface started")
        self.input_callback = input_callback

    async def stop(self):
        print("Async audio interface stopped")

    async def output(self, audio):
        print(f"Would play audio of length: {len(audio)} bytes")

    async def interrupt(self):
        print("Async audio interrupted")


# Add test constants and helpers at module level
TEST_CONVERSATION_ID = "test123"
TEST_AGENT_ID = "test_agent"


def create_mock_async_websocket(messages=None):
    """Helper to create a mock async websocket with predefined responses"""
    mock_ws = AsyncMock()

    if messages is None:
        messages = [
            {
                "type": "conversation_initiation_metadata",
                "conversation_initiation_metadata_event": {"conversation_id": TEST_CONVERSATION_ID},
            },
            {"type": "agent_response", "agent_response_event": {"agent_response": "Hello there!"}},
        ]

    # Convert messages to JSON strings
    json_messages = [json.dumps(msg) for msg in messages]

    # Create an iterator
    message_iter = iter(json_messages)

    async def mock_recv():
        try:
            return next(message_iter)
        except StopIteration:
            # After all messages, simulate timeout by sleeping forever
            # This will be caught by asyncio.wait_for timeout in the conversation
            await asyncio.sleep(float("inf"))

    mock_ws.recv = mock_recv
    return mock_ws


@pytest.mark.asyncio
async def test_async_conversation_basic_flow():
    # Mock setup
    mock_ws = create_mock_async_websocket()
    mock_client = MagicMock()
    mock_client._client_wrapper.get_base_url.return_value = "https://api.elevenlabs.io"
    agent_response_callback = AsyncMock()
    test_user_id = "test_user_123"

    # Setup the conversation with user_id passed directly to the constructor
    conversation = AsyncConversation(
        client=mock_client,
        agent_id=TEST_AGENT_ID,
        user_id=test_user_id,
        requires_auth=False,
        audio_interface=MockAsyncAudioInterface(),
        callback_agent_response=agent_response_callback,
    )

    # Run the test
    with patch("elevenlabs.conversational_ai.conversation.websockets.connect") as mock_connect:
        mock_connect.return_value.__aenter__.return_value = mock_ws

        await conversation.start_session()

        # Wait a bit for the callback to be called
        await asyncio.sleep(0.1)

        await conversation.end_session()
        await conversation.wait_for_session_end()

    # Assertions - check the call was made with the right structure
    send_calls = [call[0][0] for call in mock_ws.send.call_args_list]
    init_messages = [json.loads(call) for call in send_calls if "conversation_initiation_client_data" in call]
    assert len(init_messages) == 1
    init_message = init_messages[0]

    assert init_message["type"] == "conversation_initiation_client_data"
    assert init_message["custom_llm_extra_body"] == {}
    assert init_message["conversation_config_override"] == {}
    assert init_message["dynamic_variables"] == {}
    assert init_message["source_info"]["source"] == "python_sdk"
    assert "version" in init_message["source_info"]
    assert init_message["user_id"] == test_user_id
    agent_response_callback.assert_called_once_with("Hello there!")
    assert conversation._conversation_id == TEST_CONVERSATION_ID
    assert conversation.user_id == test_user_id


@pytest.mark.asyncio
async def test_async_conversation_with_auth():
    # Mock setup
    mock_client = MagicMock()
    mock_client.conversational_ai.conversations.get_signed_url.return_value.signed_url = "wss://signed.url"
    mock_ws = create_mock_async_websocket(
        [
            {
                "type": "conversation_initiation_metadata",
                "conversation_initiation_metadata_event": {"conversation_id": TEST_CONVERSATION_ID},
            }
        ]
    )

    conversation = AsyncConversation(
        client=mock_client,
        agent_id=TEST_AGENT_ID,
        requires_auth=True,
        audio_interface=MockAsyncAudioInterface(),
    )

    # Run the test
    with patch("elevenlabs.conversational_ai.conversation.websockets.connect") as mock_connect:
        mock_connect.return_value.__aenter__.return_value = mock_ws

        await conversation.start_session()
        await conversation.end_session()
        await conversation.wait_for_session_end()

    # Assertions
    mock_client.conversational_ai.conversations.get_signed_url.assert_called_once_with(agent_id=TEST_AGENT_ID, environment=None)


@pytest.mark.asyncio
async def test_async_conversation_gets_signed_url_off_event_loop():
    conversation = AsyncConversation(client=MagicMock(), agent_id=TEST_AGENT_ID, requires_auth=True)
    event_loop_thread = threading.get_ident()

    def get_signed_url():
        assert threading.get_ident() != event_loop_thread
        return "wss://signed.url"

    with patch.object(conversation, "_get_signed_url", side_effect=get_signed_url), patch.object(
        conversation, "_run", new=AsyncMock()
    ):
        await conversation.start_session()
        await conversation.wait_for_session_end()
        await conversation.end_session()


@pytest.mark.asyncio
async def test_async_conversation_with_dynamic_variables():
    # Mock setup
    mock_ws = create_mock_async_websocket()
    mock_client = MagicMock()
    mock_client._client_wrapper.get_base_url.return_value = "https://api.elevenlabs.io"
    agent_response_callback = AsyncMock()

    dynamic_variables = {"name": "angelo"}
    config = ConversationInitiationData(dynamic_variables=dynamic_variables)

    # Setup the conversation
    conversation = AsyncConversation(
        client=mock_client,
        config=config,
        agent_id=TEST_AGENT_ID,
        requires_auth=False,
        audio_interface=MockAsyncAudioInterface(),
        callback_agent_response=agent_response_callback,
    )

    # Run the test
    with patch("elevenlabs.conversational_ai.conversation.websockets.connect") as mock_connect:
        mock_connect.return_value.__aenter__.return_value = mock_ws

        await conversation.start_session()

        # Wait a bit for the callback to be called
        await asyncio.sleep(0.1)

        await conversation.end_session()
        await conversation.wait_for_session_end()

    # Assertions - check the call was made with the right structure
    send_calls = [call[0][0] for call in mock_ws.send.call_args_list]
    init_messages = [json.loads(call) for call in send_calls if "conversation_initiation_client_data" in call]
    assert len(init_messages) == 1
    init_message = init_messages[0]

    assert init_message["type"] == "conversation_initiation_client_data"
    assert init_message["custom_llm_extra_body"] == {}
    assert init_message["conversation_config_override"] == {}
    assert init_message["dynamic_variables"] == {"name": "angelo"}
    assert init_message["source_info"]["source"] == "python_sdk"
    assert "version" in init_message["source_info"]
    agent_response_callback.assert_called_once_with("Hello there!")
    assert conversation._conversation_id == TEST_CONVERSATION_ID


@pytest.mark.asyncio
async def test_async_conversation_with_contextual_update():
    # Mock setup
    mock_ws = create_mock_async_websocket([])
    mock_client = MagicMock()
    mock_client._client_wrapper.get_base_url.return_value = "https://api.elevenlabs.io"

    # Setup the conversation
    conversation = AsyncConversation(
        client=mock_client,
        agent_id=TEST_AGENT_ID,
        requires_auth=False,
        audio_interface=MockAsyncAudioInterface(),
    )

    # Run the test
    with patch("elevenlabs.conversational_ai.conversation.websockets.connect") as mock_connect:
        mock_connect.return_value.__aenter__.return_value = mock_ws

        await conversation.start_session()
        await asyncio.sleep(0.1)

        await conversation.send_contextual_update("User appears to be looking at pricing page")

        # Teardown
        await conversation.end_session()
        await conversation.wait_for_session_end()

    # Assertions
    expected = json.dumps({"type": "contextual_update", "text": "User appears to be looking at pricing page"})
    mock_ws.send.assert_any_call(expected)


@pytest.mark.asyncio
async def test_async_conversation_send_user_message():
    # Mock setup
    mock_ws = create_mock_async_websocket([])
    mock_client = MagicMock()
    mock_client._client_wrapper.get_base_url.return_value = "https://api.elevenlabs.io"

    # Setup the conversation
    conversation = AsyncConversation(
        client=mock_client,
        agent_id=TEST_AGENT_ID,
        requires_auth=False,
        audio_interface=MockAsyncAudioInterface(),
    )

    # Run the test
    with patch("elevenlabs.conversational_ai.conversation.websockets.connect") as mock_connect:
        mock_connect.return_value.__aenter__.return_value = mock_ws

        await conversation.start_session()
        await asyncio.sleep(0.1)

        await conversation.send_user_message("Hello, how are you?")

        # Teardown
        await conversation.end_session()
        await conversation.wait_for_session_end()

    # Assertions
    expected = json.dumps({"type": "user_message", "text": "Hello, how are you?"})
    mock_ws.send.assert_any_call(expected)


@pytest.mark.asyncio
async def test_async_conversation_register_user_activity():
    # Mock setup
    mock_ws = create_mock_async_websocket([])
    mock_client = MagicMock()
    mock_client._client_wrapper.get_base_url.return_value = "https://api.elevenlabs.io"

    # Setup the conversation
    conversation = AsyncConversation(
        client=mock_client,
        agent_id=TEST_AGENT_ID,
        requires_auth=False,
        audio_interface=MockAsyncAudioInterface(),
    )

    # Run the test
    with patch("elevenlabs.conversational_ai.conversation.websockets.connect") as mock_connect:
        mock_connect.return_value.__aenter__.return_value = mock_ws

        await conversation.start_session()
        await asyncio.sleep(0.1)

        await conversation.register_user_activity()

        # Teardown
        await conversation.end_session()
        await conversation.wait_for_session_end()

    # Assertions
    expected = json.dumps({"type": "user_activity"})
    mock_ws.send.assert_any_call(expected)


@pytest.mark.asyncio
async def test_async_conversation_callback_flows():
    # Mock setup for testing all callback types
    messages = [
        {
            "type": "conversation_initiation_metadata",
            "conversation_initiation_metadata_event": {"conversation_id": TEST_CONVERSATION_ID},
        },
        {"type": "agent_response", "agent_response_event": {"agent_response": "Hello there!"}},
        {
            "type": "agent_response_correction",
            "agent_response_correction_event": {
                "original_agent_response": "Hello ther!",
                "corrected_agent_response": "Hello there!",
            },
        },
        {"type": "user_transcript", "user_transcription_event": {"user_transcript": "Hi, how are you?"}},
        {"type": "ping", "ping_event": {"event_id": "123", "ping_ms": 50}},
        {"type": "interruption", "interruption_event": {"event_id": "456"}},
        {
            "type": "audio",
            "audio_event": {"event_id": "789", "audio_base_64": "dGVzdA=="},  # "test" in base64
        },
    ]

    mock_ws = create_mock_async_websocket(messages)
    mock_client = MagicMock()
    mock_client._client_wrapper.get_base_url.return_value = "https://api.elevenlabs.io"

    # Setup callbacks
    agent_response_callback = AsyncMock()
    agent_response_correction_callback = AsyncMock()
    user_transcript_callback = AsyncMock()
    latency_measurement_callback = AsyncMock()
    end_session_callback = AsyncMock()

    # Setup the conversation
    conversation = AsyncConversation(
        client=mock_client,
        agent_id=TEST_AGENT_ID,
        requires_auth=False,
        audio_interface=MockAsyncAudioInterface(),
        callback_agent_response=agent_response_callback,
        callback_agent_response_correction=agent_response_correction_callback,
        callback_user_transcript=user_transcript_callback,
        callback_latency_measurement=latency_measurement_callback,
        callback_end_session=end_session_callback,
    )

    # Run the test
    with patch("elevenlabs.conversational_ai.conversation.websockets.connect") as mock_connect:
        mock_connect.return_value.__aenter__.return_value = mock_ws

        await conversation.start_session()

        # Wait for callbacks to be processed
        await asyncio.sleep(0.2)

        await conversation.end_session()
        await conversation.wait_for_session_end()

    # Assertions
    agent_response_callback.assert_called_with("Hello there!")
    agent_response_correction_callback.assert_called_with("Hello ther!", "Hello there!")
    user_transcript_callback.assert_called_with("Hi, how are you?")
    latency_measurement_callback.assert_called_with(50)
    end_session_callback.assert_called_once()
    assert conversation._conversation_id == TEST_CONVERSATION_ID
    assert conversation._last_interrupt_id == 456


@pytest.mark.asyncio
async def test_async_conversation_wss_url_generation_without_get_environment():
    from elevenlabs.core.client_wrapper import SyncClientWrapper

    # Test with various base URL formats to ensure robustness
    test_cases = [
        ("https://api.elevenlabs.io", "wss://api.elevenlabs.io"),
        ("https://api.us.elevenlabs.io", "wss://api.us.elevenlabs.io"),
        ("https://api.eu.residency.elevenlabs.io", "wss://api.eu.residency.elevenlabs.io"),
        ("http://localhost:8000", "ws://localhost:8000"),
    ]

    for base_url, expected_ws_base in test_cases:
        # Create a real SyncClientWrapper to ensure it doesn't have get_environment method
        mock_client = MagicMock()
        mock_client._client_wrapper = SyncClientWrapper(
            base_url=base_url, api_key="test_key", httpx_client=MagicMock(), timeout=30.0
        )

        conversation = AsyncConversation(
            client=mock_client, agent_id=TEST_AGENT_ID, requires_auth=False, audio_interface=MockAsyncAudioInterface()
        )

        try:
            wss_url = conversation._get_wss_url()

            # Verify the URL is correctly generated
            expected_url = (
                f"{expected_ws_base}/v1/convai/conversation?agent_id={TEST_AGENT_ID}&source=python_sdk&version="
            )
            assert wss_url.startswith(expected_url), f"URL should start with {expected_url}, got {wss_url}"

            # Verify the URL contains version parameter
            assert "version=" in wss_url, f"URL should contain version parameter, got {wss_url}"

        except AttributeError as e:
            if "get_environment" in str(e):
                assert False
            else:
                raise  # Re-raise if it's a different AttributeError

        except Exception as e:
            assert False, f"Unexpected error generating WebSocket URL: {e}"


@pytest.mark.asyncio
async def test_async_websocket_url_construction_edge_cases():
    """Test WebSocket URL construction edge cases for async conversation, specifically for trailing slash handling."""
    from elevenlabs.conversational_ai.conversation import AsyncConversation
    from elevenlabs.core.client_wrapper import SyncClientWrapper

    # Test cases with various base URL formats
    test_cases = [
        # Base URLs without trailing slashes (the main edge case)
        ("https://api.eu.residency.elevenlabs.io", "wss://api.eu.residency.elevenlabs.io"),
        ("https://api.elevenlabs.io", "wss://api.elevenlabs.io"),
        ("http://localhost:8000", "ws://localhost:8000"),
        # Base URLs with trailing slashes (should still work)
        ("https://api.eu.residency.elevenlabs.io/", "wss://api.eu.residency.elevenlabs.io"),
        ("https://api.elevenlabs.io/", "wss://api.elevenlabs.io"),
        ("http://localhost:8000/", "ws://localhost:8000"),
    ]

    for base_url, expected_ws_base in test_cases:
        # Test async conversation WebSocket URL construction
        mock_client = MagicMock()
        mock_client._client_wrapper = SyncClientWrapper(
            base_url=base_url, api_key="test_key", httpx_client=MagicMock(), timeout=30.0
        )

        conversation = AsyncConversation(
            client=mock_client, agent_id=TEST_AGENT_ID, requires_auth=False, audio_interface=MockAsyncAudioInterface()
        )

        # Test conversation URL generation
        conv_url = conversation._get_wss_url()
        expected_conv_url = f"{expected_ws_base}/v1/convai/conversation"
        assert (
            expected_conv_url in conv_url
        ), f"Async conversation URL should contain {expected_conv_url}, got {conv_url}"

        # Ensure no double slashes in the path (except after the protocol)
        url_path = conv_url.split("://", 1)[1]  # Remove protocol
        assert "//" not in url_path, f"Async conversation URL should not contain double slashes in path: {conv_url}"