feat(ux): downloads sob demanda e reorganizacao dinamica da barra de digitacao

This commit is contained in:
Winícius 2026-11-21 16:47:34 -03:00
parent 63151694a9
commit 2b3f4705f6
12 changed files with 707 additions and 50 deletions

View File

@ -135,18 +135,28 @@ 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. - **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. - **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 ### 3.8. Central de Downloads Sob Demanda via WebSocket e Layout Otimizado do Chat
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: 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 com foco em legibilidade e ergonomia móvel:
- **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. - **Catálogo Transparente em Memória (`sessionFilesCatalog`):** Qualquer caminho de arquivo referenciado nas mensagens de agentes ou nas saídas do terminal é identificado automaticamente por analisador léxico (`extractFilePaths`) e catalogado silenciosamente em memória na sessão ativa.
- **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). - **Eliminação de Poluição Visual:** Foram removidos todos os chips inline automáticos das bolhas de chat e dos snapshots do terminal, mantendo o histórico de conversa limpo e focado no diálogo operacional.
- **Três Pontos de Acesso Sob Demanda:**
1. **Botão `📥` no Cabeçalho do Chat:** Exibe badge numérico dinâmico informando a quantidade de arquivos detectados na sessão atual (`#session-downloads-badge`).
2. **Opção no Menu de Anexos (`+`):** Item dedicado *"📥 Arquivos da Estação (Downloads)"* no menu flutuante.
3. **Comandos de Chat (`/downloads` e `/arquivos`):** Ao enviar `/downloads` ou `/arquivos` no campo de texto, o aplicativo intercepta o envio e abre diretamente o modal da central de downloads.
- **Modal de Arquivos da Estação (`#session-downloads-modal`):** Lista todos os arquivos identificados com ícone representativo por categoria (🖼️ imagem, 📄 documento/código, 📦 binário), nome em destaque, caminho relativo e botão *"Ver / Baixar"*.
- **Roteamento Bidirecional Sob Demanda (`FILE_READ_REQ` e `FILE_READ_RESP`):** O toque em *"Ver / Baixar"* despacha a requisição `FILE_READ_REQ` pelo túnel WebSocket já autenticado. O Relay encaminha a mensagem à estação correspondente e recebe `FILE_READ_RESP` com o conteúdo 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. - **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. - **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`):** - **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. - **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". - **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. - **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`) - **Ação de Salvar:** Botão "Salvar Arquivo" que aciona o download direto no armazenamento do dispositivo móvel (ou compartilhamento nativo no Android).
- **Reorganização Ergonômica da Barra Inferior (`.chat-input-bar`):**
- Realocação do botão de teclado virtual TUI (`⌨️`) para o cabeçalho do chat (`.chat-header`), agrupando todos os controles do terminal no topo.
- Alternância inteligente no slot direito entre botão de microfone (quando campo vazio e sem anexos) e botão de envio (ao digitar texto ou anexar fotos/arquivos), no padrão de mensageiros modernos.
- Caixa de texto (`#chat-input`) ampliada para ocupar mais de 75% da largura da tela móvel, permitindo digitação fluida e visualização clara de comandos extensos. (Change: `docs/changes/0-ux-downloads-sob-demanda-layout-input/spec.md`)
--- ---

View File

