Session events
Reference for session-level events covering connection state, errors, idle warnings, and participant changes, wired through Inspector relays or script.
The SDK exposes session-level events through two wiring approaches that you can use independently or together. ConvaiSessionEventRelay is a MonoBehaviour that wires events to Inspector-assigned UnityEvent callbacks with no code required. ConvaiEvents is a C# typed event hub accessible from any script via ConvaiManager.ActiveManager.Events. Both approaches fire on the same underlying SDK events — choose based on what your code needs. For a conceptual overview of relay components and when to choose each approach, see Event System.
Inspector wiring — ConvaiSessionEventRelay
Setup:
Add
ConvaiSessionEventRelayto any GameObject in your scene via Add Component → Convai → Events → Convai Session Event Relay.Assign a
ConvaiManagerreference in the Manager field, or leave it empty and enable Auto Resolve Manager to useConvaiManager.ActiveManagerat runtime.Wire your callbacks in the Inspector under each event.
Auto Resolve Manager is convenient but non-deterministic. For scenes with multiple ConvaiManager instances, assign the target manager explicitly.
using Convai.Runtime.Facades;
using UnityEngine;
public class SessionStatusMonitor : MonoBehaviour
{
private void OnEnable()
{
var manager = ConvaiManager.ActiveManager;
if (manager == null) return;
manager.Events.OnConnected += HandleConnected;
manager.Events.OnDisconnected += HandleDisconnected;
manager.Events.OnSessionError += HandleError;
}
private void OnDisable()
{
var manager = ConvaiManager.ActiveManager;
if (manager == null) return;
manager.Events.OnConnected -= HandleConnected;
manager.Events.OnDisconnected -= HandleDisconnected;
manager.Events.OnSessionError -= HandleError;
}
private void HandleConnected() => Debug.Log("Session connected.");
private void HandleDisconnected() => Debug.Log("Session disconnected.");
private void HandleError(SessionError err) => Debug.LogError($"[{err.ErrorCode}] {err.Message}");
}ConvaiSessionEventRelay events
OnConnected
—
Session transitions to Connected
OnDisconnected
—
Session transitions to Disconnected
OnReconnecting
—
Session transitions to Reconnecting
OnReconnected
—
Reconnection succeeds (transitions from Reconnecting to Connected)
OnUsageLimitReached
—
Convai reports quota exhausted
OnUserIdleWarning
UserIdleWarningRelayData
Convai warns the session will close due to inactivity
OnUserIdleTimeout
UserIdleTimeoutRelayData
The client-side idle deadline elapses after a warning
OnRuntimeBackgroundStateChanged
RuntimeBackgroundStateRelayData
The application background/foreground state or background policy changes
OnSessionStateChanged
SessionStateChangedRelayData
Any SessionState transition
OnSessionError
SessionErrorRelayData
Session encounters an error
SessionStateChangedRelayData fields
OldState
SessionState
State before the transition
NewState
SessionState
State after the transition
SessionId
string
Current session identifier
ErrorCode
string
Error code if new state is Error; empty otherwise
IsError
bool
True when NewState == Error
IsReconnecting
bool
True when transitioning from Connected to Reconnecting
IsConnectionEstablished
bool
True when transitioning from Connecting to Connected
IsReconnectionSuccessful
bool
True when transitioning from Reconnecting to Connected
IsDisconnected
bool
True when NewState == Disconnected
SessionErrorRelayData fields
ErrorCode
string
Hierarchical error code, e.g. "connection.timeout"
Message
string
Human-readable error description
SessionId
string
Session identifier at the time of the error
IsRecoverable
bool
True if the SDK can attempt reconnection automatically
Stage
SessionErrorStage
Broad lifecycle stage where the error originated
HttpStatusCode
int
HTTP status code if the error came from an HTTP response; 0 otherwise
HasHttpStatusCode
bool
True when HttpStatusCode > 0
UserIdleWarningRelayData fields
RemainingSeconds
int
Seconds until Convai closes the session due to inactivity
Message
string
Human-readable warning message
UserIdleTimeoutRelayData fields
For idle timeout handling, see Session lifecycle.
WarningReceivedAtUtc
string
ISO 8601 UTC timestamp of the idle warning that started this deadline
DeadlineUtc
string
ISO 8601 UTC timestamp of the client-side idle deadline
RuntimeBackgroundStateRelayData fields
For the background policy values themselves, see Application background policy in Session lifecycle.
IsBackgrounded
bool
True when the application is currently backgrounded
RequestedPolicy
RuntimeBackgroundPolicy
The policy that was requested
EffectivePolicy
RuntimeBackgroundPolicy
The policy actually applied — can differ from RequestedPolicy when the platform cannot honor it
Reason
RuntimePauseReason
Why the background transition occurred
UsedPlatformFallback
bool
True when EffectivePolicy differs from RequestedPolicy
C# event hub — ConvaiEvents
Access via ConvaiManager.ActiveManager.Events. Subscribe in OnEnable, unsubscribe in OnDisable.
Session-scoped events
OnConnected
—
Session reaches Connected
OnDisconnected
—
Session reaches Disconnected
OnSessionStateChanged
SessionStateChanged
Any SessionState transition
OnSessionError
SessionError
Session encounters an error
OnPipelineError
SessionError
Processing pipeline encounters an error (distinct from session-level errors)
OnUsageLimitReached
UsageLimitReached
Convai reports quota exhausted
OnUserIdleWarningReceived
UserIdleWarningReceived
Convai warns the session will close due to inactivity
OnUserIdleTimeoutElapsed
UserIdleTimeoutElapsed
The client-side idle deadline elapses after a warning
OnRuntimeBackgroundStateChanged
RuntimeBackgroundStateChanged
The application background/foreground state or background policy changes
OnParticipantJoined
ParticipantInfo
A participant joins the room
OnParticipantLeft
ParticipantInfo
A participant leaves the room
OnRoomOwnershipRebindStateChanged
RoomOwnershipRebindStateChanged
Active character ownership rebinding changes state
The domain event payload types below back both the C# hub events above and, where noted, the relay data types earlier on this page.
SessionStateChanged
OldState
SessionState
State before the transition
NewState
SessionState
State after the transition
SessionId
string
Session identifier
Timestamp
DateTime
UTC time of the transition
Error
SessionError?
Present when NewState == Error
ErrorCode
string
Shortcut to Error?.ErrorCode; empty when no error
UsageLimitReached
QuotaType
string
Which quota was exhausted (e.g. "monthly_minutes")
Message
string
Human-readable description from Convai
Timestamp
DateTime
UTC time of the event
UserIdleWarningReceived
RemainingSeconds
int
Seconds until Convai closes the session due to inactivity
Message
string
Human-readable warning message
Timestamp
DateTime
UTC time of the event
UserIdleTimeoutElapsed
Backs UserIdleTimeoutRelayData on the relay. See Idle warnings and timeouts in Session lifecycle for how this relates to UserIdleWarningReceived.
WarningReceivedAt
DateTime
UTC time the idle warning that started this deadline arrived
DeadlineUtc
DateTime
UTC time of the client-side idle deadline
Timestamp
DateTime
UTC time the client observed that the deadline elapsed
RuntimeBackgroundStateChanged
Backs RuntimeBackgroundStateRelayData on the relay. See Application background policy in Session lifecycle for the policy values.
IsBackgrounded
bool
True when the application is currently backgrounded
RequestedPolicy
RuntimeBackgroundPolicy
The policy that was requested
EffectivePolicy
RuntimeBackgroundPolicy
The policy actually applied — can differ when the platform cannot honor the request
Reason
RuntimePauseReason
Why the background transition occurred
Timestamp
DateTime
UTC time of the transition
ParticipantInfo
ParticipantId
string
Unique participant identifier
Identity
string
Identity string associated with this participant
DisplayName
string
Human-readable display name
ParticipantType
ParticipantType
Whether the participant is a local player, remote player, or character
IsLocal
bool
True for the local player participant
IsMuted
bool
True when this participant's audio is muted
RoomOwnershipRebindStateChanged
Outcome
RoomOwnershipRebindStatus
Result of the rebind attempt
HasPendingReconnect
bool
True when a reconnect is required to complete the rebind
SessionState
SessionState
Session state at the time of the event
ActiveCharacterId
string
Character ID currently bound for conversation
RequestedCharacterId
string
Character ID that was requested for rebind
Timestamp
DateTime
UTC time of the event
ReconnectRequired
bool
True when ownership change requires session reconnection
Supporting types
SessionState enum
Disconnected (0)
No active session. Initial state and final state after a clean disconnect.
Connecting (1)
Attempting to establish a new session.
Connected (2)
Session is active and accepting input.
Reconnecting (3)
Connection was lost; the SDK is attempting to restore it automatically.
Disconnecting (4)
Gracefully closing the session.
Error (5)
Unrecoverable error. Session cannot continue without explicit reset.
Extension Methods (on SessionState):
Method
Returns true When
IsConnected()
State is Connected or Reconnecting
IsTransitioning()
State is Connecting, Reconnecting, or Disconnecting
IsStable()
State is Disconnected, Connected, or Error
CanAcceptInput()
State is Connected only
SessionErrorStage enum
Unknown (0)
Error stage could not be determined
Configuration (1)
Error occurred while reading or applying SDK configuration
ConnectApi (2)
Error during API connection setup
Transport (3)
Error in the transport layer (WebSocket, gRPC)
SessionRecovery (4)
Error during reconnection attempt
Runtime (5)
Error during an active session
ParticipantType enum
Unknown (0)
Participant type not determined
LocalPlayer (1)
The local player on this client
RemotePlayer (2)
A remote player in a multiplayer session
Character (3)
An AI character
RoomOwnershipRebindStatus enum
DeferredUntilStartup (0)
Rebind queued; will apply once the runtime starts
AppliedImmediately (1)
Rebind applied without requiring reconnection
PendingReconnect (2)
Rebind staged; requires reconnection to take effect
RejectedTransitionState (3)
Rejected because the session is currently transitioning
RejectedInvalidOwnership (4)
Rejected because the requested character is not a valid owner
SessionError struct
The full error detail type, used as the argument to OnSessionError and OnPipelineError in the C# hub, and exposed via SessionErrorRelayData in the relay.
ErrorCode
string
Hierarchical code, e.g. "connection.timeout", "transport.closed"
Message
string
Human-readable description
SessionId
string
Session identifier at time of error
Timestamp
DateTime
UTC time the error occurred
IsRecoverable
bool
True when the SDK will attempt automatic recovery
Exception
Exception
Underlying exception, if any
Stage
SessionErrorStage
Lifecycle stage where the error originated
HttpStatusCode
int?
HTTP status code for API-layer errors
Category
string
First segment of ErrorCode (e.g. "connection" from "connection.timeout")
IsConnectionError
bool
True when ErrorCode starts with "connection."
IsSessionError
bool
True when ErrorCode starts with "session."
IsTransportError
bool
True when ErrorCode starts with "transport."
IsProtocolError
bool
True when ErrorCode starts with "protocol."
IsServerError
bool
True when ErrorCode starts with "server."
Advanced — ConvaiEvents.Raw event hub
This is an advanced pattern. Use the typed properties on ConvaiEvents for all common scenarios.
ConvaiEvents.Raw exposes the underlying IEventHub, which lets you subscribe to any domain event type that has no corresponding typed property on ConvaiEvents.
The raw hub uses a token-based subscription model. Losing the token causes a memory leak — the hub holds a reference to the adapter until explicitly unsubscribed.
EventDeliveryPolicy options:
MainThread (default)
All Unity API access — delivered on the next Unity Update tick
Background
Non-Unity thread-safe logging or metrics
Immediate
Synchronous delivery on the publishing thread (use with caution)
Usage examples
Example 1 — Proctor HUD that dims on disconnect
A training simulation shows a proctor overlay that dims when the session drops, giving learners a clear visual signal that the AI character is unavailable.
Example 2 — Session error banner with recoverability branch
A corporate onboarding simulation displays a dismissible error banner. Recoverable errors show a "reconnecting…" message; unrecoverable errors prompt the trainee to reload the module.
Example 3 — Idle warning countdown timer
A medical training simulation shows a countdown when Convai warns the session will close, giving learners time to resume before the AI character disconnects.
Troubleshooting
OnSessionError never fires
Subscribed after connect attempt; missed the event
Subscribe in OnEnable, ensure OnEnable runs before ConnectAsync
ConvaiSessionEventRelay callbacks not invoked
Manager not assigned and AutoResolveManager is off
Enable Auto Resolve Manager or assign the ConvaiManager field
Session stuck in Reconnecting indefinitely
Server unreachable or retry limit hit
Check network; listen to OnSessionError with IsRecoverable == false to detect terminal failure
OnConnected fires but CanAcceptInput() returns false
State check called during a transition
Evaluate CanAcceptInput() inside the OnConnected handler, not in Update
Next steps
With session events wired, move to Character Events to respond to speech, emotion, and turn lifecycle. For connection control from script, see ConvaiManager API.
Last updated
Was this helpful?