feat(chat): implementar gravacao e envio de videos no mobile via relay para a estacao

This commit is contained in:
Winícius 2026-11-21 22:06:50 -03:00
parent 76defabc64
commit 59a8871dab
14 changed files with 384 additions and 17 deletions

View File

@ -52,6 +52,7 @@
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" android:maxSdkVersion="32" />
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<!-- Notificações em Background, Wake Lock e Vibração -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
@ -61,4 +62,5 @@
<uses-feature android:name="android.hardware.microphone" android:required="false" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
</manifest>

View File

@ -0,0 +1,62 @@
# Spec: Gravação e Envio de Vídeos no Maestri Remote Mobile via Relay para a Estação
**Work Item:** `0-video-recording-relay` (Projeto autônomo sem Azure Boards)
**Criada em:** 2026-11-21 22:00
**Status:** 4/4 tasks concluídas.
**Baseline:** `maestri-remote@76defab` (`feat/video-recording-relay`, 2026-11-21)
**Complexidade:** M (3 pts brutos: 1 camada Frontend + 1 camada Gateway/Relay + Permissões Android e Testes E2E)
**Estimativa (h):** 2.0h
---
## Estado atual
2026-11-21 22:05 · Builder · change concluída — Suporte a gravação de vídeos via câmera nativa e seleção da galeria implementado no menu flutuante (+); pré-visualização interativa com badge 🎬, tamanho e remoção antes do envio; player de vídeo HTML5 inline no histórico de mensagens; sanitização e persistência segura de vídeos em .maestri-remote/uploads/ com extensão garantida (.mp4/.webm) e injeção formatada no terminal da estação; permissão READ_MEDIA_VIDEO e autofocus no AndroidManifest.xml; 149 testes automatizados passando com 100% de sucesso; novo bundle OTA gerado (build ID c9c26243) e pacote maestri-agent atualizado.
Papel que retoma: N/A (Entrega finalizada)
- Dispensas do usuário:
- Não há gestão por Azure Boards.
- Dispensa formal de Code Reviewer para fluxo direto autônomo de Builder.
---
## Capabilities Afetadas
- `docs/capabilities/maestri-remote.md`: Suporte a captura e envio de vídeos no chat do app móvel com persistência no gateway local.
---
## Skills Aplicáveis
- `.context/skills/command-line-environment/SKILL.md`: Manipulação de arquivos, empacotamento e comandos locais.
- `.context/skills/ota-k3s-publishing/SKILL.md`: Workflow de build de bundle OTA e empacotamento do daemon do agente.
---
## Contexto e Descrição do Problema
Atualmente, o **Maestri Remote** suporta envio de fotos (tiradas via câmera ou selecionadas da galeria), documentos, logs e mensagens de áudio com transcrição de voz. No entanto, o operador móvel frequentemente precisa demonstrar problemas visuais dinâmicos, bugs em movimento, comportamento de telas ou gravar vídeos curtos de inspeção na estação de trabalho para que o agente possa analisar o arquivo.
Esta change adiciona o suporte completo e de ponta a ponta à gravação e envio de vídeos no app móvel:
1. No menu flutuante de anexos (+), opções de gravar vídeo com a câmera móvel e selecionar vídeos existentes (.mp4, .webm, etc.).
2. Barra de pré-visualização interativa exibindo badge de vídeo, nome e tamanho formatado antes do envio, permitindo remover ou confirmar.
3. Roteamento seguro do payload via WebSocket no Relay server até o gateway conectado.
4. Persistência do vídeo em `.maestri-remote/uploads/` com sanitização rigorosa de nome e extensão no Gateway e injeção formatada no terminal da estação (`[Anexo recebido do operador: <caminho>] <mensagem>`).
5. Permissões Android atualizadas no `AndroidManifest.xml` (`READ_MEDIA_VIDEO`, câmera).
6. Cobertura completa de testes automatizados com 100% de sucesso.
---
## Tasks
- [x] 1. Declarar permissões de vídeo e hardware no AndroidManifest.xml `[2026-11-21 22:00]`
- [x] 2. Implementar opções de vídeo no frontend (index.html, style.css e app.js) com preview e player `[2026-11-21 22:02]`
- [x] 3. Implementar sanitização e persistência de vídeos no Gateway e tráfego no Relay `[2026-11-21 22:03]`
- [x] 4. Cobrir com testes automatizados (unitários e integração), gerar bundle OTA e sincronizar `[2026-11-21 22:05]`
---
## Critérios de Aceite
1. O menu de anexos (+) deve conter as opções "Gravar Vídeo (Câmera)" e "Galeria de Vídeos".
2. Os inputs HTML5 devem utilizar atributos adequados (`capture="environment"` para gravação direta e `accept="video/mp4,video/webm,video/quicktime,video/*"` para seleção).
3. A barra de preview deve apresentar thumbnail/indicador de vídeo, nome do arquivo e tamanho em bytes antes do envio.
4. O Gateway deve persistir o arquivo em `.maestri-remote/uploads/` com extensão sanitizada e injetar a mensagem formatada no terminal.
5. Toda a suíte de testes (`npm test`) deve passar com 100% de sucesso.
6. O bundle OTA deve ser empacotado (`npm run build:bundle`).