@ -0,0 +1,114 @@
# Evidências de Validação — UX Downloads Sob Demanda e Reorganização do Chat Input
**Change:** `docs/changes/0-ux-downloads-sob-demanda-layout-input/spec.md`
**Data:** 2026-11-21
**Versão Publicada:** `v1.0.27` (Build ID `49785205`)
**Responsável:** Antigravity (Builder)
---
## 1. Suíte de Testes Automatizados
Execução completa dos testes automatizados com Node.js Test Runner e JSDOM, cobrindo tanto os novos testes específicos quanto a regressão completa do sistema:
```tap
TAP version 13
# Subtest: Frontend - Downloads Sob Demanda, Catálogo em Memória e Alternância Voz/Envio
ok 1 - Frontend - Downloads Sob Demanda, Catálogo em Memória e Alternância Voz/Envio
---
duration_ms: 251.371
type: 'test'
...
1..1
# tests 1
# suites 0
# pass 1
# fail 0
# cancelled 0
# skipped 0
# todo 0
```
Suíte Global de Regressão:
```
1..53
# tests 132
# suites 5
# pass 132
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 11904.4941
```
---
## 2. Validação dos Componentes de UI/UX
### 2.1 Reorganização da Barra Inferior (`.chat-input-bar`)
- **Realocação do Botão TUI (`⌨️`):** Movido com sucesso para `.chat-header` ao lado dos demais controles de terminal (`btn-restart-terminal`, `btn-refresh-chat`, `chat-notif-toggle-btn`).
- **Alternância Dinâmica Inteligente Voz / Envio:**
- Quando `#chat-input` está vazio e sem anexos: `#btn-voice` exibido (`display: inline-flex`), `#btn-chat-send` oculto (`display: none`).
- Ao digitar qualquer caractere ou selecionar fotos/arquivos anexos: `#btn-voice` ocultado (`display: none`) e `#btn-chat-send` exibido (`display: inline-flex`).
- Ao apagar o texto ou enviar a mensagem: `#btn-voice` é restaurado instantaneamente.
- **Ampliação do Campo de Texto:** Com a redução para apenas 2 botões na barra (`+` e o botão dinâmico de ação), a caixa `#chat-input` expande para mais de 75% da largura da tela móvel, eliminando o aperto visual e permitindo redação confortável.
### 2.2 Central de Downloads Sob Demanda e Catálogo em Memória
- **Remoção dos Chips Automáticos:** Removida a renderização inline/automática de chips `📄 <arquivo>` nas bolhas de chat e nos snapshots do terminal, mantendo o histórico limpo e sem ruído visual.
- **Catálogo Transparente (`sessionFilesCatalog`):** Todos os caminhos identificados por `extractFilePaths()` são indexados transparentemente em memória na sessão ativa.
- **Acesso Sob Demanda em 3 Pontos:**
1. **Botão `📥` no cabeçalho:** Exibe badge numérico `#session-downloads-badge` com a quantidade de arquivos detectados.
2. **Menu de Anexos (`+`):** Nova opção *"📥 Arquivos da Estação (Downloads)"*.
3. **Comandos de Chat:** Enviar `/downloads`, `/download`, `/arquivos` ou `/arquivo` no chat abre diretamente o modal `#session-downloads-modal`.
- **Modal de Arquivos da Estação (`#session-downloads-modal`):**
- Lista arquivos detectados com ícone de categoria (🖼️ imagem, 📄 documento/código, 📦 binário), nome em destaque e caminho relativo.
- Botão *"Ver / Baixar"* despacha `FILE_READ_REQ` via WebSocket e abre o visualizador integrado (`#file-preview-modal`).
---
## 3. Esteira Autônoma de Publicação OTA e Rollout K3s
### 3.1 Bundle OTA da Interface Móvel
- **Comando:** `npm run build:bundle`
- **Artefato Gerado:** `public/bundles/bundle-1.0.27.zip` (69.527 bytes)
- **Manifesto:** `public/bundles/manifest.json`
- **SHA-256:** `1be6eda404c2600d5156e9a66f9eaae737e9f9a3909fe07f1ccc3384c2e04c7d`
- **Build ID:** `49785205`
### 3.2 Compilação Docker ARM64 e Push
- **Comando:** `docker buildx build --platform linux/arm64 -t winicomw/maestri-remote-relay:latest --push .`
- **Resultado:** Imagem compilada e enviada para o Docker Hub com sucesso (`winicomw/maestri-remote-relay:latest`).
### 3.3 Rollout no Cluster K3s na Oracle VPS
- **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: maestri-remote-relay-64556cc5d7-slzgj (1/1 Running)
```
### 3.4 Validação dos Endpoints Públicos de Produção
```json
// GET https://remote.winicomw.ddnsfree.com/api/health
{
"status": "ok",
"timestamp": "2026-11-21T19:45:34.894Z"
}
// GET https://remote.winicomw.ddnsfree.com/api/version
{
"version": "1.0.27",
"buildId": "49785205",
"releasedAt": "2026-11-21T19:43:00.809Z",
"bundleUrl": "/bundles/bundle-1.0.27.zip",
"latestUrl": "/bundles/bundle-latest.zip",
"checksum": "1be6eda404c2600d5156e9a66f9eaae737e9f9a3909fe07f1ccc3384c2e04c7d",
"sizeBytes": 69527
}
```
### 3.5 Pacote do Agente Daemon Local
- **Comando:** `npm run build:agent`
- **Resultado:** Smoke test aprovado e `public/maestri-agent.zip` gerado (33.5 KB).

View File

@ -1,12 +1,24 @@
# Spec: Exibição de Downloads Sob Demanda e Reorganização da Barra de Digitação # Spec: Exibição de Downloads Sob Demanda e Reorganização da Barra de Digitação
**Work Item:** N/A (Projeto Pessoal · Sem Azure Boards) **Work Item:** N/A (Projeto Pessoal · Sem Azure Boards)
**Criada em:** 2026-11-21 16:15 **Criada em:** 2026-11-21 16:15
**Status:** Especificação concluída (aguardando aprovação para implementação pelo Builder) **Status:** Concluída (implementada, publicada via OTA v1.0.27 e K3s, e evidenciada)
**Baseline:** maestri-remote@9b175f9 (main, 2026-11-21) **Baseline:** maestri-remote@9b175f9 (main, 2026-11-21)
**Complexidade:** P (1 pt — refinamento de UX e frontend no app móvel) **Complexidade:** P (1 pt — refinamento de UX e frontend no app móvel)
**Estimativa (h):** 3,0 h (por Task em `## Tasks`) **Estimativa (h):** 3,0 h (por Task em `## Tasks`)
## Estado atual ## Estado atual
2026-11-21 16:45 · Antigravity (Builder) — Implementação, validação e publicação concluídas:
- Layout da barra inferior (.chat-input-bar) reorganizado com caixa expandida para >75% da largura.
- Botão virtual de teclado TUI (⌨️) realocado para o cabeçalho (.chat-header).
- Alternância dinâmica no slot direito entre Voz (microfone) e Envio (🚀) implementada e validada.
- Chips inline automáticos removidos dos balões de chat e snapshots de terminal.
- Catálogo em memória sessionFilesCatalog integrado, com acesso sob demanda via botão 📥 no cabeçalho com badge numérico, opção no menu + e comandos /downloads e /arquivos.
- Suíte completa de testes executada (132 testes passando, 0 falhas).
- Bundle OTA v1.0.27 gerado e publicado.
- Imagem Docker ARM64 compilada e enviada para o Docker Hub.
- Rollout no cluster K3s na Oracle VPS executado com sucesso via SREOracleAgent e validado em produção.
- Capability maestri-remote.md e evidências registradas em evidence/evidence.md.
2026-11-21 16:15 · Antigravity (Planner) — Especificação técnica e arquitetural concluída após validação e solicitação do operador: 2026-11-21 16:15 · Antigravity (Planner) — Especificação técnica e arquitetural concluída após validação e solicitação do operador:
- Identificada restrição severa de espaço útil no input de texto do chat móvel devido ao acúmulo de 4 botões paralelos (`+`, microfone, `⌨️`, envio). - Identificada restrição severa de espaço útil no input de texto do chat móvel devido ao acúmulo de 4 botões paralelos (`+`, microfone, `⌨️`, envio).
- Identificada poluição visual na renderização automática de chips de download de arquivos em balões de mensagens e snapshots de terminal. - Identificada poluição visual na renderização automática de chips de download de arquivos em balões de mensagens e snapshots de terminal.
@ -160,10 +172,10 @@ Simultaneamente, a barra inferior de digitação acumulou 4 botões além do cam
<!-- aliare-sdlc:tasks:inicio --> <!-- aliare-sdlc:tasks:inicio -->
| Task | Descrição | Status | Estimativa | | Task | Descrição | Status | Estimativa |
| :--- | :--- | :--- | :--- | | :--- | :--- | :--- | :--- |
| Task 1 | [UI/UX Layout]: Reorganização da barra inferior do chat, botão dinâmico Voz/Envio e realocação do botão TUI para o cabeçalho | Pendente | 1,0 h | | Task 1 | [UI/UX Layout]: Reorganização da barra inferior do chat, botão dinâmico Voz/Envio e realocação do botão TUI para o cabeçalho | Concluída | 1,0 h |
| Task 2 | [FRONT]: Remoção de chips automáticos, catálogo de arquivos em memória e modal de downloads sob demanda (botão 📥, menu + e comando /downloads) | Pendente | 1,0 h | | Task 2 | [FRONT]: Remoção de chips automáticos, catálogo de arquivos em memória e modal de downloads sob demanda (botão 📥, menu + e comando /downloads) | Concluída | 1,0 h |
| Task 3 | [DEPLOY]: Esteira autônoma de build OTA v1.0.25, Docker ARM64, rollout no K3s via Maestri Shell e sincronização local | Pendente | 0,5 h | | Task 3 | [DEPLOY]: Esteira autônoma de build OTA v1.0.25, Docker ARM64, rollout no K3s via Maestri Shell e sincronização local | Concluída | 0,5 h |
| Task 4 | [DOC]: Atualização da capability e evidências | Pendente | 0,5 h | | Task 4 | [DOC]: Atualização da capability e evidências | Concluída | 0,5 h |
<!-- aliare-sdlc:tasks:fim --> <!-- aliare-sdlc:tasks:fim -->
## Capabilities Afetadas ## Capabilities Afetadas
@ -185,5 +197,6 @@ Nenhum. A reorganização de layout e o catálogo em memória de arquivos operam
## Rastreabilidade ## Rastreabilidade
- **Manifesto:** [manifesto.md](manifesto.md) - **Manifesto:** [manifesto.md](manifesto.md)
- **Evidências:** [evidence/evidence.md](evidence/evidence.md)
- **Change anterior (Base do protocolo de arquivos):** [../0-download-arquivos-terminal-app/spec.md](../0-download-arquivos-terminal-app/spec.md) - **Change anterior (Base do protocolo de arquivos):** [../0-download-arquivos-terminal-app/spec.md](../0-download-arquivos-terminal-app/spec.md)
- **Capability:** [../../capabilities/maestri-remote.md](../../capabilities/maestri-remote.md) - **Capability:** [../../capabilities/maestri-remote.md](../../capabilities/maestri-remote.md)

