hello! I’m wondering how I should handle page relo...
# ask-ai
m
hello! I’m wondering how I should handle page reloads / page close and reopen. I see that the agent session is closing, but I think the agent participant is still in the room. Does closing an agent session also remove the participant?
t
Thanks for reaching out, Shan. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
You're asking whether closing an agent session (e.g., on page reload/close) also removes the agent participant from the room — short answer: it does not automatically remove the participant. What happens • Calling
session.shutdown()
or
session.aclose()
disconnects the agent session and cleans up its internal state, but the participant can remain in the room unless you explicitly remove it. What you can do • If you want to remove the participant only: call the RemoveParticipant API with a room admin credential. • If you want to end the whole room when the agent leaves: call the DeleteRoom API. • Add a shutdown/cleanup hook (for example via
ctx.add_shutdown_callback
) to run the chosen removal call when the page unloads or the session ends. Would you like implementation examples for the RemoveParticipant or DeleteRoom calls in your language (Python/JS)? Sources: Job lifecycle | LiveKit docs | Managing participants | LiveKit docs
m
Why would this be the case? for example, if the user leaves the room, the session closes, and the user rejoins, it will still show an agent participant is in the room, even if it is not running a session? is it functionally a zombie?
t
You're right to call attention to that — yes, the lingering agent participant is effectively a "zombie" participant: the AgentSession and the Room participant are separate entities, so closing the session doesn't automatically delete the participant. Why this design: • Separation of concerns: a session represents an active runtime/connection; a participant represents the presence/identity in the room. Tying participant deletion only to session shutdown would remove the record of that identity immediately, which is undesirable when you want persistent participant metadata or to allow reconnection flows. • Reconnect semantics: if a user reloads and immediately rejoins, keeping the participant record lets you preserve participant state (roles, published tracks, metadata) or make reconnect logic simpler. • Controlled removal: explicit APIs (RemoveParticipant or DeleteRoom) let you decide whether leaving should be temporary (session closed, participant remains) or permanent (participant removed, room ended). Practical implications • If you don’t remove the participant, it will remain visible in the room—even though no active session is attached—until you call RemoveParticipant or DeleteRoom. • Treat session shutdown as a signal to run cleanup if you want to avoid zombies (use a shutdown hook and call RemoveParticipant or DeleteRoom depending on whether other participants remain). If you want, I can: • Show a short example (Python or JS) for hooking page unload/reload to call RemoveParticipant. • Suggest a reconnect pattern (e.g., detect existing participant and reattach session vs. remove-and-recreate). Which would be most helpful?
m
is reattaching session possible? is that why the zombie agent is useful — it can be reactivated?
t
Short answer: No — reattaching an
AgentSession
to an existing disconnected agent participant is not supported. The lingering participant is for visibility, not for session resurrection. Why: • An
AgentSession
is a transient server-side process tied to a single job and its runtime state; when it ends the session state is destroyed. • The agent participant may remain in the room in a DISCONNECTED state for visibility and reconnect semantics for clients, but it cannot be reactivated or reattached to a new
AgentSession
. What to do instead: • Persist any conversation or agent state externally (database or
userdata
) and load it into a newly created
AgentSession
when needed. • If you want to avoid orphaned participants, run cleanup on session shutdown (call RemoveParticipant for the agent or DeleteRoom if appropriate). • If you want seamless UX for reloads, detect a disconnected participant and either recreate a fresh session for that identity or remove-and-recreate based on your reconnection policy. Would you like a short example for: • persisting/restoring
userdata
for a new
AgentSession
, or • a page-unload hook that calls RemoveParticipant/DeleteRoom? Sources: Managing participants | LiveKit docs | Agent session | LiveKit docs | Agents and handoffs | LiveKit docs
m
is there an established way to detect whether an agent in the room has an active session, or if its session has been closed? When the user leaves, then rejoins, in an ideal scenario, i’d be able to decide whether to dispatch another agent. But I can’t tell at the moment, because the existing agent might be a zombie.
t
You're asking how to detect whether an agent participant in a room has an active AgentSession or is a disconnected "zombie" so you can decide whether to dispatch a new agent. Short answer: check both the participant's connection state and the agent session state attribute; combine participant events + agent session lifecycle signals for reliable decisions. What to check (concise) • Participant connection state: look at the participant's state (ACTIVE vs DISCONNECTED) or listen to participant join/leave events (client events or webhooks). • Agent session state attribute: read the
lk.agent.state
participant attribute (values like
initializing
,
listening
,
thinking
,
speaking
). If this attribute is present and in an active state (
listening
,
thinking
,
speaking
) the agent is active. • AgentSession lifecycle signals: have your agent code emit or persist session-close events (the session
close
event) to your backend so you can mark the session inactive in a database or cache. Recommended decision flow 1. On user rejoin, fetch the agent participant (by identity) and check: ◦ If participant.state === ACTIVE and
lk.agent.state
∈ {
listening
,
thinking
,
speaking
} → treat as active; do not dispatch a new agent. ◦ If participant.state === DISCONNECTED or
lk.agent.state
is missing/stale → treat as likely zombie; consider cleanup and dispatching a new agent. 1. If uncertain, consult your backend session record (set when AgentSession starts/stops). Prefer authoritative backend state over room-only signals. 2. Cleanup options when you detect a zombie: ◦ Call RemoveParticipant for that agent (room admin API) to remove the lingering participant. ◦ Or delete the room if the whole room should end. Best practices • Persist minimal session state (session id, agent job status, timestamps) in your backend when creating an AgentSession; update on
close
→ makes rejoin decisions deterministic. • Use
lk.agent.state
for near-real-time liveness checks, but rely on backend state for final dispatch decisions. • Use shutdown hooks in agent code to call cleanup (RemoveParticipant or notify backend) on session end so zombies are less likely. If you want, I can: • Show a short Node.js or Python snippet that implements the decision flow (checking
participant.state
,
lk.agent.state
, and falling back to backend state), or • Provide an example webhook/backend schema for tracking AgentSession lifecycle. Which would help you most? Sources: Turn detection and interruptions | LiveKit Docs | Webhooks | LiveKit docs | Handling events | LiveKit docs | Agent session | LiveKit docs | Agents v0.x migration guide - Python | LiveKit docs
m
Is there a safe, trusted way to tell whether an agent in the room has an active agent state, from my node.js backend?
t
Yes — from a Node.js backend you can reliably determine whether an agent in a room is actively running an AgentSession by combining two trusted sources: LiveKit participant state/attributes and your own backend session state (updated by agent lifecycle events). Use participant attributes for near-real-time checks and your backend as the authoritative source. Steps (safe, trusted approach) 1. Query the participant from the Room (LiveKit server API / SDK) and check: ◦ participant.state (ACTIVE vs DISCONNECTED) ◦ participant.attributes['lk.agent.state'] (values like
initializing
,
listening
,
thinking
,
speaking
) If state is ACTIVE and
lk.agent.state
is one of the active values, treat the agent as active. 1. Maintain backend session records: ◦ When creating an AgentSession, persist a record (session id, agent identity, job id, startedAt). ◦ On agent `close`/shutdown handlers, update that record to mark the session ended (endedAt, status). ◦ Prefer this backend record as the authoritative source when deciding whether to dispatch a new agent. 1. Use webhooks or agent lifecycle events to keep backend state in sync: ◦ Have the agent invoke a backend endpoint or emit a webhook on session start and on session
close
. ◦ If you observe participant disconnect events without a backend close, treat it as an unexpected disconnect and either mark as inactive after a short timeout or attempt cleanup. 1. Decision logic (example) ◦ If backend record shows session is active → do not dispatch. ◦ Else if backend record shows ended → dispatch new agent. ◦ If backend record is missing/untrusted → fall back to participant checks: ▪︎ If participant.state === 'ACTIVE' and
lk.agent.state
∈ {
listening
,
thinking
,
speaking
} → treat active and reconcile backend. ▪︎ Otherwise treat as zombie: remove participant or dispatch new agent and update backend. Quick Node.js hints • Use LiveKit server SDK or REST API to list/get participants and read
attributes
. • Accept agent-side lifecycle callbacks (HTTP endpoint) for start/close to update your DB. • Add a short safety timeout when participant disconnects unexpectedly before auto-dispatching, to handle transient reconnects. If you’d like, I can provide a concise Node.js code snippet showing: • fetching a participant and reading
lk.agent.state
, and • an example endpoint that the agent calls on session
close
to update backend state. Which snippet would help?
m
i want one source of truth. is lk.agent.state not trustable? e.g. is it not atomically set on close?
t
Short answer: No —
lk.agent.state
is reliable while the AgentSession is actively running, but it is not safe to use as the single source of truth because it can become stale if the agent process crashes or disconnects unexpectedly. Why not atomic on close • On graceful shutdown the agent can update
lk.agent.state
before disconnecting. • If the process is killed, crashes, or loses network, it cannot update LiveKit; the attribute remains at its last value (e.g.,
thinking
), producing a "zombie" participant until server timeouts clean it up. Safe, trusted approach (one source of truth) 1. Use your backend as the authoritative source: ◦ Record session start (agent id/identity, room, session id, startedAt). ◦ Update on session end (endedAt, status) when you receive an explicit lifecycle signal. 1. Keep
lk.agent.state
for near-real-time UI/liveness hints, not as authoritative state. 2. Sync via webhooks / agent callbacks: ◦ Have the agent POST to your backend on session start and on
close
. ◦ Also subscribe to
participant_left
webhooks to reconcile unexpected disconnects. 1. Add guarded cleanup: ◦ If webhooks/callbacks are delayed or missing, run a short expiry/heartbeat policy (e.g., mark inactive after 20–30s with no heartbeat). 1. Decision logic for dispatch: ◦ If backend record = active → do not dispatch. ◦ If backend record = ended → dispatch. ◦ If backend missing → consult
participant.state
+
lk.agent.state
as a fallback, then reconcile and update backend. If you want, I can provide a concise Node.js snippet that: • fetches a participant and reads
lk.agent.state
, and • shows an endpoint the agent calls on
close
to update backend session state. Which snippet would you prefer (participant-check, webhook handler, or both)? Sources: Agents Framework | livekit/livekit_composite | DeepWiki | Web and mobile frontends | LiveKit docs | Job lifecycle | LiveKit docs | Understanding the STATE_MISMATCH Disconnect Reason | Server-side | livekit/livekit_composite | DeepWiki
m
but if the process can exit / session.close can happen unexpectedly, how can I set my db entry?
t
Good question — unexpected exits are the core reason you need server-side safeguards. You can’t rely on the agent process to always notify you, so the robust pattern is: 1) try to get notified (webhook / agent callback) and 2) have fallbacks (heartbeat, participant state, and a short expiry/cleanup job) that reconcile DB state if no notification arrives. Concrete, safe approach (minimal steps) 1. On session start • Create DB record: session_id, agent_identity, room, status = "active", startedAt, lastHeartbeatAt. 1. Try for explicit teardown • Agent should POST a /session/close endpoint on graceful shutdown to set status = "ended", endedAt. • Also subscribe to LiveKit server webhooks (participant_left) for AGENT participants and update the DB to ended when received. 1. Add a heartbeat (recommended) • Have the AgentSession send periodic heartbeats (e.g., every 5–10s) to your backend updating lastHeartbeatAt. • While active, heartbeats reaffirm the backend record. 1. Fallback expiry / cleanup job • Run a short polling/cron job (e.g., every 10s) that marks sessions inactive if: ◦ no heartbeat for a threshold (e.g., 20–30s), OR ◦ LiveKit participant state is DISCONNECTED and
lk.agent.state
is absent/stale. • On marking inactive, optionally call RemoveParticipant to clean the room. 1. Use participant attributes as a hint, not the source of truth • Read
lk.agent.state
and participant.state from LiveKit to help decide—but authoritative truth comes from your DB which is updated by webhooks/heartbeats/cleanup. Example decision flow (pseudo) • If DB.status === "active" and lastHeartbeatAt is recent → agent active. • Else if webhook says participant_left → set DB.status = "ended". • Else if no heartbeat and participant.state !== ACTIVE or
lk.agent.state
missing/stale → expire session in DB and treat as ended. Quick Node.js sketch ideas I can provide • webhook handler for participant_left that updates DB • simple heartbeat endpoint the agent calls • cleanup job that queries DB and LiveKit participants, then expires stale sessions Which snippet would you like first: webhook handler, heartbeat + DB update, or the cleanup job?
m
the problem i’m trying to figure out is pretty simple. on page reload, how do i figure out if there is an active agent session? I want to do this quickly. You’re saying to send a heartbeat?
t
Short answer: do a fast backend check (DB + LiveKit participant attribute) — a heartbeat is recommended but not strictly required. Quick 3-step approach for page reload (fast & reliable) 1. Query your backend (single source of truth) for an active session record for that room/agent. ◦ If DB says active and lastHeartbeatAt is recent (or startedAt very recent) → treat as active and reconnect/avoid dispatch. 1. If DB is missing or stale, do a fast LiveKit query as a fallback: ◦ Fetch the participant by identity and check
participant.state
(ACTIVE vs DISCONNECTED) and
attributes['lk.agent.state']
. ◦ If participant.state === ACTIVE and
lk.agent.state
∈ {
listening
,
thinking
,
speaking
} → treat as active. 1. If both checks are inconclusive, consider it not active and dispatch a new agent, optionally removing the stale participant. Role of heartbeats • Heartbeats make the DB check fast and authoritative on reload. A short heartbeat interval (5–10s) with a short expiry (20–30s) lets your backend reliably answer instantly. • Without heartbeats you must rely on LiveKit participant state/attributes which can be stale after crashes, so you risk false positives. Recommended minimal implementation for speed • On page reload: call your backend endpoint that: a. Looks up DB record (fast in a single DB read). b. If needed, queries LiveKit participant attributes (single API call). c. Returns a boolean: active vs not active. • Use that boolean to decide immediately. If you want, I can provide a concise Node.js snippet for that backend endpoint (DB check + LiveKit participant read). Which DB are you using?