how do i record a session return ( <Liv...
# ask-ai
i
how do i record a session return ( <LiveKitRoom token={token} serverUrl={serverUrl} connect={true} audio={true} video={true} style={{ height: "70vh", width: "70vw", background: "#000000", }}> <VideoConference/> </LiveKitRoom> );
t
Thanks for reaching out, Raj. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
i
sure
t
You're using the
LiveKitRoom
React component to connect and render — that component cannot start recording by itself. To record a session you must start Egress from your backend (server-side). Here are the concise options and a minimal Node.js example to get you started. Which option you want depends on goal: • Full-room video (recommended): Room Composite Egress — records all participants into a single MP4/HLS or streams to RTMP; supports layouts (grid, speaker) and custom HTML templates. • Auto-record on room creation: AutoEgress — automatically records every room when created. • Agent sessions: If you're using AI agents, enable
record: true
when starting the agent session. Minimal Node.js example (start Room Composite Egress from your backend):
Copy code
import { RoomServiceClient } from 'livekit-server-sdk';

const roomService = new RoomServiceClient(
  'wss://your-project.livekit.cloud',
  'API_KEY',
  'API_SECRET',
);

await roomService.startRoomCompositeEgress('my-room', {
  layout: 'grid',
  audioOnly: false,
  fileOutputs: [{
    filepath: 'recordings/session.mp4',
    s3: {
      bucket: 'my-bucket',
      accessKey: '...',
      secret: '...',
      region: 'us-east-1',
    },
  }],
});
Notes: • Call this from your backend, not the browser. • You need API key/secret with permission to start egress and configured storage (S3/GCS/Azure) or RTMP target. • Recording will stop when the room ends or per egress lifecycle rules (unless using AutoEgress). If you want, tell me: • Do you want a single MP4 of the whole room, HLS + segments, or RTMP streaming? • Are you using LiveKit Cloud or self-hosted LiveKit? • Do you need a sample for another language (Go/CLI) or an AutoEgress example? I can then give the exact backend sample and configuration for your case and storage target. Sources: Composite and web recordings | LiveKit docs | Custom recording templates | LiveKit docs | Auto egress | LiveKit docs | Agents (Node.js) | livekit/livekit_composite | DeepWiki | Recording and export | LiveKit docs
Thanks — quick follow-ups so I can give the exact backend example you need: 1. Do you want a single MP4 of the whole room, HLS (segments + playlist), or RTMP streaming? 2. Are you using LiveKit Cloud or a self‑hosted LiveKit server? 3. Which storage target (S3, GCS, Azure) or RTMP destination do you plan to use? 4. Which backend language do you want the sample in (Node.js, Go, or CLI)? Answer those and I’ll provide the minimal backend code and required config.
i
im using liveavatar api
t
Thanks — since you’re using LiveAvatar, the avatar publishes like any participant, so recording must be started server‑side via LiveKit Egress (the frontend
LiveKitRoom
cannot start recordings). Quick checklist and next steps I can provide: 1. Choose output: ◦ Single MP4 (Room Composite) — recommended to capture avatar + participants. ◦ HLS segments + playlist. ◦ RTMP stream. ◦ Audio-only (OGG/MP3) if you only need voice. 1. Ensure permissions: ◦ Use an API key/secret that has the
roomRecord
permission. 1. Start Egress from your backend (example languages: Node.js, Go, Python, or CLI). Minimal Node.js example to start a Room Composite MP4 to S3:
Copy code
import { RoomServiceClient } from 'livekit-server-sdk';

const roomService = new RoomServiceClient('wss://your-project.livekit.cloud', 'API_KEY', 'API_SECRET');

await roomService.startRoomCompositeEgress('your-room-name', {
  layout: 'grid',
  audioOnly: false,
  fileOutputs: [{
    filepath: 'recordings/session.mp4',
    s3: {
      bucket: 'your-bucket',
      accessKey: '...',
      secret: '...',
      region: 'us-east-1',
    },
  }],
});
1. Stop recording: ◦ Call StopEgress via API using the returned
egress_id
, or let the Room Composite stop when the room ends/all participants leave. Tell me which of these you want and I’ll provide the exact backend sample and configuration: • Preferred output (MP4 / HLS / RTMP / audio-only) • Storage target (S3 / GCS / Azure / RTMP URL) • Backend language (Node.js / Go / Python / CLI) I’ll give the complete code and any extra config (IAM settings, bucket path, or AutoEgress example) once you pick options. Sources: LiveAvatar virtual avatar integration guide | LiveKit docs | Recording and export | LiveKit docs | Composite and web recordings | LiveKit docs | Egress API | LiveKit docs | Auto egress | LiveKit docs
i
i can have options to choose hls or mp4 both depends and s3 and azure depends. for backend im using nodejs. btw while recording the video i can capture audio as well ryt?
t
You're good — Room Composite Egress can produce MP4 or HLS and will capture audio along with video. Below are minimal Node.js examples for starting a Room Composite Egress to (A) MP4 on S3, (B) HLS on S3, and (C) MP4 on Azure Blob. Each example records audio+video by default (set
audioOnly: true
if you only want audio). You need an API key/secret with
roomRecord
permission. 1) MP4 to S3
Copy code
import { RoomServiceClient } from 'livekit-server-sdk';

const svc = new RoomServiceClient(
  'wss://your-project.livekit.cloud',
  'API_KEY',
  'API_SECRET',
);