View File

@ -1,6 +1,6 @@
{ {
"name": "maestri-remote-agent", "name": "maestri-remote-agent",
"version": "1.0.26", "version": "1.0.27",
"type": "module", "type": "module",
"description": "Gateway Local do Maestri Remote para estações de trabalho", "description": "Gateway Local do Maestri Remote para estações de trabalho",
"bin": { "bin": {

View File

@ -100,6 +100,19 @@ const chatTuiHint = document.getElementById('chat-tui-hint');
const chatTuiOptionsEl = document.getElementById('chat-tui-options'); const chatTuiOptionsEl = document.getElementById('chat-tui-options');
const chatTuiKeypad = document.querySelector('.chat-tui-keypad'); const chatTuiKeypad = document.querySelector('.chat-tui-keypad');
const btnTuiToggle = document.getElementById('btn-tui-toggle'); const btnTuiToggle = document.getElementById('btn-tui-toggle');
const btnSessionDownloads = document.getElementById('btn-session-downloads');
const sessionDownloadsBadge = document.getElementById('session-downloads-badge');
const btnMenuDownloads = document.getElementById('btn-menu-downloads');
const sessionDownloadsModal = document.getElementById('session-downloads-modal');
const btnCloseSessionDownloads = document.getElementById('btn-close-session-downloads');
const sessionDownloadsList = document.getElementById('session-downloads-list');
const sessionDownloadsEmpty = document.getElementById('session-downloads-empty');
const sessionDownloadsCount = document.getElementById('session-downloads-count');
const btnChatSend = document.getElementById('btn-chat-send');
// Catálogo em memória de arquivos citados por chat/estação
const sessionFilesCatalog = new Map(); // path -> { path, name, ext, timestamp, source }
window.sessionFilesCatalog = sessionFilesCatalog;
// Sistema de Notificações com Mute Granular por Agente (Default: ATIVADO) // Sistema de Notificações com Mute Granular por Agente (Default: ATIVADO)
const NOTIF_MUTED_STORAGE_KEY = 'maestri_terminal_notif_muted'; const NOTIF_MUTED_STORAGE_KEY = 'maestri_terminal_notif_muted';
@ -1404,7 +1417,7 @@ function handleStationMessage(pin, msg) {
break; break;
case 'FILE_READ_RESP': case 'FILE_READ_RESP':
document.querySelectorAll('.btn-file-chip').forEach(btn => { document.querySelectorAll('.btn-file-chip, .btn-session-download-action').forEach(btn => {
const btnPath = btn.getAttribute('data-path'); const btnPath = btn.getAttribute('data-path');
if (btnPath === msg.path || (msg.name && btnPath && btnPath.endsWith(msg.name))) { if (btnPath === msg.path || (msg.name && btnPath && btnPath.endsWith(msg.name))) {
btn.classList.remove('loading'); btn.classList.remove('loading');
@ -2074,6 +2087,7 @@ function openChatWithAgent(agentName, pin, machineName) {
chatInput.value = ''; chatInput.value = '';
setTimeout(() => chatInput.focus(), 150); setTimeout(() => chatInput.focus(), 150);
} }
updateInputActionButtonState();
// Marca respostas como lidas ao abrir o chat com o agente // Marca respostas como lidas ao abrir o chat com o agente
markAgentResponsesAsRead(agentName, activeChatPin); markAgentResponsesAsRead(agentName, activeChatPin);
@ -2094,6 +2108,7 @@ function closeChat() {
if (typeof window._stopAnyActiveVoiceSession === 'function') { if (typeof window._stopAnyActiveVoiceSession === 'function') {
window._stopAnyActiveVoiceSession(); window._stopAnyActiveVoiceSession();
} }
closeSessionDownloadsModal();
clearInterval(terminalPollInterval); clearInterval(terminalPollInterval);
terminalPollInterval = null; terminalPollInterval = null;
toggleAttachMenu(false); toggleAttachMenu(false);
@ -2176,6 +2191,126 @@ function extractFilePaths(text) {
} }
window.extractFilePaths = extractFilePaths; window.extractFilePaths = extractFilePaths;
// Catálogo e Downloads Sob Demanda
function registerSessionFiles(filePaths, source = 'text') {
if (!Array.isArray(filePaths) || filePaths.length === 0) return;
filePaths.forEach(filePath => {
if (!filePath || typeof filePath !== 'string') return;
const normalized = filePath.replace(/\\/g, '/').trim();
if (!normalized) return;
const baseName = normalized.split('/').pop() || normalized;
const ext = baseName.includes('.') ? baseName.split('.').pop().toLowerCase() : '';
sessionFilesCatalog.set(normalized, {
path: normalized,
name: baseName,
ext,
timestamp: Date.now(),
source
});
});
updateSessionDownloadsBadge();
}
window.registerSessionFiles = registerSessionFiles;
function updateSessionDownloadsBadge() {
if (!sessionDownloadsBadge) return;
const total = sessionFilesCatalog.size;
if (total > 0) {
sessionDownloadsBadge.textContent = String(total);
sessionDownloadsBadge.style.display = 'inline-flex';
} else {
sessionDownloadsBadge.style.display = 'none';
}
if (sessionDownloadsCount) {
sessionDownloadsCount.textContent = `${total} ${total === 1 ? 'arquivo detectado' : 'arquivos detectados'}`;
}
}
window.updateSessionDownloadsBadge = updateSessionDownloadsBadge;
function getFileCategoryIcon(ext) {
const imageExts = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'ico'];
const docExts = ['pdf', 'txt', 'md', 'markdown', 'log', 'csv', 'json', 'xml', 'yaml', 'yml'];
const codeExts = ['js', 'mjs', 'ts', 'html', 'css', 'sh', 'ps1', 'bat', 'cmd'];
const pkgExts = ['zip', 'apk', 'tar', 'gz', '7z'];
if (imageExts.includes(ext)) return '🖼️';
if (pkgExts.includes(ext)) return '📦';
if (codeExts.includes(ext)) return '💻';
if (docExts.includes(ext)) return '📄';
return '📄';
}
function openSessionDownloadsModal() {
if (!sessionDownloadsModal) return;
updateSessionDownloadsBadge();
if (sessionDownloadsList && sessionDownloadsEmpty) {
sessionDownloadsList.innerHTML = '';
if (sessionFilesCatalog.size === 0) {
sessionDownloadsEmpty.style.display = 'block';
sessionDownloadsList.style.display = 'none';
} else {
sessionDownloadsEmpty.style.display = 'none';
sessionDownloadsList.style.display = 'flex';
const files = Array.from(sessionFilesCatalog.values()).sort((a, b) => b.timestamp - a.timestamp);
files.forEach(file => {
const itemEl = document.createElement('div');
itemEl.className = 'session-download-item';
const icon = getFileCategoryIcon(file.ext);
itemEl.innerHTML = `
<div class="session-download-item-info">
<span class="session-download-item-icon">${icon}</span>
<div class="session-download-item-details">
<div class="session-download-item-name" title="${escapeHtml(file.name)}">${escapeHtml(file.name)}</div>
<div class="session-download-item-path" title="${escapeHtml(file.path)}">${escapeHtml(file.path)}</div>
</div>
</div>
<button type="button" class="btn-session-download-action" data-path="${escapeHtml(file.path)}">
Ver / Baixar
</button>
`;
const actionBtn = itemEl.querySelector('.btn-session-download-action');
if (actionBtn) {
actionBtn.addEventListener('click', (e) => {
e.preventDefault();
actionBtn.classList.add('loading');
requestFileDownload(file.path);
});
}
sessionDownloadsList.appendChild(itemEl);
});
}
}
sessionDownloadsModal.style.display = 'flex';
}
window.openSessionDownloadsModal = openSessionDownloadsModal;
function closeSessionDownloadsModal() {
if (sessionDownloadsModal) {
sessionDownloadsModal.style.display = 'none';
}
}
window.closeSessionDownloadsModal = closeSessionDownloadsModal;
function updateInputActionButtonState() {
if (!btnVoice || !btnChatSend) return;
const hasText = chatInput && chatInput.value && chatInput.value.trim().length > 0;
const hasAttachments = Array.isArray(currentAttachments) && currentAttachments.length > 0;
if (hasText || hasAttachments) {
btnVoice.style.display = 'none';
btnChatSend.style.display = 'inline-flex';
} else {
btnVoice.style.display = 'inline-flex';
btnChatSend.style.display = 'none';
}
}
window.updateInputActionButtonState = updateInputActionButtonState;
function renderFileChips(filePaths) { function renderFileChips(filePaths) {
const container = document.createElement('div'); const container = document.createElement('div');
container.className = 'file-chips-container'; container.className = 'file-chips-container';
@ -3631,8 +3766,7 @@ function updateTerminalSnapshotInPlace(terminalText, isThinking, isPausedParam =
const filePaths = extractFilePaths(terminalText); const filePaths = extractFilePaths(terminalText);
if (filePaths.length > 0) { if (filePaths.length > 0) {
const chipsContainer = renderFileChips(filePaths); registerSessionFiles(filePaths, 'terminal');
card.appendChild(chipsContainer);
} }
const prevScrollTop = chatMessagesEl.scrollTop; const prevScrollTop = chatMessagesEl.scrollTop;
@ -3659,18 +3793,14 @@ function updateTerminalSnapshotInPlace(terminalText, isThinking, isPausedParam =
pill.textContent = pillText; pill.textContent = pillText;
} }
// Atualiza os chips de arquivos no snapshot in-place // Registra caminhos no catálogo da sessão sob demanda
const existingChips = card.querySelector('.file-chips-container'); const existingChips = card.querySelector('.file-chips-container');
if (existingChips) {
existingChips.remove();
}
const filePaths = extractFilePaths(terminalText); const filePaths = extractFilePaths(terminalText);
if (filePaths.length > 0) { if (filePaths.length > 0) {
const newChips = renderFileChips(filePaths); registerSessionFiles(filePaths, 'terminal');
if (existingChips) {
existingChips.replaceWith(newChips);
} else {
card.appendChild(newChips);
}
} else if (existingChips) {
existingChips.remove();
} }
return true; return true;
@ -3804,12 +3934,14 @@ function captureAndSendScreenStateSnapshot(agentName, reason = 'state_change') {
} }
// Heartbeat leve a cada 30 segundos para manter snapshot atualizado enquanto ativo // Heartbeat leve a cada 30 segundos para manter snapshot atualizado enquanto ativo
const _snapInterval = setInterval(() => { const _chatHeartbeatTimer = setInterval(() => {
if (activeChatAgent && chatDrawer && chatDrawer.style.display === 'flex') { if (activeChatAgent && chatDrawer && chatDrawer.style.display === 'flex') {
captureAndSendScreenStateSnapshot(activeChatAgent, 'heartbeat_30s'); captureAndSendScreenStateSnapshot(activeChatAgent, 'heartbeat_30s');
} }
}, 30000); }, 30000);
if (_snapInterval && typeof _snapInterval.unref === 'function') _snapInterval.unref(); if (_chatHeartbeatTimer && typeof _chatHeartbeatTimer.unref === 'function') {
_chatHeartbeatTimer.unref();
}
function renderChatMessages(forceScroll = false) { function renderChatMessages(forceScroll = false) {
if (!chatMessagesEl || !activeChatAgent) return; if (!chatMessagesEl || !activeChatAgent) return;
@ -3853,8 +3985,7 @@ function renderChatMessages(forceScroll = false) {
const filePaths = extractFilePaths(terminalSnapshotText); const filePaths = extractFilePaths(terminalSnapshotText);
if (filePaths.length > 0) { if (filePaths.length > 0) {
const chipsContainer = renderFileChips(filePaths); registerSessionFiles(filePaths, 'terminal');
bubble.appendChild(chipsContainer);
} }
chatMessagesEl.appendChild(bubble); chatMessagesEl.appendChild(bubble);
@ -3866,8 +3997,7 @@ function renderChatMessages(forceScroll = false) {
if (item.role === 'agent') { if (item.role === 'agent') {
const filePaths = extractFilePaths(item.text); const filePaths = extractFilePaths(item.text);
if (filePaths.length > 0) { if (filePaths.length > 0) {
const chipsContainer = renderFileChips(filePaths); registerSessionFiles(filePaths, 'chat');
bubble.appendChild(chipsContainer);
} }
} }
@ -4355,6 +4485,7 @@ function setupChatEvents() {
if (index >= 0 && index < currentAttachments.length) { if (index >= 0 && index < currentAttachments.length) {
currentAttachments.splice(index, 1); currentAttachments.splice(index, 1);
renderAttachmentPreview(); renderAttachmentPreview();
updateInputActionButtonState();
} }
} }
@ -4362,6 +4493,7 @@ function setupChatEvents() {
currentAttachments = []; currentAttachments = [];
renderAttachmentPreview(); renderAttachmentPreview();
clearFileInputs(); clearFileInputs();
updateInputActionButtonState();
} }
async function handleFilesSelected(files) { async function handleFilesSelected(files) {
@ -4402,6 +4534,7 @@ function setupChatEvents() {
renderAttachmentPreview(); renderAttachmentPreview();
clearFileInputs(); clearFileInputs();
updateInputActionButtonState();
} }
async function handleFileSelected(file) { async function handleFileSelected(file) {
@ -4444,6 +4577,13 @@ function setupChatEvents() {
}); });
} }
if (btnMenuDownloads) {
btnMenuDownloads.addEventListener('click', () => {
toggleAttachMenu(false);
openSessionDownloadsModal();
});
}
const bindFileInput = (inputEl) => { const bindFileInput = (inputEl) => {
if (!inputEl) return; if (!inputEl) return;
inputEl.addEventListener('change', (e) => { inputEl.addEventListener('change', (e) => {
@ -4629,6 +4769,7 @@ function setupChatEvents() {
} }
if (chatInput) { if (chatInput) {
chatInput.value = (voiceBasePrefix + voiceAccumulatedTranscript + voiceSessionFinal + interimTranscript).trimStart(); chatInput.value = (voiceBasePrefix + voiceAccumulatedTranscript + voiceSessionFinal + interimTranscript).trimStart();
updateInputActionButtonState();
} }
}; };
@ -4723,6 +4864,33 @@ function setupChatEvents() {
window._stopAnyActiveVoiceSession = stopAnyActiveVoiceSession; window._stopAnyActiveVoiceSession = stopAnyActiveVoiceSession;
} }
if (btnSessionDownloads) {
btnSessionDownloads.addEventListener('click', (e) => {
e.preventDefault();
openSessionDownloadsModal();
});
}
if (btnCloseSessionDownloads) {
btnCloseSessionDownloads.addEventListener('click', (e) => {
e.preventDefault();
closeSessionDownloadsModal();
});
}
if (sessionDownloadsModal) {
sessionDownloadsModal.addEventListener('click', (e) => {
if (e.target === sessionDownloadsModal) {
closeSessionDownloadsModal();
}
});
}
if (chatInput) {
chatInput.addEventListener('input', updateInputActionButtonState);
chatInput.addEventListener('change', updateInputActionButtonState);
}
if (chatForm) { if (chatForm) {
chatForm.addEventListener('submit', (e) => { chatForm.addEventListener('submit', (e) => {
e.preventDefault(); e.preventDefault();
@ -4731,6 +4899,15 @@ function setupChatEvents() {
} }
if (!chatInput) return; if (!chatInput) return;
const text = chatInput.value.trim(); const text = chatInput.value.trim();
const trimmedLower = text.toLowerCase();
if (trimmedLower === '/downloads' || trimmedLower === '/download' || trimmedLower === '/arquivos' || trimmedLower === '/arquivo') {
chatInput.value = '';
updateInputActionButtonState();
openSessionDownloadsModal();
return;
}
if (!text && currentAttachments.length === 0) return; if (!text && currentAttachments.length === 0) return;
if (!activeChatAgent) return; if (!activeChatAgent) return;
@ -4792,6 +4969,7 @@ function setupChatEvents() {
clearAllAttachments(); clearAllAttachments();
chatInput.value = ''; chatInput.value = '';
updateInputActionButtonState();
isWaitingChatReply = true; isWaitingChatReply = true;
hadThinkingDuringReply = false; hadThinkingDuringReply = false;
@ -5296,5 +5474,7 @@ function initOtaChecker() {
// Ignora erro de rede temporário // Ignora erro de rede temporário
} }
}, 30000); }, 30000);
if (_otaInterval && typeof _otaInterval.unref === 'function') _otaInterval.unref(); if (_otaInterval && typeof _otaInterval.unref === 'function') {
_otaInterval.unref();
}
} }

Binary file not shown.

Binary file not shown.

View File

@ -1,9 +1,9 @@
{ {
"version": "1.0.26", "version": "1.0.27",
"buildId": "31fb927c", "buildId": "49785205",
"releasedAt": "2026-11-21T19:26:36.703Z", "releasedAt": "2026-11-21T19:43:00.809Z",
"bundleUrl": "/bundles/bundle-1.0.26.zip", "bundleUrl": "/bundles/bundle-1.0.27.zip",
"latestUrl": "/bundles/bundle-latest.zip", "latestUrl": "/bundles/bundle-latest.zip",
"checksum": "1a997a4f1238ef0177eb69e3d35d60c3e8a34891c1caf1c86cc63e224698d06f", "checksum": "1be6eda404c2600d5156e9a66f9eaae737e9f9a3909fe07f1ccc3384c2e04c7d",
"sizeBytes": 67845 "sizeBytes": 69527
} }

View File

@ -254,6 +254,31 @@
</div> </div>
</div> </div>
<!-- Modal: Arquivos da Estação (Downloads Sob Demanda) -->
<div id="session-downloads-modal" class="modal-backdrop" style="display: none;">
<div class="modal-card session-downloads-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;">📥</span>
<div style="overflow: hidden;">
<h3 style="margin: 0; font-size: 0.95rem;">Arquivos da Estação</h3>
<span id="session-downloads-count" style="font-size: 0.72rem; color: #94a3b8;">0 arquivos detectados</span>
</div>
</div>
<button id="btn-close-session-downloads" class="btn-icon" aria-label="Fechar">&times;</button>
</div>
<div class="session-downloads-body" id="session-downloads-body">
<div id="session-downloads-empty" class="session-downloads-empty">
<span style="font-size: 2.2rem; display: block; margin-bottom: 0.5rem;">📂</span>
<strong style="color: #e2e8f0; display: block; margin-bottom: 0.25rem;">Nenhum arquivo detectado</strong>
<p style="font-size: 0.8rem; margin: 0; line-height: 1.4; color: #94a3b8;">Peça ao agente para citar, gerar ou manipular arquivos no terminal para visualizá-los ou baixá-los aqui.</p>
</div>
<div id="session-downloads-list" class="session-downloads-list" style="display: none;"></div>
</div>
</div>
</div>
<!-- Bottom Sheet / Drawer: Chat Interativo com Agente --> <!-- Bottom Sheet / Drawer: Chat Interativo com Agente -->
<div id="chat-drawer" class="chat-drawer" style="display: none;"> <div id="chat-drawer" class="chat-drawer" style="display: none;">
<div class="chat-backdrop" id="chat-backdrop" onclick="window.closeChat && window.closeChat()"></div> <div class="chat-backdrop" id="chat-backdrop" onclick="window.closeChat && window.closeChat()"></div>
@ -267,6 +292,13 @@
</div> </div>
</div> </div>
<div style="display: flex; align-items: center; gap: 0.25rem;"> <div style="display: flex; align-items: center; gap: 0.25rem;">
<button id="btn-session-downloads" class="btn-icon btn-session-downloads" aria-label="Arquivos da Estação (Downloads)" title="Arquivos da Estação" style="position: relative; min-width: 44px; min-height: 44px; display: inline-flex; align-items: center; justify-content: center; cursor: pointer; touch-action: manipulation; z-index: 30;">
<span style="font-size: 1.1rem; line-height: 1;">📥</span>
<span id="session-downloads-badge" class="session-downloads-badge" style="display: none;">0</span>
</button>
<button type="button" id="btn-tui-toggle" class="btn-icon btn-tui-toggle-header" aria-label="Teclas de navegação do terminal (Setas / Enter / Esc)" title="Teclas de Menu (↑ ↓ Enter Esc)" style="min-width: 44px; min-height: 44px; display: inline-flex; align-items: center; justify-content: center; cursor: pointer; touch-action: manipulation; z-index: 30;">
<span style="font-size: 1.05rem; line-height: 1;">⌨️</span>
</button>
<button id="chat-notif-toggle-btn" class="btn-icon btn-chat-notif-toggle muted" aria-label="Alternar Notificações" title="Alternar Notificações" style="font-size: 1.1rem; min-width: 44px; min-height: 44px; display: inline-flex; align-items: center; justify-content: center; cursor: pointer; touch-action: manipulation; z-index: 30;">🔕</button> <button id="chat-notif-toggle-btn" class="btn-icon btn-chat-notif-toggle muted" aria-label="Alternar Notificações" title="Alternar Notificações" style="font-size: 1.1rem; min-width: 44px; min-height: 44px; display: inline-flex; align-items: center; justify-content: center; cursor: pointer; touch-action: manipulation; z-index: 30;">🔕</button>
<button type="button" id="btn-restart-terminal" class="btn-icon btn-restart-terminal" aria-label="Reiniciar / Recarregar terminal via Maestri" title="Reiniciar / Recarregar terminal via Maestri" style="min-width: 44px; min-height: 44px; display: inline-flex; align-items: center; justify-content: center; cursor: pointer; touch-action: manipulation; z-index: 30;"> <button type="button" id="btn-restart-terminal" class="btn-icon btn-restart-terminal" aria-label="Reiniciar / Recarregar terminal via Maestri" title="Reiniciar / Recarregar terminal via Maestri" style="min-width: 44px; min-height: 44px; display: inline-flex; align-items: center; justify-content: center; cursor: pointer; touch-action: manipulation; z-index: 30;">
<svg style="width:18px;height:18px;color:#f59e0b" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <svg style="width:18px;height:18px;color:#f59e0b" fill="none" viewBox="0 0 24 24" stroke="currentColor">
@ -336,7 +368,7 @@
<!-- Backdrop para fechar o menu de anexo flutuante --> <!-- Backdrop para fechar o menu de anexo flutuante -->
<div id="attach-backdrop" class="attach-backdrop" style="display: none;"></div> <div id="attach-backdrop" class="attach-backdrop" style="display: none;"></div>
<!-- Menu Flutuante de Ações de Anexo (Câmera / Galeria / Arquivos) --> <!-- Menu Flutuante de Ações de Anexo (Câmera / Galeria / Arquivos / Downloads) -->
<div id="attach-menu" class="attach-menu-popover" style="display: none;"> <div id="attach-menu" class="attach-menu-popover" style="display: none;">
<button type="button" class="attach-menu-item" id="btn-attach-camera"> <button type="button" class="attach-menu-item" id="btn-attach-camera">
<span class="attach-item-icon camera"> <span class="attach-item-icon camera">
@ -363,6 +395,10 @@
</span> </span>
<span class="attach-item-label">Documentos / Arquivos</span> <span class="attach-item-label">Documentos / Arquivos</span>
</button> </button>
<button type="button" class="attach-menu-item" id="btn-menu-downloads">
<span class="attach-item-icon downloads">📥</span>
<span class="attach-item-label">Arquivos da Estação (Downloads)</span>
</button>
</div> </div>
<!-- Preview de Anexo Flutuante antes do envio (Suporte a múltiplos itens) --> <!-- Preview de Anexo Flutuante antes do envio (Suporte a múltiplos itens) -->
@ -382,7 +418,7 @@
</div> </div>
</div> </div>
<!-- Barra de Input com Anexo, Voz e Envio --> <!-- Barra de Input com Anexo, Entrada e Ação Dinâmica (Voz / Envio) -->
<form class="chat-input-bar" id="chat-form"> <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 e Arquivos Gerais -->
<input type="file" id="chat-camera-input" style="display: none;" accept="image/*" capture="environment"> <input type="file" id="chat-camera-input" style="display: none;" accept="image/*" capture="environment">
@ -395,19 +431,15 @@
</svg> </svg>
</button> </button>
<input type="text" id="chat-input" placeholder="Digite ou fale para o agente..." autocomplete="off">
<button type="button" id="btn-voice" class="btn-input-action" aria-label="Gravar voz / Transcrição" title="Falar"> <button type="button" id="btn-voice" class="btn-input-action" aria-label="Gravar voz / Transcrição" title="Falar">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" style="width:20px;height:20px"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" style="width:20px;height:20px">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z" /> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11a7 7 0 01-7 7m0 0a7 7 0 01-7-7m7 7v4m0 0H8m4 0h4m-4-8a3 3 0 01-3-3V5a3 3 0 116 0v6a3 3 0 01-3 3z" />
</svg> </svg>
</button> </button>
<button type="button" id="btn-tui-toggle" class="btn-input-action" aria-label="Teclas de navegação do terminal (Setas / Enter / Esc)" title="Teclas de Menu (↑ ↓ Enter Esc)"> <button type="submit" id="btn-chat-send" class="btn-send" aria-label="Enviar mensagem" style="display: none;">
<span style="font-size: 0.95rem; line-height: 1;">⌨️</span>
</button>
<input type="text" id="chat-input" placeholder="Digite ou fale para o agente..." autocomplete="off">
<button type="submit" id="btn-chat-send" class="btn-send" aria-label="Enviar mensagem">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" style="width:18px;height:18px"> <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" style="width:18px;height:18px">
<path d="M5 12h14m-7-7l7 7-7 7" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/> <path d="M5 12h14m-7-7l7 7-7 7" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
</svg> </svg>

Binary file not shown.

View File

@ -1358,10 +1358,11 @@ main {
background: var(--bg-card); background: var(--bg-card);
border: 1px solid var(--border); border: 1px solid var(--border);
border-radius: 9999px; border-radius: 9999px;
padding: 0.6rem 0.85rem; padding: 0.65rem 1rem;
color: var(--text-primary); color: var(--text-primary);
font-size: 0.9rem; font-size: 0.92rem;
outline: none; outline: none;
transition: border-color 0.2s ease, box-shadow 0.2s ease;
} }
.chat-input-bar input:focus { .chat-input-bar input:focus {
@ -1987,9 +1988,10 @@ main {
color: #fcd34d; color: #fcd34d;
} }
#btn-tui-toggle.active { #btn-tui-toggle.active,
background: rgba(56, 189, 248, 0.2); .btn-tui-toggle-header.active {
border-color: rgba(56, 189, 248, 0.55); background: rgba(56, 189, 248, 0.25);
border-color: rgba(56, 189, 248, 0.6);
color: #38bdf8; color: #38bdf8;
} }
@ -2301,3 +2303,145 @@ main {
gap: 0.5rem; gap: 0.5rem;
align-items: center; align-items: center;
} }
/* ============================================================
Downloads Sob Demanda da Estação (Modal, Badge e Catálogo)
============================================================ */
.session-downloads-badge {
position: absolute;
top: 3px;
right: 3px;
background: #0284c7;
color: #ffffff;
font-size: 0.65rem;
font-weight: 700;
min-width: 17px;
height: 17px;
border-radius: 9999px;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0 4px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.4);
border: 1px solid rgba(255, 255, 255, 0.25);
pointer-events: none;
}
.attach-item-icon.downloads {
background: rgba(56, 189, 248, 0.15);
color: #38bdf8;
font-size: 1.15rem;
}
.session-downloads-card {
max-width: 480px;
max-height: 80vh;
display: flex;
flex-direction: column;
}
.session-downloads-body {
flex: 1;
overflow-y: auto;
margin-top: 0.75rem;
max-height: 58vh;
-webkit-overflow-scrolling: touch;
}
.session-downloads-empty {
text-align: center;
padding: 2.5rem 1.5rem;
}
.session-downloads-list {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.session-download-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
background: rgba(30, 41, 59, 0.65);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 10px;
padding: 0.6rem 0.75rem;
transition: background 0.15s ease, border-color 0.15s ease;
}
.session-download-item:hover {
background: rgba(30, 41, 59, 0.9);
border-color: rgba(56, 189, 248, 0.3);
}
.session-download-item-info {
display: flex;
align-items: center;
gap: 0.6rem;
min-width: 0;
flex: 1;
}
.session-download-item-icon {
font-size: 1.25rem;
flex-shrink: 0;
}
.session-download-item-details {
min-width: 0;
flex: 1;
}
.session-download-item-name {
font-size: 0.85rem;
font-weight: 600;
color: #f1f5f9;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.session-download-item-path {
font-size: 0.72rem;
color: #94a3b8;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.btn-session-download-action {
display: inline-flex;
align-items: center;
gap: 0.3rem;
background: rgba(14, 165, 233, 0.15);
border: 1px solid rgba(56, 189, 248, 0.4);
color: #38bdf8;
font-size: 0.78rem;
font-weight: 600;
padding: 0.4rem 0.7rem;
border-radius: 8px;
cursor: pointer;
flex-shrink: 0;
transition: all 0.2s ease;
touch-action: manipulation;
}
.btn-session-download-action:active {
transform: scale(0.96);
background: rgba(14, 165, 233, 0.3);
}
.btn-session-download-action.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-session-download-action.loading::after {
content: '...';
}

View File

@ -0,0 +1,164 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { JSDOM } from 'jsdom';
import EventEmitter from 'node:events';
class MockSocket extends EventEmitter {
constructor() {
super();
this.OPEN = 1;
this.readyState = 1;
this.sent = [];
}
send(data) {
this.sent.push(data);
}
}
test('Frontend - Downloads Sob Demanda, Catálogo em Memória e Alternância Voz/Envio', async () => {
const html = `
<!DOCTYPE html>
<html>
<body>
<div class="chat-header">
<button id="btn-session-downloads">
<span id="session-downloads-badge" style="display: none;">0</span>
</button>
<button type="button" id="btn-tui-toggle">⌨️</button>
<button id="chat-notif-toggle-btn">🔕</button>
<button id="btn-restart-terminal"></button>
<button id="btn-refresh-chat"></button>
<button id="btn-close-chat">&times;</button>
</div>
<div id="session-downloads-modal" style="display: none;">
<span id="session-downloads-count">0 arquivos detectados</span>
<button id="btn-close-session-downloads">&times;</button>
<div id="session-downloads-empty" style="display: block;"></div>
<div id="session-downloads-list" style="display: none;"></div>
</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>
<button id="btn-close-file-preview">&times;</button>
</div>
<div id="attach-menu" style="display: none;">
<button type="button" id="btn-attach-camera"></button>
<button type="button" id="btn-attach-gallery"></button>
<button type="button" id="btn-attach-file"></button>
<button type="button" id="btn-menu-downloads"></button>
</div>
<div id="attach-backdrop" style="display: none;"></div>
<div class="chat-messages" id="chat-messages"></div>
<form class="chat-input-bar" id="chat-form">
<input type="file" id="chat-camera-input" style="display: none;">
<input type="file" id="chat-gallery-input" style="display: none;">
<input type="file" id="chat-file-input" style="display: none;">
<button type="button" id="btn-attach"></button>
<input type="text" id="chat-input" placeholder="Digite...">
<button type="button" id="btn-voice" style="display: inline-flex;"></button>
<button type="submit" id="btn-chat-send" style="display: none;"></button>
</form>
</body>
</html>
`;
const dom = new JSDOM(html);
global.window = dom.window;
global.document = dom.window.document;
global.WebSocket = MockSocket;
// Importa a lógica do frontend
await import('../public/app.js');
const {
sessionFilesCatalog,
registerSessionFiles,
updateSessionDownloadsBadge,
openSessionDownloadsModal,
closeSessionDownloadsModal,
updateInputActionButtonState
} = dom.window;
assert.ok(sessionFilesCatalog instanceof Map, 'sessionFilesCatalog deve ser uma instância de Map');
assert.equal(typeof registerSessionFiles, 'function', 'registerSessionFiles deve ser função');
assert.equal(typeof openSessionDownloadsModal, 'function', 'openSessionDownloadsModal deve ser função');
assert.equal(typeof closeSessionDownloadsModal, 'function', 'closeSessionDownloadsModal deve ser função');
assert.equal(typeof updateInputActionButtonState, 'function', 'updateInputActionButtonState deve ser função');
const badge = dom.window.document.getElementById('session-downloads-badge');
const modal = dom.window.document.getElementById('session-downloads-modal');
const emptyEl = dom.window.document.getElementById('session-downloads-empty');
const listEl = dom.window.document.getElementById('session-downloads-list');
const chatInput = dom.window.document.getElementById('chat-input');
const btnVoice = dom.window.document.getElementById('btn-voice');
const btnSend = dom.window.document.getElementById('btn-chat-send');
const chatForm = dom.window.document.getElementById('chat-form');
// 1. Estado inicial de alternância Voz / Envio
updateInputActionButtonState();
assert.equal(btnVoice.style.display, 'inline-flex', 'Microfone deve estar visível com input vazio');
assert.equal(btnSend.style.display, 'none', 'Envio deve estar oculto com input vazio');
// Ao digitar texto no input:
chatInput.value = 'Olá agente';
updateInputActionButtonState();
assert.equal(btnVoice.style.display, 'none', 'Microfone deve sumir quando há texto');
assert.equal(btnSend.style.display, 'inline-flex', 'Botão de envio deve aparecer quando há texto');
// Ao limpar o input:
chatInput.value = '';
updateInputActionButtonState();
assert.equal(btnVoice.style.display, 'inline-flex', 'Microfone reaparece após limpar texto');
assert.equal(btnSend.style.display, 'none', 'Botão de envio oculta novamente');
// 2. Registro transparente de arquivos no catálogo da sessão
sessionFilesCatalog.clear();
assert.equal(sessionFilesCatalog.size, 0);
assert.equal(badge.style.display, 'none');
registerSessionFiles([
'docs/changes/0-ux-downloads-sob-demanda-layout-input/spec.md',
'evidence/screen.png',
'public/bundles/manifest.json'
], 'test');
assert.equal(sessionFilesCatalog.size, 3, 'Deve registrar 3 arquivos no catálogo');
assert.equal(badge.style.display, 'inline-flex', 'Badge deve ficar visível');
assert.equal(badge.textContent, '3', 'Badge deve exibir contagem 3');
// 3. Abertura do Modal de Downloads Sob Demanda
openSessionDownloadsModal();
assert.equal(modal.style.display, 'flex', 'Modal de downloads deve abrir com display flex');
assert.equal(emptyEl.style.display, 'none', 'Estado vazio deve ser ocultado');
assert.equal(listEl.style.display, 'flex', 'Lista de arquivos deve ser exibida');
const items = listEl.querySelectorAll('.session-download-item');
assert.equal(items.length, 3, 'Deve renderizar 3 itens na lista de downloads');
const actionBtn = items[0].querySelector('.btn-session-download-action');
assert.ok(actionBtn, 'Cada item deve ter botão de ação Ver / Baixar');
assert.ok(actionBtn.textContent.includes('Ver / Baixar'));
// Fechamento do modal
closeSessionDownloadsModal();
assert.equal(modal.style.display, 'none', 'Modal de downloads deve fechar');
// 4. Interceptação de comando /downloads no chatForm
chatInput.value = '/downloads';
const submitEvent = new dom.window.Event('submit', { cancelable: true });
chatForm.dispatchEvent(submitEvent);
assert.equal(chatInput.value, '', 'Input deve ser limpo ao executar comando /downloads');
assert.equal(modal.style.display, 'flex', 'Comando /downloads deve abrir o modal de downloads sob demanda');
closeSessionDownloadsModal();
});