code refactoring and agent improvement

This commit is contained in:
DenAntonov
2025-06-14 23:35:48 +03:00
parent bd0b11dc4a
commit 5665c4bf1e
9 changed files with 111 additions and 487 deletions

View File

@@ -1,7 +1,12 @@
const { getSupabaseClient, initializationPromise } = require('./supabaseClient');
const MODERATION_CONFIG = require('./chat-ai-agent/moderation-config');
const { getGigaAuth } = require('./get-constants');
const { moderationText } = require('./chat-ai-agent/chat-moderation');
const { getIo } = require('../../../io');
async function getGigaKey() {
const GIGA_AUTH = await getGigaAuth();
return GIGA_AUTH;
}
class ChatPollingHandler {
constructor() {
@@ -520,8 +525,8 @@ class ChatPollingHandler {
// Очистка старых событий
cleanupOldEvents() {
const now = new Date();
const MAX_EVENT_AGE = 24 * 60 * 60 * 1000; // 24 часа
const INACTIVE_USER_THRESHOLD = 60 * 60 * 1000; // 1 час
const MAX_EVENT_AGE = 1 * 60 * 60 * 1000; // 1 час
const INACTIVE_USER_THRESHOLD = 30 * 60 * 1000; // 30 минут
// Очищаем старые события
this.userEventQueues.forEach((eventQueue, user_id) => {
@@ -618,13 +623,6 @@ class ChatPollingHandler {
return;
}
console.log(`📡 [Supabase Real-time] === ПОЛУЧЕНО НОВОЕ СООБЩЕНИЕ ===`);
console.log(`📡 [Supabase Real-time] ID сообщения: ${newMessage.id}`);
console.log(`📡 [Supabase Real-time] Чат ID: ${newMessage.chat_id}`);
console.log(`📡 [Supabase Real-time] Пользователь ID: ${newMessage.user_id}`);
console.log(`📡 [Supabase Real-time] Текст: "${newMessage.text?.substring(0, 100)}${(newMessage.text?.length || 0) > 100 ? '...' : ''}"`);
console.log(`📡 [Supabase Real-time] Время: ${new Date().toISOString()}`);
// Получаем профиль пользователя
const { data: userProfile, error: profileError } = await supabase
.from('user_profiles')
@@ -634,9 +632,7 @@ class ChatPollingHandler {
if (profileError) {
console.error('❌ [Supabase] Ошибка получения профиля пользователя:', profileError);
} else {
console.log(`✅ [Supabase Real-time] Профиль пользователя получен: ${userProfile.full_name || 'No name'}`);
}
}
// Объединяем сообщение с профилем
const messageWithProfile = {
@@ -644,40 +640,26 @@ class ChatPollingHandler {
user_profiles: userProfile || null
};
// Отправляем сообщение всем участникам чата
console.log(`📤 [Supabase Real-time] Отправляем сообщение участникам чата ${newMessage.chat_id}...`);
// Отправляем сообщение всем участникам чат
this.broadcastToChat(newMessage.chat_id, 'new_message', {
message: messageWithProfile,
timestamp: new Date()
});
console.log(`✅ [Supabase Real-time] Сообщение отправлено участникам чата`);
// === ЗАПУСК МОДЕРАЦИИ ===
if (MODERATION_CONFIG.MODERATION_ENABLED) {
console.log(`🛡️ [Supabase Real-time] Модерация включена - планируем проверку сообщения`);
console.log(`🛡️ [Supabase Real-time] Задержка модерации: ${MODERATION_CONFIG.MODERATION_DELAY}мс`);
if (MODERATION_CONFIG.MODERATION_DELAY === 0) {
console.log(`⚡ [Supabase Real-time] Мгновенная модерация - запускаем setImmediate`);
setImmediate(() => {
console.log(`⚡ [Supabase Real-time] setImmediate: запускаем модерацию сообщения ${newMessage.id}`);
this.moderateMessage(newMessage.id, newMessage.text, newMessage.chat_id);
});
} else {
console.log(`⏰ [Supabase Real-time] Отложенная модерация - устанавливаем setTimeout`);
const timeoutId = setTimeout(() => {
console.log(`⏰ [Supabase Real-time] setTimeout: время пришло, запускаем модерацию сообщения ${newMessage.id}`);
console.log(`⏰ [Supabase Real-time] Фактическое время: ${new Date().toISOString()}`);
this.moderateMessage(newMessage.id, newMessage.text, newMessage.chat_id);
}, MODERATION_CONFIG.MODERATION_DELAY);
console.log(`⏰ [Supabase Real-time] Timeout ID: ${timeoutId}`);
console.log(`⏰ [Supabase Real-time] Ожидаемое время срабатывания: ${new Date(Date.now() + MODERATION_CONFIG.MODERATION_DELAY).toISOString()}`);
}
console.log(`🛡️ [Supabase Real-time] Модерация запланирована для сообщения ${newMessage.id}`);
} else {
console.log(`🔓 [Supabase Real-time] Модерация отключена - сообщение не будет проверяться`);
}
} catch (callbackError) {
@@ -704,13 +686,6 @@ class ChatPollingHandler {
return;
}
console.log(`🔄 [Supabase Real-time] === ПОЛУЧЕНО ОБНОВЛЕНИЕ СООБЩЕНИЯ ===`);
console.log(`🔄 [Supabase Real-time] ID сообщения: ${updatedMessage.id}`);
console.log(`🔄 [Supabase Real-time] Чат ID: ${updatedMessage.chat_id}`);
console.log(`🔄 [Supabase Real-time] Пользователь ID: ${updatedMessage.user_id}`);
console.log(`🔄 [Supabase Real-time] Обновленный текст: "${updatedMessage.text?.substring(0, 100)}${(updatedMessage.text?.length || 0) > 100 ? '...' : ''}"`);
console.log(`🔄 [Supabase Real-time] Время обновления: ${new Date().toISOString()}`);
// Получаем профиль пользователя
const { data: userProfile, error: profileError } = await supabase
.from('user_profiles')
@@ -728,14 +703,11 @@ class ChatPollingHandler {
user_profiles: userProfile || null
};
// Отправляем обновление всем участникам чата
console.log(`📤 [Supabase Real-time] Отправляем обновление участникам чата ${updatedMessage.chat_id}...`);
// Отправляем обновление всем участникам чат
this.broadcastToChat(updatedMessage.chat_id, 'message_updated', {
message: messageWithProfile,
timestamp: new Date()
});
console.log(`✅ [Supabase Real-time] Обновление отправлено участникам чата`);
console.log(`📊 [Supabase Real-time] Событие: message_updated`);
} catch (callbackError) {
console.error('❌ [Supabase] Ошибка в обработчике обновления сообщения:', callbackError);
@@ -768,24 +740,15 @@ class ChatPollingHandler {
const moderationStartTime = Date.now();
try {
console.log(`🔍 [Moderation] === НАЧАЛО МОДЕРАЦИИ СООБЩЕНИЯ ${messageId} ===`);
console.log(`🔍 [Moderation] Chat ID: ${chatId}`);
console.log(`🔍 [Moderation] Длина текста: ${messageText.length} символов`);
console.log(`🔍 [Moderation] Превью текста: "${messageText.length > 100 ? messageText.substring(0, 100) + '...' : messageText}"`);
console.log(`🔍 [Moderation] Время запуска: ${new Date().toISOString()}`);
// Вызываем функцию модерации
console.log(`🔍 [Moderation] Передаем сообщение AI агенту для анализа...`);
console.log(`🔍 [Moderation] Функция moderationText доступна: ${typeof moderationText}`);
console.log(`🔍 [Moderation] Тип сообщения: ${typeof messageText}`);
console.log(`🔍 [Moderation] Текст сообщения: "${messageText}"`);
let comment, isApproved, finalMessage;
const GIGA_AUTH = await getGigaKey();
console.log(GIGA_AUTH)
try {
const result = await moderationText('', messageText);
console.log(`🔍 [Moderation] Результат от AI агента получен:`, result);
const result = await moderationText('', messageText, GIGA_AUTH);
[comment, isApproved, finalMessage] = result;
console.log(`🔍 [Moderation] Распакованные значения: comment="${comment}", isApproved=${isApproved}, finalMessage="${finalMessage}"`);
} catch (moderationError) {
console.error(`❌ [Moderation] Ошибка при вызове AI агента:`, moderationError);
console.error(`❌ [Moderation] Stack trace:`, moderationError.stack);
@@ -797,11 +760,6 @@ class ChatPollingHandler {
}
const moderationTime = Date.now() - moderationStartTime;
console.log(`📝 [Moderation] === РЕЗУЛЬТАТ МОДЕРАЦИИ СООБЩЕНИЯ ${messageId} ===`);
console.log(`📝 [Moderation] Время модерации: ${moderationTime}мс`);
console.log(`📝 [Moderation] Решение: ${isApproved ? '✅ ОДОБРЕНО' : '❌ ОТКЛОНЕНО'}`);
console.log(`📝 [Moderation] Комментарий: "${comment || 'отсутствует'}"`);
console.log(`📝 [Moderation] Финальный текст: "${finalMessage}"`);
if (isApproved) {
console.log(`📝 [Moderation] Действие: сообщение остается без изменений`);
@@ -842,19 +800,9 @@ class ChatPollingHandler {
if (error) {
console.error(`❌ [Moderation] Ошибка обновления сообщения ${messageId}:`, error);
console.error(`❌ [Moderation] Детали ошибки:`, error);
} else {
console.log(`✅ [Moderation] Сообщение ${messageId} успешно обновлено в базе данных`);
console.log(`✅ [Moderation] Старый текст заменен на: "${updatedMessage.text}"`);
console.log(`✅ [Moderation] Время обновления: ${updatedMessage.updated_at || 'не указано'}`);
}
} else {
console.log(`✅ [Moderation] Сообщение ${messageId} прошло модерацию - никаких действий не требуется`);
}
const totalTime = Date.now() - moderationStartTime;
console.log(`🔍 [Moderation] === МОДЕРАЦИЯ СООБЩЕНИЯ ${messageId} ЗАВЕРШЕНА ===`);
console.log(`🔍 [Moderation] Общее время процесса: ${totalTime}мс`);
console.log(`🔍 [Moderation] Время завершения: ${new Date().toISOString()}`);
}
}
} catch (error) {
const totalTime = Date.now() - moderationStartTime;