diff --git a/app.js b/app.js index 1ec41a5..d333afc 100644 --- a/app.js +++ b/app.js @@ -3804,11 +3804,12 @@ function captureAndSendScreenStateSnapshot(agentName, reason = 'state_change') { } // Heartbeat leve a cada 30 segundos para manter snapshot atualizado enquanto ativo -setInterval(() => { +const _snapInterval = setInterval(() => { if (activeChatAgent && chatDrawer && chatDrawer.style.display === 'flex') { captureAndSendScreenStateSnapshot(activeChatAgent, 'heartbeat_30s'); } }, 30000); +if (_snapInterval && typeof _snapInterval.unref === 'function') _snapInterval.unref(); function renderChatMessages(forceScroll = false) { if (!chatMessagesEl || !activeChatAgent) return; @@ -4591,9 +4592,18 @@ function setupChatEvents() { }); }; - if (SpeechRecognition) { + const getOrCreateSpeechRecognizer = () => { + const SpeechRecognitionClass = window.SpeechRecognition || window.webkitSpeechRecognition; + if (!SpeechRecognitionClass) { + return null; + } + + if (speechRecognizer) { + return speechRecognizer; + } + try { - speechRecognizer = new SpeechRecognition(); + speechRecognizer = new SpeechRecognitionClass(); speechRecognizer.lang = 'pt-BR'; speechRecognizer.continuous = true; speechRecognizer.interimResults = true; @@ -4632,13 +4642,16 @@ function setupChatEvents() { return; } stopRecordingUI(); - // Se o serviço do Google não estiver integrado no WebView, faz fallback para gravação direta de áudio - if (err.error === 'service-not-allowed' || err.error === 'not-allowed' || err.error === 'network' || err.error === 'audio-capture') { - console.log('[Voice] Alternando para gravação direta de áudio...'); - speechRecognizer = null; - startAudioRecording(); + + // Feedback claro e contextual sem anular a instância do recognizer e sem cair silenciosamente para gravação física + 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(`Voz: ${err.error}`, 'warning'); + showToast(`Reconhecimento de fala: ${err.error}`, 'warning'); } }; @@ -4659,11 +4672,16 @@ function setupChatEvents() { } stopRecordingUI(); }; + + return speechRecognizer; } catch (err) { console.warn('[Voice] Falha ao instanciar SpeechRecognition:', err); - speechRecognizer = null; + return null; } - } + }; + + // Inicializa previamente se o navegador tiver suporte + getOrCreateSpeechRecognizer(); btnVoice.addEventListener('click', (e) => { e.preventDefault(); @@ -4674,16 +4692,28 @@ function setupChatEvents() { voiceAccumulatedTranscript = ''; voiceSessionFinal = ''; - if (speechRecognizer) { + const recognizer = getOrCreateSpeechRecognizer(); + if (!recognizer) { + showToast('Reconhecimento de fala não suportado neste navegador.', 'error'); + return; + } + + try { + recognizer.start(); + } catch (err) { + console.warn('[Voice] Erro ao iniciar recognizer, tentando recuperar estado:', err); try { - speechRecognizer.start(); - } catch (err) { - console.warn('[Voice] Falha ao iniciar reconhecimento, caindo para gravação:', err); - speechRecognizer = null; - startAudioRecording(); - } - } else { - startAudioRecording(); + 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(); @@ -5245,7 +5275,7 @@ window.closeVersionModal = closeVersionModal; window.fetchVersionInfo = fetchVersionInfo; function initOtaChecker() { - setInterval(async () => { + 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:'; @@ -5266,4 +5296,5 @@ function initOtaChecker() { // Ignora erro de rede temporário } }, 30000); + if (_otaInterval && typeof _otaInterval.unref === 'function') _otaInterval.unref(); } diff --git a/package-lock.json b/package-lock.json index 63e0502..6773216 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,13 +1,14 @@ { "name": "maestri-remote-agent", - "version": "1.0.23", + "version": "1.0.26", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "maestri-remote-agent", - "version": "1.0.23", + "version": "1.0.26", "dependencies": { + "@capacitor/push-notifications": "^6.0.2", "pg": "^8.23.1", "web-push": "^3.6.7", "ws": "^8.18.0" @@ -19,6 +20,25 @@ "jsdom": "^31.0.1" } }, + "node_modules/@capacitor/core": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/@capacitor/core/-/core-6.2.3.tgz", + "integrity": "sha512-zajW/Fu1RFi42CC6KDjjgOIJ57hCl0Mo9FixpWpm6wXYAsFOU04dk+CBLvRt6rtO3sd6Lce4xxu68Pvi1oR99w==", + "license": "MIT", + "peer": true, + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/@capacitor/push-notifications": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/@capacitor/push-notifications/-/push-notifications-6.0.5.tgz", + "integrity": "sha512-CsRmb0cnZd9Uwx24ym4My5fNKrQvwI4D51aMEph5pUZy+LAjp6q0y4NJe8DEgwaVdAqVLbb4rqn75AZ4WSiFYg==", + "license": "MIT", + "peerDependencies": { + "@capacitor/core": "^6.0.0" + } + }, "node_modules/@exodus/bytes": { "version": "1.16.0", "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz", @@ -590,6 +610,13 @@ "node": "^22.14.0 || >=24.0.0" } }, + "node_modules/tslib": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", + "license": "0BSD", + "peer": true + }, "node_modules/undici": { "version": "8.12.4", "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.4.tgz", diff --git a/public/app.js b/public/app.js index 1ec41a5..d333afc 100644 --- a/public/app.js +++ b/public/app.js @@ -3804,11 +3804,12 @@ function captureAndSendScreenStateSnapshot(agentName, reason = 'state_change') { } // Heartbeat leve a cada 30 segundos para manter snapshot atualizado enquanto ativo -setInterval(() => { +const _snapInterval = setInterval(() => { if (activeChatAgent && chatDrawer && chatDrawer.style.display === 'flex') { captureAndSendScreenStateSnapshot(activeChatAgent, 'heartbeat_30s'); } }, 30000); +if (_snapInterval && typeof _snapInterval.unref === 'function') _snapInterval.unref(); function renderChatMessages(forceScroll = false) { if (!chatMessagesEl || !activeChatAgent) return; @@ -4591,9 +4592,18 @@ function setupChatEvents() { }); }; - if (SpeechRecognition) { + const getOrCreateSpeechRecognizer = () => { + const SpeechRecognitionClass = window.SpeechRecognition || window.webkitSpeechRecognition; + if (!SpeechRecognitionClass) { + return null; + } + + if (speechRecognizer) { + return speechRecognizer; + } + try { - speechRecognizer = new SpeechRecognition(); + speechRecognizer = new SpeechRecognitionClass(); speechRecognizer.lang = 'pt-BR'; speechRecognizer.continuous = true; speechRecognizer.interimResults = true; @@ -4632,13 +4642,16 @@ function setupChatEvents() { return; } stopRecordingUI(); - // Se o serviço do Google não estiver integrado no WebView, faz fallback para gravação direta de áudio - if (err.error === 'service-not-allowed' || err.error === 'not-allowed' || err.error === 'network' || err.error === 'audio-capture') { - console.log('[Voice] Alternando para gravação direta de áudio...'); - speechRecognizer = null; - startAudioRecording(); + + // Feedback claro e contextual sem anular a instância do recognizer e sem cair silenciosamente para gravação física + 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(`Voz: ${err.error}`, 'warning'); + showToast(`Reconhecimento de fala: ${err.error}`, 'warning'); } }; @@ -4659,11 +4672,16 @@ function setupChatEvents() { } stopRecordingUI(); }; + + return speechRecognizer; } catch (err) { console.warn('[Voice] Falha ao instanciar SpeechRecognition:', err); - speechRecognizer = null; + return null; } - } + }; + + // Inicializa previamente se o navegador tiver suporte + getOrCreateSpeechRecognizer(); btnVoice.addEventListener('click', (e) => { e.preventDefault(); @@ -4674,16 +4692,28 @@ function setupChatEvents() { voiceAccumulatedTranscript = ''; voiceSessionFinal = ''; - if (speechRecognizer) { + const recognizer = getOrCreateSpeechRecognizer(); + if (!recognizer) { + showToast('Reconhecimento de fala não suportado neste navegador.', 'error'); + return; + } + + try { + recognizer.start(); + } catch (err) { + console.warn('[Voice] Erro ao iniciar recognizer, tentando recuperar estado:', err); try { - speechRecognizer.start(); - } catch (err) { - console.warn('[Voice] Falha ao iniciar reconhecimento, caindo para gravação:', err); - speechRecognizer = null; - startAudioRecording(); - } - } else { - startAudioRecording(); + 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(); @@ -5245,7 +5275,7 @@ window.closeVersionModal = closeVersionModal; window.fetchVersionInfo = fetchVersionInfo; function initOtaChecker() { - setInterval(async () => { + 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:'; @@ -5266,4 +5296,5 @@ function initOtaChecker() { // Ignora erro de rede temporário } }, 30000); + if (_otaInterval && typeof _otaInterval.unref === 'function') _otaInterval.unref(); } diff --git a/public/bundles/bundle-1.0.26.zip b/public/bundles/bundle-1.0.26.zip index 0129cce..968a026 100644 Binary files a/public/bundles/bundle-1.0.26.zip and b/public/bundles/bundle-1.0.26.zip differ diff --git a/public/bundles/bundle-latest.zip b/public/bundles/bundle-latest.zip index 0129cce..968a026 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 f1df318..89dff17 100644 --- a/public/bundles/manifest.json +++ b/public/bundles/manifest.json @@ -1,9 +1,9 @@ { "version": "1.0.26", - "buildId": "ce540d0d", - "releasedAt": "2026-11-21T17:41:31.996Z", + "buildId": "31fb927c", + "releasedAt": "2026-11-21T19:26:36.703Z", "bundleUrl": "/bundles/bundle-1.0.26.zip", "latestUrl": "/bundles/bundle-latest.zip", - "checksum": "93e2a2a6bdaca95d3c2b80a19e35ce02c89a8b2e3c7eb31a9d44d64e2bd81c29", - "sizeBytes": 67600 + "checksum": "1a997a4f1238ef0177eb69e3d35d60c3e8a34891c1caf1c86cc63e224698d06f", + "sizeBytes": 67845 } \ No newline at end of file diff --git a/test/file-transfer.test.js b/test/file-transfer.test.js index 553de60..d7969ff 100644 --- a/test/file-transfer.test.js +++ b/test/file-transfer.test.js @@ -330,4 +330,9 @@ test('Frontend - extractFilePaths, renderFileChips e modais de preview devem fun // 5. Fechar modal closeFilePreviewModal(); assert.equal(modal.style.display, 'none'); + + dom.window.close(); + delete global.window; + delete global.document; + delete global.WebSocket; }); diff --git a/test/frontend-app.test.js b/test/frontend-app.test.js index 24cdbcf..a1ebfa8 100644 --- a/test/frontend-app.test.js +++ b/test/frontend-app.test.js @@ -1343,6 +1343,49 @@ Também verificamos running command e compiling no buffer. assert.strictEqual(chatInput.value, 'Olá agente, execute os testes e gere o relatório', 'Texto final deve ser trim() sem espaços sobrando'); }); + test('20. Resiliência do Ditado por Voz — Erros Transitórios (Network, Service-Not-Allowed) Preservam a Instância e Permitem Nova Tentativa', async () => { + const btnVoice = document.getElementById('btn-voice'); + const recognizer = window.SpeechRecognition.instance; + + assert.ok(btnVoice, 'Botão de microfone deve existir'); + assert.ok(recognizer, 'Instância de recognizer deve existir'); + + // 1. Inicia gravação + btnVoice.click(); + assert.strictEqual(btnVoice.classList.contains('recording'), true, 'Microfone deve estar ativo'); + assert.strictEqual(recognizer.started, true, 'Recognizer deve estar iniciado'); + + // 2. Simula erro de rede (serviço do Google falhou temporariamente) + recognizer.onerror({ error: 'network' }); + assert.strictEqual(btnVoice.classList.contains('recording'), false, 'UI deve parar modo de gravação após erro'); + + // 3. Verifica se toast de aviso foi exibido + const toast = document.getElementById('app-toast'); + assert.ok(toast && toast.textContent.includes('Falha de conexão com o serviço de voz'), 'Toast de erro de rede deve ser exibido'); + + // 4. Garante que NÃO houve fallback invisível para anexo de áudio + const attachmentPreviewBar = document.getElementById('attachment-preview-bar'); + assert.strictEqual(attachmentPreviewBar.style.display, 'none', 'Não deve criar anexo de áudio furtivo'); + + // 5. Tenta iniciar novamente (quando conexão restabelece) + btnVoice.click(); + assert.strictEqual(btnVoice.classList.contains('recording'), true, 'Microfone deve conseguir iniciar novamente sem ser anulado'); + assert.strictEqual(recognizer.started, true, 'Recognizer continua funcional para novas tentativas'); + + // 6. Simula erro service-not-allowed (permissão ou WebView temporário) + recognizer.onerror({ error: 'service-not-allowed' }); + assert.strictEqual(btnVoice.classList.contains('recording'), false, 'UI deve parar modo de gravação após erro de serviço'); + assert.ok(toast && toast.textContent.includes('Permissão de microfone/fala não concedida'), 'Toast de permissão deve ser exibido'); + + // 7. Nova tentativa subsequente ainda deve ser possível + btnVoice.click(); + assert.strictEqual(btnVoice.classList.contains('recording'), true, 'Deve poder tentar novamente após erro de permissão'); + + // 8. Encerra voluntariamente + btnVoice.click(); + assert.strictEqual(btnVoice.classList.contains('recording'), false); + }); + test('9. Sincronização Determinística de Terminal e Telemetria de Estado de Tela', async () => { // 1. Autentica previamente document.getElementById('pin-input').value = '712000';