what's the error in the below code, whenever I run...
# ask-ai
r
what's the error in the below code, whenever I run it, an infinite calls of this error occurred: ## ERROR
Copy code
[Error: aborted] { code: 'ECONNRESET' }
 ⨯ uncaughtException: [Error: aborted] { code: 'ECONNRESET' }
 ⨯ uncaughtException:  [Error: aborted] { code: 'ECONNRESET' }
## CODE
Copy code
// src/app/api/livekit/token/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@clerk/nextjs/server';
import { AccessToken } from 'livekit-server-sdk';

export async function POST(request: NextRequest) {
  try {
    const { userId } = await auth();
    if (!userId) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const apiKey = process.env.LIVEKIT_API_KEY;
    const apiSecret = process.env.LIVEKIT_API_SECRET;
    const wsUrl = process.env.LIVEKIT_URL;

    if (!apiKey || !apiSecret || !wsUrl) {
      console.error('[LiveKit Token] Missing configuration:', { 
        hasApiKey: !!apiKey, 
        hasApiSecret: !!apiSecret, 
        hasWsUrl: !!wsUrl 
      });
      return NextResponse.json({ error: 'Server configuration error' }, { status: 500 });
    }

    let participantName: string | undefined;
    let threadId: string | undefined;
    let context: any | undefined;

    let raw: string;
    try {
      raw = await request.text();  // This can throw on abort
    } catch (e: any) {
      if (e.name === 'AbortError' || e.code === 'ECONNRESET') {
        console.log('[LiveKit Token] Request aborted by client');
        return new NextResponse(null, { status: 499 });  // Client Closed Request
      }
      throw e;  // Rethrow other errors
    }

    if (!raw || raw.trim() === '') {
      console.error('[LiveKit Token] Empty request body');
      return NextResponse.json({ error: 'Empty request body' }, { status: 400 });
    }

    try {
      const body = JSON.parse(raw);
      participantName = body.participantName;
      threadId = body.threadId;
      context = body.context;
      
      console.log('[LiveKit Token] Request received:', { 
        hasParticipantName: !!participantName,
        hasThreadId: !!threadId,
        hasContext: !!context 
      });
    } catch (e: any) {
      console.error('[LiveKit Token] JSON parse error:', e.message);
      return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
    }

    if (!threadId) {
      console.error('[LiveKit Token] Missing threadId');
      return NextResponse.json({ error: 'threadId is required' }, { status: 400 });
    }

    const roomName = spiders-voice-${userId}-${threadId};

    const cfg = (context?.configurable ?? {}) as Record<string, any>;
    const safeConfigurable = {
      __user_id: cfg.__user_id ?? userId,
      FEtimezone: cfg.FEtimezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone,
      user: cfg.user ?? null,
      organization: cfg.organization ?? null,
      integrations: cfg.integrations ?? [],
      itemContext: cfg.itemContext ?? null,
      slack: cfg.slack ?? null,
      clickup: cfg.clickup ?? null,
      notion: cfg.notion ?? null,
      jira: cfg.jira ?? null,
      contacts: cfg.contacts ?? null,
    };
    const participantMetadata = JSON.stringify({ configurable: safeConfigurable });

    const at = new AccessToken(apiKey, apiSecret, {
      identity: userId,
      name: participantName || userId,
    });
    at.addGrant({
      room: roomName,
      roomJoin: true,
      canPublish: true,
      canSubscribe: true,
      canPublishData: true,
    });

    (at as any).setMetadata?.(participantMetadata);
    if (!(at as any).setMetadata) (at as any).metadata = participantMetadata;

    const token = await at.toJwt();
    
    console.log('[LiveKit Token] Token generated successfully:', { 
      roomName, 
      userId,
      metadataSize: participantMetadata.length 
    });
    
    return NextResponse.json({ token, wsUrl, roomName });
  } catch (err: any) {
    console.error('[LiveKit Token] Error:', err.message || err);
    return NextResponse.json({ error: 'Failed to generate token' }, { status: 500 });
  }
}
t
Thanks for reaching out, Roaa. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Could you please share a bit more about when the ECONNRESET error pops up? For instance, does it happen right when you're trying to connect, during longer server-to-server communication, or maybe while media is being transported? Understanding this will really help us get to the bottom of the issue and find the best solution for you. Sources: Diagnosing Connection Errors with Connection Test Utility | Connecting to LiveKit | LiveKit Docs | engine.go
r
The above code represents route.ts that used to generate LiveKit token in next.js. It is called from the below code that represents the page that occurs when I click on voice mode button
Copy code
// src/app/[locale]/(user-apps)/chat_components/voice-chat/voice-chat-container.tsx
'use client';

