// Pool de Conexões WebSocket Multi-Estações // Map const stationPool = new Map(); const reconnectTimers = new Map(); const RE_ANSI = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g; // 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 authScreen = document.getElementById('auth-screen'); const btnGoogleLogin = document.getElementById('btn-google-login'); const authStatusText = document.getElementById('auth-status-text'); const userBadge = document.getElementById('user-badge'); const userAvatar = document.getElementById('user-avatar'); const userNameEl = document.getElementById('user-name'); const btnAuthLogout = document.getElementById('btn-auth-logout'); 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'); // Elementos de Preview e Download de Arquivos const filePreviewModal = document.getElementById('file-preview-modal'); const btnCloseFilePreview = document.getElementById('btn-close-file-preview'); const btnSaveFile = document.getElementById('btn-save-file'); const btnCopyFileContent = document.getElementById('btn-copy-file-content'); let currentActiveFile = null; 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'); const btnSessionDownloads = document.getElementById('btn-session-downloads'); const sessionDownloadsBadge = document.getElementById('session-downloads-badge'); const btnMenuDownloads = document.getElementById('btn-menu-downloads'); const sessionDownloadsModal = document.getElementById('session-downloads-modal'); const btnCloseSessionDownloads = document.getElementById('btn-close-session-downloads'); const sessionDownloadsList = document.getElementById('session-downloads-list'); const sessionDownloadsEmpty = document.getElementById('session-downloads-empty'); const sessionDownloadsCount = document.getElementById('session-downloads-count'); const btnChatSend = document.getElementById('btn-chat-send'); // Catálogo em memória de arquivos citados por chat/estação const sessionFilesCatalog = new Map(); // path -> { path, name, ext, timestamp, source } window.sessionFilesCatalog = sessionFilesCatalog; // 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 chatVideoRecordInput = document.getElementById('chat-video-record-input'); const chatVideoInput = document.getElementById('chat-video-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 btnAttachVideoRecord = document.getElementById('btn-attach-video-record'); const btnAttachVideoGallery = document.getElementById('btn-attach-video-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 = []; Object.defineProperty(window, 'isRecording', { get: () => isRecording, set: (val) => { isRecording = !!val; if (typeof setVoiceRecordingButtonActive === 'function') { setVoiceRecordingButtonActive(isRecording); } if (typeof updateInputActionButtonState === 'function') { updateInputActionButtonState(); } }, configurable: true }); 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)); if (typeof sendFcmTokenToRelay === 'function') { sendFcmTokenToRelay(); } } 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) {} } // ========================================== // Autenticação Google SSO & Sync de Estações // ========================================== let currentAuthUser = null; let activeAuthPollCleanup = null; function getApiBaseUrl() { 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:'; return isLocal ? 'https://remote.winicomw.ddnsfree.com' : ''; } function getAuthToken() { try { return localStorage.getItem('maestri_auth_token') || null; } catch (e) { return null; } } function getRefreshToken() { try { return localStorage.getItem('maestri_refresh_token') || null; } catch (e) { return null; } } function setAuthSession(token, refreshToken, user) { try { if (token) localStorage.setItem('maestri_auth_token', token); if (refreshToken) localStorage.setItem('maestri_refresh_token', refreshToken); if (user) localStorage.setItem('maestri_user', JSON.stringify(user)); } catch (e) {} } function clearAuthSession() { try { localStorage.removeItem('maestri_auth_token'); localStorage.removeItem('maestri_refresh_token'); localStorage.removeItem('maestri_user'); } catch (e) {} currentAuthUser = null; } let activeRefreshPromise = null; async function refreshAuthSession() { const refreshToken = getRefreshToken(); if (!refreshToken) { return false; } // Deduplicação: reaproveita a Promise se já houver uma renovação silenciosa em andamento if (activeRefreshPromise) { return activeRefreshPromise; } activeRefreshPromise = (async () => { try { const res = await fetch(`${getApiBaseUrl()}/api/auth/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refreshToken }) }); if (res.ok) { const data = await res.json(); if (data && data.token) { setAuthSession(data.token, data.refreshToken || refreshToken, data.user); if (data.user) { updateUserBadge(data.user); } return true; } } // 401 ou 403 indica que o refresh token expirou ou foi revogado if (res.status === 401 || res.status === 403) { console.warn('[Auth] Refresh token inválido ou expirado. Sessão encerrada.'); clearAuthSession(); return false; } // Erro transitório de rede ou servidor return false; } catch (err) { console.warn('[Auth] Falha de rede ao tentar renovar sessão:', err.message); return false; } finally { activeRefreshPromise = null; } })(); return activeRefreshPromise; } async function fetchWithAuth(url, options = {}) { let token = getAuthToken(); const headers = { ...(options.headers || {}) }; if (token) { headers['Authorization'] = `Bearer ${token}`; } let res; try { res = await fetch(url, { ...options, headers }); } catch (netErr) { throw netErr; } if (res.status === 401 && getRefreshToken()) { const refreshed = await refreshAuthSession(); if (refreshed) { const newToken = getAuthToken(); const retryHeaders = { ...(options.headers || {}) }; if (newToken) { retryHeaders['Authorization'] = `Bearer ${newToken}`; } return await fetch(url, { ...options, headers: retryHeaders }); } } return res; } function getSavedAuthUser() { try { const raw = localStorage.getItem('maestri_user'); return raw ? JSON.parse(raw) : null; } catch (e) { return null; } } function showAuthScreen(statusMessage) { if (authScreen) authScreen.style.display = 'flex'; if (pinScreen) pinScreen.style.display = 'none'; if (appScreen) appScreen.style.display = 'none'; if (userBadge) userBadge.style.display = 'none'; if (statusBadge) statusBadge.style.display = 'none'; if (btnLogout) btnLogout.style.display = 'none'; if (btnGoogleLogin) btnGoogleLogin.disabled = false; if (authStatusText) { if (statusMessage) { authStatusText.textContent = statusMessage; authStatusText.style.display = 'block'; } else { authStatusText.textContent = ''; authStatusText.style.display = 'none'; } } } function updateUserBadge(user) { currentAuthUser = user || null; if (!userBadge) return; if (!user) { userBadge.style.display = 'none'; return; } userBadge.style.display = 'inline-flex'; if (userNameEl) { userNameEl.textContent = user.name || user.email || 'Usuário'; userNameEl.title = user.email || user.name || ''; } if (userAvatar) { if (user.picture) { userAvatar.src = user.picture; userAvatar.style.display = 'block'; } else { userAvatar.style.display = 'none'; } } } async function syncStationToServer(method, pathSuffix, body) { if (!getAuthToken() && !getRefreshToken()) return null; try { const res = await fetchWithAuth(`${getApiBaseUrl()}${pathSuffix}`, { method, headers: { 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined }); if (res.status === 401) { logoutUser(); return null; } if (res.ok) { return await res.json(); } } catch (e) { console.warn('[Sync] Falha ao sincronizar estação com servidor:', e.message); } return null; } async function syncStationsFromServer() { if (!getAuthToken() && !getRefreshToken()) return getSavedStations(); try { const res = await fetchWithAuth(`${getApiBaseUrl()}/api/stations`); if (res.status === 401) { logoutUser(); return []; } if (res.ok) { const data = await res.json(); if (Array.isArray(data.stations)) { const localStations = getSavedStations(); const localByPin = new Map(localStations.map(s => [String(s.pin), s])); const merged = data.stations.map(s => { const local = localByPin.get(String(s.pin)); return { id: 'station-' + s.pin, pin: String(s.pin), name: s.name || ('Estação ' + s.pin), machineName: s.machineName || local?.machineName || null, cachedAgents: local?.cachedAgents }; }); saveStationsList(merged); if (merged.length > 0 && !localStorage.getItem('maestri_pin')) { localStorage.setItem('maestri_pin', merged[0].pin); } return merged; } } } catch (e) { console.warn('[Sync] Falha ao carregar estações do servidor:', e.message); } return getSavedStations(); } async function completeAuthenticatedStartup(user) { updateUserBadge(user); if (authScreen) authScreen.style.display = 'none'; const pendingPin = sessionStorage.getItem('maestri_pending_pin'); if (pendingPin && pendingPin.length >= 4) { sessionStorage.removeItem('maestri_pending_pin'); if (pinInput) pinInput.value = pendingPin; registerOrUpdateStation(pendingPin, 'Link Direto'); } const stations = await syncStationsFromServer(); 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(); renderStationsSelect(); } else { if (appScreen) appScreen.style.display = 'none'; if (pinScreen) pinScreen.style.display = 'flex'; renderStationsSelect(); renderAllStations(); } } async function startGoogleLogin() { if (activeAuthPollCleanup) { activeAuthPollCleanup(); activeAuthPollCleanup = null; } const isNativeOrLocal = Boolean( window.Capacitor || window.location.protocol === 'capacitor:' || window.location.protocol === 'file:' ); // Abre a janela popup sincronamente dentro do gesto de clique para evitar bloqueador de popups let preOpenedPopup = null; if (!isNativeOrLocal) { try { preOpenedPopup = window.open('about:blank', 'maestri_google_auth', 'width=500,height=680'); } catch (e) { preOpenedPopup = null; } } if (btnGoogleLogin) btnGoogleLogin.disabled = true; if (authStatusText) { authStatusText.textContent = 'Abrindo navegador para login com Google...'; authStatusText.style.display = 'block'; } try { const res = await fetch(`${getApiBaseUrl()}/api/auth/start`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ mode: isNativeOrLocal ? 'app' : 'web' }) }); if (!res.ok) { if (preOpenedPopup && !preOpenedPopup.closed) { try { preOpenedPopup.close(); } catch (e) {} } throw new Error(`Servidor respondeu HTTP ${res.status}`); } const { flowId, authUrl } = await res.json(); if (!flowId || !authUrl) { if (preOpenedPopup && !preOpenedPopup.closed) { try { preOpenedPopup.close(); } catch (e) {} } throw new Error('Resposta inválida ao iniciar autenticação.'); } if (isNativeOrLocal) { let opened = false; const cap = window.Capacitor; // 1. Tenta Capacitor Browser plugin se registrado if (cap?.Plugins?.Browser?.open) { try { await cap.Plugins.Browser.open({ url: authUrl }); opened = true; } catch (e) { console.warn('[Auth] Falha no Browser.open:', e); } } // 2. Tenta Capacitor App plugin (openUrl) se disponível if (!opened && cap?.Plugins?.App?.openUrl) { try { await cap.Plugins.App.openUrl({ url: authUrl }); opened = true; } catch (e) { console.warn('[Auth] Falha no App.openUrl:', e); } } // 3. Tenta window.open com target '_system' if (!opened) { try { const w = window.open(authUrl, '_system', 'location=yes'); if (w) opened = true; } catch (e) { console.warn('[Auth] Falha no window.open(_system):', e); } } // 4. Fallback via elemento com target="_system" (nunca substitui window.location.href em app nativo!) if (!opened) { try { const link = document.createElement('a'); link.href = authUrl; link.target = '_system'; link.rel = 'noopener noreferrer'; document.body.appendChild(link); link.click(); setTimeout(() => { try { document.body.removeChild(link); } catch (e) {} }, 100); opened = true; } catch (e) { console.warn('[Auth] Falha ao disparar link _system:', e); } } // Em ambiente nativo/Capacitor, JAMAIS substitua window.location.href diretamente, // pois a WebView perderia a origem do app, quebraria o Capacitor e causaria // erro 403 (disallowed_useragent) no Google OAuth! if (!opened && authStatusText) { authStatusText.innerHTML = `Por favor, clique aqui para abrir o login no navegador externo.`; } } else if (preOpenedPopup && !preOpenedPopup.closed) { try { preOpenedPopup.location = authUrl; } catch (e) { window.location.href = authUrl; } } else { window.location.href = authUrl; return; } if (authStatusText) { authStatusText.textContent = 'Aguardando conclusão do login no navegador...'; authStatusText.style.display = 'block'; } let finished = false; let pollTimer = null; const startedAt = Date.now(); const cleanup = () => { if (pollTimer) clearInterval(pollTimer); window.removeEventListener('message', onWindowMessage); window.removeEventListener('focus', triggerImmediatePoll); window.removeEventListener('resume', triggerImmediatePoll); document.removeEventListener('visibilitychange', onVisibilityChange); if (activeAuthPollCleanup === cleanup) { activeAuthPollCleanup = null; } }; activeAuthPollCleanup = cleanup; const finalizeSuccess = async (token, user, refreshToken) => { if (finished) return; finished = true; cleanup(); setAuthSession(token, refreshToken, user); await completeAuthenticatedStartup(user); }; const onWindowMessage = (event) => { const data = event?.data; if (data && data.type === 'MAESTRI_AUTH_SUCCESS' && data.token) { finalizeSuccess(data.token, data.user, data.refreshToken); } }; const checkPoll = async () => { if (finished) return; if (Date.now() - startedAt > 5 * 60 * 1000) { finished = true; cleanup(); showAuthScreen('Tempo de login expirado. Tente novamente.'); return; } try { const pollRes = await fetch(`${getApiBaseUrl()}/api/auth/poll?flowId=${encodeURIComponent(flowId)}`); if (!pollRes.ok) return; const data = await pollRes.json(); if (data.status === 'completed' && data.token) { await finalizeSuccess(data.token, data.user, data.refreshToken); } else if (data.status === 'expired') { finished = true; cleanup(); showAuthScreen('Sessão de login expirada. Tente novamente.'); } } catch (e) {} }; const triggerImmediatePoll = () => { checkPoll(); }; const onVisibilityChange = () => { if (!document.hidden) checkPoll(); }; window.addEventListener('message', onWindowMessage); window.addEventListener('focus', triggerImmediatePoll); window.addEventListener('resume', triggerImmediatePoll); document.addEventListener('visibilitychange', onVisibilityChange); pollTimer = setInterval(checkPoll, 2000); } catch (err) { showAuthScreen(`Não foi possível iniciar o login: ${err.message}`); } } window.startGoogleLogin = startGoogleLogin; window.syncStationsFromServer = syncStationsFromServer; function registerOrUpdateStation(pin, name, skipServerSync = false) { if (!pin) return; const stations = getSavedStations(); const existingIdx = stations.findIndex(s => s.pin === pin); const hasValidName = !isInvalidMachineName(name); const resolvedName = hasValidName ? name.trim() : ('Estação ' + pin); if (existingIdx >= 0) { if (hasValidName) { stations[existingIdx].name = resolvedName; } } else { stations.push({ id: 'station-' + pin, name: resolvedName, pin }); } saveStationsList(stations); renderStationsSelect(); if (!skipServerSync) { const finalEntry = stations.find(s => s.pin === pin); syncStationToServer('POST', '/api/stations', { pin, name: finalEntry ? finalEntry.name : resolvedName }); } } function renameStation(pin, newName) { if (!pin || !newName || typeof newName !== 'string') return; const trimmed = newName.trim(); if (!trimmed) return; registerOrUpdateStation(pin, trimmed, true); const entry = stationPool.get(pin); if (entry) { entry.name = trimmed; } renderAllStations(); renderStationsSelect(); syncStationToServer('PATCH', `/api/stations/${encodeURIComponent(pin)}`, { name: trimmed }); showToast(`Estação renomeada para "${trimmed}"`, 'info'); } window.renameStation = renameStation; function getStationSortRank(pin) { const entry = stationPool.get(pin); if (!entry) return 2; if (entry.status === 'online') return 0; if (entry.status === 'connecting') return 1; return 2; } function sortStationsByOnlineStatus(stations) { return [...stations] .map((st, idx) => ({ st, idx })) .sort((a, b) => { const rankDiff = getStationSortRank(a.st.pin) - getStationSortRank(b.st.pin); return rankDiff !== 0 ? rankDiff : a.idx - b.idx; }) .map(item => item.st); } function renderStationsSelect() { if (!stationSelect) return; const stations = sortStationsByOnlineStatus(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(false); 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(true); 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(true); 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 'FILE_READ_RESP': document.querySelectorAll('.btn-file-chip, .btn-session-download-action').forEach(btn => { const btnPath = btn.getAttribute('data-path'); if (btnPath === msg.path || (msg.name && btnPath && btnPath.endsWith(msg.name))) { btn.classList.remove('loading'); } }); if (!msg.ok) { showToast(msg.error || 'Erro ao carregar arquivo da estação.', 'error'); break; } openFilePreviewModal(msg); 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(); syncStationToServer('DELETE', `/api/stations/${encodeURIComponent(pin)}`); } 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 = ''; } const orderedStations = sortStationsByOnlineStatus(stations); orderedStations.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 = orderedStations[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; } renderStationsSelect(); // 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 || ''; // Contador de arquivos passa a refletir só o terminal deste chat updateSessionDownloadsBadge(); // 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); } updateInputActionButtonState(); // 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(); } closeSessionDownloadsModal(); 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]; } // ============================================================ // Extração e Transferência de Arquivos sob Demanda via WebSocket // ============================================================ function extractFilePaths(text) { if (!text || typeof text !== 'string') return []; // Lista abrangente de extensões suportadas pelo projeto e agentes const validExtensions = '(?:png|jpe?g|gif|svg|webp|ico|pdf|txt|md|markdown|json|m?js|ts|html?|css|zip|log|csv|xml|ya?ml|sh|ps1|bat|cmd|apk)'; // O hífen fica no início da classe [-a-zA-Z0-9_./\\] para não ser tratado como intervalo ASCII // O lookahead inclui pontuação de fechamento e ponto final de frase const regex = new RegExp(`(?:^|[\\s"'(\`\\[<])((?:[a-zA-Z]:[\\\\/])?[-a-zA-Z0-9_./\\\\]+?\\.${validExtensions})(?=[\\s"')\`\\]>,;:!?.|\\)]|$)`, 'gim'); const matches = new Set(); let match; while ((match = regex.exec(text)) !== null) { let filePath = match[1].trim(); // Remove aspas ou delimitadores no início e fim filePath = filePath.replace(/^['"`(<\\[]+|['"`)>\\]]+$/g, ''); // Remove pontuação de final de frase filePath = filePath.replace(/[:.,;!?]+$/g, ''); if (!filePath) continue; // Ignora URLs completas if (/^https?:\/\//i.test(filePath) || /^wss?:\/\//i.test(filePath) || filePath.includes('://')) { continue; } // Normaliza barras invertidas do Windows filePath = filePath.replace(/\\/g, '/'); // Remove prefixos ./ redundantes if (filePath.startsWith('./')) { filePath = filePath.slice(2); } const baseName = filePath.split('/').pop() || ''; // Ignora se for apenas a extensão isolada (ex: .json ou .md sem nome de arquivo) if (baseName.startsWith('.') && baseName.split('.').length === 2 && baseName.length <= 5) { continue; } matches.add(filePath); } return Array.from(matches); } window.extractFilePaths = extractFilePaths; // Catálogo e Downloads Sob Demanda (um escopo por estação + terminal: o contador e a lista mostram só o chat aberto) function getSessionFilesScope() { const pin = activeChatPin || currentPin || ''; return `${pin}::${activeChatAgent || ''}`; } window.getSessionFilesScope = getSessionFilesScope; function getScopedSessionFiles(scope = getSessionFilesScope()) { return Array.from(sessionFilesCatalog.values()).filter(file => file.scope === scope); } window.getScopedSessionFiles = getScopedSessionFiles; function registerSessionFiles(filePaths, source = 'text') { if (!Array.isArray(filePaths) || filePaths.length === 0) return; const scope = getSessionFilesScope(); filePaths.forEach(filePath => { if (!filePath || typeof filePath !== 'string') return; const normalized = filePath.replace(/\\/g, '/').trim(); if (!normalized) return; const baseName = normalized.split('/').pop() || normalized; const ext = baseName.includes('.') ? baseName.split('.').pop().toLowerCase() : ''; sessionFilesCatalog.set(`${scope}|${normalized}`, { path: normalized, name: baseName, ext, timestamp: Date.now(), source, scope, agentName: activeChatAgent || '' }); }); updateSessionDownloadsBadge(); } window.registerSessionFiles = registerSessionFiles; function updateSessionDownloadsBadge() { if (!sessionDownloadsBadge) return; const total = getScopedSessionFiles().length; if (total > 0) { sessionDownloadsBadge.textContent = String(total); sessionDownloadsBadge.style.display = 'inline-flex'; } else { sessionDownloadsBadge.style.display = 'none'; } if (sessionDownloadsCount) { sessionDownloadsCount.textContent = `${total} ${total === 1 ? 'arquivo detectado' : 'arquivos detectados'}`; } } window.updateSessionDownloadsBadge = updateSessionDownloadsBadge; function getFileCategoryIcon(ext) { const imageExts = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'ico']; const docExts = ['pdf', 'txt', 'md', 'markdown', 'log', 'csv', 'json', 'xml', 'yaml', 'yml']; const codeExts = ['js', 'mjs', 'ts', 'html', 'css', 'sh', 'ps1', 'bat', 'cmd']; const pkgExts = ['zip', 'apk', 'tar', 'gz', '7z']; if (imageExts.includes(ext)) return '🖼️'; if (pkgExts.includes(ext)) return '📦'; if (codeExts.includes(ext)) return '💻'; if (docExts.includes(ext)) return '📄'; return '📄'; } function openSessionDownloadsModal() { if (!sessionDownloadsModal) return; updateSessionDownloadsBadge(); if (sessionDownloadsList && sessionDownloadsEmpty) { sessionDownloadsList.innerHTML = ''; const scopedFiles = getScopedSessionFiles(); if (scopedFiles.length === 0) { sessionDownloadsEmpty.style.display = 'block'; sessionDownloadsList.style.display = 'none'; } else { sessionDownloadsEmpty.style.display = 'none'; sessionDownloadsList.style.display = 'flex'; const files = scopedFiles.sort((a, b) => b.timestamp - a.timestamp); files.forEach(file => { const itemEl = document.createElement('div'); itemEl.className = 'session-download-item'; const icon = getFileCategoryIcon(file.ext); itemEl.innerHTML = `
${icon}
${escapeHtml(file.name)}
${escapeHtml(file.path)}
`; const actionBtn = itemEl.querySelector('.btn-session-download-action'); if (actionBtn) { actionBtn.addEventListener('click', (e) => { e.preventDefault(); actionBtn.classList.add('loading'); requestFileDownload(file.path); }); } sessionDownloadsList.appendChild(itemEl); }); } } sessionDownloadsModal.style.display = 'flex'; } window.openSessionDownloadsModal = openSessionDownloadsModal; function closeSessionDownloadsModal() { if (sessionDownloadsModal) { sessionDownloadsModal.style.display = 'none'; } } window.closeSessionDownloadsModal = closeSessionDownloadsModal; const VOICE_MIC_SVG = ''; const VOICE_STOP_SVG = ''; function setVoiceRecordingButtonActive(active) { if (!btnVoice) return; if (active) { btnVoice.classList.add('recording'); btnVoice.setAttribute('aria-pressed', 'true'); btnVoice.setAttribute('aria-label', 'Parar gravação de voz'); btnVoice.setAttribute('title', 'Parar gravação'); btnVoice.innerHTML = VOICE_STOP_SVG; } else { btnVoice.classList.remove('recording'); btnVoice.removeAttribute('aria-pressed'); btnVoice.setAttribute('aria-label', 'Gravar voz / Transcrição'); btnVoice.setAttribute('title', 'Falar'); btnVoice.innerHTML = VOICE_MIC_SVG; } } window.setVoiceRecordingButtonActive = setVoiceRecordingButtonActive; function updateInputActionButtonState() { if (!btnVoice || !btnChatSend) return; const hasText = chatInput && chatInput.value && chatInput.value.trim().length > 0; const hasAttachments = Array.isArray(currentAttachments) && currentAttachments.length > 0; // Enquanto a gravação de voz estiver ativa, o botão de microfone / parar DEVE permanecer // visível e acessível para interrupção a qualquer momento, mesmo com texto presente no input. // O botão de envio fica estritamente oculto e bloqueado até a gravação ser interrompida. if (isRecording) { btnVoice.style.display = 'inline-flex'; btnChatSend.style.display = 'none'; return; } // Com a gravação inativa: se houver texto ou anexos, exibe o botão de envio. // Caso contrário, exibe o botão de microfone pronto para nova gravação. if (hasText || hasAttachments) { btnVoice.style.display = 'none'; btnChatSend.style.display = 'inline-flex'; } else { btnVoice.style.display = 'inline-flex'; btnChatSend.style.display = 'none'; } } window.updateInputActionButtonState = updateInputActionButtonState; function renderFileChips(filePaths) { const container = document.createElement('div'); container.className = 'file-chips-container'; filePaths.forEach(filePath => { const chip = document.createElement('button'); chip.type = 'button'; chip.className = 'btn-file-chip'; chip.setAttribute('data-path', filePath); const baseName = filePath.split('/').pop() || filePath; chip.innerHTML = ` 📄 ${escapeHtml(baseName)} Baixar `; chip.addEventListener('click', (e) => { e.preventDefault(); e.stopPropagation(); requestFileDownload(filePath, chip); }); container.appendChild(chip); }); return container; } window.renderFileChips = renderFileChips; function requestFileDownload(filePath, chipElement = null) { const pin = activeChatPin || currentPin; if (!pin) { showToast('Nenhuma estação conectada para solicitar arquivo.', 'error'); return; } const station = stationPool.get(String(pin)); const activeWs = (station && station.ws) ? station.ws : ws; if (!activeWs || activeWs.readyState !== (WebSocket.OPEN || 1)) { showToast('⚠️ Estação offline: o gateway não está conectado.', 'error'); return; } if (chipElement) { chipElement.classList.add('loading'); } const baseName = filePath.split('/').pop() || filePath; showToast(`Solicitando "${baseName}" da estação...`, 'info'); activeWs.send(JSON.stringify({ type: 'FILE_READ_REQ', path: filePath, agentName: activeChatAgent || '', chatId: activeChatAgent ? `chat-${Date.now()}` : '' })); } window.requestFileDownload = requestFileDownload; function openFilePreviewModal(fileData) { currentActiveFile = fileData; const modal = document.getElementById('file-preview-modal'); const titleEl = document.getElementById('file-preview-title'); const metaEl = document.getElementById('file-preview-meta'); const bodyEl = document.getElementById('file-preview-body'); const copyBtn = document.getElementById('btn-copy-file-content'); const iconEl = document.getElementById('file-preview-icon'); if (!modal || !bodyEl) return; const fileName = fileData.name || (fileData.path ? fileData.path.split('/').pop() : 'arquivo'); const mimeType = fileData.mimeType || 'application/octet-stream'; const sizeFormatted = formatBytes(fileData.size || 0); if (titleEl) titleEl.textContent = fileName; if (metaEl) metaEl.textContent = `${sizeFormatted} • ${mimeType}`; bodyEl.innerHTML = ''; const isImage = mimeType.startsWith('image/'); const isVideo = mimeType.startsWith('video/') || /\.(mp4|webm|mov|mkv|avi|ogv)$/i.test(fileName); const isText = mimeType.startsWith('text/') || mimeType === 'application/json' || mimeType === 'application/xml' || mimeType === 'application/javascript' || mimeType === 'text/markdown'; if (isImage) { if (iconEl) iconEl.textContent = '🖼️'; if (copyBtn) copyBtn.style.display = 'none'; const imgContainer = document.createElement('div'); imgContainer.className = 'file-preview-img-container'; const img = document.createElement('img'); img.src = `data:${mimeType};base64,${fileData.contentBase64}`; img.alt = fileName; img.className = 'file-preview-image'; imgContainer.appendChild(img); bodyEl.appendChild(imgContainer); } else if (isVideo) { if (iconEl) iconEl.textContent = '🎬'; if (copyBtn) copyBtn.style.display = 'none'; const vidContainer = document.createElement('div'); vidContainer.className = 'file-preview-video-container'; vidContainer.style.textAlign = 'center'; const video = document.createElement('video'); video.controls = true; video.autoplay = false; video.playsInline = true; video.src = `data:${mimeType};base64,${fileData.contentBase64}`; video.style.maxWidth = '100%'; video.style.maxHeight = '65vh'; video.style.borderRadius = '8px'; video.style.background = '#000'; vidContainer.appendChild(video); bodyEl.appendChild(vidContainer); } else if (isText) { if (iconEl) iconEl.textContent = '📝'; if (copyBtn) copyBtn.style.display = 'inline-flex'; let textContent = ''; try { const binString = atob(fileData.contentBase64 || ''); const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0)); textContent = new TextDecoder('utf-8').decode(bytes); } catch (e) { textContent = atob(fileData.contentBase64 || ''); } const pre = document.createElement('pre'); pre.className = 'file-preview-pre'; const code = document.createElement('code'); code.className = 'file-preview-code'; code.textContent = textContent; pre.appendChild(code); bodyEl.appendChild(pre); } else { if (iconEl) iconEl.textContent = mimeType.includes('pdf') ? '📕' : (mimeType.includes('zip') ? '📦' : '📄'); if (copyBtn) copyBtn.style.display = 'none'; const binaryBox = document.createElement('div'); binaryBox.className = 'file-preview-binary-box'; binaryBox.innerHTML = `
📦
${escapeHtml(fileName)}