4
package-lock.json generated
View File

@ -1,12 +1,12 @@
{
"name": "maestri-remote-agent",
"version": "1.0.28",
"version": "1.0.30",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "maestri-remote-agent",
"version": "1.0.28",
"version": "1.0.30",
"dependencies": {
"@capacitor/push-notifications": "^6.0.2",
"pg": "^8.23.1",

View File

@ -373,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');
@ -2443,6 +2447,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' ||
@ -2461,6 +2466,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';
@ -4060,11 +4083,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 = `<img src="${imageItems[0].dataUrl}" alt="${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 => {
@ -4077,6 +4101,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 = `
<video controls playsinline preload="metadata" style="max-width:100%;max-height:240px;border-radius:8px;background:#000;display:block;" src="${vAtt.dataUrl}"></video>
<div style="font-size:0.75rem;color:#94a3b8;margin-top:2px;">🎬 ${escapeHtml(vAtt.name || 'video')} (${formatBytes(vAtt.size || 0)})</div>
`;
videoContainer.appendChild(vWrapper);
});
attachBox.appendChild(videoContainer);
}
if (fileItems.length > 0) {
const fileListEl = document.createElement('div');
fileListEl.className = 'chat-attachment-file-list';
@ -4309,6 +4349,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) {
@ -4473,6 +4515,8 @@ function setupChatEvents() {
if (attachmentThumbWrapper && currentAttachment) {
if (currentAttachment.isImage && currentAttachment.dataUrl) {
attachmentThumbWrapper.innerHTML = `<img src="${currentAttachment.dataUrl}" alt="Thumbnail" />`;
} else if (currentAttachment.isVideo) {
attachmentThumbWrapper.innerHTML = `<span style="font-size:22px;display:inline-flex;align-items:center;justify-content:center;width:100%;height:100%;">🎬</span>`;
} else {
attachmentThumbWrapper.innerHTML = `<svg style="width:20px;height:20px;color:#38bdf8" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>`;
}
@ -4490,6 +4534,8 @@ function setupChatEvents() {
thumb.className = 'attachment-chip-thumb';
if (att.isImage && att.dataUrl) {
thumb.innerHTML = `<img src="${att.dataUrl}" alt="${escapeHtml(att.name)}" />`;
} else if (att.isVideo) {
thumb.innerHTML = `<span style="font-size:14px;display:inline-flex;align-items:center;justify-content:center;width:100%;height:100%;">🎬</span>`;
} else {
thumb.innerHTML = `<svg style="width:14px;height:14px;color:#38bdf8" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>`;
}
@ -4568,13 +4614,28 @@ function setupChatEvents() {
}
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
});
@ -4592,7 +4653,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();
@ -4620,6 +4681,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);
@ -4646,6 +4721,8 @@ function setupChatEvents() {
bindFileInput(chatCameraInput);
bindFileInput(chatGalleryInput);
bindFileInput(chatVideoRecordInput);
bindFileInput(chatVideoInput);
bindFileInput(chatFileInput);
if (btnRemoveAttachment) {

Binary file not shown.

Binary file not shown.

View File

@ -1,9 +1,9 @@
{
"version": "1.0.30",
"buildId": "1a30dc06",
"releasedAt": "2026-11-22T00:12:47.004Z",
"buildId": "c9c26243",
"releasedAt": "2026-11-22T01:05:18.116Z",
"bundleUrl": "/bundles/bundle-1.0.30.zip",
"latestUrl": "/bundles/bundle-latest.zip",
"checksum": "d6c15fa467d18257241f3aa2544b26ee9356ddf433ce556c912b9513ff99b113",
"sizeBytes": 71856
"checksum": "7ff3e869423692aa19843ebd4c237fe2fcd6ef5b238fe993420c34ed9b5026c2",
"sizeBytes": 73028
}

View File

@ -368,7 +368,7 @@
<!-- Backdrop para fechar o menu de anexo flutuante -->
<div id="attach-backdrop" class="attach-backdrop" style="display: none;"></div>
<!-- Menu Flutuante de Ações de Anexo (Câmera / Galeria / Arquivos / Downloads) -->
<!-- Menu Flutuante de Ações de Anexo (Câmera / Galeria / Vídeos / Arquivos / Downloads) -->
<div id="attach-menu" class="attach-menu-popover" style="display: none;">
<button type="button" class="attach-menu-item" id="btn-attach-camera">
<span class="attach-item-icon camera">
@ -387,6 +387,23 @@
</span>
<span class="attach-item-label">Galeria de Fotos</span>
</button>
<button type="button" class="attach-menu-item" id="btn-attach-video-record">
<span class="attach-item-icon video-record">
<svg style="width:18px;height:18px" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
</span>
<span class="attach-item-label">Gravar Vídeo (Câmera)</span>
</button>
<button type="button" class="attach-menu-item" id="btn-attach-video-gallery">
<span class="attach-item-icon video-gallery">
<svg style="width:18px;height:18px" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</span>
<span class="attach-item-label">Galeria de Vídeos</span>
</button>
<button type="button" class="attach-menu-item" id="btn-attach-file">
<span class="attach-item-icon file">
<svg style="width:18px;height:18px" fill="none" viewBox="0 0 24 24" stroke="currentColor">
@ -420,10 +437,12 @@
<!-- Barra de Input com Anexo, Entrada e Ação Dinâmica (Voz / Envio) -->
<form class="chat-input-bar" id="chat-form">
<!-- Inputs Especializados para Câmera Direta, Galeria de Fotos e Arquivos Gerais -->
<!-- Inputs Especializados para Câmera Direta, Galeria de Fotos, Gravação de Vídeo, Galeria de Vídeos e Arquivos Gerais -->
<input type="file" id="chat-camera-input" style="display: none;" accept="image/*" capture="environment">
<input type="file" id="chat-gallery-input" style="display: none;" accept="image/*" multiple>
<input type="file" id="chat-file-input" style="display: none;" accept=".pdf,.txt,.log,.json,.csv,.md,audio/*" multiple>
<input type="file" id="chat-video-record-input" style="display: none;" accept="video/*" capture="environment">
<input type="file" id="chat-video-input" style="display: none;" accept="video/mp4,video/webm,video/quicktime,video/*" multiple>
<input type="file" id="chat-file-input" style="display: none;" accept=".pdf,.txt,.log,.json,.csv,.md,audio/*,video/*" multiple>
<button type="button" id="btn-attach" class="btn-input-action" aria-label="Anexar foto ou arquivo" title="Anexar foto ou arquivo">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" style="width:20px;height:20px">

Binary file not shown.

View File

@ -1700,6 +1700,16 @@ main {
color: #c084fc;
}
.attach-item-icon.video-record {
background: rgba(239, 68, 68, 0.15);
color: #f87171;
}
.attach-item-icon.video-gallery {
background: rgba(245, 158, 11, 0.15);
color: #fbbf24;
}
.attach-item-icon.file {
background: rgba(34, 197, 94, 0.15);
color: #4ade80;

View File

@ -660,7 +660,26 @@ export class GatewayDaemon {
}
const rawName = attachment.name || 'anexo.bin';
const safeBaseName = path.basename(rawName).replace(/[^a-zA-Z0-9._-]/g, '_');
let safeBaseName = path.basename(rawName).replace(/[^a-zA-Z0-9._-]/g, '_');
// Sanitização e garantia de extensão adequada para vídeos e multimídia
let ext = path.extname(safeBaseName).toLowerCase();
if (!ext || ext === '.') {
const mime = (attachment.mimeType || '').toLowerCase();
if (mime.includes('mp4')) ext = '.mp4';
else if (mime.includes('webm')) ext = '.webm';
else if (mime.includes('quicktime') || mime.includes('mov')) ext = '.mov';
else if (mime.includes('mkv')) ext = '.mkv';
else if (mime.includes('ogg') || mime.includes('ogv')) ext = '.ogv';
else if (mime.includes('jpeg') || mime.includes('jpg')) ext = '.jpg';
else if (mime.includes('png')) ext = '.png';
else if (mime.includes('webp')) ext = '.webp';
else if (mime.includes('pdf')) ext = '.pdf';
else ext = '.bin';
safeBaseName = safeBaseName.replace(/\.+$/, '') + ext;
}
const fileName = `${Date.now()}-${safeBaseName}`;
const filePath = path.join(uploadsDir, fileName);

View File

@ -444,11 +444,16 @@ describe('Suite de Testes Automatizados E2E do Frontend (Maestri Remote)', () =>
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 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 chatFileInput = document.getElementById('chat-file-input');
const attachmentPreviewBar = document.getElementById('attachment-preview-bar');
const attachmentThumbWrapper = document.getElementById('attachment-thumb-wrapper');
const attachmentName = document.getElementById('attachment-name');
const attachmentSize = document.getElementById('attachment-size');
const btnRemoveAttachment = document.getElementById('btn-remove-attachment');
@ -461,6 +466,8 @@ describe('Suite de Testes Automatizados E2E do Frontend (Maestri Remote)', () =>
assert.ok(attachBackdrop, 'Backdrop de anexo (#attach-backdrop) deve existir');
assert.ok(btnAttachCamera, 'Opção de Câmera (#btn-attach-camera) deve existir');
assert.ok(btnAttachGallery, 'Opção de Galeria (#btn-attach-gallery) deve existir');
assert.ok(btnAttachVideoRecord, 'Opção de Gravação de Vídeo (#btn-attach-video-record) deve existir');
assert.ok(btnAttachVideoGallery, 'Opção de Galeria de Vídeos (#btn-attach-video-gallery) deve existir');
assert.ok(btnAttachFile, 'Opção de Arquivos (#btn-attach-file) deve existir');
// Validação dos atributos HTML5 de captura móvel direta
@ -472,6 +479,14 @@ describe('Suite de Testes Automatizados E2E do Frontend (Maestri Remote)', () =>
assert.strictEqual(chatGalleryInput.getAttribute('accept'), 'image/*', 'Input galeria deve restringir a image/*');
assert.strictEqual(chatGalleryInput.hasAttribute('multiple'), true, 'Input galeria deve conter atributo multiple');
assert.ok(chatVideoRecordInput, 'Input gravação de vídeo oculto deve existir');
assert.strictEqual(chatVideoRecordInput.getAttribute('capture'), 'environment', 'Input vídeo record deve conter capture="environment"');
assert.strictEqual(chatVideoRecordInput.getAttribute('accept'), 'video/*', 'Input vídeo record deve restringir a video/*');
assert.ok(chatVideoInput, 'Input galeria de vídeo oculto deve existir');
assert.ok(chatVideoInput.getAttribute('accept').includes('video/'), 'Input vídeo galeria deve aceitar tipos de vídeo');
assert.strictEqual(chatVideoInput.hasAttribute('multiple'), true, 'Input vídeo galeria deve conter atributo multiple');
assert.ok(chatFileInput, 'Input file geral oculto deve existir');
assert.strictEqual(chatFileInput.hasAttribute('multiple'), true, 'Input arquivos deve conter atributo multiple');
@ -540,6 +555,53 @@ describe('Suite de Testes Automatizados E2E do Frontend (Maestri Remote)', () =>
btnRemoveAttachment.click();
assert.strictEqual(attachmentPreviewBar.style.display, 'none', 'Botão remover deve limpar anexo da galeria');
// 6.1. Testa gravação de vídeo via Câmera
btnAttach.click();
let videoRecordInputClicked = false;
chatVideoRecordInput.click = () => { videoRecordInputClicked = true; };
btnAttachVideoRecord.click();
assert.strictEqual(videoRecordInputClicked, true, 'Deve ter disparado clique no chatVideoRecordInput');
const recordedVideo = new window.File(['video recorded stream bytes'], 'gravacao_painel.mp4', { type: 'video/mp4' });
Object.defineProperty(chatVideoRecordInput, 'files', {
value: [recordedVideo],
writable: true
});
chatVideoRecordInput.dispatchEvent(new window.Event('change'));
await new Promise(r => setTimeout(r, 60));
assert.strictEqual(attachmentPreviewBar.style.display, 'flex', 'Preview deve exibir vídeo gravado');
assert.ok(attachmentName.textContent.includes('gravacao_painel.mp4'));
assert.ok(attachmentThumbWrapper.innerHTML.includes('🎬'), 'Preview deve exibir ícone de vídeo');
btnRemoveAttachment.click();
assert.strictEqual(attachmentPreviewBar.style.display, 'none', 'Botão remover deve limpar vídeo gravado');
// 6.2. Testa seleção de vídeo via Galeria e envio no chat
btnAttach.click();
let videoGalleryInputClicked = false;
chatVideoInput.click = () => { videoGalleryInputClicked = true; };
btnAttachVideoGallery.click();
assert.strictEqual(videoGalleryInputClicked, true, 'Deve ter disparado clique no chatVideoInput');
const galleryVideo = new window.File(['video gallery demo bytes'], 'demonstracao.webm', { type: 'video/webm' });
Object.defineProperty(chatVideoInput, 'files', {
value: [galleryVideo],
writable: true
});
chatVideoInput.dispatchEvent(new window.Event('change'));
await new Promise(r => setTimeout(r, 60));
assert.strictEqual(attachmentPreviewBar.style.display, 'flex', 'Preview deve exibir vídeo selecionado da galeria');
chatInput.value = 'Vídeo de demonstração do problema';
chatForm.dispatchEvent(new window.Event('submit'));
const sendVideoMsg = sentWsMessages.find(m => m.type === 'CHAT_SEND' && m.attachment && m.attachment.name.includes('demonstracao'));
assert.ok(sendVideoMsg, 'Mensagem CHAT_SEND deve conter o vídeo enviado');
assert.strictEqual(sendVideoMsg.attachment.mimeType, 'video/webm');
assert.strictEqual(sendVideoMsg.message, 'Vídeo de demonstração do problema');
assert.strictEqual(attachmentPreviewBar.style.display, 'none', 'Preview deve fechar após envio de vídeo');
// 7. Testa seleção de múltiplos arquivos simultâneos e acúmulo entre fontes
const attachmentList = document.getElementById('attachment-list');
const multiPhoto1 = new window.File(['bytes foto 1'], 'foto1.jpg', { type: 'image/jpeg' });

View File

@ -94,6 +94,84 @@ test('GatewayDaemon deve salvar anexo e injetar path no prompt do askAgent', asy
}
});
test('GatewayDaemon deve salvar anexo de vídeo (.mp4 e .webm) com extensão sanitizada e injetar no prompt do askAgent', async () => {
const fs = await import('node:fs');
const mockAdapter = new MockAdapter();
const daemon = new GatewayDaemon({
adapter: mockAdapter
});
const videoBinary = Buffer.from('fake mp4 video bytes header');
const sampleBase64 = videoBinary.toString('base64');
let savedFile = null;
await daemon.handleRelayMessage({
type: 'CHAT_SEND',
chatId: 'chat-video-1',
agentName: 'TestAgent',
message: 'Assista a este vídeo do bug em execução',
attachment: {
name: 'bug_animacao:teste?.mp4',
mimeType: 'video/mp4',
size: videoBinary.length,
dataBase64: sampleBase64
}
});
assert.equal(mockAdapter.responses.length, 1);
assert.equal(mockAdapter.responses[0].agentName, 'TestAgent');
assert.ok(mockAdapter.responses[0].message.includes('[Anexo recebido do operador:'));
assert.ok(mockAdapter.responses[0].message.includes('Assista a este vídeo do bug em execução'));
const match = mockAdapter.responses[0].message.match(/\[Anexo recebido do operador: (.*?)\]/);
assert.ok(match, 'Deve ter injetado o path do vídeo');
savedFile = match[1];
assert.ok(savedFile.endsWith('.mp4'), 'Deve terminar com extensão .mp4');
assert.ok(!savedFile.includes(':') && !savedFile.includes('?'), 'Caracteres perigosos devem estar sanitizados');
assert.ok(fs.existsSync(savedFile), 'Arquivo de vídeo deve existir no diretório de uploads');
assert.deepEqual(fs.readFileSync(savedFile), videoBinary);
// Limpeza
if (savedFile && fs.existsSync(savedFile)) {
fs.unlinkSync(savedFile);
}
});
test('GatewayDaemon deve inferir extensão de vídeo a partir do mimeType quando nome vier sem extensão', async () => {
const fs = await import('node:fs');
const mockAdapter = new MockAdapter();
const daemon = new GatewayDaemon({
adapter: mockAdapter
});
const videoBinary = Buffer.from('webm binary stream');
let savedFile = null;
await daemon.handleRelayMessage({
type: 'CHAT_SEND',
chatId: 'chat-video-no-ext',
agentName: 'TestAgent',
message: 'Vídeo gravado sem extensão',
attachment: {
name: 'video_gravado_blob',
mimeType: 'video/webm',
size: videoBinary.length,
dataBase64: videoBinary.toString('base64')
}
});
const match = mockAdapter.responses[0].message.match(/\[Anexo recebido do operador: (.*?)\]/);
assert.ok(match, 'Deve ter injetado o path do anexo');
savedFile = match[1];
assert.ok(savedFile.endsWith('.webm'), 'Deve ter inferido extensão .webm');
assert.ok(fs.existsSync(savedFile), 'Arquivo deve existir');
// Limpeza
if (savedFile && fs.existsSync(savedFile)) {
fs.unlinkSync(savedFile);
}
});
test('GatewayDaemon deve salvar múltiplos anexos e injetar lista de paths no prompt do askAgent', async () => {
const fs = await import('node:fs');
const mockAdapter = new MockAdapter();

View File

@ -153,6 +153,44 @@ test('handleClientWsMessage deve rotear TERMINAL_RAW_INPUT com telemetria e devo
assert.equal(chatOffline.ok, false);
});
test('handleClientWsMessage deve rotear CHAT_SEND com anexo de vídeo para o gateway conectado', () => {
const manager = new SessionManager();
const clientWs = new MockSocket();
const gatewayWs = new MockSocket();
const mockTelemetry = { logEvent: () => {} };
manager.registerGateway('998877', gatewayWs);
manager.registerClient('998877', clientWs);
const videoMsg = {
type: 'CHAT_SEND',
chatId: 'chat-vid-relay',
agentName: 'BuilderAgent',
message: 'Segue o vídeo do teste',
attachment: {
name: 'teste_app.mp4',
mimeType: 'video/mp4',
size: 512,
dataBase64: 'AAAA...'
}
};
handleClientWsMessage({
ws: clientWs,
sessionPin: '998877',
msg: videoMsg,
sessionManager: manager,
telemetryService: mockTelemetry
});
assert.equal(gatewayWs.sent.length, 1);
const delivered = JSON.parse(gatewayWs.sent[0]);
assert.equal(delivered.type, 'CHAT_SEND');
assert.equal(delivered.agentName, 'BuilderAgent');
assert.equal(delivered.attachment.name, 'teste_app.mp4');
assert.equal(delivered.attachment.mimeType, 'video/mp4');
});
test('OtaService deve fornecer manifesto inicial de versão', () => {
const ota = new OtaService();
const manifest = ota.getManifest();