await svc.startRoomCompositeEgress('your-room-name', {
  layout: 'grid',
  audioOnly: false,
  fileOutputs: [{
    filepath: 'recordings/session.mp4',
    s3: {
      bucket: 'your-bucket',
      accessKey: 'S3_ACCESS_KEY',
      secret: 'S3_SECRET',
      region: 'us-east-1',
    },
  }],
});
2) HLS (segments + playlist) to S3
Copy code
await svc.startRoomCompositeEgress('your-room-name', {
  layout: 'speaker',
  audioOnly: false,
  hls: {
    segmentOutputs: [{
      filenamePrefix: 'recordings/session',
      s3: {
        bucket: 'your-bucket',
        accessKey: 'S3_ACCESS_KEY',
        secret: 'S3_SECRET',
        region: 'us-east-1',
      },
    }],
    playlistName: 'session.m3u8',
  },
});
3) MP4 to Azure Blob
Copy code
await svc.startRoomCompositeEgress('your-room-name', {
  layout: 'grid',
  audioOnly: false,
  fileOutputs: [{
    filepath: 'recordings/session.mp4',
    azure: {
      container: 'your-container',
      storageAccount: 'your-account',
      storageKey: 'AZURE_STORAGE_KEY',
    },
  }],
});
Stopping a recording • The API returns an
egress_id
you can use to stop via StopEgress, or Room Composite stops automatically when the room ends/all participants leave. Notes & quick tips • Audio is included by default when
audioOnly: false
. Use audio mixing options if you need separate channels or special mixing. • Ensure the API key has
roomRecord
permission and your storage credentials (S3/Azure) are valid and have write access. • If you want AutoEgress (start on room creation) or a sample that records only the LiveAvatar track, I can provide that too. Which output/target do you want first (MP4→S3, HLS→S3, or MP4→Azure)? I’ll give a ready-to-run Node.js snippet for your chosen option including request/response handling and StopEgress.
i
curl --request POST \ --url https://api.liveavatar.com/v1/sessions/start \ --header 'accept: application/json' { "code": 100, "data": { "session_id": "string", "livekit_url": "string", "livekit_client_token": "string", "max_session_duration": 0, "ws_url": "string" }, "message": "string" } i have this im not sure where to get url n api key and token
t
You're on the right track — that LiveAvatar
sessions/start
response contains the LiveKit connection details you need on the client. I’ll clarify where each value comes from and what you need on the backend to start Egress recording. What each field is and where to use it •
livekit_url
— the LiveKit server URL to connect to (use this in the frontend
LiveKitRoom
serverUrl
or when creating a RoomServiceClient on the backend). •
livekit_client_token
— short‑lived token for the client to join the room (use this in your frontend
token
prop). •
session_id
/
ws_url
— LiveAvatar session identifiers/WS endpoint (keep for session management; not required to start egress). • API key / API secret for Egress — separate from the client token. You must use an API key/secret with
roomRecord
permission from your LiveKit project (or LiveKit Cloud project) to call the Egress API from your backend. Where to get keys/URLs • LiveAvatar / LiveKit Cloud dashboard: retrieve or generate the LiveKit API key and secret for your project (the key/secret used server‑side to start Egress). The
livekit_url
and
livekit_client_token
are returned by the LiveAvatar
sessions/start
response; use those on the client to connect. • If you’re self‑hosting LiveKit, use your server address as
livekit_url
and create an API key/secret with
roomRecord
permissions in your LiveKit admin. Minimal flow to record (summary) 1. Frontend: call LiveAvatar
sessions/start
(your example curl). Use
livekit_client_token
and
livekit_url
to render
LiveKitRoom
. 2. Backend (Node.js): use your LiveKit API key/secret (server credentials) to call the Egress API (Room Composite) and write to S3/Azure. This is separate from the client token returned by LiveAvatar. 3. Stop egress via StopEgress when done or let it stop automatically. Node.js Egress example (fill in placeholders)
Copy code
import { RoomServiceClient } from 'livekit-server-sdk';

const svc = new RoomServiceClient('wss://<LIVEKIT_SERVER>', '<API_KEY>', '<API_SECRET>');

await svc.startRoomCompositeEgress('<room-name>', {
  layout: 'grid',
  audioOnly: false,
  fileOutputs: [{
    filepath: 'recordings/session.mp4',
    s3: {
      bucket: '<BUCKET>',
      accessKey: '<S3_KEY>',
      secret: '<S3_SECRET>',
      region: '<REGION>',
    },
  }],
});
Quick checklist for you to confirm • Do you have access to the LiveAvatar response that includes
livekit_url
and
livekit_client_token
? (That’s what the client uses.) • Do you have a server API key/secret with
roomRecord
permission from your LiveKit project or Cloud dashboard? (That’s what the backend uses to start Egress.) • Which storage target do you want to use first (S3 or Azure)? I’ll give the exact Node.js snippet with the correct output block and StopEgress example. Tell me which storage target to show first and whether you can access your project API key/secret in the LiveKit/LiveAvatar dashboard.
i
yes i do have access to livekit_url and livkit_client_token and okay i got it now for api key secret and wsurl i will get from livkit dashboard ryt?
t
Yes — that’s correct. Quick summary and exact places to look: • livekit_url and livekit_client_token: provided by LiveAvatar’s
sessions/start
response — use
livekit_url
as the server URL in your frontend
LiveKitRoom
and
livekit_client_token
as the client token. • API key & API secret (server credentials): get these from your LiveKit project (LiveKit Cloud or self‑hosted admin/dashboard). Use the key/secret on your backend to call Egress. Ensure the key has the roomRecord permission. • ws_url: LiveAvatar may return a
ws_url
for session control; your backend doesn’t need it to start Egress. For LiveKit server SDKs, use the
livekit_url
(or your LiveKit dashboard URL) when creating
RoomServiceClient
. Ready-to-use checklist for your Node.js backend: 1. In LiveKit dashboard: create/get an API key + secret with roomRecord permission. 2. In your backend code, create
RoomServiceClient
with your LiveKit server URL and API key/secret. 3. Call
startRoomCompositeEgress(...)
with desired output (MP4/HLS) and S3/Azure config. 4. Use the returned
egress_id
to stop recording if needed. If you want, tell me which storage target (S3 or Azure) you want to implement first and I’ll paste a complete ready-to-run Node.js snippet with error handling and StopEgress.
i
ws_url i get this as null in liveavatar so that leaves only client_url and token from livkit_
t
Got it — thanks for confirming that
ws_url
is null. That’s fine: you only need
livekit_url
+
livekit_client_token
for the frontend, and a separate server API key/secret for Egress. Quick confirmation and next step: • Confirmed:
ws_url
is not needed to start Egress. • Frontend uses:
livekit_url
(serverUrl) and
livekit_client_token
(token). • Backend uses: LiveKit API key & secret (from your LiveKit dashboard) + the same
room name
that the client joins to start Egress. Which storage target should I provide the ready-to-run Node.js snippet for first — S3 or Azure Blob?
i
how do i get this room name from
t
Good question — you need the LiveKit room name on the backend to start Egress. Two simple ways to get it when using LiveAvatar: 1. Use the LiveAvatar response • Check the
sessions/start
response fields — some integrations include
session_id
or a
room
field you can use directly as the room name. If LiveAvatar set a room name at creation, use that. 1. Decode the
livekit_client_token
• The
livekit_client_token
is a JWT. It often contains a
room
(or
room_name
) claim you can read to get the room name. Quick Node.js example to decode the token (no verification needed just to read claims):
Copy code
const jwt = require('jsonwebtoken');