${escapeHtml(sizeFormatted)} • ${escapeHtml(mimeType)}

Arquivo binário pronto para download no dispositivo.

`; bodyEl.appendChild(binaryBox); } modal.style.display = 'flex'; } window.openFilePreviewModal = openFilePreviewModal; function closeFilePreviewModal() { const modal = document.getElementById('file-preview-modal'); if (modal) modal.style.display = 'none'; currentActiveFile = null; } window.closeFilePreviewModal = closeFilePreviewModal; function getNativeDownloadPlugin() { const cap = window.Capacitor; if (!cap || typeof cap.isNativePlatform !== 'function' || !cap.isNativePlatform()) return null; if (typeof cap.isPluginAvailable === 'function' && !cap.isPluginAvailable('NativeDownload')) return undefined; return (cap.Plugins && cap.Plugins.NativeDownload) || undefined; } async function saveCurrentActiveFile() { if (!currentActiveFile || !currentActiveFile.contentBase64) return; const { name, path: filePath, mimeType, contentBase64 } = currentActiveFile; const fileName = name || (filePath ? filePath.split('/').pop() : 'arquivo'); // No app Android (WebView do Capacitor), link blob: com a.download é ignorado em silêncio. // O arquivo escolhido na pré-visualização é salvo em Downloads pelo plugin nativo NativeDownload. const nativeDownload = getNativeDownloadPlugin(); if (nativeDownload === undefined) { showToast('Atualize o app Android (APK) para baixar arquivos.', 'error'); return; } if (nativeDownload) { try { const res = await nativeDownload.save({ name: fileName, mimeType: mimeType || 'application/octet-stream', data: contentBase64 }); showToast(`"${fileName}" salvo em ${(res && res.path) || 'Downloads'}`, 'info'); } catch (err) { console.error('[FileDownload] Erro ao salvar arquivo pelo app nativo:', err); showToast(`Erro ao salvar arquivo: ${(err && err.message) || err}`, 'error'); } return; } try { const byteCharacters = atob(contentBase64); const byteNumbers = new Array(byteCharacters.length); for (let i = 0; i < byteCharacters.length; i++) { byteNumbers[i] = byteCharacters.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); const blob = new Blob([byteArray], { type: mimeType || 'application/octet-stream' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = fileName; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(url), 1000); showToast(`Download de "${fileName}" iniciado!`, 'info'); } catch (err) { console.error('[FileDownload] Erro ao salvar arquivo:', err); showToast(`Erro ao salvar arquivo: ${err.message}`, 'error'); } } window.saveCurrentActiveFile = saveCurrentActiveFile; 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 ''; const clean = cleanTerminalOutput(terminalText).trim(); const lines = clean.split('\n').map(l => l.trim()).filter(Boolean); if (!lines.length) return ''; 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*Interrupted|What should.*?do instead)\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; // Ignora prompts de shell do sistema (PowerShell, CMD, Bash e fragmentos wrapped) if (/^(?:PS\s+[A-Za-z]:|[A-Za-z]:[\\/]|(?:[\w.-]+@[\w.-]+:.*?[#$])|bash-|\$|#|PS\s*>)/i.test(line)) continue; if (line.endsWith('>') && /(?:\\|\/|PS\s+|[A-Za-z]:|Reader>|Prompt>|[a-zA-Z0-9_.-]+>)/i.test(line)) continue; if (/Windows PowerShell|Copyright \(C\) Microsoft|Microsoft Windows \[Version/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)\s+/i.test(line)) { return line.slice(0, 50); } } // Se a última linha for um prompt de shell ou prompt fragmentado (ex: apeReader>), não exibe como ação const lastLine = lines[lines.length - 1]; if (/^(?:PS\s+[A-Za-z]:|[A-Za-z]:[\\/]|[\w.-]+@[\w.-]+:|\$|#|PS\s*>)/i.test(lastLine) || lastLine.endsWith('>') || /Windows PowerShell|Microsoft Windows/i.test(lastLine)) { return ''; } 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_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|variant)|Switch Model|Set Effort)(?:\s*[:\-]?\s*(?:esc|type to search|\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, '') .replace(/:\s*type to search.*$/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; if (/tab to switch panels/i.test(line) || /^Settings for (?:selected )?model:/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 isKiroControlsPanelFocused(lines, footerIdx) { if (footerIdx === -1) return false; const footerLine = lines[footerIdx] || ''; if (!/switch panels|at top for controls/i.test(footerLine)) { return false; } if (/\b(?:to toggle|back to models|to edit)\b/i.test(footerLine)) { return true; } let settingsHeaderIdx = -1; for (let i = footerIdx - 1; i >= Math.max(0, footerIdx - 10); i--) { if (/tab to switch panels/i.test(lines[i]) || /^Settings for (?:selected )?model:/i.test(stripBoxBorders(lines[i]))) { settingsHeaderIdx = i; break; } } if (settingsHeaderIdx !== -1) { for (let i = settingsHeaderIdx + 1; i < footerIdx; i++) { if (/^[>❯]\s+/.test(stripBoxBorders(lines[i]))) { return true; } } } return false; } 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; } } let modelMenuHeaderIdx = lines.findIndex(l => RE_MODEL_MENU_HEADER.test(stripBoxBorders(l))); if (modelMenuHeaderIdx === -1) { modelMenuHeaderIdx = lines.findIndex(l => /\bSelect (?:model|variant)\b/i.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 (isKiroControlsPanelFocused(lines, footerIdx)) { const controlsMenu = parseKiroControlsMenu(lines, footerIdx); if (controlsMenu && controlsMenu.options.length > 0) { return controlsMenu; } } 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 clean = terminalText.replace(RE_ANSI, '').trim(); if (!clean) { return { isThinking: isWaiting, isPaused: false, label: isWaiting ? 'Aguardando agente...' : '' }; } const lastChunk = clean.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: Prompts de Shell do Sistema e Prompts Ociosos de IA const lines = clean.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 combinedLast2 = prevLine ? `${prevLine}${lastLine}` : lastLine; const combinedLast3 = lines.slice(-3).join(''); const isShellPrompt = /(?:^|\n)\s*PS\s+(?:[A-Za-z]:[\\/]|[/~]|\.{1,2}[\\/]|[\w.-]+[\\/]).*?>\s*$/m.test(lastLine) || /(?:^|\n)\s*PS\s*>\s*$/m.test(lastLine) || /(?:^|\n)\s*[A-Za-z]:[\\/].*?>\s*$/m.test(lastLine) || /(?:^|\n)\s*(?:(?:\([\w.-]+\)\s*)?[\w.-]+@[\w.-]+:.*?[#$]|MINGW(?:32|64).*?\$|bash-[\d.]+\$|\$\s*|#\s*)$/m.test(lastLine) || /(?:^|\n)\s*PS\s+(?:[A-Za-z]:[\\/]|[/~]|\.{1,2}[\\/]|[\w.-]+[\\/]).*?>\s*$/m.test(combinedLast2) || /(?:^|\n)\s*[A-Za-z]:[\\/].*?>\s*$/m.test(combinedLast2) || /(?:^|\n)\s*PS\s+.*?>\s*$/m.test(combinedLast3) || /^\s*PS\s+.*?>\s*$/i.test(lastLine) || (lastLine.endsWith('>') && (/Windows PowerShell|PowerShell 7|Microsoft Windows/i.test(clean) || /PS\s+[A-Za-z]:/i.test(clean))); if (isShellPrompt) { return { isThinking: false, isPaused: false, label: 'Pronto' }; } const hasExplicitActiveSubagents = /[1-9]\d*\s+subagent\(s\)/i.test(lastLine) || /[1-9]\d*\s+subagent\(s\)/i.test(clean.slice(-300)); const hasActiveSubagentOrToolOnPrev = hasExplicitActiveSubagents || (/●\s*Agent\(/i.test(prevLine) && !/^\??\s*for shortcuts/i.test(lastLine) && !/^(?:│\s*)?(?:[>❯›]|↳\s*Interrupted)/i.test(lastLine)) || /[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ]/.test(prevLine) || /(?:running command|generating|percolating|analyzing|working\.\.\.|building|compiling|thinking\.\.\.|Kiro is working)/i.test(prevLine); const isAtIdlePrompt = !hasExplicitActiveSubagents && ( /^(?:│\s*)?(?:[>❯›]\s*[\u2588\u258C\u258E]?(?:ask a question or describe a task(?:\s*↵)?)?|↳\s*Interrupted.*?|(?:\bWhat should\b.*?\bdo instead\?)|(?:Are you sure|Do you want to proceed)\b.*?\?)\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) || /Gemini|Claude/i.test(lastLine) || /●\s*Agent\(/i.test(prevLine) || /●\s*Agent\(/i.test(prevPrevLine))) ); 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 (/[1-9]\d*\s+subagent\(s\)/i.test(lastChunk) || (/●\s*Agent\(/i.test(lastChunk) && !isAtIdlePrompt && /[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⣾⣽⣻⢿⡿⣟⣯⣷ᗧᗤᗥᗣᗢᗡᗠ]/.test(lastChunk))) { return { isThinking: true, isPaused: false, label: 'Executando subagente...' }; } if (/(Ran \(|Explored |Edited )/i.test(lastChunk) && !/\? for shortcuts/i.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Executando ações no workspace...' }; } // 6. Sessão com IA ativa em andamento fora do prompt ocioso de entrada if (!isAtIdlePrompt && !isShellPrompt && /(?:Antigravity CLI|\? for shortcuts|● Ran \(|● Explored |● Edited |Claude Code|Kiro CLI|kiro>|Gemini CLI|Aider)/i.test(lastChunk)) { return { isThinking: true, isPaused: false, label: 'Trabalhando na tarefa...' }; } // 7. 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: 'Pronto' }; } window.detectAgentThinking = detectAgentThinking; window.extractLatestAction = extractLatestAction; 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 filePaths = extractFilePaths(terminalText); if (filePaths.length > 0) { registerSessionFiles(filePaths, 'terminal'); } 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; } // Registra caminhos no catálogo da sessão sob demanda const existingChips = card.querySelector('.file-chips-container'); if (existingChips) { existingChips.remove(); } const filePaths = extractFilePaths(terminalText); if (filePaths.length > 0) { registerSessionFiles(filePaths, 'terminal'); } 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 const _chatHeartbeatTimer = setInterval(() => { if (activeChatAgent && chatDrawer && chatDrawer.style.display === 'flex') { captureAndSendScreenStateSnapshot(activeChatAgent, 'heartbeat_30s'); } }, 30000); if (_chatHeartbeatTimer && typeof _chatHeartbeatTimer.unref === 'function') { _chatHeartbeatTimer.unref(); } 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)}
`; const filePaths = extractFilePaths(terminalSnapshotText); if (filePaths.length > 0) { registerSessionFiles(filePaths, 'terminal'); } chatMessagesEl.appendChild(bubble); } else { const bubble = document.createElement('div'); bubble.className = `chat-bubble ${item.role}`; bubble.textContent = cleanTerminalOutput(item.text); if (item.role === 'agent') { const filePaths = extractFilePaths(item.text); if (filePaths.length > 0) { registerSessionFiles(filePaths, 'chat'); } } 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 videoItems = itemsToRender.filter(att => att && (att.isVideo || (att.mimeType && att.mimeType.startsWith('video/'))) && att.dataUrl); const fileItems = itemsToRender.filter(att => att && (!att.isImage || !att.dataUrl) && (!att.isVideo && (!att.mimeType || !att.mimeType.startsWith('video/')))); if (imageItems.length === 1 && fileItems.length === 0 && videoItems.length === 0) { attachBox.innerHTML = `${escapeHtml(imageItems[0].name)}`; } else if (imageItems.length > 0) { 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 (videoItems.length > 0) { const videoContainer = document.createElement('div'); videoContainer.className = 'chat-attachment-video-container'; videoItems.forEach(vAtt => { const vWrapper = document.createElement('div'); vWrapper.className = 'chat-attachment-video-wrapper'; vWrapper.style.marginTop = '6px'; vWrapper.innerHTML = `
🎬 ${escapeHtml(vAtt.name || 'video')} (${formatBytes(vAtt.size || 0)})
`; videoContainer.appendChild(vWrapper); }); attachBox.appendChild(videoContainer); } 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 authoritativeThinking = (activeAgentInfo && typeof activeAgentInfo.isThinking === 'boolean') ? activeAgentInfo.isThinking : (histKey && agentThinkingStates.has(histKey) ? agentThinkingStates.get(histKey) : null); const isThinkingEffective = typeof authoritativeThinking === 'boolean' ? authoritativeThinking : detection.isThinking; const showThinkingCard = !hasActiveMenu && !detection.isPaused && (isWaitingChatReply || isThinkingEffective); 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(forceRemoveAll = false) { clearTimeout(typingTimeoutTimer); typingTimeoutTimer = null; const typing = document.getElementById('chat-typing-indicator'); if (typing) { if (forceRemoveAll || !typing.classList.contains('thinking-card')) { 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 = ''; if (chatVideoRecordInput) chatVideoRecordInput.value = ''; if (chatVideoInput) chatVideoInput.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 || ''; const commaIdx = dataUrl.indexOf(','); const dataBase64 = commaIdx >= 0 ? dataUrl.slice(commaIdx + 1) : ''; resolve({ name: file.name, mimeType: file.type || 'application/octet-stream', size: file.size, dataUrl, dataBase64 }); }; reader.onerror = () => { resolve({ name: file.name, mimeType: file.type || 'application/octet-stream', size: file.size, dataUrl: '', dataBase64: '' }); }; 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 if (currentAttachment.isVideo) { attachmentThumbWrapper.innerHTML = `🎬`; } 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 if (att.isVideo) { thumb.innerHTML = `🎬`; } 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(); updateInputActionButtonState(); } } function clearAllAttachments() { currentAttachments = []; renderAttachmentPreview(); clearFileInputs(); updateInputActionButtonState(); } async function handleFilesSelected(files) { if (!files || files.length === 0) return; const fileList = Array.from(files); const MAX_FILES = 10; const MAX_TOTAL_SIZE = 100 * 1024 * 1024; // 100MB 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 100MB.`); continue; } const isImage = file.type && file.type.startsWith('image/'); const isVideo = Boolean(file.type && file.type.startsWith('video/')) || /\.(mp4|webm|mov|mkv|avi|ogv|m4v)$/i.test(file.name); const processed = await optimizeImageFile(file); let attName = processed.name || file.name || 'video.mp4'; let attMime = processed.mimeType || file.type; if (isVideo) { if (!attMime || attMime === 'application/octet-stream') { if (/\.webm$/i.test(attName)) attMime = 'video/webm'; else if (/\.mov$/i.test(attName)) attMime = 'video/quicktime'; else attMime = 'video/mp4'; } if (!/\.[a-zA-Z0-9]+$/.test(attName)) { attName = attName + (attMime.includes('webm') ? '.webm' : '.mp4'); } } currentAttachments.push({ name: attName, mimeType: attMime, size: processed.size || file.size, isImage, isVideo, dataUrl: processed.dataUrl, dataBase64: processed.dataBase64 }); currentTotalSize += processed.size; } renderAttachmentPreview(); clearFileInputs(); updateInputActionButtonState(); } async function handleFileSelected(file) { if (!file) return; await handleFilesSelected([file]); } // Controle do Menu Flutuante de Anexo (Câmera / Galeria / Gravação de Vídeo / Galeria de Vídeos / 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 (btnAttachVideoRecord) { btnAttachVideoRecord.addEventListener('click', () => { toggleAttachMenu(false); if (chatVideoRecordInput) chatVideoRecordInput.click(); }); } if (btnAttachVideoGallery) { btnAttachVideoGallery.addEventListener('click', () => { toggleAttachMenu(false); if (chatVideoInput) chatVideoInput.click(); }); } if (btnAttachFile) { btnAttachFile.addEventListener('click', () => { toggleAttachMenu(false); if (chatFileInput) chatFileInput.click(); }); } if (btnMenuDownloads) { btnMenuDownloads.addEventListener('click', () => { toggleAttachMenu(false); openSessionDownloadsModal(); }); } 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(chatVideoRecordInput); bindFileInput(chatVideoInput); 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; let voiceRestartTimeout = null; const stopRecordingUI = () => { isRecording = false; isVoiceExplicitlyStopped = true; if (voiceRestartTimeout) { clearTimeout(voiceRestartTimeout); voiceRestartTimeout = null; } voiceRestartCount = 0; setVoiceRecordingButtonActive(false); if (chatInput) { chatInput.placeholder = 'Digite ou fale para o agente...'; chatInput.value = chatInput.value.trim(); } updateInputActionButtonState(); }; const stopAnyActiveVoiceSession = () => { isVoiceExplicitlyStopped = true; if (voiceRestartTimeout) { clearTimeout(voiceRestartTimeout); voiceRestartTimeout = null; } 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 restartRecognitionSafely = (delay = 0) => { if (isVoiceExplicitlyStopped || !isRecording || !speechRecognizer) { return; } if (voiceRestartTimeout) { clearTimeout(voiceRestartTimeout); voiceRestartTimeout = null; } const attemptStart = () => { if (isVoiceExplicitlyStopped || !isRecording || !speechRecognizer) { return; } try { speechRecognizer.start(); } catch (e) { // Erro comum ao tentar reiniciar enquanto o motor nativo ainda está liberando o hardware // ou durante foco temporário de notificação (DOMException, InvalidStateError, etc.) console.warn('[Voice] Tentativa de reiniciar reconhecimento contínuo falhou, agendando retry:', e); if (!isVoiceExplicitlyStopped && isRecording) { voiceRestartTimeout = setTimeout(() => { restartRecognitionSafely(300); }, 300); } } }; if (delay > 0) { voiceRestartTimeout = setTimeout(attemptStart, delay); } else { attemptStart(); } }; // Mantém a gravação viva caso o app receba notificações ou perca foco temporariamente const handleVoiceFocusResume = () => { if (!isVoiceExplicitlyStopped && isRecording && speechRecognizer) { restartRecognitionSafely(100); } }; if (typeof window !== 'undefined') { window.addEventListener('focus', handleVoiceFocusResume); } if (typeof document !== 'undefined') { document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') { handleVoiceFocusResume(); } }); } 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; isVoiceExplicitlyStopped = false; setVoiceRecordingButtonActive(true); updateInputActionButtonState(); if (chatInput) chatInput.placeholder = 'Gravando áudio... Toque no botão para finalizar'; showToast('Gravando áudio... Fale e toque no botão para concluir.', '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(); }); }; const getOrCreateSpeechRecognizer = () => { const SpeechRecognitionClass = window.SpeechRecognition || window.webkitSpeechRecognition; if (!SpeechRecognitionClass) { return null; } if (speechRecognizer) { return speechRecognizer; } try { speechRecognizer = new SpeechRecognitionClass(); speechRecognizer.lang = 'pt-BR'; speechRecognizer.continuous = true; speechRecognizer.interimResults = true; speechRecognizer.onstart = () => { isRecording = true; isVoiceExplicitlyStopped = false; setVoiceRecordingButtonActive(true); updateInputActionButtonState(); if (chatInput) chatInput.placeholder = 'Ouvindo... Fale à vontade (toque no botão para encerrar)'; showToast('Ditado contínuo ativado. Toque no botão 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(); updateInputActionButtonState(); } }; speechRecognizer.onerror = (err) => { console.warn('[Voice] SpeechRecognition erro:', err.error); if (isVoiceExplicitlyStopped) return; // Erros não fatais causados por pausas de respiração, interrupções transitórias de foco ou sons de notificações if (err.error === 'no-speech' || err.error === 'aborted' || err.error === 'audio-capture') { if (err.error === 'audio-capture') { restartRecognitionSafely(400); } return; } // Se for erro crítico (falha de rede do Google ou permissão negada), notifica e interrompe if (err.error === 'network') { showToast('Falha de conexão com o serviço de voz. Verifique sua internet e tente novamente.', 'warning'); } else if (err.error === 'service-not-allowed' || err.error === 'not-allowed') { showToast('Permissão de microfone/fala não concedida no dispositivo ou navegador.', 'error'); } else { showToast(`Reconhecimento de fala: ${err.error}`, 'warning'); } stopRecordingUI(); }; speechRecognizer.onend = () => { if (!isVoiceExplicitlyStopped && isRecording && speechRecognizer) { // Consolida a transcrição final da sessão e reinicia sem desligar a gravação voiceAccumulatedTranscript += voiceSessionFinal; voiceSessionFinal = ''; voiceRestartCount++; restartRecognitionSafely(0); return; } stopRecordingUI(); }; return speechRecognizer; } catch (err) { console.warn('[Voice] Falha ao instanciar SpeechRecognition:', err); return null; } }; // Inicializa previamente se o navegador tiver suporte getOrCreateSpeechRecognizer(); btnVoice.addEventListener('click', (e) => { e.preventDefault(); if (!isRecording) { isVoiceExplicitlyStopped = false; voiceRestartCount = 0; voiceBasePrefix = chatInput && chatInput.value ? chatInput.value.trimEnd() + ' ' : ''; voiceAccumulatedTranscript = ''; voiceSessionFinal = ''; const recognizer = getOrCreateSpeechRecognizer(); if (!recognizer) { startAudioRecording(); return; } try { recognizer.start(); } catch (err) { console.warn('[Voice] Erro ao iniciar recognizer, tentando recuperar estado:', err); try { recognizer.stop(); } catch (stopErr) {} setTimeout(() => { try { recognizer.start(); } catch (retryErr) { console.warn('[Voice] Falha definitiva ao iniciar recognizer:', retryErr); showToast('Não foi possível iniciar o microfone de ditado. Tente novamente.', 'warning'); stopRecordingUI(); } }, 150); } } else { stopAnyActiveVoiceSession(); } }); window._stopAnyActiveVoiceSession = stopAnyActiveVoiceSession; } if (btnSessionDownloads) { btnSessionDownloads.addEventListener('click', (e) => { e.preventDefault(); openSessionDownloadsModal(); }); } if (btnCloseSessionDownloads) { btnCloseSessionDownloads.addEventListener('click', (e) => { e.preventDefault(); closeSessionDownloadsModal(); }); } if (sessionDownloadsModal) { sessionDownloadsModal.addEventListener('click', (e) => { if (e.target === sessionDownloadsModal) { closeSessionDownloadsModal(); } }); } if (chatInput) { chatInput.addEventListener('input', updateInputActionButtonState); chatInput.addEventListener('change', updateInputActionButtonState); chatInput.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.shiftKey) { if (isRecording) { e.preventDefault(); } } }); } if (chatForm) { chatForm.addEventListener('submit', (e) => { e.preventDefault(); // O botão e a ação de envio ficam bloqueados enquanto a gravação de voz estiver ativa if (isRecording) { return; } if (typeof window._stopAnyActiveVoiceSession === 'function') { window._stopAnyActiveVoiceSession(); } if (!chatInput) return; const text = chatInput.value.trim(); const trimmedLower = text.toLowerCase(); if (trimmedLower === '/downloads' || trimmedLower === '/download' || trimmedLower === '/arquivos' || trimmedLower === '/arquivo') { chatInput.value = ''; updateInputActionButtonState(); openSessionDownloadsModal(); return; } 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 } : undefined })); clearAllAttachments(); if (chatInput) { chatInput.value = ''; chatInput.dispatchEvent(new Event('input', { bubbles: true })); } updateInputActionButtonState(); 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(); clearAuthSession(); localStorage.removeItem('maestri_pin'); localStorage.removeItem('maestri_stations'); currentPin = null; ws = null; setConnected(false); if (pinInput) pinInput.value = ''; if (statusText) statusText.textContent = 'Desconectado'; if (btnConnect) { btnConnect.disabled = false; btnConnect.textContent = 'Conectar'; } closeChat(); showAuthScreen(); } // ========================================== // Inicialização do Aplicativo // ========================================== async function initApp() { const params = new URLSearchParams(window.location.search); const pinFromUrl = params.get('pin'); setupStationEvents(); setupChatEvents(); if (btnGoogleLogin) btnGoogleLogin.addEventListener('click', startGoogleLogin); if (btnAuthLogout) btnAuthLogout.addEventListener('click', logoutUser); 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(); }); } // Listeners do Modal de Preview e Download de Arquivos if (btnCloseFilePreview) { btnCloseFilePreview.addEventListener('click', closeFilePreviewModal); } if (filePreviewModal) { filePreviewModal.addEventListener('click', (e) => { if (e.target === filePreviewModal) closeFilePreviewModal(); }); } if (btnSaveFile) { btnSaveFile.addEventListener('click', saveCurrentActiveFile); } if (btnCopyFileContent) { btnCopyFileContent.addEventListener('click', async () => { if (!currentActiveFile || !currentActiveFile.contentBase64) return; try { const binString = atob(currentActiveFile.contentBase64 || ''); const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0)); const text = new TextDecoder('utf-8').decode(bytes); if (navigator.clipboard && navigator.clipboard.writeText) { await navigator.clipboard.writeText(text); } else { const ta = document.createElement('textarea'); ta.value = text; document.body.appendChild(ta); ta.select(); document.execCommand('copy'); document.body.removeChild(ta); } showToast('Conteúdo copiado para a área de transferência!', 'info'); } catch (e) { showToast('Falha ao copiar conteúdo.', 'error'); } }); } 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(); try { initNativePushNotifications(); } catch (pushInitErr) { console.warn('[Boot] Erro seguro ao disparar initNativePushNotifications:', pushInitErr); } initOtaChecker(); // Gate obrigatório de autenticação Google SSO com renovação silenciosa via refresh token let token = getAuthToken(); const refreshToken = getRefreshToken(); if (!token && !refreshToken) { if (pinFromUrl && pinFromUrl.length >= 4) { try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {} } showAuthScreen(); return; } // Se o access token está ausente mas temos refresh token, tenta renovação silenciosa imediata if (!token && refreshToken) { const refreshed = await refreshAuthSession(); if (refreshed) { token = getAuthToken(); } else { if (pinFromUrl && pinFromUrl.length >= 4) { try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {} } showAuthScreen(); return; } } try { let meRes = await fetch(`${getApiBaseUrl()}/api/auth/me`, { headers: { 'Authorization': `Bearer ${token}` } }); // Se respondeu 401, tenta renovação silenciosa via refresh token antes de deslogar if (meRes.status === 401 && getRefreshToken()) { const refreshed = await refreshAuthSession(); if (refreshed) { token = getAuthToken(); meRes = await fetch(`${getApiBaseUrl()}/api/auth/me`, { headers: { 'Authorization': `Bearer ${token}` } }); } } if (meRes.ok) { const data = await meRes.json(); if (data && data.user) { try { localStorage.setItem('maestri_user', JSON.stringify(data.user)); } catch (e) {} if (pinFromUrl && pinFromUrl.length >= 4) { try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {} } await completeAuthenticatedStartup(data.user); return; } } if (meRes.status === 401) { clearAuthSession(); if (pinFromUrl && pinFromUrl.length >= 4) { try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {} } showAuthScreen(); return; } } catch (err) { console.warn('[Auth] Falha de rede ao validar sessão:', err.message); } const cachedUser = getSavedAuthUser(); if (cachedUser && cachedUser.id) { if (pinFromUrl && pinFromUrl.length >= 4) { try { sessionStorage.setItem('maestri_pending_pin', pinFromUrl); } catch (e) {} } await completeAuthenticatedStartup(cachedUser); } else { showAuthScreen(); } } // Listener para renovação proativa quando o app volta do background const checkTokenExpiryAndRefresh = async () => { const currentToken = getAuthToken(); const currentRefresh = getRefreshToken(); if (!currentToken || !currentRefresh) return; try { const parts = currentToken.split('.'); if (parts.length === 3) { const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/'))); const nowSec = Math.floor(Date.now() / 1000); if (typeof payload.exp === 'number' && payload.exp - nowSec < 300) { await refreshAuthSession(); } } } catch (e) {} }; document.addEventListener('visibilitychange', () => { if (!document.hidden) checkTokenExpiryAndRefresh(); }); window.addEventListener('focus', checkTokenExpiryAndRefresh); window.addEventListener('resume', checkTokenExpiryAndRefresh); window.logoutUser = logoutUser; window.getRefreshToken = getRefreshToken; window.refreshAuthSession = refreshAuthSession; window.fetchWithAuth = fetchWithAuth; 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 (typeof window === 'undefined' || typeof navigator === 'undefined' || !('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) {} if (typeof sendFcmTokenToRelay === 'function') { sendFcmTokenToRelay(null, pin); } } async function sendFcmTokenToRelay(tokenOverride = null, specificPin = null) { try { let token = tokenOverride; if (!token && typeof localStorage !== 'undefined') { token = localStorage.getItem('maestri_fcm_token'); } if (!token) return; const baseUrl = getApiBaseUrl(); const stations = getSavedStations(); const targets = new Set(); targets.add('default'); if (specificPin) targets.add(String(specificPin)); stations.forEach(s => { if (s.pin) targets.add(String(s.pin)); }); for (const t of targets) { try { await fetch(`${baseUrl}/api/notifications/fcm-token`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token, stationId: t, pin: t }) }); } catch (err) {} } } catch (err) { console.warn('[FCM] Erro ao sincronizar token com relay:', err); } } async function initNativePushNotifications() { const cap = window.Capacitor; if (!cap) return; const isNative = typeof cap.isNativePlatform === 'function' ? cap.isNativePlatform() : (cap.getPlatform && cap.getPlatform() !== 'web'); if (!isNative) return; const PushNotifications = cap?.Plugins?.PushNotifications; if (!PushNotifications) return; try { if (typeof cap.isPluginAvailable === 'function' && !cap.isPluginAvailable('PushNotifications')) { console.warn('[FCM] Plugin PushNotifications não está disponível nesta plataforma/build.'); return; } } catch (e) { console.warn('[FCM] Falha ao verificar disponibilidade do plugin PushNotifications:', e); } try { // 1. Cria canais de alta prioridade no Android antes do registro (com proteção defensiva) const isAndroid = cap.getPlatform && cap.getPlatform() === 'android'; if (isAndroid && typeof PushNotifications.createChannel === 'function') { try { await PushNotifications.createChannel({ id: 'maestri_urgent', name: 'Alertas Críticos', description: 'Notificações urgentes de tarefas e aprovações do Maestri', importance: 5, visibility: 1, vibration: true, lights: true, lightColor: '#22c55e' }).catch(err => console.warn('[FCM] createChannel maestri_urgent aviso:', err)); } catch (channelErr) { console.warn('[FCM] Aviso ao criar canal maestri_urgent:', channelErr); } try { await PushNotifications.createChannel({ id: 'fcm_fallback_notification_channel', name: 'Notificações Maestri', description: 'Notificações gerais e avisos de tarefas', importance: 5, visibility: 1, vibration: true, lights: true, lightColor: '#22c55e' }).catch(err => console.warn('[FCM] createChannel fcm_fallback aviso:', err)); } catch (channelErr) { console.warn('[FCM] Aviso ao criar canal fcm_fallback:', channelErr); } } // 2. Registra os listeners OBRIGATORIAMENTE ANTES de invocar register() para evitar race conditions if (typeof PushNotifications.addListener === 'function') { try { PushNotifications.addListener('registration', async (token) => { console.log('[FCM] Token de registro nativo recebido:', token?.value); if (token?.value) { try { localStorage.setItem('maestri_fcm_token', token.value); } catch (e) {} await sendFcmTokenToRelay(token.value); } }); PushNotifications.addListener('registrationError', (error) => { console.warn('[FCM] Registro de push nativo reportou erro ou Firebase não configurado:', error); }); PushNotifications.addListener('pushNotificationReceived', (notification) => { console.log('[FCM] Notificação recebida no cliente:', notification); if (typeof playNotificationSound === 'function') { try { playNotificationSound(); } catch (e) {} } if (typeof navigator !== 'undefined' && navigator.vibrate) { try { navigator.vibrate([200, 100, 200]); } catch (e) {} } }); PushNotifications.addListener('pushNotificationActionPerformed', (action) => { console.log('[FCM] Notificação acionada pelo operador:', action); const data = action?.notification?.data || {}; if (data.stationId && data.agentName) { switchStation(data.stationId); setTimeout(() => { openChatModal(data.agentName, data.stationId); }, 300); } }); } catch (listenerErr) { console.warn('[FCM] Erro defensivo ao registrar listeners do PushNotifications:', listenerErr); } } // 3. Solicita permissão e registra defensivamente (isolado em try/catch para nunca crashar na ausência do Firebase) try { let permResult = null; if (typeof PushNotifications.checkPermissions === 'function') { permResult = await PushNotifications.checkPermissions().catch(() => null); } if (!permResult || permResult.receive !== 'granted') { if (typeof PushNotifications.requestPermissions === 'function') { permResult = await PushNotifications.requestPermissions().catch(() => null); } } if (permResult && permResult.receive === 'granted' && typeof PushNotifications.register === 'function') { try { await PushNotifications.register(); } catch (regErr) { console.warn('[FCM] PushNotifications.register() ignorado defensivamente (Firebase/google-services ausente):', regErr); } } else { console.log('[FCM] Permissão de notificações não concedida pelo usuário.'); } } catch (permErr) { console.warn('[FCM] Falha defensiva ao verificar permissões/registrar PushNotifications:', permErr); } // 4. Se já houver token em cache no localStorage, sincroniza imediatamente com o relay try { const cachedToken = localStorage.getItem('maestri_fcm_token'); if (cachedToken) { await sendFcmTokenToRelay(cachedToken); } } catch (tokenSyncErr) { console.warn('[FCM] Erro ao sincronizar cachedToken:', tokenSyncErr); } } catch (err) { console.warn('[FCM] Erro ao inicializar notificações nativas Capacitor:', err); } } 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() { const _otaInterval = 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); if (_otaInterval && typeof _otaInterval.unref === 'function') { _otaInterval.unref(); } }