narrow-hairdresser-82835
12/10/2025, 8:03 AM@function_tool
async def end_call(self, context: RunContext[None]) -> None:
"""End the current health check call/session. Use this when the candidate confirms they can hear you and you can hear them."""
try:
logger.info("End call tool invoked by health check agent")
job_ctx = get_job_context()
room = job_ctx.room
# Disconnect from the room to end the session
logger.info("Disconnecting from room to end session...")
await room.disconnect()
logger.info("Disconnected from room")
except Exception as e:
logger.error(f"Error in end_call tool: {e}")
# Don't raise ToolError - just log and let the session end gracefully
logger.info("Attempting to disconnect despite error...")
try:
await get_job_context().room.disconnect()
except Exception:
pass
This is my tool call on the backend which is getting executed correctly.
const LivekitTestCallSession: React.FC<{
testCallSuccess: boolean;
setTestCallSuccess: (success: boolean) => void;
agentName: string;
onRetry: () => void;
}> = ({
testCallSuccess,
setTestCallSuccess,
agentName,
onRetry,
}) => {
const room = useRoomContext();
const { currentStatus, currentStatusText } = useLiveKitAgentStatus();
const [isTestCallError, setTestCallError] = useState(false);
const [isCallInProgress, setIsCallInProgress] = useState(false);
// Use refs to track state in callbacks without triggering re-renders
const isCallInProgressRef = useRef(false);
const isTestCallErrorRef = useRef(false);
const hasHandledConnection = useRef(false);
// Handle room events
useEffect(() => {
const handleConnected = (): void => {
// Prevent multiple invocations
if (hasHandledConnection.current) {
return;
}
hasHandledConnection.current = true;
setTestCallError(false);
isTestCallErrorRef.current = false;
setIsCallInProgress(true);
isCallInProgressRef.current = true;
// Enable microphone for the test call
room.localParticipant.setMicrophoneEnabled(true).catch(() => {
setTestCallError(true);
isTestCallErrorRef.current = true;
setIsCallInProgress(false);
isCallInProgressRef.current = false;
});
};
const handleDisconnected = (reason?: DisconnectReason): void => {
debugger;
// If disconnected by agent (test completed successfully) or client initiated
const isSuccessfulDisconnect = reason === DisconnectReason.CLIENT_INITIATED
|| reason === undefined
|| !isTestCallErrorRef.current;
if (isSuccessfulDisconnect && isCallInProgressRef.current) {
setTestCallSuccess(true);
}
setIsCallInProgress(false);
isCallInProgressRef.current = false;
hasHandledConnection.current = false;
};
room.on(RoomEvent.Connected, handleConnected);
room.on(RoomEvent.Disconnected, handleDisconnected);
room.on(RoomEvent.MediaDevicesError, () => {
setTestCallError(true);
isTestCallErrorRef.current = true;
setIsCallInProgress(false);
isCallInProgressRef.current = false;
});
// Check if already connected
if (room.state === 'connected') {
handleConnected();
}
return () => {
room.off(RoomEvent.Connected, handleConnected);
room.off(RoomEvent.Disconnected, handleDisconnected);
};
}, [room, setTestCallSuccess]);
const state = {
isTestCallError,
isCallInProgress,
testCallSuccess,
currentStatus,
currentStatusText,
};
return (
<AIConnectivityView
state={state}
agentName={agentName}
onRetry={onRetry}
/>
);
};
The handleOnDisconnect on my frontend is never getting called even after doing room.disconnected() on the backend.tall-airline-16756
12/10/2025, 8:03 AMtall-airline-16756
12/10/2025, 8:04 AMroom.disconnect() only disconnects that agent participant; it does not automatically disconnect the client. So your frontend's Room Disconnected handler may never fire. A few focused steps to fix/debug:
1) Quick check (add logs)
• Add console logs to confirm what events fire:
room.on(RoomEvent.Connected, () => console.log('connected'));
room.on(RoomEvent.Disconnected, (r) => console.log('disconnected', r));
room.on(RoomEvent.ParticipantDisconnected, (p) => console.log('participant disconnected', p.identity));
2) Recommended fix — listen for the agent leaving
• Instead of relying on RoomEvent.Disconnected, handle RoomEvent.ParticipantDisconnected and check the participant identity (agentName). When the agent leaves, treat the test as finished:
const handleParticipantDisconnected = (participant) => {
if (participant.identity === agentName && isCallInProgressRef.current && !isTestCallErrorRef.current) {
setTestCallSuccess(true);
setIsCallInProgress(false);
isCallInProgressRef.current = false;
hasHandledConnection.current = false;
}
};
room.on(RoomEvent.ParticipantDisconnected, handleParticipantDisconnected);
3) Optional: disconnect the client by removing the room (if you want all clients forced off)
• Deleting the room server-side will produce a client-side Disconnected (reason ROOM_DELETED). Use the LiveKit server API to delete the room if you need everyone disconnected.
4) Edge cases to consider
• If the agent simply stops publishing tracks but stays connected, ParticipantDisconnected won’t fire — check participant states or track subscriptions.
• Ensure your frontend has the correct agentName identity and that participant.identity matches it.
If you’d like, share a short log output from the console after you trigger the backend disconnect and I’ll point to the exact event behavior and the smallest code change to make your UI update.
Sources: Connecting to LiveKit | LiveKit docs