import React, { useState, useCallback, useEffect, useRef } from 'react';
import { VoiceChatInterface } from './voice-chat-interface';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Loader2, AlertCircle } from 'lucide-react';
import { useTranslation } from '@/lib/i18n/useTranslation';
import { useAuth } from '@clerk/nextjs';
import { useThreadListItemRuntime } from '@assistant-ui/react';
import { useAgentContext } from '../../_actions/prepare-agent-context';
import { useItemContextForAgent } from '../item-context-provider';

interface VoiceChatContainerProps {
  onClose: () => void;
  onTranscriptComplete?: (transcript: { role: string; content: string }[]) => void;
}

interface LiveKitConfig {
  token: string;
  wsUrl: string;
  roomName: string;
}

function isAbortError(e: unknown): boolean {
  return !!(e && typeof e === 'object' && 'name' in e && (e as any).name === 'AbortError');
}

export function VoiceChatContainer({ onClose, onTranscriptComplete }: VoiceChatContainerProps) {
  const { t } = useTranslation();
  const { userId } = useAuth();
  const threadListItemRuntime = useThreadListItemRuntime();
  const agentContext = useAgentContext();
  const { itemContext } = useItemContextForAgent();

  const [config, setConfig] = useState<LiveKitConfig | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [transcript, setTranscript] = useState<{ role: string; content: string }[]>([]);

  // StrictMode-safe one-time guard + prevent infinite loops
  const stableThreadIdRef = useRef<string | null>(null);
  const hasFetchedRef = useRef(false);

  useEffect(() => {
    // Prevent multiple fetches
    if (hasFetchedRef.current) {
      return;
    }
    hasFetchedRef.current = true;

    const ac = new AbortController();
    let cancelled = false;

    (async () => {
      try {
        setLoading(true);
        setError(null);

        // derive a stable threadId only once
        if (!stableThreadIdRef.current) {
          const state = threadListItemRuntime.getState();
          stableThreadIdRef.current = state?.externalId ?? `thread-${Date.now()}`;
        }
        const threadId = stableThreadIdRef.current!;

        // Build itemContextForAgent (same as your code) ...
        const itemContextForAgent = itemContext
          ? {
              itemId: itemContext.itemId,
              itemType: itemContext.itemType,
              source: itemContext.source,
              title: itemContext.title,
              description: itemContext.description,
              status: itemContext.status,
              priority: itemContext.priority,
              dueDate: itemContext.dueDate ? String(itemContext.dueDate) : undefined,
              startTime: itemContext.startTime ? String(itemContext.startTime) : undefined,
              endTime: itemContext.endTime ? String(itemContext.endTime) : undefined,
              assignee: itemContext.assignee,
              senderId: itemContext.senderId,
              senderName: itemContext.senderName,
              text: itemContext.text,
              timestamp: itemContext.timestamp,
              isPrivate: itemContext.isPrivate,
              isArchived: itemContext.isArchived,
              type: itemContext.type,
              isRecurring: itemContext.isRecurring,
              attendees: itemContext.attendees,
              location: itemContext.location,
              organizer: itemContext.organizer,
              hierarchy: itemContext.hierarchy
                ? {
                    workspace: itemContext.hierarchy.workspace?.name,
                    space: itemContext.hierarchy.space?.name,
                    project: itemContext.hierarchy.project?.name,
                    list: itemContext.hierarchy.list?.name,
                    folder: itemContext.hierarchy.folder?.name,
                    team: itemContext.hierarchy.team?.name,
                    meeting: itemContext.hierarchy.meeting?.title,
                  }
                : undefined,
              metadata: itemContext.metadata,
            }
          : null;

        const contextForVoiceAgent = {
          configurable: {
            __user_id: userId,
            tracked_key: 'voice_user_id',
            FEtimezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            user: agentContext.user ?? null,
            organization: agentContext.organization ?? null,
            slack: agentContext.slack ?? null,
            clickup: agentContext.clickup ?? null,
            notion: agentContext.notion ?? null,
            jira: agentContext.jira ?? null,
            contacts: agentContext.contacts ?? null,
            integrations: agentContext.connectedServices ?? null,
            itemContext: itemContextForAgent,
          },
        };

        const res = await fetch('/api/livekit/token', {
          method: 'POST',
          signal: ac.signal,
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            participantName: userId,
            threadId,                 // <-- stable
            context: contextForVoiceAgent,
          }),
        });

        if (!res.ok) throw new Error('Failed to generate LiveKit token');
        const data = await res.json();
        if (!cancelled) {
          setConfig({ token: data.token, wsUrl: data.wsUrl, roomName: data.roomName });
        }
      } catch (e: any) {
        if (isAbortError(e)) {
          // ignore StrictMode cleanup aborts
          return;
        }
        console.error('Error generating LiveKit token:', e);
        if (!cancelled) setError(e?.message ?? 'Failed to initialize voice chat');
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();

    return () => {
      cancelled = true;
      ac.abort('component unmounted'); // safe; ignored by the catch above
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // Run only once on mount

  const handleTranscriptUpdate = useCallback(
    (updated: { role: string; content: string }[]) => setTranscript(updated),
    [],
  );

  const handleDisconnect = useCallback(() => {
    if (transcript.length > 0 && onTranscriptComplete) onTranscriptComplete(transcript);
    onClose();
  }, [transcript, onClose, onTranscriptComplete]);

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center h-full p-8">
        <Loader2 className="w-12 h-12 animate-spin text-brand mb-4" />
        <p className="text-sm text-muted-foreground">{t('voice.initializing')}</p>
      </div>
    );
  }

  if (error || !config) {
    return (
      <div className="flex flex-col items-center justify-center h-full p-8">
        <Card className="max-w-md">
          <CardContent className="p-6 flex flex-col items-center">
            <AlertCircle className="w-12 h-12 text-red-500 mb-4" />
            <h3 className="text-lg font-semibold mb-2">{t('voice.error')}</h3>
            <p className="text-sm text-muted-foreground text-center mb-4">
              {error || t('voice.failedToInitialize')}
            </p>
            <Button onClick={onClose} variant="outline" className="w-full">
              {t('voice.close')}
            </Button>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <VoiceChatInterface
      token={config.token}
      wsUrl={config.wsUrl}
      roomName={config.roomName}
      onDisconnect={handleDisconnect}
      onTranscriptUpdate={handleTranscriptUpdate}
    />
  );
}
t
Could you please help me understand a bit better? Is the ECONNRESET error happening on the client side when you're calling the token endpoint, or is it showing up in the server-side code? Also, does this issue come up during local development, in production, or both? Knowing this will really help us pinpoint the cause and find the best solution for you. Sources: Web Applications & Integration Examples | livekit/livekit_composite | DeepW... | Next.js 12 quickstart | LiveKit Docs | avatars/hedra/education_avatar/education-frontend/app/api/connection-detail... | client/web/src/app/api/token/route.ts | Next.js quickstart | LiveKit Docs
r
It is happen in client side during local development
t
The ECONNRESET error you're encountering during local development usually points to a network connectivity hiccup between your client and the LiveKit server. Don't worry—let's walk through some steps together to help you troubleshoot and get things running smoothly: • Verify Environment Configuration: Please double-check that your
.env.local
file is set up correctly with
LIVEKIT_API_KEY
,
LIVEKIT_API_SECRET
, and
LIVEKIT_URL
. Make sure the URL is pointing to your LiveKit server. • Use the LiveKit Connection Test Utility: Running these tests can be really helpful to pinpoint any WebSocket or WebRTC connectivity issues. Sometimes firewalls or VPNs might be blocking the connection. • Check Network Settings: It’s good to confirm that your local network allows connections to the LiveKit server. If you’re using a self-hosted server, please ensure it’s up and accessible. • Implement Error Handling: Adding solid error handling in your API route and React components can help manage connection errors more gracefully. If you’re still seeing the issue after trying these, could you let me know if the error happens when the API route generates the token or when the client tries to connect with that token? Also, are you using LiveKit Cloud or a self-hosted server? This info will really help us get to the bottom of it together. Sources: Core Platform Architecture & Authentication | livekit/livekit_composite | D... | complex-agents/nova-sonic/nova-sonic-form-agent/app/api/connection-details/... | Next.js quickstart | LiveKit Docs | Diagnosing Connection Errors with Connection Test Utility | client/web/src/app/api/token/route.ts
r
The issue occurred when the client tries to connect with that token. I'm using LiveKit cloud
t
The ECONNRESET error during client connection to LiveKit Cloud usually points to a network hiccup or an issue with the token. Let’s walk through some steps together to help you troubleshoot this: • Verify Token and URL: Double-check that your
wsUrl
is correct and starts with
wss://
. You can decode your token using a handy tool like jwt.io to make sure it has all the necessary claims (like
roomJoin
,
identity
, and
exp
). • Run Connection Tests: Try using the LiveKit Connection Test Utility to see how your WebSocket, WebRTC, and TURN connections are doing. If everything fails, it might be a network or firewall blocking things. • Generate a Test Token: You can create a test token with the LiveKit CLI and try it out in your app. If this one works, it could help pinpoint differences with your original token. • Check Network Configuration: Make sure your local network isn’t blocking LiveKit Cloud connections. Temporarily turning off VPNs or firewalls can help us rule out those as causes. If you’re still running into issues after these steps, just share what you find from the connection tests and token checks. I’m here to help you get this sorted!