I want to keep my session running for 3 minutes wh...
# ask-ai
d
I want to keep my session running for 3 minutes when a participant disconnects in case he wants to reconnect. How can I do this?
t
Thanks for reaching out, Basile. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking how to keep a session alive for 3 minutes after a participant disconnects so they can reconnect — here's how to do that. • LiveKit does not provide a configurable built-in reconnect timeout you can set to exactly 3 minutes. The server preserves short-lived client state and has a default departure timeout (about 20s) before a room is closed, but that can't be extended via a simple server setting. • To achieve a 3-minute window, keep the room/session open in your application code instead of immediately shutting it down when a participant disconnects: a. When a participant disconnects, start a 3-minute timer in your agent/service logic. b. If the participant reconnects before the timer expires, cancel the timer and resume the session. c. If the timer expires with no reconnection, then call your cleanup (e.g.,
session.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 docs
d
Can you show me: • How to ensure I 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. • 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.
t
I'll show the key points and can provide a code sample once you tell me which server language you use (Node.js, Go, Python, or another). 1) Don’t call immediate room-deletion APIs • On participant disconnect, stop any code path that immediately calls room deletion/cleanup (e.g.,
deleteRoom()
,
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.
d
Here is my code that does not work
t
Thanks — I can help troubleshoot. Please share: • The server language (Node.js, Go, or Python). • The relevant code snippet that handles participant disconnect, the timer logic, and any room deletion calls (include event handlers and where you call
deleteRoom()
/
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.
d
This is my main.py # --- Standard Library Imports --- from datetime import datetime import json import logging from livekit import rtc # Import rtc import asyncio from livekit.agents.voice.room_io import RoomInputOptions # --- Third-Party Imports --- from livekit import agents from livekit.agents import ( AgentSession, MetricsCollectedEvent, metrics, UserStateChangedEvent, ) from app.lifecycle_management import LifecycleController from livekit.agents import BackgroundAudioPlayer, AudioConfig, BuiltinAudioClip from app.settings import ( S3_BUCKET_NAME, S3_TRANSCRIPT_FOLDER, s3_client, ) from app.utils.telemetry import setup_langfuse from app.session import build_agent_and_session # Initialize logger for this module logger = logging.getLogger(name) def save_transcript(session: AgentSession) -> None: """ Persists the conversation history from the agent session to an S3 bucket. The transcript is saved as a JSON file with a timestamped filename. Args: session: The AgentSession object containing the conversation history. """ # Generate a unique filename based on the current date and time fn = f"transcript_{datetime.now().strftime('%Y-%m-%d_%H:%M:%S')}.json" s3_key = S3_TRANSCRIPT_FOLDER + fn try: logger.info(f"Saving transcript to S3: s3://{S3_BUCKET_NAME}/{s3_key}") # Upload the session history (converted to a dict) as a JSON object s3_client.put_object( Bucket=S3_BUCKET_NAME, Key=s3_key, Body=json.dumps(session.history.to_dict()), ContentType="application/json", ) logger.info(f"Successfully uploaded transcript {fn}.") except Exception as e: logger.error(f"Error uploading transcript to S3: {e}") async def entrypoint(ctx: agents.JobContext): """ The main entrypoint for the LiveKit agent worker. This function handles: 1. Setting up telemetry (Langfuse). 2. Connecting to the LiveKit room. 3. Waiting for a participant to join. 4. Building the agent and session. 5. Registering shutdown hooks for saving transcripts and logging usage. 6. Starting the agent session loop. """ session, agent = await build_agent_and_session(ctx.job.metadata, ctx.room.name) background_audio = BackgroundAudioPlayer( # play office ambience sound looping in the background ambient_sound=AudioConfig(BuiltinAudioClip.OFFICE_AMBIENCE, volume=0.8), # play keyboard typing sound when the agent is thinking thinking_sound=[ AudioConfig(BuiltinAudioClip.KEYBOARD_TYPING, volume=0.8), AudioConfig(BuiltinAudioClip.KEYBOARD_TYPING2, volume=0.7), ], ) #################################################################### # Reconnection / Grace Period Logic # #################################################################### # Track the grace period task grace_period_task: asyncio.Task | None = None async def _grace_period_timer(): """Waits 3 minutes, logging status periodically, then disconnects.""" try: logger.info("⚠️ Candidate disconnected. Starting 3-minute grace period.") # Loop 6 times, waiting 30 seconds each time (Total 3 mins) for i in range(6): await asyncio.sleep(30) # --- VERIFICATION CHECKS --- # 1. Check if Room is still connected room_state = ctx.room.connection_state # 2. Check if Session object still exists has_session = session is not None # 3. Check current QA progress (to prove memory is safe) # Accessing the QAState stored in userdata current_q = ( session.userdata.questions.get( list(session.userdata.questions.keys())[0], "Unknown" ) if session.userdata.questions else "No questions" ) logger.info( f"⏳ Grace Period Check {(i+1)*30}s/180s | " f"Room State: {room_state} | " f"Session Active: {has_session} | " f"QA Data Present: {current_q}" ) logger.info( "❌ Grace period expired. Candidate did not return. Disconnecting." ) ctx.disconnect() except asyncio.CancelledError: logger.info("✅ Grace period cancelled. Candidate returned successfully.") @ctx.room.on("participant_disconnected") def on_participant_disconnected(p: rtc.RemoteParticipant): # Logic: If the candidate leaves, start the countdown. # We check if the room is empty (except for the Agent) # Note: ctx.agent.participant is the Agent itself. # Determine if there are any humans left humans_left = [ rp for rp in ctx.room.remote_participants.values() if rp.kind != rtc.ParticipantKind.PARTICIPANT_KIND_AGENT ] if not humans_left: nonlocal grace_period_task 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 a timer is running, the session is still alive. Cancel the kill-switch. if grace_period_task and not grace_period_task.done(): grace_period_task.cancel() grace_period_task = None logger.info(f"Participant {p.identity} reconnected. Resuming session.") #################################################################### # Register shutdown hooks # #################################################################### trace_provider = setup_langfuse( # metadata will be set as attributes on all spans created by the tracer metadata={ "langfuse.session.id": ctx.room.name, } ) # (optional) add a shutdown callback to flush the trace before process exit async def flush_trace(): trace_provider.force_flush() ctx.add_shutdown_callback(flush_trace) @session.on("metrics_collected") def _on_metrics_collected(ev: MetricsCollectedEvent): metrics.log_metrics(ev.metrics) # Hook to save the transcript on shutdown async def write_transcript(): logger.info("Shutdown hook: saving transcript...") save_transcript(session) ctx.add_shutdown_callback(write_transcript) # Setup usage metrics collection usage_collector = metrics.UsageCollector() """ # 1. Setup Telemetry (Langfuse) - TODO -> Replace this by DATADOG trace_provider = setup_langfuse( session_id=ctx.room.name ) # metadata={"langfuse.session.id": ctx.room.name}) @session.on("metrics_collected") def _on_metrics_collected(ev: MetricsCollectedEvent): usage_collector.collect(ev.metrics) # Register a shutdown hook to ensure all traces are flushed async def flush_trace(): trace_provider.force_flush() ctx.add_shutdown_callback(flush_trace) """ # Hook to log usage summary on shutdown async def log_usage(): summary = usage_collector.get_summary() logger.info(f"Shutdown hook: Usage Summary - {summary}") ctx.add_shutdown_callback(log_usage) #################################################################### # Start the agent session # #################################################################### lifecycle = LifecycleController(session=session, ctx=ctx) lifecycle.start_lifecycle() @session.on("user_state_changed") def handle_user_state_change(ev: UserStateChangedEvent): lifecycle.on_user_state_changed(ev) logger.info("Starting agent session...") await session.start( room=ctx.room, agent=agent, ) await background_audio.start(room=ctx.room, agent_session=session) if name == "__main__": """ Main execution block to run the agent worker. This loads the worker options and starts the CLI run loop. """ opts = agents.WorkerOptions( entrypoint_fnc=entrypoint, ) agents.cli.run_app(opts)
t
Thanks — I reviewed your code. I’ll: (1) point out the likely issues causing the grace timer to not behave, (2) give a minimal corrected Python snippet that matches your approach (async timer, start on disconnect, cancel on reconnect), and (3) highlight the event checks to ensure you never call immediate room-deletion APIs. Key issues I see • nonlocal usage: you declare
grace_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.
Copy code
# 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?
d
Yes please provide this • Adapt the snippet to use identity-checking (store the identity of the last human who left and only cancel for that identity), or
t
Below is a concise, self-contained Python snippet that adapts your approach to store the identity of the last human who left and only cancels the 3-minute grace timer when that same identity reconnects. It keeps the room alive (no immediate delete), starts the timer when the last human leaves, cancels it if that human returns, and calls disconnect only when the timer truly expires. Key points: • Track
last_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):
Copy code
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?