dazzling-train-30986
12/02/2025, 3:00 PMtall-airline-16756
12/02/2025, 3:01 PMtall-airline-16756
12/02/2025, 3:01 PMsession.shutdown() or deleteRoom()).
• Ensure you do not call any immediate room deletion APIs on disconnect. Use rooms with auto-creation so they can accept the reconnection during the timer window.
If you’d like, I can:
• Provide a short code example for implementing the 3-minute timer in your server language (which language are you using?), or
• Explain how to detect reconnections (events to watch) so you can cancel the timer reliably. Sources: Connecting to LiveKit | LiveKit docs | Avoiding Room ID Reuse When Re-Creating Rooms With the Same Name | Rooms, participants, and tracks | LiveKit docs | Job lifecycle | LiveKit docsdazzling-train-30986
12/02/2025, 3:03 PMtall-airline-16756
12/02/2025, 3:03 PMdeleteRoom(), session.shutdown(), or similar).
• Instead, only run cleanup when your 3-minute timer expires and the participant has not rejoined.
2) Use auto-creation rooms
• Create rooms by letting the first participant trigger room creation (auto-creation). Do not force-delete the room on disconnect — this keeps the room available for reconnection during your 3-minute window.
3) Detecting reconnections (events to watch)
• Watch server-side participant lifecycle events:
◦ participant disconnected / left event — start your 3-minute timer.
◦ participant connected / joined event — cancel the timer if it matches the participant who left.
• Also consider tracking participant identity (user ID) and session ID so returning connections can be matched to the original participant.
4) Implementation outline (language-agnostic)
1. On "participant disconnected" event:
◦ Record timestamp and participant ID.
◦ Start a 3-minute timer for that participant/session.
1. On "participant connected" event:
◦ If participant ID matches a pending timer, cancel the timer and resume session logic.
1. On timer expiration:
◦ Verify participant still absent.
◦ Perform final cleanup: call your room deletion or session shutdown.
5) Next step Which server language would you like the code example in (Node.js, Go, or Python)? I’ll provide a concise snippet showing event handlers, the 3-minute timer, and cancelation logic.dazzling-train-30986
12/02/2025, 3:05 PMtall-airline-16756
12/02/2025, 3:06 PMdeleteRoom() / session.shutdown()).
• Any logs or error messages you see when it "does not work."
• How you identify participants on reconnect (user ID, session ID, token).
With that I’ll point out the bug(s) and provide a corrected, minimal code example that implements the 3-minute reconnection window and cancels cleanup on reconnection.dazzling-train-30986
12/02/2025, 3:07 PMtall-airline-16756
12/02/2025, 3:07 PMgrace_period_task in the outer function, then use nonlocal grace_period_task inside handlers — that’s correct only if handlers are nested in the same scope. Ensure those handlers are defined in the same function scope as grace_period_task. If they are methods on different objects or registered elsewhere, nonlocal will raise or not reference the same variable.
• Handlers are synchronous functions (not async) — cancelling an asyncio.Task from a synchronous callback is fine, but creating tasks and accessing `session`/`ctx` must reference the same objects (you already do). Ensure the event callbacks run in the same event loop as your timer.
• ctx.disconnect(): calling this inside the timer will disconnect the worker immediately. That is the intended cleanup — ensure you only call it when the timer truly expires.
• Room-empty detection: you build humans_left from ctx.room.remote_participants.values() — verify rp.kind matches the value used for human participants. If ParticipantKind constants differ, your check could miss humans and start the timer incorrectly.
• Race between connect/disconnect events: a reconnect may generate a participant_connected event slightly after the disconnect handler started the timer. You must cancel the timer reliably and handle CancelledError in the timer (you already do).
• Logging shows grace timer starts, but if it still proceeds to disconnect, the timer likely wasn’t cancelled because:
◦ grace_period_task referenced by on_participant_connected is different (scoping issue), or
◦ participant_connected never fires for that identity (different identity/session on reconnect), or
◦ grace_period_task.cancel() is called but the task swallows CancelledError incorrectly (your _grace_period_timer catches CancelledError and logs — that’s fine).
Minimal corrected example
• This snippet assumes handlers are declared in the same entrypoint scope and run in the same asyncio event loop. Replace the room-empty check condition with your actual agent kind if needed.
# inside entrypoint(...)
grace_period_task: asyncio.Task | None = None
async def _grace_period_timer():
try:
logger.info("⚠️ Candidate disconnected. Starting 3-minute grace period.")
# wait full 3 minutes, but can be cancelled anytime
await asyncio.sleep(180)
logger.info("❌ Grace period expired. Candidate did not return. Disconnecting.")
await ctx.disconnect() # ensure this is awaited if it's async
except asyncio.CancelledError:
logger.info("✅ Grace period cancelled. Candidate returned successfully.")
raise
@ctx.room.on("participant_disconnected")
def on_participant_disconnected(p: rtc.RemoteParticipant):
nonlocal grace_period_task
# Recompute humans left (exclude agent)
humans_left = [
rp for rp in ctx.room.remote_participants.values()
if rp.kind != rtc.ParticipantKind.PARTICIPANT_KIND_AGENT
]
if not humans_left:
# If a previous task exists, cancel it first to avoid duplicates
if grace_period_task and not grace_period_task.done():
grace_period_task.cancel()
grace_period_task = asyncio.create_task(_grace_period_timer())
@ctx.room.on("participant_connected")
def on_participant_connected(p: rtc.RemoteParticipant):
nonlocal grace_period_task
# If reconnecting participant matches the one who left, cancel timer
if grace_period_task and not grace_period_task.done():
grace_period_task.cancel()
grace_period_task = None
logger.info(f"Participant {p.identity} connected — canceled grace timer.")
Notes and checks to make it reliable
• Ensure ctx.room.on(...) callbacks run on the same asyncio loop as asyncio.create_task. If your library dispatches handlers in a different thread, use asyncio.get_event_loop().call_soon_threadsafe(...) to create/cancel tasks.
• Participant identity matching: if reconnecting clients use a different identity or participant ID, participant_connected won’t match the original. Track participant identity (e.g., store last-human-identity on disconnect) and compare on connect.
• Do not call ctx.disconnect(), deleteRoom(), or session.shutdown() elsewhere on disconnect events. Only perform cleanup in the timer expiration path.
• If ctx.disconnect() is a synchronous call in your environment, call it without await; if it’s async, await it. Use the same form you use elsewhere.
• For visibility, log participant identities on connect/disconnect to verify reconnects map to the same identity.
If you want, I can:
• Inspect your runtime logs if you paste the connect/disconnect lines around the failure, or
• Adapt the snippet to use identity-checking (store the identity of the last human who left and only cancel for that identity), or
• Show a thread-safe variant if your event callbacks run on worker threads.
Which would you prefer next?dazzling-train-30986
12/02/2025, 3:10 PMtall-airline-16756
12/02/2025, 3:11 PMlast_human_identity on disconnect.
• Only cancel the timer when a connecting participant's p.identity matches last_human_identity.
• Use thread-safe task creation/cancellation if callbacks may run off the asyncio loop.
• Ensure you await ctx.disconnect() if it is async in your environment.
Code (place inside your existing entrypoint where ctx, session, etc. are available):
import asyncio
import logging
from livekit import rtc
logger = logging.getLogger(__name__)
# inside entrypoint(...)
grace_period_task: asyncio.Task | None = None
last_human_identity: str | None = None
grace_lock = asyncio.Lock() # prevents races when starting/cancelling the task
async def _grace_period_timer(identity: str):
try:
logger.info(f"⚠️ Participant {identity} disconnected. Starting 3-minute grace period.")
await asyncio.sleep(180) # full 3 minutes
# Verify participant still absent before disconnecting
humans_present = [
rp for rp in ctx.room.remote_participants.values()
if rp.kind != rtc.ParticipantKind.PARTICIPANT_KIND_AGENT
]
if not humans_present:
logger.info(f"❌ Grace period expired for {identity}. No return detected — disconnecting.")
# await if ctx.disconnect is async
maybe_await = ctx.disconnect()
if asyncio.iscoroutine(maybe_await):
await maybe_await
else:
logger.info(f"Participant returned during grace period for {identity}; not disconnecting.")
except asyncio.CancelledError:
logger.info(f"✅ Grace period cancelled for {identity}. Participant reconnected.")
raise
@ctx.room.on("participant_disconnected")
def on_participant_disconnected(p: rtc.RemoteParticipant):
# Only consider human participants
if p.kind == rtc.ParticipantKind.PARTICIPANT_KIND_AGENT:
return
async def _start_timer():
nonlocal grace_period_task, last_human_identity
async with grace_lock:
# Recompute humans left (exclude agent)
humans_left = [
rp for rp in ctx.room.remote_participants.values()
if rp.kind != rtc.ParticipantKind.PARTICIPANT_KIND_AGENT
]
if humans_left:
# other humans still present; do nothing
return
# record the identity of the last human who left
last_human_identity = p.identity
# cancel any existing timer (safety)
if grace_period_task and not grace_period_task.done():
grace_period_task.cancel()
# create a new timer task bound to this identity
grace_period_task = asyncio.create_task(_grace_period_timer(last_human_identity))
# Ensure we schedule the async start on the event loop
try:
loop = asyncio.get_running_loop()
loop.create_task(_start_timer())
except RuntimeError:
# If callbacks run in another thread, submit safely
asyncio.get_event_loop().call_soon_threadsafe(lambda: asyncio.create_task(_start_timer()))
@ctx.room.on("participant_connected")
def on_participant_connected(p: rtc.RemoteParticipant):
# Only consider human participants
if p.kind == rtc.ParticipantKind.PARTICIPANT_KIND_AGENT:
return
async def _maybe_cancel():
nonlocal grace_period_task, last_human_identity
async with grace_lock:
# If the reconnecting identity matches the last one who left, cancel timer
if last_human_identity and p.identity == last_human_identity:
if grace_period_task and not grace_period_task.done():
grace_period_task.cancel()
grace_period_task = None
last_human_identity = None
logger.info(f"Participant {p.identity} reconnected — canceled grace timer.")
else:
# If a different human joined, we still keep the session (no action)
logger.info(f"Participant {p.identity} connected (not the one who left).")
try:
loop = asyncio.get_running_loop()
loop.create_task(_maybe_cancel())
except RuntimeError:
asyncio.get_event_loop().call_soon_threadsafe(lambda: asyncio.create_task(_maybe_cancel()))
Small checklist to verify in your runtime:
• Confirm p.identity is stable across reconnects (log identities on connect/disconnect).
• Confirm callbacks run on the same event loop; if not, the call_soon_threadsafe branches handle that.
• Ensure you do not call ctx.disconnect(), deleteRoom(), or session.shutdown() anywhere else on immediate disconnect.
• If ctx.disconnect() must be called synchronously, remove the await wrapper and call it directly.
If you want, I can adapt this to:
• Track multiple simultaneous human participants (per-participant timers), or
• Add logging lines you can paste into your runtime to confirm identity continuity. Which would you prefer?