Chat e Streaming (Socket.IO)
Questa sezione descrive come il Node Agent gestisce la chat in tempo reale e lo streaming delle risposte tramite Socket.IO, inclusa la creazione dei thread e la validazione JWT.
Autenticazione Socket
const validateToken = (socket: CustomSocket, next: (err?: Error) => void) => {
const token = socket.handshake.auth.token
if (!token) return next(new Error('Authentication token is required'))
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET ?? '') as jwt.JwtPayload & {
companyId: string
}
socket.companyId = decoded.companyId
next()
} catch (error) {
return next(new Error('Invalid token'))
}
}
Inizializzazione server Socket.IO
export function initializeSocketServer(httpServer: HttpServer) {
const io = new Server(httpServer, { cors: { origin: '*', methods: ['GET', 'POST'] } })
io.use(validateToken)
io.on('connection', (socket: CustomSocket) => {
logger.info('New client connected', { socketId: socket.id, companyId: socket.companyId })
/* handlers ... */
})
return io
}
Client: esempi Socket.IO
import { io } from 'socket.io-client'
const socket = io(BASE_URL, { auth: { token: JWT } })
socket.on('connect', () => console.log('connected', socket.id))
socket.on('typing', d => console.log('typing', d))
socket.on('chat_response_start', () => console.log('start'))
socket.on('chat_response_chunk', ({ response }) => console.log('chunk', response))
socket.on('chat_response_end', () => console.log('end'))
socket.on('error', e => console.error('error', e))
socket.emit('create_thread', { agentId: 'agent_123', type: 'agent' })
socket.emit('chat_message', {
message: 'Ciao! Mostrami scarpe nere 42',
threadId: 'thread_abc',
collection_name: 'company123_agentABC',
agentId: 'agent_123',
companyName: 'Shop',
companyDescription: 'Ecommerce',
language: 'italian',
hasDocuments: false,
websiteUrl: 'https://shop.example.com',
laravelAppUrl: 'https://app.example.com',
extraInstructions: '',
assistantInstructions: '',
type: 'agent',
})
Streaming della risposta (eventi Socket)
socket.on('chat_message', async data => {
if (!socket.companyId) return socket.emit('error', { error: 'Unauthorized' })
const { message, threadId, collection_name, agentId /* ... */ } = data
socket.emit('typing', { isTyping: true })
const response = await chatApp.stream(
{ messages: [new HumanMessage(message)] },
{
configurable: {
thread_id: threadId,
agent_id: agentId,
collection_name /* ... */,
} as CustomConfigurable,
streamMode: 'messages',
}
)
let firstChunk = false
for await (const message of response) {
if (
(message[0] instanceof AIMessageChunk || message[0] instanceof AIMessage) &&
message[0].content.length > 0
) {
if (!firstChunk) {
firstChunk = true
socket.emit('typing', { isTyping: false })
socket.emit('chat_response_start')
}
socket.emit('chat_response_chunk', { response: message[0].content })
}
}
socket.emit('chat_response_end')
Ripresa di una Run aperta
Una Run è la risposta dell’assistente ancora in produzione per un messaggio del visitatore. Vive solo nel processo Node che l’ha avviata (main/src/server/runRegistry.ts). Un altro processo non la vede: restituisce lo storico già salvato, senza errore e senza attesa infinita.
Ricaricare il widget, o aprire un’altra scheda, riusa load_thread_messages (chat:read). Non esiste un evento di subscribe separato.
- Il server emette
thread_messages. Se la Run è in corso e l’ultima bollabotè lo stesso testo ancora in scrittura, quella bolla non è nello storico. Una risposta precedente che il nuovo testo si limita a continuare resta nello storico. - Se la Run è in corso o è fallita su questo processo,
runRelay.tsinvia poi gli eventi live:- testo ancora vuoto:
typing { isTyping: true }fino al primo pezzo; - testo già presente:
chat_response_start, un solochat_response_chunkcon tutto il testo finora, l’ultimotool_feedbackse c’è, poi solo i pezzi nuovi; - fine:
chat_response_end; - errore: il testo finora, poi
chat_response_endse il testo è stato mostrato, poierror.
- testo ancora vuoto:
- Se la Run è in pausa su un modulo (contatto, conferma azione, consenso visitatore), non parte uno stream di token. Si riapre il modulo come prima. Lo storico tiene il testo prodotto prima del modulo.
- Chiudere una vista non ferma la Run. Ogni vista si iscrive una volta: pezzi duplicati sulla stessa vista sono un bug.
- Un secondo
chat_messagementre la Run è aperta riceve{ error: 'run_open' }.
Il client del Chat SDK concatena i chunk. Se la privacy non è ancora accettata, start/chunk/end/tool/error restano in attesa e compaiono solo dopo l’accettazione, insieme allo storico.
Modulo di contatto (eventi HITL)
Quando l'agente invoca requestContactForm, il grafo LangGraph viene interrotto e il server emette eventi dedicati:
socket.on('contact_form_request', ({ requestId, openToken, exp }) => {
// Apri overlay modulo contatto nel widget
})
socket.emit('contact_form_submitted', { requestId, receipt })
socket.emit('contact_form_cancelled', { requestId })
socket.emit('contact_form_heartbeat', { requestId }) // reset TTL 5 min
Vedi: Contact Form HITL · Tool Feedback.
Creazione thread
- Via Socket: evento
create_thread(crea thread e registra conversazione in Laravel) - Via HTTP: endpoint dedicato.
app.post('/create-thread/:agentId', async (req, res) => {
const { agentId } = req.params
const { type } = req.query
const threadId = await chatService.createThread(agentId)
res.json({ threadId })
laravelService.createConversation(
{
assistant_or_agent_uuid: agentId,
conversation_uuid: threadId,
date_time: new Date().toISOString(),
sender: 'user',
},
type as AssistantType
)
})