// Pool de Conexões WebSocket Multi-Estações // Map const stationPool = new Map(); const reconnectTimers = new Map(); // Variáveis de compatibilidade legada let ws = null; let currentPin = null; let currentMachine = 'Desconhecida'; let pendingPrompts = new Map(); let agents = []; let activeChatAgent = null; let activeChatPin = null; let activeChatMachine = ''; const chatHistories = new Map(); // agentName ou `${pin}:${agentName}` -> Array of { role, text, timestamp, isTerminalSnapshot, attachment } const pinScreen = document.getElementById('pin-screen'); const appScreen = document.getElementById('app-screen'); const pinInput = document.getElementById('pin-input'); const btnConnect = document.getElementById('btn-connect'); const btnLogout = document.getElementById('btn-logout'); const btnLogoutScreen = document.getElementById('btn-logout-screen'); const sessionPinDisplay = document.getElementById('session-pin-display'); const btnClearStored = document.getElementById('btn-clear-stored'); const statusBadge = document.getElementById('status-badge'); const statusText = document.getElementById('status-text'); const pushBanner = document.getElementById('push-banner'); const btnEnablePush = document.getElementById('btn-enable-push'); // Elementos de Versão e Sobre o App const brandHeader = document.getElementById('brand-header'); const modalVersion = document.getElementById('modal-version'); const btnCloseVersionModal = document.getElementById('btn-close-version-modal'); const btnCheckUpdateManual = document.getElementById('btn-check-update-manual'); const appVersionVal = document.getElementById('app-version-val'); const appBuildVal = document.getElementById('app-build-val'); const appDateVal = document.getElementById('app-date-val'); const appChecksumVal = document.getElementById('app-checksum-val'); const appChecksumRow = document.getElementById('app-checksum-row'); let currentBuildId = null; let appVersionInfo = { version: '1.0.2', buildId: '510c212a', releasedAt: '2026-11-10T23:59:21.219Z', checksum: '' }; // Elementos de Múltiplas Estações const stationsContainer = document.getElementById('stations-container'); const stationsCountBadge = document.getElementById('stations-count-badge'); const stationSelect = document.getElementById('station-select'); const btnAddStation = document.getElementById('btn-add-station'); const modalStation = document.getElementById('modal-station'); const btnCloseStationModal = document.getElementById('btn-close-station-modal'); const stationNameInput = document.getElementById('station-name-input'); const stationPinInput = document.getElementById('station-pin-input'); const btnSaveStation = document.getElementById('btn-save-station'); // Elementos legados para compatibilidade com testes anteriores const machineNameEl = document.getElementById('machine-name'); const agentsListEl = document.getElementById('agents-list'); const cardsContainer = document.getElementById('cards-container'); // Chat Drawer Elements const chatDrawer = document.getElementById('chat-drawer'); const chatBackdrop = document.getElementById('chat-backdrop'); const btnCloseChat = document.getElementById('btn-close-chat'); const btnRestartTerminal = document.getElementById('btn-restart-terminal'); const chatAgentNameEl = document.getElementById('chat-agent-name'); const chatAgentStatusDot = document.getElementById('chat-agent-status-dot'); const chatAgentSubtitle = document.getElementById('chat-agent-subtitle'); const chatThinkingBanner = document.getElementById('chat-thinking-banner'); const chatThinkingText = document.getElementById('chat-thinking-text'); const chatMessagesEl = document.getElementById('chat-messages'); const btnChatScrollBottom = document.getElementById('btn-chat-scroll-bottom'); const chatTerminalCollapsible = document.getElementById('chat-terminal-collapsible'); const chatTerminalToggleBtn = document.getElementById('chat-terminal-toggle-btn'); const chatTerminalCollapsibleContent = document.getElementById('chat-terminal-collapsible-content'); const chatTerminalOutputRaw = document.getElementById('chat-terminal-output-raw'); const chatNotifToggleBtn = document.getElementById('chat-notif-toggle-btn'); const chatTuiPanel = document.getElementById('chat-tui-panel'); const chatTuiTitle = document.getElementById('chat-tui-title'); const chatTuiHint = document.getElementById('chat-tui-hint'); const chatTuiOptionsEl = document.getElementById('chat-tui-options'); const chatTuiKeypad = document.querySelector('.chat-tui-keypad'); const btnTuiToggle = document.getElementById('btn-tui-toggle'); // Sistema de Notificações com Mute Granular por Agente (Default: ATIVADO) const NOTIF_MUTED_STORAGE_KEY = 'maestri_terminal_notif_muted'; let terminalMutedSettings = new Set(); try { if (typeof localStorage !== 'undefined') { const rawMuted = localStorage.getItem(NOTIF_MUTED_STORAGE_KEY); if (rawMuted) { const parsed = JSON.parse(rawMuted); if (Array.isArray(parsed)) { terminalMutedSettings = new Set(parsed); } } } } catch (e) { console.warn('[Notif] Falha ao carregar mute do localStorage:', e); } function saveTerminalMutedSettings() { try { if (typeof localStorage !== 'undefined') { localStorage.setItem(NOTIF_MUTED_STORAGE_KEY, JSON.stringify(Array.from(terminalMutedSettings))); } } catch (e) { console.warn('[Notif] Falha ao salvar mute no localStorage:', e); } } // Map para compatibilidade const terminalNotificationSettings = new Map(); const agentThinkingStates = new Map(); // pin:agentName ou agentName -> boolean const lastThinkingDoneNotifTimes = new Map(); // pin:agentName -> timestamp const agentMenuStates = new Map(); // pin:agentName ou agentName -> boolean const agentPausedStates = new Map(); // pin:agentName ou agentName -> boolean const unreadResponseCounts = new Map(); // pin:agentName ou agentName -> number const lastReadTimestamps = new Map(); // pin:agentName ou agentName -> timestamp let isTuiPanelManualOpen = false; let currentInteractiveMenu = null; function getAgentScopedKey(agentName, pin) { return pin ? `${pin}:${agentName}` : agentName; } function getAgentChatHistory(agentName, pin) { if (!agentName) return []; return chatHistories.get(getAgentScopedKey(agentName, pin)) || []; } function setAgentChatHistory(agentName, pin, hist) { if (!agentName) return; chatHistories.set(getAgentScopedKey(agentName, pin), hist); } window.getAgentChatHistory = getAgentChatHistory; window.setAgentChatHistory = setAgentChatHistory; function hasUnreadResponseForAgent(agentName, pin) { if (!agentName) return false; const key = getAgentScopedKey(agentName, pin); if ((unreadResponseCounts.get(key) || 0) > 0) { return true; } const hist = getAgentChatHistory(agentName, pin); if (!hist || !Array.isArray(hist) || hist.length === 0) return false; const convMsgs = hist.filter(m => !m.isTerminalSnapshot); if (convMsgs.length === 0) return false; const lastMsg = convMsgs[convMsgs.length - 1]; if (lastMsg.role !== 'agent') return false; const lastRead = lastReadTimestamps.get(key) || 0; return lastMsg.timestamp > lastRead; } function markAgentResponsesAsRead(agentName, pin) { if (!agentName) return; const key = getAgentScopedKey(agentName, pin); unreadResponseCounts.delete(key); lastReadTimestamps.set(key, Date.now()); } function clearStationAgentStates(pin) { if (!pin) return; const prefix = `${pin}:`; for (const key of Array.from(agentMenuStates.keys())) { if (key.startsWith(prefix)) { agentMenuStates.delete(key); } } for (const key of Array.from(agentPausedStates.keys())) { if (key.startsWith(prefix)) { agentPausedStates.delete(key); } } for (const key of Array.from(agentThinkingStates.keys())) { if (key.startsWith(prefix)) { agentThinkingStates.delete(key); } } for (const key of Array.from(lastThinkingDoneNotifTimes.keys())) { if (key.startsWith(prefix)) { lastThinkingDoneNotifTimes.delete(key); } } } function isTerminalNotifEnabled(agentName, pin) { if (!agentName) return true; const key = getAgentScopedKey(agentName, pin); if (terminalMutedSettings.has(key)) return false; if (pin && terminalMutedSettings.has(agentName)) return false; return true; } function setTerminalNotifEnabled(agentName, pin, enabled) { if (!agentName) return; const key = getAgentScopedKey(agentName, pin); terminalNotificationSettings.set(key, Boolean(enabled)); if (enabled) { terminalMutedSettings.delete(key); if (pin) terminalMutedSettings.delete(agentName); } else { terminalMutedSettings.add(key); } saveTerminalMutedSettings(); } function notifyAgentIfEnabled(pin, agentName, toastMessage, level = 'warning', vibratePattern = [80, 50, 80]) { if (!isTerminalNotifEnabled(agentName, pin)) return; playChimeSound(); showToast(toastMessage, level); if (typeof navigator !== 'undefined' && navigator.vibrate) { navigator.vibrate(vibratePattern); } try { if (typeof document !== 'undefined' && document.hidden && typeof Notification !== 'undefined' && Notification.permission === 'granted') { new Notification(`Maestri Remote: ${agentName}`, { body: toastMessage.replace(/^[🔔⏸️⚡🎛️💬✅\s]+/, ''), icon: '/icon.svg', tag: `agent-${agentName}` }); } } catch (notifErr) {} } const THINKING_DONE_NOTIF_DEBOUNCE_MS = 4000; function notifyAgentTaskCompletedIfNeeded(pin, agentName, { markUnread = true } = {}) { if (!agentName) return false; const key = getAgentScopedKey(agentName, pin); const now = Date.now(); const lastSentAt = lastThinkingDoneNotifTimes.get(key) || 0; if (now - lastSentAt < THINKING_DONE_NOTIF_DEBOUNCE_MS) { return false; } lastThinkingDoneNotifTimes.set(key, now); const isChatOpen = activeChatAgent === agentName && (!activeChatPin || String(activeChatPin) === String(pin)) && chatDrawer && chatDrawer.style.display === 'flex'; if (markUnread && !isChatOpen) { const cur = unreadResponseCounts.get(key) || 0; unreadResponseCounts.set(key, cur + 1); } notifyAgentIfEnabled(pin, agentName, `🔔 ${agentName}: Resposta concluída!`, 'info', [80, 50, 80]); return true; } const lastMenuAlertTimes = new Map(); function updateAgentMenuStateAndAlert(pin, agentName, hasMenu) { if (!agentName) return false; const key = getAgentScopedKey(agentName, pin); const prev = agentMenuStates.get(key) === true; const next = !!hasMenu; agentMenuStates.set(key, next); if (!prev && next) { const now = Date.now(); const lastAlert = lastMenuAlertTimes.get(key) || 0; if (now - lastAlert >= 4000) { lastMenuAlertTimes.set(key, now); notifyAgentIfEnabled(pin, agentName, `🔔 ${agentName}: Aguardando ação em menu interativo!`, 'warning', [80, 50, 80]); } } return prev !== next; } function updateAgentPausedStateAndAlert(pin, agentName, isPaused, pauseResetTime) { if (!agentName) return false; const key = getAgentScopedKey(agentName, pin); const prev = agentPausedStates.get(key) === true; const next = Boolean(isPaused); agentPausedStates.set(key, next); if (!prev && next) { const timeHint = pauseResetTime ? ` (até ${pauseResetTime})` : ''; notifyAgentIfEnabled(pin, agentName, `⏸️ ${agentName}: Pausado por limite de cota${timeHint}!`, 'warning', [100, 60, 100]); } return prev !== next; } function playChimeSound() { try { const AudioCtx = window.AudioContext || window.webkitAudioContext; if (!AudioCtx) return; const ctx = new AudioCtx(); const osc = ctx.createOscillator(); const gain = ctx.createGain(); osc.type = 'sine'; const now = ctx.currentTime; osc.frequency.setValueAtTime(880, now); // Nota A5 osc.frequency.exponentialRampToValueAtTime(1320, now + 0.12); // Salto harmônico E6 gain.gain.setValueAtTime(0.2, now); gain.gain.exponentialRampToValueAtTime(0.001, now + 0.25); osc.connect(gain); gain.connect(ctx.destination); osc.start(now); osc.stop(now + 0.25); } catch (err) { console.warn('[Audio] Erro ao sintetizar chime:', err); } } function syncChatHeaderNotifButton() { if (!chatNotifToggleBtn || !activeChatAgent) return; const isEnabled = isTerminalNotifEnabled(activeChatAgent, activeChatPin); chatNotifToggleBtn.textContent = isEnabled ? '🔔' : '🔕'; chatNotifToggleBtn.className = `btn-icon btn-chat-notif-toggle ${isEnabled ? '' : 'muted'}`; chatNotifToggleBtn.title = isEnabled ? 'Notificações ativadas para este agente (toque para silenciar)' : 'Notificações desativadas para este agente (toque para ativar)'; } if (chatNotifToggleBtn) { chatNotifToggleBtn.addEventListener('click', () => { if (!activeChatAgent) return; const cur = isTerminalNotifEnabled(activeChatAgent, activeChatPin); setTerminalNotifEnabled(activeChatAgent, activeChatPin, !cur); syncChatHeaderNotifButton(); renderAllStations(); }); } if (chatTerminalToggleBtn && chatTerminalCollapsibleContent) { chatTerminalToggleBtn.addEventListener('click', () => { const isHidden = chatTerminalCollapsibleContent.style.display === 'none'; chatTerminalCollapsibleContent.style.display = isHidden ? 'block' : 'none'; chatTerminalToggleBtn.setAttribute('aria-expanded', isHidden ? 'true' : 'false'); }); } let isUserScrolledUp = false; let isWaitingChatReply = false; const chatForm = document.getElementById('chat-form'); const chatInput = document.getElementById('chat-input'); const chatFileInput = document.getElementById('chat-file-input'); const chatCameraInput = document.getElementById('chat-camera-input'); const chatGalleryInput = document.getElementById('chat-gallery-input'); const attachMenu = document.getElementById('attach-menu'); const attachBackdrop = document.getElementById('attach-backdrop'); const btnAttachCamera = document.getElementById('btn-attach-camera'); const btnAttachGallery = document.getElementById('btn-attach-gallery'); const btnAttachFile = document.getElementById('btn-attach-file'); const btnAttach = document.getElementById('btn-attach'); const btnVoice = document.getElementById('btn-voice'); const attachmentPreviewBar = document.getElementById('attachment-preview-bar'); const attachmentList = document.getElementById('attachment-list'); const attachmentSummaryBadge = document.getElementById('attachment-summary-badge'); const btnClearAllAttachments = document.getElementById('btn-clear-all-attachments'); const attachmentThumbWrapper = document.getElementById('attachment-thumb-wrapper'); const attachmentNameEl = document.getElementById('attachment-name'); const attachmentSizeEl = document.getElementById('attachment-size'); const btnRemoveAttachment = document.getElementById('btn-remove-attachment'); let currentAttachments = []; let currentAttachment = null; let speechRecognizer = null; let isRecording = false; let mediaRecorder = null; let audioChunks = []; function getRelayWsUrl() { const host = window.location.host; const isLocal = !host || host.includes('localhost') || host.includes('127.0.0.1') || window.location.protocol === 'file:' || window.location.protocol === 'capacitor:'; if (isLocal) { return 'wss://remote.winicomw.ddnsfree.com/ws/client'; } const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; return `${protocol}//${host}/ws/client`; } function showToast(msg, type = 'info') { try { if (typeof document === 'undefined') return; let toast = document.getElementById('app-toast'); if (!toast) { toast = document.createElement('div'); toast.id = 'app-toast'; toast.style.cssText = 'position:fixed;bottom:24px;left:50%;transform:translateX(-50%);background:#1e293b;color:#f8fafc;padding:0.6rem 1.2rem;border-radius:24px;font-size:0.85rem;font-weight:600;box-shadow:0 10px 25px rgba(0,0,0,0.5);border:1px solid #334155;z-index:9999;transition:opacity 0.2s ease;pointer-events:none;'; document.body.appendChild(toast); } toast.textContent = msg; if (type === 'warning') toast.style.borderColor = '#f59e0b'; else if (type === 'error') toast.style.borderColor = '#ef4444'; else if (type === 'success') toast.style.borderColor = '#34d399'; else toast.style.borderColor = '#38bdf8'; toast.style.opacity = '1'; clearTimeout(toast._timer); toast._timer = setTimeout(() => { toast.style.opacity = '0'; }, 2500); } catch (e) {} } // ========================================== // Gerenciamento de Múltiplas Estações // ========================================== function isInvalidMachineName(name) { if (!name || typeof name !== 'string') return true; const lower = name.trim().toLowerCase(); return ( lower === '' || lower.includes('aguardando') || lower === 'workstation' || lower === 'desconhecida' || lower === 'null' || lower === 'undefined' ); } function getSavedStations() { let stations = []; try { const raw = localStorage.getItem('maestri_stations'); if (raw) { const parsed = JSON.parse(raw); if (Array.isArray(parsed) && parsed.length > 0) { stations = parsed.map(s => { if (isInvalidMachineName(s.name)) { s.name = 'Estação ' + s.pin; } return s; }); } } } catch (e) {} const storedPin = localStorage.getItem('maestri_pin'); if (storedPin && !stations.some(s => s.pin === storedPin)) { stations.push({ id: 'station-' + storedPin, name: 'Estação ' + storedPin, pin: storedPin }); } return stations; } function saveStationsList(stations) { try { localStorage.setItem('maestri_stations', JSON.stringify(stations)); } catch (e) {} } function cacheStationAgents(pin, agents) { if (!pin || !Array.isArray(agents) || agents.length === 0) return; try { const stations = getSavedStations(); const st = stations.find(s => String(s.pin) === String(pin)); if (st) { st.cachedAgents = agents; saveStationsList(stations); } } catch (e) {} } function registerOrUpdateStation(pin, name) { if (!pin) return; const stations = getSavedStations(); const existingIdx = stations.findIndex(s => s.pin === pin); const hasValidName = !isInvalidMachineName(name); if (existingIdx >= 0) { if (hasValidName) { stations[existingIdx].name = name.trim(); } } else { stations.push({ id: 'station-' + pin, name: hasValidName ? name.trim() : ('Estação ' + pin), pin }); } saveStationsList(stations); renderStationsSelect(); } function renameStation(pin, newName) { if (!pin || !newName || typeof newName !== 'string') return; const trimmed = newName.trim(); if (!trimmed) return; registerOrUpdateStation(pin, trimmed); const entry = stationPool.get(pin); if (entry) { entry.name = trimmed; } renderAllStations(); renderStationsSelect(); showToast(`Estação renomeada para "${trimmed}"`, 'info'); } window.renameStation = renameStation; function renderStationsSelect() { if (!stationSelect) return; const stations = getSavedStations(); stationSelect.innerHTML = ''; if (stations.length === 0) { const opt = document.createElement('option'); opt.value = ''; opt.textContent = 'Nenhuma estação cadastrada'; stationSelect.appendChild(opt); } else { stations.forEach(s => { const opt = document.createElement('option'); opt.value = s.pin; const displayName = s.name || ('Estação ' + s.pin); opt.textContent = `🖥️ ${displayName} (${s.pin})`; if (s.pin === currentPin) { opt.selected = true; } stationSelect.appendChild(opt); }); } const optAdd = document.createElement('option'); optAdd.value = '__add_new__'; optAdd.textContent = '➕ Adicionar nova estação...'; stationSelect.appendChild(optAdd); } function closeStationModal() { if (modalStation) modalStation.style.display = 'none'; } window.closeStationModal = closeStationModal; function setupStationEvents() { if (stationSelect) { stationSelect.addEventListener('change', () => { const selectedValue = stationSelect.value; if (selectedValue === '__add_new__') { if (modalStation) { modalStation.style.display = 'flex'; if (stationNameInput) stationNameInput.value = ''; if (stationPinInput) { stationPinInput.value = ''; setTimeout(() => stationPinInput.focus(), 150); } } } }); } if (btnAddStation && modalStation) { const handleOpenModal = (e) => { if (e) e.preventDefault(); modalStation.style.display = 'flex'; if (stationNameInput) stationNameInput.value = ''; if (stationPinInput) stationPinInput.value = ''; setTimeout(() => { if (stationNameInput) stationNameInput.focus(); }, 100); }; btnAddStation.addEventListener('click', handleOpenModal); } if (btnCloseStationModal && modalStation) { const handleClose = (e) => { if (e) e.preventDefault(); closeStationModal(); }; btnCloseStationModal.addEventListener('click', handleClose); } if (modalStation) { modalStation.addEventListener('click', (e) => { if (e.target === modalStation) closeStationModal(); }); } let isSavingStation = false; const handleSaveStation = (e) => { if (e) e.preventDefault(); if (isSavingStation) return; isSavingStation = true; setTimeout(() => { isSavingStation = false; }, 350); const pin = stationPinInput ? stationPinInput.value.trim() : ''; const name = stationNameInput ? stationNameInput.value.trim() : ''; if (!pin || pin.length < 4) { if (stationPinInput) { stationPinInput.style.borderColor = '#ef4444'; stationPinInput.focus(); setTimeout(() => { stationPinInput.style.borderColor = ''; }, 1500); } showToast('Digite um PIN válido de pelo menos 4 dígitos.', 'warning'); return; } const label = name || ('Estação ' + pin); registerOrUpdateStation(pin, label); closeStationModal(); showToast(`Conectando à ${label}...`, 'info'); connectStation(pin, label); }; const formStation = document.getElementById('form-station'); if (formStation) { formStation.addEventListener('submit', handleSaveStation); } if (btnSaveStation) { btnSaveStation.addEventListener('click', handleSaveStation); } } // ========================================== // Conexão WebSocket Multi-Estações em Pool // ========================================== function connectToRelay(pin, name) { registerOrUpdateStation(pin, name || ('Estação ' + pin)); connectStation(pin, name); } function connectStation(pin, initialName) { if (!pin) return; const existingTimer = reconnectTimers.get(pin); if (existingTimer) { clearTimeout(existingTimer); reconnectTimers.delete(pin); } let entry = stationPool.get(pin); if (!entry) { const savedSt = getSavedStations().find(s => String(s.pin) === String(pin)); entry = { pin, name: initialName || ('Estação ' + pin), machineName: initialName || ('Estação ' + pin), ws: null, status: 'connecting', agents: (savedSt && Array.isArray(savedSt.cachedAgents)) ? savedSt.cachedAgents : [], pendingPrompts: new Map() }; stationPool.set(pin, entry); } if (entry.ws && (entry.ws.readyState === WebSocket.OPEN || entry.ws.readyState === WebSocket.CONNECTING)) { return; } if (entry.ws) { try { entry.ws.onclose = null; entry.ws.onerror = null; entry.ws.close(); } catch (e) {} entry.ws = null; } entry.status = 'connecting'; renderAllStations(); const wsUrl = getRelayWsUrl(); let socket; try { socket = new WebSocket(wsUrl); } catch (err) { console.error(`[App] Falha ao abrir WebSocket para PIN ${pin}:`, err); entry.status = 'offline'; renderAllStations(); return; } entry.ws = socket; ws = socket; // Sync legado currentPin = pin; socket.onopen = () => { console.log('[App] Conectado ao Relay para o PIN', pin); socket.send(JSON.stringify({ type: 'AUTH_CLIENT', pin })); }; socket.onmessage = (event) => { try { const msg = JSON.parse(event.data); handleStationMessage(pin, msg); } catch (err) { console.error(`[App] Erro ao processar mensagem do PIN ${pin}:`, err); } }; socket.onclose = () => { entry.status = 'offline'; if (activeChatAgent && (!activeChatPin || String(activeChatPin) === String(pin))) { resetRestartButtonState(); } renderAllStations(); const saved = getSavedStations(); if (saved.some(s => s.pin === pin) && appScreen && appScreen.style.display === 'block') { const t = setTimeout(() => { connectStation(pin, entry.name); }, 4000); reconnectTimers.set(pin, t); } }; socket.onerror = (err) => { console.error(`[App] Erro de WebSocket no PIN ${pin}:`, err); }; } // ========================================== // Resiliência de Ciclo de Vida Móvel (Auto-Resume) // ========================================== let lastMobileResumeTime = 0; function handleMobileResume() { const now = Date.now(); if (now - lastMobileResumeTime < 350) { return; } lastMobileResumeTime = now; executeMobileResume(); } function executeMobileResume() { console.log('[App:Lifecycle] Retomada de ciclo de vida móvel detectada. Verificando conexões...'); let reconnectedAny = false; stationPool.forEach((entry, pin) => { const wsDead = !entry.ws || entry.ws.readyState === WebSocket.CLOSED || entry.ws.readyState === WebSocket.CLOSING; if (wsDead) { console.log(`[App:Lifecycle] Conexão inativa para PIN ${pin}. Reconectando imediatamente.`); connectStation(pin, entry.name); reconnectedAny = true; } else if (entry.ws && entry.ws.readyState === WebSocket.OPEN) { try { entry.ws.send(JSON.stringify({ type: 'GET_AGENTS' })); if (activeChatAgent && (!activeChatPin || activeChatPin === pin)) { entry.ws.send(JSON.stringify({ type: 'GET_AGENT_TERMINAL', agentName: activeChatAgent })); } } catch (e) { console.warn(`[App:Lifecycle] Falha ao enviar keepalive para PIN ${pin}:`, e); connectStation(pin, entry.name); reconnectedAny = true; } } }); if (reconnectedAny) { showToast('🟢 Conexão restabelecida', 'info'); } } if (typeof document !== 'undefined') { document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') { handleMobileResume(); } }); } if (typeof window !== 'undefined') { window.addEventListener('online', handleMobileResume); window.addEventListener('resume', handleMobileResume); window.addEventListener('pageshow', (e) => { if (e.persisted) handleMobileResume(); }); if (window.Capacitor?.Plugins?.App) { try { window.Capacitor.Plugins.App.addListener('appStateChange', (state) => { if (state && state.isActive) handleMobileResume(); }); } catch (e) {} } } function handleStationMessage(pin, msg) { let entry = stationPool.get(pin); if (!entry) { entry = { pin, name: 'Estação ' + pin, machineName: 'Estação ' + pin, ws: null, status: 'connecting', agents: [], pendingPrompts: new Map() }; stationPool.set(pin, entry); } switch (msg.type) { case 'AUTH_SUCCESS': if (typeof msg.gatewayConnected === 'boolean') { entry.status = msg.gatewayConnected ? 'online' : 'offline'; } renderAllStations(); break; case 'AUTH_ERROR': entry.status = 'offline'; showToast(`PIN ${pin}: ${msg.message || 'Erro de autenticação'}`, 'error'); renderAllStations(); break; case 'INIT_STATE': entry.status = (msg.gatewayConnected === true || (msg.gatewayConnected === undefined && msg.agents && msg.agents.length > 0)) ? 'online' : 'offline'; if (msg.machineName && !isInvalidMachineName(msg.machineName)) { entry.machineName = msg.machineName; // O nome atribuído no pareamento (entry.name / st.name) é soberano sobre o hostname do OS } entry.agents = msg.agents || []; if (Array.isArray(msg.agents) && msg.agents.length > 0) { cacheStationAgents(pin, msg.agents); } clearStationAgentStates(pin); if (entry.status === 'online' && Array.isArray(entry.agents)) { entry.agents.forEach(ag => { const agKey = `${pin}:${ag.name}`; const hasMenu = !!ag.hasInteractiveMenu; agentMenuStates.set(agKey, hasMenu); if (typeof ag.isPaused === 'boolean') { agentPausedStates.set(agKey, ag.isPaused); } if (hasMenu) { ag.isThinking = false; agentThinkingStates.set(agKey, false); } else if (typeof ag.isThinking === 'boolean') { agentThinkingStates.set(agKey, ag.isThinking); } }); } entry.pendingPrompts.clear(); (msg.pendingPrompts || []).forEach(p => { p.pin = pin; entry.pendingPrompts.set(p.requestId, p); }); renderAllStations(); break; case 'AGENTS_UPDATE': entry.agents = msg.agents || []; if (Array.isArray(msg.agents) && msg.agents.length > 0) { cacheStationAgents(pin, msg.agents); } if (Array.isArray(msg.agents)) { const activeNames = new Set(msg.agents.map(ag => `${pin}:${ag.name}`)); for (const key of Array.from(agentMenuStates.keys())) { if (key.startsWith(`${pin}:`) && !activeNames.has(key)) { agentMenuStates.delete(key); } } for (const key of Array.from(agentThinkingStates.keys())) { if (key.startsWith(`${pin}:`) && !activeNames.has(key)) { agentThinkingStates.delete(key); } } msg.agents.forEach(ag => { const agKey = `${pin}:${ag.name}`; const hasMenu = !!ag.hasInteractiveMenu; if (hasMenu && ag.interactiveMenu) { ag.interactiveMenu = sanitizeInteractiveMenu(ag.interactiveMenu); } updateAgentMenuStateAndAlert(pin, ag.name, hasMenu); const prevThinking = agentThinkingStates.get(agKey) === true; const isPaused = !!ag.isPaused; let isNowThinking; if (hasMenu) { isNowThinking = false; } else if (typeof ag.isThinking === 'boolean') { isNowThinking = ag.isThinking; } else { const localTerminal = lastTerminalOutputs.get(agKey); isNowThinking = localTerminal ? detectAgentThinking(localTerminal).isThinking : false; } ag.isThinking = isNowThinking; agentThinkingStates.set(agKey, isNowThinking); if (prevThinking && !isNowThinking && !hasMenu && !isPaused) { notifyAgentTaskCompletedIfNeeded(pin, ag.name); } }); } renderAllStations(); break; case 'AGENT_TERMINAL_OUTPUT': if (msg.agentName) { const histKey = `${pin}:${msg.agentName}`; const previousOutput = lastTerminalOutputs.get(histKey); const newOutput = msg.output || ''; const rawSource = (typeof msg.rawOutput === 'string' && msg.rawOutput.length > 0) ? msg.rawOutput : newOutput; lastTerminalOutputs.set(histKey, rawSource); const fallbackMenu = detectInteractiveMenu(rawSource); const rawDetectedMenu = (typeof msg.hasInteractiveMenu === 'boolean') ? (msg.hasInteractiveMenu ? (msg.interactiveMenu ? sanitizeInteractiveMenu(msg.interactiveMenu, rawSource) : fallbackMenu) : { hasInteractiveMenu: false, axis: null, menuTitle: null, selectedIndex: -1, options: [], rawHint: null }) : fallbackMenu; const detectedMenu = rawDetectedMenu && rawDetectedMenu.hasInteractiveMenu ? sanitizeInteractiveMenu(rawDetectedMenu, rawSource) : { hasInteractiveMenu: false, axis: null, menuTitle: null, selectedIndex: -1, options: [], rawHint: null }; const hasInteractiveMenu = !!detectedMenu.hasInteractiveMenu; const menuStateChanged = updateAgentMenuStateAndAlert(pin, msg.agentName, hasInteractiveMenu); // Status determinístico fornecido diretamente pelo Daemon da estação const hasAuthoritativeThinking = typeof msg.isThinking === 'boolean'; const hasAuthoritativePaused = typeof msg.isPaused === 'boolean'; const localThinking = detectAgentThinking(msg.rawOutput || newOutput, isWaitingChatReply); const isThinking = hasInteractiveMenu ? false : (hasAuthoritativeThinking ? msg.isThinking : localThinking.isThinking); const isPaused = hasInteractiveMenu ? false : (hasAuthoritativePaused ? msg.isPaused : localThinking.isPaused); const pauseResetTime = msg.pauseResetTime || localThinking.resetTime; const thinkingLabel = hasInteractiveMenu ? 'Aguardando seleção em menu interativo' : (msg.details || (hasAuthoritativeThinking ? (isThinking ? 'Executando comando no agente...' : (isPaused ? 'Pausado por limite de uso' : 'Pronto')) : localThinking.label)); const authoritativeStatus = { isThinking, isPaused, label: thinkingLabel, resetTime: pauseResetTime }; const prevThinking = agentThinkingStates.get(histKey); agentThinkingStates.set(histKey, isThinking); const targetAgent = entry.agents.find(a => a.name === msg.agentName); if (targetAgent) { targetAgent.isThinking = isThinking; targetAgent.isPaused = isPaused; targetAgent.hasInteractiveMenu = hasInteractiveMenu; targetAgent.interactiveMenu = hasInteractiveMenu ? detectedMenu : null; if (pauseResetTime) { targetAgent.pauseResetTime = pauseResetTime; } } const completedNotified = (prevThinking === true && !isThinking && !hasInteractiveMenu && !isPaused) ? notifyAgentTaskCompletedIfNeeded(pin, msg.agentName) : false; if (prevThinking !== isThinking || menuStateChanged || completedNotified) { renderAllStations(); } const hist = getAgentChatHistory(msg.agentName, pin); const snapshot = { role: 'agent', isTerminalSnapshot: true, text: cleanTerminalOutput(newOutput || 'Terminal vazio no momento.'), rawText: rawSource, timestamp: Date.now() }; const existingIdx = hist.findIndex(h => h.isTerminalSnapshot); if (existingIdx >= 0) { hist[existingIdx] = snapshot; } else { hist.unshift(snapshot); } setAgentChatHistory(msg.agentName, pin, hist); if (activeChatAgent === msg.agentName && (!activeChatPin || String(activeChatPin) === String(pin))) { removeAgentTyping(); if (chatTerminalOutputRaw) { chatTerminalOutputRaw.textContent = cleanTerminalOutput(newOutput); } const uiIsThinking = updateAgentThinkingUI(newOutput, isWaitingChatReply, authoritativeStatus); renderTuiPanel(hasInteractiveMenu ? detectedMenu : null); updateTerminalSnapshotInPlace(newOutput, uiIsThinking, isPaused, pauseResetTime); updateThinkingBubbleInPlace(newOutput, uiIsThinking, authoritativeStatus); if (uiIsThinking) { hadThinkingDuringReply = true; } // Se estávamos aguardando resposta e o agente concluiu a execução no terminal if (isWaitingChatReply && !hasInteractiveMenu && (hadThinkingDuringReply || !uiIsThinking)) { const cleanedNew = cleanTerminalOutput(newOutput); const isTerminalFinished = !uiIsThinking && cleanedNew && cleanedNew !== terminalTextBeforePrompt && cleanedNew !== 'Terminal pronto.'; if (isTerminalFinished) { isWaitingChatReply = false; hadThinkingDuringReply = false; stopThinkingTimer(); removeAgentTyping(); updateAgentThinkingUI('', false, { isThinking: false, isPaused: false, label: 'Pronto' }); agentThinkingStates.set(histKey, false); const targetAgent = entry.agents.find(a => a.name === msg.agentName); if (targetAgent) { targetAgent.isThinking = false; } renderAllStations(); // Adiciona a resposta gerada pelo agente no terminal ABAIXO do prompt do usuário hist.push({ role: 'agent', text: cleanedNew, timestamp: Date.now() }); setAgentChatHistory(msg.agentName, pin, hist); renderChatMessages(!isUserScrolledUp); const isChatOpen = activeChatAgent === msg.agentName && chatDrawer && chatDrawer.style.display === 'flex'; if (!isChatOpen && !completedNotified) { const cur = unreadResponseCounts.get(histKey) || 0; unreadResponseCounts.set(histKey, cur + 1); renderAllStations(); } } } // Telemetria: envia snapshot do estado de tela comparativo captureAndSendScreenStateSnapshot(msg.agentName, 'terminal_output'); } } break; case 'CHAT_RESPONSE': isWaitingChatReply = false; hadThinkingDuringReply = false; stopThinkingTimer(); removeAgentTyping(); updateAgentThinkingUI('', false); if (msg.agentName) { const histKey = `${pin}:${msg.agentName}`; agentThinkingStates.set(histKey, false); const targetAgent = entry.agents.find(a => a.name === msg.agentName); if (targetAgent) { targetAgent.isThinking = false; } renderAllStations(); const hist = getAgentChatHistory(msg.agentName, pin); const replyText = cleanTerminalOutput(msg.response || ''); if (replyText && !replyText.startsWith('Sem resposta') && replyText !== 'Terminal pronto.') { hist.push({ role: 'agent', text: replyText, timestamp: Date.now() }); setAgentChatHistory(msg.agentName, pin, hist); const isChatOpen = activeChatAgent === msg.agentName && chatDrawer && chatDrawer.style.display === 'flex'; if (!isChatOpen) { const cur = unreadResponseCounts.get(histKey) || 0; unreadResponseCounts.set(histKey, cur + 1); renderAllStations(); } } if (activeChatAgent === msg.agentName && (!activeChatPin || activeChatPin === pin)) { renderChatMessages(!isUserScrolledUp); } captureAndSendScreenStateSnapshot(msg.agentName, 'chat_response'); lastThinkingDoneNotifTimes.set(getAgentScopedKey(msg.agentName, pin), Date.now()); notifyAgentIfEnabled(pin, msg.agentName, `🔔 ${msg.agentName}: Resposta concluída!`, 'info', [80, 50, 80]); } break; case 'PROMPT_PENDING': msg.pin = pin; entry.pendingPrompts.set(msg.requestId, msg); pendingPrompts.set(msg.requestId, msg); // Sync legado renderAllStations(); if (msg.agentName) { notifyAgentIfEnabled(pin, msg.agentName, `🔔 ${msg.agentName}: Aguardando aprovação`, 'warning', [100, 50, 100]); } break; case 'PROMPT_RESOLVED': entry.pendingPrompts.delete(msg.requestId); pendingPrompts.delete(msg.requestId); // Sync legado renderAllStations(); break; case 'AGENT_TERMINAL_RESTARTED': { const isCurrentChatTarget = msg.agentName === activeChatAgent && (!activeChatPin || String(activeChatPin) === String(pin)); if (isCurrentChatTarget) { resetRestartButtonState(); if (msg.ok) { showToast(`✅ Terminal ${msg.agentName} reiniciado!`, 'success'); requestAgentTerminal(msg.agentName, pin); } else { showToast(`❌ Falha ao reiniciar ${msg.agentName}: ${msg.error || 'erro desconhecido'}`, 'error'); } } break; } case 'GATEWAY_STATUS': entry.status = msg.connected ? 'online' : 'offline'; if (!msg.connected) { entry.agents = []; entry.pendingPrompts.clear(); clearStationAgentStates(pin); if (activeChatAgent && (!activeChatPin || String(activeChatPin) === String(pin))) { resetRestartButtonState(); } } renderAllStations(); break; } } function removeStation(pin) { const timer = reconnectTimers.get(pin); if (timer) { clearTimeout(timer); reconnectTimers.delete(pin); } const entry = stationPool.get(pin); if (entry && entry.ws) { try { entry.ws.onclose = null; entry.ws.onerror = null; entry.ws.close(); } catch (e) {} } stationPool.delete(pin); const stations = getSavedStations().filter(s => s.pin !== pin); saveStationsList(stations); if (localStorage.getItem('maestri_pin') === pin) { if (stations.length > 0) { localStorage.setItem('maestri_pin', stations[0].pin); } else { localStorage.removeItem('maestri_pin'); } } showToast(`Estação ${pin} removida.`, 'info'); renderAllStations(); } function setConnected(connected) { if (connected) { if (statusBadge) statusBadge.style.display = 'inline-flex'; if (statusBadge) statusBadge.classList.add('connected'); if (statusText) statusText.textContent = 'Online'; } else { const isAppVisible = appScreen && appScreen.style.display === 'block'; if (statusBadge) { statusBadge.style.display = isAppVisible ? 'inline-flex' : 'none'; statusBadge.classList.remove('connected'); } if (statusText) statusText.textContent = 'Desconectado'; } } // ========================================== // Renderização de Todas as Estações Agrupadas // ========================================== function renderAllStations() { const stations = getSavedStations(); if (stations.length === 0) { if (appScreen) appScreen.style.display = 'none'; if (pinScreen && pinScreen.style.display === 'none') { pinScreen.style.display = 'flex'; } if (statusBadge) statusBadge.style.display = 'none'; if (btnLogout) btnLogout.style.display = 'none'; if (btnConnect) { btnConnect.disabled = false; btnConnect.textContent = 'Conectar'; } return; } if (appScreen) appScreen.style.display = 'block'; if (pinScreen) pinScreen.style.display = 'none'; if (btnLogout) btnLogout.style.display = 'inline-flex'; let totalOnline = 0; let totalPromptsCount = 0; if (stationsContainer) { stationsContainer.innerHTML = ''; } if (agentsListEl) { agentsListEl.innerHTML = ''; } stations.forEach(st => { let entry = stationPool.get(st.pin); if (!entry) { entry = { pin: st.pin, name: st.name || ('Estação ' + st.pin), machineName: st.name || ('Estação ' + st.pin), ws: null, status: 'connecting', agents: (Array.isArray(st.cachedAgents) && st.cachedAgents.length > 0) ? st.cachedAgents : [], pendingPrompts: new Map() }; stationPool.set(st.pin, entry); } else if ((!Array.isArray(entry.agents) || entry.agents.length === 0) && Array.isArray(st.cachedAgents) && st.cachedAgents.length > 0) { entry.agents = st.cachedAgents; } const isOnline = entry.status === 'online'; if (isOnline) totalOnline++; // O nome cadastrado pelo operador (st.name ou entry.name) é soberano sobre o hostname do OS const dispMachine = !isInvalidMachineName(st.name) ? st.name : (!isInvalidMachineName(entry.name) ? entry.name : ('Estação ' + st.pin)); const promptsCount = entry.pendingPrompts.size; totalPromptsCount += promptsCount; if (stationsContainer) { const card = document.createElement('div'); card.className = `station-group-card ${isOnline ? 'online' : 'offline'}`; card.id = `station-card-${st.pin}`; // 1. Header do card const headerEl = document.createElement('div'); headerEl.className = 'station-group-header'; headerEl.innerHTML = `
${escapeHtml(dispMachine)}
PIN: ${escapeHtml(st.pin)} ${isOnline ? 'Online' : (entry.status === 'connecting' ? 'Conectando...' : 'Desconectado')}
`; const btnRename = headerEl.querySelector('.btn-station-rename'); if (btnRename) { btnRename.addEventListener('click', (e) => { e.stopPropagation(); const currentName = st.name || entry.name || ('Estação ' + st.pin); const newName = prompt(`Digite o novo apelido para a estação (PIN: ${st.pin}):`, currentName); if (newName !== null && newName.trim() !== '') { renameStation(st.pin, newName.trim()); } }); } const btnRemove = headerEl.querySelector('.btn-station-remove'); btnRemove.addEventListener('click', (e) => { e.stopPropagation(); removeStation(st.pin); }); card.appendChild(headerEl); // 2. Seção de Agentes com Atividade const agentsSection = document.createElement('div'); agentsSection.className = 'station-section'; const activeAiAgents = []; const otherAgents = []; entry.agents.forEach(agent => { if (agent.isSelf) return; // Oculta o próprio daemon supervisor dos cards da Home const hasMenu = !!agent.hasInteractiveMenu; const isAiActive = hasMenu || (agent.hasAiActivity !== undefined ? !!agent.hasAiActivity : (agent.status !== undefined ? agent.status === 'active' : true)); if (isAiActive) { activeAiAgents.push(agent); } else { otherAgents.push(agent); } }); // Prioriza agentes com menu ativo e respostas não lidas no topo da lista activeAiAgents.sort((a, b) => { const aMenu = !!a.hasInteractiveMenu; const bMenu = !!b.hasInteractiveMenu; if (aMenu && !bMenu) return -1; if (!aMenu && bMenu) return 1; const aUnread = hasUnreadResponseForAgent(a.name, st.pin); const bUnread = hasUnreadResponseForAgent(b.name, st.pin); if (aUnread && !bUnread) return -1; if (!aUnread && bUnread) return 1; return 0; }); const stationHasUnread = entry.agents.some(ag => hasUnreadResponseForAgent(ag.name, st.pin)); const activeCount = activeAiAgents.length; agentsSection.innerHTML = ` ${stationHasUnread ? `
💬 Você tem respostas novas para ler nesta estação
` : ''}
Agentes com Atividade (${activeCount}) ${stationHasUnread ? '● Novas respostas' : ''} Toque para conversar
`; function createAgentPill(agent) { const pill = document.createElement('div'); const notifKey = `${st.pin}:${agent.name}`; const isSelf = !!agent.isSelf; const isPaused = !isSelf && !!agent.isPaused; let isThinking = !isSelf && !isPaused && !!agent.isThinking; if (agentThinkingStates.has(notifKey)) { isThinking = !isSelf && !isPaused && agentThinkingStates.get(notifKey) === true; } const isAiActive = !isSelf && (agent.hasAiActivity !== undefined ? !!agent.hasAiActivity : (agent.status !== undefined ? agent.status === 'active' : true)); const hasUnread = hasUnreadResponseForAgent(agent.name, st.pin); const hasInteractiveMenu = !isSelf && !!agent.hasInteractiveMenu; // Prioridade visual de estado: // 1. isSelf -> azul (#38bdf8) // 2. isPaused -> laranja (#fb923c) // 3. isThinking -> amarelo (#f59e0b) com pulse-dot // 4. isAiActive -> verde (#34d399) // 5. idle -> cinza (#94a3b8) const dotColor = isSelf ? '#38bdf8' : (isPaused ? '#fb923c' : (isThinking ? '#f59e0b' : (isAiActive || hasInteractiveMenu ? '#34d399' : '#94a3b8'))); const statusClass = isSelf ? 'self' : (isPaused ? 'ai-paused' : (isThinking ? 'thinking' : (isAiActive || hasInteractiveMenu ? 'ai-active' : 'shell-idle'))); let tooltip = `Toque para conversar com ${agent.name} em ${dispMachine}`; if (hasInteractiveMenu) { tooltip = `🎛️ Menu interativo ativo em ${agent.name} (${dispMachine})! Toque para selecionar.`; } else if (hasUnread) { tooltip = `⚠️ Nova resposta de ${agent.name}! Toque para ler em ${dispMachine}`; } else if (isSelf) { tooltip = `${agent.name} (Daemon Local Supervisor) em ${dispMachine}`; } else if (isPaused) { tooltip = `Agente Pausado (Limite de Cota): ${agent.name}${agent.pauseResetTime ? ` até ${agent.pauseResetTime}` : ''} em ${dispMachine}`; } else if (isThinking) { tooltip = `Agente em Execução (Trabalhando): ${agent.name}${agent.aiType ? ` (${agent.aiType.toUpperCase()})` : ''} em ${dispMachine}`; } else if (isAiActive) { tooltip = `Agente de IA Ativo: ${agent.name}${agent.aiType ? ` (${agent.aiType.toUpperCase()})` : ''} em ${dispMachine}`; } else { const shellName = agent.shellType === 'cmd' ? 'DOS' : agent.shellType === 'bash' ? 'Bash' : agent.shellType === 'powershell' ? 'PowerShell' : 'Shell'; tooltip = `Terminal ${shellName}: ${agent.name} em ${dispMachine}`; } const isNotifActive = isTerminalNotifEnabled(agent.name, st.pin); pill.className = `agent-pill agent-chip ${statusClass}${hasUnread ? ' has-unread-reply' : ''}${hasInteractiveMenu ? ' has-interactive-menu' : ''}`; pill.setAttribute('title', tooltip); pill.innerHTML = ` ${escapeHtml(agent.name)} ${isPaused ? '⏸️' : ''} ${isThinking ? '⚡' : ''} ${hasInteractiveMenu ? '🎛️ Menu ativo' : ''} ${hasUnread ? '💬 Resposta nova' : ''} `; const notifBtn = pill.querySelector('.btn-terminal-notif-toggle'); if (notifBtn) { notifBtn.addEventListener('click', (e) => { e.stopPropagation(); const cur = isTerminalNotifEnabled(agent.name, st.pin); setTerminalNotifEnabled(agent.name, st.pin, !cur); renderAllStations(); syncChatHeaderNotifButton(); }); } pill.addEventListener('click', () => { openChatWithAgent(agent.name, st.pin, dispMachine); }); return pill; } const visibleAgents = activeAiAgents.length + otherAgents.length; const agentsListContainer = agentsSection.querySelector('.station-agents-list'); if (visibleAgents === 0) { agentsListContainer.innerHTML = `${isOnline ? 'Nenhum agente ativo' : 'Estação desligada ou desconectada'}`; } else { // 1. Renderiza primeiro os agentes com atividade (sinal verde) if (activeAiAgents.length === 0) { const emptyActiveEl = document.createElement('div'); emptyActiveEl.className = 'station-empty-active-agents'; emptyActiveEl.innerHTML = `Nenhum agente em atividade nesta estação`; agentsListContainer.appendChild(emptyActiveEl); } else { activeAiAgents.forEach(agent => { agentsListContainer.appendChild(createAgentPill(agent)); }); } // 2. Renderiza outros terminais (supervisor ou shells) ordenados if (otherAgents.length > 0) { otherAgents.sort((a, b) => { if (a.isPaused && !b.isPaused) return -1; if (!a.isPaused && b.isPaused) return 1; if (a.isSelf && !b.isSelf) return 1; if (!a.isSelf && b.isSelf) return -1; return a.name.localeCompare(b.name); }); if (activeAiAgents.length > 0) { const sepWrapper = document.createElement('div'); sepWrapper.className = 'station-other-terminals-wrapper'; sepWrapper.innerHTML = `
Outros Terminais (${otherAgents.length})
`; const otherList = sepWrapper.querySelector('.station-other-terminals-list'); otherAgents.forEach(agent => { otherList.appendChild(createAgentPill(agent)); }); agentsListContainer.appendChild(sepWrapper); } else { otherAgents.forEach(agent => { agentsListContainer.appendChild(createAgentPill(agent)); }); } } } card.appendChild(agentsSection); stationsContainer.appendChild(card); } }); // Atualiza badge de contagem de estações if (stationsCountBadge) { stationsCountBadge.textContent = `${totalOnline}/${stations.length}`; } // Sincroniza dados globais para compatibilidade const firstStation = stations[0]; const firstEntry = firstStation ? stationPool.get(firstStation.pin) : null; if (firstEntry) { currentPin = firstEntry.pin; currentMachine = firstEntry.machineName; if (machineNameEl) machineNameEl.textContent = firstEntry.machineName; agents = firstEntry.agents; ws = firstEntry.ws; if (sessionPinDisplay) sessionPinDisplay.textContent = firstEntry.pin; } // Sincroniza elemento legado #cards-container para passar em testes if (cardsContainer) { if (totalPromptsCount === 0) { cardsContainer.innerHTML = `

