livekit-plugins-facemode 0.2.0__tar.gz → 0.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (18) hide show
  1. {livekit_plugins_facemode-0.2.0 → livekit_plugins_facemode-0.3.1}/PKG-INFO +3 -3
  2. {livekit_plugins_facemode-0.2.0 → livekit_plugins_facemode-0.3.1}/README.md +2 -2
  3. {livekit_plugins_facemode-0.2.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode/avatar.py +171 -16
  4. livekit_plugins_facemode-0.3.1/livekit_plugins_facemode/version.py +1 -0
  5. {livekit_plugins_facemode-0.2.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode.egg-info/PKG-INFO +3 -3
  6. {livekit_plugins_facemode-0.2.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode.egg-info/SOURCES.txt +2 -1
  7. {livekit_plugins_facemode-0.2.0 → livekit_plugins_facemode-0.3.1}/pyproject.toml +1 -1
  8. livekit_plugins_facemode-0.3.1/test/test_playback.py +256 -0
  9. livekit_plugins_facemode-0.2.0/livekit_plugins_facemode/version.py +0 -1
  10. {livekit_plugins_facemode-0.2.0 → livekit_plugins_facemode-0.3.1}/LICENSE +0 -0
  11. {livekit_plugins_facemode-0.2.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode/__init__.py +0 -0
  12. {livekit_plugins_facemode-0.2.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode/exceptions.py +0 -0
  13. {livekit_plugins_facemode-0.2.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode/models.py +0 -0
  14. {livekit_plugins_facemode-0.2.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode.egg-info/dependency_links.txt +0 -0
  15. {livekit_plugins_facemode-0.2.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode.egg-info/requires.txt +0 -0
  16. {livekit_plugins_facemode-0.2.0 → livekit_plugins_facemode-0.3.1}/livekit_plugins_facemode.egg-info/top_level.txt +0 -0
  17. {livekit_plugins_facemode-0.2.0 → livekit_plugins_facemode-0.3.1}/setup.cfg +0 -0
  18. {livekit_plugins_facemode-0.2.0 → livekit_plugins_facemode-0.3.1}/test/test_ingestion.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: livekit-plugins-facemode
3
- Version: 0.2.0
3
+ Version: 0.3.1
4
4
  Summary: FaceMode avatar integration for LiveKit Agents
5
5
  Author: FaceMode
6
6
  License-Expression: Apache-2.0
@@ -22,7 +22,7 @@ Dynamic: license-file
22
22
 
23
23
  # livekit-plugins-facemode
24
24
 
25
- FaceMode avatar output for LiveKit Agents Python applications.
25
+ [FaceMode](https://facemode.io) avatar output for LiveKit Agents Python applications.
26
26
 
27
27
  ## Install
28
28
 
@@ -36,7 +36,7 @@ From this repository:
36
36
  pip install .
37
37
  ```
38
38
 
39
- Requires Python 3.13 or later, LiveKit 1.x, and LiveKit Agents 1.7 or later.
39
+ Requires Python 3.13 or later, `livekit>=1.1,<2`, and `livekit-agents>=1.7,<2`.
40
40
 
41
41
  ## Usage
42
42
 
@@ -1,6 +1,6 @@
1
1
  # livekit-plugins-facemode
2
2
 
3
- FaceMode avatar output for LiveKit Agents Python applications.
3
+ [FaceMode](https://facemode.io) avatar output for LiveKit Agents Python applications.
4
4
 
5
5
  ## Install
6
6
 
@@ -14,7 +14,7 @@ From this repository:
14
14
  pip install .
15
15
  ```
16
16
 
17
- Requires Python 3.13 or later, LiveKit 1.x, and LiveKit Agents 1.7 or later.
17
+ Requires Python 3.13 or later, `livekit>=1.1,<2`, and `livekit-agents>=1.7,<2`.
18
18
 
19
19
  ## Usage
20
20
 
@@ -57,6 +57,15 @@ _PREFERRED_SAMPLE_RATES = frozenset(
57
57
 
58
58
 
59
59
  class _FaceModeAudioOutput(AudioOutput):
60
+ """Audio sink forwarding TTS audio to the FaceMode ingestion socket.
61
+
62
+ Playback completion is reported only when the server confirms it through
63
+ ``utterance_ended``: TTS audio is forwarded faster than realtime, so the
64
+ framework's speech handle must stay interruptible while the server-side
65
+ queue is still draining. The pending-report ledger lives on the owner so
66
+ reconnects and session teardown can settle interrupted segments.
67
+ """
68
+
60
69
  def __init__(self, owner: "AvatarSession"):
61
70
  super().__init__(
62
71
  label="FaceModeAudioOutput",
@@ -66,6 +75,9 @@ class _FaceModeAudioOutput(AudioOutput):
66
75
  )
67
76
  self.owner = owner
68
77
  self._utterance_started = False
78
+ self._segment_duration = 0.0
79
+ self._segment_started_at: float | None = None
80
+ self._end_task: asyncio.Task | None = None
69
81
 
70
82
  async def capture_frame(self, frame: rtc.AudioFrame) -> None:
71
83
  await self.owner._drain_control_tasks()
@@ -74,23 +86,75 @@ class _FaceModeAudioOutput(AudioOutput):
74
86
  await self.owner._ensure_protocol_started(frame.sample_rate, frame.num_channels)
75
87
  await self.owner._send_start_utterance()
76
88
  self._utterance_started = True
89
+ self._segment_duration = 0.0
90
+ self._segment_started_at = time.monotonic()
91
+ self.on_playback_started(created_at=time.time())
92
+ self._segment_duration += _frame_duration_seconds(frame)
77
93
  await self.owner._send_tts_audio(frame)
78
94
 
79
95
  def flush(self) -> None:
80
96
  super().flush()
81
- if self._utterance_started:
82
- self.owner._schedule_control(self._finish_utterance(), "facemode-end-utterance")
83
- self._utterance_started = False
97
+ if not self._utterance_started:
98
+ return
99
+ sequence = self.owner._next_sequence()
100
+ self.owner._register_pending_playback(
101
+ sequence, playback_position=self._segment_duration
102
+ )
103
+ self._end_task = self.owner._schedule_control(
104
+ self._end_utterance(sequence), "facemode-end-utterance"
105
+ )
106
+ self._utterance_started = False
84
107
 
85
108
  def clear_buffer(self) -> None:
86
- if self._utterance_started:
109
+ # The framework flushes before clearing, so an interrupted utterance
110
+ # usually already sent end_utterance. The server-side queue is still
111
+ # draining at that point and must be told to discard it; the cancel is
112
+ # chained after the end send so the wire order stays end-then-cancel.
113
+ streaming = self._utterance_started
114
+ has_unconfirmed_end = bool(self.owner._pending_playback)
115
+ if streaming or has_unconfirmed_end:
116
+ sequence = self.owner._next_sequence()
87
117
  self.owner._schedule_control(
88
- self.owner._send_cancel_utterance(), "facemode-cancel-utterance"
118
+ self._cancel_utterance(
119
+ sequence, streaming, self._interrupted_position(), self._end_task
120
+ ),
121
+ "facemode-cancel-utterance",
89
122
  )
90
123
  self._utterance_started = False
91
-
92
- async def _finish_utterance(self) -> None:
93
- await self.owner._send_end_utterance()
124
+ self._end_task = None
125
+
126
+ def _interrupted_position(self) -> float:
127
+ if self._segment_started_at is None:
128
+ return 0.0
129
+ elapsed = time.monotonic() - self._segment_started_at
130
+ return max(0.0, min(self._segment_duration, elapsed))
131
+
132
+ async def _end_utterance(self, sequence: int) -> None:
133
+ sent = await self.owner._send_end_utterance(sequence)
134
+ if not sent:
135
+ # The end never reached the server (e.g. the transport dropped into
136
+ # a reconnect first), so no confirmation can ever arrive; the
137
+ # segment is abandoned rather than completed.
138
+ self.owner._drop_pending_playback(sequence)
139
+
140
+ async def _cancel_utterance(
141
+ self,
142
+ sequence: int,
143
+ streaming: bool,
144
+ playback_position: float,
145
+ end_task: asyncio.Task | None,
146
+ ) -> None:
147
+ if end_task is not None and end_task is not asyncio.current_task():
148
+ with contextlib.suppress(Exception):
149
+ await end_task
150
+ # A server-side cancel wipes every queued speech/end marker, so each
151
+ # unconfirmed end settles here as interrupted; its own utterance_ended
152
+ # can never arrive. The cancel control frame itself is not a captured
153
+ # segment and gets no ledger entry - its confirmation is ignored.
154
+ self.owner._settle_unconfirmed_playback()
155
+ if streaming:
156
+ self.on_playback_finished(playback_position=playback_position, interrupted=True)
157
+ await self.owner._send_cancel_utterance(sequence)
94
158
 
95
159
 
96
160
  class AvatarSession(BaseAvatarSession):
@@ -140,6 +204,8 @@ class AvatarSession(BaseAvatarSession):
140
204
  self._audio_sample_rate: int | None = None
141
205
  self._audio_channels: int | None = None
142
206
  self._session_log_marker: str | None = None
207
+ self._audio_output: _FaceModeAudioOutput | None = None
208
+ self._pending_playback: dict[int, dict[str, Any]] = {}
143
209
  self._sequence = 0
144
210
  self._started_once = False
145
211
  self._stopped = False
@@ -229,7 +295,8 @@ class AvatarSession(BaseAvatarSession):
229
295
  )
230
296
  if getattr(agent_session, "output", None) is None:
231
297
  raise FaceModeAPIError("LiveKit AgentSession output is not initialized")
232
- agent_session.output.replace_audio_tail(_FaceModeAudioOutput(self))
298
+ self._audio_output = _FaceModeAudioOutput(self)
299
+ agent_session.output.replace_audio_tail(self._audio_output)
233
300
  self._join_task = asyncio.create_task(
234
301
  self._wait_for_video_track(), name="facemode-avatar-join"
235
302
  )
@@ -262,6 +329,7 @@ class AvatarSession(BaseAvatarSession):
262
329
  if self._stopped:
263
330
  return
264
331
  self._stopped = True
332
+ self._fail_pending_playback()
265
333
  await self._cancel_task(self._keepalive_task)
266
334
  self._keepalive_task = None
267
335
  await self._cancel_task(self._reconnect_task)
@@ -491,6 +559,7 @@ class AvatarSession(BaseAvatarSession):
491
559
  self._protocol_started.clear()
492
560
  self._protocol_response.clear()
493
561
  self._avatar_ready.clear()
562
+ self._fail_pending_playback()
494
563
  task = asyncio.create_task(self._reconnect(), name="facemode-ws-reconnect")
495
564
  self._reconnect_task = task
496
565
  return task
@@ -512,7 +581,12 @@ class AvatarSession(BaseAvatarSession):
512
581
  pending = None
513
582
  adopted = False
514
583
  try:
584
+ # A failed attempt records the error through _set_protocol_error,
585
+ # which also sets _protocol_response. Both must be re-armed
586
+ # together: clearing only the error leaves the event set, and
587
+ # _wait_for_send_ready would spin without ever yielding.
515
588
  self._protocol_error = None
589
+ self._protocol_response.clear()
516
590
  refreshed = await self._request_reconnect_session()
517
591
  self.session = refreshed
518
592
  pending = await self._connect_websocket()
@@ -521,6 +595,12 @@ class AvatarSession(BaseAvatarSession):
521
595
  await pending.send(self._start_message())
522
596
  await self._await_reconnect_started(pending)
523
597
  adopted = True
598
+ output = self._audio_output
599
+ if output is not None:
600
+ # The fresh socket has no utterance state. Clearing the flag
601
+ # makes the next captured frame re-declare start_utterance
602
+ # through the normal path, keeping the wire order correct.
603
+ output._utterance_started = False
524
604
  logger.info(
525
605
  "FaceMode WebSocket reconnected session=%s attempt=%s",
526
606
  self._session_log_marker,
@@ -587,13 +667,17 @@ class AvatarSession(BaseAvatarSession):
587
667
  async def _send_start_utterance(self) -> None:
588
668
  await self._send_control("start_utterance", self._next_sequence())
589
669
 
590
- async def _send_end_utterance(self) -> None:
591
- if self._protocol_started.is_set():
592
- await self._send_control("end_utterance", self._next_sequence())
670
+ async def _send_end_utterance(self, sequence: int) -> bool:
671
+ if not self._protocol_started.is_set():
672
+ return False
673
+ await self._send_control("end_utterance", sequence)
674
+ return True
593
675
 
594
- async def _send_cancel_utterance(self) -> None:
595
- if self._protocol_started.is_set():
596
- await self._send_control("cancel_utterance", self._next_sequence())
676
+ async def _send_cancel_utterance(self, sequence: int) -> bool:
677
+ if not self._protocol_started.is_set():
678
+ return False
679
+ await self._send_control("cancel_utterance", sequence)
680
+ return True
597
681
 
598
682
  async def _send_tts_audio(self, frame: rtc.AudioFrame) -> None:
599
683
  await self._ensure_protocol_started(frame.sample_rate, frame.num_channels)
@@ -792,6 +876,7 @@ class AvatarSession(BaseAvatarSession):
792
876
  elif message_type == "audio_ready":
793
877
  self._avatar_ready.set()
794
878
  elif message_type == "utterance_ended":
879
+ self._resolve_pending_playback(message)
795
880
  logger.debug(
796
881
  "FaceMode utterance ended seq=%s cycles=%s",
797
882
  message.get("seq"),
@@ -808,6 +893,7 @@ class AvatarSession(BaseAvatarSession):
808
893
  elif message_type == "ended":
809
894
  self._session_ended.set()
810
895
  self._protocol_response.set()
896
+ self._fail_pending_playback()
811
897
  elif message_type == "error":
812
898
  protocol_error = FaceModeProtocolError(
813
899
  f"{message.get('code', 'INTERNAL_ERROR')}: {message.get('message', 'FaceMode error')}"
@@ -872,10 +958,11 @@ class AvatarSession(BaseAvatarSession):
872
958
  for publication in participant.track_publications.values()
873
959
  )
874
960
 
875
- def _schedule_control(self, coroutine, name: str) -> None:
961
+ def _schedule_control(self, coroutine, name: str) -> asyncio.Task:
876
962
  task = asyncio.create_task(coroutine, name=name)
877
963
  self._control_tasks.add(task)
878
964
  task.add_done_callback(self._control_task_done)
965
+ return task
879
966
 
880
967
  def _control_task_done(self, task: asyncio.Task) -> None:
881
968
  self._control_tasks.discard(task)
@@ -916,8 +1003,67 @@ class AvatarSession(BaseAvatarSession):
916
1003
  def _set_protocol_error(self, error: FaceModeError) -> None:
917
1004
  if self._protocol_error is None:
918
1005
  self._protocol_error = error
1006
+ self._fail_pending_playback()
919
1007
  self._protocol_response.set()
920
1008
 
1009
+ def _register_pending_playback(self, sequence: int, *, playback_position: float) -> None:
1010
+ self._pending_playback[sequence] = {"position": playback_position}
1011
+
1012
+ def _report_playback_finished(self, entry: dict[str, Any], *, interrupted: bool) -> None:
1013
+ output = self._audio_output
1014
+ if output is None:
1015
+ return
1016
+ output.on_playback_finished(
1017
+ playback_position=float(entry.get("position", 0.0)),
1018
+ interrupted=interrupted,
1019
+ )
1020
+
1021
+ def _resolve_pending_playback(self, message: Mapping[str, Any]) -> None:
1022
+ """Match one server ``utterance_ended`` to its segment report.
1023
+
1024
+ The echoed sequence is the protocol sequence of the end/cancel control
1025
+ frame the server consumed. Confirmations for entries already settled
1026
+ by a cancel, reconnect, or teardown are unmatched and ignored.
1027
+ """
1028
+ sequence = message.get("seq")
1029
+ entry = self._pending_playback.pop(sequence, None) if isinstance(sequence, int) else None
1030
+ if entry is None:
1031
+ return
1032
+ self._report_playback_finished(entry, interrupted=False)
1033
+
1034
+ def _settle_unconfirmed_playback(self) -> None:
1035
+ """Report every end-confirmed-pending segment as interrupted.
1036
+
1037
+ A server-side cancel wipes all queued speech/end markers, so ends
1038
+ that have not been confirmed yet will never produce their own
1039
+ ``utterance_ended``. Each captured segment owes the framework exactly
1040
+ one playback report, so they are settled here before the cancel goes
1041
+ out; the cancel's own confirmation resolves the final segment.
1042
+ """
1043
+ unconfirmed = list(self._pending_playback)
1044
+ for sequence in unconfirmed:
1045
+ entry = self._pending_playback.pop(sequence, None)
1046
+ if entry is not None:
1047
+ self._report_playback_finished(entry, interrupted=True)
1048
+
1049
+ def _drop_pending_playback(self, sequence: int) -> None:
1050
+ """Settle one ledger entry as interrupted when its end never went out."""
1051
+ entry = self._pending_playback.pop(sequence, None)
1052
+ if entry is not None:
1053
+ self._report_playback_finished(entry, interrupted=True)
1054
+
1055
+ def _fail_pending_playback(self) -> None:
1056
+ """Settle every pending segment as interrupted.
1057
+
1058
+ Used when the transport drops or the session stops: the server
1059
+ discards in-flight utterances on disconnect, so no confirmation can
1060
+ ever arrive for them.
1061
+ """
1062
+ entries = list(self._pending_playback.values())
1063
+ self._pending_playback.clear()
1064
+ for entry in entries:
1065
+ self._report_playback_finished(entry, interrupted=True)
1066
+
921
1067
  def _raise_protocol_error(self) -> None:
922
1068
  if self._protocol_error is not None:
923
1069
  raise self._protocol_error
@@ -928,6 +1074,15 @@ class AvatarSession(BaseAvatarSession):
928
1074
  return sequence
929
1075
 
930
1076
 
1077
+ def _frame_duration_seconds(frame: rtc.AudioFrame) -> float:
1078
+ duration = getattr(frame, "duration", None)
1079
+ if isinstance(duration, (int, float)) and duration > 0:
1080
+ return float(duration)
1081
+ channels = max(int(frame.num_channels), 1)
1082
+ rate = max(int(frame.sample_rate), 1)
1083
+ return len(frame.data) / (2.0 * channels * rate)
1084
+
1085
+
931
1086
  def _token_identity_hint(token: str) -> str | None:
932
1087
  claims = _token_claims_hint(token)
933
1088
  identity = claims.get("sub") if claims else None
@@ -0,0 +1 @@
1
+ __version__ = "0.3.1"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: livekit-plugins-facemode
3
- Version: 0.2.0
3
+ Version: 0.3.1
4
4
  Summary: FaceMode avatar integration for LiveKit Agents
5
5
  Author: FaceMode
6
6
  License-Expression: Apache-2.0
@@ -22,7 +22,7 @@ Dynamic: license-file
22
22
 
23
23
  # livekit-plugins-facemode
24
24
 
25
- FaceMode avatar output for LiveKit Agents Python applications.
25
+ [FaceMode](https://facemode.io) avatar output for LiveKit Agents Python applications.
26
26
 
27
27
  ## Install
28
28
 
@@ -36,7 +36,7 @@ From this repository:
36
36
  pip install .
37
37
  ```
38
38
 
39
- Requires Python 3.13 or later, LiveKit 1.x, and LiveKit Agents 1.7 or later.
39
+ Requires Python 3.13 or later, `livekit>=1.1,<2`, and `livekit-agents>=1.7,<2`.
40
40
 
41
41
  ## Usage
42
42
 
@@ -11,4 +11,5 @@ livekit_plugins_facemode.egg-info/SOURCES.txt
11
11
  livekit_plugins_facemode.egg-info/dependency_links.txt
12
12
  livekit_plugins_facemode.egg-info/requires.txt
13
13
  livekit_plugins_facemode.egg-info/top_level.txt
14
- test/test_ingestion.py
14
+ test/test_ingestion.py
15
+ test/test_playback.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "livekit-plugins-facemode"
7
- version = "0.2.0"
7
+ version = "0.3.1"
8
8
  license = "Apache-2.0"
9
9
  license-files = ["LICENSE"]
10
10
  readme = "README.md"
@@ -0,0 +1,256 @@
1
+ import asyncio
2
+ import json
3
+ import unittest
4
+ from unittest.mock import patch
5
+
6
+ from livekit import rtc
7
+
8
+ from livekit_plugins_facemode import avatar as avatar_module
9
+ from livekit_plugins_facemode.avatar import AvatarSession
10
+ from livekit_plugins_facemode.models import LiveKitRoom, SessionDetails
11
+
12
+ from test_ingestion import _FakeWebSocket, _PostClient, _Response, _fake_connect
13
+
14
+
15
+ def _running_avatar(room):
16
+ """A session that already negotiated the canonical protocol once."""
17
+ avatar = AvatarSession(
18
+ api_key="api-key",
19
+ avatar_id="avatar-1",
20
+ api_url="https://api.example.test/api",
21
+ )
22
+ avatar.session = SessionDetails.from_api(
23
+ {
24
+ "sessionId": "session-123",
25
+ "room": room.to_payload(),
26
+ "workerStatus": "ACTIVE",
27
+ "ingestion": {
28
+ "ready": True,
29
+ "url": "wss://worker.example.test/ws/session-123",
30
+ "wsToken": "token-1",
31
+ },
32
+ }
33
+ )
34
+ avatar._websocket = _FakeWebSocket()
35
+ avatar._protocol_started.set()
36
+ avatar._protocol_response.set()
37
+ avatar._audio_sample_rate = 16000
38
+ avatar._audio_channels = 1
39
+ avatar._session_log_marker = "session-123"
40
+ return avatar
41
+
42
+
43
+ def _reconnect_response(token):
44
+ return _Response(
45
+ json.dumps(
46
+ {
47
+ "workerStatus": "ACTIVE",
48
+ "ingestion": {
49
+ "ready": True,
50
+ "url": "wss://worker.example.test/ws/session-123",
51
+ "wsToken": token,
52
+ "headers": {},
53
+ },
54
+ }
55
+ )
56
+ )
57
+
58
+
59
+ class _PlaybackHarness:
60
+ """Wires a running avatar to its audio output and captures playback reports."""
61
+
62
+ def __init__(self, avatar):
63
+ self.avatar = avatar
64
+ self.output = avatar_module._FaceModeAudioOutput(avatar)
65
+ avatar._audio_output = self.output
66
+ self.finished = []
67
+ self.output.on("playback_finished", self.finished.append)
68
+
69
+ def frame(self, samples=160, rate=16000):
70
+ return rtc.AudioFrame(
71
+ data=b"\x01\x00" * samples,
72
+ sample_rate=rate,
73
+ num_channels=1,
74
+ samples_per_channel=samples,
75
+ )
76
+
77
+ async def capture(self, count=2, samples=160, rate=16000):
78
+ for _ in range(count):
79
+ await self.output.capture_frame(self.frame(samples, rate))
80
+
81
+ def utterance_ended(self, seq, cancelled=False):
82
+ self.avatar._dispatch_message(
83
+ json.dumps(
84
+ {"type": "utterance_ended", "seq": seq, "cycles": 3, "cancelled": cancelled}
85
+ )
86
+ )
87
+
88
+ def control_types(self):
89
+ return [
90
+ m["type"]
91
+ for m in self.avatar._websocket.text_messages()
92
+ if m["type"] in ("start_utterance", "end_utterance", "cancel_utterance")
93
+ ]
94
+
95
+ def control_seq(self, message_type):
96
+ return next(
97
+ m["seq"]
98
+ for m in self.avatar._websocket.text_messages()
99
+ if m["type"] == message_type
100
+ )
101
+
102
+
103
+ class _RoomMixin:
104
+ def setUp(self):
105
+ self.room = LiveKitRoom(
106
+ url="wss://livekit.example.test",
107
+ token="worker-room-token",
108
+ name="room-123",
109
+ )
110
+
111
+
112
+ class LiveKitPlaybackReportingTests(_RoomMixin, unittest.IsolatedAsyncioTestCase):
113
+ async def test_playback_finished_waits_for_server_confirmation(self):
114
+ harness = _PlaybackHarness(_running_avatar(self.room))
115
+ await harness.capture(count=2) # 2 x 10ms at 16kHz = 0.02s of audio
116
+ harness.output.flush()
117
+ await harness.avatar._drain_control_tasks()
118
+
119
+ # end_utterance went out, but playback must not be reported yet
120
+ self.assertIn("end_utterance", harness.control_types())
121
+ self.assertEqual(harness.finished, [])
122
+
123
+ harness.utterance_ended(harness.control_seq("end_utterance"))
124
+ self.assertEqual(len(harness.finished), 1)
125
+ event = harness.finished[0]
126
+ self.assertFalse(event.interrupted)
127
+ self.assertAlmostEqual(event.playback_position, 0.02, places=3)
128
+
129
+ async def test_interruption_after_flush_sends_end_then_cancel(self):
130
+ harness = _PlaybackHarness(_running_avatar(self.room))
131
+ await harness.capture(count=2)
132
+ harness.output.flush()
133
+ harness.output.clear_buffer()
134
+ await harness.avatar._drain_control_tasks()
135
+
136
+ types = harness.control_types()
137
+ self.assertIn("end_utterance", types)
138
+ self.assertIn("cancel_utterance", types)
139
+ self.assertLess(types.index("end_utterance"), types.index("cancel_utterance"))
140
+
141
+ # exactly one report for the single captured segment, interrupted
142
+ self.assertEqual(len(harness.finished), 1)
143
+ self.assertTrue(harness.finished[0].interrupted)
144
+
145
+ async def test_confirmed_completion_then_idle_interruption_sends_no_cancel(self):
146
+ harness = _PlaybackHarness(_running_avatar(self.room))
147
+ await harness.capture(count=1)
148
+ harness.output.flush()
149
+ await harness.avatar._drain_control_tasks()
150
+ harness.utterance_ended(harness.control_seq("end_utterance"))
151
+ self.assertEqual(len(harness.finished), 1)
152
+
153
+ # playback fully confirmed: a later stray clear_buffer is a no-op
154
+ harness.output.clear_buffer()
155
+ await harness.avatar._drain_control_tasks()
156
+ self.assertNotIn("cancel_utterance", harness.control_types())
157
+ self.assertEqual(len(harness.finished), 1)
158
+
159
+ async def test_reconnect_settles_pending_playback_as_interrupted(self):
160
+ harness = _PlaybackHarness(_running_avatar(self.room))
161
+ await harness.capture(count=2)
162
+ harness.output.flush()
163
+ await harness.avatar._drain_control_tasks()
164
+ self.assertEqual(harness.finished, [])
165
+
166
+ # transport drops while the protocol is still up, as in the receiver path
167
+ harness.avatar._start_reconnect()
168
+ self.assertEqual(len(harness.finished), 1)
169
+ self.assertTrue(harness.finished[0].interrupted)
170
+ harness.avatar._reconnect_task.cancel()
171
+ try:
172
+ await harness.avatar._reconnect_task
173
+ except asyncio.CancelledError:
174
+ pass
175
+
176
+ async def test_end_dropped_during_reconnect_settles_segment(self):
177
+ harness = _PlaybackHarness(_running_avatar(self.room))
178
+ await harness.capture(count=1)
179
+ # simulate transport loss before the end send executes: the protocol
180
+ # is down, so end_utterance silently cannot go out
181
+ harness.avatar._protocol_started.clear()
182
+ harness.output.flush()
183
+ await harness.avatar._drain_control_tasks()
184
+
185
+ self.assertNotIn("end_utterance", harness.control_types())
186
+ self.assertEqual(len(harness.finished), 1)
187
+ self.assertTrue(harness.finished[0].interrupted)
188
+ self.assertEqual(harness.avatar._pending_playback, {})
189
+
190
+ async def test_pipelined_segments_each_report_exactly_once(self):
191
+ harness = _PlaybackHarness(_running_avatar(self.room))
192
+ # segment A completes input-side
193
+ await harness.capture(count=1)
194
+ harness.output.flush()
195
+ await harness.avatar._drain_control_tasks()
196
+ # segment B starts before A's confirmation arrives, then interruption
197
+ await harness.capture(count=1)
198
+ harness.output.flush()
199
+ harness.output.clear_buffer()
200
+ await harness.avatar._drain_control_tasks()
201
+
202
+ self.assertEqual(len(harness.finished), 2)
203
+ self.assertTrue(all(ev.interrupted for ev in harness.finished))
204
+ self.assertEqual(harness.avatar._pending_playback, {})
205
+
206
+ async def test_unmatched_utterance_ended_is_ignored(self):
207
+ harness = _PlaybackHarness(_running_avatar(self.room))
208
+ harness.utterance_ended(999)
209
+ self.assertEqual(harness.finished, [])
210
+
211
+
212
+ class LiveKitReconnectRetryTests(_RoomMixin, unittest.IsolatedAsyncioTestCase):
213
+ async def test_retry_rearms_protocol_response_event(self):
214
+ """A failed attempt sets _protocol_response through the error path; the
215
+ next attempt must clear it or _wait_for_send_ready spins freely."""
216
+ avatar = _running_avatar(self.room)
217
+ # first socket negotiates with the WRONG session id: the error path
218
+ # records a protocol error, which also sets the response event
219
+ bad_socket = _FakeWebSocket(session_id="wrong-session")
220
+ good_socket = _FakeWebSocket(session_id="session-123")
221
+ client = _PostClient(
222
+ [_reconnect_response("token-2"), _reconnect_response("token-3")]
223
+ )
224
+ event_states = []
225
+ original_request = avatar._request_reconnect_session
226
+
227
+ async def recording_request():
228
+ event_states.append(avatar._protocol_response.is_set())
229
+ return await original_request()
230
+
231
+ avatar._request_reconnect_session = recording_request
232
+
233
+ with (
234
+ patch(
235
+ "livekit_plugins_facemode.avatar.websockets.connect",
236
+ _fake_connect([bad_socket, good_socket], []),
237
+ ),
238
+ patch(
239
+ "livekit_plugins_facemode.avatar.aiohttp.ClientSession",
240
+ return_value=client,
241
+ ),
242
+ ):
243
+ avatar._protocol_started.clear()
244
+ avatar._protocol_response.clear()
245
+ await avatar._reconnect()
246
+
247
+ # reconnect eventually succeeded on the good socket
248
+ self.assertTrue(avatar._protocol_started.is_set())
249
+ self.assertIsNone(avatar._protocol_error)
250
+ # two attempts happened; the second must have re-armed a cleared event
251
+ self.assertEqual(len(event_states), 2)
252
+ self.assertFalse(event_states[1])
253
+
254
+
255
+ if __name__ == "__main__":
256
+ unittest.main()
@@ -1 +0,0 @@
1
- __version__ = "0.2.0"