diff --git a/package-lock.json b/package-lock.json index 6773216..775ab4d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "maestri-remote-agent", - "version": "1.0.26", + "version": "1.0.27", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "maestri-remote-agent", - "version": "1.0.26", + "version": "1.0.27", "dependencies": { "@capacitor/push-notifications": "^6.0.2", "pg": "^8.23.1", diff --git a/public/app.js b/public/app.js index 952d6e4..32f8f93 100644 --- a/public/app.js +++ b/public/app.js @@ -4619,20 +4619,31 @@ 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'); + btnVoice.removeAttribute('aria-pressed'); 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) {} } @@ -4646,6 +4657,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'); @@ -4659,7 +4721,9 @@ function setupChatEvents() { navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => { voiceActiveStream = stream; isRecording = true; + isVoiceExplicitlyStopped = false; btnVoice.classList.add('recording'); + btnVoice.setAttribute('aria-pressed', 'true'); if (chatInput) chatInput.placeholder = 'Gravando áudio... Toque no mic para finalizar'; showToast('Gravando áudio... Fale e toque no microfone para enviar.', 'info'); @@ -4752,6 +4816,7 @@ function setupChatEvents() { isRecording = true; isVoiceExplicitlyStopped = false; btnVoice.classList.add('recording'); + btnVoice.setAttribute('aria-pressed', 'true'); if (chatInput) chatInput.placeholder = 'Ouvindo... Fale à vontade (toque no mic para encerrar)'; showToast('Ditado contínuo ativado. Toque no microfone para concluir.', 'info'); }; @@ -4775,41 +4840,35 @@ function setupChatEvents() { 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(); }; @@ -4835,7 +4894,7 @@ function setupChatEvents() { const recognizer = getOrCreateSpeechRecognizer(); if (!recognizer) { - showToast('Reconhecimento de fala não suportado neste navegador.', 'error'); + startAudioRecording(); return; } diff --git a/public/bundles/bundle-1.0.27.zip b/public/bundles/bundle-1.0.27.zip index a4633da..1118821 100644 Binary files a/public/bundles/bundle-1.0.27.zip and b/public/bundles/bundle-1.0.27.zip differ diff --git a/public/bundles/bundle-latest.zip b/public/bundles/bundle-latest.zip index a4633da..1118821 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 e7fb42d..98585fe 100644 --- a/public/bundles/manifest.json +++ b/public/bundles/manifest.json @@ -1,9 +1,9 @@ { "version": "1.0.27", - "buildId": "49785205", - "releasedAt": "2026-11-21T19:43:00.809Z", + "buildId": "5181769b", + "releasedAt": "2026-11-21T20:13:48.591Z", "bundleUrl": "/bundles/bundle-1.0.27.zip", "latestUrl": "/bundles/bundle-latest.zip", - "checksum": "1be6eda404c2600d5156e9a66f9eaae737e9f9a3909fe07f1ccc3384c2e04c7d", - "sizeBytes": 69527 + "checksum": "00b871aa4e720f78156263527c325a6fb941e9e145ecfbbd3edb852595441690", + "sizeBytes": 70574 } \ No newline at end of file diff --git a/public/index.html b/public/index.html index 7a3b780..0e84f08 100644 --- a/public/index.html +++ b/public/index.html @@ -291,7 +291,7 @@
Terminal Maestri Conectado
-
+
- +
diff --git a/public/style.css b/public/style.css index 9575deb..7ad0441 100644 --- a/public/style.css +++ b/public/style.css @@ -865,6 +865,26 @@ main { justify-content: space-between; align-items: center; margin-bottom: 0.75rem; + padding-right: max(0.25rem, env(safe-area-inset-right, 0px)); +} + +.modal-header .btn-icon { + margin-right: max(0.15rem, env(safe-area-inset-right, 0px)); + border-radius: 50%; + width: 38px; + height: 38px; + min-width: 38px; + min-height: 38px; + background: rgba(255, 255, 255, 0.06); + display: inline-flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; +} + +.modal-header .btn-icon:hover { + background: rgba(239, 68, 68, 0.2); + color: #f87171; } .modal-header h3 { @@ -996,7 +1016,9 @@ main { display: flex; flex-direction: column; justify-content: flex-end; - padding-top: max(1.2rem, calc(0.5rem + env(safe-area-inset-top, 0px))); + padding-top: max(1.5rem, calc(0.75rem + env(safe-area-inset-top, 0px))); + padding-left: env(safe-area-inset-left, 0px); + padding-right: env(safe-area-inset-right, 0px); } .chat-backdrop { @@ -1023,19 +1045,108 @@ main { } .chat-header { - padding: 0.85rem 1rem; + padding-top: max(0.85rem, calc(0.5rem + env(safe-area-inset-top, 0px))); + padding-bottom: 0.85rem; + padding-left: max(1rem, calc(0.75rem + env(safe-area-inset-left, 0px))); + padding-right: max(1.25rem, calc(1rem + env(safe-area-inset-right, 0px))); border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; background: rgba(10, 15, 29, 0.6); flex-shrink: 0; + gap: 0.5rem; } .chat-agent-info { display: flex; align-items: center; gap: 0.6rem; + min-width: 0; + flex: 1 1 auto; + overflow: hidden; +} + +.chat-agent-info > div { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.chat-header-actions { + display: flex; + align-items: center; + gap: 0.35rem; + flex-shrink: 0; + margin-right: max(0.25rem, env(safe-area-inset-right, 0px)); +} + +#btn-close-chat, +.btn-close-chat { + margin-left: 0.35rem; + margin-right: max(0.35rem, calc(0.2rem + env(safe-area-inset-right, 0px))); + flex-shrink: 0; + border-radius: 50%; + width: 40px; + height: 40px; + min-width: 40px; + min-height: 40px; + display: inline-flex; + align-items: center; + justify-content: center; + background: rgba(255, 255, 255, 0.08); + border: 1px solid rgba(255, 255, 255, 0.12); + color: var(--text-secondary); + font-size: 1.5rem; + line-height: 1; + cursor: pointer; + touch-action: manipulation; + z-index: 30; + transition: all 0.2s ease; +} + +#btn-close-chat:hover, +#btn-close-chat:focus, +.btn-close-chat:hover, +.btn-close-chat:focus { + background: rgba(239, 68, 68, 0.2); + color: #f87171; + border-color: rgba(239, 68, 68, 0.4); +} + +#btn-close-chat:active, +.btn-close-chat:active { + transform: scale(0.92); + background: rgba(239, 68, 68, 0.3); +} + +@media (max-width: 480px) { + .chat-header { + padding-left: max(0.75rem, calc(0.5rem + env(safe-area-inset-left, 0px))); + padding-right: max(1rem, calc(0.75rem + env(safe-area-inset-right, 0px))); + gap: 0.35rem; + } + .chat-header-actions { + gap: 0.2rem; + margin-right: max(0.2rem, env(safe-area-inset-right, 0px)); + } + .chat-header-actions .btn-icon:not(.btn-close-chat) { + min-width: 36px; + min-height: 36px; + padding: 0.35rem; + font-size: 0.95rem; + } + #btn-close-chat, + .btn-close-chat { + width: 38px; + height: 38px; + min-width: 38px; + min-height: 38px; + font-size: 1.4rem; + margin-left: 0.25rem; + margin-right: max(0.35rem, calc(0.2rem + env(safe-area-inset-right, 0px))); + } } .chat-messages { diff --git a/test/frontend-app.test.js b/test/frontend-app.test.js index a1ebfa8..1ce6fcc 100644 --- a/test/frontend-app.test.js +++ b/test/frontend-app.test.js @@ -1386,6 +1386,44 @@ Também verificamos running command e compiling no buffer. assert.strictEqual(btnVoice.classList.contains('recording'), false); }); + test('21. Resiliência da Gravação contra Notificações, Perda de Foco e Enquadramento do Botão de Fechar', async () => { + // 1. Valida o enquadramento do botão de fechar do chat (#btn-close-chat) + const btnCloseChat = document.getElementById('btn-close-chat'); + assert.ok(btnCloseChat, 'Botão #btn-close-chat deve existir no DOM'); + assert.ok(btnCloseChat.classList.contains('btn-close-chat'), 'Botão de fechar deve possuir a classe .btn-close-chat'); + assert.strictEqual(btnCloseChat.getAttribute('aria-label'), 'Fechar Chat'); + + // 2. Inicia gravação de voz + const btnVoice = document.getElementById('btn-voice'); + const recognizer = window.SpeechRecognition.instance; + assert.ok(btnVoice, 'Botão de voz deve existir'); + assert.ok(recognizer, 'Recognizer deve existir'); + + btnVoice.click(); + assert.strictEqual(btnVoice.classList.contains('recording'), true, 'Microfone deve estar gravando'); + assert.strictEqual(btnVoice.getAttribute('aria-pressed'), 'true'); + + // 3. Simula chegada de notificação no celular emitindo erro audio-capture + recognizer.onerror({ error: 'audio-capture' }); + assert.strictEqual(btnVoice.classList.contains('recording'), true, 'Notificação/audio-capture NÃO deve parar a gravação'); + + // 4. Simula interrupção transitória por perda de foco (notificação shade / banner) emitindo aborted + recognizer.onerror({ error: 'aborted' }); + assert.strictEqual(btnVoice.classList.contains('recording'), true, 'Perda de foco temporária (aborted) NÃO deve parar a gravação'); + + // 5. Simula onend gerado pelo sistema durante a notificação + recognizer.onend(); + assert.strictEqual(btnVoice.classList.contains('recording'), true, 'onend transitório durante notificação NÃO deve desativar a gravação'); + + // 6. Simula retorno do foco (window focus / visibility visible) + window.dispatchEvent(new window.Event('focus')); + assert.strictEqual(btnVoice.classList.contains('recording'), true, 'Gravação permanece ativa após retomada de foco'); + + // 7. A gravação SÓ encerra estritamente quando o usuário toca novamente no botão + btnVoice.click(); + assert.strictEqual(btnVoice.classList.contains('recording'), false, 'Gravação deve parar estritamente no clique voluntário do usuário'); + }); + test('9. Sincronização Determinística de Terminal e Telemetria de Estado de Tela', async () => { // 1. Autentica previamente document.getElementById('pin-input').value = '712000';