Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,24 @@ All notable changes to `ojin-client` are documented here. The format follows

## Unreleased

## 0.12.1 - 2026-10-01

### Changed
- `WebRTCSettings.webrtc_join_timeout_s` now defaults to **90 s** (was 10 s). The
wait covers the model's cold start as well as the room join, and a cold start
alone can take more than 30 s, so the old default failed sessions the server
was about to start. An explicit value still wins; anything under ~60 s will
trip on cold starts.
- The `WEBRTC_JOIN_TIMEOUT` message now starts with `Timed out:`.

### Fixed
- A connection that the server closes before `sessionReady` without sending an
`errorResponse` (for example a failed entitlement check) is now reported at
once as a fatal `ERROR` with code `CONNECTION_CLOSED` and the WebSocket close
code and reason in the message. Previously nothing was reported: the WebSocket
client waited forever and the WebRTC client waited out the whole join timeout,
then blamed a timeout.

## 0.12.0 - 2026-09-29

### Added
Expand Down
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ avatar_token = (
| `WEBRTC_AUTH_FAILED` | The room rejected the avatar's token |
| `WEBRTC_NETWORK_FAILED` | Ojin couldn't reach the room |
| `WEBRTC_INVALID_SETTINGS` | The room URL or provider was unusable |
| `WEBRTC_JOIN_TIMEOUT` | The session wasn't ready within `webrtc_join_timeout_s` (default 10 s — it covers the model's cold start too, so leave headroom) |
| `WEBRTC_JOIN_TIMEOUT` | The session wasn't ready within `webrtc_join_timeout_s` (default 90 s — it covers the model's cold start too, which alone can take more than 30 s) |
| `WEBRTC_ROOM_LOST` | The avatar dropped out of the room mid-session |
| `WEBRTC_NOT_SUPPORTED` | The server returned no room result for this session |
| `WEBRTC_JOIN_FAILED` | Fallback: the join failed with a code this SDK doesn't recognise |
Expand Down Expand Up @@ -412,7 +412,7 @@ avatar_token = (

Video frames are emitted at the server's native resolution — read `STVVideoFrame.width`/`height` per frame rather than configuring an output size. Set `OJIN_MODE=dev` in the environment to attach the dev-mode query flag when connecting with the default transport.

For direct WebRTC, `WebRTCSettings` takes `provider`, `room_url`, `token`, `audio_sample_rate` (default `16000`) and `webrtc_join_timeout_s` (default `10.0`); the playback fields above don't apply because the media goes to the room.
For direct WebRTC, `WebRTCSettings` takes `provider`, `room_url`, `token`, `audio_sample_rate` (default `16000`) and `webrtc_join_timeout_s` (default `90.0`); the playback fields above don't apply because the media goes to the room.

---

Expand Down Expand Up @@ -491,7 +491,8 @@ async def main(pcm_16k_mono: bytes) -> None:
- **Choppy playback** — keep the event loop free; the SDK already decodes JPEG off-loop, but heavy synchronous work in your frame handlers will stall the 40 ms tick. Enable `STVConfig(lipsync_trace_enabled=True)` to inspect per-tick timing.
- **Latency higher than expected** — the WebSocket transport is built for **server-to-server** use over a stable connection. Run the client on a backend (not an end-user device), ideally in **US East**, close to Ojin's inference; deliver the final media to end users over a realtime transport such as WebRTC — or publish straight into their room with [direct WebRTC](#direct-webrtc-livekit--daily). The client keeps a small video buffer (`initial_buffer_frames`) to absorb network jitter, since the server delivers at realtime 25 fps.
- **`WEBRTC_AUTH_FAILED`** — the token doesn't grant the avatar access to that room. On LiveKit, check the token's identity is exactly `ojin-avatar` and it allows publishing; on Daily, check the meeting token is for the same room as `room_url`.
- **`WEBRTC_JOIN_TIMEOUT`** — the session didn't become ready within `webrtc_join_timeout_s`. It covers the model's cold start as well as the room join, so raise it (e.g. `30.0`) if it trips on first sessions.
- **`WEBRTC_JOIN_TIMEOUT`** — the session didn't become ready within `webrtc_join_timeout_s` (default 90 s). It covers the model's cold start as well as the room join, and a cold start alone can take more than 30 s, so don't lower it below that. Retrying usually succeeds: the server keeps starting after the client gives up.
- **`CONNECTION_CLOSED`** — the connection ended before the session was ready and the server sent no error of its own. The message carries the WebSocket close code and reason (for example `1008: Insufficient funds`).
- **Your bot hears the avatar** — it's subscribed to the `ojin-avatar` participant's microphone. Detect it with `is_avatar_participant()` / `is_avatar_identity()` and unsubscribe.

---
Expand Down
3 changes: 0 additions & 3 deletions examples/03-direct-webrtc/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@
from ojin import Credentials, MissingCredentialsError, load_env, resolve_credentials
from ojin.stv import OjinSTVClient, STVEvent, WebRTCSettings

JOIN_TIMEOUT_S = 30.0 # covers the room join AND a model cold start


def read_mono_wav(path: pathlib.Path) -> tuple[bytes, int]:
"""Read a mono 16-bit PCM WAV as (pcm_bytes, sample_rate), or exit with a hint."""
Expand Down Expand Up @@ -60,7 +58,6 @@ def webrtc_settings_from_env(sample_rate: int) -> WebRTCSettings:
room_url=room_url,
token=token,
audio_sample_rate=sample_rate, # publish at the clip's own rate
webrtc_join_timeout_s=JOIN_TIMEOUT_S,
)
except ValueError as exc:
sys.exit(f"\n Invalid WebRTC settings: {exc}\n")
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "ojin-client"
version = "0.12.0"
version = "0.12.1"
description = "Ojin platform services"
readme = "README.md"
requires-python = ">=3.10"
Expand Down
4 changes: 2 additions & 2 deletions skills/ojin-stv-integration/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,8 +205,8 @@ client = OjinSTVClient(
ends at close. Don't build a render path in this mode.
- `WEBRTC_CONNECTED` fires when the avatar is in the room; `FIRST_FRAME` and the
speaking events still fire.
- **No fallback.** A failed join, a `webrtc_join_timeout_s` expiry (default 10 s,
includes cold start — use ~30 s in production) or an unsupporting server is a fatal
- **No fallback.** A failed join, a `webrtc_join_timeout_s` expiry (default 90 s,
includes cold start — don't lower it below ~60 s) or an unsupporting server is a fatal
`ERROR` naming the cause (`WEBRTC_AUTH_FAILED`, `WEBRTC_NETWORK_FAILED`,
`WEBRTC_INVALID_SETTINGS`, `WEBRTC_JOIN_TIMEOUT`, `WEBRTC_ROOM_LOST` or
`WEBRTC_NOT_SUPPORTED`) and the session closes.
Expand Down
39 changes: 39 additions & 0 deletions src/ojin/ojin_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,9 @@ def __init__( # noqa: PLR0913
# tracer derives an ingress-bandwidth lane from its slope.
self._ingress_bytes_total: int = 0
self._inference_server_ready: bool = False
# Set once an error has been queued for the consumer, so a close that
# follows it is not reported as a second, vaguer error.
self._error_reported: bool = False
self._cancelled: bool = False
self._outbound_generation: int = 0
self._active_interaction_id: str | None = None
Expand Down Expand Up @@ -270,6 +273,7 @@ async def connect(self) -> None:
# Enable TCP_NODELAY to reduce latency for real-time frames
_configure_tcp_nodelay(self._ws)
self._running = True
self._error_reported = False
self._receive_task = asyncio.create_task(
self._receive_server_messages()
)
Expand Down Expand Up @@ -352,8 +356,40 @@ async def _receive_server_messages(self) -> None:
except Exception as e:
logger.exception("Error in WebSocket receive loop: %s", e)
finally:
if self._running: # the server ended it, not our own close()
await self._report_closed_before_ready()
await self.close()

async def _report_closed_before_ready(self) -> None:
"""Queue an error when the connection ends before ``sessionReady``.

Consumers block on :meth:`receive_message`, so a proxy that closes
without an ``errorResponse`` (a failed entitlement check, a dropped
connection) would otherwise look like a session that is still starting
until the caller's own timeout expires.
"""
if self._inference_server_ready or self._error_reported:
return
close_code = getattr(self._ws, "close_code", None)
close_reason = getattr(self._ws, "close_reason", None)
detail = ""
if close_code is not None:
detail = f" (close code {close_code}"
detail += f": {close_reason})" if close_reason else ")"
self._error_reported = True
await self._available_response_messages_queue.put(
ErrorResponseMessage(
payload=ErrorResponse(
interaction_id=None,
code="CONNECTION_CLOSED",
message="The connection closed before the session was ready"
+ detail,
timestamp=int(time.time() * 1000),
details=None,
)
)
)

async def _handle_server_message(self, message: str | bytes) -> None:
"""Handle an incoming WebSocket message.

Expand Down Expand Up @@ -401,6 +437,7 @@ async def _handle_server_message(self, message: str | bytes) -> None:
"active_interaction_id": self._active_interaction_id,
},
)
self._error_reported = True
await self._available_response_messages_queue.put(
ErrorResponseMessage(
payload=ErrorResponse(
Expand Down Expand Up @@ -431,6 +468,7 @@ async def _handle_server_message(self, message: str | bytes) -> None:
"active_interaction_id": self._active_interaction_id,
},
)
self._error_reported = True
await self._available_response_messages_queue.put(
ErrorResponseMessage(
payload=ErrorResponse(
Expand Down Expand Up @@ -473,6 +511,7 @@ async def _handle_server_message(self, message: str | bytes) -> None:
await self._available_response_messages_queue.put(msg)

if isinstance(msg, ErrorResponseMessage):
self._error_reported = True
raise RuntimeError(f"Error in Inference Server received: {msg}")

if isinstance(msg, OjinSessionReadyPing):
Expand Down
6 changes: 4 additions & 2 deletions src/ojin/stv/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ class WebRTCSettings:

Set ``audio_sample_rate`` to the rate your TTS emits to avoid resampling.
``webrtc_join_timeout_s`` bounds the whole wait for the session to become
ready — the room join *and* a model cold start — so leave headroom.
ready — the room join *and* a model cold start, which alone can take more
than 30 s. It is a backstop: a start the service itself gives up on is
reported sooner, as the server's own error.

The settings are declared in the WebSocket **upgrade request** (DR-006 as
amended 2026-07-24): the non-secret fields ride ``webrtc_*`` query params
Expand All @@ -64,7 +66,7 @@ class WebRTCSettings:
token: str = field(repr=False)
provider: WebRTCProvider | str = WebRTCProvider.DAILY
audio_sample_rate: int = 16000
webrtc_join_timeout_s: float = 10.0
webrtc_join_timeout_s: float = 90.0
version: int = 2

def to_connect_query_params(self) -> dict:
Expand Down
6 changes: 3 additions & 3 deletions src/ojin/stv/ojin_stv_webrtc_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -669,9 +669,9 @@ async def _handle_join_timeout(self) -> None:
self._tracer.instant("webrtc", "join_timeout")
await self._fail(
WEBRTC_JOIN_TIMEOUT,
"The session was not ready within "
f"{self._webrtc_settings.webrtc_join_timeout_s} s (the wait covers the "
"room join and the model's cold start)",
"Timed out: the session was not ready within "
f"{self._webrtc_settings.webrtc_join_timeout_s:g} s (the wait covers "
"the room join and the model's cold start)",
{"outcome": "timeout"},
)

Expand Down
25 changes: 25 additions & 0 deletions tests/stv/test_stv_client_webrtc_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import pytest

from ojin.entities.interaction_messages import ErrorResponse, ErrorResponseMessage
from ojin.ojin_client_messages import (
FrameType,
OjinAudioInputMessage,
Expand Down Expand Up @@ -242,6 +243,30 @@ async def test_join_timeout_is_reported_and_closes() -> None:
assert closed == [{}]


async def test_error_before_session_ready_fails_without_waiting_for_timeout() -> None:
"""A start the server gives up on ends at once, under the server's own code."""
fake_client = _NeverReadyClient()
client, _ = make_client(fake=fake_client, join_timeout_s=60.0)
errors = _record(client, STVEvent.ERROR)
closed = _record(client, STVEvent.CLOSED)
await client.start()

await fake_client.push(
ErrorResponseMessage(
payload=ErrorResponse(
code="BACKEND_UNAVAILABLE",
message="No GPU became available",
timestamp=1789000000000,
)
)
)
await asyncio.sleep(0.05)

assert [(e["code"], e["fatal"]) for e in errors] == [("BACKEND_UNAVAILABLE", True)]
assert errors[0]["message"] == "No GPU became available"
assert closed == [{}]


async def test_mid_session_room_loss_is_reported_and_closes() -> None:
"""A post-connect webrtcStatus failed(REJOIN_FAILED) ends the session."""
client, fake_client = make_client()
Expand Down
2 changes: 1 addition & 1 deletion tests/stv/test_webrtc_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ def test_webrtc_settings_repr_hides_token_and_pins_defaults() -> None:
assert settings.version == 2 # protocol v2 (DR-006)
# Client-local; in v2 it governs the whole sessionReady wait and must not
# appear in the connect declaration.
assert settings.webrtc_join_timeout_s == 10.0
assert settings.webrtc_join_timeout_s == 90.0
assert "webrtc_join_timeout_s" not in settings.to_connect_query_params()
assert settings.to_connect_query_params()["webrtc_version"] == "2"
# The token travels only in the header — never in a query param.
Expand Down
3 changes: 2 additions & 1 deletion tests/stv/test_webrtc_negotiation.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,8 @@ async def test_no_session_ready_within_timeout_is_fatal_and_closes() -> None:
assert len(errors) == 1
assert errors[0]["code"] == "WEBRTC_JOIN_TIMEOUT"
assert errors[0]["fatal"] is True
assert "not ready within" in errors[0]["message"]
assert errors[0]["message"].startswith("Timed out: ")
assert "not ready within 90 s" in errors[0]["message"]
assert client._preinit_inputs == [] # held input discarded on timeout
assert _audio_messages(fake_client) == []
assert closed == [{}]
Expand Down
64 changes: 64 additions & 0 deletions tests/test_ojin_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -665,3 +665,67 @@ def on_status(status: OjinWebRTCStatusMessage) -> None:
# The seeded interaction response was drained by the cancel; the status,
# delivered via the callback, was never at risk.
assert client._available_response_messages_queue.empty()


class _ClosingWS:
"""Delivers ``messages`` and then ends, as a socket the server closed does."""

def __init__(self, messages: list, close_code: int, close_reason: str) -> None:
self._messages = list(messages)
self.close_code = close_code
self.close_reason = close_reason

def __aiter__(self) -> "_ClosingWS":
return self

async def __anext__(self):
if not self._messages:
raise StopAsyncIteration
return self._messages.pop(0)

async def close(self) -> None:
"""Nothing to release."""


async def _run_receive_loop(messages: list, code: int, reason: str) -> list:
"""Run the receive loop over a server-closed socket; return what it queued."""
client = _client()
client._ws = _ClosingWS(messages, code, reason)
client._running = True
await client._receive_server_messages()
queue = client._available_response_messages_queue
return [queue.get_nowait() for _ in range(queue.qsize())]


async def test_close_before_session_ready_is_reported_with_the_close_reason() -> None:
"""A proxy close with no errorResponse must not look like a slow start."""
queued = await _run_receive_loop([], 1008, "Insufficient funds")

assert len(queued) == 1
assert isinstance(queued[0], ErrorResponseMessage)
assert queued[0].payload.code == "CONNECTION_CLOSED"
assert "before the session was ready" in queued[0].payload.message
assert "1008: Insufficient funds" in queued[0].payload.message


async def test_close_after_server_error_reports_only_the_server_error() -> None:
"""The server's own errorResponse is the cause; the close adds no second one."""
error = {
"type": "errorResponse",
"payload": {
"code": "BACKEND_UNAVAILABLE",
"message": "No GPU became available",
"timestamp": 1789000000000,
},
}
queued = await _run_receive_loop([json.dumps(error)], 1013, "")

assert [m.payload.code for m in queued] == ["BACKEND_UNAVAILABLE"]


async def test_close_after_session_ready_queues_no_error() -> None:
"""Only the pre-ready wait is covered; a later close stays as it was."""
ready = {"type": "sessionReady", "payload": {"parameters": {"persona": "x"}}}
queued = await _run_receive_loop([json.dumps(ready)], 1000, "")

assert [type(m) for m in queued] == [OjinSessionReadyMessage]
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading