Hey everyone :wave: I’m building an AI Interview ...
# ask-ai
s
Hey everyone 👋 I’m building an AI Interview platform using Next.js + @livekit/components-react. The setup: • Candidate joins the room • AI Interviewer joins • But an extra agent participant (system one) also joins automatically 🟠 Questions: 1. How can I hide that extra agent participant from the UI (GridLayout / ParticipantTile)? 2. Also, is there any way to get live transcription (real-time) directly via LiveKit listeners or events, without third-party APIs? Thanks in advance 🙏
t
Thanks for reaching out, Vishal. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thank you for reaching out! Let me help you with your questions: 1. Hiding the extra agent participant: You can easily hide a participant in the UI by setting their
hidden
property to
true
using the LiveKit RoomService API. This way, the participant won’t show up in components like
GridLayout
or
ParticipantTile
. Here’s a simple snippet to update the participant’s permissions:
Copy code
await roomService.updateParticipant(roomName, identity, {
  hidden: true,
});
Once you apply this, the participant will be hidden from everyone else in the room’s UI. 1. Real-time transcription: LiveKit offers support for live transcription through event listeners. You can tap into the
SpeechEvent
type with events such as
INTERIM_TRANSCRIPT
and
FINAL_TRANSCRIPT
to get real-time updates. These events are accessible via the
AgentSession
and can be forwarded under the topic
lk.transcription
. This lets you display transcriptions live, without needing any third-party APIs. Please don’t hesitate to ask if you’d like me to walk you through implementing these features or if you need any more details. I’m here to help! Sources: LiveKit Server Components | livekit/livekit_composite | DeepWiki | agent-console/app/_components/participant-action-panel.tsx | livekit-plugins/livekit-plugins-fal/livekit/plugins/fal/stt.py | Text and transcriptions | LiveKit Docs | Agents v0.x migration guide - Node.js | LiveKit Docs
s
help me with the change in code.. page.tsx=------>>>>>>>>> 'use client'; import { ControlBar, RoomAudioRenderer, RoomContext, } from '@livekit/components-react'; import { Room } from 'livekit-client'; import '@livekit/components-styles'; import { useEffect, useState } from 'react'; import { VideoRoom } from "./components/VideoRoom"; import { api } from "../services/api"; interface MeetingResponse { token: string; meetingUrl: string; candidateId: string; aiIdentity?: string; } export default function CandidateInterviewPage() { const [room] = useState(() => new Room({ adaptiveStream: true, dynacast: true })); const [loading, setLoading] = useState(true); const [meetingData, setMeetingData] = useState<MeetingResponse | null>(null); useEffect(() => { let mounted = true; (async () => { try { const data = await api.post('/meetings/details', { id: 'h4Mt3W%2FCsBbFPgfhN2YoCfIoPVMh9sI6545d31mXcmRYw2ZduvXpXe%2FlD7jUgfNX%2FiPMJExW72P67VZ8ariKK4%2BpVTpL7qpU', type: 'P' }); if (!mounted) return; data.meetingUrl = "wss://jobtwine-lv95xkul.livekit.cloud"; data.token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoic2FjaGluIiwidmlkZW8iOnsicm9vbUpvaW4iOnRydWUsInJvb20iOiJpbnRlcnZpZXctMWJlOGJjNDItNGVhYi00YWFmLTgxZTAtMzllNWU5M2E2NjZjLTE3NjAxNTYzNzciLCJjYW5QdWJsaXNoIjp0cnVlLCJjYW5TdWJzY3JpYmUiOnRydWUsImNhblB1Ymxpc2hEYXRhIjp0cnVlfSwic3ViIjoiY2FuZGlkYXRlLTFiZThiYzQyLTRlYWItNGFhZi04MWUwLTM5ZTVlOTNhNjY2Yy0wM2RmZWI2YSIsImlzcyI6IkFQSTJTeG9EVDI0RzJ0NiIsIm5iZiI6MTc2MDE1NjM3NywiZXhwIjoxNzYwMTY3MTc3fQ.zhgbM2f_fYDoXt0fWyQLR-YlDAU1VZHXmkFW3DqbXsg"; setMeetingData(data); await room.connect(data.meetingUrl, data.token); await room.localParticipant.enableCameraAndMicrophone(); } catch (e) { console.error('Error connecting to LiveKit:', e); } finally { if (mounted) setLoading(false); } })(); return () => { mounted = false; room.disconnect(); }; }, [room]); if (loading) return <div className="text-center p-8">Preparing your interview...</div>; if (!meetingData) return <div className="text-center text-red-600">Failed to start interview.</div>; return ( <RoomContext.Provider value={room}> <div data-lk-theme="default" className="h-screen bg-gray-100"> <VideoRoom room={room} /> <RoomAudioRenderer /> <ControlBar /> </div> </RoomContext.Provider> ); } VideoRoom in compoennets ---->>>>>> 'use client'; import { useEffect, useRef } from 'react'; import { GridLayout, ParticipantTile, useTracks } from '@livekit/components-react'; import { Track, RoomEvent } from 'livekit-client'; import '@livekit/components-styles'; export function VideoRoom({ room }: { room: any }) { const tracks = useTracks( [ { source: Track.Source.Camera, withPlaceholder: true }, { source: Track.Source.ScreenShare, withPlaceholder: false }, ], { onlySubscribed: false } ); // Active speaker highlighting useEffect(() => { const onActiveSpeakerChange = (speakers: any[]) => { const active = speakers[0]; if (active) { const el = document.querySelector(
[data-participant-id="${active.sid}"]
); if (el) { el.classList.add('ring-4', 'ring-blue-500'); setTimeout(() => el.classList.remove('ring-4', 'ring-blue-500'), 1000); } } }; room.on(RoomEvent.ActiveSpeakersChanged, onActiveSpeakerChange); return () => { room.off(RoomEvent.ActiveSpeakersChanged, onActiveSpeakerChange); }; }, [room]); return ( <GridLayout tracks={tracks} style={{ height: 'calc(100vh - var(--lk-control-bar-height))', }} > <ParticipantTile /> </GridLayout> ); } api.ts in services // /services/api.ts export class ApiService { private baseUrl: string; private token: string | null = null; constructor(baseUrl: string) { this.baseUrl = baseUrl; // ✅ Auto-read token from URL query param if available if (typeof window !== "undefined") { const urlParams = new URLSearchParams(window.location.search); const tokenFromQuery = urlParams.get("authToken"); // e.g. ?authToken=xyz if (tokenFromQuery) { this.setToken(tokenFromQuery); } } } setToken(token: string) { this.token = token; } private getHeaders(isFormData = false): HeadersInit { const headers: HeadersInit = {}; if (!isFormData) headers["Content-Type"] = "application/json"; if (this.token) headers["Authorization"] = `Bearer ${this.token}`; return headers; } async post(endpoint: string, data?: any, isFormData = false) { const res = await fetch(
${this.baseUrl}${endpoint}
, { method: "POST", headers: this.getHeaders(isFormData), body: isFormData ? data : JSON.stringify(data), }); if (!res.ok) { const err = await res.text(); throw new Error(
API Error: ${res.status} ${err}
); } return res.json(); } async get(endpoint: string) { const res = await fetch(
${this.baseUrl}${endpoint}
, { method: "GET", headers: this.getHeaders(), }); if (!res.ok) { const err = await res.text(); throw new Error(
API Error: ${res.status} ${err}
); } return res.json(); } } // ✅ Initialize with your backend base URL export const api = new ApiService( process.env.NEXT_PUBLIC_BACKEND_API_BASE || "https://api.jobtwine.com" ); these are code which we had done so far
t
To help you hide the extra agent participant in your current setup, you’ll want to update the participant's permissions by setting the
hidden
property to
true
. Don’t worry, I’ll guide you through the steps to modify your code: 1. Update Participant Permissions: Add this code snippet to set the
hidden
property for the extra agent participant:
Copy code
import { RoomServiceClient } from 'livekit-server-sdk';

const roomService = new RoomServiceClient('your-api-key', 'your-api-secret');

async function hideAgentParticipant(roomName, agentIdentity) {
  try {
    await roomService.updateParticipant(roomName, agentIdentity, {
      hidden: true,
    });
    console.log('Agent participant hidden successfully');
  } catch (error) {
    console.error('Error hiding agent participant:', error);
  }
}

// Call this function after the room is created
hideAgentParticipant('your-room-name', 'agent-identity');
Just be sure to replace
'your-api-key'
,
'your-api-secret'
,
'your-room-name'
, and
'agent-identity'
with the values that match your setup. 1. Modify the
VideoRoom
Component:
Make sure the
GridLayout
or
ParticipantTile
components automatically exclude participants with the
hidden
property set to
true
. Luckily, LiveKit’s server-side logic takes care of this, so you won’t need to add any extra filtering on the client side. If anything feels unclear or you’d like a hand implementing this, please don’t hesitate to reach out. I’m here to help!
s
in which file i can add this ? give me full code
t
I'd be happy to guide you through adding the code to hide the extra agent participant! You can place this in a server-side file or a utility file where you manage room creation and participant updates. Here's a complete example to help you out: 1. Create a Utility File: First, add a new file, like
roomServiceUtils.ts
, in your project. This will be where we handle the participant update logic.
Copy code
// /utils/roomServiceUtils.ts
import { RoomServiceClient } from 'livekit-server-sdk';

// Initialize RoomServiceClient with your API key and secret
const roomService = new RoomServiceClient('your-api-key', 'your-api-secret');

/**
 * Hide a participant in the room by setting the hidden property to true.
 * @param roomName - The name of the room
 * @param participantIdentity - The identity of the participant to hide
 */
export async function hideAgentParticipant(roomName: string, participantIdentity: string) {
  try {
    await roomService.updateParticipant(roomName, participantIdentity, {
      hidden: true,
    });
    console.log('Agent participant hidden successfully');
  } catch (error) {
    console.error('Error hiding agent participant:', error);
  }
}
1. Call the Function: Next, in your
CandidateInterviewPage
component or wherever you manage room setup, you can call the
hideAgentParticipant
function right after the room is created. Here's an example:
Copy code
import { hideAgentParticipant } from '../utils/roomServiceUtils';

useEffect(() => {
  (async () => {
    try {
      // Connect to the room
      await room.connect(data.meetingUrl, data.token);
      await room.localParticipant.enableCameraAndMicrophone();

      // Hide the extra agent participant
      await hideAgentParticipant('your-room-name', 'agent-identity');
    } catch (e) {
      console.error('Error connecting to LiveKit:', e);
    }
  })();
}, [room]);
Just be sure to replace
'your-api-key'
,
'your-api-secret'
,
'your-room-name'
, and
'agent-identity'
with the correct details for your setup. If you have any questions or need further clarification, please don’t hesitate to ask. I’m here to help!
h
No overload matches this call. Overload 1 of 2, '(room: string, identity: string, options: UpdateParticipantOptions): Promise<ParticipantInfo>', gave the following error. Object literal may only specify known properties, and 'hidden' does not exist in type 'UpdateParticipantOptions'. Overload 2 of 2, '(room: string, identity: string, metadata?: string | undefined, permission?: Partial<ParticipantPermission> | undefined, name?: string | undefined): Promise<...>', gave the following error. Argument of type '{ hidden: boolean; }' is not assignable to parameter of type 'string'.ts(2769) (method) RoomServiceClient.updateParticipant(room: string, identity: string, options: UpdateParticipantOptions): Promise<ParticipantInfo> (+1 overload)
t
It looks like the error is happening because the
hidden
property needs to be set inside the
permission
object when you use the
updateParticipant
method. No worries, here’s the corrected code for you:
Copy code
import { RoomServiceClient } from 'livekit-server-sdk';

const roomService = new RoomServiceClient('your-api-key', 'your-api-secret');

async function hideAgentParticipant(roomName, participantIdentity) {
  try {
    await roomService.updateParticipant(roomName, participantIdentity, {
      permission: { hidden: true },
    });
    console.log('Agent participant hidden successfully');
  } catch (error) {
    console.error('Error hiding agent participant:', error);
  }
}

// Call this function after the room is created
hideAgentParticipant('your-room-name', 'agent-identity');
Just be sure to replace
'your-api-key'
,
'your-api-secret'
,
'your-room-name'
, and
'agent-identity'
with the details that match your setup. If you have any more questions or need a hand with anything else, feel free to ask—I’m here to help! Sources: Managing participants | LiveKit Docs | LiveKit Server Components | livekit/livekit_composite | DeepWiki | agent-console/app/_components/participant-action-panel.tsx
s
give me code in context of my code which i had sent to you
t
Here is the updated code with the necessary changes integrated into your existing setup:
Copy code
`'use client';

import { ControlBar, RoomAudioRenderer, RoomContext } from '@livekit/components-react';
import { Room } from 'livekit-client';
import '@livekit/components-styles';
import { useEffect, useState } from 'react';
import { VideoRoom } from "./components/VideoRoom";
import { api } from "../services/api";
import { RoomServiceClient } from 'livekit-server-sdk';

// Initialize RoomServiceClient
const roomService = new RoomServiceClient('your-api-key', 'your-api-secret');

async function hideAgentParticipant(roomName, participantIdentity) {
  try {
    await roomService.updateParticipant(roomName, participantIdentity, {
      permission: { hidden: true },
    });
    console.log('Agent participant hidden successfully');
  } catch (error) {
    console.error('Error hiding agent participant:', error);
  }
}

interface MeetingResponse {
  token: string;
  meetingUrl: string;
  candidateId: string;
  aiIdentity?: string;
}

export default function CandidateInterviewPage() {
  const [room] = useState(() => new Room({ adaptiveStream: true, dynacast: true }));
  const [loading, setLoading] = useState(true);
  const [meetingData, setMeetingData] = useState(null);

  useEffect(() => {
    let mounted = true;

    (async () => {
      try {
        const data = await api.post('/meetings/details', {
          id: 'h4Mt3W%2FCsBbFPgfhN2YoCfIoPVMh9sI6545d31mXcmRYw2ZduvXpXe%2FlD7jUgfNX%2FiPMJExW72P67VZ8ariKK4%2BpVTpL7qpU',
          type: 'P' });
        if (!mounted) return;

        data.meetingUrl = "wss://jobtwine-lv95xkul.livekit.cloud";
        data.token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoic2FjaGluIiwidmlkZW8iOnsicm9vbUpvaW4iOnRydWUsInJvb20iOiJpbnRlcnZpZXctMWJlOGJjNDItNGVhYi00YWFmLTgxZTAtMzllNWU5M2E2NjZjLTE3NjAxNTYzNzciLCJjYW5QdWJsaXNoIjp0cnVlLCJjYW5TdWJzY3JpYmUiOnRydWUsImNhblB1Ymxpc2hEYXRhIjp0cnVlfSwic3ViIjoiY2FuZGlkYXRlLTFiZThiYzQyLTRlYWItNGFhZi04MWUwLTM5ZTVlOTNhNjY2Yy0wM2RmZWI2YSIsImlzcyI6IkFQSTJTeG9EVDI0RzJ0NiIsIm5iZiI6MTc2MDE1NjM3NywiZXhwIjoxNzYwMTY3MTc3fQ.zhgbM2f_fYDoXt0fWyQLR-YlDAU1VZHXmkFW3DqbXsg";
        setMeetingData(data);

        await room.connect(data.meetingUrl, data.token);
        await room.localParticipant.enableCameraAndMicrophone();

        // Hide the extra agent participant
        await hideAgentParticipant('your-room-name', 'agent-identity');
      } catch (e) {
        console.error('Error connecting to LiveKit:', e);
      } finally {
        if (mounted) setLoading(false);
      }
    })();

    return () => {
      mounted = false;
      room.disconnect();
    };
  }, [room]);

  if (loading) return Preparing your interview...;
  if (!meetingData) return Failed to start interview.;

  return (
    
  );
}`Just a quick reminder to replace `'your-api-key'`, `'your-api-secret'`, `'your-room-name'`, and `'agent-identity'` with the correct values for your setup. If anything feels unclear or if you'd like me to walk you through any part of this, please don't hesitate to ask. I'm here to help you every step of the way!
s
and give code of roomserviceutilts
t
Here is the complete code for the
roomServiceUtils.ts
file:
Copy code
// /utils/roomServiceUtils.ts
import { RoomServiceClient } from 'livekit-server-sdk';

// Initialize RoomServiceClient with your API key and secret
const roomService = new RoomServiceClient('your-api-key', 'your-api-secret');

/**
 * Hide a participant in the room by setting the hidden property to true.
 * @param roomName - The name of the room
 * @param participantIdentity - The identity of the participant to hide
 */
export async function hideAgentParticipant(roomName: string, participantIdentity: string) {
  try {
    await roomService.updateParticipant(roomName, participantIdentity, {
      permission: { hidden: true },
    });
    console.log('Agent participant hidden successfully');
  } catch (error) {
    console.error('Error hiding agent participant:', error);
  }
}

/**
 * Example usage:
 * hideAgentParticipant('your-room-name', 'agent-identity');
 */
Just a friendly reminder to replace
'your-api-key'
and
'your-api-secret'
with your actual LiveKit API credentials. This utility function is ready for you to import and use in your main code whenever you need to hide participants. If you have any questions or need a hand with anything else, please don’t hesitate to reach out. I’m here to help!
h
and what change in CandidateInterviewPage
t
In the
CandidateInterviewPage
, you’ll want to import and call the
hideAgentParticipant
function right after the room connects. I’ve updated the code for the
CandidateInterviewPage
to help guide you through this:
Copy code
`'use client';

import { ControlBar, RoomAudioRenderer, RoomContext } from '@livekit/components-react';
import { Room } from 'livekit-client';
import '@livekit/components-styles';
import { useEffect, useState } from 'react';
import { VideoRoom } from "./components/VideoRoom";
import { api } from "../services/api";
import { hideAgentParticipant } from '../utils/roomServiceUtils';

interface MeetingResponse {
  token: string;
  meetingUrl: string;
  candidateId: string;
  aiIdentity?: string;
}

export default function CandidateInterviewPage() {
  const [room] = useState(() => new Room({ adaptiveStream: true, dynacast: true }));
  const [loading, setLoading] = useState(true);
  const [meetingData, setMeetingData] = useState(null);

  useEffect(() => {
    let mounted = true;

    (async () => {
      try {
        const data = await api.post('/meetings/details', {
          id: 'h4Mt3W%2FCsBbFPgfhN2YoCfIoPVMh9sI6545d31mXcmRYw2ZduvXpXe%2FlD7jUgfNX%2FiPMJExW72P67VZ8ariKK4%2BpVTpL7qpU',
          type: 'P' });
        if (!mounted) return;

        data.meetingUrl = "wss://jobtwine-lv95xkul.livekit.cloud";
        data.token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoic2FjaGluIiwidmlkZW8iOnsicm9vbUpvaW4iOnRydWUsInJvb20iOiJpbnRlcnZpZXctMWJlOGJjNDItNGVhYi00YWFmLTgxZTAtMzllNWU5M2E2NjZjLTE3NjAxNTYzNzciLCJjYW5QdWJsaXNoIjp0cnVlLCJjYW5TdWJzY3JpYmUiOnRydWUsImNhblB1Ymxpc2hEYXRhIjp0cnVlfSwic3ViIjoiY2FuZGlkYXRlLTFiZThiYzQyLTRlYWItNGFhZi04MWUwLTM5ZTVlOTNhNjY2Yy0wM2RmZWI2YSIsImlzcyI6IkFQSTJTeG9EVDI0RzJ0NiIsIm5iZiI6MTc2MDE1NjM3NywiZXhwIjoxNzYwMTY3MTc3fQ.zhgbM2f_fYDoXt0fWyQLR-YlDAU1VZHXmkFW3DqbXsg";
        setMeetingData(data);

        await room.connect(data.meetingUrl, data.token);
        await room.localParticipant.enableCameraAndMicrophone();

        // Hide the extra agent participant
        await hideAgentParticipant('your-room-name', 'agent-identity');
      } catch (e) {
        console.error('Error connecting to LiveKit:', e);
      } finally {
        if (mounted) setLoading(false);
      }
    })();

    return () => {
      mounted = false;
      room.disconnect();
    };
  }, [room]);

  if (loading) return Preparing your interview...;
  if (!meetingData) return Failed to start interview.;

  return (
    
  );
}`Just make sure to replace `'your-room-name'` and `'agent-identity'` with the correct values for your setup. If you have any questions or want me to walk you through any part of this, please don’t hesitate to ask—I’m here to help!
h
how can I get to know the identity of agent like i don't get in any api from my backend. so can livekit send me from room object or anything
t
I'm happy to help you retrieve the identity of participants in a LiveKit room! Here are a couple of ways you can do this: 1. Client-Side: If you're using the LiveKit client SDK, you can easily access participant identities right from the
Room
object. For instance, in JavaScript, you can loop through the participants like this:
Copy code
room.participants.forEach((participant) => {
  console.log(participant.identity); // Logs the identity of each participant
});
This will give you the identities of everyone currently in the room, which is pretty straightforward! 1. Server-Side: If you prefer to get the identities from the server, you can use the
RoomService
API. Here's a simple example:
Copy code
import { RoomServiceClient } from 'livekit-server-sdk';

const roomService = new RoomServiceClient('your-api-key', 'your-api-secret');

async function getParticipants(roomName) {
  try {
    const participants = await roomService.listParticipants(roomName);
    participants.forEach((participant) => {
      console.log(participant.identity); // Logs the identity of each participant
    });
  } catch (error) {
    console.error('Error fetching participants:', error);
  }
}

getParticipants('your-room-name');
Just be sure to replace
'your-api-key'
,
'your-api-secret'
, and
'your-room-name'
with your actual LiveKit credentials and the room name you're working with. If you run into any issues or want me to walk you through the implementation, please don't hesitate to ask. I'm here to help! Sources: livekit-android-sdk/src/main/java/io/livekit/android/room/Room.kt | Sources/LiveKit/Participant/Participant.swift | livekit-api/livekit/api/room_service.py | Managing participants | LiveKit Docs | Rooms, participants, and tracks | LiveKit Docs
h
it says Error hiding agent participant: Error: api-key and api-secret must be set at new AccessToken (AccessToken.ts6713) at RoomServiceClient.authHeader (ServiceBase.ts2916) at RoomServiceClient.updateParticipant (RoomServiceClient.ts35418) at hideAgentParticipant (roomServiceUtils.ts1423) at CandidateInterviewPage.useEffect (page.tsx856)
t
It looks like the error is happening because the
api-key
and
api-secret
aren’t being set correctly in the
RoomServiceClient
. No worries, this is a common hiccup! Just double-check that you’ve replaced
'your-api-key'
and
'your-api-secret'
with the actual API key and secret you got from LiveKit. Here’s a simple way to get it sorted: 1. First, make sure you have the right API key and secret from your LiveKit dashboard. 2. Then, update how you initialize
RoomServiceClient
in your
roomServiceUtils.ts
file:
Copy code
import { RoomServiceClient } from 'livekit-server-sdk';

// Just swap these out with your actual API key and secret
const roomService = new RoomServiceClient('your-api-key', 'your-api-secret');
If you’re using environment variables to keep your API key and secret safe, double-check that they’re loading correctly like this:
Copy code
const roomService = new RoomServiceClient(
  process.env.LIVEKIT_API_KEY || '',
  process.env.LIVEKIT_API_SECRET || ''
);
Also, it’s a good idea to confirm that your environment variables are set up properly in your development or production setup. For example, in a
.env
file, it should look like this:
Copy code
LIVEKIT_API_KEY=your-api-key
LIVEKIT_API_SECRET=your-api-secret
If you run into any more bumps or want me to walk you through it step-by-step, just let me know—I’m here to help!
h
i am doing this // /utils/roomServiceUtils.ts import { RoomServiceClient } from 'livekit-server-sdk'; // Initialize RoomServiceClient with your API key and secret const roomService = new RoomServiceClient('API2SxoDT24G2t6', 'lS6Ohx41ZKX2zzmyfKtURl3xogdJGBaBlII9fNb38d0'); /** * Hide a participant in the room by setting the hidden property to true. * @average-fall-32270 roomName - The name of the room * @average-fall-32270 participantIdentity - The identity of the participant to hide */ export async function hideAgentParticipant(roomName: string, participantIdentity: string) { try { await roomService.updateParticipant(roomName, participantIdentity, { permission: { hidden: true }, }); console.log('Agent participant hidden successfully'); } catch (error) { console.error('Error hiding agent participant:', error); } } /** * Example usage: * hideAgentParticipant('your-room-name', 'agent-identity'); */
t
It looks like the API key and secret you're using in the
RoomServiceClient
initialization are correct, which is great! Sometimes, though, this error can happen if the server-side SDK is accidentally used in a client-side environment. Since the API key and secret are sensitive, we want to make sure they’re never exposed in the browser for security reasons. Here's a friendly way to fix this: 1. Double-check that the
RoomServiceClient
is only used on the server side — for example, inside an API route or a server-side function. 2. Try moving your
hideAgentParticipant
logic into a server-side API route. For instance, you can create a new API route in your Next.js project like this:
Copy code
// /pages/api/hideParticipant.ts
import { RoomServiceClient } from 'livekit-server-sdk';

const roomService = new RoomServiceClient('API2SxoDT24G2t6', 'lS6Ohx41ZKX2zzmyfKtURl3xogdJGBaBlII9fNb38d0');

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { roomName, participantIdentity } = req.body;

    try {
      await roomService.updateParticipant(roomName, participantIdentity, {
        permission: { hidden: true },
      });
      res.status(200).json({ message: 'Participant hidden successfully' });
    } catch (error) {
      console.error('Error hiding participant:', error);
      res.status(500).json({ error: 'Failed to hide participant' });
    }
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}
Then, you can call this API route from your client-side code like so:
Copy code
import axios from 'axios';

async function hideParticipant(roomName, participantIdentity) {
  try {
    const response = await axios.post('/api/hideParticipant', {
      roomName,
      participantIdentity,
    });
    console.log(response.data.message);
  } catch (error) {
    console.error('Error hiding participant:', error);
  }
}
This way, your API key and secret stay safe and sound on the server, away from the client side. If you’d like, I’m here to help you step through this or clarify anything else. Just let me know!
h
how to get the room name.. can I get from any event listener or variable or object of livekit
t
I'm happy to help you retrieve the room name in LiveKit! You have a couple of friendly options to do this using the
Room
object or event listeners: 1. Accessing Room Name from the Room Object: The
Room
object includes a
name
property that holds the room name. Here's a simple example:
Copy code
console.log(room.name); // Logs the room name
Just a heads-up, this property becomes available once the room is connected. 1. Retrieving Room Name via Event Listeners: Another great way is to listen for the
RoomConnectedEvent
. This lets you grab the room name right when the connection is established:
Copy code
room.on(RoomEvent.Connected, () => {
  console.log('Connected to room:', room.name);
});
Both approaches let you access the room name dynamically while your app is running. If you have any questions or want me to walk you through this further, just let me know—I’m here to help! Sources: controller/lib/components/controller.dart | sip-refer/README.mdoc | Operational Guidance & Best Practices | livekit/livekit_composite | DeepWik... | src/room/Room.ts | livekit-android-sdk/src/main/java/io/livekit/android/room/Room.kt
h
import { NextRequest, NextResponse } from 'next/server'; import { RoomServiceClient } from 'livekit-server-sdk'; const apiKey = process.env.LIVEKIT_API_KEY; const apiSecret = process.env.LIVEKIT_API_SECRET; const livekitUrl = process.env.NEXT_PUBLIC_LIVEKIT_URL; if (!apiKey || !apiSecret || !livekitUrl) { throw new Error("LIVEKIT_API_KEY, LIVEKIT_API_SECRET, or NEXT_PUBLIC_LIVEKIT_URL is missing"); } // Initialize RoomServiceClient (server-side only) const roomService = new RoomServiceClient(apiKey!, apiSecret!, livekitUrl!); export async function POST(req: NextRequest) { try { const body = await req.json(); const { roomName, participantIdentity } = body; if (!roomName || !participantIdentity) { return NextResponse.json({ error: "Missing roomName or participantIdentity" }, { status: 400 }); } const updatedParticipant = await roomService.updateParticipant(roomName, participantIdentity, { // Server-side SDK expects
metadata
or
permission
updates
permission: { hidden: true }, }); return NextResponse.json({ message: "Participant hidden successfully", updatedParticipant }); } catch (err: any) { console.error("Error hiding participant:", err); return NextResponse.json({ error: err.message || "Unknown error" }, { status: 500 }); } } it says invalid url
t
It looks like you're encountering the "invalid URL" error, which usually means the
livekitUrl
provided to the
RoomServiceClient
might not be formatted quite right or could be missing. Let’s walk through a few steps together to get this sorted out: 1. First, please double-check that your
NEXT_PUBLIC_LIVEKIT_URL
environment variable is set correctly. This should be the base URL of your LiveKit server, something like:
<LIVEKIT_SERVER_URL>
. 2. Make sure the URL includes the right protocol, either
https://
or
http://
. 3. It’s also a good idea to confirm that your environment variable is loading properly. You can do this by adding a quick log to see what’s being picked up:
Copy code
console.log('LiveKit URL:', process.env.NEXT_PUBLIC_LIVEKIT_URL);
If you notice the URL is missing or not quite right, simply update your
.env
file with the correct value like this:
Copy code
NEXT_PUBLIC_LIVEKIT_URL=<LIVEKIT_SERVER_URL>
Once you’ve made these updates, don’t forget to restart your development server so it picks up the changes. Please feel free to reach out if you have any questions or need a hand with any of these steps—I’m here to help!
h
it starts from wss
t
Hi there! Just a quick note about the `RoomServiceClient`: it needs the base URL of your LiveKit server, which should start with
http://
or
https://
, rather than
wss://
. The
wss://
protocol is actually meant for WebSocket connections, usually used by client-side SDKs to connect to the room. To help you fix this, here’s what you can do: 1. Double-check that your
NEXT_PUBLIC_LIVEKIT_URL
environment variable is set to the correct base URL of your LiveKit server. For example:
Copy code
NEXT_PUBLIC_LIVEKIT_URL=<LIVEKIT_SERVER_BASE_URL>
Just replace
<LIVEKIT_SERVER_BASE_URL>
with your actual LiveKit server’s base URL. 1. Then, update your
RoomServiceClient
initialization to use this URL like so:
Copy code
const roomService = new RoomServiceClient(apiKey!, apiSecret!, livekitUrl!);
If you only have the
wss://
URL handy, no worries! I recommend reaching out to your LiveKit server administrator to get the corresponding
http://
or
https://
base URL for the server API. Feel free to reach out if you have any more questions or need a hand with this. I’m here to help!
h
wss://kqjkjqkjne-235uhhl.livessskit.cloud what it should be i have set to this
t
Thank you for reaching out! The URL
wss://kqjkjqkjne-235uhhl.livessskit.cloud
is actually a WebSocket URL, which is used for client-side connections to LiveKit rooms. When working with the
RoomServiceClient
, you'll want to use the corresponding HTTP or HTTPS base URL for your LiveKit server. Usually, the server API base URL looks quite similar to the WebSocket URL but starts with
https://
or
http://
. So, you can try replacing
wss://
with
https://
, like this:
Copy code
NEXT_PUBLIC_LIVEKIT_URL=<LIVEKIT_SERVER_BASE_URL>
If that doesn’t quite do the trick, no worries! It’s a good idea to double-check with your LiveKit server administrator or hosting provider to make sure you have the correct base URL for the server API. Feel free to reach out if you have any more questions or need a hand with anything else—I’m here to help!
h
is there anything we can do instaed of useing LIVEKIT_SERVER_BASE_URL
t
The
RoomServiceClient
needs the base URL of your LiveKit server to connect and communicate with the server API. If you'd prefer not to use the
LIVEKIT_SERVER_BASE_URL
environment variable, no worries! You can simply pass the base URL as a string when you initialize the
RoomServiceClient
. Here's a quick example:
Copy code
const roomService = new RoomServiceClient('your-api-key', 'your-api-secret', '<LIVEKIT_SERVER_BASE_URL>');
Just make sure to replace
<LIVEKIT_SERVER_BASE_URL>
with the actual base URL of your LiveKit server. That said, I highly recommend using environment variables for this. It helps keep your API keys, secrets, and server URLs safe and your code clean—plus, it makes switching between environments like development, staging, and production much smoother. If anything’s unclear or you’d like me to walk you through it, please don’t hesitate to ask. I’m here to help!
h
no like .. can we skip server base url and use something e;se or any other way to hide participant
t
Absolutely! There are a few alternative ways to hide a participant without directly using the
RoomServiceClient
or exposing the server base URL in your client-side code. Let me walk you through them: 1. Use a Backend API: One friendly approach is to create a backend API route that takes care of the
updateParticipant
call using the
RoomServiceClient
. Your frontend can simply send a request to this API, and your backend will handle the interaction with LiveKit. For example:
Copy code
// Frontend request
await fetch('/api/hideParticipant', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ roomName: 'my-room', participantIdentity: 'user123' })
});
Then, your backend API will use the
RoomServiceClient
to hide the participant seamlessly. 1. Admin Tools or Dashboards: If you happen to have access to an admin tool or dashboard (like the realtime-room-monitor), you can easily toggle the "hidden" state of participants without needing to write any custom code. 2. Custom Proxy: Another option is setting up a proxy service that acts as a middleman for the LiveKit server API. This way, you can send requests without revealing the server base URL or API credentials on the client side. All of these approaches use the
UpdateParticipant
API with the
hidden
flag set to
true
, but they help keep your client-side code clean and secure by avoiding direct use of the
RoomServiceClient
. Please feel free to reach out if you'd like a hand with implementing any of these solutions — I’m here to help! Sources: livekit-api/src/services/room.rs | roomclient.go | packages/livekit-server-sdk/src/RoomServiceClient.ts | src/main/kotlin/io/livekit/server/RoomServiceClient.kt | lib/livekit/room_service_client.rb
h
any other way
t
I’m happy to help you with hiding a participant in LiveKit! Right now, the supported way to do this is by using the
UpdateParticipant
API and setting the
hidden
flag to
true
. This does require some server-side interaction, either through the
RoomServiceClient
or a custom backend API that handles the request for you. If you’d prefer to avoid server-side work altogether, there’s a handy client-side workaround you can try. You can filter out the participant directly in your UI. For example, inside your
VideoRoom
component, you could exclude the participant with a specific identity like this:
Copy code
const filteredTracks = tracks.filter(track => track.participant.identity !== 'agent-identity');
After that, just pass
filteredTracks
to your
GridLayout
component:
Copy code
<GridLayout tracks={filteredTracks} />
This won’t hide the participant on the server side, but it will make sure they don’t show up in your UI. Please feel free to let me know if this approach works for you or if you’d like me to help you explore other options. I’m here to support you!
h
Untitled
t
Hi there! It looks like your last message didn’t come through. No worries at all—could you please let me know if you still need any help or if the solution I shared worked for you? I’m here to support you every step of the way!
h
how to know who is rempte and who is local and then filter .. like tracks is array
t
In LiveKit, you can easily tell apart local and remote participants by looking at the
isLocal
property of the participant linked to each track. Here’s a friendly guide on how you can filter tracks depending on whether they belong to a local or remote participant: 1. Access the Participant: Each track in the
tracks
array includes a
participant
property that points to the participant who owns that track. 2. Check the
isLocal
Property:
By checking the
isLocal
property of the participant, you can find out if they’re the local participant:
Copy code
const remoteTracks = tracks.filter(track => !track.participant.isLocal);
This will give you a list of tracks that come from remote participants. 1. Pass the Filtered Tracks: You can then use these filtered tracks in your
GridLayout
or any other components you’re working with:
Copy code
<GridLayout tracks={remoteTracks} />
If you have any questions or need a hand with implementing this, please don’t hesitate to ask. I’m here to help! Sources: README.md
h
also i don't know agent id so i want to hide the one who has agent in the name
t
Hi there! If you'd like to hide participants whose identity includes "agent" in their name, you can easily filter the tracks based on that. Here's a simple way to do it: 1. Filter Tracks: You can use the
identity
property of each participant to check if it contains the word "agent":
Copy code
const filteredTracks = tracks.filter(track => !track.participant.identity.includes('agent'));
This will help you exclude any tracks from participants with "agent" in their identity. 1. Pass the Filtered Tracks: Then, just use these filtered tracks in your
GridLayout
or any other components you're working with:
Copy code
<GridLayout tracks={filteredTracks} />
If you have any questions or need a hand with this, please feel free to reach out. I'm here to help!
h
no hide those whose permission is agent : true
t
I'm happy to help you with hiding participants based on a specific permission like
agent: true
. You can achieve this by using the
metadata
property of the participant, which is a JSON string where you can store custom information such as permissions. Here’s a simple way to filter tracks based on the
agent
permission: 1. Parse the Metadata: First, access the
metadata
property of each participant and parse it as JSON:
Copy code
const filteredTracks = tracks.filter(track => {
  const metadata = JSON.parse(track.participant.metadata || '{}');
  return !metadata.agent; // This will exclude participants with agent: true
});
1. Pass the Filtered Tracks: Then, use these filtered tracks in your
GridLayout
or any other components you’re working with:
Copy code
<GridLayout tracks={filteredTracks} />
Just make sure that the
metadata
field is properly set when participants join the room. For example, you can add
{ "agent": true }
to the metadata for those participants who are agents. If you have any questions or need a hand with this, please don’t hesitate to ask. I’m here to help!
h
metadata is always "".. so what to do//like i can see in response { "_eventsCount": 18, "_maxListeners": 100, "audioLevel": 0, "isSpeaking": false, "_connectionQuality": "excellent", "log": { "name": "livekit-participant", "levels": { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3, "ERROR": 4, "SILENT": 5 } }, "loggerOptions": {}, "sid": "PA_Y7kqt3shNXy4", "identity": "candidate-93c7cab7-21cf-4d11-a5e3-0c40fd43c5b7-343e19a1", "name": "sachin", "metadata": "", "audioTrackPublications": {}, "videoTrackPublications": {}, "trackPublications": {}, "_kind": 0, "_attributes": {}, "pendingPublishing": {}, "pendingPublishPromises": {}, "participantTrackPermissions": [], "allParticipantsAllowedToSubscribe": true, "encryptionType": 0, "enabledPublishVideoCodecs": [ { "mime": "video/VP8", "fmtpLine": "" }, { "mime": "video/H264", "fmtpLine": "" }, { "mime": "video/VP9", "fmtpLine": "" }, { "mime": "video/AV1", "fmtpLine": "" }, { "mime": "video/H265", "fmtpLine": "" } ], "pendingAcks": {}, "pendingResponses": {}, "activeDeviceMap": {}, "pendingSignalRequests": {}, "rpcHandlers": {}, "audioContext": {}, "permissions": { "canSubscribe": true, "canPublish": true, "canPublishData": true, "hidden": false, "recorder": false, "canPublishSources": [], "canUpdateMetadata": false, "agent": false, "canSubscribeMetrics": false }, "participantInfo": { "sid": "PA_Y7kqt3shNXy4", "identity": "candidate-93c7cab7-21cf-4d11-a5e3-0c40fd43c5b7-343e19a1", "state": "ACTIVE", "tracks": [], "metadata": "", "joinedAt": "1760179481", "name": "sachin", "version": 2, "permission": { "canSubscribe": true, "canPublish": true, "canPublishData": true, "hidden": false, "recorder": false, "canPublishSources": [], "canUpdateMetadata": false, "agent": false, "canSubscribeMetrics": false }, "region": "omumbai1b", "isPublisher": false, "kind": "STANDARD", "attributes": {}, "disconnectReason": "UNKNOWN_REASON", "joinedAtMs": "1760179481515", "kindDetails": [] }, "signalConnectedFuture": { "_isResolved": true, "promise": {} } }
t
Thank you so much for providing the detailed response! Since the
metadata
field is empty, a great way to move forward is by using the
permissions
object to directly check for the
agent
property. Here’s a simple way you can filter tracks based on the
agent
permission:
Copy code
const filteredTracks = tracks.filter(track => {
  return !track.participant.permissions.agent; // Exclude participants with agent: true
});
After that, you can pass these filtered tracks to your
GridLayout
like this:
Copy code
<GridLayout tracks={filteredTracks} />
This method leverages the
permissions
object, which includes the
agent
property, to help you easily identify and exclude participants who have
agent: true
. If you’d like, I’m here to help you with any part of this implementation—just let me know!
h
when i filter out then automatically pqrticipants gets disconnected and all... so can i set hidden true by anyywhere
t
To set the
hidden
property to
true
for a participant, it’s best to do this server-side using the
updateParticipant
method of the
RoomServiceClient
. This is currently the only supported way to programmatically set the
hidden
flag in LiveKit. If you want to prevent participants from being disconnected or avoid other issues when filtering, a great approach is to create a backend API route to handle this. Here’s an example you might find helpful:
Copy code
// /pages/api/hideParticipant.ts
import { RoomServiceClient } from 'livekit-server-sdk';

const roomService = new RoomServiceClient('your-api-key', 'your-api-secret');

export default async function handler(req, res) {
  if (req.method === 'POST') {
    const { roomName, participantIdentity } = req.body;

    try {
      await roomService.updateParticipant(roomName, participantIdentity, {
        permission: { hidden: true },
      });
      res.status(200).json({ message: 'Participant hidden successfully' });
    } catch (error) {
      console.error('Error hiding participant:', error);
      res.status(500).json({ error: 'Failed to hide participant' });
    }
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}
After setting this up, you can call this API route from your client-side code to set the
hidden
flag for the participant without needing to use the
RoomServiceClient
directly in the frontend. Please feel free to reach out if you’d like any more help with implementing this—I’m here to support you!
h
i want that any paricipant who has either bey-avatar-agent as agentidentity or the particiant is local.. if anoene of this true then show them or else not i want tile to hide only from ui .. but it should remain in the meet.. so make it like behind any tile..
t
To help you hide tiles from the UI while still keeping all participants in the meeting, you can filter the tracks based on your conditions and include the hidden participants in the layout, just rendered so they aren’t visible. Here’s a friendly step-by-step on how you can do this: 1. Filter Tracks: First, filter the tracks to include only those participants who meet your conditions:
Copy code
const filteredTracks = tracks.map(track => {
  const isAgent = track.participant.identity.includes('bey-avatar-agent');
  const isLocal = track.participant.isLocal;

  return {
    ...track,
    hidden: !(isAgent || isLocal), // Mark as hidden if neither condition is true
  };
});
1. Render Tiles: Next, use the
hidden
property to control which tiles are visible:
Copy code
<GridLayout tracks={filteredTracks} style={{ height: '100%' }}>
  {filteredTracks.map(track => (
    <ParticipantTile
      key={track.participant.sid}
      track={track}
      style={{ display: track.hidden ? 'none' : 'block' }}
    />
  ))}
</GridLayout>
This way, participants who don’t meet your conditions won’t show up in the UI, but they’ll still be part of the meeting behind the scenes. If you’d like me to walk you through any part of this or if you have any questions, please don’t hesitate to ask—I’m here to help!
h
## Error Type Runtime Error ## Error Message React.Children.only expected to receive a single React element child. at Object.only (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_5150ccfd._.js143350) at <unknown> (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_%40livekit_components-react_dist_9a9e95ca._.js4131546) at <unknown> (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_5150ccfd._.js121425) at mapIntoArray (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_5150ccfd._.js119224) at mapIntoArray (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_5150ccfd._.js1201166) at Object.mapChildren [as map] (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_5150ccfd._.js12139) at H (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_%40livekit_components-react_dist_9a9e95ca._.js4131182) at <unknown> (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_%40livekit_components-react_dist_9a9e95ca._.js6979198) at Array.map (<anonymous>nullnull) at Ie (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_%40livekit_components-react_dist_9a9e95ca._.js6976382) at Object.react_stack_bottom_frame (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js1307224) at renderWithHooks (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js409124) at updateFunctionComponent (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js552321) at beginWork (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js611124) at runWithFiberInDEV (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js88674) at performUnitOfWork (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js829897) at workLoopSync (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js819040) at renderRootSync (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js817313) at performWorkOnRoot (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js793256) at performSyncWorkOnRoot (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js88909) at flushSyncWorkAcrossRoots_impl (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js8809316) at flushSpawnedWork (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js858613) at commitRoot (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js844713) at commitRootWhenReady (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js80059) at performWorkOnRoot (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js798325) at performWorkOnRootViaSchedulerTask (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js88829) at MessagePort.performWorkUntilDeadline (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_5150ccfd._.js260164) at va (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_%40livekit_components-react_dist_9a9e95ca._.js7037198) at VideoRoom (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/src_9bf0efc7._.js72214) at CandidateInterviewPage (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/src_9bf0efc7._.js304219) at ClientPageRoot (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_8db7fb1f._.js264550) Next.js version: 15.5.4 (Turbopack)
t
It looks like you're encountering the error "React.Children.only expected to receive a single React element child," which usually happens when a React component expects just one child element but ends up getting multiple or none. This might be connected to how the
GridLayout
or
ParticipantTile
components are being rendered in your code. Here’s a gentle nudge on how to fix it: 1. Make Sure There’s Only One Child: If you’re rendering multiple
ParticipantTile
components, try wrapping them inside a parent container. For example:
Copy code
<GridLayout tracks={filteredTracks} style={{ height: '100%' }}>
  {filteredTracks.map(track => (
    <div key={track.participant.sid} style={{ display: track.hidden ? 'none' : 'block' }}>
      <ParticipantTile track={track} />
    </div>
  ))}
</GridLayout>
1. Double Check How You’re Using `GridLayout`: If
GridLayout
expects only one child, make sure your
filteredTracks
array is mapped in a way that all tiles are inside a single parent container. 2. Take a Look at Your Data: It’s helpful to log the
filteredTracks
array to confirm it has the right data and that each track has a unique `sid`—this often clears up confusion:
Copy code
console.log(filteredTracks);
Please feel free to reach out if this doesn’t quite solve the problem or if you’d like me to walk you through the next steps. I’m here to help!
h
it worked .. iam using this code 'use client'; import { useEffect, useRef } from 'react'; import { GridLayout, ParticipantTile, useTracks } from '@livekit/components-react'; import { Track, RoomEvent } from 'livekit-client'; import '@livekit/components-styles'; import { ParticipantGrid } from './ParticipantGrid'; export function VideoRoom({ room }: { room: any }) { const tracks = useTracks( [ { source: Track.Source.Camera, withPlaceholder: true }, { source: Track.Source.ScreenShare, withPlaceholder: false }, ], { onlySubscribed: false } ); const filteredTracks = tracks.map(track => { const isAgent = track.participant.identity.includes('bey-avatar-agent'); const isLocal = track.participant.isLocal; return { ...track, hidden: !(isAgent || isLocal), // Mark as hidden if neither condition is true }; }); // Active speaker highlighting useEffect(() => { const onActiveSpeakerChange = (speakers: any[]) => { const active = speakers[0]; if (active) { const el = document.querySelector(
[data-participant-id="${active.sid}"]
); if (el) { el.classList.add('ring-4', 'ring-blue-500'); setTimeout(() => el.classList.remove('ring-4', 'ring-blue-500'), 1000); } } }; room.on(RoomEvent.ActiveSpeakersChanged, onActiveSpeakerChange); return () => { room.off(RoomEvent.ActiveSpeakersChanged, onActiveSpeakerChange); }; }, [room]); return ( <GridLayout tracks={filteredTracks} style={{ height: 'calc(100vh - var(--lk-control-bar-height))', }} > <ParticipantGrid tracks={filteredTracks} /> </GridLayout> ); } 'use client'; import { ParticipantTile } from '@livekit/components-react'; import { CSSProperties } from 'react'; interface ParticipantGridProps { tracks: any[]; } export function ParticipantGrid({ tracks }: ParticipantGridProps) { const hiddenStyle: CSSProperties = { position: 'absolute', left: '-10000px', visibility: 'hidden', width: '0', height: '0', pointerEvents: 'none', opacity: 0, zIndex: 0, }; // ✅ Filter only camera tracks (or whichever you want visible) const cameraTracks = tracks.filter( (t) => t.source === 'camera' || t.publication?.source === 'camera' ); return ( <> {cameraTracks.map((track) => { const isHidden = track.hidden; return isHidden ? ( <div key={track.participant.sid} style={hiddenStyle}> <ParticipantTile trackRef={track} /> </div> ) : ( <ParticipantTile key={track.participant.sid} trackRef={track} /> ); })} </> ); } but getting issue like why am i getting x3 times tiles.. like i have 2 remote 1 local.. to 2 remote me se 1 ko hide kie to 2 dikhna chaie (1 remote 1 local).. but nai mujhe 1 remote 1 local 3 baar dikh rahe h.. jo hude karm atha wo hide ho gaya h
t
I understand how seeing duplicate tiles (like 1 remote and 1 local participant appearing 3 times) can be a bit confusing. This usually happens because of how the tracks are being processed or rendered. Let’s walk through some steps together to help you debug and fix this: 1. Check the
tracks
Array:
Try logging the
tracks
array to see if there are any duplicate entries:
Copy code
console.log('Tracks:', tracks);
If you spot duplicates here, it might mean the
useTracks
hook is returning multiple entries for the same participant or track. It’s a good place to start! 1. Filter Unique Tracks: Make sure each participant or track is rendered just once. You can use a
Set
or some filter logic to remove any duplicates like this:
Copy code
const uniqueTracks = Array.from(new Map(tracks.map(track => [track.participant.sid, track])).values());
Then, swap out
tracks
with
uniqueTracks
in your rendering code. 1. Debug the Rendering Logic: It’s also worth checking that the
ParticipantGrid
component isn’t rendering the same track multiple times. Try logging the
cameraTracks
array:
Copy code
console.log('Camera Tracks:', cameraTracks);
If duplicates show up here, you might want to revisit the filtering logic inside
ParticipantGrid
. 1. Check the
hidden
Logic:
Lastly, make sure the
hidden
property is applied correctly so it doesn’t cause duplicates. For example:
Copy code
const filteredTracks = tracks.map(track => {
  const isAgent = track.participant.identity.includes('bey-avatar-agent');
  const isLocal = track.participant.isLocal;

  return {
    ...track,
    hidden: !(isAgent || isLocal),
  };
});
Please give these steps a try, and feel free to reach out if you need any more help or if something isn’t clear. I’m here to support you through this!
h
all are camera tracks only and showing 3 in length of tracks
t
I understand how it can be a bit confusing when the
tracks
array has a length of 3, but you’re expecting just 2 (1 local and 1 remote). This usually means duplicate tracks might be sneaking in, possibly because the same participant has multiple camera tracks published. Let’s work through this together: 1. Filter by Track Source: To make sure you only include one camera track per participant, you can filter using
publication.source
or
track.source
. Here’s a snippet that might help:
Copy code
const uniqueCameraTracks = Array.from(
  new Map(
    tracks
      .filter(track => track.source === 'camera' || track.publication?.source === 'camera')
      .map(track => [track.participant.sid, track])
  ).values()
);
This way, you’ll be confident that only one camera track per participant is included. 1. Log Track Details: It’s also helpful to log each track’s details to spot any duplicates easily:
Copy code
tracks.forEach(track => {
  console.log('Participant:', track.participant.identity, 'Source:', track.source);
});
Take a look here to see if the same participant is publishing multiple camera tracks. 1. Debug the
useTracks
Hook:
Sometimes, the
useTracks
hook might be returning duplicate tracks. Double-check its configuration and how your room is set up to make sure everything’s working smoothly. Please feel free to reach out if this helps or if you’d like me to walk you through any step in more detail. I’m here to help you get this sorted!
h
in controlbar how can i hide screenshre
t
To help you hide the screen share button in the
ControlBar
component, you can simply use the
controls
prop and set
screenShare
to
false
. Here’s a little example to guide you:
Copy code
<ControlBar
  controls={{
    microphone: true,
    camera: true,
    chat: true,
    screenShare: false, // Hides the screen share button
    leave: true,
    settings: true,
  }}
/>
This way, the screen share button will be hidden, while all your other buttons stay right where you want them. If you have any more questions or need a hand with anything else, please don’t hesitate to ask. I’m here to help! Sources: packages/react/CHANGELOG.md
h
## Error Type Runtime Error ## Error Message Tried to access LayoutContext context outside a LayoutContextProvider provider. at Ns (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_%40livekit_components-react_dist_e46577a5._.js395819) at Xt (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_%40livekit_components-react_dist_e46577a5._.js5146229) at <unknown> (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_%40livekit_components-react_dist_e46577a5._.js6032219) at Object.react_stack_bottom_frame (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js1307224) at renderWithHooks (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js409124) at updateForwardRef (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js534221) at beginWork (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js618624) at runWithFiberInDEV (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js88674) at performUnitOfWork (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js829897) at workLoopSync (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js819040) at renderRootSync (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js817313) at performWorkOnRoot (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js793256) at performSyncWorkOnRoot (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js88909) at flushSyncWorkAcrossRoots_impl (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js8809316) at flushSyncWork$1 (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js804886) at Object.scheduleRefresh (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_react-dom_1e674e59._.js29413) at <unknown> (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_5150ccfd._.js39133) at Set.forEach (<anonymous>nullnull) at Object.performReactRefresh (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_5150ccfd._.js38438) at applyUpdate (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_5150ccfd._.js87831) at <unknown> (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_compiled_5150ccfd._.js88613) at te (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_%40livekit_components-react_dist_e46577a5._.js8048258) at CandidateInterviewPage (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/src_a2ed7809._.js616223) at ClientPageRoot (<file//C&gt;/Users/SURABHI BISHWAS/Desktop/JobTwine/repositories/jt-ai-human-avatar/.next/static/chunks/node_modules_next_dist_8db7fb1f._.js264550) Next.js version: 15.5.4 (Turbopack)<RoomContext.Provider value={room}> <div data-lk-theme="default" className="h-screen flex bg-gray-100 overflow-y-auto"> {/* Left Side - Video Room */} <div className="flex-1 flex flex-col" style={{ background: "#353535" }}> <VideoRoom room={room} /> <RoomAudioRenderer /> </div> {/* Right Side - Transcript Component */} <Transcript transcripts={transcripts} /> </div> <ControlBar controls={{ microphone: true, camera: true, chat: true, screenShare: false, // Hides the screen share button leave: true, settings: true, }}/> </RoomContext.Provider>
t
It looks like you're encountering the error "Tried to access LayoutContext context outside a LayoutContextProvider provider," which happens when a component depending on the
LayoutContext
is rendered without being inside its required provider. This often relates to the
ControlBar
or other LiveKit components being used outside the necessary context. Here’s how we can work through this together: 1. Wrap Components in `LayoutContextProvider`: Make sure that the
ControlBar
and all other LiveKit components are wrapped inside the
LayoutContextProvider
. For example:
Copy code
import { LayoutContextProvider } from '@livekit/components-react';

<RoomContext.Provider value={room}>
  <LayoutContextProvider>
    <div data-lk-theme="default" className="h-screen flex bg-gray-100 overflow-y-auto">
      {/** Left Side - Video Room */}
      <div className="flex-1 flex flex-col" style={{ background: "#353535" }}>
        <VideoRoom room={room} />
        <RoomAudioRenderer />
      </div>

      {/** Right Side - Transcript Component */}
      <Transcript transcripts={transcripts} />
    </div>
    <ControlBar controls={{
      microphone: true,
      camera: true,
      chat: true,
      screenShare: false, // Hides the screen share button
      leave: true,
      settings: true,
    }} />
  </LayoutContextProvider>
</RoomContext.Provider>
1. Verify Component Placement: Double-check that all LiveKit components like
ControlBar
and
GridLayout
are indeed inside the appropriate context providers (
RoomContext.Provider
and
LayoutContextProvider
). 2. Check for Nested Providers: If you’re using multiple providers, it’s a good idea to ensure they are properly nested and not missing in any part of your component tree. Please feel free to reach out if this helps or if you’d like me to guide you further—I’m here to help!
h
I dont wan to use ControlBar.. i want to use button and click help me complete the changes 'use client'; import { ControlBar, RoomAudioRenderer, RoomContext, } from '@livekit/components-react'; import { Room } from 'livekit-client'; import '@livekit/components-styles'; import { useEffect, useState } from 'react'; import { VideoRoom } from './components/VideoRoom'; import { api } from '../services/api'; import { Transcript, TranscriptMessage } from './components/Transcript'; import Header from './components/Header'; import { TooltipContent, TooltipTrigger } from "@radix-ui/react-tooltip"; import { Button } from "@components/common/button"; import { Tooltip } from "@radix-ui/react-tooltip"; // import '@livekit/components-styles/dist/general/index.css'; import { useLocalParticipant, useTracks, // Track, // RoomEvent, useRoomContext } from "@livekit/components-react"; interface MeetingResponse { token: string; meetingUrl: string; candidateId: string; jobName: string; } export default function CandidateInterviewPage() { const [room] = useState(() => new Room({ adaptiveStream: true, dynacast: true })); const [loading, setLoading] = useState(true); const [meetingData, setMeetingData] = useState<MeetingResponse | null>(null); const [transcripts, setTranscripts] = useState<TranscriptMessage[]>([]); const livekitUrl = process.env.NEXT_PUBLIC_LIVEKIT_URL; const [showTranscript, setShowTranscript] = useState(true); useEffect(() => { let mounted = true; (async () => { try { const data = await api.post('/meetings/details', { id: 'h4Mt3W%2FCsBbFPgfhN2YoCfIoPVMh9sI6545d31mXcmRYw2ZduvXpXe%2FlD7jUgfNX%2FiPMJExW72P67VZ8ariKK4%2BpVTpL7qpU', type: 'P', }); if (!mounted) return; // Hardcoded token for now, replace with your API token data.token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoic2FjaGluIiwidmlkZW8iOnsicm9vbUpvaW4iOnRydWUsInJvb20iOiJpbnRlcnZpZXctY2ViZTliZDQtNmEyZi00NTdiLTk4MTMtZTg2Njg4MzZmNzNhLTE3NjAzNTQ4ODQiLCJjYW5QdWJsaXNoIjp0cnVlLCJjYW5TdWJzY3JpYmUiOnRydWUsImNhblB1Ymxpc2hEYXRhIjp0cnVlfSwic3ViIjoiY2FuZGlkYXRlLWNlYmU5YmQ0LTZhMmYtNDU3Yi05ODEzLWU4NjY4ODM2ZjczYS0wMzQ1Mjc3MiIsImlzcyI6IkFQSTkzeU5YOGhNRkNSRiIsIm5iZiI6MTc2MDM1NDg4NCwiZXhwIjoxNzYwMzY1Njg0fQ.cUV2cth274gu-zD88TkpXif5txYA43sEfZtNsntVuC8" setMeetingData(data); setTranscripts(prev => [ ...prev, { speaker: 'AI', text: 'Good afternoon! How has your day been so far?', isAI: true, }, { speaker: 'Candidate', text: 'Hello. How are you?', isAI: false, }, { speaker: 'AI', text: "I'm doing well, thank you! I'm glad to hear from you. I'm JayT, your AI interviewer, and I'll be conducting your interview for the Software Engineer role at JobTwine_Vikrant_Demo. Shall we get started?", isAI: true, }, { speaker: 'AI', text: 'I have not heard from you for a while. Is everything okay?', isAI: true, }, { speaker: 'Candidate', text: 'Yes. We can get started. And what have you shared?', isAI: false, }, { speaker: 'Candidate', text: 'I have shared my resume and a few projects. I am eager to learn more about the role and the company.', isAI: false, }, { speaker: 'AI', text: "To give you a quick overview, we'll start by getting to know you better and what brings you to this opportunity. Next, we'll have some experience-based questions, and finally, we'll discuss any questions you might have about the role, team, or company. Are you ready to begin? I haven't heard from you for a while. Are you there? Shall we continue the interview, or would you like to reschedule? I notice you've been quiet for a while. If this isn't a good time for our interview, we can certainly reschedule. Would you like to continue, or shall we end the meeting? Since I haven't heard from you for some time, I think we should end our meeting and reschedule for a better time. Thank you for your time today. I will end the interview now.", isAI: true, } ]); await room.connect(livekitUrl!, data.token); // await room.localParticipant.enableCameraAndMicrophone(); // Register transcription handler room.registerTextStreamHandler('lk.transcription', async (reader, participantInfo) => { const message = await reader.readAll(); const isHuman = !!reader.info?.attributes?.['lk.transcribed_track_id']; const speaker = isHuman ? 'You' : 'JayT'; setTranscripts(prev => { if (prev.length > 0 && prev[prev.length - 1].speaker === speaker) { // Append to the existing message instead of creating a new one const updatedMessages = [...prev]; updatedMessages[updatedMessages.length - 1] = { ...updatedMessages[updatedMessages.length - 1], text: updatedMessages[updatedMessages.length - 1].text + ' ' + message }; return updatedMessages; } else { // Create a new message if from a different sender return [...prev, { speaker, text: message, isAI: !isHuman }]; } }); }); } catch (e) { console.error('Error connecting to LiveKit:', e); } finally { if (mounted) setLoading(false); } })(); return () => { mounted = false; room.disconnect(); }; }, [room, livekitUrl]); if (loading) return <div className="text-center p-8">Preparing your interview...</div>; if (!meetingData) return <div className="text-center text-red-600">Failed to start interview.</div>; return ( <div className="h-screen flex flex-col w-screen"> <Header /> <div className="flex-1 flex flex-col"> <div className="flex justify-between items-center gap-2 bg-[#424242] py-3 px-4 text-white text-sm"> <div className="flex flex-col sm:flex-row items-start sm:items-center text-sm"> <span className="text-white mr-1 font-semibold whitespace-nowrap"> Discussion: </span> <span className="text-sm text-white break-words sm:break-normal !text-left"> {sessionStorage?.getItem("Candidate") || "Candidate"} for{" "} {meetingData?.jobName} </span> </div> {/* <div className="flex items-center bg-[#353535] rounded-full px-3 py-1 gap-2 text-sm"> <div className="flex items-center gap-1.5"> <div className="w-2 h-2 bg-red-500 rounded-full animate-pulse"></div> <span className="text-white">Rec</span> <span className="ml-1">|</span> </div> <div className="flex items-center gap-1"> <Clock className="h-4 w-4 text-gray-300" /> <span className="text-gray-300"> {formatTime(elapsedTime)} </span> </div> </div> */} </div> </div> <RoomContext.Provider value={room}> <div data-lk-theme="default" className="h-screen flex overflow-y-auto" style={{padding: '20px', background: 'rgb(53, 53, 53)', gap: '20px'}}> {/* Left Side - Video Room */} <div className="flex-1 flex flex-col" style={{ background: "#353535" }}> <VideoRoom room={room} /> <RoomAudioRenderer /> </div> {/* Right Side - Transcript Component */} <Transcript transcripts={transcripts} isOpen={showTranscript} setIsOpen={setShowTranscript} /> </div> <ControlBar className='bg-[#424242]' /> </RoomContext.Provider> <footer className="w-full flex justify-between py-3 px-4 shadow-[0_-4px_6px_-2px_rgba(0,0,0,0.1)] sticky bottom-0" style={{ background: "#424242" }}
<div className="flex items-center"> <img src="/images/jayT-footer.svg" alt="Left Logo" /> </div> <div className="flex flex-wrap items-center justify-center gap-3 w-full"> <Tooltip> <TooltipTrigger asChild> <Button className="!bg-[#353535] text-white border-none" size="icon" onClick={toggleMic} > {/* {micEnabled ? <Mic /> : <MicOff />} */} </Button> </TooltipTrigger> </Tooltip> <Tooltip> <TooltipTrigger asChild> <Button className="!bg-[#353535] text-white border-none" size="icon" onClick={toggleVideo} > {/* {videoEnabled ? <Video /> : <VideoOff />} */} </Button> </TooltipTrigger> </Tooltip> <Button jtEndButton={true} onClick={() => onLeave()}> <img className="p-3" src="/images/call-End.svg" alt="call" /> </Button> </div> <div className="flex items-center cursor-pointer" onClick={() => setShowTranscript(!showTranscript)} > <img src={ showTranscript ? "/images/transcript-on.svg" : "/images/transcript-off.svg" } alt="Transcript toggle" /> </div> </footer> </div> ); }
t
I'd love to help you replace the
ControlBar
with custom buttons for toggling the microphone, video, and other actions using the LiveKit SDK methods. Here's a friendly guide on how you can implement these changes: 1. Toggle Microphone: You can easily toggle the microphone using the
room.localParticipant.setMicrophoneEnabled
method like this:
Copy code
const toggleMic = () => {
  const isMicEnabled = room.localParticipant.isMicrophoneEnabled;
  room.localParticipant.setMicrophoneEnabled(!isMicEnabled);
};
1. Toggle Video: Similarly, to toggle the video, use the
room.localParticipant.setCameraEnabled
method:
Copy code
const toggleVideo = () => {
  const isVideoEnabled = room.localParticipant.isCameraEnabled;
  room.localParticipant.setCameraEnabled(!isVideoEnabled);
};
1. Leave Room: When you want to leave the room, simply call the
room.disconnect
method:
Copy code
const onLeave = () => {
  room.disconnect();
};
1. Custom Buttons: Now, you can replace the
ControlBar
with your own custom buttons like this:
Copy code
<footer
  className="w-full flex justify-between py-3 px-4 shadow-[0_-4px_6px_-2px_rgba(0,0,0,0.1)] sticky bottom-0"
  style={{ background: "#424242" }}
>
  <div className="flex items-center">
    <img src="/images/jayT-footer.svg" alt="Left Logo" />
  </div>

  <div className="flex flex-wrap items-center justify-center gap-3 w-full">
    <Tooltip>
      <TooltipTrigger asChild>
        <Button
          className="!bg-[#353535] text-white border-none"
          size="icon"
          onClick={toggleMic}
        >
          {room.localParticipant.isMicrophoneEnabled ? "Mic On" : "Mic Off"}
        </Button>
      </TooltipTrigger>
    </Tooltip>

    <Tooltip>
      <TooltipTrigger asChild>
        <Button
          className="!bg-[#353535] text-white border-none"
          size="icon"
          onClick={toggleVideo}
        >
          {room.localParticipant.isCameraEnabled ? "Video On" : "Video Off"}
        </Button>
      </TooltipTrigger>
    </Tooltip>

    <Button jtEndButton={true} onClick={onLeave}>
      <img className="p-3" src="/images/call-End.svg" alt="call" />
    </Button>
  </div>

  <div
    className="flex items-center cursor-pointer"
    onClick={() => setShowTranscript(!showTranscript)}
  >
    <img
      src={
        showTranscript
          ? "/images/transcript-on.svg"
          : "/images/transcript-off.svg"
      }
      alt="Transcript toggle"
    />
  </div>
</footer>
This way, you get full control to customize the footer exactly how you want it, while still keeping all the great functionality of the
ControlBar
. If you have any questions or want to explore more customizations, please feel free to reach out. I'm here to help!
h
'use client'; import { ControlBar, RoomAudioRenderer, RoomContext, } from '@livekit/components-react'; import { Room } from 'livekit-client'; import '@livekit/components-styles'; import { useEffect, useState } from 'react'; import { VideoRoom } from './components/VideoRoom'; import { api } from '../services/api'; import { Transcript, TranscriptMessage } from './components/Transcript'; import Header from './components/Header'; import { TooltipContent, TooltipTrigger } from "@radix-ui/react-tooltip"; import { Button } from "@components/common/button"; import { Tooltip } from "@radix-ui/react-tooltip"; import { TooltipProvider } from "@components/common/tooltip"; import { PhoneOff, Video, VideoOff, Mic, MicOff, Clock } from "lucide-react"; import { useSearchParams } from 'next/navigation'; interface MeetingResponse { authToken: string; meetingUrl: string; candidateId: string; jobName: string; } export default function CandidateInterviewPage() { const [room] = useState(() => new Room({ adaptiveStream: true, dynacast: true })); const [loading, setLoading] = useState(true); const [meetingData, setMeetingData] = useState<MeetingResponse | null>(null); const [transcripts, setTranscripts] = useState<TranscriptMessage[]>([]); const livekitUrl = process.env.NEXT_PUBLIC_LIVEKIT_URL; const [showTranscript, setShowTranscript] = useState(false); const [micEnabled, setMicEnabled] = useState(room.localParticipant.isMicrophoneEnabled); const [videoEnabled, setVideoEnabled] = useState(room.localParticipant.isCameraEnabled); const searchParams = useSearchParams(); const meetingId = searchParams.get('id'); const type = searchParams.get("type"); const authCode : string = searchParams.get("authCode") || ""; const [hasLeftRoom, setHasLeftRoom] = useState(false); const toggleMic = () => { const newState = !micEnabled; room.localParticipant.setMicrophoneEnabled(newState); setMicEnabled(newState); }; const toggleVideo = () => { const newState = !videoEnabled; room.localParticipant.setCameraEnabled(newState); setVideoEnabled(newState); }; const onLeave = () => { room.disconnect(); setHasLeftRoom(true); }; const handleClick = () => { window.close(); } const [elapsedTime, setElapsedTime] = useState(0); const formatTime = (seconds: number) => { const hrs = Math.floor(seconds / 3600) .toString() .padStart(2, "0"); const mins = Math.floor((seconds % 3600) / 60) .toString() .padStart(2, "0"); const secs = (seconds % 60).toString().padStart(2, "0"); return `${hrs}:${mins}:${secs}`; }; useEffect(() => { let mounted = true; (async () => { try { const data = await api.post('/meetings/details', { id: meetingId, type: type, }); if (!mounted) return; setMeetingData(data); const startTime = Date.now(); const timer = setInterval(() => { const currentTime = Date.now(); const elapsedSeconds = Math.floor((currentTime - startTime) / 1000); setElapsedTime(elapsedSeconds); }, 1000); await room.connect(livekitUrl!, authCode); // await room.localParticipant.enableCameraAndMicrophone(); room.registerTextStreamHandler('lk.transcription', async (reader, participantInfo) => { const message = await reader.readAll(); const isHuman = !!reader.info?.attributes?.['lk.transcribed_track_id']; const speaker = isHuman ? 'You' : 'JayT'; setTranscripts(prev => { let updatedMessages; if (prev.length > 0 && prev[prev.length - 1].speaker === speaker) { // Append to the existing message instead of creating a new one updatedMessages = [...prev]; updatedMessages[updatedMessages.length - 1] = { ...updatedMessages[updatedMessages.length - 1], text: updatedMessages[updatedMessages.length - 1].text + ' ' + message }; return updatedMessages; } else { // Create a new message if from a different sender updatedMessages = [...prev, { speaker, text: message, isAI: !isHuman }]; // Open transcript only if this is the very first message if (prev.length === 0) { setShowTranscript(true); } return updatedMessages; } }); }); } catch (e) { console.error('Error connecting to LiveKit:', e); } finally { if (mounted) setLoading(false); } })(); return () => { mounted = false; room.disconnect(); }; }, [room, livekitUrl]); if (loading) return <div className="items-center justify-center h-screen p-8 flex flex-col"> <img style={{height:'8rem'}} src="

https://d19o5tm6bkxi0c.cloudfront.net/jobtwine-webapp-images/jt-loader-gif-bg-transparent.gif▾

" alt="" /> Preparing your interview...</div>; if (!meetingData) return <div className="text-center text-red-600">Failed to start interview.</div>; return ( <TooltipProvider delayDuration={300}> <div className="h-screen flex flex-col w-screen"> <Header /> {hasLeftRoom ? ( <div className="fixed inset-0 flex items-center justify-center"> <div className="p-8 rounded-lg text-center bg-white bg-opacity-30 z-10 flex items-center justify-center flex-col"> <img src="/images/Animation - 1746449546651.gif" style={{"height": "12rem"}} /> <h2 className="text-xl font-semibold">Great!</h2> <p className="mt-4 text-gray-600 text-base font-medium">The interview is now complete.</p> <p className="mt-4 text-gray-600 text-base font-medium">We’ll connect with you shortly about next steps.<br/>Thank you for your time!</p> <div className="mt-8" style={{"width":"30%"}}> <Button jtBlueButton={true} onClick={handleClick} > Okay </Button> </div> </div> </div> ) : ( <> <div className="flex-1 flex flex-col"> <div className="flex justify-between items-center gap-2 bg-[#424242] py-3 px-4 text-white text-sm"> <div className="flex flex-col sm:flex-row items-start sm:items-center text-sm"> <span className="text-white mr-1 font-semibold whitespace-nowrap"> Discussion: </span> <span className="text-sm text-white break-words sm:break-normal !text-left"> {sessionStorage?.getItem("Candidate") || "Candidate"} for{" "} {meetingData?.jobName} </span> </div> <div className="flex items-center bg-[#353535] rounded-full px-3 py-1 gap-2 text-sm"> <div className="flex items-center gap-1.5"> <div className="w-2 h-2 bg-red-500 rounded-full animate-pulse"></div> <span className="text-white">Rec</span> <span className="ml-1">|</span> </div> <div className="flex items-center gap-1"> <Clock className="h-4 w-4 text-gray-300" /> <span className="text-gray-300"> {formatTime(elapsedTime)} </span> </div> </div> </div> </div> <RoomContext.Provider value={room}> <div data-lk-theme="default" className="h-screen flex overflow-y-auto" style={{ padding: '20px', background: 'rgb(53, 53, 53)', gap: '20px' }}> {/* Left Side */} <div className="flex-1 flex flex-col" style={{ background: "#353535" }}> <VideoRoom room={room} /> <RoomAudioRenderer /> </div> {/* Right Side */} <Transcript transcripts={transcripts} isOpen={showTranscript} setIsOpen={setShowTranscript} /> </div> {/* <ControlBar className='bg-[#424242]' /> */} </RoomContext.Provider> <footer className="w-full flex justify-between py-3 px-4 shadow-[0_-4px_6px_-2px_rgba(0,0,0,0.1)] sticky bottom-0" style={{ background: "#424242" }}> <div className="flex items-center"> <img src="/images/jayT-footer.svg" alt="Left Logo" /> </div> <div className="flex flex-wrap items-center justify-center gap-3 w-full"> <Tooltip> <TooltipTrigger asChild> <Button className="!bg-[#353535] text-white border-none" size="icon" onClick={toggleMic} > {micEnabled ? <Mic /> : <MicOff />} </Button> </TooltipTrigger> </Tooltip> <Tooltip> <TooltipTrigger asChild> <Button className="!bg-[#353535] text-white border-none" size="icon" onClick={toggleVideo} > {videoEnabled ? <Video /> : <VideoOff />} </Button> </TooltipTrigger> </Tooltip> <Button jtEndButton={true} onClick={onLeave}> <img className="p-3" src="/images/call-End.svg" alt="call" /> </Button> </div> <div className="flex items-center cursor-pointer" onClick={() => setShowTranscript(!showTranscript)}> <img src={showTranscript ? "/images/transcript-on.svg" : "/images/transcript-off.svg"} alt="Transcript toggle" /> </div> </footer> </> )} </div> </TooltipProvider> ); } When the candidate speaks during the AI interview, duplicate transcript lines are getting generated in the transcript sidebar. However, when the bot (JayT) speaks, the transcript behaves correctly without duplication. This issue leads to repeated text blocks and breaks the readability of the conversation. Acceptance Criteria: • Each speech segment from the candidate should appear only once in the transcript. • Bot (JayT) transcripts should continue to appear normally. • No duplicate entries should appear even if multiple events are fired simultaneously.
t
It looks like the duplicate transcript lines for your candidate might be happening because multiple events are firing at the same time or the logic for adding messages isn’t quite handling duplicates as smoothly as we’d like. No worries though—here’s a friendly guide to help you fix it: 1. Debounce or Throttle Events: This helps manage multiple events that happen in quick succession. You can use a debounce function to control how often
setTranscripts
gets called, which can really tidy things up:
Copy code
let debounceTimeout;
const debounce = (func, delay) => {
  clearTimeout(debounceTimeout);
  debounceTimeout = setTimeout(func, delay);
};
Then, wrap your
setTranscripts
call inside this debounce function like so:
Copy code
room.registerTextStreamHandler('lk.transcription', async (reader, participantInfo) => {
  const message = await reader.readAll();
  const isHuman = !!reader.info?.attributes?.['lk.transcribed_track_id'];
  const speaker = isHuman ? 'You' : 'JayT';

  debounce(() => {
    setTranscripts(prev => {
      if (prev.length > 0 && prev[prev.length - 1].speaker === speaker) {
        const updatedMessages = [...prev];
        updatedMessages[updatedMessages.length - 1] = {
          ...updatedMessages[updatedMessages.length - 1],
          text: updatedMessages[updatedMessages.length - 1].text + ' ' + message,
        };
        return updatedMessages;
      } else {
        return [...prev, { speaker, text: message, isAI: !isHuman }];
      }
    });
  }, 300); // You can adjust this delay to suit your needs
});
1. Check for Existing Messages: Before adding a new message, it’s a good idea to check if it’s already there in the transcript to avoid duplicates:
Copy code
setTranscripts(prev => {
  const exists = prev.some(
    t => t.speaker === speaker && t.text === message
  );
  if (exists) return prev;

  if (prev.length > 0 && prev[prev.length - 1].speaker === speaker) {
    const updatedMessages = [...prev];
    updatedMessages[updatedMessages.length - 1] = {
      ...updatedMessages[updatedMessages.length - 1],
      text: updatedMessages[updatedMessages.length - 1].text + ' ' + message,
    };
    return updatedMessages;
  } else {
    return [...prev, { speaker, text: message, isAI: !isHuman }];
  }
});
1. Log Events: Adding some logging can really help you see what’s going on behind the scenes and make sure events aren’t firing more than they should:
Copy code
room.registerTextStreamHandler('lk.transcription', async (reader, participantInfo) => {
  const message = await reader.readAll();
  console.log('New transcription event:', { message, participantInfo });
});
With these tweaks, each speech segment from your candidate should appear just once in the transcript, while the bot (JayT) transcripts will keep working just right. If you run into any other questions or need a hand with anything else, please don’t hesitate to reach out. I’m here to help!
h
1. no i don't want debouncing becauase i want live trancripts.. it should display as it comes from livekit
t
To help you display live transcripts without duplicates, you can tweak the logic a bit to check if a message already exists before adding it. Here’s a simple way to do that: 1. Check for Existing Messages: Before adding a new message, make sure it’s not already in the transcript:
Copy code
room.registerTextStreamHandler('lk.transcription', async (reader, participantInfo) => {
  const message = await reader.readAll();
  const isHuman = !!reader.info?.attributes?.['lk.transcribed_track_id'];
  const speaker = isHuman ? 'You' : 'JayT';

  setTranscripts(prev => {
    // Let’s see if this exact message is already here
    const exists = prev.some(
      t => t.speaker === speaker && t.text === message
    );
    if (exists) return prev;

    // If the last message is from the same speaker, we’ll add to it
    if (prev.length > 0 && prev[prev.length - 1].speaker === speaker) {
      const updatedMessages = [...prev];
      updatedMessages[updatedMessages.length - 1] = {
        ...updatedMessages[updatedMessages.length - 1],
        text: updatedMessages[updatedMessages.length - 1].text + ' ' + message,
      };
      return updatedMessages;
    } else {
      // Otherwise, we add a new message for a different speaker
      return [...prev, { speaker, text: message, isAI: !isHuman }];
    }
  });
});
1. Log Events: It’s also helpful to add some logging so you can see the events as they come in and make sure everything’s working smoothly:
Copy code
room.registerTextStreamHandler('lk.transcription', async (reader, participantInfo) => {
  const message = await reader.readAll();
  console.log('New transcription event:', { message, participantInfo });
});
This way, your live transcripts will show up just as they come from LiveKit, without any duplicates cluttering things up. If you’d like, I’m here to help you with any other questions or to walk you through the process. Just let me know!
h
also i don't want to filter because anyone can speak also two words or same thing twice then i don't want to remove that..
t
To help you handle live transcripts without filtering out or removing valid repeated messages, let's focus on making sure each event is processed properly and added as a new entry only when it makes sense. Here’s a friendly way to refine your logic: 1. Append Messages Without Filtering: Always add new messages, but group them by speaker if the same person keeps talking:
Copy code
room.registerTextStreamHandler('lk.transcription', async (reader, participantInfo) => {
  const message = await reader.readAll();
  const isHuman = !!reader.info?.attributes?.['lk.transcribed_track_id'];
  const speaker = isHuman ? 'You' : 'JayT';

  setTranscripts(prev => {
    // Append to the last message if the speaker is the same
    if (prev.length > 0 && prev[prev.length - 1].speaker === speaker) {
      const updatedMessages = [...prev];
      updatedMessages[updatedMessages.length - 1] = {
        ...updatedMessages[updatedMessages.length - 1],
        text: updatedMessages[updatedMessages.length - 1].text + ' ' + message,
      };
      return updatedMessages;
    } else {
      // Add a new message if the speaker changes
      return [...prev, { speaker, text: message, isAI: !isHuman }];
    }
  });
});
1. Log Events for Debugging: Adding some logging can be really helpful to check the sequence and content of events:
Copy code
room.registerTextStreamHandler('lk.transcription', async (reader, participantInfo) => {
  const message = await reader.readAll();
  console.log('New transcription event:', { message, participantInfo });
});
This way, you’ll make sure all messages from LiveKit show up without filtering out any valid repeats, while still keeping things neat by grouping messages from the same speaker together. If you have any questions or need a hand with this, just let me know—I’m here to help!
h
this i have done that appended in same spaeaker but its wrng when user saus onece then why multiple times coming my code only registers the handler once. this is a LiveKit-side duplication issue — the
registerTextStreamHandler
callback itself is getting triggered multiple times for the same participant (only for the human one), even though I register it once.
t
It looks like the
registerTextStreamHandler
being triggered multiple times for the same participant is happening because LiveKit might be generating multiple streams for the same topic. This often occurs in transcription scenarios where both interim (real-time) and final (complete) streams are sent for each speech segment. Here’s a friendly way to resolve this: 1. Filter Interim and Final Streams: You can use the metadata
lk.transcription_final
to tell the difference between interim and final transcriptions. By processing only the final transcription, you’ll avoid duplicates:
Copy code
room.registerTextStreamHandler('lk.transcription', async (reader, participantInfo) => {
  const message = await reader.readAll();
  const isFinal = reader.info?.attributes?.['lk.transcription_final'];

  if (!isFinal) return; // Skip interim transcriptions

  const isHuman = !!reader.info?.attributes?.['lk.transcribed_track_id'];
  const speaker = isHuman ? 'You' : 'JayT';

  setTranscripts(prev => {
    if (prev.length > 0 && prev[prev.length - 1].speaker === speaker) {
      const updatedMessages = [...prev];
      updatedMessages[updatedMessages.length - 1] = {
        ...updatedMessages[updatedMessages.length - 1],
        text: updatedMessages[updatedMessages.length - 1].text + ' ' + message,
      };
      return updatedMessages;
    } else {
      return [...prev, { speaker, text: message, isAI: !isHuman }];
    }
  });
});
1. Log Stream Metadata: It might also help to add some logging to check the attributes of each stream, so you can be sure you’re only processing the streams you want:
Copy code
room.registerTextStreamHandler('lk.transcription', async (reader, participantInfo) => {
  const message = await reader.readAll();
  console.log('Stream metadata:', reader.info?.attributes);
});
This way, you’ll be confident that only the final transcriptions are processed, which helps avoid those pesky duplicates caused by interim streams. If you have any more questions or need further help, please don’t hesitate to ask. I’m here to support you! Sources: Sending text | LiveKit Docs | Text and transcriptions | LiveKit Docs | Tests/LiveKitCoreTests/DataStream/IncomingStreamManagerTests.swift | packages/livekit-rtc/src/room.ts | Runtime/Scripts/Room.cs
h
acha i want one thing I have seen that when any particpant either egent or human complets then complete setence paragrapgh come at once.. but i want word to word it should come like a rwal time transcript and streaming
t
I'm glad you're interested in implementing real-time word-by-word transcription streaming in LiveKit! You can definitely achieve this by using the LiveKit Agents framework alongside a speech-to-text (STT) provider that supports streaming. Here's a friendly guide to help you through the process: 1. Use a Streaming STT Provider: Start by choosing an STT provider such as Google Cloud, AssemblyAI, or OpenAI Whisper that supports real-time streaming. Make sure to configure the STT implementation to enable interim results so you can get those word-by-word updates as they happen. 2. Handle Interim and Final Transcriptions: It’s helpful to use
SpeechEventType.INTERIM_TRANSCRIPT
for those live updates and
SpeechEventType.FINAL_TRANSCRIPT
for the completed text. Here’s a simple example:
Copy code
room.registerTextStreamHandler('lk.transcription', async (reader, participantInfo) => {
  const message = await reader.readAll();
  const isFinal = reader.info?.attributes?.['lk.transcription_final'];

  if (isFinal) {
    // Handle final transcription
    console.log('Final:', message);
  } else {
    // Handle interim transcription
    console.log('Interim:', message);
  }
});
1. Frontend Integration: To create a smooth user experience, update your UI to show interim results as they come in and then swap them out with the final results once available. Here’s how you might do that:
Copy code
const [currentTranscript, setCurrentTranscript] = useState('');
const [finalTranscripts, setFinalTranscripts] = useState([]);

useEffect(() => {
  room.registerTextStreamHandler('lk.transcription', async (reader) => {
    const message = await reader.readAll();
    const isFinal = reader.info?.attributes?.['lk.transcription_final'];

    if (isFinal) {
      setFinalTranscripts(prev => [...prev, message]);
      setCurrentTranscript('');
    } else {
      setCurrentTranscript(message);
    }
  });
}, [room]);
1. Optimize for Performance: To keep things running smoothly, consider using faster STT models and reducing buffer sizes to cut down latency. For example, with AssemblyAI, you can set a smaller
buffer_size_seconds
to get quicker updates. This setup will help words appear in real-time as they’re spoken, making the transcription feel seamless and natural. If you run into any questions or want to dive deeper into any step, just let me know—I’m here to help! Sources: Text and transcriptions | LiveKit Docs | livekit-plugins/livekit-plugins-elevenlabs/livekit/plugins/elevenlabs/tts.p... | main.py
h
i don't want to use anything extra other than live kit
t
To help you achieve real-time word-by-word transcription using only LiveKit, you can work with the interim transcription events provided by LiveKit's
registerTextStreamHandler
. Here’s a friendly walkthrough on how to handle it: 1. Process Interim Transcriptions: LiveKit sends both interim and final transcription events. You can use the
lk.transcription
topic to capture those interim updates like this:
Copy code
room.registerTextStreamHandler('lk.transcription', async (reader, participantInfo) => {
  const message = await reader.readAll();
  const isFinal = reader.info?.attributes?.['lk.transcription_final'];

  if (!isFinal) {
    // Here’s where you handle the interim transcription (word-by-word updates)
    console.log('Interim:', message);
    setCurrentTranscript(message); // This updates the UI with the interim text
  } else {
    // This handles the final transcription
    console.log('Final:', message);
    setFinalTranscripts(prev => [...prev, message]);
    setCurrentTranscript(''); // Clears the interim text once final is ready
  }
});
1. Update the UI: You’ll want to show the interim text live, then swap it out with the final text as soon as it’s available:
Copy code
const [currentTranscript, setCurrentTranscript] = useState('');
const [finalTranscripts, setFinalTranscripts] = useState([]);

return (
  <div>
    <div>
      {finalTranscripts.map((text, index) => (
        <p key={index}>{text}</p>
      ))}
    </div>
    <p style={{ fontStyle: 'italic' }}>{currentTranscript}</p>
  </div>
);
This method lets you display word-by-word updates in real-time, relying solely on LiveKit’s built-in transcription features. If you have any questions or want me to walk you through any part of this, just let me know—I’m here to help!
h
this is my trancript component 'use client'; import { useEffect, useRef } from 'react'; export interface TranscriptMessage { speaker: string; text: string; isAI: boolean; } interface TranscriptProps { transcripts: TranscriptMessage[]; isOpen: boolean; // received from parent setIsOpen: (open: boolean) => void; // function to toggle } export function Transcript({ transcripts, isOpen, setIsOpen }: TranscriptProps) { const transcriptContainerRef = useRef<HTMLDivElement>(null); const candidateName = 'Y'; // Auto-scroll to bottom whenever transcripts change useEffect(() => { if (isOpen && transcriptContainerRef.current) { transcriptContainerRef.current.scrollTop = transcriptContainerRef.current.scrollHeight; } }, [transcripts, isOpen]); return ( <> <div className={
transition-all duration-300 w-full md:w-1/3 px-4 flex-shrink-0 flex flex-col h-[300px] md:h-full ${isOpen ? '' : 'hidden'}
}> <div className="rounded-lg shadow-md flex flex-col h-full" style={{"background" : "#404040"}}> <h3 className="text-md font-bold px-4 pt-3 pb-2 text-white text-left">Transcript</h3> <div className="p-3 rounded m-2 overflow-y-auto flex-1 text-left" ref={transcriptContainerRef} > {transcripts.map((msg, index) => ( <div key={index} className={
flex mb-3 ${!msg.isAI ? 'flex-row-reverse' : 'flex-row rounded-3xl bg-gradient py-4'}
}> <div className="flex-shrink-0 mx-2"> {!msg.isAI ? ( <div className="w-8 h-8 rounded-full flex items-center justify-center text-white font-bold" style={{"background":"#353535"}}> {candidateName ? candidateName.charAt(0).toUpperCase() : 'U'} </div> ) : ( <img src="/images/jayT.svg" alt="Bot" className="w-8 h-8 rounded-full" /> )} </div> <div className={
max-w-[70%] flex flex-col ${!msg.isAI ? 'items-end' : 'items-start'}
}> <span className="text-sm text-white font-semibold mb-1"> {!msg.isAI ? 'You' : 'JayT'} </span> <div className={
rounded-lg break-words text-white text-sm
} style={{ userSelect: 'none' }} > {msg.text} </div> </div> </div> ))} </div> </div> </div> </> ); }
t
Thank you so much for sharing your
Transcript
component! To help you achieve real-time word-by-word updates in the transcript, a great approach is to handle interim and final transcriptions separately. Let me walk you through how you can integrate this: 1. Handle Interim and Final Transcriptions: You can update the parent component to pass both interim and final transcripts to the
Transcript
component. Here's an example:
Copy code
const [currentTranscript, setCurrentTranscript] = useState('');
const [finalTranscripts, setFinalTranscripts] = useState([]);

room.registerTextStreamHandler('lk.transcription', async (reader) => {
  const message = await reader.readAll();
  const isFinal = reader.info?.attributes?.['lk.transcription_final'];

  if (isFinal) {
    setFinalTranscripts(prev => [...prev, { speaker: 'You', text: message, isAI: false }]);
    setCurrentTranscript('');
  } else {
    setCurrentTranscript(message);
  }
});
1. Update the
Transcript
Component:
You can modify the component to display the interim transcript separately like this:
Copy code
export function Transcript({ transcripts, isOpen, setIsOpen, currentTranscript }: TranscriptProps & { currentTranscript: string }) {
  const transcriptContainerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (isOpen && transcriptContainerRef.current) {
      transcriptContainerRef.current.scrollTop = transcriptContainerRef.current.scrollHeight;
    }
  }, [transcripts, isOpen, currentTranscript]);

  return (
    <>
      <div className={`transition-all duration-300 w-full md:w-1/3 px-4 flex-shrink-0 flex flex-col h-[300px] md:h-full ${isOpen ? '' : 'hidden'}`}>
        <div className="rounded-lg shadow-md flex flex-col h-full" style={{ background: '#404040' }}>
          <h3 className="text-md font-bold px-4 pt-3 pb-2 text-white text-left">Transcript</h3>
          <div className="p-3 rounded m-2 overflow-y-auto flex-1 text-left" ref={transcriptContainerRef}>
            {transcripts.map((msg, index) => (
              <div key={index} className={`flex mb-3 ${!msg.isAI ? 'flex-row-reverse' : 'flex-row rounded-3xl bg-gradient py-4'}`}>
                <div className="flex-shrink-0 mx-2">
                  {!msg.isAI ? (
                    <div className="w-8 h-8 rounded-full flex items-center justify-center text-white font-bold" style={{ background: '#353535' }}>
                      Y
                    </div>
                  ) : (
                    <img src="/images/jayT.svg" alt="Bot" className="w-8 h-8 rounded-full" />
                  )}
                </div>
                <div className={`max-w-[70%] flex flex-col ${!msg.isAI ? 'items-end' : 'items-start'}`}>
                  <span className="text-sm text-white font-semibold mb-1">
                    {!msg.isAI ? 'You' : 'JayT'}
                  </span>
                  <div className="rounded-lg break-words text-white text-sm" style={{ userSelect: 'none' }}>
                    {msg.text}
                  </div>
                </div>
              </div>
            ))}
            {currentTranscript && (
              <div className="flex mb-3 flex-row-reverse">
                <div className="flex-shrink-0 mx-2">
                  <div className="w-8 h-8 rounded-full flex items-center justify-center text-white font-bold" style={{ background: '#353535' }}>
                    Y
                  </div>
                </div>
                <div className="max-w-[70%] flex flex-col items-end">
                  <span className="text-sm text-white font-semibold mb-1">You</span>
                  <div className="rounded-lg break-words text-white text-sm" style={{ userSelect: 'none' }}>
                    {currentTranscript}
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </>
  );
}
This approach will nicely display the interim transcript in real-time and then seamlessly replace it with the final transcript once it's ready. If you have any questions or need a hand with anything else, please don’t hesitate to reach out. I’m here to help!
h
i want that automatcllly room disconnect hone pe setHasLeftRoom(true) ho jae 'use client'; import { ControlBar, RoomAudioRenderer, RoomContext, } from '@livekit/components-react'; import { Room } from 'livekit-client'; import '@livekit/components-styles'; import { Suspense, useEffect, useState } from 'react'; import { VideoRoom } from './components/VideoRoom'; import { api } from '../services/api'; import { Transcript, TranscriptMessage } from './components/Transcript'; import Header from './components/Header'; import { TooltipContent, TooltipTrigger } from "@radix-ui/react-tooltip"; import { Button } from "@components/common/button"; import { Tooltip } from "@radix-ui/react-tooltip"; import { TooltipProvider } from "@components/common/tooltip"; import { PhoneOff, Video, VideoOff, Mic, MicOff, Clock } from "lucide-react"; import { useSearchParams } from 'next/navigation'; interface MeetingResponse { authToken: string; meetingUrl: string; candidateId: string; jobName: string; jobRoundNumber: number; } function CandidateInterviewContent() { const [room] = useState(() => new Room({ adaptiveStream: true, dynacast: true })); const [loading, setLoading] = useState(true); const [meetingData, setMeetingData] = useState<MeetingResponse | null>(null); const [transcripts, setTranscripts] = useState<TranscriptMessage[]>([]); const [currentTranscript, setCurrentTranscript] = useState<string>(''); const livekitUrl = process.env.NEXT_PUBLIC_LIVEKIT_URL; const [showTranscript, setShowTranscript] = useState(false); const [micEnabled, setMicEnabled] = useState(room.localParticipant.isMicrophoneEnabled); const [videoEnabled, setVideoEnabled] = useState(room.localParticipant.isCameraEnabled); const searchParams = useSearchParams(); const meetingId = searchParams.get('id'); const type = searchParams.get("type"); const authCode: string = searchParams.get("authCode") || ""; const [hasLeftRoom, setHasLeftRoom] = useState(false); const [elapsedTime, setElapsedTime] = useState(0); const toggleMic = () => { room.localParticipant.setMicrophoneEnabled(!micEnabled); setMicEnabled(!micEnabled); }; const toggleVideo = () => { room.localParticipant.setCameraEnabled(!videoEnabled); setVideoEnabled(!videoEnabled); }; const onLeave = () => { room.disconnect(); setHasLeftRoom(true); }; const handleClick = () => { window.open('https://www.jobtwine.com', "_self"); }; const formatTime = (seconds: number) => { const hrs = Math.floor(seconds / 3600).toString().padStart(2, "0"); const mins = Math.floor((seconds % 3600) / 60).toString().padStart(2, "0"); const secs = (seconds % 60).toString().padStart(2, "0"); return `${hrs}:${mins}:${secs}`; }; useEffect(() => { let mounted = true; (async () => { try { const data = await api.post('/meetings/details', { id: meetingId, type }); if (!mounted) return; setMeetingData(data); const startTime = Date.now(); const timer = setInterval(() => setElapsedTime(Math.floor((Date.now() - startTime) / 1000)), 1000); await room.connect(livekitUrl!, authCode); room.registerTextStreamHandler('lk.transcription', async (reader) => { const message = await reader.readAll(); const isFinal = reader.info?.attributes?.['lk.transcription_final'] === 'true'; const isHuman = !!reader.info?.attributes?.['lk.transcribed_track_id']; const speaker = isHuman ? 'You' : 'JayT'; if (!isFinal) return setCurrentTranscript(message); setTranscripts(prev => { let updatedMessages; if (prev.length > 0 && prev[prev.length - 1].speaker === speaker) { updatedMessages = [...prev]; updatedMessages[updatedMessages.length - 1] = { ...updatedMessages[updatedMessages.length - 1], text: updatedMessages[updatedMessages.length - 1].text + ' ' + message, }; } else { updatedMessages = [...prev, { speaker, text: message, isAI: !isHuman }]; } if (prev.length === 0) setShowTranscript(true); return updatedMessages; }); setCurrentTranscript(''); }); } catch (e) { console.error('Error connecting to LiveKit:', e); } finally { if (mounted) setLoading(false); } })(); return () => { mounted = false; room.disconnect(); }; }, [room, livekitUrl, meetingId, type, authCode]); if (loading) return ( <div className="items-center justify-center h-screen p-8 flex flex-col"> <img style={{height:'8rem'}} src="

https://d19o5tm6bkxi0c.cloudfront.net/jobtwine-webapp-images/jt-loader-gif-bg-transparent.gif▾

" alt="" /> Preparing your interview... </div> ); if (!meetingData) return <div className="flex items-center justify-center text-center h-screen text-red-600">Failed to start interview.</div>; return ( <TooltipProvider delayDuration={300}> <div className="h-screen flex flex-col w-screen"> <Header /> {hasLeftRoom ? ( <div className="fixed inset-0 flex items-center justify-center"> <div className="p-8 rounded-lg text-center bg-white bg-opacity-30 z-10 flex items-center justify-center flex-col"> <img src="/images/Animation - 1746449546651.gif" style={{"height": "12rem"}} /> <h2 className="text-xl font-semibold">Great!</h2> <p className="mt-4 text-gray-600 text-base font-medium">The interview is now complete.</p> <p className="mt-4 text-gray-600 text-base font-medium">We’ll connect with you shortly about next steps.<br/>Thank you for your time!</p> <div className="mt-8" style={{"width":"30%"}}> <Button jtBlueButton={true} onClick={handleClick}>Okay</Button> </div> </div> </div> ) : ( <> <div className="flex-1 flex flex-col"> <div className="flex justify-between items-center gap-2 bg-[#424242] py-3 px-4 text-white text-sm"> <div className="flex flex-col sm:flex-row items-start sm:items-center text-sm"> <span className="text-white mr-1 font-semibold whitespace-nowrap">Round {meetingData.jobRoundNumber}</span> <span className="text-sm text-white break-words sm:break-normal !text-left"> {/* {sessionStorage?.getItem("Candidate") || "Candidate"} */} for {meetingData?.jobName} </span> </div> <div className="flex items-center bg-[#353535] rounded-full px-3 py-1 gap-2 text-sm"> <div className="flex items-center gap-1.5"> <div className="w-2 h-2 bg-red-500 rounded-full animate-pulse"></div> <span className="text-white">Rec</span> <span className="ml-1">|</span> </div> <div className="flex items-center gap-1"> <Clock className="h-4 w-4 text-gray-300" /> <span className="text-gray-300">{formatTime(elapsedTime)}</span> </div> </div> </div> </div> <RoomContext.Provider value={room}> <div data-lk-theme="default" className="h-screen flex overflow-y-auto p-2.5 md:p-5 gap-2.5 md:gap-5" style={{ background: 'rgb(53, 53, 53)' }}> <div className="flex-1 flex flex-col" style={{ background: "#353535" }}> <VideoRoom room={room} /> <RoomAudioRenderer /> </div> <Transcript transcripts={transcripts} currentTranscript={currentTranscript} isOpen={showTranscript} setIsOpen={setShowTranscript} /> </div> </RoomContext.Provider> <footer className="w-full flex justify-between py-3 px-4 shadow-[0_-4px_6px_-2px_rgba(0,0,0,0.1)] sticky bottom-0" style={{ background: "#424242" }}> <div className="hidden md:flex items-center"> <img src="/images/jayT-footer.svg" alt="Left Logo" /> </div> <div className="flex flex-wrap items-center justify-center gap-3 w-full"> <Tooltip><TooltipTrigger asChild> <Button className="!bg-[#353535] text-white border-none" size="icon" onClick={toggleMic}>{micEnabled ? <Mic /> : <MicOff />}</Button> </TooltipTrigger></Tooltip> <Tooltip><TooltipTrigger asChild> <Button className="!bg-[#353535] text-white border-none" size="icon" onClick={toggleVideo}>{videoEnabled ? <Video /> : <VideoOff />}</Button> </TooltipTrigger></Tooltip> <Button jtEndButton={true} onClick={onLeave}> <img className="p-3" src="/images/call-End.svg" alt="call" /> </Button> </div> <div className="flex items-center cursor-pointer" onClick={() => setShowTranscript(!showTranscript)}> <img src={showTranscript ? "/images/transcript-on.svg" : "/images/transcript-off.svg"} alt="Transcript toggle" /> </div> </footer> </> )} </div> </TooltipProvider> ); } export default function Page() { return ( <Suspense fallback={<div>Loading interview...</div>}> <CandidateInterviewContent /> </Suspense> ); }
t
To help you automatically set
setHasLeftRoom(true)
when the room disconnects, you can listen for the
RoomEvent.Disconnected
event in LiveKit. Here's a simple way to do it:
Copy code
useEffect(() => {
  const handleDisconnect = () => {
    setHasLeftRoom(true);
  };

  // Listen for the Disconnected event
  room.on(RoomEvent.Disconnected, handleDisconnect);

  return () => {
    // Clean up the event listener when the component unmounts
    room.off(RoomEvent.Disconnected, handleDisconnect);
  };
}, [room]);
This setup makes sure that
setHasLeftRoom(true)
runs automatically whenever the room disconnects, whether that happens manually or due to an automatic disconnection. If you have any questions or need a hand with anything else, just let me know—I’m here to help!