const token = '<livekit_client_token>';
const decoded = jwt.decode(token);
console.log(decoded); // look for decoded.room or decoded.room_name
Notes • If you control the LiveAvatar session creation, you can supply a custom room name there (recommended for predictable naming). • The room name you use for Egress must match the room clients join. • If the token has no room claim and LiveAvatar response contains no room, ask your LiveAvatar flow what room name it assigns (or configure it to set one). Tell me whether you want the S3 or Azure Node.js egress snippet next and I’ll include using the exact room name you get from the token/response.
i
i have this
session_id
t
Thanks — quick clarification and next steps. The
session_id
from LiveAvatar is not necessarily the LiveKit room name. To get the room name you should: 1. Decode the
livekit_client_token
JWT and look for a
room
or
room_name
claim.
Copy code
const jwt = require('jsonwebtoken');
   const decoded = jwt.decode('<livekit_client_token>');
   console.log(decoded); // look for decoded.room or decoded.room_name
1. If the token has no room claim, check the LiveAvatar
sessions/start
response for a
room
field or configure LiveAvatar to set a specific room name when creating the session. Use that exact room name in your backend when calling
startRoomCompositeEgress(...)
. Which storage target do you want the ready-to-run Node.js egress snippet for first — S3 or Azure?
i
i decoded the token {id: "AE_RGerpw4zLUDi" project_id: "p_4se0gzeagbr" room_id: "RM_YxcnGaXotX9f" timestamp: "2025-12-05T160451Z" type: "Room created" node_id: "NM_OHYDERABAD1A_SaY3NiCHdqmh" timestamp_us: 1764950691000000 }
t
Good — that decoded token shows
room_id: "RM_YxcnGaXotX9f"
. Use that value as the LiveKit room name when starting Egress from your backend. Next, tell me: • Which storage target do you want first: S3 or Azure Blob? • Which output format: MP4 or HLS? I’ll give a ready-to-run Node.js snippet (start + stop egress) using that room ID and your chosen storage.
i
s3
t
Do you want MP4 or HLS output to S3? Once you pick, I’ll provide a ready-to-run Node.js snippet (start + stop egress) using your
RM_YxcnGaXotX9f
room ID.
i
mp4
t
Great — below is a ready-to-run Node.js example to start and stop a Room Composite Egress that records MP4 (video + audio) to S3, using your room ID
RM_YxcnGaXotX9f
. Before you run: • Ensure you have a LiveKit API key/secret with the
roomRecord
permission. • Install the server SDK:
npm install livekit-server-sdk
. • Make sure your S3 creds have write access to the target bucket. Start Egress (MP4 → S3)
Copy code
// start-egress.ts
import { RoomServiceClient } from 'livekit-server-sdk';

const LIVEKIT_WS = 'wss://<YOUR_LIVEKIT_HOST>'; // e.g. wss://your-project.livekit.cloud
const API_KEY = process.env.LIVEKIT_API_KEY!;
const API_SECRET = process.env.LIVEKIT_API_SECRET!;

const svc = new RoomServiceClient(LIVEKIT_WS, API_KEY, API_SECRET);

async function startEgress() {
  const roomName = 'RM_YxcnGaXotX9f';

  const resp = await svc.startRoomCompositeEgress(roomName, {
    layout: 'grid',           // or 'speaker', 'single-speaker'
    audioOnly: false,         // false => include audio + video
    fileOutputs: [{
      filepath: 'recordings/session.mp4',
      s3: {
        bucket: 'your-s3-bucket',
        accessKey: process.env.S3_ACCESS_KEY!,
        secret: process.env.S3_SECRET!,
        region: 'us-east-1',
      },
    }],
  });

  console.log('Egress started:', resp.egressId || resp.egress_id || resp);
  return resp;
}

startEgress().catch((err) => {
  console.error('startEgress error', err);
  process.exit(1);
});
Stop Egress (by egress_id returned above)
Copy code
// stop-egress.ts
import { RoomServiceClient } from 'livekit-server-sdk';

const LIVEKIT_WS = 'wss://<YOUR_LIVEKIT_HOST>';
const API_KEY = process.env.LIVEKIT_API_KEY!;
const API_SECRET = process.env.LIVEKIT_API_SECRET!;

const svc = new RoomServiceClient(LIVEKIT_WS, API_KEY, API_SECRET);

async function stopEgress(egressId: string) {
  const resp = await svc.stopEgress(egressId);
  console.log('Egress stopped:', resp);
}

const egressId = process.argv[2];
if (!egressId) {
  console.error('Usage: node stop-egress.js <egressId>');
  process.exit(1);
}

stopEgress(egressId).catch((err) => {
  console.error('stopEgress error', err);
  process.exit(1);
});
Notes and tips • The
startRoomCompositeEgress
response includes an
egressId
(store it to stop later). • S3
filepath
is the path within the bucket (the SDK manages uploading). • If you prefer HLS later, change the request to include an
hls
block instead of
fileOutputs
. • If you want audio-only, set
audioOnly: true
. • Use HTTPS/WSS host from your LiveKit dashboard as
LIVEKIT_WS
. • Ensure environment variables are set:
LIVEKIT_API_KEY
,
LIVEKIT_API_SECRET
,
S3_ACCESS_KEY
,
S3_SECRET
. Want me to: • Return a version that writes logs and retries on failure? • Convert this to an Express endpoint that starts/stops egress via HTTP?
i
do i need to pass session token from aws bucket?
t
Short answer: No — you do not pass the LiveAvatar/LiveKit session token to S3. Egress needs valid S3 credentials so it can write the file; those credentials are separate from the LiveKit client token. Details and best practice: • What Egress needs: include S3 credentials (accessKey + secret, and optionally a sessionToken if you use temporary STS credentials) in the egress request so LiveKit can upload the MP4 to your bucket. • What you do NOT pass: the LiveAvatar
livekit_client_token
or session_id — those are only for clients to join the room. • Temporary creds: if you use AWS STS (temporary credentials), pass the
sessionToken
along with accessKey/secret in the egress S3 block. • Security: keep S3 credentials only on your backend (never in browser/client). Use IAM roles or short‑lived STS creds for better security. If you want, I can show the exact Node.js egress snippet using temporary STS credentials (including
sessionToken
) or standard accessKey/secret — which do you prefer?
i
temp sts plz
t
Below is a ready-to-run Node.js example that: • Gets temporary AWS STS credentials (accessKeyId, secretAccessKey, sessionToken) using AWS SDK. • Starts a LiveKit Room Composite Egress to write an MP4 to your S3 bucket using those temporary creds. • Shows how to stop the egress by egressId. Important notes: • Do NOT send LiveAvatar/LiveKit client tokens to S3. The STS creds are what LiveKit uses to upload the recorded file. • Ensure the IAM role you assume has S3 PutObject permissions for the target bucket. • Keep LiveKit API key/secret and AWS credentials on your backend only. 1) Install dependencies
Copy code
npm install livekit-server-sdk @aws-sdk/client-sts @aws-sdk/credential-providers
2) start-egress-with-sts.ts
Copy code
import { RoomServiceClient } from 'livekit-server-sdk';
import { STSClient, AssumeRoleCommand } from '@aws-sdk/client-sts';

