diff --git a/app.js b/app.js index d333afc..abaf574 100644 --- a/app.js +++ b/app.js @@ -100,6 +100,19 @@ 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'; @@ -360,10 +373,14 @@ 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'); @@ -383,6 +400,20 @@ 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:'; @@ -463,6 +494,9 @@ function getSavedStations() { function saveStationsList(stations) { try { localStorage.setItem('maestri_stations', JSON.stringify(stations)); + if (typeof sendFcmTokenToRelay === 'function') { + sendFcmTokenToRelay(); + } } catch (e) {} } @@ -688,9 +722,62 @@ async function startGoogleLogin() { } if (isNativeOrLocal) { - const opened = window.open(authUrl, '_system'); + 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) { - window.location.href = authUrl; + 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 { @@ -1404,7 +1491,7 @@ function handleStationMessage(pin, msg) { break; case 'FILE_READ_RESP': - document.querySelectorAll('.btn-file-chip').forEach(btn => { + 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'); @@ -2074,6 +2161,7 @@ function openChatWithAgent(agentName, pin, machineName) { chatInput.value = ''; setTimeout(() => chatInput.focus(), 150); } + updateInputActionButtonState(); // Marca respostas como lidas ao abrir o chat com o agente markAgentResponsesAsRead(agentName, activeChatPin); @@ -2094,6 +2182,7 @@ function closeChat() { if (typeof window._stopAnyActiveVoiceSession === 'function') { window._stopAnyActiveVoiceSession(); } + closeSessionDownloadsModal(); clearInterval(terminalPollInterval); terminalPollInterval = null; toggleAttachMenu(false); @@ -2176,6 +2265,159 @@ function extractFilePaths(text) { } window.extractFilePaths = extractFilePaths; +// Catálogo e Downloads Sob Demanda +function registerSessionFiles(filePaths, source = 'text') { + if (!Array.isArray(filePaths) || filePaths.length === 0) return; + 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(normalized, { + path: normalized, + name: baseName, + ext, + timestamp: Date.now(), + source + }); + }); + updateSessionDownloadsBadge(); +} +window.registerSessionFiles = registerSessionFiles; + +function updateSessionDownloadsBadge() { + if (!sessionDownloadsBadge) return; + const total = sessionFilesCatalog.size; + 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 = ''; + if (sessionFilesCatalog.size === 0) { + sessionDownloadsEmpty.style.display = 'block'; + sessionDownloadsList.style.display = 'none'; + } else { + sessionDownloadsEmpty.style.display = 'none'; + sessionDownloadsList.style.display = 'flex'; + + const files = Array.from(sessionFilesCatalog.values()).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'; @@ -2258,6 +2500,7 @@ function openFilePreviewModal(fileData) { 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' || @@ -2276,6 +2519,24 @@ function openFilePreviewModal(fileData) { 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'; @@ -3631,8 +3892,7 @@ function updateTerminalSnapshotInPlace(terminalText, isThinking, isPausedParam = const filePaths = extractFilePaths(terminalText); if (filePaths.length > 0) { - const chipsContainer = renderFileChips(filePaths); - card.appendChild(chipsContainer); + registerSessionFiles(filePaths, 'terminal'); } const prevScrollTop = chatMessagesEl.scrollTop; @@ -3659,18 +3919,14 @@ function updateTerminalSnapshotInPlace(terminalText, isThinking, isPausedParam = pill.textContent = pillText; } - // Atualiza os chips de arquivos no snapshot in-place + // 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) { - const newChips = renderFileChips(filePaths); - if (existingChips) { - existingChips.replaceWith(newChips); - } else { - card.appendChild(newChips); - } - } else if (existingChips) { - existingChips.remove(); + registerSessionFiles(filePaths, 'terminal'); } return true; @@ -3804,12 +4060,14 @@ function captureAndSendScreenStateSnapshot(agentName, reason = 'state_change') { } // Heartbeat leve a cada 30 segundos para manter snapshot atualizado enquanto ativo -const _snapInterval = setInterval(() => { +const _chatHeartbeatTimer = setInterval(() => { if (activeChatAgent && chatDrawer && chatDrawer.style.display === 'flex') { captureAndSendScreenStateSnapshot(activeChatAgent, 'heartbeat_30s'); } }, 30000); -if (_snapInterval && typeof _snapInterval.unref === 'function') _snapInterval.unref(); +if (_chatHeartbeatTimer && typeof _chatHeartbeatTimer.unref === 'function') { + _chatHeartbeatTimer.unref(); +} function renderChatMessages(forceScroll = false) { if (!chatMessagesEl || !activeChatAgent) return; @@ -3853,8 +4111,7 @@ function renderChatMessages(forceScroll = false) { const filePaths = extractFilePaths(terminalSnapshotText); if (filePaths.length > 0) { - const chipsContainer = renderFileChips(filePaths); - bubble.appendChild(chipsContainer); + registerSessionFiles(filePaths, 'terminal'); } chatMessagesEl.appendChild(bubble); @@ -3866,8 +4123,7 @@ function renderChatMessages(forceScroll = false) { if (item.role === 'agent') { const filePaths = extractFilePaths(item.text); if (filePaths.length > 0) { - const chipsContainer = renderFileChips(filePaths); - bubble.appendChild(chipsContainer); + registerSessionFiles(filePaths, 'chat'); } } @@ -3880,11 +4136,12 @@ function renderChatMessages(forceScroll = false) { attachBox.className = 'chat-attachment-bubble'; const imageItems = itemsToRender.filter(att => att && att.isImage && att.dataUrl); - const fileItems = itemsToRender.filter(att => att && (!att.isImage || !att.dataUrl)); + 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) { + if (imageItems.length === 1 && fileItems.length === 0 && videoItems.length === 0) { attachBox.innerHTML = `${escapeHtml(imageItems[0].name)}`; - } else if (imageItems.length > 1) { + } else if (imageItems.length > 0) { const grid = document.createElement('div'); grid.className = 'chat-attachment-grid'; imageItems.forEach(imgAtt => { @@ -3897,6 +4154,22 @@ function renderChatMessages(forceScroll = false) { 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'; @@ -4129,6 +4402,8 @@ function setupChatEvents() { 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) { @@ -4136,13 +4411,24 @@ function setupChatEvents() { 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 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: (dataUrl || '').split(',')[1] || '' + dataBase64 + }); + }; + reader.onerror = () => { + resolve({ + name: file.name, + mimeType: file.type || 'application/octet-stream', + size: file.size, + dataUrl: '', + dataBase64: '' }); }; reader.readAsDataURL(file); @@ -4293,6 +4579,8 @@ function setupChatEvents() { if (attachmentThumbWrapper && currentAttachment) { if (currentAttachment.isImage && currentAttachment.dataUrl) { attachmentThumbWrapper.innerHTML = `Thumbnail`; + } else if (currentAttachment.isVideo) { + attachmentThumbWrapper.innerHTML = `🎬`; } else { attachmentThumbWrapper.innerHTML = ``; } @@ -4310,6 +4598,8 @@ function setupChatEvents() { thumb.className = 'attachment-chip-thumb'; if (att.isImage && att.dataUrl) { thumb.innerHTML = `${escapeHtml(att.name)}`; + } else if (att.isVideo) { + thumb.innerHTML = `🎬`; } else { thumb.innerHTML = ``; } @@ -4355,6 +4645,7 @@ function setupChatEvents() { if (index >= 0 && index < currentAttachments.length) { currentAttachments.splice(index, 1); renderAttachmentPreview(); + updateInputActionButtonState(); } } @@ -4362,6 +4653,7 @@ function setupChatEvents() { currentAttachments = []; renderAttachmentPreview(); clearFileInputs(); + updateInputActionButtonState(); } async function handleFilesSelected(files) { @@ -4369,7 +4661,7 @@ function setupChatEvents() { const fileList = Array.from(files); const MAX_FILES = 10; - const MAX_TOTAL_SIZE = 25 * 1024 * 1024; // 25MB + 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.`); @@ -4381,18 +4673,33 @@ function setupChatEvents() { for (const file of fileList) { if (currentTotalSize + file.size > MAX_TOTAL_SIZE) { - alert(`O arquivo "${file.name}" excede o limite máximo total de 25MB.`); + 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: processed.name, - mimeType: processed.mimeType, - size: processed.size, + name: attName, + mimeType: attMime, + size: processed.size || file.size, isImage, + isVideo, dataUrl: processed.dataUrl, dataBase64: processed.dataBase64 }); @@ -4402,6 +4709,7 @@ function setupChatEvents() { renderAttachmentPreview(); clearFileInputs(); + updateInputActionButtonState(); } async function handleFileSelected(file) { @@ -4409,7 +4717,7 @@ function setupChatEvents() { await handleFilesSelected([file]); } - // Controle do Menu Flutuante de Anexo (Câmera / Galeria / Arquivos) + // 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(); @@ -4437,6 +4745,20 @@ function setupChatEvents() { }); } + 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); @@ -4444,6 +4766,13 @@ function setupChatEvents() { }); } + if (btnMenuDownloads) { + btnMenuDownloads.addEventListener('click', () => { + toggleAttachMenu(false); + openSessionDownloadsModal(); + }); + } + const bindFileInput = (inputEl) => { if (!inputEl) return; inputEl.addEventListener('change', (e) => { @@ -4456,6 +4785,8 @@ function setupChatEvents() { bindFileInput(chatCameraInput); bindFileInput(chatGalleryInput); + bindFileInput(chatVideoRecordInput); + bindFileInput(chatVideoInput); bindFileInput(chatFileInput); if (btnRemoveAttachment) { @@ -4479,20 +4810,30 @@ function setupChatEvents() { let voiceAccumulatedTranscript = ''; let voiceSessionFinal = ''; let voiceRestartCount = 0; + let voiceRestartTimeout = null; const stopRecordingUI = () => { isRecording = false; isVoiceExplicitlyStopped = true; + if (voiceRestartTimeout) { + clearTimeout(voiceRestartTimeout); + voiceRestartTimeout = null; + } voiceRestartCount = 0; - btnVoice.classList.remove('recording'); + 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) {} } @@ -4506,6 +4847,57 @@ function setupChatEvents() { 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'); @@ -4519,9 +4911,11 @@ function setupChatEvents() { navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => { voiceActiveStream = stream; isRecording = true; - btnVoice.classList.add('recording'); - if (chatInput) chatInput.placeholder = 'Gravando áudio... Toque no mic para finalizar'; - showToast('Gravando áudio... Fale e toque no microfone para enviar.', 'info'); + 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'; @@ -4611,9 +5005,10 @@ function setupChatEvents() { speechRecognizer.onstart = () => { isRecording = true; isVoiceExplicitlyStopped = false; - btnVoice.classList.add('recording'); - if (chatInput) chatInput.placeholder = 'Ouvindo... Fale à vontade (toque no mic para encerrar)'; - showToast('Ditado contínuo ativado. Toque no microfone para concluir.', 'info'); + 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) => { @@ -4629,46 +5024,41 @@ function setupChatEvents() { } if (chatInput) { chatInput.value = (voiceBasePrefix + voiceAccumulatedTranscript + voiceSessionFinal + interimTranscript).trimStart(); + updateInputActionButtonState(); } }; speechRecognizer.onerror = (err) => { console.warn('[Voice] SpeechRecognition erro:', err.error); - if (err.error === 'no-speech') { - // Silêncio temporário (pausa para respirar ou pensar): ignora e deixa o ciclo continuar + 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; } - if (err.error === 'aborted') { - return; - } - stopRecordingUI(); - - // Feedback claro e contextual sem anular a instância do recognizer e sem cair silenciosamente para gravação física + + // 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 if (err.error === 'audio-capture') { - showToast('Nenhum microfone detectado ou microfone ocupado por outro app.', 'warning'); } 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 para tolerar pausas de respiração + // Consolida a transcrição final da sessão e reinicia sem desligar a gravação voiceAccumulatedTranscript += voiceSessionFinal; voiceSessionFinal = ''; voiceRestartCount++; - if (voiceRestartCount < 50) { - try { - speechRecognizer.start(); - return; - } catch (e) { - console.warn('[Voice] Falha ao auto-reiniciar reconhecimento contínuo:', e); - } - } + restartRecognitionSafely(0); + return; } stopRecordingUI(); }; @@ -4694,7 +5084,7 @@ function setupChatEvents() { const recognizer = getOrCreateSpeechRecognizer(); if (!recognizer) { - showToast('Reconhecimento de fala não suportado neste navegador.', 'error'); + startAudioRecording(); return; } @@ -4723,14 +5113,61 @@ function setupChatEvents() { 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; @@ -4785,13 +5222,16 @@ function setupChatEvents() { attachment: attachmentToSend ? { name: attachmentToSend.name, mimeType: attachmentToSend.mimeType, - size: attachmentToSend.size, - dataBase64: attachmentToSend.dataBase64 + size: attachmentToSend.size } : undefined })); clearAllAttachments(); - chatInput.value = ''; + if (chatInput) { + chatInput.value = ''; + chatInput.dispatchEvent(new Event('input', { bubbles: true })); + } + updateInputActionButtonState(); isWaitingChatReply = true; hadThinkingDuringReply = false; @@ -4987,7 +5427,11 @@ async function initApp() { } initServiceWorker(); - initNativePushNotifications(); + try { + initNativePushNotifications(); + } catch (pushInitErr) { + console.warn('[Boot] Erro seguro ao disparar initNativePushNotifications:', pushInitErr); + } initOtaChecker(); // Gate obrigatório de autenticação Google SSO @@ -5079,7 +5523,7 @@ if (pinInput) { // Web Push Notifications & OTA Service // ========================================== async function initServiceWorker() { - if (!('serviceWorker' in navigator) || !('PushManager' in window)) return; + if (typeof window === 'undefined' || typeof navigator === 'undefined' || !('serviceWorker' in navigator) || !('PushManager' in window)) return; try { const reg = await navigator.serviceWorker.register('/sw.js'); @@ -5135,60 +5579,170 @@ async function syncPushSubscription(pin, sub) { 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 (cap.getPlatform && cap.getPlatform() === 'android') { - 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, - sound: 'default', - vibration: true - }); + 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); + } } - const permResult = await PushNotifications.requestPermissions(); - if (permResult && permResult.receive === 'granted') { - await PushNotifications.register(); + // 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); + } } - PushNotifications.addListener('registration', async (token) => { - console.log('[FCM] Token de registro nativo recebido:', token.value); - try { localStorage.setItem('maestri_fcm_token', token.value); } catch (e) {} - 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 stations = getSavedStations(); - const targets = stations.length > 0 ? stations.map(s => s.pin) : ['default']; - for (const t of targets) { + // 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 fetch(`${baseUrl}/api/notifications/fcm-token`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ token: token.value, stationId: t, pin: t }) - }); - } catch (err) {} + 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); + } - 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); + // 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); } @@ -5296,5 +5850,7 @@ function initOtaChecker() { // Ignora erro de rede temporário } }, 30000); - if (_otaInterval && typeof _otaInterval.unref === 'function') _otaInterval.unref(); + if (_otaInterval && typeof _otaInterval.unref === 'function') { + _otaInterval.unref(); + } } diff --git a/public/app.js b/public/app.js index 78db93a..abaf574 100644 --- a/public/app.js +++ b/public/app.js @@ -4411,13 +4411,24 @@ function setupChatEvents() { 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 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: (dataUrl || '').split(',')[1] || '' + dataBase64 + }); + }; + reader.onerror = () => { + resolve({ + name: file.name, + mimeType: file.type || 'application/octet-stream', + size: file.size, + dataUrl: '', + dataBase64: '' }); }; reader.readAsDataURL(file); @@ -5211,8 +5222,7 @@ function setupChatEvents() { attachment: attachmentToSend ? { name: attachmentToSend.name, mimeType: attachmentToSend.mimeType, - size: attachmentToSend.size, - dataBase64: attachmentToSend.dataBase64 + size: attachmentToSend.size } : undefined })); diff --git a/public/bundles/bundle-1.0.30.zip b/public/bundles/bundle-1.0.30.zip index ec77cae..b8cde51 100644 Binary files a/public/bundles/bundle-1.0.30.zip and b/public/bundles/bundle-1.0.30.zip differ diff --git a/public/bundles/bundle-latest.zip b/public/bundles/bundle-latest.zip index ec77cae..b8cde51 100644 Binary files a/public/bundles/bundle-latest.zip and b/public/bundles/bundle-latest.zip differ diff --git a/public/bundles/manifest.json b/public/bundles/manifest.json index 8a40853..3da61b4 100644 --- a/public/bundles/manifest.json +++ b/public/bundles/manifest.json @@ -1,9 +1,9 @@ { "version": "1.0.30", - "buildId": "2b19b259", - "releasedAt": "2026-11-22T01:45:51.720Z", + "buildId": "80e2a090", + "releasedAt": "2026-11-22T02:08:06.061Z", "bundleUrl": "/bundles/bundle-1.0.30.zip", "latestUrl": "/bundles/bundle-latest.zip", - "checksum": "51f053551f194cc6c082dedbbab16fc05a50ab5c81e8b497131e723c0e3c48ce", - "sizeBytes": 74104 + "checksum": "6c29b0b1a4fd55a8ec77b89647273c243e8246492d76092394dbbeb755ea4dbe", + "sizeBytes": 74169 } \ No newline at end of file diff --git a/scripts/publish-kaniko.sh b/scripts/publish-kaniko.sh index d215d5e..c9c4d7b 100755 --- a/scripts/publish-kaniko.sh +++ b/scripts/publish-kaniko.sh @@ -71,7 +71,7 @@ spec: EOF echo "3. Aguardando inicialização do ambiente de transferência..." -while ! kubectl get pod "${POD_NAME}" -n "${NAMESPACE}" -o jsonpath='{.status.initContainerStatuses[0].state.running}' 2>/dev/null | grep -q true; do +while [ -z "$(kubectl get pod "${POD_NAME}" -n "${NAMESPACE}" -o jsonpath='{.status.initContainerStatuses[0].state.running.startedAt}' 2>/dev/null || true)" ]; do sleep 1 done @@ -82,13 +82,20 @@ kubectl exec -n "${NAMESPACE}" "${POD_NAME}" -c prep -- touch /workspace/ready echo "5. Executando build Kaniko e push para ${IMAGE_DEST}..." kubectl logs -f -n "${NAMESPACE}" "${POD_NAME}" -c kaniko -PHASE=$(kubectl get pod "${POD_NAME}" -n "${NAMESPACE}" -o jsonpath='{.status.phase}') +# Aguarda encerramento do container kaniko +EXIT_CODE="" +for _ in $(seq 1 15); do + EXIT_CODE=$(kubectl get pod "${POD_NAME}" -n "${NAMESPACE}" -o jsonpath='{.status.containerStatuses[0].state.terminated.exitCode}' 2>/dev/null || true) + if [ -n "${EXIT_CODE}" ]; then break; fi + sleep 1 +done + echo "6. Limpando Pod construtor e arquivos temporários..." kubectl delete pod "${POD_NAME}" -n "${NAMESPACE}" --grace-period=0 --force >/dev/null 2>&1 || true rm -f "${CONTEXT_TAR}" -if [ "${PHASE}" != "Succeeded" ]; then - echo "ERRO: O build do Kaniko falhou com status: ${PHASE}" >&2 +if [ "${EXIT_CODE}" != "0" ]; then + echo "ERRO: O build do Kaniko falhou com exitCode: ${EXIT_CODE}" >&2 exit 1 fi diff --git a/src/gateway/daemon.js b/src/gateway/daemon.js index 79a52cf..dcee076 100644 --- a/src/gateway/daemon.js +++ b/src/gateway/daemon.js @@ -157,7 +157,7 @@ export class GatewayDaemon { } console.log(`[Gateway] Conectando ao Relay Server em ${this.relayUrl}...`); - this.ws = new WebSocket(this.relayUrl, { maxPayload: 150 * 1024 * 1024 }); + this.ws = new WebSocket(this.relayUrl, { maxPayload: 200 * 1024 * 1024 }); this.ws.on('open', () => { console.log('[Gateway] Conectado com sucesso ao Relay Server!'); diff --git a/src/relay/server.js b/src/relay/server.js index f0eeace..591b564 100644 --- a/src/relay/server.js +++ b/src/relay/server.js @@ -82,8 +82,8 @@ const server = http.createServer(createRelayHttpHandler({ })); // Setup dos Servidores WebSocket -const wssGateway = new WebSocketServer({ noServer: true, maxPayload: 150 * 1024 * 1024 }); -const wssClient = new WebSocketServer({ noServer: true, maxPayload: 150 * 1024 * 1024 }); +const wssGateway = new WebSocketServer({ noServer: true, maxPayload: 200 * 1024 * 1024 }); +const wssClient = new WebSocketServer({ noServer: true, maxPayload: 200 * 1024 * 1024 }); server.on('upgrade', (request, socket, head) => { const { pathname } = new URL(request.url, `http://${request.headers.host}`);