feat: suporte a download sob demanda de arquivos do terminal para o app mobile via WebSocket

This commit is contained in:
Winícius 2026-11-21 13:29:03 -03:00
parent 10f20efbd4
commit 10c11dfc2b
16 changed files with 1091 additions and 30 deletions

View File

@ -1,6 +1,7 @@
{
"package": "@aliare/sdlc-workflow",
"version": "0.1.259",
"modo": "embutido",
"updatedAt": "2026-11-21",
"agentsBlock": "745e6df551b8a03cdf7de86efcece2569568b5d5bf50ac6408cad55415304a2c",
"files": {

View File

@ -135,6 +135,19 @@ Para evitar perda de estado, piscamento de tela ou conexões zumbis (half-open)
- **Tolerância a Pausas e Auto-Reconexão:** Caso o motor de voz nativo do sistema operacional emita evento `onend` ou erro `no-speech` por inatividade durante pausas prolongadas enquanto a gravação permanecer ativa, a sessão é reiniciada de forma transparente mantendo o buffer acumulado.
- **Controle Manual Explícito:** A captura só encerra quando o operador toca novamente no botão de microfone (toggle de encerramento) ou envia a mensagem.
### 3.8. Download e Inspeção de Arquivos do Terminal Sob Demanda via WebSocket
Durante sessões de supervisão de agentes autônomos, os agentes frequentemente criam e citam arquivos em disco no host (prints de evidência gráfica, relatórios Markdown, arquivos de log, especificações ou pacotes compilados). O Maestri Remote disponibiliza transporte reverso sob demanda integrado via WebSocket:
- **Detecção Automática de Caminhos e Chips Interativos (`📄 <arquivo>`):** Qualquer caminho de arquivo referenciado nas respostas de agentes de IA ou nas saídas do terminal é identificado automaticamente por analisador léxico (`extractFilePaths`), gerando chips visuais clicáveis (`.btn-file-chip`) tanto nos balões de chat quanto no cartão de snapshot do terminal.
- **Roteamento Bidirecional Sob Demanda (`FILE_READ_REQ` e `FILE_READ_RESP`):** O toque em um chip dispara a requisição `FILE_READ_REQ` através do túnel WebSocket já autenticado. O Relay encaminha a mensagem à estação correspondente e recebe `FILE_READ_RESP` com o conteúdo codificado em Base64 e metadados completos (tamanho, MIME type detectado e nome original).
- **Sandbox Defensivo Estrito no Host:** O Gateway Daemon local valida rigorosamente o caminho solicitado (`path.normalize` e `path.relative`), garantindo que o arquivo resida estritamente dentro da raiz do workspace do projeto (`process.cwd()`) ou de `.maestri-remote/`. Qualquer tentativa de path traversal (`../`) ou leitura fora do escopo é barrada com recusa imediata de acesso.
- **Teto Rígido de Memória (20 MB):** Arquivos que excedam o limite defensivo de 20 MB são recusados no host com mensagem informativa, protegendo o consumo de memória do dispositivo móvel e do Relay.
- **Modal de Pré-Visualização e Download Responsivo (`#file-preview-modal`):**
- **Imagens (PNG, JPG, SVG, WebP, ICO):** Renderização direta em tag `<img>` adaptada à tela do smartphone com ajuste visual de proporção.
- **Código e Textos (Markdown, JSON, JS/TS, HTML, CSS, Logs, CSV, Scripts):** Decodificação em UTF-8 com renderização em bloco monoespaçado `<pre><code>` com rolagem bidirecional e botão dedicado "Copiar Texto".
- **Arquivos Binários e Pacotes (PDF, ZIP, APK):** Identificação visual com badge e metadados descritivos.
- **Ação de Salvar:** Botão "Salvar Arquivo" que aciona o download direto no armazenamento do dispositivo móvel (ou compartilhamento nativo no Android). (Change: `docs/changes/0-download-arquivos-terminal-app/spec.md`)
---
## 4. Mecanismo de Atualização Over-The-Air (Live OTA Bundles)

View File

@ -0,0 +1,25 @@
# Evidências de Validação: 0-download-arquivos-terminal-app
**Data:** 2026-11-21
**Change:** `docs/changes/0-download-arquivos-terminal-app/spec.md`
**Papel Executor:** Builder
## 1. Resumo das Evidências Coletadas
1. **Testes Unitários Automatizados (`test/file-transfer.test.js`):**
- Validação de transporte de arquivos sob demanda via `FILE_READ_REQ` e `FILE_READ_RESP`.
- Sandbox defensivo bloqueando escape de diretório (`../../../../etc/passwd`).
- Bloqueio de arquivos maiores que 20 MB.
- Detecção precisa de MIME types (imagens, markdown, JSON, scripts, binários).
- Roteamento e telemetria no Relay com tratamento de estação offline.
- JSDOM: Detecção léxica de caminhos (`extractFilePaths`), renderização de chips (`renderFileChips`) e modal de pré-visualização para imagens e códigos.
- Resultado: 100% dos testes aprovados.
2. **Esteira de Publicação OTA e Rollout K3s na Oracle VPS:**
- Build do bundle OTA `public/bundles/bundle-1.0.24.zip` (Build ID `5a3f32bc`).
- Compilação e push da imagem Docker multi-arch ARM64 `winicomw/maestri-remote-relay:latest`.
- Rollout restart executado no cluster K3s na Oracle VPS via Maestri Shell para o agente `SREOracleAgent`.
- Healthcheck validado em produção: `HTTP 200 {"status":"ok"}`.
- Endpoint de versão validado em produção: `{"version":"1.0.24","buildId":"5a3f32bc",...}`.
- Empacotamento do agente daemon `public/maestri-agent.zip` e sincronização local em `maestri-remote-dist`.
- Daemon local reiniciado com sucesso e pareado na sessão ativa.

View File

@ -0,0 +1,33 @@
=== MAESTRI REMOTE - DEPLOY & VALIDATION EVIDENCE ===
Date: 2026-11-21T16:25:43Z
Change: 0-download-arquivos-terminal-app
[1] OTA Bundle Build:
Arquivo: D:\Desenvolvimento\maestri-remote\public\bundles\bundle-1.0.24.zip (67263 bytes)
SHA-256: 6710730c8f71a8db1eef7fd4673a6633a2b590a4186ee7d500b4afb4b24bc00f
Build ID: 5a3f32bc
[2] Docker ARM64 Build & Push:
Platform: linux/arm64
Tag: winicomw/maestri-remote-relay:latest
Image Digest: sha256:1158f6d9b1252b75aabdc70a8ab621b55415d8d33aa624cfe25c9f2f34fa4f1f
Status: Push concluído no Docker Hub.
[3] K3s Rollout Restart via SREOracleAgent:
Comando: maestri ask "SREOracleAgent" "kubectl rollout restart deployment maestri-remote-relay -n maestri-remote"
Resultado:
deployment.apps/maestri-remote-relay restarted
deployment "maestri-remote-relay" successfully rolled out
Pod ativo: maestri-remote-relay-594d7d5bb-k7dcs (1/1 Running)
[4] Healthcheck & Version Validation:
GET https://remote.winicomw.ddnsfree.com/api/health
Response: {"status":"ok","timestamp":"2026-11-21T16:25:43.055Z"}
GET https://remote.winicomw.ddnsfree.com/api/version
Response: {"version":"1.0.24","buildId":"5a3f32bc","releasedAt":"2026-11-21T16:23:44.908Z","bundleUrl":"/bundles/bundle-1.0.24.zip","latestUrl":"/bundles/bundle-latest.zip","checksum":"6710730c8f71a8db1eef7fd4673a6633a2b590a4186ee7d500b4afb4b24bc00f","sizeBytes":67263}
[5] Daemon Package & Local Sync:
npm run build:agent -> public/maestri-agent.zip (33.3 KB)
Arquivos sincronizados com ../maestri-remote-dist
Daemon reiniciado e conectado em wss://remote.winicomw.ddnsfree.com/ws/gateway (Sessão 161818)

View File

@ -1,24 +1,19 @@
# Spec: Download de Arquivos do Terminal para o App Mobile via Relay
**Work Item:** N/A (Projeto Pessoal · Sem Azure Boards)
**Criada em:** 2026-11-21 13:05
**Status:** 0/4 tasks concluídas.
**Status:** 4/4 tasks concluídas.
**Baseline:** maestri-remote@fdc3988 (main, 2026-11-21)
**Complexidade:** P (2 pts — rotas/mensagens WS novas + camada dupla backend/frontend)
**Estimativa (h):** 5,0 h (por Task em `## Tasks`)
## Estado atual
2026-11-21 13:05 · Antigravity (Planner) · fdc3988 — Especificação técnica concluída a partir do manifesto de ideação e desenho da solução em SVG versionado. Pronta para implementação pelo Builder.
Papel que retoma: Builder (.context/agents/builder.md)
- Dispensas do usuário:
- Dispensa do papel de Code Reviewer e de Azure Boards (desenvolvedor único, autonomia máxima e esteira OTA/K3s direta).
- Decisões:
- Transporte sob demanda em Base64 através do WebSocket reverso existente (/ws/client e /ws/gateway).
- Detecção automática de referências a arquivos com chips clicáveis (`📄 <arquivo>`).
- Sandbox defensivo no host: somente arquivos no workspace (`process.cwd()`) ou em `.maestri-remote/`.
- Teto rígido de 20 MB por arquivo para segurança de memória do mobile e do Relay.
- Modal responsivo com preview para imagens (PNG, JPG, SVG, WebP), código/texto formatado com rolagem e download local no smartphone.
- Sessões em aberto:
- Antigravity bafca308-e939-4860-b296-3146d2d8a9a5 · 2026-11-21 13:05
2026-11-21 13:28 · Antigravity (Builder) — Implementação completa concluída e validada de ponta a ponta:
- Task 1 [BE]: Suporte a `FILE_READ_REQ` e `FILE_READ_RESP` com sandbox defensivo no host (`process.cwd()`), limite de 20 MB e codificação Base64 no Gateway Daemon e Relay Server implementado e testado.
- Task 2 [FRONT]: Detecção automática de caminhos de arquivos (`extractFilePaths`), chips clicáveis `📄 <arquivo>` (`renderFileChips`), evento WS de download e modal responsivo de pré-visualização/salvamento (imagens, código formatado com botão "Copiar Texto" e download no smartphone) implementados em `public/app.js`, `public/index.html` e `public/style.css`.
- Task 3 [DEPLOY]: Esteira autônoma OTA e K3s concluída: bundle OTA v1.0.24 gerado (buildId `5a3f32bc`), Docker ARM64 compilado e enviado ao Docker Hub, rollout no cluster K3s na Oracle VPS executado via Maestri Shell para o agente `SREOracleAgent` e validado com HTTP 200 em `/api/health` e `/api/version`, daemon local empacotado (`public/maestri-agent.zip`) e sincronizado com `maestri-remote-dist`.
- Task 4 [DOC]: Capability `docs/capabilities/maestri-remote.md` atualizada com especificação detalhada da capacidade na seção 3.8.
- Suíte completa de testes automatizados criada em `test/file-transfer.test.js` e aprovada com 100% de sucesso.
- Evidências registradas em `docs/changes/0-download-arquivos-terminal-app/evidence/`.
## Pronto quando
1. Ao exibir mensagens do chat ou snapshots do terminal que citem caminhos de arquivos válidos, o app renderiza chips interativos `📄 <arquivo>` clicáveis.
@ -181,21 +176,21 @@ Sem desenho de dados: a funcionalidade opera em memória e transporte WebSocket
---
## Critérios de Aceite
- [ ] AC1: Saídas de texto e snapshots do terminal que mencionam caminhos de arquivos válidos exibem chips interativos `📄 <arquivo>` clicáveis.
- [ ] AC2: O toque no chip dispara a mensagem `FILE_READ_REQ` e abre o modal de visualização assim que a resposta `FILE_READ_RESP` for recebida.
- [ ] AC3: Imagens (PNG, JPG, SVG, WebP) são visualizadas diretamente dentro do modal de preview.
- [ ] AC4: Textos, logs e arquivos de código são renderizados com formatação monoespaçada e rolagem vertical/horizontal no modal, com botão de copiar conteúdo.
- [ ] AC5: O botão "Salvar" no modal baixa o arquivo no armazenamento do smartphone.
- [ ] AC6: Caminhos que tentam acessar diretórios fora do workspace (`process.cwd()`) ou utilizar sequências de escape (`../`) são bloqueados com erro descritivo de acesso negado.
- [ ] AC7: Arquivos que excedam o teto de 20 MB são recusados defensivamente no host com a mensagem *"Arquivo excede o limite máximo de 20 MB"*.
- [ ] AC8: Se a estação host estiver offline no momento da solicitação, o app mobile exibe alerta informativo sem falhar.
- [ ] AC9: A publicação completa OTA e o rollout no cluster K3s são realizados com sucesso, e `/api/health` responde status 200.
- [x] AC1: Saídas de texto e snapshots do terminal que mencionam caminhos de arquivos válidos exibem chips interativos `📄 <arquivo>` clicáveis.
- [x] AC2: O toque no chip dispara a mensagem `FILE_READ_REQ` e abre o modal de visualização assim que a resposta `FILE_READ_RESP` for recebida.
- [x] AC3: Imagens (PNG, JPG, SVG, WebP) são visualizadas diretamente dentro do modal de preview.
- [x] AC4: Textos, logs e arquivos de código são renderizados com formatação monoespaçada e rolagem vertical/horizontal no modal, com botão de copiar conteúdo.
- [x] AC5: O botão "Salvar" no modal baixa o arquivo no armazenamento do smartphone.
- [x] AC6: Caminhos que tentam acessar diretórios fora do workspace (`process.cwd()`) ou utilizar sequências de escape (`../`) são bloqueados com erro descritivo de acesso negado.
- [x] AC7: Arquivos que excedam o teto de 20 MB são recusados defensivamente no host com a mensagem *"Arquivo excede o limite máximo de 20 MB"*.
- [x] AC8: Se a estação host estiver offline no momento da solicitação, o app mobile exibe alerta informativo sem falhar.
- [x] AC9: A publicação completa OTA e o rollout no cluster K3s são realizados com sucesso, e `/api/health` responde status 200.
## Tasks
- [ ] 1. [BE] Gateway Daemon & Relay Server: Suporte a FILE_READ_REQ e FILE_READ_RESP com sandbox e limite de 20MB — maestri-remote · 1,5 h (sem amostra) [Skill: ota-k3s-publishing]
- [ ] 2. [FRONT] App Mobile: Detecção de caminhos de arquivos em saídas de texto, chips clicáveis 📄 e modal de preview/download — maestri-remote · 2,0 h (sem amostra) [Skill: ota-k3s-publishing]
- [ ] 3. [DEPLOY] Publicação OTA e Rollout K3s: Build de bundle OTA, compilação Docker ARM64, rollout no cluster e sync do daemon local — maestri-remote · 1,0 h (sem amostra) [Skill: ota-k3s-publishing]
- [ ] 4. [DOC] Atualização da capability maestri-remote com especificação do download de arquivos do terminal — maestri-remote · 0,5 h (sem amostra)
- [x] 1. [BE] Gateway Daemon & Relay Server: Suporte a FILE_READ_REQ e FILE_READ_RESP com sandbox e limite de 20MB — maestri-remote · 1,5 h (sem amostra) [Skill: ota-k3s-publishing]
- [x] 2. [FRONT] App Mobile: Detecção de caminhos de arquivos em saídas de texto, chips clicáveis 📄 e modal de preview/download — maestri-remote · 2,0 h (sem amostra) [Skill: ota-k3s-publishing]
- [x] 3. [DEPLOY] Publicação OTA e Rollout K3s: Build de bundle OTA, compilação Docker ARM64, rollout no cluster e sync do daemon local — maestri-remote · 1,0 h (sem amostra) [Skill: ota-k3s-publishing]
- [x] 4. [DOC] Atualização da capability maestri-remote com especificação do download de arquivos do terminal — maestri-remote · 0,5 h (sem amostra)
## Skills Aplicáveis
- `.context/skills/ota-k3s-publishing/SKILL.md`: Processo obrigatório e autônomo de build do bundle OTA, Docker ARM64, rollout K3s via Maestri Shell e sincronização local.

View File

@ -46,6 +46,13 @@ const appDateVal = document.getElementById('app-date-val');
const appChecksumVal = document.getElementById('app-checksum-val');
const appChecksumRow = document.getElementById('app-checksum-row');
// Elementos de Preview e Download de Arquivos
const filePreviewModal = document.getElementById('file-preview-modal');
const btnCloseFilePreview = document.getElementById('btn-close-file-preview');
const btnSaveFile = document.getElementById('btn-save-file');
const btnCopyFileContent = document.getElementById('btn-copy-file-content');
let currentActiveFile = null;
let currentBuildId = null;
let appVersionInfo = {
version: '1.0.2',
@ -1396,6 +1403,22 @@ function handleStationMessage(pin, msg) {
}
break;
case 'FILE_READ_RESP':
document.querySelectorAll('.btn-file-chip').forEach(btn => {
const btnPath = btn.getAttribute('data-path');
if (btnPath === msg.path || (msg.name && btnPath && btnPath.endsWith(msg.name))) {
btn.classList.remove('loading');
}
});
if (!msg.ok) {
showToast(msg.error || 'Erro ao carregar arquivo da estação.', 'error');
break;
}
openFilePreviewModal(msg);
break;
case 'PROMPT_PENDING':
msg.pin = pin;
entry.pendingPrompts.set(msg.requestId, msg);
@ -2104,6 +2127,231 @@ function formatBytes(bytes) {
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}
// ============================================================
// Extração e Transferência de Arquivos sob Demanda via WebSocket
// ============================================================
function extractFilePaths(text) {
if (!text || typeof text !== 'string') return [];
// Lista abrangente de extensões suportadas pelo projeto e agentes
const validExtensions = '(?:png|jpe?g|gif|svg|webp|ico|pdf|txt|md|markdown|json|m?js|ts|html?|css|zip|log|csv|xml|ya?ml|sh|ps1|bat|cmd|apk)';
// O hífen fica no início da classe [-a-zA-Z0-9_./\\] para não ser tratado como intervalo ASCII
// O lookahead inclui pontuação de fechamento e ponto final de frase
const regex = new RegExp(`(?:^|[\\s"'(\`\\[<])([-a-zA-Z0-9_./\\\\]+?\\.${validExtensions})(?=[\\s"')\`\\]>,;:!?.|\\)]|$)`, 'gim');
const matches = new Set();
let match;
while ((match = regex.exec(text)) !== null) {
let filePath = match[1].trim();
// Remove aspas ou delimitadores no início e fim
filePath = filePath.replace(/^['"`(<\\[]+|['"`)>\\]]+$/g, '');
// Remove pontuação de final de frase
filePath = filePath.replace(/[:.,;!?]+$/g, '');
if (!filePath) continue;
// Ignora URLs completas
if (/^https?:\/\//i.test(filePath) || /^wss?:\/\//i.test(filePath) || filePath.includes('://')) {
continue;
}
// Normaliza barras invertidas do Windows
filePath = filePath.replace(/\\/g, '/');
// Remove prefixos ./ redundantes
if (filePath.startsWith('./')) {
filePath = filePath.slice(2);
}
const baseName = filePath.split('/').pop() || '';
// Ignora se for apenas a extensão isolada (ex: .json ou .md sem nome de arquivo)
if (baseName.startsWith('.') && baseName.split('.').length === 2 && baseName.length <= 5) {
continue;
}
matches.add(filePath);
}
return Array.from(matches);
}
window.extractFilePaths = extractFilePaths;
function renderFileChips(filePaths) {
const container = document.createElement('div');
container.className = 'file-chips-container';
filePaths.forEach(filePath => {
const chip = document.createElement('button');
chip.type = 'button';
chip.className = 'btn-file-chip';
chip.setAttribute('data-path', filePath);
const baseName = filePath.split('/').pop() || filePath;
chip.innerHTML = `
<span class="file-chip-icon">📄</span>
<span class="file-chip-name" title="${escapeHtml(filePath)}">${escapeHtml(baseName)}</span>
<span class="file-chip-action">Baixar</span>
`;
chip.addEventListener('click', (e) => {
e.preventDefault();
e.stopPropagation();
requestFileDownload(filePath, chip);
});
container.appendChild(chip);
});
return container;
}
window.renderFileChips = renderFileChips;
function requestFileDownload(filePath, chipElement = null) {
const pin = activeChatPin || currentPin;
if (!pin) {
showToast('Nenhuma estação conectada para solicitar arquivo.', 'error');
return;
}
const station = stationPool.get(String(pin));
const activeWs = (station && station.ws) ? station.ws : ws;
if (!activeWs || activeWs.readyState !== (WebSocket.OPEN || 1)) {
showToast('⚠️ Estação offline: o gateway não está conectado.', 'error');
return;
}
if (chipElement) {
chipElement.classList.add('loading');
}
const baseName = filePath.split('/').pop() || filePath;
showToast(`Solicitando "${baseName}" da estação...`, 'info');
activeWs.send(JSON.stringify({
type: 'FILE_READ_REQ',
path: filePath,
agentName: activeChatAgent || '',
chatId: activeChatAgent ? `chat-${Date.now()}` : ''
}));
}
window.requestFileDownload = requestFileDownload;
function openFilePreviewModal(fileData) {
currentActiveFile = fileData;
const modal = document.getElementById('file-preview-modal');
const titleEl = document.getElementById('file-preview-title');
const metaEl = document.getElementById('file-preview-meta');
const bodyEl = document.getElementById('file-preview-body');
const copyBtn = document.getElementById('btn-copy-file-content');
const iconEl = document.getElementById('file-preview-icon');
if (!modal || !bodyEl) return;
const fileName = fileData.name || (fileData.path ? fileData.path.split('/').pop() : 'arquivo');
const mimeType = fileData.mimeType || 'application/octet-stream';
const sizeFormatted = formatBytes(fileData.size || 0);
if (titleEl) titleEl.textContent = fileName;
if (metaEl) metaEl.textContent = `${sizeFormatted} • ${mimeType}`;
bodyEl.innerHTML = '';
const isImage = mimeType.startsWith('image/');
const isText = mimeType.startsWith('text/') ||
mimeType === 'application/json' ||
mimeType === 'application/xml' ||
mimeType === 'application/javascript' ||
mimeType === 'text/markdown';
if (isImage) {
if (iconEl) iconEl.textContent = '🖼️';
if (copyBtn) copyBtn.style.display = 'none';
const imgContainer = document.createElement('div');
imgContainer.className = 'file-preview-img-container';
const img = document.createElement('img');
img.src = `data:${mimeType};base64,${fileData.contentBase64}`;
img.alt = fileName;
img.className = 'file-preview-image';
imgContainer.appendChild(img);
bodyEl.appendChild(imgContainer);
} else if (isText) {
if (iconEl) iconEl.textContent = '📝';
if (copyBtn) copyBtn.style.display = 'inline-flex';
let textContent = '';
try {
const binString = atob(fileData.contentBase64 || '');
const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0));
textContent = new TextDecoder('utf-8').decode(bytes);
} catch (e) {
textContent = atob(fileData.contentBase64 || '');
}
const pre = document.createElement('pre');
pre.className = 'file-preview-pre';
const code = document.createElement('code');
code.className = 'file-preview-code';
code.textContent = textContent;
pre.appendChild(code);
bodyEl.appendChild(pre);
} else {
if (iconEl) iconEl.textContent = mimeType.includes('pdf') ? '📕' : (mimeType.includes('zip') ? '📦' : '📄');
if (copyBtn) copyBtn.style.display = 'none';
const binaryBox = document.createElement('div');
binaryBox.className = 'file-preview-binary-box';
binaryBox.innerHTML = `
<div style="font-size: 3rem; margin-bottom: 0.75rem;">📦</div>
<strong style="color: #f1f5f9; font-size: 1rem;">${escapeHtml(fileName)}</strong>
<p style="color: #94a3b8; font-size: 0.8rem; margin-top: 0.25rem;">${escapeHtml(sizeFormatted)} • ${escapeHtml(mimeType)}</p>
<p style="color: #38bdf8; font-size: 0.78rem; margin-top: 0.75rem;">Arquivo binário pronto para download no dispositivo.</p>
`;
bodyEl.appendChild(binaryBox);
}
modal.style.display = 'flex';
}
window.openFilePreviewModal = openFilePreviewModal;
function closeFilePreviewModal() {
const modal = document.getElementById('file-preview-modal');
if (modal) modal.style.display = 'none';
currentActiveFile = null;
}
window.closeFilePreviewModal = closeFilePreviewModal;
function saveCurrentActiveFile() {
if (!currentActiveFile || !currentActiveFile.contentBase64) return;
const { name, path: filePath, mimeType, contentBase64 } = currentActiveFile;
const fileName = name || (filePath ? filePath.split('/').pop() : 'arquivo');
try {
const byteCharacters = atob(contentBase64);
const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
const blob = new Blob([byteArray], { type: mimeType || 'application/octet-stream' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 1000);
showToast(`Download de "${fileName}" iniciado!`, 'info');
} catch (err) {
console.error('[FileDownload] Erro ao salvar arquivo:', err);
showToast(`Erro ao salvar arquivo: ${err.message}`, 'error');
}
}
window.saveCurrentActiveFile = saveCurrentActiveFile;
function hasHorizontalMenuHints(text) {
if (!text) return false;
return (
@ -3375,6 +3623,12 @@ function updateTerminalSnapshotInPlace(terminalText, isThinking, isPausedParam =
<pre class="terminal-snapshot-body" id="chat-terminal-snapshot-body">${escapeHtml(cleaned)}</pre>
`;
const filePaths = extractFilePaths(terminalText);
if (filePaths.length > 0) {
const chipsContainer = renderFileChips(filePaths);
card.appendChild(chipsContainer);
}
const prevScrollTop = chatMessagesEl.scrollTop;
if (chatMessagesEl.firstChild) {
chatMessagesEl.insertBefore(card, chatMessagesEl.firstChild);
@ -3398,6 +3652,21 @@ function updateTerminalSnapshotInPlace(terminalText, isThinking, isPausedParam =
pill.className = `agent-state-pill ${pillClass}`;
pill.textContent = pillText;
}
// Atualiza os chips de arquivos no snapshot in-place
const existingChips = card.querySelector('.file-chips-container');
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();
}
return true;
}
@ -3574,12 +3843,27 @@ function renderChatMessages(forceScroll = false) {
</div>
<pre class="terminal-snapshot-body" id="chat-terminal-snapshot-body">${escapeHtml(cleaned)}</pre>
`;
const filePaths = extractFilePaths(terminalSnapshotText);
if (filePaths.length > 0) {
const chipsContainer = renderFileChips(filePaths);
bubble.appendChild(chipsContainer);
}
chatMessagesEl.appendChild(bubble);
} else {
const bubble = document.createElement('div');
bubble.className = `chat-bubble ${item.role}`;
bubble.textContent = cleanTerminalOutput(item.text);
if (item.role === 'agent') {
const filePaths = extractFilePaths(item.text);
if (filePaths.length > 0) {
const chipsContainer = renderFileChips(filePaths);
bubble.appendChild(chipsContainer);
}
}
const itemsToRender = Array.isArray(item.attachments) && item.attachments.length > 0
? item.attachments
: (item.attachment ? [item.attachment] : []);
@ -4570,6 +4854,45 @@ async function initApp() {
});
}
// Listeners do Modal de Preview e Download de Arquivos
if (btnCloseFilePreview) {
btnCloseFilePreview.addEventListener('click', closeFilePreviewModal);
}
if (filePreviewModal) {
filePreviewModal.addEventListener('click', (e) => {
if (e.target === filePreviewModal) closeFilePreviewModal();
});
}
if (btnSaveFile) {
btnSaveFile.addEventListener('click', saveCurrentActiveFile);
}
if (btnCopyFileContent) {
btnCopyFileContent.addEventListener('click', async () => {
if (!currentActiveFile || !currentActiveFile.contentBase64) return;
try {
const binString = atob(currentActiveFile.contentBase64 || '');
const bytes = Uint8Array.from(binString, (m) => m.codePointAt(0));
const text = new TextDecoder('utf-8').decode(bytes);
if (navigator.clipboard && navigator.clipboard.writeText) {
await navigator.clipboard.writeText(text);
} else {
const ta = document.createElement('textarea');
ta.value = text;
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
document.body.removeChild(ta);
}
showToast('Conteúdo copiado para a área de transferência!', 'info');
} catch (e) {
showToast('Falha ao copiar conteúdo.', 'error');
}
});
}
if (btnCheckUpdateManual) {
btnCheckUpdateManual.addEventListener('click', async () => {
btnCheckUpdateManual.disabled = true;

Binary file not shown.

Binary file not shown.

View File

@ -1,9 +1,9 @@
{
"version": "1.0.24",
"buildId": "76f70c16",
"releasedAt": "2026-11-21T15:03:06.574Z",
"buildId": "5a3f32bc",
"releasedAt": "2026-11-21T16:23:44.908Z",
"bundleUrl": "/bundles/bundle-1.0.24.zip",
"latestUrl": "/bundles/bundle-latest.zip",
"checksum": "83555f4be33cb2b490cf1bdd7105e9c53abe9696d41c3a202c2c818f99426aa7",
"sizeBytes": 63298
"checksum": "6710730c8f71a8db1eef7fd4673a6633a2b590a4186ee7d500b4afb4b24bc00f",
"sizeBytes": 67263
}

View File

@ -225,6 +225,35 @@
</div>
</div>
<!-- Modal: Visualização e Download de Arquivo -->
<div id="file-preview-modal" class="modal-backdrop" style="display: none;">
<div class="modal-card file-preview-card">
<div class="modal-header">
<div style="display: flex; align-items: center; gap: 0.5rem; overflow: hidden;">
<span style="font-size: 1.2rem; flex-shrink: 0;" id="file-preview-icon">📄</span>
<div style="overflow: hidden;">
<h3 id="file-preview-title" style="margin: 0; font-size: 0.95rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">arquivo.ext</h3>
<span id="file-preview-meta" style="font-size: 0.72rem; color: #94a3b8;">0 KB • text/plain</span>
</div>
</div>
<button id="btn-close-file-preview" class="btn-icon" aria-label="Fechar">&times;</button>
</div>
<div class="file-preview-body" id="file-preview-body">
<!-- Conteúdo do arquivo renderizado via JS -->
</div>
<div class="file-preview-actions">
<button type="button" id="btn-copy-file-content" class="btn-secondary" style="display: none; padding: 0.65rem 0.9rem; font-size: 0.82rem;">
📋 Copiar Texto
</button>
<button type="button" id="btn-save-file" class="btn-primary" style="flex: 1; padding: 0.65rem 1rem; font-size: 0.85rem;">
💾 Salvar Arquivo
</button>
</div>
</div>
</div>
<!-- Bottom Sheet / Drawer: Chat Interativo com Agente -->
<div id="chat-drawer" class="chat-drawer" style="display: none;">
<div class="chat-backdrop" id="chat-backdrop" onclick="window.closeChat && window.closeChat()"></div>

Binary file not shown.

View File

@ -2156,3 +2156,148 @@ main {
color: #f87171;
background: rgba(248, 113, 113, 0.12);
}
/* ============================================================
Chips de Download de Arquivo no Terminal e Chat
============================================================ */
.file-chips-container {
display: flex;
flex-wrap: wrap;
gap: 0.4rem;
margin-top: 0.55rem;
padding-top: 0.45rem;
border-top: 1px solid rgba(255, 255, 255, 0.08);
}
.btn-file-chip {
display: inline-flex;
align-items: center;
gap: 0.35rem;
background: rgba(14, 165, 233, 0.12);
border: 1px solid rgba(56, 189, 248, 0.3);
color: #38bdf8;
padding: 0.35rem 0.6rem;
border-radius: 8px;
font-size: 0.78rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
max-width: 100%;
overflow: hidden;
text-align: left;
user-select: none;
touch-action: manipulation;
}
.btn-file-chip:hover {
background: rgba(14, 165, 233, 0.22);
border-color: rgba(56, 189, 248, 0.6);
transform: translateY(-1px);
}
.btn-file-chip:active {
transform: translateY(0);
}
.btn-file-chip.loading {
opacity: 0.7;
cursor: wait;
pointer-events: none;
background: rgba(245, 158, 11, 0.15);
border-color: rgba(245, 158, 11, 0.4);
color: #fbbf24;
}
.btn-file-chip.loading .file-chip-action::after {
content: '...';
}
.file-chip-icon {
font-size: 0.85rem;
flex-shrink: 0;
}
.file-chip-name {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
flex: 1;
}
.file-chip-action {
font-size: 0.68rem;
color: #94a3b8;
background: rgba(0, 0, 0, 0.25);
padding: 0.1rem 0.35rem;
border-radius: 4px;
flex-shrink: 0;
}
/* ============================================================
Modal de Preview e Download de Arquivos
============================================================ */
.file-preview-card {
max-width: 460px;
max-height: 85vh;
display: flex;
flex-direction: column;
}
.file-preview-body {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
margin: 0.5rem 0 1rem 0;
background: rgba(15, 23, 42, 0.75);
border: 1px solid var(--border);
border-radius: 10px;
padding: 0.75rem;
min-height: 140px;
max-height: 52vh;
-webkit-overflow-scrolling: touch;
}
.file-preview-img-container {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
}
.file-preview-image {
max-width: 100%;
max-height: 48vh;
object-fit: contain;
border-radius: 6px;
}
.file-preview-pre {
margin: 0;
padding: 0;
white-space: pre;
word-break: normal;
overflow-x: auto;
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
font-size: 0.75rem;
line-height: 1.45;
color: #e2e8f0;
}
.file-preview-code {
font-family: inherit;
}
.file-preview-binary-box {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 2rem 1rem;
text-align: center;
}
.file-preview-actions {
display: flex;
gap: 0.5rem;
align-items: center;
}

View File

@ -447,7 +447,125 @@ export class GatewayDaemon {
} else if (msg.type === 'AGENT_UPDATE_AVAILABLE') {
console.log('[Gateway] Notificação push do Relay: Nova versão do daemon disponível!');
this.checkForAutoUpdate();
} else if (msg.type === 'FILE_READ_REQ') {
const reqPath = typeof msg.path === 'string' ? msg.path.trim() : '';
const agentName = msg.agentName || '';
const chatId = msg.chatId || '';
const respondFailure = (errorMsg) => {
if (this.ws && this.connected) {
this.ws.send(JSON.stringify({
type: 'FILE_READ_RESP',
path: reqPath,
ok: false,
error: errorMsg,
chatId,
agentName,
timestamp: new Date().toISOString()
}));
}
};
if (!reqPath) {
respondFailure('Caminho de arquivo inválido ou não informado.');
return;
}
try {
const workspaceRoot = path.resolve(process.cwd());
const normalizedInput = path.normalize(reqPath);
const targetPath = path.isAbsolute(normalizedInput)
? path.resolve(normalizedInput)
: path.resolve(workspaceRoot, normalizedInput);
const relative = path.relative(workspaceRoot, targetPath);
const isInsideWorkspace = !relative.startsWith('..') && !path.isAbsolute(relative);
if (!isInsideWorkspace) {
console.warn(`[Gateway:Security] Bloqueio de sandbox para path fora do workspace: ${reqPath} -> ${targetPath}`);
respondFailure('Acesso negado: o arquivo solicitado está fora do workspace do projeto.');
return;
}
if (!fs.existsSync(targetPath)) {
respondFailure('Arquivo não encontrado no host.');
return;
}
const stats = fs.statSync(targetPath);
if (!stats.isFile()) {
respondFailure('O caminho solicitado não é um arquivo regular.');
return;
}
const MAX_SIZE = 20 * 1024 * 1024; // 20 MB
if (stats.size > MAX_SIZE) {
respondFailure('Arquivo excede o limite máximo de 20 MB.');
return;
}
const mimeType = this.detectMimeType(targetPath);
const contentBase64 = fs.readFileSync(targetPath).toString('base64');
const fileName = path.basename(targetPath);
if (this.ws && this.connected) {
this.ws.send(JSON.stringify({
type: 'FILE_READ_RESP',
path: reqPath,
name: fileName,
mimeType,
size: stats.size,
contentBase64,
ok: true,
chatId,
agentName,
timestamp: new Date().toISOString()
}));
console.log(`[Gateway] Arquivo lido e despachado: ${fileName} (${stats.size} bytes, ${mimeType})`);
}
} catch (err) {
console.error(`[Gateway] Erro ao ler arquivo ${reqPath}:`, err.message);
respondFailure(`Erro ao ler arquivo: ${err.message}`);
}
}
}
detectMimeType(filePath) {
const ext = path.extname(filePath).toLowerCase().replace('.', '');
const mimeMap = {
png: 'image/png',
jpg: 'image/jpeg',
jpeg: 'image/jpeg',
gif: 'image/gif',
svg: 'image/svg+xml',
webp: 'image/webp',
ico: 'image/x-icon',
pdf: 'application/pdf',
txt: 'text/plain',
md: 'text/markdown',
markdown: 'text/markdown',
json: 'application/json',
js: 'text/javascript',
mjs: 'text/javascript',
ts: 'text/typescript',
html: 'text/html',
htm: 'text/html',
css: 'text/css',
csv: 'text/csv',
xml: 'application/xml',
yaml: 'text/yaml',
yml: 'text/yaml',
log: 'text/plain',
sh: 'text/x-sh',
ps1: 'text/plain',
bat: 'text/plain',
cmd: 'text/plain',
zip: 'application/zip',
tar: 'application/x-tar',
gz: 'application/gzip',
apk: 'application/vnd.android.package-archive'
};
return mimeMap[ext] || 'application/octet-stream';
}
emitTerminalOutput(agentName, rawOutput) {

View File

@ -133,6 +133,33 @@ export function handleClientWsMessage({ ws, sessionPin, msg, sessionManager, tel
return;
}
if (msg.type === 'FILE_READ_REQ') {
const reqPath = typeof msg.path === 'string' ? msg.path.trim() : '';
telemetryService.logEvent({
source: 'mobile',
pin: sessionPin,
agentName: msg.agentName,
category: 'file_transfer',
action: 'file_read_req',
summary: `Solicitação de leitura de arquivo (${reqPath}) para ${msg.agentName}`,
payload: { path: reqPath, agentName: msg.agentName, chatId: msg.chatId }
});
const delivered = sessionManager.sendToGateway(sessionPin, msg);
if (!delivered) {
ws.send(JSON.stringify({
type: 'FILE_READ_RESP',
path: reqPath,
ok: false,
error: '⚠️ Estação offline: o gateway desta máquina não está conectado ao Relay no momento.',
chatId: msg.chatId,
agentName: msg.agentName,
timestamp: new Date().toISOString()
}));
}
return;
}
if (msg.type === 'TELEMETRY_LOG' || msg.type === 'SCREEN_STATE_SNAPSHOT') {
telemetryService.logEvent({
source: 'mobile',

View File

@ -68,6 +68,25 @@ export function handleGatewayWsMessage({
replySnippet: (msg.reply || '').slice(0, 300)
}
});
} else if (msg.type === 'FILE_READ_RESP') {
sessionManager.broadcastToClients(sessionPin, msg);
telemetryService.logEvent({
source: 'gateway',
pin: sessionPin,
agentName: msg.agentName,
category: 'file_transfer',
action: 'file_read_resp',
summary: `Resposta de leitura de arquivo: ${msg.name || msg.path} (ok=${Boolean(msg.ok)}, size=${msg.size || 0})`,
payload: {
path: msg.path,
name: msg.name || null,
ok: Boolean(msg.ok),
size: msg.size || 0,
mimeType: msg.mimeType || null,
error: msg.error || null,
chatId: msg.chatId || null
}
});
} else if (msg.type === 'AGENT_OUTPUT' || msg.type === 'ANALYZE_OUTPUT') {
// Classifica semanticamente a saída bruta do terminal via LiteLLM
intentClassifier.classify(msg.text, msg.agentName).then((classification) => {

333
test/file-transfer.test.js Normal file
View File

@ -0,0 +1,333 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import EventEmitter from 'node:events';
import { GatewayDaemon } from '../src/gateway/daemon.js';
import { handleClientWsMessage } from '../src/relay/client-message-handler.js';
import { handleGatewayWsMessage } from '../src/relay/gateway-message-handler.js';
import { SessionManager } from '../src/relay/session-manager.js';
class MockSocket extends EventEmitter {
constructor() {
super();
this.OPEN = 1;
this.readyState = 1;
this.sent = [];
}
send(data) {
this.sent.push(data);
}
}
test('GatewayDaemon - FILE_READ_REQ: Deve ler arquivo existente no workspace com Base64 e MIME type correto', async () => {
const daemon = new GatewayDaemon({ pin: '112233' });
const mockWs = new MockSocket();
daemon.ws = mockWs;
daemon.connected = true;
// Usa um arquivo real do projeto que certamente existe
const testPath = 'package.json';
await daemon.handleRelayMessage({
type: 'FILE_READ_REQ',
path: testPath,
agentName: 'TestAgent',
chatId: 'chat-101'
});
assert.equal(mockWs.sent.length, 1);
const resp = JSON.parse(mockWs.sent[0]);
assert.equal(resp.type, 'FILE_READ_RESP');
assert.equal(resp.ok, true);
assert.equal(resp.path, testPath);
assert.equal(resp.name, 'package.json');
assert.equal(resp.mimeType, 'application/json');
assert.equal(resp.agentName, 'TestAgent');
assert.equal(resp.chatId, 'chat-101');
assert.ok(typeof resp.contentBase64 === 'string' && resp.contentBase64.length > 0);
// Decodifica Base64 e valida conteúdo
const decoded = Buffer.from(resp.contentBase64, 'base64').toString('utf8');
assert.ok(decoded.includes('maestri-remote-agent'));
});
test('GatewayDaemon - FILE_READ_REQ: Sandbox defensivo deve bloquear escape de diretório (../)', async () => {
const daemon = new GatewayDaemon({ pin: '112233' });
const mockWs = new MockSocket();
daemon.ws = mockWs;
daemon.connected = true;
await daemon.handleRelayMessage({
type: 'FILE_READ_REQ',
path: '../../../../../../etc/passwd',
agentName: 'TestAgent',
chatId: 'chat-sandbox'
});
assert.equal(mockWs.sent.length, 1);
const resp = JSON.parse(mockWs.sent[0]);
assert.equal(resp.type, 'FILE_READ_RESP');
assert.equal(resp.ok, false);
assert.ok(resp.error.includes('Acesso negado') || resp.error.includes('workspace'));
});
test('GatewayDaemon - FILE_READ_REQ: Deve retornar erro informativo se arquivo não existir', async () => {
const daemon = new GatewayDaemon({ pin: '112233' });
const mockWs = new MockSocket();
daemon.ws = mockWs;
daemon.connected = true;
await daemon.handleRelayMessage({
type: 'FILE_READ_REQ',
path: 'arquivo-totalmente-inexistente-12345.xyz',
agentName: 'TestAgent'
});
assert.equal(mockWs.sent.length, 1);
const resp = JSON.parse(mockWs.sent[0]);
assert.equal(resp.type, 'FILE_READ_RESP');
assert.equal(resp.ok, false);
assert.ok(resp.error.includes('não encontrado'));
});
test('GatewayDaemon - FILE_READ_REQ: Bloqueio defensivo para arquivos que excedem 20 MB', async () => {
const daemon = new GatewayDaemon({ pin: '112233' });
const mockWs = new MockSocket();
daemon.ws = mockWs;
daemon.connected = true;
// Cria temporariamente um arquivo fictício e testa ou mocka fs.statSync
const originalStat = fs.statSync;
try {
fs.statSync = (targetPath) => {
if (String(targetPath).includes('mock-large-file.bin')) {
return {
isFile: () => true,
size: 21 * 1024 * 1024 // 21 MB
};
}
return originalStat(targetPath);
};
// Cria arquivo vazio temporário
const largeDummy = path.resolve(process.cwd(), 'mock-large-file.bin');
fs.writeFileSync(largeDummy, 'dummy');
await daemon.handleRelayMessage({
type: 'FILE_READ_REQ',
path: 'mock-large-file.bin',
agentName: 'Claude'
});
assert.equal(mockWs.sent.length, 1);
const resp = JSON.parse(mockWs.sent[0]);
assert.equal(resp.type, 'FILE_READ_RESP');
assert.equal(resp.ok, false);
assert.ok(resp.error.includes('20 MB'));
if (fs.existsSync(largeDummy)) fs.unlinkSync(largeDummy);
} finally {
fs.statSync = originalStat;
}
});
test('Relay - handleClientWsMessage deve rotear FILE_READ_REQ para Gateway e devolver erro se offline', () => {
const manager = new SessionManager();
const gatewayWs = new MockSocket();
const clientWs = new MockSocket();
const pin = '556677';
const loggedEvents = [];
const mockTelemetry = { logEvent: (evt) => loggedEvents.push(evt) };
// 1. Estação offline: deve responder erro imediato ao cliente
handleClientWsMessage({
ws: clientWs,
sessionPin: pin,
msg: {
type: 'FILE_READ_REQ',
path: 'evidence/test.png',
agentName: 'Claude'
},
sessionManager: manager,
telemetryService: mockTelemetry
});
assert.equal(clientWs.sent.length, 1);
const offlineResp = JSON.parse(clientWs.sent[0]);
assert.equal(offlineResp.type, 'FILE_READ_RESP');
assert.equal(offlineResp.ok, false);
assert.ok(offlineResp.error.includes('offline'));
// 2. Conecta Gateway e reenvia: deve encaminhar com telemetria
manager.registerGateway(pin, gatewayWs, 'Estacao-Dev');
clientWs.sent.length = 0;
handleClientWsMessage({
ws: clientWs,
sessionPin: pin,
msg: {
type: 'FILE_READ_REQ',
path: 'docs/spec.md',
agentName: 'Claude',
chatId: 'chat-99'
},
sessionManager: manager,
telemetryService: mockTelemetry
});
assert.equal(gatewayWs.sent.length, 1);
const forwarded = JSON.parse(gatewayWs.sent[0]);
assert.equal(forwarded.type, 'FILE_READ_REQ');
assert.equal(forwarded.path, 'docs/spec.md');
assert.equal(forwarded.agentName, 'Claude');
assert.equal(loggedEvents.length, 2);
assert.equal(loggedEvents[1].category, 'file_transfer');
assert.equal(loggedEvents[1].action, 'file_read_req');
});
test('Relay - handleGatewayWsMessage deve fazer broadcast de FILE_READ_RESP aos clientes e logar telemetria', () => {
const manager = new SessionManager();
const gatewayWs = new MockSocket();
const clientWs = new MockSocket();
const loggedEvents = [];
const pin = '889900';
manager.registerGateway(pin, gatewayWs, 'Estacao-Files');
manager.registerClient(pin, clientWs);
clientWs.sent.length = 0;
handleGatewayWsMessage({
sessionPin: pin,
msg: {
type: 'FILE_READ_RESP',
path: 'docs/evidence.png',
name: 'evidence.png',
mimeType: 'image/png',
size: 4096,
contentBase64: 'aW1n',
ok: true,
chatId: 'chat-88',
agentName: 'Claude'
},
sessionManager: manager,
telemetryService: { logEvent: (evt) => loggedEvents.push(evt) }
});
assert.equal(clientWs.sent.length, 1);
const clientMsg = JSON.parse(clientWs.sent[0]);
assert.equal(clientMsg.type, 'FILE_READ_RESP');
assert.equal(clientMsg.name, 'evidence.png');
assert.equal(clientMsg.ok, true);
assert.equal(clientMsg.size, 4096);
assert.equal(loggedEvents.length, 1);
assert.equal(loggedEvents[0].category, 'file_transfer');
assert.equal(loggedEvents[0].action, 'file_read_resp');
});
test('Frontend - extractFilePaths, renderFileChips e modais de preview devem funcionar no ambiente JSDOM', async () => {
const { JSDOM } = await import('jsdom');
const html = `
<!DOCTYPE html>
<html>
<body>
<div id="container"></div>
<div id="file-preview-modal" style="display: none;">
<span id="file-preview-icon"></span>
<h3 id="file-preview-title"></h3>
<span id="file-preview-meta"></span>
<div id="file-preview-body"></div>
<button id="btn-copy-file-content" style="display: none;"></button>
<button id="btn-save-file"></button>
</div>
</body>
</html>
`;
const dom = new JSDOM(html);
global.window = dom.window;
global.document = dom.window.document;
global.WebSocket = MockSocket;
// Executa o script do app
await import('../public/app.js');
const extractFilePaths = dom.window.extractFilePaths;
const renderFileChips = dom.window.renderFileChips;
const openFilePreviewModal = dom.window.openFilePreviewModal;
const closeFilePreviewModal = dom.window.closeFilePreviewModal;
assert.equal(typeof extractFilePaths, 'function', 'extractFilePaths deve estar exposta no window');
assert.equal(typeof renderFileChips, 'function', 'renderFileChips deve estar exposta no window');
assert.equal(typeof openFilePreviewModal, 'function', 'openFilePreviewModal deve estar exposta no window');
assert.equal(typeof closeFilePreviewModal, 'function', 'closeFilePreviewModal deve estar exposta no window');
// 1. Testa regex e extração de caminhos
const sampleOutput = `
Arquivo gerado em docs/changes/0-download-arquivos-terminal-app/spec.md com sucesso!
Evidência salva em 'evidence/print.png'.
Ignorar versão v1.0.2 e link https://remote.winicomw.ddnsfree.com/api/health.
Log final em test.log e script deploy.ps1.
`;
const paths = extractFilePaths(sampleOutput);
assert.ok(paths.includes('docs/changes/0-download-arquivos-terminal-app/spec.md'));
assert.ok(paths.includes('evidence/print.png'));
assert.ok(paths.includes('test.log'));
assert.ok(paths.includes('deploy.ps1'));
assert.ok(!paths.some(p => p.includes('http')));
assert.ok(!paths.some(p => p === 'v1.0.2'));
// 2. Testa criação dos chips
const chipsContainer = renderFileChips(paths);
assert.equal(chipsContainer.className, 'file-chips-container');
const buttons = chipsContainer.querySelectorAll('.btn-file-chip');
assert.equal(buttons.length, paths.length);
assert.equal(buttons[0].getAttribute('data-path'), paths[0]);
// 3. Testa Preview de Arquivo de Texto / Código
const modal = dom.window.document.getElementById('file-preview-modal');
const title = dom.window.document.getElementById('file-preview-title');
const meta = dom.window.document.getElementById('file-preview-meta');
const body = dom.window.document.getElementById('file-preview-body');
const copyBtn = dom.window.document.getElementById('btn-copy-file-content');
const textSample = '# Spec Markdown\nLinha 2 de teste';
const textBase64 = Buffer.from(textSample, 'utf8').toString('base64');
openFilePreviewModal({
name: 'spec.md',
path: 'docs/spec.md',
mimeType: 'text/markdown',
size: Buffer.byteLength(textSample),
contentBase64: textBase64,
ok: true
});
assert.equal(modal.style.display, 'flex');
assert.equal(title.textContent, 'spec.md');
assert.ok(meta.textContent.includes('text/markdown'));
assert.equal(copyBtn.style.display, 'inline-flex');
const codeEl = body.querySelector('code.file-preview-code');
assert.ok(codeEl, 'Deve conter bloco de código para texto');
assert.equal(codeEl.textContent, textSample);
// 4. Testa Preview de Imagem
openFilePreviewModal({
name: 'evidence.png',
path: 'evidence/evidence.png',
mimeType: 'image/png',
size: 1024,
contentBase64: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
ok: true
});
assert.equal(title.textContent, 'evidence.png');
assert.equal(copyBtn.style.display, 'none');
const imgEl = body.querySelector('img.file-preview-image');
assert.ok(imgEl, 'Deve renderizar elemento img para imagens');
assert.ok(imgEl.src.startsWith('data:image/png;base64,'));
// 5. Fechar modal
closeFilePreviewModal();
assert.equal(modal.style.display, 'none');
});