const LIVEKIT_WS = process.env.LIVEKIT_WS!; // e.g. wss://your-project.livekit.cloud
const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY!;
const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET!;
const ROLE_ARN = process.env.AWS_ASSUME_ROLE_ARN!; // role with S3 write permissions
const S3_BUCKET = process.env.S3_BUCKET!;

async function assumeRole() {
  const client = new STSClient({});
  const cmd = new AssumeRoleCommand({
    RoleArn: ROLE_ARN,
    RoleSessionName: 'livekit-egress-session',
    DurationSeconds: 3600, // adjust as needed
  });
  const res = await client.send(cmd);
  if (!res.Credentials) throw new Error('Failed to assume role');
  return {
    accessKeyId: res.Credentials.AccessKeyId!,
    secretAccessKey: res.Credentials.SecretAccessKey!,
    sessionToken: res.Credentials.SessionToken!,
  };
}

async function startEgress() {
  // assume role to get temporary S3 creds
  const { accessKeyId, secretAccessKey, sessionToken } = await assumeRole();

  // create LiveKit RoomService client
  const svc = new RoomServiceClient(LIVEKIT_WS, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);

  const roomName = 'RM_YxcnGaXotX9f'; // your room ID from decoded token

  const resp = await svc.startRoomCompositeEgress(roomName, {
    layout: 'grid',
    audioOnly: false, // include audio + video
    fileOutputs: [{
      filepath: 'recordings/session.mp4',
      s3: {
        bucket: S3_BUCKET,
        accessKey: accessKeyId,
        secret: secretAccessKey,
        region: process.env.AWS_REGION || 'us-east-1',
        sessionToken: sessionToken, // include the STS session token
      },
    }],
  });

  console.log('Egress started:', resp.egressId || resp.egress_id || resp);
  return resp.egressId || resp.egress_id;
}

startEgress().then(id => {
  console.log('Use this egressId to stop:', id);
}).catch(err => {
  console.error(err);
  process.exit(1);
});
3) stop-egress.ts
Copy code
import { RoomServiceClient } from 'livekit-server-sdk';

const LIVEKIT_WS = process.env.LIVEKIT_WS!;
const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY!;
const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET!;

const svc = new RoomServiceClient(LIVEKIT_WS, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);

async function stopEgress(egressId: string) {
  const res = await svc.stopEgress(egressId);
  console.log('Stopped egress:', res);
}

const egressId = process.argv[2];
if (!egressId) {
  console.error('Usage: node stop-egress.js <egressId>');
  process.exit(1);
}
stopEgress(egressId).catch(err => {
  console.error(err);
  process.exit(1);
});
Environment variables to set: • LIVEKIT_WS (wss://... from LiveKit dashboard) • LIVEKIT_API_KEY and LIVEKIT_API_SECRET (server credentials with roomRecord permission) • AWS_ASSUME_ROLE_ARN (ARN of the role that has S3 PutObject permissions) • S3_BUCKET • AWS_REGION (optional) IAM tips: • The role you assume should allow PutObject and PutObjectAcl (if needed) on the target S3 prefix. • If you prefer, you can also use an IAM user accessKey/secret directly (omit sessionToken) — STS is recommended for security. Would you like this as an Express endpoint (start/stop via HTTP) or with automatic StopEgress after a timeout?
i
so one question even if i pass the s3 credentials and room name all of that still who will start the recording and who will store it in my s3
t
Good question — here’s the short, clear flow and who does what: • Who starts the recording: Your backend. You call LiveKit’s Egress API (e.g., via the Node.js RoomServiceClient) with the room name and S3 credentials. That API call initiates the recording. • Who records the media: LiveKit’s Egress service (running on LiveKit Cloud or your LiveKit server) performs the actual recording/compositing of the room (video + audio). • Who stores the file in your S3: LiveKit Egress uploads the recorded MP4 directly to your S3 bucket using the S3 credentials you provided in the egress request (these can be temporary STS creds). Security notes: • Keep LiveKit API key/secret and S3 creds on your backend only — never in the browser. • Use temporary STS creds (recommended) so LiveKit uploads using short‑lived credentials. • The LiveAvatar/LiveKit client token is only for joining the room; it is not used for S3 uploads. If you want, I can show an Express endpoint that (1) assumes the role, (2) calls startRoomCompositeEgress, and (3) stores the returned egressId so you can stop it later. Which would you prefer?
i
when the livkit Ui component starts in the frontend i can call this api then it will store
t
Yes — that’s exactly right. High-level flow and a minimal example so you can wire it up: Flow • Frontend (LiveKitRoom) connects using
livekit_url
+
livekit_client_token
. • When your front end is ready to start recording, call your backend endpoint (not LiveKit directly from the browser). • Backend: assumes role / gets S3 temporary creds (or uses long‑term creds), then calls LiveKit Egress (startRoomCompositeEgress) with the room name and S3 creds. • LiveKit Egress records the room and uploads the MP4 directly to your S3 bucket. • Backend stores the returned
egressId
so you can stop the recording later (or stop automatically). Minimal frontend fetch example (call your backend when UI starts recording)
Copy code
// from your React app when you want to start recording
await fetch('/api/start-recording', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ room: 'RM_YxcnGaXotX9f' }) });
Backend responsibilities 1. Optionally assume AWS role (STS) to get temp S3 creds. 2. Call LiveKit RoomServiceClient.startRoomCompositeEgress(roomName, { fileOutputs: [{ s3: { accessKey, secret, sessionToken, bucket, region }, filepath: 'recordings/session.mp4' }], audioOnly:false, layout:'grid' }) 3. Return or persist the
egressId
to allow stopping later. 4. Provide an endpoint to stop egress (calls stopEgress with
egressId
). If you want, I’ll give a full ready-to-run Express pair of endpoints (/api/start-recording and /api/stop-recording) that: • assumes role for STS, • starts Room Composite MP4 egress to S3, • returns/saves the egressId, and includes basic error handling. Should I provide that now?
i
okay return ( <LiveKitRoom token={token} serverUrl={serverUrl} connect={true} audio={true} video={true} style={{ height: "70vh", width: "70vw", background: "#000000", }}> <VideoConference/> </LiveKitRoom> ); currently im using this so when user leaves the room what happens to liveavatar session does it close itself or we need to handle stop session api
t
Short answer: the LiveAvatar session does not automatically close when the user leaves — you should stop it (or delete the room) from your backend. What happens now • When the user leaves the frontend
LiveKitRoom
, the client disconnects but the agent/avatar can remain in the LiveKit room. • That means the avatar and agent may keep running (and egress may keep recording) unless you explicitly stop them. What you should do • Best practice: when the user leaves, call your backend to delete the LiveKit room (or stop the AgentSession). Deleting the room will: ◦ Disconnect the agent and avatar, ◦ Stop any active egress recordings, ◦ Cleanly end the LiveAvatar session. How to implement (minimal) 1. Frontend: on leave/unmount, call your backend endpoint:
Copy code
fetch('/api/end-session', { method: 'POST', body: JSON.stringify({ room: 'RM_YxcnGaXotX9f' }) });
1. Backend: delete the room using RoomServiceClient:
Copy code
import { RoomServiceClient } from 'livekit-server-sdk';
const svc = new RoomServiceClient(LIVEKIT_WS, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);
await svc.deleteRoom('RM_YxcnGaXotX9f');
Alternative • If you prefer not to delete the room, call your agent logic to stop the AgentSession (e.g.,
session.aclose()
), or call
stopEgress(egressId)
to stop recordings while keeping the room. Recommendation • Delete the room on user disconnect for a clean shutdown (recommended). Would you like the Express endpoints for /api/end-session (delete room) and /api/start-recording wired together? Sources: Job lifecycle | LiveKit docs | RoomComposite Egress | LiveKit Docs | Egress output types | LiveKit docs | Web Egress | LiveKit Docs | Virtual avatar plugins | LiveKit Docs
i
if thats the case how do i that since videoconference component inside exit button is there how do i call that
t
Good question — here’s a minimal, practical way to wire your exit button to cleanly stop the LiveAvatar session by deleting the LiveKit room on the backend. 1) Frontend: call your backend when the user clicks Exit • Inside your VideoConference component, call an endpoint with the room name (use the decoded room id you already have). Example (React):
Copy code
// inside VideoConference component
async function handleExit() {
  await fetch('/api/end-session', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ room: 'RM_YxcnGaXotX9f' }),
  });
  // then navigate away / cleanup client UI
  // e.g., window.location = '/goodbye' or update app state
}

