document.addEventListener('DOMContentLoaded', () => { const userInput = document.getElementById('userInput'); const chatLogs = document.querySelectorAll('.chat-log'); const leftChatLog = chatLogs[0]; const rightChatLog = chatLogs[1]; let currentLeftChatModel = 'chief'; let currentRightChatModel = 'ceo'; let currentSessionId = null; let lastClickedSide = 'left'; let dynamicModelMapping = {}; // Загрузка названия текущего проекта async function loadCurrentProjectName() { try { const response = await fetch('/api/project/current'); if (!response.ok) return; const data = await response.json(); const projectNameEl = document.getElementById('current-project-name'); if ( projectNameEl && data.project_name && data.project_name !== 'Проект не выбран' ) { projectNameEl.textContent = `| ${data.project_name}`; projectNameEl.title = `Текущий проект: ${data.project_name}`; } } catch (error) { console.error('Ошибка загрузки проекта:', error); } } // Управление информ-окном function showInfoPanel() { const infoPanel = document.getElementById('info-panel'); const gcbWindow = document.getElementById('gcb-window'); if (infoPanel) infoPanel.classList.add('active'); if (gcbWindow) gcbWindow.classList.remove('active'); } function showGCBQueue() { const infoPanel = document.getElementById('info-panel'); const gcbWindow = document.getElementById('gcb-window'); if (infoPanel) infoPanel.classList.remove('active'); if (gcbWindow) gcbWindow.classList.add('active'); updateGCBQueue(); } // Загрузка контента в информ-окно async function loadInfoContent(infoType, additionalData = null) { try { const url = additionalData ? `/api/info/${infoType}?${new URLSearchParams(additionalData).toString()}` : `/api/info/${infoType}`; const response = await fetch(url); if (!response.ok) throw new Error(`HTTP ${response.status}`); const html = await response.text(); const infoPanel = document.getElementById('info-panel'); if (infoPanel) { infoPanel.innerHTML = html; showInfoPanel(); } } catch (error) { console.error(`Ошибка загрузки контента ${infoType}:`, error); const infoPanel = document.getElementById('info-panel'); if (infoPanel) { infoPanel.innerHTML = `
Чат очищен
`; break; case '/mode': const model = side === 'left' ? currentLeftChatModel : currentRightChatModel; addMessage( chatLog, 'Система', `Текущая модель: ${model}. Режим работы: AI-Collaboration.`, ); break; default: console.log('Неизвестная команда:', cmd); } } function showModal(title, content) { const modal = document.getElementById('soulModal'); const modalTitle = document.getElementById('modalTitle'); const modalBody = document.getElementById('modalBody'); if (!modal) return; modal.style.display = 'block'; if (modalTitle) modalTitle.textContent = title; if (modalBody) modalBody.innerHTML = content; } function showHelpModal() { const helpContent = `[INTRO] — роль модели[TASK] — задания/help | Справка |
/clear | Очистить |
/mode | Режим |
${data.summary || 'Нет данных'}
${res.output}`;
addMessage(leftChatLog, 'Gemini MCP', out);
}
};
}
async function handleSend(side) {
updateActiveUI(side);
const rawValue = userInput.value.trim();
if (!rawValue) return;
if (rawValue.startsWith('/')) {
handleSystemCommand(rawValue, side);
userInput.value = '';
return;
}
// Очистка от введённых вручную маркеров
const cleanMessage = rawValue
.replace(/^\[INTRO\]\s*/i, '')
.replace(/^\[TASK\]\s*/i, '');
const fullMessage = '[INTRO] ' + cleanMessage;
const chatLog = side === 'left' ? leftChatLog : rightChatLog;
const modelName =
side === 'left' ? currentLeftChatModel : currentRightChatModel;
const senderLabel = `Вы (${modelName})`;
addMessage(chatLog, senderLabel, cleanMessage);
userInput.value = '';
let modelKey = modelName;
if (side === 'left' && modelKey === 'gemini_direct') {
if (!geminiWS || geminiWS.readyState !== WebSocket.OPEN) {
connectGeminiWS();
return;
}
// Для консоли отправляем чистую команду БЕЗ [INTRO]
geminiWS.send(
JSON.stringify({
directive: {
action: 'shell',
tool: 'direct_command',
parameters: { command: cleanMessage },
},
}),
);
return;
}
try {
const response = await fetch('/api/secretary', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: fullMessage,
side: side,
model: modelKey,
session_id: currentSessionId,
}),
});
const data = await response.json();
if (data.session_id) currentSessionId = data.session_id;
if (data.response)
addMessage(chatLog, 'AI', data.response, data.pair_id, data.modelInfo);
else if (data.error)
addMessage(chatLog, 'Система', 'Ошибка: ' + data.error);
} catch (e) {
addMessage(chatLog, 'Система', 'Ошибка связи с сервером');
}
}
if (sendBtnLeft)
sendBtnLeft.addEventListener('click', () => {
lastClickedSide = 'left';
handleSend('left');
});
if (sendBtnRight)
sendBtnRight.addEventListener('click', () => {
lastClickedSide = 'right';
handleSend('right');
});
userInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
const now = Date.now();
if (now - lastEnterTime < 700) enterCount++;
else enterCount = 1;
lastEnterTime = now;
if (enterCount === 2) {
e.preventDefault();
handleSend(lastClickedSide);
enterCount = 0;
}
}
});
if (topChiefBtn)
topChiefBtn.addEventListener('click', () => {
currentLeftChatModel = 'chief';
updateActiveUI('left', 'chief');
addMessage(leftChatLog, 'Система', 'Шеф на связи.');
});
if (topCeoBtn)
topCeoBtn.addEventListener('click', () => {
currentRightChatModel = 'ceo';
updateActiveUI('right', 'ceo');
addMessage(rightChatLog, 'Система', 'СЕО на связи.');
});
if (topGeminiBtn)
topGeminiBtn.addEventListener('click', () => {
currentLeftChatModel = 'gemini_direct';
updateActiveUI('left', 'gemini');
addMessage(leftChatLog, 'Система', '[CONSOLE] Готов к исполнению задач.');
showGCBQueue(); // Показываем очередь GCB
connectGeminiWS();
});
if (topDoctorBtn)
topDoctorBtn.addEventListener('click', () => {
currentRightChatModel = 'doctor';
updateActiveUI('right', 'doctor');
addMessage(
rightChatLog,
'Система',
'Доктор на связи. Провести внеплановый медосмотр моделей?',
);
});
// Инициализация
loadCurrentProjectName();
showInfoPanel(); // Показываем информ-окно по умолчанию
document.querySelectorAll('.dept-btn').forEach((btn) => {
btn.addEventListener('click', () => {
let id = btn.classList.contains('dept-a')
? 'A'
: btn.classList.contains('dept-b')
? 'B'
: btn.classList.contains('dept-c')
? 'C'
: 'D';
currentLeftChatModel = `dept-${id}`;
updateActiveUI('left');
});
});
document.querySelectorAll('.model-btn').forEach((btn) => {
btn.addEventListener('click', () => {
const modelName = btn.dataset.model;
currentRightChatModel = modelName;
updateActiveUI('right');
addMessage(
rightChatLog,
'Система',
`Модель ${modelName} выбрана для диалога.`,
);
});
});
document.querySelectorAll('.mention-content a').forEach((link) => {
link.addEventListener('click', (e) => {
e.preventDefault();
const role = link.dataset.role;
const isCeo = link
.closest('.mention-menu')
.querySelector('.mention-btn')
.textContent.includes('СЕО');
if (isCeo) {
currentRightChatModel = role;
updateActiveUI('right');
addMessage(
rightChatLog,
'Система',
`Модель ${role} выбрана из меню СЕО.`,
);
} else {
currentLeftChatModel = role;
updateActiveUI('left');
addMessage(leftChatLog, 'Система', `Роль ${role} выбрана из меню ШЕФ.`);
}
});
});
const modal = document.getElementById('soulModal');
const closeModal = document.getElementById('closeModal');
if (closeModal) closeModal.onclick = () => (modal.style.display = 'none');
window.onclick = (e) => {
if (e.target == modal) modal.style.display = 'none';
};
// Инициализация
loadDynamicModelMapping();
updateActiveUI('left');
connectGeminiWS(); // Автоматическое подключение MCP
updateGCBQueue();
setInterval(updateGCBQueue, 5000);
async function updateGCBQueue() {
try {
const response = await fetch('/api/gcb/queue');
const queue = await response.json();
const container = document.getElementById('gcbQueue');
if (!container || !Array.isArray(queue)) return;
if (queue.length === 0) {
initDashboard();
return;
}
container.innerHTML = queue
.reverse()
.map(
(item) => `