Tudo limpo! Nenhum agente aguardando resposta no momento.

`; } else { cardsContainer.innerHTML = ''; stationPool.forEach((stEntry) => { stEntry.pendingPrompts.forEach(p => { cardsContainer.appendChild(renderActionCardElement(p, stEntry.pin)); }); }); } } setConnected(totalOnline > 0); renderStationsSelect(); } function renderActionCardElement(p, pin) { const card = document.createElement('div'); card.className = 'action-card'; let optionsHtml = ''; if (Array.isArray(p.options) && p.options.length > 0) { optionsHtml = `
` + p.options.map(opt => ``).join('') + `
`; } card.innerHTML = `
${escapeHtml(p.agentName)} ${new Date(p.timestamp || Date.now()).toLocaleTimeString()}
${escapeHtml(p.prompt)}
${optionsHtml}
`; // Eventos dos botões de opções card.querySelectorAll('.btn-option').forEach(btn => { btn.addEventListener('click', () => { sendResponse(p.requestId, p.agentName, btn.getAttribute('data-val'), pin); }); }); // Evento do input livre const inputEl = card.querySelector(`#input-${p.requestId}`); const sendBtn = card.querySelector(`#send-${p.requestId}`); const handleCustomSend = () => { const val = inputEl.value.trim(); if (val) sendResponse(p.requestId, p.agentName, val, pin); }; sendBtn.addEventListener('click', handleCustomSend); inputEl.addEventListener('keypress', (e) => { if (e.key === 'Enter') handleCustomSend(); }); return card; } function sendResponse(requestId, agentName, response, pin) { const targetPin = pin || currentPin; const entry = targetPin ? stationPool.get(targetPin) : null; const targetWs = entry?.ws || ws; if (!targetWs || targetWs.readyState !== WebSocket.OPEN) { alert('Conexão perdida com o Relay'); return; } targetWs.send(JSON.stringify({ type: 'RESOLVE_PROMPT', requestId, agentName, response })); if (entry) { entry.pendingPrompts.delete(requestId); } pendingPrompts.delete(requestId); renderAllStations(); } function escapeHtml(text) { const div = document.createElement('div'); div.textContent = text || ''; return div.innerHTML; } // ========================================== // Chat Interativo com Agentes (Bottom Sheet) // ========================================== let terminalPollInterval = null; function requestAgentTerminal(agentName, pin) { const targetPin = pin ? String(pin) : (activeChatPin ? String(activeChatPin) : (currentPin ? String(currentPin) : null)); const entry = targetPin ? stationPool.get(String(targetPin)) : null; const targetWs = entry?.ws || ws; if (!agentName) return; if (!targetWs || targetWs.readyState !== WebSocket.OPEN) { console.warn(`[App] WebSocket inativo ao requisitar terminal para ${agentName} (PIN: ${targetPin}). Reconectando...`); if (targetPin) { connectStation(targetPin, entry?.name); } return; } targetWs.send(JSON.stringify({ type: 'GET_AGENT_TERMINAL', agentName })); } function openChatWithAgent(agentName, pin, machineName) { if (!agentName) return; activeChatAgent = agentName; activeChatPin = pin ? String(pin) : (currentPin ? String(currentPin) : null); activeChatMachine = machineName || ''; // Reseta qualquer estado residual de espera anterior para nova sessão isWaitingChatReply = false; hadThinkingDuringReply = false; resetRestartButtonState(); stopThinkingTimer(); removeAgentTyping(); // Garante que o WebSocket da estação esteja ativo; caso inativo, reconecta imediatamente const targetPin = activeChatPin || currentPin; const entry = targetPin ? stationPool.get(String(targetPin)) : null; const targetWs = entry?.ws || ws; if (!targetWs || targetWs.readyState !== WebSocket.OPEN) { console.log(`[App] Conexão WebSocket inativa para estação ${targetPin} ao abrir chat. Reconectando imediatamente...`); if (targetPin) { connectStation(targetPin, activeChatMachine || entry?.name); } } if (chatAgentNameEl) { chatAgentNameEl.textContent = agentName; } const chatSubtitleEl = chatDrawer ? chatDrawer.querySelector('.chat-agent-info div div') : null; if (chatSubtitleEl) { chatSubtitleEl.textContent = activeChatMachine ? `🖥️ ${activeChatMachine} (${activeChatPin}) · Terminal Conectado` : 'Terminal Maestri Conectado'; } const history = getAgentChatHistory(activeChatAgent, activeChatPin); const lastSnapshot = history.find(h => h.isTerminalSnapshot); const currentAgentInfo = entry?.agents?.find(a => a.name === agentName); const hasAuthoritativeMenu = Boolean(currentAgentInfo && typeof currentAgentInfo.hasInteractiveMenu === 'boolean'); const initialRawFallback = lastSnapshot ? (lastSnapshot.rawText || lastSnapshot.text) : ''; const usingSnapshotMenu = Boolean( (!hasAuthoritativeMenu && lastSnapshot) || (hasAuthoritativeMenu && currentAgentInfo.hasInteractiveMenu && !currentAgentInfo.interactiveMenu && lastSnapshot) ); const rawInitialMenu = hasAuthoritativeMenu ? (currentAgentInfo.hasInteractiveMenu ? (currentAgentInfo.interactiveMenu || (lastSnapshot ? detectInteractiveMenu(initialRawFallback) : null)) : null) : (lastSnapshot ? detectInteractiveMenu(initialRawFallback) : null); const initialMenu = rawInitialMenu && rawInitialMenu.hasInteractiveMenu ? sanitizeInteractiveMenu(rawInitialMenu, usingSnapshotMenu ? initialRawFallback : '') : null; isTuiPanelManualOpen = false; const authoritativeOpenStatus = (hasAuthoritativeMenu && !currentAgentInfo.hasInteractiveMenu && typeof currentAgentInfo.isThinking === 'boolean') ? { isThinking: currentAgentInfo.isThinking, isPaused: !!currentAgentInfo.isPaused, label: currentAgentInfo.isThinking ? 'Executando comando no agente...' : (currentAgentInfo.isPaused ? 'Pausado por limite de uso' : 'Pronto'), resetTime: currentAgentInfo.pauseResetTime || null } : null; if (lastSnapshot) { updateAgentThinkingUI(lastSnapshot.rawText || lastSnapshot.text, isWaitingChatReply, authoritativeOpenStatus); } else { updateAgentThinkingUI('', isWaitingChatReply, authoritativeOpenStatus); } const hasInitialMenu = Boolean( initialMenu && (initialMenu.hasInteractiveMenu || (Array.isArray(initialMenu.options) && initialMenu.options.length > 0)) ); renderTuiPanel(hasInitialMenu ? initialMenu : null); isUserScrolledUp = false; if (btnChatScrollBottom) btnChatScrollBottom.style.display = 'none'; if (chatDrawer) chatDrawer.style.display = 'flex'; syncChatHeaderNotifButton(); if (chatTerminalOutputRaw && lastSnapshot) { chatTerminalOutputRaw.textContent = cleanTerminalOutput(lastSnapshot.text); } renderChatMessages(true); if (history.length === 0) { appendTerminalLoading(); } requestAgentTerminal(agentName, activeChatPin); clearInterval(terminalPollInterval); terminalPollInterval = setInterval(() => { if (activeChatAgent && chatDrawer && chatDrawer.style.display === 'flex') { requestAgentTerminal(activeChatAgent, activeChatPin); } }, 4000); if (chatInput) { chatInput.value = ''; setTimeout(() => chatInput.focus(), 150); } // Marca respostas como lidas ao abrir o chat com o agente markAgentResponsesAsRead(agentName, activeChatPin); renderAllStations(); captureAndSendScreenStateSnapshot(agentName, 'open_chat'); } window.openChatWithAgent = openChatWithAgent; function toggleAttachMenu(show) { const isVisible = attachMenu && attachMenu.style.display !== 'none'; const target = typeof show === 'boolean' ? show : !isVisible; if (attachMenu) attachMenu.style.display = target ? 'flex' : 'none'; if (attachBackdrop) attachBackdrop.style.display = target ? 'block' : 'none'; } window.toggleAttachMenu = toggleAttachMenu; function closeChat() { if (typeof window._stopAnyActiveVoiceSession === 'function') { window._stopAnyActiveVoiceSession(); } clearInterval(terminalPollInterval); terminalPollInterval = null; toggleAttachMenu(false); isWaitingChatReply = false; hadThinkingDuringReply = false; isTuiPanelManualOpen = false; renderTuiPanel(null); removeAgentTyping(); stopThinkingTimer(); updateAgentThinkingUI('', false); resetRestartButtonState(); isUserScrolledUp = false; if (btnChatScrollBottom) btnChatScrollBottom.style.display = 'none'; if (chatDrawer) { chatDrawer.style.display = 'none'; } if (activeChatAgent) { markAgentResponsesAsRead(activeChatAgent, activeChatPin); } activeChatAgent = null; activeChatPin = null; renderAllStations(); } window.closeChat = closeChat; function formatBytes(bytes) { if (!bytes || bytes === 0) return '0 B'; const k = 1024; const sizes = ['B', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]; } function hasHorizontalMenuHints(text) { if (!text) return false; return ( /ctrl\+f\s+fullscreen/i.test(text) || /⇆\s*select/i.test(text) || /enter\s+confirm/i.test(text) || /←\/?→\s*(?:to\s+)?(?:select|navigate)/i.test(text) ); } function cleanTerminalOutput(rawText) { if (!rawText || typeof rawText !== 'string') return ''; let text = rawText.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g, ''); const lines = text.split(/\r?\n/); const cleanedLines = []; for (let i = 0; i < lines.length; i++) { let line = lines[i]; let trimmed = line.trim(); // Remove linhas compostas unicamente por bordas/traços/divisores repetidos if (/^[─━═\-_=~┄┅┈┉┌┐└┘├┤┬┴┼]{3,}$/.test(trimmed)) { continue; } // Remove linhas contendo apenas prompts residuais (>, $, ❯) e eventuais traços ou espaços if (/^[>$❯]\s*[─━═\-_=~]*\s*$/.test(trimmed)) { continue; } // Remove rodapés, modos e atalhos operacionais de TUI (Claude Code, Gemini CLI, Maestri) const isInteractiveMenuFooter = /Keyboard:\s*↑\/↓\s*Navigate/i.test(trimmed) || /Keyboard:\s*←\/→\s*Effort/i.test(trimmed) || /←\/→\s*Effort/i.test(trimmed) || /↑\/?↓\s*to navigate/i.test(trimmed) || /↵\s*to select/i.test(trimmed) || /Enter to confirm/i.test(trimmed) || /esc\s+to\s+close/i.test(trimmed) || /esc\s+Go Back/i.test(trimmed) || /space to select/i.test(trimmed) || /ctrl\+f\s+fullscreen/i.test(trimmed) || /⇆\s*select/i.test(trimmed) || /enter\s+confirm/i.test(trimmed) || /Connect provider/i.test(trimmed) || /Favorite ctrl\+f/i.test(trimmed) || /ctrl\+t variants/i.test(trimmed); if (!isInteractiveMenuFooter && ( /^\??\s*for shortcuts/i.test(trimmed) || /^esc to (?:cancel|interrupt)\s*$/i.test(trimmed) || /ctrl\+[a-z] to expand/i.test(trimmed) || /shift\+tab to cycle/i.test(trimmed) || /auto mode on/i.test(trimmed) || /^Tip:\s+Start your message/i.test(trimmed) || /Gemini\s+[\d.]+\s+(Flash|Pro).*task/i.test(trimmed) || /^\/?(tasks|status)\s*$/i.test(trimmed) || /^Running command\.\.\./i.test(trimmed) || /^[✻✽*•]?\s*Percolating…/i.test(trimmed) || /^[✻✽*•]?\s*Worked for \d+s/i.test(trimmed) || /[↓↑]\s*[\d.]+k?\s*tokens/i.test(trimmed))) { continue; } // Remove traços residuais longos dentro da linha line = line.replace(/[─━═\-_=~]{3,}/g, ''); // Normaliza símbolos de execução do Claude Code line = line.replace(/^[ \t]*⎿[ \t]*/, ' ↳ '); line = line.replace(/^[ \t]*●[ \t]*/, '• '); // Colapsa múltiplos espaços consecutivos preservando separador de menus horizontais (1 ou 2 linhas, inclusive com bordas │/┃/║) e recuo inicial estruturado const bodyWithoutBox = trimmed.replace(/^[│┃║\s]+/, ''); let nextBodyWithoutBox = ''; for (let j = i + 1; j < Math.min(lines.length, i + 3); j++) { const candidateBody = lines[j].trim().replace(/^[│┃║\s]+/, ''); if (candidateBody) { nextBodyWithoutBox = candidateBody; break; } } const isHorizontalMenuLine = hasHorizontalMenuHints(bodyWithoutBox) || (/[ \t]{2,}/.test(bodyWithoutBox) && hasHorizontalMenuHints(nextBodyWithoutBox)); const leadingSpaces = line.match(/^[ \t]*/)[0]; const indent = leadingSpaces.length > 4 ? ' ' : leadingSpaces; const collapsedSpacing = isHorizontalMenuLine ? ' ' : ' '; const restOfLine = line.slice(leadingSpaces.length).replace(/[ \t]{2,}/g, collapsedSpacing).trimEnd(); line = (indent + restOfLine).trimEnd(); // Evita linhas vazias consecutivas duplicadas if (!line.trim()) { if (cleanedLines.length > 0 && !cleanedLines[cleanedLines.length - 1].trim()) { continue; } cleanedLines.push(''); } else { cleanedLines.push(line); } } const result = cleanedLines.join('\n') .replace(/\n{3,}/g, '\n\n') .trim(); return result || 'Terminal pronto.'; } let thinkingStartTime = null; let thinkingTimerInterval = null; let terminalTextBeforePrompt = ''; let hadThinkingDuringReply = false; const lastTerminalOutputs = new Map(); function formatElapsed(startTime) { if (!startTime) return '00:00'; const totalSecs = Math.max(0, Math.floor((Date.now() - startTime) / 1000)); const mins = Math.floor(totalSecs / 60); const secs = totalSecs % 60; return `${mins < 10 ? '0' : ''}${mins}:${secs < 10 ? '0' : ''}${secs}`; } function extractLatestAction(terminalText) { if (!terminalText || typeof terminalText !== 'string') return 'Processando solicitação...'; const clean = cleanTerminalOutput(terminalText).trim(); const lines = clean.split('\n').map(l => l.trim()).filter(Boolean); if (!lines.length) return 'Processando solicitação...'; for (let i = lines.length - 1; i >= 0; i--) { const line = lines[i]; if (/^(>|❯|│\s*[>❯]|\$|#|\? for shortcuts|esc to cancel|ctrl\+o to expand)\s*$/i.test(line)) continue; // Ignora avisos de limite de cota, rate limit ou contagem regressiva para não classificar como ação ativa if (/usage limit reached|continuing automatically at|limit resets|5-hour limit|rate limit reached|quota exceeded/i.test(line)) continue; // Ignora menções de código ou CSS para evitar falsos positivos if (/\.thinking|\#f59e0b|isThinking/i.test(line)) continue; if (/(?:running command|generating|percolating|analyzing|working|building|compiling|thinking\.\.\.)/i.test(line)) { return line.slice(0, 50); } if (/^(●|○|⚡|✽|⠇|⣻|⣾|⣽)\s+/i.test(line)) { return line.slice(0, 50); } if (/^(Ran|Explored|Edited|Thought for)\s+/i.test(line)) { return line.slice(0, 50); } } const lastLine = lines[lines.length - 1]; return lastLine.length > 50 ? lastLine.slice(0, 47) + '...' : lastLine; } function startThinkingTimer() { if (!thinkingStartTime) { thinkingStartTime = Date.now(); } if (!thinkingTimerInterval) { thinkingTimerInterval = setInterval(() => { const timerEl = document.getElementById('chat-thinking-elapsed'); if (timerEl) { timerEl.textContent = formatElapsed(thinkingStartTime); } }, 1000); } } function stopThinkingTimer() { if (thinkingTimerInterval) { clearInterval(thinkingTimerInterval); thinkingTimerInterval = null; } thinkingStartTime = null; } const RE_ANSI = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g; const RE_HORIZONTAL_FOOTER = /(?:ctrl\+f\s+fullscreen\s+⇆\s*select|⇆\s*select\s+enter\s+confirm|←\/?→\s*(?:Effort|(?:to\s+)?(?:select|navigate)))/i; const RE_TUI_FOOTER = /(?:Keyboard:\s*(?:↑\/↓\s*Navigate|←\/→\s*Effort)|←\/→\s*Effort|↑\/?↓\s*to navigate|↵\s*to select|enter\s+Select|esc\s+Go Back|esc\s+to\s+close|esc\s+to\s+go\s+back|Enter to confirm\s*·\s*Esc to cancel|space to select|to navigate\s*·\s*↵\s*to select|ctrl\+f\s+fullscreen\s+⇆\s*select|⇆\s*select\s+enter\s+confirm|Connect provider ctrl\+a|Favorite ctrl\+f|ctrl\+t variants|tab to switch panels|at top for controls)/i; const RE_APPROVAL_HEADER = /\brequires approval\b|\bDo you want to proceed\?|\bPermission required\b|\bAlways allow\b|\bSelect model\b|\bSelect variant\b|\bSwitch Model\b|\bSet Effort\b|tab to switch panels/i; const RE_MODEL_MENU_HEADER = /^\s*(?:Select model|Select variant|Switch Model|Set Effort)(?:\s+esc)?\s*$/i; const RE_KILO_CATEGORY = /^(?:Search|Recent|Recommended|Kilo Gateway|Provider options|Other models|Ask|Code|commands)$/i; const RE_BOX_BORDER_ONLY = /^[│┃║▏▎▍▌▋▊▉─━═┄┅┈┉┌┐└┘├┤┬┴┼|+\s]*$/; const RE_BOX_BORDER_TOKEN = /^[│┃║▏▎▍▌▋▊▉|+]+$/; const RE_BOX_BORDER_LEADING = /^(?:\s*[│┃║▏▎▍▌▋▊▉|+]+)+/; const RE_BOX_BORDER_TRAILING = /(?:^|\s+)[│┃║▏▎▍▌▋▊▉|+]+(?:\s*[│┃║▏▎▍▌▋▊▉|+]+)*\s*$|[│┃║▏▎▍▌▋▊▉]+\s*$/; function stripBoxBorders(text) { if (!text) return ''; return text .replace(RE_BOX_BORDER_LEADING, '') .replace(RE_BOX_BORDER_TRAILING, '') .trim(); } function findLabelOffsetInSegment(segment, label, startFrom) { let pos = startFrom; while (pos <= segment.length) { const idx = segment.indexOf(label, pos); if (idx === -1) return -1; const beforeOk = idx === 0 || /[\s│┃║▏▎▍▌▋▊▉|+]/.test(segment[idx - 1]); const afterIdx = idx + label.length; const afterOk = afterIdx === segment.length || /[\s│┃║▏▎▍▌▋▊▉|+]/.test(segment[afterIdx]); if (beforeOk && afterOk) return idx; pos = idx + 1; } return segment.indexOf(label, startFrom); } const RE_MENU_CURSOR_STRICT = /^\s*[>❯]\s+(.+?)\s*$/; const RE_MENU_ACTIVE_LINE = /^\s*(?:[>❯]|●|◉)\s+(.+?)\s*$/; const RE_MENU_EXEC_BULLET = /^\s*●\s*(?:Ran|Explored|Edited|Created|Updated|Deleted|Read|Wrote|Searched|Checked|Thought|Task|Tool)\b/i; const RE_MENU_SPINNERS = /[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷]/; const RE_MENU_RUNNING_WORDS = /(?:^|\n|\s)(?:[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷●○⚡✽✻✶]\s*)?(?:running command|generating|percolating|analyzing|working\.\.\.|building|compiling|thinking\.\.\.)\b/i; const RE_MENU_SHELL_OR_IDLE = /^(?:PS\s+(?:[A-Za-z]:[\\/]|[/~]).*?>|PS\s*>|[A-Za-z]:[\\/].*?>|(?:[\w.-]+@[\w.-]+:.*?[#$]|MINGW(?:32|64).*?\$|bash-[\d.]+\$|\$)|(?:Claude|kiro|gemini-cli|aider)>|(?:│\s*)?[>❯]|\??\s*for shortcuts)\s*$/i; const RE_MENU_BOUNDARY = /^(?:[─━═\-_=~]{3,}|Search:|Switch Model|Keyboard:|esc\s+to\s+(?:close|cancel)|Enter to confirm|\?\s*for shortcuts|(?:shell|bash|cmd|tool|command)\s*→)/i; function extractAnsiStylesPerChar(rawLine) { const styles = []; let curReverse = false; let curBold = false; let curBg = null; let curFg = null; const re = /\x1B(?:\[([0-9;]*)m|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g; let lastIndex = 0; let match; while ((match = re.exec(rawLine)) !== null) { for (let k = lastIndex; k < match.index; k++) { styles.push({ reverse: curReverse, bold: curBold, bg: curBg, fg: curFg }); } if (match[1] !== undefined) { const parts = match[1] === '' ? ['0'] : match[1].split(';'); for (let p = 0; p < parts.length; p++) { const code = parts[p]; if (code === '0' || code === '') { curReverse = false; curBold = false; curBg = null; curFg = null; } else if (code === '1') { curBold = true; } else if (code === '22') { curBold = false; } else if (code === '7') { curReverse = true; } else if (code === '27') { curReverse = false; } else if (code === '49') { curBg = null; } else if (code === '39') { curFg = null; } else if (code === '48') { if (parts[p + 1] === '5' && parts[p + 2] !== undefined) { curBg = `48;5;${parts[p + 2]}`; p += 2; } else if (parts[p + 1] === '2' && parts[p + 4] !== undefined) { curBg = `48;2;${parts[p + 2]};${parts[p + 3]};${parts[p + 4]}`; p += 4; } } else if (code === '38') { if (parts[p + 1] === '5' && parts[p + 2] !== undefined) { curFg = `38;5;${parts[p + 2]}`; p += 2; } else if (parts[p + 1] === '2' && parts[p + 4] !== undefined) { curFg = `38;2;${parts[p + 2]};${parts[p + 3]};${parts[p + 4]}`; p += 4; } } else if (/^(?:4[0-7]|10[0-7])$/.test(code)) { curBg = code; } else if (/^(?:3[0-7]|9[0-7])$/.test(code)) { curFg = code; } } } lastIndex = re.lastIndex; } for (let k = lastIndex; k < rawLine.length; k++) { styles.push({ reverse: curReverse, bold: curBold, bg: curBg, fg: curFg }); } return styles; } function isAccentAnsiBg(bg) { if (!bg) return false; if (bg === '40' || bg === '100') return false; if (/^(?:4[1-7]|10[1-7])$/.test(bg)) return true; if (bg.startsWith('48;5;')) { const n = Number(bg.slice(5)); if (n === 0 || n === 8 || (n >= 232 && n <= 243)) return false; return true; } if (bg.startsWith('48;2;')) { const [r, g, b] = bg.slice(5).split(';').map(Number); const luma = 0.299 * r + 0.587 * g + 0.114 * b; const chroma = Math.max(r, g, b) - Math.min(r, g, b); return luma >= 90 || chroma >= 40; } return false; } function isDarkAnsiFg(fg) { if (!fg) return false; if (fg === '30' || fg === '38;5;0') return true; if (fg.startsWith('38;5;')) { const n = Number(fg.slice(5)); return n >= 232 && n <= 238; } if (fg.startsWith('38;2;')) { const [r, g, b] = fg.slice(5).split(';').map(Number); return (0.299 * r + 0.587 * g + 0.114 * b) < 60; } return false; } function detectHorizontalSelectedIndex(rawLine, optionsSegmentRaw, labels) { const styles = extractAnsiStylesPerChar(rawLine); const leadMatch = optionsSegmentRaw.match(RE_BOX_BORDER_LEADING); let searchFrom = leadMatch ? leadMatch[0].length : 0; const optionStyles = labels.map((label) => { const idx = findLabelOffsetInSegment(optionsSegmentRaw, label, searchFrom); if (idx === -1) return { hasReverse: false, bold: false, bg: null, fg: null }; searchFrom = idx + label.length; const slice = styles.slice(idx, idx + label.length); const hasReverse = slice.some(s => s.reverse); const bold = slice.some(s => s.bold); const bgEntry = slice.find(s => s.bg !== null); const fgEntry = slice.find(s => s.fg !== null); return { hasReverse, bold, bg: bgEntry ? bgEntry.bg : null, fg: fgEntry ? fgEntry.fg : null }; }); const revIdx = optionStyles.findIndex(s => s.hasReverse); if (revIdx !== -1) return revIdx; const bgIndices = optionStyles .map((s, i) => (s.bg !== null ? i : -1)) .filter(i => i !== -1); if (bgIndices.length === 1) return bgIndices[0]; if (bgIndices.length > 1) { const counts = new Map(); bgIndices.forEach(i => counts.set(optionStyles[i].bg, (counts.get(optionStyles[i].bg) || 0) + 1)); const hasRepeatedBg = Array.from(counts.values()).some(c => c > 1); let bestIdx = bgIndices[0]; let bestScore = -1; for (const i of bgIndices) { const st = optionStyles[i]; let score = 0; if (hasRepeatedBg && counts.get(st.bg) === 1) score += 40; if (isAccentAnsiBg(st.bg)) score += 25; if (st.bold) score += 10; if (isDarkAnsiFg(st.fg)) score += 10; if (score > bestScore) { bestScore = score; bestIdx = i; } } if (bestScore > 0) return bestIdx; } return 0; } function extractHorizontalMenuTitle(lines, optionsLineIdx) { const floor = Math.max(0, optionsLineIdx - 10); for (let i = optionsLineIdx - 1; i >= floor; i--) { const t = stripBoxBorders(lines[i]); if (RE_APPROVAL_HEADER.test(t)) return t; } for (let i = optionsLineIdx - 1; i >= floor; i--) { const t = stripBoxBorders(lines[i]); if (!t || /^[─━═\-_=~]{3,}$/.test(t) || /^[#$>]/.test(t) || /^-\s+/.test(t)) continue; return t; } return 'Permission required'; } function parseHorizontalMenuBar(ansiLines, lines, footerIdx) { const cleanFooterLine = lines[footerIdx]; const rawFooterLine = ansiLines[footerIdx]; const hintStart = cleanFooterLine.search(/(?:ctrl\+f\s+fullscreen|⇆\s*select|enter\s+confirm|←\/?→\s*(?:to\s+)?(?:select|navigate))/i); if (hintStart === -1) return null; const rawHint = stripBoxBorders(cleanFooterLine.slice(hintStart)).replace(/\s{2,}/g, ' ').trim(); let optionsSegmentRaw = cleanFooterLine.slice(0, hintStart); let targetAnsiLine = rawFooterLine; let optionsLineIdx = footerIdx; if (!stripBoxBorders(optionsSegmentRaw) && footerIdx > 0) { for (let prevIdx = footerIdx - 1; prevIdx >= Math.max(0, footerIdx - 2); prevIdx--) { const prevClean = stripBoxBorders(lines[prevIdx]); if (!prevClean) continue; if (/\s{2,}/.test(prevClean)) { optionsSegmentRaw = lines[prevIdx]; targetAnsiLine = ansiLines[prevIdx]; optionsLineIdx = prevIdx; } break; } } const labels = stripBoxBorders(optionsSegmentRaw) .split(/\s{2,}/) .map(s => s.trim()) .filter(s => s && !RE_BOX_BORDER_TOKEN.test(s)); if (labels.length === 0) return null; const selectedIndex = detectHorizontalSelectedIndex(targetAnsiLine, optionsSegmentRaw, labels); const options = labels.map((label, idx) => { const numMatch = label.match(/^(\d+)[.)]\s+/); return { index: idx, label, selected: idx === selectedIndex, numberPrefix: numMatch ? numMatch[1] : null }; }); return { hasInteractiveMenu: true, axis: 'horizontal', menuTitle: extractHorizontalMenuTitle(lines, optionsLineIdx), selectedIndex, options, rawHint }; } function isMenuOptionStopLine(line) { const trimmed = line.trim(); if (!trimmed) return true; if (RE_MENU_BOUNDARY.test(trimmed) || RE_TUI_FOOTER.test(trimmed) || RE_APPROVAL_HEADER.test(trimmed)) { return true; } if (RE_MENU_SPINNERS.test(trimmed) || RE_MENU_RUNNING_WORDS.test(trimmed)) { return true; } if (/^[└├│⎿]/.test(trimmed)) return true; if (/[?:]$/.test(trimmed) && !RE_MENU_ACTIVE_LINE.test(line)) return true; if (!/^\s/.test(line) && !RE_MENU_ACTIVE_LINE.test(line) && !/^\d+[.)]\s+/.test(trimmed)) { return true; } return false; } function parseKiloModelMenu(lines, headerIdx, footerIdx) { const headerLine = stripBoxBorders(lines[headerIdx]); const menuTitle = headerLine.replace(/\s+esc\s*$/i, '').trim(); const endIdx = footerIdx !== -1 ? footerIdx : lines.length - 1; const rawOptions = []; let selectedIdx = -1; for (let i = headerIdx + 1; i <= endIdx; i++) { let line = stripBoxBorders(lines[i]); if (!line) continue; if (/^[─━═\-_=~]{3,}$/.test(line)) continue; if (/^●\s+Tip\b/i.test(line)) continue; if (RE_KILO_CATEGORY.test(line)) continue; if (/^Connect provider/i.test(line)) break; line = line.replace(/\s+commands\s*$/i, '').trim(); if (RE_KILO_CATEGORY.test(line)) continue; const isSelected = /^[●>❯]\s+/.test(line); const cleanLabel = line .replace(/^[●>❯]\s+/, '') .replace(/\s+May train\s*$/i, '') .replace(/\s{2,}/g, ' ') .trim(); if (!cleanLabel || cleanLabel.length < 2) continue; if (/^(?:commands|tab agents|ctrl\+[a-z])/i.test(cleanLabel)) continue; if (isSelected && selectedIdx === -1) { selectedIdx = rawOptions.length; } rawOptions.push({ index: rawOptions.length, label: cleanLabel, selected: isSelected, numberPrefix: null }); } if (selectedIdx === -1 && rawOptions.length > 0) { selectedIdx = 0; rawOptions[0].selected = true; } return { hasInteractiveMenu: true, axis: 'vertical', menuTitle: menuTitle || 'Select model', selectedIndex: selectedIdx, options: rawOptions, rawHint: footerIdx !== -1 ? lines[footerIdx].trim() : 'esc to close' }; } function parseEffortMenu(lines, headerIdx, footerIdx) { const headerLine = (headerIdx !== -1) ? stripBoxBorders(lines[headerIdx]) : 'Set Effort'; const menuTitle = headerLine.replace(/\s+esc\s*$/i, '').trim() || 'Set Effort'; const startIdx = headerIdx !== -1 ? headerIdx : Math.max(0, footerIdx - 6); const endIdx = footerIdx !== -1 ? footerIdx : Math.min(lines.length - 1, startIdx + 6); let selectedIdx = 1; // default medium let foundMarkers = false; for (let i = startIdx; i <= endIdx; i++) { const line = lines[i]; if (line.includes('◉') || (line.includes('●') && line.includes('○'))) { const markers = line.match(/[●○◉]/g); if (markers && markers.length >= 2) { const idx = markers.indexOf('◉'); if (idx !== -1) { selectedIdx = idx; foundMarkers = true; break; } } } } if (!foundMarkers) { for (let i = startIdx; i <= endIdx; i++) { const line = lines[i].toLowerCase(); if (line.includes('(current)')) { if (line.includes('low') || line.includes('concise')) selectedIdx = 0; else if (line.includes('medium') || line.includes('balanced')) selectedIdx = 1; else if (line.includes('high') || line.includes('deeper') || line.includes('stronger')) selectedIdx = 2; break; } } } const rawOptions = [ { index: 0, label: 'low', selected: selectedIdx === 0, numberPrefix: null }, { index: 1, label: 'medium', selected: selectedIdx === 1, numberPrefix: null }, { index: 2, label: 'high', selected: selectedIdx === 2, numberPrefix: null } ]; return { hasInteractiveMenu: true, axis: 'horizontal', menuTitle, selectedIndex: selectedIdx, options: rawOptions, rawHint: footerIdx !== -1 ? lines[footerIdx].trim() : '←/→ Effort enter Select esc Go Back' }; } function parseKiroControlsMenu(lines, footerIdx) { const endIdx = footerIdx !== -1 ? footerIdx : lines.length - 1; let headerIdx = -1; for (let i = endIdx - 1; i >= Math.max(0, endIdx - 10); i--) { if (/tab to switch panels/i.test(lines[i])) { headerIdx = i; break; } } const titleLine = headerIdx !== -1 ? stripBoxBorders(lines[headerIdx]) : ''; const menuTitle = titleLine ? titleLine.replace(/\s+tab to switch panels/i, '').trim() : 'Model Controls'; const startIdx = headerIdx !== -1 ? headerIdx + 1 : Math.max(0, endIdx - 6); const options = []; let selectedIdx = -1; for (let i = startIdx; i < endIdx; i++) { const raw = stripBoxBorders(lines[i]); const trimmed = raw.trim(); if (!trimmed) continue; if (/^[─━═\-_=~]{3,}$/.test(trimmed)) continue; if (/^esc\b/i.test(trimmed)) continue; const isSelected = /^[>❯●◉]\s+/.test(trimmed); const cleanText = trimmed.replace(/^[>❯●◉]\s+/, '').trim(); let optionLabel = cleanText; const kvMatch = cleanText.match(/^([A-Za-z0-9_.-]+)\s+([A-Za-z0-9_./-]+)(?:\s+(.*))?$/); if (kvMatch) { optionLabel = `${kvMatch[1]}: ${kvMatch[2]}`; } if (isSelected && selectedIdx === -1) { selectedIdx = options.length; } options.push({ index: options.length, label: optionLabel, selected: isSelected, numberPrefix: null }); } if (selectedIdx === -1 && options.length > 0) { const effortIdx = options.findIndex(o => /^effort\b/i.test(o.label)); selectedIdx = effortIdx !== -1 ? effortIdx : 0; options[selectedIdx].selected = true; } if (options.length === 0) { return null; } return { hasInteractiveMenu: true, axis: 'vertical', menuTitle: menuTitle || 'Model Controls', selectedIndex: selectedIdx, options, rawHint: footerIdx !== -1 ? lines[footerIdx].trim() : 'esc to go back · ↑↓ to navigate · ↵ to select' }; } function detectInteractiveMenu(rawOutput) { const empty = { hasInteractiveMenu: false, axis: null, menuTitle: null, selectedIndex: -1, options: [], rawHint: null }; if (!rawOutput || typeof rawOutput !== 'string') return empty; const normalized = rawOutput.replace(/\r\n?/g, '\n'); const ansiAllLines = normalized.split('\n').map(l => l.replace(/\s+$/, '')); while (ansiAllLines.length > 0 && RE_BOX_BORDER_ONLY.test(ansiAllLines[ansiAllLines.length - 1].replace(RE_ANSI, ''))) { ansiAllLines.pop(); } if (ansiAllLines.length === 0) return empty; const ansiLines = ansiAllLines.slice(-35); const lines = ansiLines.map(l => l.replace(RE_ANSI, '')); const lastTrimmed = lines[lines.length - 1].trim(); if (RE_MENU_SHELL_OR_IDLE.test(lastTrimmed)) { return empty; } let footerIdx = -1; for (let i = lines.length - 1; i >= Math.max(0, lines.length - 15); i--) { if (RE_TUI_FOOTER.test(lines[i].trim())) { footerIdx = i; break; } } const modelMenuHeaderIdx = lines.findIndex(l => RE_MODEL_MENU_HEADER.test(stripBoxBorders(l))); const tailText = lines.filter(l => l.trim()).slice(-25).join('\n'); const hasFooter = footerIdx !== -1; const hasApproval = RE_APPROVAL_HEADER.test(tailText); const hasModelMenu = modelMenuHeaderIdx !== -1; if (!hasFooter && !hasApproval && !hasModelMenu) return empty; if (hasModelMenu && /Select (?:model|variant)/i.test(lines[modelMenuHeaderIdx])) { const kiloMenu = parseKiloModelMenu(lines, modelMenuHeaderIdx, footerIdx); if (kiloMenu && kiloMenu.options.length > 0) { return kiloMenu; } } if ((hasModelMenu && /Set Effort/i.test(lines[modelMenuHeaderIdx])) || (hasFooter && /←\/?→\s*Effort/i.test(lines[footerIdx]))) { const effortMenu = parseEffortMenu(lines, modelMenuHeaderIdx, footerIdx); if (effortMenu && effortMenu.options.length > 0) { return effortMenu; } } if (hasFooter && /switch panels|at top for controls/i.test(lines[footerIdx])) { const controlsMenu = parseKiroControlsMenu(lines, footerIdx); if (controlsMenu && controlsMenu.options.length > 0) { return controlsMenu; } } if (hasFooter && RE_HORIZONTAL_FOOTER.test(lines[footerIdx])) { const horizontalMenu = parseHorizontalMenuBar(ansiLines, lines, footerIdx); if (horizontalMenu) { return horizontalMenu; } } const searchEnd = hasFooter ? Math.max(0, footerIdx - 1) : lines.length - 1; let cursorIdx = -1; const cursorRe = hasFooter ? RE_MENU_ACTIVE_LINE : RE_MENU_CURSOR_STRICT; for (let i = searchEnd; i >= Math.max(0, searchEnd - 15); i--) { if (RE_MENU_EXEC_BULLET.test(lines[i])) continue; const m = lines[i].match(cursorRe); if (!m) continue; const candidate = m[1].trim(); if (RE_TUI_FOOTER.test(candidate) || RE_APPROVAL_HEADER.test(candidate)) continue; if (RE_MENU_SPINNERS.test(candidate) || RE_MENU_RUNNING_WORDS.test(candidate)) continue; const nextNonEmpty = lines.slice(i + 1).find(l => l.trim().length > 0) || ''; if (candidate.startsWith('/') && /^\s*(?:L|└|⎿)\s+/.test(nextNonEmpty)) continue; cursorIdx = i; break; } let optionStartIdx = Math.max(0, searchEnd); let selectedIndex = -1; const options = []; if (cursorIdx !== -1) { let startIdx = cursorIdx; while (startIdx > 0 && !isMenuOptionStopLine(lines[startIdx - 1])) { startIdx--; } let endIdx = cursorIdx; while (endIdx < searchEnd) { const nextTrimmed = lines[endIdx + 1].trim(); if (!nextTrimmed || RE_MENU_BOUNDARY.test(nextTrimmed) || RE_TUI_FOOTER.test(nextTrimmed) || RE_MENU_SPINNERS.test(nextTrimmed) || RE_MENU_RUNNING_WORDS.test(nextTrimmed) || RE_MENU_SHELL_OR_IDLE.test(nextTrimmed)) { break; } endIdx++; } optionStartIdx = startIdx; for (let i = startIdx; i <= endIdx; i++) { const isCursor = i === cursorIdx; const rawText = isCursor ? lines[i].replace(/^\s*(?:[>❯]|●|◉)\s+/, '') : lines[i]; const label = rawText.replace(/\s+/g, ' ').trim(); if (!label) continue; const numMatch = label.match(/^(\d+)[.)]\s+/); options.push({ index: options.length, label, selected: isCursor, numberPrefix: numMatch ? numMatch[1] : null }); } selectedIndex = options.findIndex(o => o.selected); } else if (hasFooter) { const numbered = []; for (let i = searchEnd; i >= Math.max(0, searchEnd - 15); i--) { const t = lines[i].trim(); if (!t) { if (numbered.length > 0) break; continue; } const numMatch = t.match(/^(\d+)[.)]\s+(.+)$/); if (!numMatch) { if (numbered.length > 0) break; continue; } optionStartIdx = i; numbered.unshift({ label: t.replace(/\s+/g, ' '), numberPrefix: numMatch[1] }); } numbered.forEach((item, idx) => { options.push({ index: idx, label: item.label, selected: false, numberPrefix: item.numberPrefix }); }); } if (!hasFooter) { const approvalIdx = lines.findIndex(l => RE_APPROVAL_HEADER.test(l)); const hasPostApprovalActivity = approvalIdx !== -1 && lines.slice(approvalIdx + 1).some(l => RE_MENU_SPINNERS.test(l) || RE_MENU_RUNNING_WORDS.test(l) || RE_MENU_EXEC_BULLET.test(l) ); if (approvalIdx === -1 || hasPostApprovalActivity || selectedIndex === -1 || optionStartIdx <= approvalIdx) { return empty; } } if (!options || options.length === 0) { return empty; } let menuTitle = 'Menu Interativo'; for (let i = optionStartIdx - 1; i >= Math.max(0, optionStartIdx - 6); i--) { const t = lines[i].trim(); if (!t || /^[─━═\-_=~]{3,}$/.test(t) || /^Search:/i.test(t) || /^(?:shell|bash|cmd|tool|command)\s*→/i.test(t)) continue; if (RE_MENU_SPINNERS.test(t) || RE_MENU_RUNNING_WORDS.test(t)) continue; menuTitle = t; break; } return { hasInteractiveMenu: true, axis: 'vertical', menuTitle, selectedIndex, options, rawHint: hasFooter ? lines[footerIdx].trim() : '' }; } window.detectInteractiveMenu = detectInteractiveMenu; function sanitizeInteractiveMenu(menu, rawFallbackText = '') { const emptyMenu = { hasInteractiveMenu: false, axis: null, menuTitle: null, selectedIndex: -1, options: [], rawHint: null }; if (!menu || !menu.hasInteractiveMenu) return emptyMenu; const rawOptions = Array.isArray(menu.options) ? menu.options : []; let hadBorderOption = false; let removedSelectedBorder = false; const kept = []; for (const opt of rawOptions) { const rawLabel = String(opt && opt.label !== undefined ? opt.label : ''); if (RE_BOX_BORDER_TOKEN.test(rawLabel.trim())) { hadBorderOption = true; if (opt?.selected || opt?.index === menu.selectedIndex) { removedSelectedBorder = true; } continue; } const cleanLabel = stripBoxBorders(rawLabel).trim(); if (!cleanLabel || RE_BOX_BORDER_TOKEN.test(cleanLabel)) { hadBorderOption = true; if (opt?.selected || opt?.index === menu.selectedIndex) { removedSelectedBorder = true; } continue; } kept.push({ ...opt, label: cleanLabel, selected: Boolean(opt?.selected || (!hadBorderOption && typeof menu.selectedIndex === 'number' && opt?.index === menu.selectedIndex)) }); } if (hadBorderOption && typeof rawFallbackText === 'string' && rawFallbackText.trim()) { const reparsed = detectInteractiveMenu(rawFallbackText); if (reparsed && reparsed.hasInteractiveMenu && Array.isArray(reparsed.options) && reparsed.options.length > 0) { return { ...reparsed, menuTitle: reparsed.menuTitle ? stripBoxBorders(String(reparsed.menuTitle)).trim() || null : null, rawHint: reparsed.rawHint ? stripBoxBorders(String(reparsed.rawHint)).replace(/\s{2,}/g, ' ').trim() : '' }; } } if (kept.length === 0) return emptyMenu; let selectedIndex = kept.findIndex(o => o.selected); if (selectedIndex < 0 && (removedSelectedBorder || menu.selectedIndex === 0)) { selectedIndex = 0; } const normalizedOptions = kept.map((opt, idx) => ({ ...opt, index: idx, selected: idx === selectedIndex })); const cleanTitle = menu.menuTitle ? (stripBoxBorders(String(menu.menuTitle)).trim() || null) : null; const cleanHint = menu.rawHint ? stripBoxBorders(String(menu.rawHint)).replace(/\s{2,}/g, ' ').trim() : ''; return { ...menu, hasInteractiveMenu: true, axis: menu.axis === 'horizontal' ? 'horizontal' : 'vertical', menuTitle: cleanTitle, selectedIndex, options: normalizedOptions, rawHint: cleanHint }; } function sendTerminalRawInput(rawSeq, keysArray = null) { if (!activeChatAgent) return; const targetPin = activeChatPin ? String(activeChatPin) : (currentPin ? String(currentPin) : null); const entry = targetPin ? stationPool.get(String(targetPin)) : null; const targetWs = entry?.ws || ws; if (!targetWs || targetWs.readyState !== WebSocket.OPEN) { showToast('Estação offline ou reconectando...', 'warning'); return; } const payload = { type: 'TERMINAL_RAW_INPUT', agentName: activeChatAgent }; if (Array.isArray(keysArray) && keysArray.length > 0) { payload.keys = keysArray; payload.raw = (typeof rawSeq === 'string' && rawSeq.length > 0) ? rawSeq : keysArray.join(''); } else if (typeof rawSeq === 'string' && rawSeq.length > 0) { payload.raw = rawSeq; } else { return; } targetWs.send(JSON.stringify(payload)); } window.sendTerminalRawInput = sendTerminalRawInput; let restartButtonTimeout = null; function resetRestartButtonState() { if (restartButtonTimeout) { clearTimeout(restartButtonTimeout); restartButtonTimeout = null; } if (!btnRestartTerminal) return; btnRestartTerminal.classList.remove('restarting'); btnRestartTerminal.disabled = false; } function restartActiveAgentTerminal() { if (!activeChatAgent) return; const targetPin = activeChatPin ? String(activeChatPin) : (currentPin ? String(currentPin) : null); const entry = targetPin ? stationPool.get(String(targetPin)) : null; const targetWs = entry?.ws || ws; if (btnRestartTerminal?.classList.contains('restarting')) { return; } const activeAgentInfo = entry?.agents?.find(a => a.name === activeChatAgent); if (activeAgentInfo?.isSelf) { showToast('ℹ️ O terminal do daemon supervisor não pode ser reiniciado remotamente por aqui.', 'warning'); return; } if (!targetWs || targetWs.readyState !== WebSocket.OPEN) { showToast('Estação offline ou reconectando...', 'warning'); return; } if (btnRestartTerminal) { btnRestartTerminal.classList.add('restarting'); btnRestartTerminal.disabled = true; restartButtonTimeout = setTimeout(() => { resetRestartButtonState(); }, 30000); if (typeof restartButtonTimeout?.unref === 'function') { restartButtonTimeout.unref(); } } // Limpa histórico de chat e buffers no APK ao reiniciar para iniciar nova sessão limpa setAgentChatHistory(activeChatAgent, targetPin, []); if (activeChatAgent) { const scopedKey = getAgentScopedKey(activeChatAgent, targetPin); unreadResponseCounts.delete(scopedKey); } if (chatMessagesEl) { chatMessagesEl.innerHTML = ''; } if (chatTerminalOutputRaw) { chatTerminalOutputRaw.textContent = 'Aguardando inicialização da nova sessão...'; } isWaitingChatReply = false; hadThinkingDuringReply = false; isTuiPanelManualOpen = false; currentInteractiveMenu = null; renderTuiPanel(null); removeAgentTyping(); stopThinkingTimer(); updateAgentThinkingUI('', false); appendTerminalLoading(); captureAndSendScreenStateSnapshot(activeChatAgent, 'restart_clear'); showToast(`🔄 Reiniciando terminal ${activeChatAgent} via Maestri...`, 'info'); targetWs.send(JSON.stringify({ type: 'RESTART_AGENT_TERMINAL', agentName: activeChatAgent })); } window.restartActiveAgentTerminal = restartActiveAgentTerminal; function renderTuiPanel(menu) { const sanitizedMenu = (menu && menu.hasInteractiveMenu) ? sanitizeInteractiveMenu(menu) : null; currentInteractiveMenu = (sanitizedMenu && sanitizedMenu.hasInteractiveMenu) ? sanitizedMenu : null; const hasMenu = !!currentInteractiveMenu; const shouldShow = hasMenu || isTuiPanelManualOpen; if (btnTuiToggle) { btnTuiToggle.classList.toggle('active', isTuiPanelManualOpen); } if (!chatTuiPanel) return; chatTuiPanel.style.display = shouldShow ? 'flex' : 'none'; if (!shouldShow) return; const options = hasMenu && Array.isArray(currentInteractiveMenu.options) ? currentInteractiveMenu.options : []; const showKeypad = isTuiPanelManualOpen || options.length === 0; if (chatTuiKeypad) { chatTuiKeypad.style.display = showKeypad ? 'grid' : 'none'; } if (chatTuiTitle) { chatTuiTitle.textContent = hasMenu ? `🎛️ ${currentInteractiveMenu.menuTitle || 'Menu Interativo Detectado'}` : '⌨️ Teclas de Navegação TUI'; } if (chatTuiHint) { chatTuiHint.textContent = hasMenu ? (currentInteractiveMenu.rawHint || (showKeypad ? 'Toque numa opção ou use as teclas' : 'Toque na ação desejada')) : 'Envio direto de setas e atalhos (--raw)'; } if (chatTuiOptionsEl) { chatTuiOptionsEl.innerHTML = ''; chatTuiOptionsEl.classList.toggle('horizontal', hasMenu && currentInteractiveMenu.axis === 'horizontal'); if (options.length > 0) { chatTuiOptionsEl.style.display = 'flex'; options.forEach((opt) => { const btn = document.createElement('button'); btn.type = 'button'; btn.className = `btn-tui-option${opt.selected ? ' selected' : ''}`; btn.textContent = opt.selected ? `❯ ${opt.label}` : opt.label; btn.addEventListener('click', () => { const selIdx = typeof currentInteractiveMenu.selectedIndex === 'number' ? currentInteractiveMenu.selectedIndex : -1; const axis = currentInteractiveMenu.axis === 'horizontal' ? 'horizontal' : 'vertical'; const nextKey = axis === 'horizontal' ? '\\e[C' : '\\e[B'; const prevKey = axis === 'horizontal' ? '\\e[D' : '\\e[A'; if (selIdx >= 0) { const delta = opt.index - selIdx; if (delta === 0) { sendTerminalRawInput('\\n', ['\\n']); } else if (delta > 0) { const keys = [...Array(delta).fill(nextKey), '\\n']; sendTerminalRawInput(keys.join(''), keys); } else { const keys = [...Array(Math.abs(delta)).fill(prevKey), '\\n']; sendTerminalRawInput(keys.join(''), keys); } } else if (opt.numberPrefix) { sendTerminalRawInput(`${opt.numberPrefix}\\n`); } else { sendTerminalRawInput('\\n', ['\\n']); } }); chatTuiOptionsEl.appendChild(btn); }); } else { chatTuiOptionsEl.style.display = 'none'; } } } function detectAgentThinking(terminalText, isWaiting = false) { if (!terminalText || typeof terminalText !== 'string') { return { isThinking: isWaiting, isPaused: false, label: isWaiting ? 'Aguardando agente...' : '' }; } const raw = terminalText.trim(); const lastChunk = raw.slice(-800); // 0. Detecção de Limite de Cota / Rate Limit / Pausa de Agente const isUsageLimit = /(?:usage limit reached|limit resets|continuing automatically at|you've hit your \d+-hour limit|rate limit reached|quota exceeded)/i.test(lastChunk); if (isUsageLimit) { const timeMatch = lastChunk.match(/(?:resets|continuing automatically at)\s+([0-9]{1,2}:[0-9]{2}(?:\s*[ap]m)?)/i); const resetTime = timeMatch ? timeMatch[1] : null; const label = resetTime ? `Limite de cota atingido · Reseta às ${resetTime}` : 'Limite de cota atingido (Aguardando reset)'; return { isThinking: false, isPaused: true, resetTime, label }; } // 0.5 Precedência de Menu Interativo TUI: nunca classificar menu aberto como pensando const menu = detectInteractiveMenu(terminalText); if (menu.hasInteractiveMenu) { return { isThinking: false, isPaused: false, hasInteractiveMenu: true, interactiveMenu: menu, label: 'Aguardando seleção em menu interativo' }; } // 1. PRECEDÊNCIA MÁXIMA: Se o terminal está no prompt ocioso de entrada de IA const lines = raw.split(/\r?\n/).map(l => l.trim()).filter(Boolean); const lastLine = lines.length > 0 ? lines[lines.length - 1] : ''; const prevLine = lines.length > 1 ? lines[lines.length - 2] : ''; const prevPrevLine = lines.length > 2 ? lines[lines.length - 3] : ''; const hasActiveSubagentOrToolOnPrev = /\d+\s+subagent\(s\)/i.test(lastLine) || /●\s*Agent\(/i.test(prevLine) || /[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ]/.test(prevLine) || /(?:running command|generating|percolating|analyzing|working\.\.\.|building|compiling|thinking\.\.\.|Kiro is working)/i.test(prevLine); const isAtIdlePrompt = !(/\d+\s+subagent\(s\)/i.test(lastLine)) && ( /^(?:│\s*)?[>❯›]\s*[\u2588\u258C\u258E]?(?:ask a question or describe a task(?:\s*↵)?)?$/i.test(lastLine) || /^(?:Claude>|kiro>|gemini-cli>|aider>)\s*$/i.test(lastLine) || (/^\??\s*for shortcuts/i.test(lastLine) && !hasActiveSubagentOrToolOnPrev && (/^(?:│\s*)?[>❯›]\s*$/.test(prevLine) || /^(?:│\s*)?[>❯›]\s*$/.test(prevPrevLine) || /Gemini/i.test(prevLine) || /Claude/i.test(prevLine))) ); if (isAtIdlePrompt) { return { isThinking: false, isPaused: false, label: 'Pronto' }; } // 2. Termos específicos de status ativo detectados if (/percolating/i.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Processando tokens (Percolating)...' }; } if (/(?:^|\n|\s)(?:[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ●○⚡✽✻✶]\s*)?running command/i.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Executando comando...' }; } if (/(?:^|\n|\s)(?:[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ●○⚡✽✻✶]\s*)?generating/i.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Gerando resposta...' }; } if (/(?:^|\n|\s)(?:[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ●○⚡✽✻✶]\s*)?analyzing/i.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Analisando código...' }; } if (/(?:^|\n|\s)(?:[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ●○⚡✽✻✶]\s*)?(?:searching|fetching)/i.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Pesquisando arquivos / web...' }; } if (/(?:^|\n|\s)(?:[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ●○⚡✽✻✶]\s*)?(?:compiling|building)/i.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Compilando / Build em andamento...' }; } if (/(?:^|\n|\s)(?:[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ●○⚡✽✻✶]\s*)?thinking(?:\.\.\.(?=\s|$|\(|\[|\.|,|;|:)|\b)/i.test(lastChunk) && !/\.thinking|isThinking/i.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Pensando na resposta...' }; } if ( /(?:^|\n|\s)(?:[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ●○⚡✽✻✶]\s*)?Kiro is working(?:\s|·|$)/i.test(lastChunk) || /(?:^|\n|\s)(?:[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ●○⚡✽✻✶]\s*)?working\.\.\.(?=\s|$|\(|\[|\.|,|;|:)/i.test(lastChunk) || /(?:^|\n)\s*[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ●⚡]\s*working\b(?!\s+(?:directory|dir|tree|copy|branch|on\s+it|hours|day))/i.test(lastChunk) ) { return { isThinking: true, isPaused: false, label: 'Trabalhando na tarefa...' }; } // 3. Spinners Unicode / Braille / Pac-Man ativos (Claude Code, AGY, Kiro) if (/[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ]/.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Agente em execução...' }; } // 4. Símbolos de atividade do Claude Code if (/[✽✻✶✹✸]/.test(lastChunk) && !/(done|completed|finished)/i.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Processando no Claude Code...' }; } // 5. Símbolos de execução (Gemini CLI, AGY, Claude Code, Kiro) if (/^esc to (?:cancel|interrupt)\s*$/im.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Executando comando no agente...' }; } if (/\d+\s+subagent\(s\)/i.test(lastChunk) || (/●\s*Agent\(/i.test(lastChunk) && !isAtIdlePrompt)) { return { isThinking: true, isPaused: false, label: 'Executando subagente...' }; } if (/(Thought for|Ran \(|Explored |Edited )/i.test(lastChunk) && !/\? for shortcuts/i.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Executando ações no workspace...' }; } // 6. Se o usuário acabou de enviar uma mensagem e ainda está aguardando if (isWaiting) { return { isThinking: true, isPaused: false, label: 'Agente está pensando...' }; } return { isThinking: false, isPaused: false, label: '' }; } window.detectAgentThinking = detectAgentThinking; function updateAgentThinkingUI(terminalText, isWaiting, authoritativeStatus = null) { const result = (authoritativeStatus && typeof authoritativeStatus.isThinking === 'boolean') ? authoritativeStatus : detectAgentThinking(terminalText, isWaiting); const isThinking = result.isThinking; const isPaused = !!result.isPaused; const stationPrefix = activeChatMachine ? `${escapeHtml(activeChatMachine)} · ` : ''; if (chatAgentStatusDot) { if (isPaused) { chatAgentStatusDot.className = 'status-dot paused'; chatAgentStatusDot.style.backgroundColor = '#fb923c'; } else if (isThinking) { chatAgentStatusDot.className = 'status-dot thinking'; chatAgentStatusDot.style.backgroundColor = '#fbbf24'; } else { chatAgentStatusDot.className = 'status-dot active'; chatAgentStatusDot.style.backgroundColor = '#38bdf8'; } } if (chatAgentSubtitle) { if (isPaused) { chatAgentSubtitle.innerHTML = `${stationPrefix}⏸️ ${escapeHtml(result.label || 'Limite de uso atingido')}`; } else if (isThinking) { chatAgentSubtitle.innerHTML = `${stationPrefix}⚡ ${escapeHtml(result.label || 'Pensando / Executando...')}`; } else { chatAgentSubtitle.innerHTML = `${stationPrefix}🟢 Pronto · Terminal Conectado`; } } if (chatThinkingBanner) { chatThinkingBanner.style.display = isThinking ? 'flex' : 'none'; } if (chatThinkingText && isThinking) { chatThinkingText.textContent = `${activeChatAgent || 'Agente'}: ${result.label || 'pensando...'}`; } return isThinking; } function updateTerminalSnapshotInPlace(terminalText, isThinking, isPausedParam = null, pauseResetTimeParam = null) { let card = document.getElementById('chat-terminal-snapshot-card'); let body = document.getElementById('chat-terminal-snapshot-body'); let dot = document.getElementById('chat-terminal-status-dot'); let pill = document.getElementById('chat-terminal-state-pill'); const cleaned = cleanTerminalOutput(terminalText || 'Terminal pronto.'); const detection = detectAgentThinking(terminalText); const isPaused = typeof isPausedParam === 'boolean' ? isPausedParam : !!detection.isPaused; const resetTime = pauseResetTimeParam || detection.resetTime; const pillClass = isThinking ? 'thinking' : (isPaused ? 'paused' : 'idle'); const pillText = isThinking ? '⚡ Pensando' : (isPaused ? (resetTime ? `⏸️ Reseta às ${resetTime}` : '⏸️ Aguardando cota') : '🟢 Pronto'); if (!card) { if (!chatMessagesEl) return false; card = document.createElement('div'); card.className = 'chat-bubble agent terminal-snapshot'; card.id = 'chat-terminal-snapshot-card'; card.innerHTML = `
Terminal Atual — ${escapeHtml(activeChatAgent)}
${escapeHtml(pillText)}
${escapeHtml(cleaned)}
`; const prevScrollTop = chatMessagesEl.scrollTop; if (chatMessagesEl.firstChild) { chatMessagesEl.insertBefore(card, chatMessagesEl.firstChild); } else { chatMessagesEl.appendChild(card); } if (isUserScrolledUp) { chatMessagesEl.scrollTop = prevScrollTop; } return true; } if (body && body.textContent !== cleaned) { body.textContent = cleaned; } if (dot) { dot.className = `status-dot ${isThinking ? 'thinking' : (isPaused ? 'paused' : 'active')}`; dot.style.backgroundColor = isPaused ? '#fb923c' : (isThinking ? '#fbbf24' : '#38bdf8'); } if (pill) { pill.className = `agent-state-pill ${pillClass}`; pill.textContent = pillText; } return true; } function updateThinkingBubbleInPlace(terminalText, isThinking, authoritativeStatus = null) { let indicator = document.getElementById('chat-typing-indicator'); if (!isThinking) { stopThinkingTimer(); if (indicator) { indicator.remove(); } return; } startThinkingTimer(); const detection = (authoritativeStatus && authoritativeStatus.label) ? authoritativeStatus : detectAgentThinking(terminalText, isWaitingChatReply); const actionText = extractLatestAction(terminalText) || detection.label || 'Processando solicitação...'; if (indicator && indicator.classList.contains('thinking-card')) { const actionBadge = indicator.querySelector('.thinking-action-badge'); if (actionBadge) { actionBadge.textContent = `⚡ ${actionText}`; } } else { if (indicator) { indicator.remove(); } const thinkingBubble = document.createElement('div'); thinkingBubble.className = 'chat-bubble thinking-card'; thinkingBubble.id = 'chat-typing-indicator'; thinkingBubble.innerHTML = `
${escapeHtml(activeChatAgent || 'Agente')} está trabalhando
${formatElapsed(thinkingStartTime)}
⚡ ${escapeHtml(actionText)}
`; if (chatMessagesEl) { chatMessagesEl.appendChild(thinkingBubble); if (!isUserScrolledUp) { chatMessagesEl.scrollTop = chatMessagesEl.scrollHeight; } } } } // Telemetria: Coleta e envio do snapshot do estado de tela do app móvel para cada terminal function captureAndSendScreenStateSnapshot(agentName, reason = 'state_change') { const targetAgent = agentName || activeChatAgent; if (!targetAgent) return; try { const pin = activeChatPin || (stationPool.size > 0 ? stationPool.keys().next().value : null); const stationEntry = pin ? stationPool.get(String(pin)) : null; const targetWs = stationEntry ? stationEntry.ws : null; const isWsConnected = Boolean(targetWs && targetWs.readyState === 1); const histKey = `${pin}:${targetAgent}`; const hist = getAgentChatHistory(targetAgent, pin); // Filtra mensagens excluindo snapshots puros de terminal const realMessages = hist.filter(h => !h.isTerminalSnapshot); const lastUser = [...realMessages].reverse().find(m => m.role === 'user'); const lastAgent = [...realMessages].reverse().find(m => m.role === 'agent'); const isThinking = agentThinkingStates.get(histKey) || false; const bannerVisible = chatThinkingBanner ? chatThinkingBanner.style.display !== 'none' : false; const bannerText = chatThinkingText ? chatThinkingText.textContent : ''; let drawerActive = 'none'; if (chatDrawer && chatDrawer.style.display === 'flex') drawerActive = 'chat'; const isTerminalExpanded = Boolean(chatTerminalCollapsibleContent && chatTerminalCollapsibleContent.style.display !== 'none'); const snapshot = { agentName: targetAgent, isThinking: !!isThinking, bannerVisible, bannerText, drawerActive, isTerminalExpanded, isWaitingChatReply, hadThinkingDuringReply, chatBubblesCount: realMessages.length, lastUserMessage: lastUser ? { text: (lastUser.text || '').slice(0, 120), timestamp: lastUser.timestamp } : null, lastAgentMessage: lastAgent ? { text: (lastAgent.text || '').slice(0, 120), timestamp: lastAgent.timestamp } : null, connectionStatus: isWsConnected ? 'connected' : 'disconnected', capturedAt: new Date().toISOString() }; // 1. Envio prioritário via WebSocket direto if (isWsConnected && pin) { targetWs.send(JSON.stringify({ type: 'SCREEN_STATE_SNAPSHOT', agentName: targetAgent, action: reason, summary: `Snapshot [${reason}]: thinking=${isThinking}, banner=${bannerVisible}, msgs=${realMessages.length}`, payload: snapshot })); } else { // 2. Fallback via HTTP POST caso WebSocket esteja reconectando fetch('/api/telemetry/log', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ source: 'mobile', pin: pin ? String(pin) : null, agentName: targetAgent, category: 'screen_state', action: reason, summary: `Snapshot HTTP [${reason}]: thinking=${isThinking}, msgs=${realMessages.length}`, payload: snapshot }) }).catch(() => {}); } } catch (err) { console.warn('[Telemetry] Falha ao capturar snapshot de tela:', err.message); } } // Heartbeat leve a cada 30 segundos para manter snapshot atualizado enquanto ativo setInterval(() => { if (activeChatAgent && chatDrawer && chatDrawer.style.display === 'flex') { captureAndSendScreenStateSnapshot(activeChatAgent, 'heartbeat_30s'); } }, 30000); function renderChatMessages(forceScroll = false) { if (!chatMessagesEl || !activeChatAgent) return; const threshold = 60; const wasAtBottom = (chatMessagesEl.scrollHeight - chatMessagesEl.scrollTop - chatMessagesEl.clientHeight) <= threshold; const prevScrollTop = chatMessagesEl.scrollTop; chatMessagesEl.innerHTML = ''; const histKey = activeChatPin ? `${activeChatPin}:${activeChatAgent}` : activeChatAgent; const history = getAgentChatHistory(activeChatAgent, activeChatPin); let terminalSnapshotText = ''; let terminalSnapshotRawText = ''; history.forEach(item => { if (item.isTerminalSnapshot) { terminalSnapshotText = item.text || ''; terminalSnapshotRawText = item.rawText || item.text || ''; const bubble = document.createElement('div'); bubble.className = 'chat-bubble agent terminal-snapshot'; bubble.id = 'chat-terminal-snapshot-card'; const cleaned = cleanTerminalOutput(item.text); const detection = detectAgentThinking(terminalSnapshotRawText, isWaitingChatReply); const isThinking = !detection.hasInteractiveMenu && detection.isThinking; const isPaused = !detection.hasInteractiveMenu && !!detection.isPaused; const pillClass = isThinking ? 'thinking' : (isPaused ? 'paused' : 'idle'); const pillText = isThinking ? '⚡ Pensando' : (isPaused ? (detection.resetTime ? `⏸️ Reseta às ${detection.resetTime}` : '⏸️ Aguardando cota') : '🟢 Pronto'); bubble.innerHTML = `
Terminal Atual — ${escapeHtml(activeChatAgent)}
${escapeHtml(pillText)}
${escapeHtml(cleaned)}
`; chatMessagesEl.appendChild(bubble); } else { const bubble = document.createElement('div'); bubble.className = `chat-bubble ${item.role}`; bubble.textContent = cleanTerminalOutput(item.text); const itemsToRender = Array.isArray(item.attachments) && item.attachments.length > 0 ? item.attachments : (item.attachment ? [item.attachment] : []); if (itemsToRender.length > 0) { const attachBox = document.createElement('div'); attachBox.className = 'chat-attachment-bubble'; const imageItems = itemsToRender.filter(att => att && att.isImage && att.dataUrl); const fileItems = itemsToRender.filter(att => att && (!att.isImage || !att.dataUrl)); if (imageItems.length === 1 && fileItems.length === 0) { attachBox.innerHTML = `${escapeHtml(imageItems[0].name)}`; } else if (imageItems.length > 1) { const grid = document.createElement('div'); grid.className = 'chat-attachment-grid'; imageItems.forEach(imgAtt => { const imgEl = document.createElement('img'); imgEl.src = imgAtt.dataUrl; imgEl.alt = escapeHtml(imgAtt.name); imgEl.title = escapeHtml(imgAtt.name); grid.appendChild(imgEl); }); attachBox.appendChild(grid); } if (fileItems.length > 0) { const fileListEl = document.createElement('div'); fileListEl.className = 'chat-attachment-file-list'; fileItems.forEach(fAtt => { const row = document.createElement('div'); row.className = 'chat-attachment-file'; row.innerHTML = ` ${escapeHtml(fAtt.name)} `; fileListEl.appendChild(row); }); attachBox.appendChild(fileListEl); } bubble.appendChild(attachBox); } chatMessagesEl.appendChild(bubble); } }); // Card dinâmico no final da conversa enquanto o agente trabalha const terminalToCheck = terminalSnapshotRawText || terminalSnapshotText || lastTerminalOutputs.get(histKey) || ''; const detection = detectAgentThinking(terminalToCheck, isWaitingChatReply); const activeAgentInfo = activeChatPin ? stationPool.get(String(activeChatPin))?.agents?.find(a => a.name === activeChatAgent) : null; const hasActiveMenu = (activeAgentInfo && typeof activeAgentInfo.hasInteractiveMenu === 'boolean') ? activeAgentInfo.hasInteractiveMenu : Boolean(detection.hasInteractiveMenu || (currentInteractiveMenu && currentInteractiveMenu.hasInteractiveMenu)); const showThinkingCard = !hasActiveMenu && !detection.isPaused && (isWaitingChatReply || detection.isThinking); if (showThinkingCard) { startThinkingTimer(); const actionText = extractLatestAction(terminalToCheck) || detection.label || 'Processando solicitação...'; const thinkingBubble = document.createElement('div'); thinkingBubble.className = 'chat-bubble thinking-card'; thinkingBubble.id = 'chat-typing-indicator'; thinkingBubble.innerHTML = `
${escapeHtml(activeChatAgent || 'Agente')} está trabalhando
${formatElapsed(thinkingStartTime)}
⚡ ${escapeHtml(actionText)}
`; chatMessagesEl.appendChild(thinkingBubble); } else { stopThinkingTimer(); } // Auto-scroll inteligente: só força scroll para o fim se explicitamente solicitado ou se não estiver com scroll para cima e estava no rodapé if (forceScroll || (!isUserScrolledUp && wasAtBottom)) { chatMessagesEl.scrollTop = chatMessagesEl.scrollHeight; isUserScrolledUp = false; if (btnChatScrollBottom) btnChatScrollBottom.style.display = 'none'; } else { chatMessagesEl.scrollTop = prevScrollTop; if (btnChatScrollBottom) btnChatScrollBottom.style.display = isUserScrolledUp ? 'flex' : 'none'; } } function appendTerminalLoading() { if (!chatMessagesEl) return; removeAgentTyping(); const loading = document.createElement('div'); loading.id = 'chat-typing-indicator'; loading.className = 'chat-bubble typing'; loading.textContent = `Lendo saída do terminal de ${activeChatAgent || 'Agente'}...`; chatMessagesEl.appendChild(loading); if (!isUserScrolledUp) { chatMessagesEl.scrollTop = chatMessagesEl.scrollHeight; } } let typingTimeoutTimer = null; function appendAgentTyping() { clearTimeout(typingTimeoutTimer); typingTimeoutTimer = setTimeout(() => { if (isWaitingChatReply) { isWaitingChatReply = false; stopThinkingTimer(); renderChatMessages(); const alertBubble = document.createElement('div'); alertBubble.className = 'chat-bubble agent'; alertBubble.style.borderColor = 'rgba(245, 158, 11, 0.4)'; alertBubble.textContent = '⏳ Tempo limite: o agente demorou mais de 15 minutos para responder ou a estação desconectou.'; if (chatMessagesEl) { chatMessagesEl.appendChild(alertBubble); chatMessagesEl.scrollTop = chatMessagesEl.scrollHeight; } } }, 900000); } function removeAgentTyping() { clearTimeout(typingTimeoutTimer); typingTimeoutTimer = null; const typing = document.getElementById('chat-typing-indicator'); if (typing) typing.remove(); } function setupChatEvents() { const handleClose = (e) => { if (e) { e.preventDefault(); e.stopPropagation(); } closeChat(); }; if (btnCloseChat) { btnCloseChat.addEventListener('click', handleClose); btnCloseChat.addEventListener('touchend', handleClose); } const btnRefreshChat = document.getElementById('btn-refresh-chat'); if (btnRefreshChat) { const handleRefresh = (e) => { if (e) e.preventDefault(); if (activeChatAgent) { appendTerminalLoading(); requestAgentTerminal(activeChatAgent, activeChatPin); } }; btnRefreshChat.addEventListener('click', handleRefresh); btnRefreshChat.addEventListener('touchend', handleRefresh); } if (btnRestartTerminal) { const handleRestart = (e) => { if (e) e.preventDefault(); restartActiveAgentTerminal(); }; btnRestartTerminal.addEventListener('click', handleRestart); btnRestartTerminal.addEventListener('touchend', handleRestart); } if (btnTuiToggle) { btnTuiToggle.addEventListener('click', (e) => { e.preventDefault(); isTuiPanelManualOpen = !isTuiPanelManualOpen; renderTuiPanel(currentInteractiveMenu); }); } if (chatTuiPanel) { chatTuiPanel.querySelectorAll('.btn-tui-key').forEach((keyBtn) => { keyBtn.addEventListener('click', (e) => { e.preventDefault(); const rawSeq = keyBtn.getAttribute('data-raw'); if (rawSeq) { sendTerminalRawInput(rawSeq); } }); }); } if (chatBackdrop) { chatBackdrop.addEventListener('click', handleClose); chatBackdrop.addEventListener('touchend', handleClose); } if (chatMessagesEl) { chatMessagesEl.addEventListener('scroll', () => { const threshold = 60; const distanceFromBottom = chatMessagesEl.scrollHeight - chatMessagesEl.scrollTop - chatMessagesEl.clientHeight; isUserScrolledUp = distanceFromBottom > threshold; if (btnChatScrollBottom) { btnChatScrollBottom.style.display = isUserScrolledUp ? 'flex' : 'none'; } }); } if (btnChatScrollBottom) { const handleScrollBottom = (e) => { if (e) e.preventDefault(); if (chatMessagesEl) { if (typeof chatMessagesEl.scrollTo === 'function') { chatMessagesEl.scrollTo({ top: chatMessagesEl.scrollHeight, behavior: 'smooth' }); } else { chatMessagesEl.scrollTop = chatMessagesEl.scrollHeight; } } isUserScrolledUp = false; btnChatScrollBottom.style.display = 'none'; }; btnChatScrollBottom.addEventListener('click', handleScrollBottom); btnChatScrollBottom.addEventListener('touchend', handleScrollBottom); } window.addEventListener('keydown', (e) => { if (e.key === 'Escape') { if (attachMenu && attachMenu.style.display !== 'none') { toggleAttachMenu(false); return; } closeChat(); closeStationModal(); } }); function clearFileInputs() { if (chatFileInput) chatFileInput.value = ''; if (chatCameraInput) chatCameraInput.value = ''; if (chatGalleryInput) chatGalleryInput.value = ''; } function optimizeImageFile(file, maxDimension = 2048, quality = 0.82) { return new Promise((resolve) => { if (!file || !file.type.startsWith('image/') || file.type === 'image/gif' || file.type === 'image/svg+xml') { const reader = new FileReader(); reader.onload = (e) => { const dataUrl = e.target.result; resolve({ name: file.name, mimeType: file.type || 'application/octet-stream', size: file.size, dataUrl, dataBase64: (dataUrl || '').split(',')[1] || '' }); }; reader.readAsDataURL(file); return; } const reader = new FileReader(); reader.onload = (e) => { const rawDataUrl = e.target.result; // Se o ambiente não suporta Canvas 2D (ex: Node/JSDOM ou browser restrito), bypass imediato let hasCanvas = false; try { const testCanvas = document.createElement('canvas'); hasCanvas = !!(testCanvas && testCanvas.getContext && testCanvas.getContext('2d')); } catch { hasCanvas = false; } if (!hasCanvas || typeof Image === 'undefined') { resolve({ name: file.name, mimeType: file.type, size: file.size, dataUrl: rawDataUrl, dataBase64: (rawDataUrl || '').split(',')[1] || '' }); return; } const fallbackTimer = setTimeout(() => { resolve({ name: file.name, mimeType: file.type, size: file.size, dataUrl: rawDataUrl, dataBase64: (rawDataUrl || '').split(',')[1] || '' }); }, 300); const img = new Image(); img.onload = () => { clearTimeout(fallbackTimer); let width = img.width || 0; let height = img.height || 0; if ((width <= maxDimension && height <= maxDimension && file.size < 1.5 * 1024 * 1024) || !width || !height) { resolve({ name: file.name, mimeType: file.type, size: file.size, dataUrl: rawDataUrl, dataBase64: (rawDataUrl || '').split(',')[1] || '' }); return; } if (width > height) { if (width > maxDimension) { height = Math.round((height * maxDimension) / width); width = maxDimension; } } else { if (height > maxDimension) { width = Math.round((width * maxDimension) / height); height = maxDimension; } } try { const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); if (!ctx) throw new Error('Contexto 2D indisponível'); ctx.drawImage(img, 0, 0, width, height); const optimizedDataUrl = canvas.toDataURL('image/jpeg', quality); const base64Data = (optimizedDataUrl || '').split(',')[1] || ''; const estimatedSize = Math.round((base64Data.length * 3) / 4); let fileName = file.name; if (!fileName.toLowerCase().endsWith('.jpg') && !fileName.toLowerCase().endsWith('.jpeg')) { fileName = fileName.replace(/\.[^/.]+$/, "") + ".jpg"; } resolve({ name: fileName, mimeType: 'image/jpeg', size: estimatedSize, dataUrl: optimizedDataUrl, dataBase64: base64Data }); } catch { resolve({ name: file.name, mimeType: file.type, size: file.size, dataUrl: rawDataUrl, dataBase64: (rawDataUrl || '').split(',')[1] || '' }); } }; img.onerror = () => { clearTimeout(fallbackTimer); resolve({ name: file.name, mimeType: file.type, size: file.size, dataUrl: rawDataUrl, dataBase64: (rawDataUrl || '').split(',')[1] || '' }); }; img.src = rawDataUrl; }; reader.readAsDataURL(file); }); } function renderAttachmentPreview() { currentAttachment = currentAttachments[0] || null; if (!attachmentPreviewBar) return; if (currentAttachments.length === 0) { attachmentPreviewBar.style.display = 'none'; if (attachmentNameEl) attachmentNameEl.textContent = ''; if (attachmentSizeEl) attachmentSizeEl.textContent = ''; if (attachmentThumbWrapper) attachmentThumbWrapper.innerHTML = ''; if (attachmentList) attachmentList.innerHTML = ''; if (attachmentSummaryBadge) attachmentSummaryBadge.style.display = 'none'; clearFileInputs(); return; } attachmentPreviewBar.style.display = 'flex'; // Mantém compatibilidade com elementos legados if (attachmentNameEl && currentAttachment) { attachmentNameEl.textContent = currentAttachment.name; } if (attachmentSizeEl && currentAttachment) { attachmentSizeEl.textContent = formatBytes(currentAttachment.size); } if (attachmentThumbWrapper && currentAttachment) { if (currentAttachment.isImage && currentAttachment.dataUrl) { attachmentThumbWrapper.innerHTML = `Thumbnail`; } else { attachmentThumbWrapper.innerHTML = ``; } } // Renderiza lista de chips interativos if (attachmentList) { attachmentList.innerHTML = ''; currentAttachments.forEach((att, idx) => { const chip = document.createElement('div'); chip.className = 'attachment-chip'; chip.dataset.index = idx; const thumb = document.createElement('div'); thumb.className = 'attachment-chip-thumb'; if (att.isImage && att.dataUrl) { thumb.innerHTML = `${escapeHtml(att.name)}`; } else { thumb.innerHTML = ``; } const info = document.createElement('div'); info.className = 'attachment-chip-info'; info.innerHTML = ` ${escapeHtml(att.name)} ${formatBytes(att.size)} `; const btnRemove = document.createElement('button'); btnRemove.type = 'button'; btnRemove.className = 'attachment-chip-remove'; btnRemove.setAttribute('aria-label', `Remover ${att.name}`); btnRemove.innerHTML = '×'; btnRemove.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); removeAttachment(idx); }); chip.appendChild(thumb); chip.appendChild(info); chip.appendChild(btnRemove); attachmentList.appendChild(chip); }); } // Resumo de contagem e tamanho if (attachmentSummaryBadge) { const totalSize = currentAttachments.reduce((sum, a) => sum + (a.size || 0), 0); if (currentAttachments.length > 1) { attachmentSummaryBadge.textContent = `${currentAttachments.length} itens · ${formatBytes(totalSize)}`; attachmentSummaryBadge.style.display = 'inline-block'; } else { attachmentSummaryBadge.style.display = 'none'; } } } function removeAttachment(index) { if (index >= 0 && index < currentAttachments.length) { currentAttachments.splice(index, 1); renderAttachmentPreview(); } } function clearAllAttachments() { currentAttachments = []; renderAttachmentPreview(); clearFileInputs(); } async function handleFilesSelected(files) { if (!files || files.length === 0) return; const fileList = Array.from(files); const MAX_FILES = 10; const MAX_TOTAL_SIZE = 25 * 1024 * 1024; // 25MB if (currentAttachments.length + fileList.length > MAX_FILES) { alert(`Você pode anexar no máximo ${MAX_FILES} arquivos simultaneamente.`); clearFileInputs(); return; } let currentTotalSize = currentAttachments.reduce((sum, a) => sum + (a.size || 0), 0); for (const file of fileList) { if (currentTotalSize + file.size > MAX_TOTAL_SIZE) { alert(`O arquivo "${file.name}" excede o limite máximo total de 25MB.`); continue; } const isImage = file.type && file.type.startsWith('image/'); const processed = await optimizeImageFile(file); currentAttachments.push({ name: processed.name, mimeType: processed.mimeType, size: processed.size, isImage, dataUrl: processed.dataUrl, dataBase64: processed.dataBase64 }); currentTotalSize += processed.size; } renderAttachmentPreview(); clearFileInputs(); } async function handleFileSelected(file) { if (!file) return; await handleFilesSelected([file]); } // Controle do Menu Flutuante de Anexo (Câmera / Galeria / Arquivos) if (btnAttach) { btnAttach.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); toggleAttachMenu(); }); } if (attachBackdrop) { attachBackdrop.addEventListener('click', () => toggleAttachMenu(false)); attachBackdrop.addEventListener('touchend', () => toggleAttachMenu(false)); } if (btnAttachCamera) { btnAttachCamera.addEventListener('click', () => { toggleAttachMenu(false); if (chatCameraInput) chatCameraInput.click(); }); } if (btnAttachGallery) { btnAttachGallery.addEventListener('click', () => { toggleAttachMenu(false); if (chatGalleryInput) chatGalleryInput.click(); }); } if (btnAttachFile) { btnAttachFile.addEventListener('click', () => { toggleAttachMenu(false); if (chatFileInput) chatFileInput.click(); }); } const bindFileInput = (inputEl) => { if (!inputEl) return; inputEl.addEventListener('change', (e) => { const files = e.target.files; if (files && files.length > 0) { handleFilesSelected(files); } }); }; bindFileInput(chatCameraInput); bindFileInput(chatGalleryInput); bindFileInput(chatFileInput); if (btnRemoveAttachment) { btnRemoveAttachment.addEventListener('click', () => { clearAllAttachments(); }); } if (btnClearAllAttachments) { btnClearAllAttachments.addEventListener('click', () => { clearAllAttachments(); }); } // Eventos de Reconhecimento de Voz / Gravação de Áudio if (btnVoice) { const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; let voiceActiveStream = null; let isVoiceExplicitlyStopped = true; let voiceBasePrefix = ''; let voiceAccumulatedTranscript = ''; let voiceSessionFinal = ''; let voiceRestartCount = 0; const stopRecordingUI = () => { isRecording = false; isVoiceExplicitlyStopped = true; voiceRestartCount = 0; btnVoice.classList.remove('recording'); if (chatInput) { chatInput.placeholder = 'Digite ou fale para o agente...'; chatInput.value = chatInput.value.trim(); } }; const stopAnyActiveVoiceSession = () => { isVoiceExplicitlyStopped = true; if (speechRecognizer) { try { speechRecognizer.stop(); } catch (e) {} } if (mediaRecorder && mediaRecorder.state !== 'inactive') { try { mediaRecorder.stop(); } catch (e) {} } if (voiceActiveStream) { try { voiceActiveStream.getTracks().forEach(t => t.stop()); } catch (e) {} voiceActiveStream = null; } stopRecordingUI(); }; const startAudioRecording = () => { if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) { showToast('Gravação de microfone não suportada neste aparelho.', 'error'); alert('Seu navegador ou aparelho não suporta captura de microfone via Web.'); stopRecordingUI(); return; } showToast('Solicitando acesso ao microfone...', 'info'); navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => { voiceActiveStream = stream; isRecording = true; btnVoice.classList.add('recording'); if (chatInput) chatInput.placeholder = 'Gravando áudio... Toque no mic para finalizar'; showToast('Gravando áudio... Fale e toque no microfone para enviar.', 'info'); audioChunks = []; let chosenMime = 'audio/webm'; if (typeof MediaRecorder !== 'undefined' && MediaRecorder.isTypeSupported) { if (MediaRecorder.isTypeSupported('audio/webm;codecs=opus')) { chosenMime = 'audio/webm;codecs=opus'; } else if (MediaRecorder.isTypeSupported('audio/mp4')) { chosenMime = 'audio/mp4'; } else if (MediaRecorder.isTypeSupported('audio/aac')) { chosenMime = 'audio/aac'; } } try { mediaRecorder = new MediaRecorder(stream, { mimeType: chosenMime }); } catch { mediaRecorder = new MediaRecorder(stream); } mediaRecorder.ondataavailable = (evt) => { if (evt.data && evt.data.size > 0) audioChunks.push(evt.data); }; mediaRecorder.onstop = () => { const finalMime = (mediaRecorder && mediaRecorder.mimeType) || chosenMime || 'audio/webm'; const ext = finalMime.includes('mp4') ? 'mp4' : 'webm'; const audioBlob = new Blob(audioChunks, { type: finalMime }); if (voiceActiveStream) { try { voiceActiveStream.getTracks().forEach(t => t.stop()); } catch (e) {} voiceActiveStream = null; } if (audioBlob.size < 400) { showToast('Gravação muito curta descartada.', 'warning'); stopRecordingUI(); return; } const reader = new FileReader(); reader.onload = (loadEvt) => { const dataUrl = loadEvt.target.result; const base64Data = (dataUrl || '').split(',')[1] || ''; const audioAttachment = { name: `audio-${Date.now()}.${ext}`, mimeType: finalMime, size: audioBlob.size, isImage: false, dataUrl, dataBase64: base64Data }; currentAttachments.push(audioAttachment); renderAttachmentPreview(); showToast('Áudio gravado com sucesso! Pronto para enviar.', 'success'); }; reader.readAsDataURL(audioBlob); stopRecordingUI(); }; mediaRecorder.start(); }).catch(err => { console.error('[Voice] Erro ao obter microfone:', err); showToast('Permissão de microfone negada ou indisponível.', 'error'); alert('Para usar o microfone, instale a atualização do APK v1.0.2 (toque no nome do app no topo > "Baixar APK v1.0.2"). O Android exige que o APK nativo seja atualizado para registrar permissões de hardware.'); stopRecordingUI(); }); }; if (SpeechRecognition) { try { speechRecognizer = new SpeechRecognition(); speechRecognizer.lang = 'pt-BR'; speechRecognizer.continuous = true; speechRecognizer.interimResults = true; speechRecognizer.onstart = () => { isRecording = true; isVoiceExplicitlyStopped = false; btnVoice.classList.add('recording'); if (chatInput) chatInput.placeholder = 'Ouvindo... Fale à vontade (toque no mic para encerrar)'; showToast('Ditado contínuo ativado. Toque no microfone para concluir.', 'info'); }; speechRecognizer.onresult = (event) => { let interimTranscript = ''; voiceSessionFinal = ''; for (let i = 0; i < event.results.length; ++i) { const resultItem = event.results[i]; if (resultItem.isFinal) { voiceSessionFinal += resultItem[0].transcript + ' '; } else { interimTranscript += resultItem[0].transcript; } } if (chatInput) { chatInput.value = (voiceBasePrefix + voiceAccumulatedTranscript + voiceSessionFinal + interimTranscript).trimStart(); } }; speechRecognizer.onerror = (err) => { console.warn('[Voice] SpeechRecognition erro:', err.error); if (err.error === 'no-speech') { // Silêncio temporário (pausa para respirar ou pensar): ignora e deixa o ciclo continuar return; } if (err.error === 'aborted') { return; } stopRecordingUI(); // Se o serviço do Google não estiver integrado no WebView, faz fallback para gravação direta de áudio if (err.error === 'service-not-allowed' || err.error === 'not-allowed' || err.error === 'network' || err.error === 'audio-capture') { console.log('[Voice] Alternando para gravação direta de áudio...'); speechRecognizer = null; startAudioRecording(); } else { showToast(`Voz: ${err.error}`, 'warning'); } }; speechRecognizer.onend = () => { if (!isVoiceExplicitlyStopped && isRecording && speechRecognizer) { // Consolida a transcrição final da sessão e reinicia para tolerar pausas de respiração voiceAccumulatedTranscript += voiceSessionFinal; voiceSessionFinal = ''; voiceRestartCount++; if (voiceRestartCount < 50) { try { speechRecognizer.start(); return; } catch (e) { console.warn('[Voice] Falha ao auto-reiniciar reconhecimento contínuo:', e); } } } stopRecordingUI(); }; } catch (err) { console.warn('[Voice] Falha ao instanciar SpeechRecognition:', err); speechRecognizer = null; } } btnVoice.addEventListener('click', (e) => { e.preventDefault(); if (!isRecording) { isVoiceExplicitlyStopped = false; voiceRestartCount = 0; voiceBasePrefix = chatInput && chatInput.value ? chatInput.value.trimEnd() + ' ' : ''; voiceAccumulatedTranscript = ''; voiceSessionFinal = ''; if (speechRecognizer) { try { speechRecognizer.start(); } catch (err) { console.warn('[Voice] Falha ao iniciar reconhecimento, caindo para gravação:', err); speechRecognizer = null; startAudioRecording(); } } else { startAudioRecording(); } } else { stopAnyActiveVoiceSession(); } }); window._stopAnyActiveVoiceSession = stopAnyActiveVoiceSession; } if (chatForm) { chatForm.addEventListener('submit', (e) => { e.preventDefault(); if (typeof window._stopAnyActiveVoiceSession === 'function') { window._stopAnyActiveVoiceSession(); } if (!chatInput) return; const text = chatInput.value.trim(); if (!text && currentAttachments.length === 0) return; if (!activeChatAgent) return; const targetPin = activeChatPin || currentPin; const entry = targetPin ? stationPool.get(targetPin) : null; const targetWs = entry?.ws || ws; if (!targetWs || targetWs.readyState !== WebSocket.OPEN) { alert('Sem conexão ativa com o Relay da estação.'); return; } if (entry && entry.status === 'offline') { showToast(`A estação ${entry.name || targetPin} parece estar offline no momento.`, 'warning'); } const attachmentsToSend = [...currentAttachments]; const attachmentToSend = attachmentsToSend[0] || null; let msgText = text; if (!msgText && attachmentsToSend.length > 0) { if (attachmentsToSend.length === 1) { msgText = `[Enviou ${attachmentsToSend[0].name}]`; } else { msgText = `[Enviou ${attachmentsToSend.length} anexos: ${attachmentsToSend.map(a => a.name).join(', ')}]`; } } const histKey = targetPin ? `${targetPin}:${activeChatAgent}` : activeChatAgent; const history = getAgentChatHistory(activeChatAgent, targetPin); history.push({ role: 'user', text: msgText, attachment: attachmentToSend, attachments: attachmentsToSend, timestamp: Date.now() }); setAgentChatHistory(activeChatAgent, targetPin, history); targetWs.send(JSON.stringify({ type: 'CHAT_SEND', agentName: activeChatAgent, message: msgText, attachments: attachmentsToSend.map(a => ({ name: a.name, mimeType: a.mimeType, size: a.size, dataBase64: a.dataBase64 })), attachment: attachmentToSend ? { name: attachmentToSend.name, mimeType: attachmentToSend.mimeType, size: attachmentToSend.size, dataBase64: attachmentToSend.dataBase64 } : undefined })); clearAllAttachments(); chatInput.value = ''; isWaitingChatReply = true; hadThinkingDuringReply = false; terminalTextBeforePrompt = cleanTerminalOutput(lastTerminalOutputs.get(histKey) || ''); startThinkingTimer(); updateAgentThinkingUI('', true); renderChatMessages(true); appendAgentTyping(); captureAndSendScreenStateSnapshot(activeChatAgent, 'chat_send'); }); } } function logoutUser() { stopThinkingTimer(); reconnectTimers.forEach(t => clearTimeout(t)); reconnectTimers.clear(); stationPool.forEach(entry => { if (entry.ws) { try { entry.ws.onclose = null; entry.ws.onerror = null; entry.ws.close(); } catch (e) {} } }); stationPool.clear(); localStorage.removeItem('maestri_pin'); localStorage.removeItem('maestri_stations'); currentPin = null; ws = null; setConnected(false); if (pinInput) pinInput.value = ''; if (btnLogout) btnLogout.style.display = 'none'; if (statusBadge) statusBadge.style.display = 'none'; if (appScreen) appScreen.style.display = 'none'; if (pinScreen) pinScreen.style.display = 'flex'; if (statusText) statusText.textContent = 'Desconectado'; if (btnConnect) { btnConnect.disabled = false; btnConnect.textContent = 'Conectar'; } closeChat(); } // ========================================== // Inicialização do Aplicativo // ========================================== function initApp() { const params = new URLSearchParams(window.location.search); const pinFromUrl = params.get('pin'); setupStationEvents(); setupChatEvents(); if (pinFromUrl && pinFromUrl.length >= 4) { if (pinInput) pinInput.value = pinFromUrl; registerOrUpdateStation(pinFromUrl, 'Link Direto'); } const stations = getSavedStations(); if (stations.length > 0) { if (appScreen) appScreen.style.display = 'block'; if (pinScreen) pinScreen.style.display = 'none'; if (btnLogout) btnLogout.style.display = 'inline-flex'; stations.forEach(s => connectStation(s.pin, s.name)); renderAllStations(); } else { renderStationsSelect(); renderAllStations(); } if (btnLogout) btnLogout.addEventListener('click', logoutUser); if (btnLogoutScreen) btnLogoutScreen.addEventListener('click', logoutUser); if (btnClearStored) { btnClearStored.addEventListener('click', (e) => { e.preventDefault(); localStorage.removeItem('maestri_pin'); localStorage.removeItem('maestri_stations'); if (pinInput) pinInput.value = ''; renderStationsSelect(); if (pinInput) pinInput.focus(); }); } // Configuração do Modal de Versão e Informações do App try { const cachedVer = localStorage.getItem('maestri_version_info'); if (cachedVer) { const parsed = JSON.parse(cachedVer); appVersionInfo = Object.assign(appVersionInfo, parsed); } const otaBuild = localStorage.getItem('maestri_ota_build_id'); const otaVer = localStorage.getItem('maestri_ota_version'); const otaDate = localStorage.getItem('maestri_ota_released_at'); if (otaBuild) appVersionInfo.buildId = otaBuild; if (otaVer) appVersionInfo.version = otaVer; if (otaDate) appVersionInfo.releasedAt = otaDate; } catch (e) {} updateVersionUI(); fetchVersionInfo(); if (brandHeader) { brandHeader.addEventListener('click', openVersionModal); brandHeader.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); openVersionModal(); } }); } if (btnCloseVersionModal) { btnCloseVersionModal.addEventListener('click', closeVersionModal); } if (modalVersion) { modalVersion.addEventListener('click', (e) => { if (e.target === modalVersion) closeVersionModal(); }); } if (btnCheckUpdateManual) { btnCheckUpdateManual.addEventListener('click', async () => { btnCheckUpdateManual.disabled = true; btnCheckUpdateManual.textContent = 'Verificando...'; let updated = false; if (typeof window.checkForOtaUpdate === 'function') { updated = await window.checkForOtaUpdate(true); } const latest = await fetchVersionInfo(); btnCheckUpdateManual.disabled = false; btnCheckUpdateManual.textContent = 'Verificar Atualização'; if (updated) { showToast(`Baixando atualização v${latest?.version || ''}...`, 'info'); } else if (latest) { showToast(`Versão v${latest.version} (${latest.buildId}) confirmada!`, 'info'); } else { showToast('Não foi possível conectar ao servidor OTA.', 'warning'); } }); } const btnForceReload = document.getElementById('btn-force-reload'); if (btnForceReload) { btnForceReload.addEventListener('click', () => { try { localStorage.removeItem('maestri_ota_js'); localStorage.removeItem('maestri_ota_css'); localStorage.removeItem('maestri_ota_body'); localStorage.removeItem('maestri_ota_build_id'); localStorage.removeItem('maestri_ota_version'); localStorage.removeItem('maestri_version_info'); } catch (e) {} window.location.reload(true); }); } const btnDownloadApk = document.getElementById('btn-download-apk'); if (btnDownloadApk) { const isLocal = !window.location.host || window.location.host.includes('localhost') || window.location.protocol === 'file:' || window.location.protocol === 'capacitor:'; if (isLocal) { btnDownloadApk.href = 'https://remote.winicomw.ddnsfree.com/maestri-remote.apk'; } } initServiceWorker(); initOtaChecker(); } if (document.readyState === 'loading') { window.addEventListener('DOMContentLoaded', initApp); } else { initApp(); } if (btnConnect) { btnConnect.addEventListener('click', (e) => { e.preventDefault(); const pin = pinInput ? pinInput.value.trim() : ''; const pinNameInput = document.getElementById('pin-station-name-input'); const customName = pinNameInput ? pinNameInput.value.trim() : ''; if (!pin || pin.length < 4) { if (pinInput) { pinInput.focus(); pinInput.style.borderColor = '#ef4444'; setTimeout(() => { pinInput.style.borderColor = ''; }, 1500); } return; } btnConnect.disabled = true; btnConnect.textContent = 'Conectando...'; const stationLabel = customName || ('Estação ' + pin); registerOrUpdateStation(pin, stationLabel); connectStation(pin, stationLabel); }); } if (pinInput) { pinInput.addEventListener('keypress', (e) => { if (e.key === 'Enter' && btnConnect) btnConnect.click(); }); } // ========================================== // Web Push Notifications & OTA Service // ========================================== async function initServiceWorker() { if (!('serviceWorker' in navigator) || !('PushManager' in window)) return; try { const reg = await navigator.serviceWorker.register('/sw.js'); console.log('Service Worker registrado:', reg.scope); const sub = await reg.pushManager.getSubscription(); if (sub) { if (pushBanner) pushBanner.style.display = 'none'; const stations = getSavedStations(); stations.forEach(s => syncPushSubscription(s.pin, sub)); } else { if (pushBanner) pushBanner.style.display = 'flex'; } } catch (err) { console.warn('Erro ao registrar Service Worker:', err); } } if (btnEnablePush) { btnEnablePush.addEventListener('click', async () => { try { const perm = await Notification.requestPermission(); if (perm !== 'granted') { alert('Permissão de notificação negada.'); return; } const res = await fetch('/api/push/vapid-key'); const { publicKey } = await res.json(); const reg = await navigator.serviceWorker.ready; const sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlB64ToUint8Array(publicKey) }); const stations = getSavedStations(); stations.forEach(s => syncPushSubscription(s.pin, sub)); if (pushBanner) pushBanner.style.display = 'none'; alert('Notificações no celular ativadas com sucesso!'); } catch (err) { console.error('Erro ao ativar push:', err); } }); } async function syncPushSubscription(pin, sub) { try { await fetch('/api/push/subscribe', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ pin, subscription: sub }) }); } catch (e) {} } function urlB64ToUint8Array(base64String) { const padding = '='.repeat((4 - base64String.length % 4) % 4); const base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/'); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; } function formatBuildDate(isoString) { if (!isoString) return 'Desconhecida'; try { const d = new Date(isoString); if (isNaN(d.getTime())) return isoString; return d.toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }); } catch (e) { return isoString; } } function updateVersionUI() { if (appVersionVal) appVersionVal.textContent = `v${appVersionInfo.version || '1.0.2'}`; if (appBuildVal) appBuildVal.textContent = appVersionInfo.buildId || 'local'; if (appDateVal) appDateVal.textContent = formatBuildDate(appVersionInfo.releasedAt); if (appChecksumVal && appChecksumRow) { if (appVersionInfo.checksum) { appChecksumVal.textContent = appVersionInfo.checksum; appChecksumVal.title = appVersionInfo.checksum; appChecksumRow.style.display = 'flex'; } else { appChecksumRow.style.display = 'none'; } } } async function fetchVersionInfo() { try { const host = window.location.host; const isLocal = !host || host.includes('localhost') || host.includes('127.0.0.1') || window.location.protocol === 'file:' || window.location.protocol === 'capacitor:'; const baseUrl = isLocal ? 'https://remote.winicomw.ddnsfree.com' : ''; const res = await fetch(`${baseUrl}/api/version?src=app&t=${Date.now()}`); if (res.ok) { const data = await res.json(); appVersionInfo = Object.assign(appVersionInfo, data); if (data.buildId) currentBuildId = data.buildId; try { localStorage.setItem('maestri_version_info', JSON.stringify(appVersionInfo)); } catch (e) {} updateVersionUI(); return data; } } catch (err) { console.warn('[Version] Falha ao consultar /api/version:', err.message); } return null; } function openVersionModal() { updateVersionUI(); if (modalVersion) modalVersion.style.display = 'flex'; fetchVersionInfo(); } function closeVersionModal() { if (modalVersion) modalVersion.style.display = 'none'; } window.openVersionModal = openVersionModal; window.closeVersionModal = closeVersionModal; window.fetchVersionInfo = fetchVersionInfo; function initOtaChecker() { setInterval(async () => { try { const host = window.location.host; const isLocal = !host || host.includes('localhost') || host.includes('127.0.0.1') || window.location.protocol === 'file:' || window.location.protocol === 'capacitor:'; const baseUrl = isLocal ? 'https://remote.winicomw.ddnsfree.com' : ''; const res = await fetch(`${baseUrl}/api/version?src=app&t=${Date.now()}`); if (res.ok) { const data = await res.json(); if (currentBuildId && data.buildId && data.buildId !== currentBuildId) { console.log('[OTA] Nova versão detectada! Recarregando aplicação...'); window.location.reload(); } else if (!currentBuildId) { currentBuildId = data.buildId; } appVersionInfo = Object.assign(appVersionInfo, data); updateVersionUI(); } } catch (err) { // Ignora erro de rede temporário } }, 30000); }