// render
<button onClick={handleExit}>Exit</button>
2) Backend: delete the LiveKit room (stops avatar/agent and any egress) • Implement /api/end-session to call RoomServiceClient.deleteRoom with your server API key/secret. Example (Express + Node.js):
Copy code
// server.js (or routes file)
import express from 'express';
import { RoomServiceClient } from 'livekit-server-sdk';

const app = express();
app.use(express.json());

const svc = new RoomServiceClient(process.env.LIVEKIT_WS!, process.env.LIVEKIT_API_KEY!, process.env.LIVEKIT_API_SECRET!);

app.post('/api/end-session', async (req, res) => {
  const { room } = req.body;
  if (!room) return res.status(400).json({ error: 'room required' });

  try {
    await svc.deleteRoom(room);
    return res.json({ ok: true });
  } catch (err) {
    console.error('deleteRoom error', err);
    return res.status(500).json({ error: 'failed to delete room' });
  }
});

app.listen(3000);
Why this works • Deleting the room disconnects all participants, stops the LiveAvatar/agent, and automatically ends any Room Composite egress. It avoids lingering avatar activity or extra recordings. Extras / best practices • Confirm the frontend only calls the endpoint after local cleanup (stop local tracks, unmount LiveKitRoom). • Protect the endpoint (authenticate the caller) so only authorized users can delete rooms. • Optionally return the current egressId or egress status from the backend if you need to show recording state to the user. Would you like a full example that: • unmounts LiveKitRoom, stops local tracks, then calls /api/end-session, or • includes auth on the endpoint?
i
return ( <LiveKitRoom token={token} serverUrl={serverUrl} connect={true} audio={true} video={true} style={{ height: "70vh", width: "70vw", background: "#000000", }}> <VideoConference/> </LiveKitRoom> ); im using this react compoentn
t
Use LiveKitRoom's disconnect hooks to detect the user leaving and call your backend to delete the room. Below is a minimal React pattern you can drop into your app — it shows an Exit button and also handles automatic cleanup when the user disconnects (unmounts or network disconnect). Frontend (React — inside the component that renders LiveKitRoom / VideoConference)
Copy code
import { useRoom } from '@livekit/react'; // or useRoomContext hook your SDK provides
import { useEffect } from 'react';

function VideoConferenceWrapper({ roomName }) {
  const room = useRoom(); // or useRoomContext() depending on your SDK
  // call backend to end session
  async function endSession() {
    try {
      await fetch('/api/end-session', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ room: roomName }),
      });
    } catch (err) {
      console.error('endSession error', err);
    }
  }

  // Exit button handler
  async function handleExit() {
    // stop local tracks / cleanup client UI first (optional)
    try {
      room?.localParticipant?.stopPublishing?.(); // optional safe cleanup if available
    } catch {}
    // unmount LiveKitRoom (navigate away) then tell backend to delete room
    await endSession();
    // navigate away or update state to remove LiveKitRoom
    window.location.href = '/';
  }

  // Detect disconnect (network or client leaving) and call backend cleanup
  useEffect(() => {
    if (!room) return;
    const onDisconnected = () => {
      endSession();
    };
    room.on('disconnected', onDisconnected); // event name may be 'disconnected' or 'connectionStateChanged' depending on SDK
    // also handle page unload as a fallback
    const onUnload = () => { navigator.sendBeacon('/api/end-session', JSON.stringify({ room: roomName })); };
    window.addEventListener('beforeunload', onUnload);

    return () => {
      room.off?.('disconnected', onDisconnected);
      window.removeEventListener('beforeunload', onUnload);
    };
  }, [room, roomName]);

  return (
    <>
      <VideoConference />
      <button onClick={handleExit}>Exit</button>
    </>
  );
}
Backend endpoint (Express example — deletes the LiveKit room)
Copy code
import express from 'express';
import { RoomServiceClient } from 'livekit-server-sdk';
const app = express();
app.use(express.json());

const svc = new RoomServiceClient(process.env.LIVEKIT_WS!, process.env.LIVEKIT_API_KEY!, process.env.LIVEKIT_API_SECRET!);

app.post('/api/end-session', async (req, res) => {
  const { room } = req.body;
  if (!room) return res.status(400).send({ error: 'room required' });
  try {
    await svc.deleteRoom(room);
    return res.json({ ok: true });
  } catch (err) {
    console.error('deleteRoom error', err);
    return res.status(500).json({ error: 'failed to delete room' });
  }
});
Notes • Use the decoded
room_id
(e.g.,
RM_YxcnGaXotX9f
) as
roomName
. • Protect /api/end-session (authenticate requests) so only authorized users can delete rooms. • Deleting the room will stop the LiveAvatar/agent and any active egress automatically. • Use
navigator.sendBeacon
on unload to improve delivery reliability for quick disconnects. If you want, I can adapt the React snippet to your exact LiveKit React SDK hooks (showing the exact event name and local track cleanup) — tell me which LiveKit React package/version you’re using.
i
okay provide me a UI react components for two participants one for user and other for liveavatar
t
Below is a minimal, ready-to-drop-in React implementation that renders two participant panels: the local user and the LiveAvatar agent. It uses @livekit/components-react hooks/components. It also includes an Exit button that unmounts the room and calls your backend to delete the room. Prereqs • Install: npm install livekit-client @livekit/components-react @livekit/components-styles • Provide
serverUrl
,
token
, and
roomName
as props (you already decode the token to get roomName). • Protect backend /api/end-session so only authorized callers can delete the room. File: VideoRoom.tsx
Copy code
import React, { useEffect, useState } from 'react';
import {
  LiveKitRoom,
  RoomAudioRenderer,
  useParticipants,
  VideoTrack,
  Participant,
  useRoomContext,
} from '@livekit/components-react';
import '@livekit/components-styles';

type VideoRoomProps = {
  serverUrl: string;
  token: string;
  roomName: string; // e.g. RM_YxcnGaXotX9f
  onEnded?: () => void;
};

export default function VideoRoom({ serverUrl, token, roomName, onEnded }: VideoRoomProps) {
  return (
    <LiveKitRoom
      serverUrl={serverUrl}
      token={token}
      connect={true}
      audio={true}
      video={true}
      style={{ height: '70vh', width: '70vw', background: '#000' }}
    >
      <RoomUI roomName={roomName} onEnded={onEnded} />
      <RoomAudioRenderer />
    </LiveKitRoom>
  );
}

function RoomUI({ roomName, onEnded }: { roomName: string; onEnded?: () => void }) {
  const participants = useParticipants();
  const [egressId, setEgressId] = useState<string | null>(null);

  // Identify local user and agent participant
  const local = participants.find(p => p.isLocal);
  // Heuristic: LiveAvatar agent often has identity prefix/suffix; adjust if needed.
  const agent = participants.find(p => /agent|avatar/i.test(p.identity));

  // Exit handler: call backend to delete room, then navigate/unmount
  async function handleExit() {
    try {
      // optional: stop local tracks/cleanup here if needed
      await fetch('/api/end-session', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ room: roomName, egressId }),
      });
    } catch (err) {
      console.error('end-session error', err);
    } finally {
      if (onEnded) onEnded();
      else window.location.href = '/';
    }
  }

  // Optional: detect unmount/disconnect and call end-session via sendBeacon
  useEffect(() => {
    const onUnload = () => {
      try {
        navigator.sendBeacon('/api/end-session', JSON.stringify({ room: roomName, egressId }));
      } catch {}
    };
    window.addEventListener('beforeunload', onUnload);
    return () => window.removeEventListener('beforeunload', onUnload);
  }, [roomName, egressId]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ display: 'flex', gap: 12, flex: 1 }}>
        <ParticipantPanel title="You" participant={local} />
        <ParticipantPanel title="AI Agent" participant={agent} placeholder="Agent connecting..." />
      </div>

      <div style={{ marginTop: 8, display: 'flex', gap: 8 }}>
        <button onClick={handleExit} style={{ padding: '8px 12px' }}>Exit</button>
      </div>
    </div>
  );
}

function ParticipantPanel({
  participant,
  title,
  placeholder = 'No video',
}: {
  participant?: Participant;
  title: string;
  placeholder?: string;
}) {
  // If we have an attached video track publication, VideoTrack component will render it.
  // VideoTrack accepts a trackRef: publication or track reference; components library handles it.
  return (
    <div style={{ flex: 1, position: 'relative', background: '#111', borderRadius: 8, overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 8, left: 8, color: '#fff', zIndex: 5 }}>{title}</div>
      <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {participant ? (
          // VideoTrack will auto-render the participant's first camera track if available
          // Provide participant to VideoTrack via trackRef APIs; components lib handles subscriptions.
          // Using <VideoTrack publication={...} /> is an option, but passing participant here is fine for simplicity.
          <VideoTrack participant={participant} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
        ) : (
          <div style={{
            color: '#ddd',
            textAlign: 'center',
            padding: 16,
          }}>{placeholder}</div>
        )}
      </div>
    </div>
  );
}
How it works • LiveKitRoom handles connection with the provided serverUrl and token. • useParticipants returns current participants; we pick local.isLocal for the user and find the agent by identity matching "agent" or "avatar". • VideoTrack renders each participant's camera track and RoomAudioRenderer plays all audio. • Exit button calls /api/end-session with the room name (backend should call RoomServiceClient.deleteRoom(roomName)). Notes / tuning • Participant detection: adjust the agent identity heuristic to whatever LiveAvatar uses in your project (e.g., startsWith('agent-avatar')). • If you prefer explicit track rendering, find the camera publication via participant.getTrack(Track.Source.Camera) and pass that to VideoTrack publication prop. • Protect /api/end-session and authenticate the caller. • If you want the Exit button to also stop local tracks before deleting the room, call participant.localParticipant?.unpublishTrack(...) or stop tracks locally before calling the backend. Want this adapted to: • raw livekit-client hooks (no @livekit/components-react), or • include a start/stop recording button that calls your backend endpoints to start Egress? Which would you like next? Sources: LiveAvatar virtual avatar integration guide | LiveKit docs | Bringing AI avatars to voice agents | Bringing AI avatars to voice agents | Subscribing to tracks | LiveKit docs
i
Module '"@livekit/components-react"' has no exported member 'Participant'
t
Good catch —
Participant
is exported from
livekit-client
, not
@livekit/components-react
. Below is a corrected, minimal TypeScript React component that: • Uses correct imports • Renders two panels: local user and LiveAvatar agent • Uses
useParticipants()
from
@livekit/components-react
• Uses
VideoTrack
to render participant video • Includes an Exit button that calls your backend to delete the room Drop-in file: VideoRoom.tsx
Copy code
import React, { useEffect, useState } from 'react';
import { Participant } from 'livekit-client';
import {
  LiveKitRoom,
  RoomAudioRenderer,
  useParticipants,
  VideoTrack,
} from '@livekit/components-react';
import '@livekit/components-styles';

type VideoRoomProps = {
  serverUrl: string;
  token: string;
  roomName: string; // e.g. RM_YxcnGaXotX9f
  onEnded?: () => void;
};

export default function VideoRoom({ serverUrl, token, roomName, onEnded }: VideoRoomProps) {
  return (
    <LiveKitRoom
      serverUrl={serverUrl}
      token={token}
      connect={true}
      audio={true}
      video={true}
      style={{ height: '70vh', width: '70vw', background: '#000' }}
    >
      <RoomUI roomName={roomName} onEnded={onEnded} />
      <RoomAudioRenderer />
    </LiveKitRoom>
  );
}

function RoomUI({ roomName, onEnded }: { roomName: string; onEnded?: () => void }) {
  const participants = useParticipants();
  const [egressId, setEgressId] = useState<string | null>(null);

  const local = participants.find(p => p.isLocal) as Participant | undefined;
  const agent = participants.find(p => /agent|avatar/i.test(p.identity)) as Participant | undefined;

  async function handleExit() {
    try {
      await fetch('/api/end-session', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ room: roomName, egressId }),
      });
    } catch (err) {
      console.error('end-session error', err);
    } finally {
      if (onEnded) onEnded();
      else window.location.href = '/';
    }
  }

  useEffect(() => {
    const onUnload = () => {
      try {
        navigator.sendBeacon('/api/end-session', JSON.stringify({ room: roomName, egressId }));
      } catch {}
    };
    window.addEventListener('beforeunload', onUnload);
    return () => window.removeEventListener('beforeunload', onUnload);
  }, [roomName, egressId]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ display: 'flex', gap: 12, flex: 1 }}>
        <ParticipantPanel title="You" participant={local} />
        <ParticipantPanel title="AI Agent" participant={agent} placeholder="Agent connecting..." />
      </div>

      <div style={{ marginTop: 8, display: 'flex', gap: 8 }}>
        <button onClick={handleExit} style={{ padding: '8px 12px' }}>Exit</button>
      </div>
    </div>
  );
}

function ParticipantPanel({
  participant,
  title,
  placeholder = 'No video',
}: {
  participant?: Participant;
  title: string;
  placeholder?: string;
}) {
  return (
    <div style={{ flex: 1, position: 'relative', background: '#111', borderRadius: 8, overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 8, left: 8, color: '#fff', zIndex: 5 }}>{title}</div>
      <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {participant ? (
          <VideoTrack participant={participant} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
        ) : (
          <div style={{ color: '#ddd', textAlign: 'center', padding: 16 }}>{placeholder}</div>
        )}
      </div>
    </div>
  );
}
Notes • Adjust the agent identity detection (/agent|avatar/i) to match your LiveAvatar identity scheme. • If you prefer to render a specific publication, use participant.getTrack(Track.Source.Camera) from
livekit-client
and pass the publication to
VideoTrack
. • Protect
/api/end-session
on the backend so only authorized users can delete rooms. Would you like the variant that selects camera publication explicitly (with
Track
imports) or an example without @livekit/components-react using raw hooks?
i
Type '{ participant: Participant; style: { width: string; height: string; objectFit: "cover"; }; }' is not assignable to type 'IntrinsicAttributes & VideoTrackProps & RefAttributes<HTMLVideoElement>'. Property 'participant' does not exist on type 'IntrinsicAttributes & VideoTrackProps & RefAttributes<HTMLVideoElement>'.ts(2322)
t
You're seeing that error because
VideoTrack
expects a
trackRef
(a TrackReference) or a
publication/track
, not a
Participant
. Use
useTracks
(or get the participant's camera publication) to produce a TrackReference and pass it as
trackRef
. Minimal TypeScript React example (local user + LiveAvatar agent, Exit button, backend call):
Copy code
import React, { useEffect } from 'react';
import { Participant, Track } from 'livekit-client';
import {
  LiveKitRoom,
  RoomAudioRenderer,
  useParticipants,
  useTracks,
  VideoTrack,
} from '@livekit/components-react';
import '@livekit/components-styles';

type VideoRoomProps = {
  serverUrl: string;
  token: string;
  roomName: string;
  onEnded?: () => void;
};

export default function VideoRoom({ serverUrl, token, roomName, onEnded }: VideoRoomProps) {
  return (
    <LiveKitRoom
      serverUrl={serverUrl}
      token={token}
      connect={true}
      audio={true}
      video={true}
      style={{ height: '70vh', width: '70vw', background: '#000' }}
    >
      <RoomUI roomName={roomName} onEnded={onEnded} />
      <RoomAudioRenderer />
    </LiveKitRoom>
  );
}

function RoomUI({ roomName, onEnded }: { roomName: string; onEnded?: () => void }) {
  const participants = useParticipants();

  const local = participants.find(p => p.isLocal) as Participant | undefined;
  const agent = participants.find(p => /agent|avatar/i.test(p.identity)) as Participant | undefined;

  // Get camera track refs for local and agent (onlySubscribed: false so it works immediately)
  const localTracks = useTracks([{ participant: local, source: Track.Source.Camera }], { onlySubscribed: false });
  const agentTracks = useTracks([{ participant: agent, source: Track.Source.Camera }], { onlySubscribed: false });

  const localVideo = localTracks[0]; // TrackReference | undefined
  const agentVideo = agentTracks[0];

  async function handleExit() {
    try {
      // optional: stop local tracks locally
      local?.getTracks().forEach(t => t.stop?.());
      await fetch('/api/end-session', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ room: roomName }),
      });
    } catch (err) {
      console.error('end-session error', err);
    } finally {
      if (onEnded) onEnded();
      else window.location.href = '/';
    }
  }

  useEffect(() => {
    const onUnload = () => {
      try {
        navigator.sendBeacon('/api/end-session', JSON.stringify({ room: roomName }));
      } catch {}
    };
    window.addEventListener('beforeunload', onUnload);
    return () => window.removeEventListener('beforeunload', onUnload);
  }, [roomName]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ display: 'flex', gap: 12, flex: 1 }}>
        <ParticipantPanel title="You" trackRef={localVideo} placeholder="Your camera off" />
        <ParticipantPanel title="AI Agent" trackRef={agentVideo} placeholder="Agent connecting..." />
      </div>

      <div style={{ marginTop: 8 }}>
        <button onClick={handleExit} style={{ padding: '8px 12px' }}>Exit</button>
      </div>
    </div>
  );
}

