damp-belgium-53878
10/04/2025, 10:13 AMimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
LiveKitRoom,
RoomAudioRenderer,
VideoConference,
} from '@livekit/components-react';
// LiveKit component styles are imported globally in main.tsx
import '@livekit/components-styles';
// Backend base URL provided at build time
const API_URL = (import.meta as any).env?.VITE_API_URL as string | undefined;
const TOKEN_ENDPOINT = API_URL ? `${API_URL}/getToken` : '/getToken';
const DISPATCH_ENDPOINT = API_URL ? `${API_URL}/dispatchAgent` : undefined;
const LIVEKIT_URL = import.meta.env.VITE_LIVEKIT_URL as string | undefined;
// Accept any metadata shape; it is forwarded to the backend as-is
type PatientMetadata = unknown;
type LivekitRoomProps = {
onCallEnd?: () => void;
patientMetadata?: PatientMetadata;
};
function uuid() {
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) return crypto.randomUUID();
return Math.random().toString(36).slice(2);
}
export default function LivekitRoom({ onCallEnd, patientMetadata }: LivekitRoomProps) {
const [token, setToken] = useState<string>();
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const isJoiningRef = useRef(false);
const agentDispatchedRef = useRef(false);
// Generate unique room and patient names for each component mount
const [roomName] = useState(() => `room-${uuid()}`);
const [patientName] = useState(() => `patient-${uuid().slice(0, 8)}`);
const joinRoom = useCallback(async () => {
if (isJoiningRef.current) return;
isJoiningRef.current = true;
setLoading(true);
setError(null);
try {
// Request a token for our generated room + identity
const params = new URLSearchParams({ room: roomName, identity: patientName, name: patientName });
const res = await fetch(`${TOKEN_ENDPOINT}?${params.toString()}`);
const { token } = await res.json();
if (!token) throw new Error('No token received');
// Optionally dispatch an agent (only once)
if (DISPATCH_ENDPOINT && !agentDispatchedRef.current) {
agentDispatchedRef.current = true;
await fetch(DISPATCH_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
agent_name:"patient",
room: roomName,
patient_name: patientName,
metadata: patientMetadata ?? [],
}),
});
}
setToken(token);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to join room');
} finally {
setLoading(false);
isJoiningRef.current = false;
}
}, [roomName, patientName, patientMetadata]);
const leaveRoom = useCallback(() => {
setToken(undefined);
onCallEnd?.();
}, [onCallEnd]);
// Auto-join immediately when this screen mounts
useEffect(() => { void joinRoom(); }, [joinRoom]);
if (!token) {
return (
<div className="app-shell">
<div className="card">
<h1>{loading ? 'Connecting…' : 'Connection'}</h1>
{loading ? (
<p>Setting up your LiveKit session.</p>
) : error ? (
<>
<p className="error">{error}</p>
<div className="form-actions">
<button className="primary" onClick={joinRoom} disabled={loading}>
Retry
</button>
</div>
</>
) : null}
</div>
</div>
);
}
return (
<LiveKitRoom
token={token}
serverUrl={LIVEKIT_URL}
onDisconnected={leaveRoom}
data-lk-theme="default"
>
<CallLayout />
</LiveKitRoom>
);
}
function CallLayout() {
return (
<div className="room-container">
<RoomAudioRenderer />
<div className="room-stage">
<VideoConference />
</div>
</div>
);
}tall-airline-16756
10/04/2025, 10:13 AMtall-airline-16756
10/04/2025, 10:13 AMdamp-belgium-53878
10/04/2025, 10:15 AM@router.post("/dispatchAgent")
async def dispatch_agent(payload: DispatchAgentPayload):
room_name = payload.room
agent_name = payload.agent_name
# Serialize metadata to JSON for LiveKit API
# Handle both dict (persona) and list (backward compatibility) formats
if isinstance(payload.metadata, dict):
metadata_json = json.dumps(payload.metadata)
elif isinstance(payload.metadata, list):
metadata_json = json.dumps([item.model_dump() if hasattr(item, 'model_dump') else item for item in payload.metadata])
else:
metadata_json = json.dumps(payload.metadata)
logger.info(f"#### {metadata_json} ####")
lkapi = api.LiveKitAPI(
os.getenv("LIVEKIT_URL"),
os.getenv("LIVEKIT_API_KEY"),
os.getenv("LIVEKIT_API_SECRET"),
)
dispatch_req = CreateAgentDispatchRequest(
agent_name=agent_name,
room=room_name,
metadata=metadata_json,
)
try:
dispatch_resp = await lkapi.agent_dispatch.create_dispatch(dispatch_req)
except Exception as e: # noqa: BLE001
raise HTTPException(
status_code=500, detail=f"Failed to dispatch agent: {str(e)}"
)
finally:
await lkapi.aclose()
return {
"status": "ok",
"room": room_name,
"agent_name": agent_name,
"patient_name": payload.patient_name,
"dispatch_id": getattr(dispatch_resp, "dispatch_id", None),
}tall-airline-16756
10/04/2025, 10:16 AMdamp-belgium-53878
10/04/2025, 10:17 AMtall-airline-16756
10/04/2025, 10:17 AMcreate_dispatch method to assign an agent specifically to a room.
• Restart Conversations: When you’re ready to close a conversation, simply delete the existing agent dispatch using its dispatch_id. This ends the agent’s session. Then, to start fresh, create a new dispatch for the new room.
• Room Lifecycle Management: You can control how long rooms stay active after participants leave by setting room timeouts like empty_timeout and departure_timeout. This helps keep things tidy and efficient.
• Pass Metadata: Don’t forget to use the metadata field in your dispatch requests! Passing contextual info like user details or session history helps the agent maintain continuity even after restarts.
If you’d like, I’m here to provide detailed code examples or walk you through any of these steps. Just let me know! Sources: livekit-api/livekit/api/agent_dispatch_service.py | examples/agent-dispatch/index.ts | Web and mobile frontends | LiveKit Docs | Worker lifecycle | LiveKit Docs | Agent dispatch | LiveKit Docsdamp-belgium-53878
10/04/2025, 10:17 AMtall-airline-16756
10/04/2025, 10:18 AMelegant-glass-77462
10/04/2025, 12:56 PM${API_URL}/deleteDispatch : '/deleteDispatch';
// --- inside LivekitRoom component (add these refs/state) ---
const dispatchIdRef = useRef null(null);
// load persisted dispatch id for this room on mount (prevents duplicate dispatch across remounts in same tab)
useEffect(() => {
try {
const stored = sessionStorage.getItem(dispatch:${roomName});
if (stored) dispatchIdRef.current = stored;
} catch (e) {
console.warn('sessionStorage unavailable', e);
}
}, [roomName]);
// --- replace your joinRoom with this version (or merge) ---
const joinRoom = useCallback(async () => {
if (isJoiningRef.current) return;
isJoiningRef.current = true;
setLoading(true);
setError(null);
try {
const params = new URLSearchParams({ room: roomName, identity: patientName, name: patientName });
const res = await fetch(${TOKEN_ENDPOINT}?${params.toString()});
const { token } = await res.json();
if (!token) throw new Error('No token received');
// Only dispatch if we DON'T already have a dispatch id for this room
if (DISPATCH_ENDPOINT && !dispatchIdRef.current) {
agentDispatchedRef.current = true; // prevent concurrent double-dispatch in this instance
const dispatchRes = await fetch(DISPATCH_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
agent_name: "patient",
room: roomName,
patient_name: patientName,
metadata: patientMetadata ?? [],
}),
});
if (dispatchRes.ok) {
const dispatchJson = await dispatchRes.json();
const dispatch_id = dispatchJson.dispatch_id;
if (dispatch_id) {
dispatchIdRef.current = dispatch_id;
try { sessionStorage.setItem(dispatch:${roomName}, dispatch_id); } catch (e) {}
} else {
console.warn('Dispatch response missing dispatch_id', dispatchJson);
}
} else {
console.warn('Dispatch failed:', await dispatchRes.text());
}
}
setToken(token);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to join room');
} finally {
setLoading(false);
isJoiningRef.current = false;
}
}, [roomName, patientName, patientMetadata]);
// --- replace your leaveRoom with this (or merge) ---
const leaveRoom = useCallback(async () => {
// Best-effort: delete the dispatch if we created one
const did = dispatchIdRef.current;
if (did && DISPATCH_DELETE_ENDPOINT) {
try {
await fetch(DISPATCH_DELETE_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ room: roomName, dispatch_id: did }),
});
} catch (err) {
console.warn('Failed to delete dispatch', err);
} finally {
try { sessionStorage.removeItem(dispatch:${roomName}); } catch (e) {}
dispatchIdRef.current = null;
}
}
// reset local flags and leave
agentDispatchedRef.current = false;
setToken(undefined);
onCallEnd?.();
}, [roomName, onCallEnd]);
---
Backend (FastAPI) — minimal endpoints (drop-in to your router)
This example uses a simple in-memory store for room -> dispatch_id. Replace with a persistent DB (Postgres / Redis) in production.
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import os, json
router = APIRouter()
# Naive in-memory mapping (use DB in prod)
_dispatch_store: dict[str, str] = {}
class DispatchAgentPayload(BaseModel):
room: str
agent_name: str
patient_name: str | None = None
metadata: dict | list | None = None
class DeleteDispatchPayload(BaseModel):
room: str
dispatch_id: str
@router.post("/dispatchAgent")
async def dispatch_agent(payload: DispatchAgentPayload):
room_name = payload.room
# Idempotent: if we already dispatched for this room, return the same dispatch_id
existing = _dispatch_store.get(room_name)
if existing:
return {"status": "ok", "room": room_name, "dispatch_id": existing, "note": "already_exists"}
# Prepare metadata string for LiveKit
metadata_json = json.dumps(payload.metadata or {})
lkapi = api.LiveKitAPI(os.getenv("LIVEKIT_URL"), os.getenv("LIVEKIT_API_KEY"), os.getenv("LIVEKIT_API_SECRET"))
try:
dispatch_req = CreateAgentDispatchRequest(agent_name=payload.agent_name, room=room_name, metadata=metadata_json)
dispatch_resp = await lkapi.agent_dispatch.create_dispatch(dispatch_req)
dispatch_id = getattr(dispatch_resp, "dispatch_id", None)
if not dispatch_id:
raise Exception("create_dispatch returned no dispatch_id")
_dispatch_store[room_name] = dispatch_id
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to dispatch agent: {str(e)}")
finally:
await lkapi.aclose()
return {"status": "ok", "room": room_name, "dispatch_id": dispatch_id}
@router.post("/deleteDispatch")
async def delete_dispatch(payload: DeleteDispatchPayload):
lkapi = api.LiveKitAPI(os.getenv("LIVEKIT_URL"), os.getenv("LIVEKIT_API_KEY"), os.getenv("LIVEKIT_API_SECRET"))
try:
resp = await lkapi.agent_dispatch.delete_dispatch(payload.dispatch_id, payload.room)
# Remove mapping if it matches
if payload.room in _dispatch_store and _dispatch_store[payload.room] == payload.dispatch_id:
del _dispatch_store[payload.room]
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to delete dispatch: {str(e)}")
finally:
await lkapi.aclose()
return {"status": "ok", "deleted_dispatch_id": payload.dispatch_id}
---
Short description / notes
Frontend: persist dispatch_id to sessionStorage and avoid re-dispatch if present; delete on leave.
Backend: make dispatchAgent idempotent by returning existing dispatch_id if present; add deleteDispatch which calls LiveKit delete_dispatch and removes mapping.
Production: replace in-memory _dispatch_store with durable storage (DB/Redis) to survive restarts and multi-server deployments. Also ensure agent worker calls ctx.shutdown() when its job ends to avoid orphaned participants.
If you want, I can now produce a tiny git-style diff for each file (or the DB-backed example). Which would be more useful?tall-airline-16756
10/04/2025, 12:56 PMdispatch_id in sessionStorage so we avoid duplicate dispatches when remounting.
• Designing the /dispatchAgent endpoint to be idempotent, which means it returns the existing dispatch_id if there's already a dispatch for that room.
• Introducing a /deleteDispatch endpoint to tidy up the dispatch when someone leaves the room.
This method is really solid and scalable, especially with the helpful tip to switch from an in-memory store to a durable database for production. If you'd like, I’d be happy to provide a git-style diff of the changes or an example that uses a database—just let me know how I can support you!