function ParticipantPanel({ title, trackRef, placeholder = 'No video' }: { title: string; trackRef?: any; placeholder?: string }) {
  return (
    <div style={{ flex: 1, position: 'relative', background: '#111', borderRadius: 8, overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 8, left: 8, color: '#fff', zIndex: 5 }}>{title}</div>
      <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {trackRef ? (
          <VideoTrack trackRef={trackRef} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
        ) : (
          <div style={{ color: '#ddd', textAlign: 'center', padding: 16 }}>{placeholder}</div>
        )}
      </div>
    </div>
  );
}
Notes: • Use
useTracks
to get a TrackReference and pass it as
trackRef
to
VideoTrack
. •
onlySubscribed: false
lets you get the publication even before subscription—adjust to your needs. • If you prefer to pull the publication directly, use
participant.getTrackPublication(Track.Source.Camera)
and convert to a TrackReference the component accepts. • Protect
/api/end-session
on the backend. Want a variant that explicitly finds the camera publication (without useTracks) or an example using raw livekit-client hooks? Sources: Handling events | LiveKit docs | Rooms, participants, and tracks | LiveKit docs
i
Object literal may only specify known properties, and 'participant' does not exist in type 'TrackSourceWithOptions'.
t
You're seeing that error because
useTracks
expects track source configs (not participant objects) and
VideoTrack
requires a
trackRef
(a TrackReference), not a
participant
. Below is a corrected, minimal TypeScript React component that: • uses
useParticipants()
to find local and agent participants • builds TrackReference objects from each participant's camera publication • passes those TrackReference(s) to
VideoTrack
• includes an Exit button that calls your backend to delete the room Drop-in file: VideoRoom.tsx
Copy code
import React, { useEffect } from 'react';
import { Participant, Track } from 'livekit-client';
import {
  LiveKitRoom,
  RoomAudioRenderer,
  useParticipants,
  useTracks,
  VideoTrack,
  TrackReference,
} from '@livekit/components-react';
import '@livekit/components-styles';

type Props = {
  serverUrl: string;
  token: string;
  roomName: string;
  onEnded?: () => void;
};

export default function VideoRoom({ serverUrl, token, roomName, onEnded }: Props) {
  return (
    <LiveKitRoom
      serverUrl={serverUrl}
      token={token}
      connect={true}
      audio={true}
      video={true}
      style={{ height: '70vh', width: '70vw', background: '#000' }}
    >
      <RoomUI roomName={roomName} onEnded={onEnded} />
      <RoomAudioRenderer />
    </LiveKitRoom>
  );
}

function RoomUI({ roomName, onEnded }: { roomName: string; onEnded?: () => void }) {
  const participants = useParticipants();

  // find local and agent participants
  const local = participants.find(p => p.isLocal) as Participant | undefined;
  const agent = participants.find(p => /agent|avatar/i.test(p.identity)) as Participant | undefined;

  // Use useTracks to get all camera TrackReferences (optional, not required here)
  // const cameraRefs = useTracks([{ source: Track.Source.Camera }], { onlySubscribed: false });

  // Build TrackReference for a participant's camera publication (if present)
  const makeTrackRef = (p?: Participant): TrackReference | undefined => {
    if (!p) return undefined;
    const pub = p.getTrackPublication(Track.Source.Camera);
    if (!pub) return undefined;
    // TrackReference shape the VideoTrack expects: { participant, publication, source }
    return { participant: p, publication: pub, source: Track.Source.Camera } as TrackReference;
  };

  const localTrackRef = makeTrackRef(local);
  const agentTrackRef = makeTrackRef(agent);

  async function handleExit() {
    try {
      // stop local tracks locally
      local?.getTracks().forEach(t => t.stop?.());
      await fetch('/api/end-session', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ room: roomName }),
      });
    } catch (err) {
      console.error('end-session error', err);
    } finally {
      if (onEnded) onEnded();
      else window.location.href = '/';
    }
  }

  useEffect(() => {
    const onUnload = () => {
      try {
        navigator.sendBeacon('/api/end-session', JSON.stringify({ room: roomName }));
      } catch {}
    };
    window.addEventListener('beforeunload', onUnload);
    return () => window.removeEventListener('beforeunload', onUnload);
  }, [roomName]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
      <div style={{ display: 'flex', gap: 12, flex: 1 }}>
        <ParticipantPanel title="You" trackRef={localTrackRef} placeholder="Your camera off" />
        <ParticipantPanel title="AI Agent" trackRef={agentTrackRef} placeholder="Agent connecting..." />
      </div>

      <div style={{ marginTop: 8 }}>
        <button onClick={handleExit} style={{ padding: '8px 12px' }}>Exit</button>
      </div>
    </div>
  );
}

function ParticipantPanel({ title, trackRef, placeholder = 'No video' }: { title: string; trackRef?: TrackReference; placeholder?: string }) {
  return (
    <div style={{ flex: 1, position: 'relative', background: '#111', borderRadius: 8, overflow: 'hidden' }}>
      <div style={{ position: 'absolute', top: 8, left: 8, color: '#fff', zIndex: 5 }}>{title}</div>
      <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {trackRef ? (
          <VideoTrack trackRef={trackRef} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
        ) : (
          <div style={{ color: '#ddd', textAlign: 'center', padding: 16 }}>{placeholder}</div>
        )}
      </div>
    </div>
  );
}
Notes • The key fix: create a TrackReference from the participant's camera publication and pass it as
trackRef
to
VideoTrack
. Passing a raw
Participant
causes the TypeScript error. • If
getTrackPublication(Track.Source.Camera)
returns undefined (participant not publishing camera), show placeholder or use
useTracks([{ source: Track.Source.Camera }])
to find available camera tracks. • Adjust the agent identity detection regex to match your environment. • Keep
/api/end-session
protected and running on your backend to call LiveKit's RoomServiceClient.deleteRoom. If you want, I can: • provide a variant that uses
useTracks
to list all camera tracks and maps them to panels, or • convert this into a version without
@livekit/components-react
using raw livekit-client hooks. Which would you prefer? Sources: Subscribing to tracks | LiveKit docs | Handling events | LiveKit docs | Expo quickstart | LiveKit docs | Virtual avatar plugins | LiveKit Docs