maestri-remote/test/frontend-app.test.js

3455 lines
164 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { test, describe, beforeEach, afterEach } from 'node:test';
import assert from 'node:assert';
import fs from 'node:fs';
import path from 'node:path';
import { JSDOM } from 'jsdom';
describe('Suite de Testes Automatizados E2E do Frontend (Maestri Remote)', () => {
let dom;
let window;
let document;
let sentWsMessages = [];
let mockWsInstance;
let mockWsInstances = [];
afterEach(() => {
if (dom && dom.window) {
dom.window.close();
}
});
beforeEach(async () => {
sentWsMessages = [];
mockWsInstances = [];
const htmlContent = fs.readFileSync(path.resolve('public', 'index.html'), 'utf8');
const appJsContent = fs.readFileSync(path.resolve('public', 'app.js'), 'utf8');
// Cria ambiente JSDOM limpo
dom = new JSDOM(htmlContent, {
runScripts: 'dangerously',
url: 'https://remote.winicomw.ddnsfree.com/'
});
window = dom.window;
document = window.document;
// Mock do WebSocket
class MockWebSocket {
constructor(url) {
this.url = url;
this.readyState = 1; // OPEN
mockWsInstance = this;
mockWsInstances.push(this);
setTimeout(() => {
if (this.onopen) this.onopen();
}, 10);
}
send(data) {
sentWsMessages.push(JSON.parse(data));
}
close() {
this.readyState = 3;
if (this.onclose) this.onclose();
}
}
MockWebSocket.OPEN = 1;
window.WebSocket = MockWebSocket;
// Sessão autenticada mockada padrão para os testes de fluxo de estação/chat
window.localStorage.setItem('maestri_auth_token', 'mock-jwt-token');
window.localStorage.setItem('maestri_user', JSON.stringify({
id: 'mock-user-1',
name: 'Operador Teste',
email: 'teste@example.com'
}));
// Mock do fetch e push
window.fetch = async (url) => {
const target = String(url || '');
if (target.includes('/api/auth/me')) {
return {
ok: true,
status: 200,
json: async () => ({
user: { id: 'mock-user-1', name: 'Operador Teste', email: 'teste@example.com' }
}),
text: async () => ''
};
}
if (target.includes('/api/stations')) {
return {
ok: true,
status: 200,
json: async () => ({ stations: [] }),
text: async () => ''
};
}
return {
ok: true,
status: 200,
json: async () => ({ status: 'ok', buildId: 'test-123', version: '1.0.2' }),
text: async () => ''
};
};
// Mock do Web Speech API
class MockSpeechRecognition {
constructor() {
this.lang = '';
this.continuous = false;
this.interimResults = false;
this.onstart = null;
this.onresult = null;
this.onerror = null;
this.onend = null;
this.started = false;
MockSpeechRecognition.instance = this;
}
start() {
this.started = true;
if (this.onstart) this.onstart();
}
stop() {
this.started = false;
if (this.onend) this.onend();
}
abort() {
this.started = false;
if (this.onend) this.onend();
}
}
MockSpeechRecognition.instance = null;
window.SpeechRecognition = MockSpeechRecognition;
window.webkitSpeechRecognition = MockSpeechRecognition;
// Injeta o script app.js no DOM e aguarda inicialização assíncrona (auth/me + stations)
const scriptEl = document.createElement('script');
scriptEl.textContent = appJsContent;
document.body.appendChild(scriptEl);
await new Promise(r => setTimeout(r, 15));
});
test('1. Fluxo de Autenticação por PIN e Login', async () => {
await new Promise(r => setTimeout(r, 15));
const pinInput = document.getElementById('pin-input');
const btnConnect = document.getElementById('btn-connect');
const pinScreen = document.getElementById('pin-screen');
const appScreen = document.getElementById('app-screen');
assert.strictEqual(pinScreen.style.display, 'flex', 'Tela de PIN deve iniciar visível após sessão Google autenticada');
// Insere PIN e clica em conectar
pinInput.value = '712000';
btnConnect.click();
await new Promise(r => setTimeout(r, 30));
// Valida que AUTH_CLIENT foi enviado pelo WebSocket
const authMsg = sentWsMessages.find(m => m.type === 'AUTH_CLIENT');
assert.ok(authMsg, 'Deve ter enviado mensagem AUTH_CLIENT');
assert.strictEqual(authMsg.pin, '712000');
// Simula resposta AUTH_SUCCESS e INIT_STATE do servidor
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'Estacao Alpha',
agents: [
{ name: 'SREOracle #2', isSelf: false },
{ name: 'maestri-remote', isSelf: true }
],
pendingPrompts: []
})
});
assert.strictEqual(pinScreen.style.display, 'none', 'Tela de PIN deve ser ocultada');
assert.strictEqual(appScreen.style.display, 'block', 'Tela do App deve ficar visível');
assert.strictEqual(document.getElementById('machine-name').textContent, 'Estacao Alpha');
// Valida renderização dos chips de agentes
const pills = document.querySelectorAll('.agent-pill');
assert.strictEqual(pills.length, 1, 'Deve ter renderizado 1 pill de agente (isSelf ocultado)');
assert.ok(pills[0].textContent.includes('SREOracle #2'));
assert.strictEqual(Array.from(pills).some(p => p.textContent.includes('maestri-remote')), false, 'Terminal do daemon supervisor (isSelf) não deve ser renderizado');
});
test('2. Chat Interativo — Abertura, Envio, Resposta e Fechamento', async () => {
// Autentica previamente
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'Estacao Alpha',
agents: [{ name: 'SREOracle #2', isSelf: false }]
})
});
const chatDrawer = document.getElementById('chat-drawer');
const btnCloseChat = document.getElementById('btn-close-chat');
const chatBackdrop = document.getElementById('chat-backdrop');
const chatInput = document.getElementById('chat-input');
const chatForm = document.getElementById('chat-form');
const chatAgentName = document.getElementById('chat-agent-name');
assert.strictEqual(chatDrawer.style.display, 'none', 'Chat deve iniciar fechado');
// Clica no chip do agente para abrir o chat
const agentPill = document.querySelector('.agent-pill');
agentPill.click();
assert.strictEqual(chatDrawer.style.display, 'flex', 'Chat Drawer deve abrir ao tocar no agente');
assert.strictEqual(chatAgentName.textContent, 'SREOracle #2', 'Nome do agente correto no cabeçalho do chat');
// Valida que solicitou a saída real do terminal
const getTerminalMsg = sentWsMessages.find(m => m.type === 'GET_AGENT_TERMINAL');
assert.ok(getTerminalMsg, 'Deve ter solicitado GET_AGENT_TERMINAL');
assert.strictEqual(getTerminalMsg.agentName, 'SREOracle #2');
// Simula resposta com o output do terminal
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'SREOracle #2',
output: 'kubectl rollout status deployment... 1/1 Running'
})
});
// Valida que o snapshot do terminal é exibido e NÃO o texto fake "Olá! Sou o agente..."
const terminalSnapshot = document.querySelector('.terminal-snapshot');
assert.ok(terminalSnapshot, 'Deve renderizar a caixa de terminal real');
assert.ok(terminalSnapshot.textContent.includes('1/1 Running'));
assert.ok(!chatDrawer.textContent.includes('Olá! Sou o agente'), 'NÃO deve exibir saudação Olá! Sou o agente...');
// Digita mensagem e envia
chatInput.value = 'reinicie o pod';
chatForm.dispatchEvent(new window.Event('submit'));
// Valida envio no WebSocket
const sendMsg = sentWsMessages.find(m => m.type === 'CHAT_SEND');
assert.ok(sendMsg, 'Deve ter enviado mensagem CHAT_SEND');
assert.strictEqual(sendMsg.agentName, 'SREOracle #2');
assert.strictEqual(sendMsg.message, 'reinicie o pod');
// Valida que o balão do usuário e o typing indicator estão no DOM
const userBubble = document.querySelector('.chat-bubble.user');
assert.ok(userBubble, 'Balão do usuário deve estar renderizado');
assert.strictEqual(userBubble.textContent, 'reinicie o pod');
const typing = document.getElementById('chat-typing-indicator');
assert.ok(typing, 'Indicador de digitação do agente deve estar visível');
// Simula atualização do terminal do agente em resposta ao prompt do usuário
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'SREOracle #2',
output: 'kubectl rollout restart deployment... Pod em reinicializacao'
})
});
// Valida que o terminal e o balão do usuário estão presentes no DOM na ordem correta
const bubbles = Array.from(document.querySelectorAll('.chat-messages .chat-bubble'));
const userBubbleEl = bubbles.find(b => b.classList.contains('user'));
const terminalEl = bubbles.find(b => b.classList.contains('terminal-snapshot'));
assert.ok(userBubbleEl, 'Balão do usuário deve estar renderizado no chat');
assert.ok(terminalEl, 'Terminal snapshot deve estar renderizado no topo do chat');
const userBubbleIdx = bubbles.indexOf(userBubbleEl);
const terminalIdx = bubbles.indexOf(terminalEl);
assert.ok(terminalIdx < userBubbleIdx, 'O terminal snapshot atua como o console no topo do chat, e a mensagem do usuário fica logo abaixo');
// Simula resposta final do agente
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'CHAT_RESPONSE',
agentName: 'SREOracle #2',
response: 'Pod reiniciado com sucesso!'
})
});
const agentBubble = document.querySelectorAll('.chat-bubble.agent');
const lastAgentBubble = agentBubble[agentBubble.length - 1];
assert.strictEqual(lastAgentBubble.textContent, 'Pod reiniciado com sucesso!');
assert.strictEqual(document.getElementById('chat-typing-indicator'), null, 'Typing indicator deve ter sido removido');
// ==========================================
// TESTE CRÍTICO: Fechar pelo botão &times;
// ==========================================
btnCloseChat.click();
assert.strictEqual(chatDrawer.style.display, 'none', 'Chat Drawer DEVE fechar ao clicar no botão de fechar (&times;)');
// Reabre e testa fechar pelo backdrop
agentPill.click();
assert.strictEqual(chatDrawer.style.display, 'flex', 'Chat Drawer deve reabrir');
chatBackdrop.click();
assert.strictEqual(chatDrawer.style.display, 'none', 'Chat Drawer DEVE fechar ao clicar no backdrop');
// Reabre e testa fechar pela tecla Escape
agentPill.click();
assert.strictEqual(chatDrawer.style.display, 'flex');
window.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape' }));
assert.strictEqual(chatDrawer.style.display, 'none', 'Chat Drawer DEVE fechar ao pressionar a tecla Escape');
});
test('3. Gerenciamento e Alternância de Múltiplas Estações', async () => {
// Autentica na primeira estação
document.getElementById('pin-input').value = '111222';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
const btnAddStation = document.getElementById('btn-add-station');
const modalStation = document.getElementById('modal-station');
const btnCloseStationModal = document.getElementById('btn-close-station-modal');
const stationNameInput = document.getElementById('station-name-input');
const stationPinInput = document.getElementById('station-pin-input');
const btnSaveStation = document.getElementById('btn-save-station');
const stationSelect = document.getElementById('station-select');
assert.strictEqual(modalStation.style.display, 'none', 'Modal de nova estação inicia fechado');
// Abre o modal
btnAddStation.click();
assert.strictEqual(modalStation.style.display, 'flex', 'Modal deve abrir ao clicar em + Estação');
// Fecha pelo botão &times;
btnCloseStationModal.click();
assert.strictEqual(modalStation.style.display, 'none', 'Modal deve fechar ao clicar em fechar');
// Reabre e cadastra segunda estação (PC Empresa)
btnAddStation.click();
stationNameInput.value = 'PC Empresa';
stationPinInput.value = '999888';
btnSaveStation.click();
await new Promise(r => setTimeout(r, 30));
assert.strictEqual(modalStation.style.display, 'none', 'Modal deve fechar após salvar');
// Verifica que o select contém a nova estação
const options = Array.from(stationSelect.querySelectorAll('option'));
assert.ok(options.some(o => o.value === '999888' && (o.text || o.textContent).includes('PC Empresa')), 'Dropdown deve conter a nova estação');
// Valida que o WebSocket autenticou no novo PIN
const authMsgs = sentWsMessages.filter(m => m.type === 'AUTH_CLIENT');
const lastAuth = authMsgs[authMsgs.length - 1];
assert.strictEqual(lastAuth.pin, '999888', 'Deve ter conectado no PIN da nova estação');
// Valida persistência no localStorage
const saved = JSON.parse(window.localStorage.getItem('maestri_stations'));
assert.ok(saved.find(s => s.pin === '999888'), 'Nova estação salva no localStorage');
// Valida que ambas as estações estão listadas simultaneamente agrupadas no DOM sem precisar selecionar
const stationCards = document.querySelectorAll('.station-group-card');
assert.strictEqual(stationCards.length, 2, 'Deve listar 2 estações agrupadas simultaneamente na tela');
assert.ok(document.getElementById('station-card-111222'), 'Card da estação 111222 deve existir');
assert.ok(document.getElementById('station-card-999888'), 'Card da estação 999888 deve existir');
assert.ok(document.getElementById('station-card-999888').textContent.includes('PC Empresa'), 'Card deve exibir nome da estação');
});
test('4. Resolução de Action Cards com Opções Estruturadas', async () => {
// Autentica
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
const cardsContainer = document.getElementById('cards-container');
// Envia PROMPT_PENDING da grill-me
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'PROMPT_PENDING',
requestId: 'req-456',
agentName: 'Planner',
prompt: '1. Deseja aplicar o fix agora?\na) Sim\nb) Não',
options: ['1a', '1b', 'tudo padrão']
})
});
const card = document.querySelector('.action-card');
assert.ok(card, 'Card de ação deve ter sido renderizado');
assert.ok(card.textContent.includes('Planner'));
assert.ok(card.textContent.includes('Deseja aplicar o fix agora'));
// Valida botões de opções
const btnOptions = card.querySelectorAll('.btn-option');
assert.strictEqual(btnOptions.length, 3, 'Deve exibir 3 botões de opções');
assert.strictEqual(btnOptions[0].getAttribute('data-val'), '1a');
// Clica na opção '1a'
btnOptions[0].click();
// Valida envio da resolução
const resolveMsg = sentWsMessages.find(m => m.type === 'RESOLVE_PROMPT');
assert.ok(resolveMsg, 'Deve ter enviado RESOLVE_PROMPT');
assert.strictEqual(resolveMsg.requestId, 'req-456');
assert.strictEqual(resolveMsg.response, '1a');
// Card é removido após responder
assert.strictEqual(document.querySelectorAll('.action-card').length, 0);
assert.ok(cardsContainer.textContent.includes('Tudo limpo'));
});
test('5. Fluxo de Logout e Limpeza de Sessão', async () => {
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'Estacao Alpha',
agents: []
})
});
const btnLogoutScreen = document.getElementById('btn-logout-screen');
const authScreen = document.getElementById('auth-screen');
const pinScreen = document.getElementById('pin-screen');
const appScreen = document.getElementById('app-screen');
assert.strictEqual(appScreen.style.display, 'block');
// Clica no botão Sair da tela 2
btnLogoutScreen.click();
assert.strictEqual(appScreen.style.display, 'none', 'Tela do App deve ser ocultada no logout');
assert.strictEqual(pinScreen.style.display, 'none', 'Tela de PIN deve permanecer oculta após logout');
assert.strictEqual(authScreen.style.display, 'flex', 'Tela de login Google deve ser exibida no logout');
assert.strictEqual(window.localStorage.getItem('maestri_auth_token'), null, 'Token JWT deve ter sido removido do storage');
assert.strictEqual(window.localStorage.getItem('maestri_pin'), null, 'PIN deve ter sido removido do storage');
});
test('6. Envio de Prints/Arquivos e Reconhecimento de Voz no Chat', async () => {
// Autentica e inicializa chat
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'Estacao Alpha',
agents: [{ name: 'TestBot', isSelf: false }]
})
});
const agentPill = document.querySelector('.agent-pill');
agentPill.click();
const btnAttach = document.getElementById('btn-attach');
const btnVoice = document.getElementById('btn-voice');
const attachMenu = document.getElementById('attach-menu');
const attachBackdrop = document.getElementById('attach-backdrop');
const btnAttachCamera = document.getElementById('btn-attach-camera');
const btnAttachGallery = document.getElementById('btn-attach-gallery');
const btnAttachVideoRecord = document.getElementById('btn-attach-video-record');
const btnAttachVideoGallery = document.getElementById('btn-attach-video-gallery');
const btnAttachFile = document.getElementById('btn-attach-file');
const chatCameraInput = document.getElementById('chat-camera-input');
const chatGalleryInput = document.getElementById('chat-gallery-input');
const chatVideoRecordInput = document.getElementById('chat-video-record-input');
const chatVideoInput = document.getElementById('chat-video-input');
const chatFileInput = document.getElementById('chat-file-input');
const attachmentPreviewBar = document.getElementById('attachment-preview-bar');
const attachmentThumbWrapper = document.getElementById('attachment-thumb-wrapper');
const attachmentName = document.getElementById('attachment-name');
const attachmentSize = document.getElementById('attachment-size');
const btnRemoveAttachment = document.getElementById('btn-remove-attachment');
const chatInput = document.getElementById('chat-input');
const chatForm = document.getElementById('chat-form');
assert.ok(btnAttach, 'Botão de anexo (+) deve existir');
assert.ok(btnVoice, 'Botão de microfone deve existir');
assert.ok(attachMenu, 'Popover de anexo (#attach-menu) deve existir');
assert.ok(attachBackdrop, 'Backdrop de anexo (#attach-backdrop) deve existir');
assert.ok(btnAttachCamera, 'Opção de Câmera (#btn-attach-camera) deve existir');
assert.ok(btnAttachGallery, 'Opção de Galeria (#btn-attach-gallery) deve existir');
assert.ok(btnAttachVideoRecord, 'Opção de Gravação de Vídeo (#btn-attach-video-record) deve existir');
assert.ok(btnAttachVideoGallery, 'Opção de Galeria de Vídeos (#btn-attach-video-gallery) deve existir');
assert.ok(btnAttachFile, 'Opção de Arquivos (#btn-attach-file) deve existir');
// Validação dos atributos HTML5 de captura móvel direta
assert.ok(chatCameraInput, 'Input camera oculto deve existir');
assert.strictEqual(chatCameraInput.getAttribute('capture'), 'environment', 'Input câmera deve conter capture="environment"');
assert.strictEqual(chatCameraInput.getAttribute('accept'), 'image/*', 'Input câmera deve restringir a image/*');
assert.ok(chatGalleryInput, 'Input galeria oculto deve existir');
assert.strictEqual(chatGalleryInput.getAttribute('accept'), 'image/*', 'Input galeria deve restringir a image/*');
assert.strictEqual(chatGalleryInput.hasAttribute('multiple'), true, 'Input galeria deve conter atributo multiple');
assert.ok(chatVideoRecordInput, 'Input gravação de vídeo oculto deve existir');
assert.strictEqual(chatVideoRecordInput.getAttribute('capture'), 'environment', 'Input vídeo record deve conter capture="environment"');
assert.strictEqual(chatVideoRecordInput.getAttribute('accept'), 'video/*', 'Input vídeo record deve restringir a video/*');
assert.ok(chatVideoInput, 'Input galeria de vídeo oculto deve existir');
assert.ok(chatVideoInput.getAttribute('accept').includes('video/'), 'Input vídeo galeria deve aceitar tipos de vídeo');
assert.strictEqual(chatVideoInput.hasAttribute('multiple'), true, 'Input vídeo galeria deve conter atributo multiple');
assert.ok(chatFileInput, 'Input file geral oculto deve existir');
assert.strictEqual(chatFileInput.hasAttribute('multiple'), true, 'Input arquivos deve conter atributo multiple');
// 1. Testa abertura do Menu Flutuante ao clicar em (+)
assert.strictEqual(attachMenu.style.display, 'none', 'Menu deve iniciar fechado');
btnAttach.click();
assert.strictEqual(attachMenu.style.display, 'flex', 'Menu flutuante deve abrir em display flex');
assert.strictEqual(attachBackdrop.style.display, 'block', 'Backdrop deve abrir em display block');
// 2. Testa fechamento ao tocar no backdrop
attachBackdrop.click();
assert.strictEqual(attachMenu.style.display, 'none', 'Menu flutuante deve fechar ao tocar no backdrop');
// 3. Reabre e testa fechamento ao pressionar Escape
btnAttach.click();
assert.strictEqual(attachMenu.style.display, 'flex');
window.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape' }));
assert.strictEqual(attachMenu.style.display, 'none', 'Menu deve fechar com Escape');
// 4. Testa acionamento da Câmera Fotográfica
btnAttach.click();
let cameraInputClicked = false;
chatCameraInput.click = () => { cameraInputClicked = true; };
btnAttachCamera.click();
assert.strictEqual(attachMenu.style.display, 'none', 'Menu deve fechar ao escolher opção');
assert.strictEqual(cameraInputClicked, true, 'Deve ter disparado clique no chatCameraInput');
// Simula captura de foto pela Câmera
const cameraPhoto = new window.File(['camera raw photo'], 'foto_painel.jpg', { type: 'image/jpeg' });
Object.defineProperty(chatCameraInput, 'files', {
value: [cameraPhoto],
writable: true
});
chatCameraInput.dispatchEvent(new window.Event('change'));
await new Promise(r => setTimeout(r, 60));
assert.strictEqual(attachmentPreviewBar.style.display, 'flex', 'Preview deve exibir foto da câmera');
assert.strictEqual(attachmentName.textContent, 'foto_painel.jpg');
// 5. Simula envio de mensagem com a foto da Câmera
chatInput.value = 'Foto tirada da câmera do smartphone';
chatForm.dispatchEvent(new window.Event('submit'));
const sendMsg = sentWsMessages.find(m => m.type === 'CHAT_SEND' && m.attachment && m.attachment.name.includes('foto_painel'));
assert.ok(sendMsg, 'Mensagem CHAT_SEND deve conter a foto capturada da câmera');
assert.strictEqual(sendMsg.attachment.mimeType, 'image/jpeg');
assert.strictEqual(sendMsg.message, 'Foto tirada da câmera do smartphone');
assert.strictEqual(attachmentPreviewBar.style.display, 'none', 'Preview deve fechar após envio');
// 6. Testa seleção de imagem via Galeria de Fotos e remoção manual
btnAttach.click();
let galleryInputClicked = false;
chatGalleryInput.click = () => { galleryInputClicked = true; };
btnAttachGallery.click();
assert.strictEqual(galleryInputClicked, true, 'Deve ter disparado clique no chatGalleryInput');
const galleryPhoto = new window.File(['gallery image bytes'], 'print_grafico.png', { type: 'image/png' });
Object.defineProperty(chatGalleryInput, 'files', {
value: [galleryPhoto],
writable: true
});
chatGalleryInput.dispatchEvent(new window.Event('change'));
await new Promise(r => setTimeout(r, 120));
assert.strictEqual(attachmentPreviewBar.style.display, 'flex');
btnRemoveAttachment.click();
assert.strictEqual(attachmentPreviewBar.style.display, 'none', 'Botão remover deve limpar anexo da galeria');
// 6.1. Testa gravação de vídeo via Câmera
btnAttach.click();
let videoRecordInputClicked = false;
chatVideoRecordInput.click = () => { videoRecordInputClicked = true; };
btnAttachVideoRecord.click();
assert.strictEqual(videoRecordInputClicked, true, 'Deve ter disparado clique no chatVideoRecordInput');
const recordedVideo = new window.File(['video recorded stream bytes'], 'gravacao_painel.mp4', { type: 'video/mp4' });
Object.defineProperty(chatVideoRecordInput, 'files', {
value: [recordedVideo],
writable: true
});
chatVideoRecordInput.dispatchEvent(new window.Event('change'));
await new Promise(r => setTimeout(r, 60));
assert.strictEqual(attachmentPreviewBar.style.display, 'flex', 'Preview deve exibir vídeo gravado');
assert.ok(attachmentName.textContent.includes('gravacao_painel.mp4'));
assert.ok(attachmentThumbWrapper.innerHTML.includes('🎬'), 'Preview deve exibir ícone de vídeo');
btnRemoveAttachment.click();
assert.strictEqual(attachmentPreviewBar.style.display, 'none', 'Botão remover deve limpar vídeo gravado');
// 6.2. Testa seleção de vídeo via Galeria e envio no chat
btnAttach.click();
let videoGalleryInputClicked = false;
chatVideoInput.click = () => { videoGalleryInputClicked = true; };
btnAttachVideoGallery.click();
assert.strictEqual(videoGalleryInputClicked, true, 'Deve ter disparado clique no chatVideoInput');
const galleryVideo = new window.File(['video gallery demo bytes'], 'demonstracao.webm', { type: 'video/webm' });
Object.defineProperty(chatVideoInput, 'files', {
value: [galleryVideo],
writable: true
});
chatVideoInput.dispatchEvent(new window.Event('change'));
await new Promise(r => setTimeout(r, 60));
assert.strictEqual(attachmentPreviewBar.style.display, 'flex', 'Preview deve exibir vídeo selecionado da galeria');
chatInput.value = 'Vídeo de demonstração do problema';
chatForm.dispatchEvent(new window.Event('submit'));
const sendVideoMsg = sentWsMessages.find(m => m.type === 'CHAT_SEND' && m.attachment && m.attachment.name.includes('demonstracao'));
assert.ok(sendVideoMsg, 'Mensagem CHAT_SEND deve conter o vídeo enviado');
assert.strictEqual(sendVideoMsg.attachment.mimeType, 'video/webm');
assert.strictEqual(sendVideoMsg.message, 'Vídeo de demonstração do problema');
assert.strictEqual(attachmentPreviewBar.style.display, 'none', 'Preview deve fechar após envio de vídeo');
// 7. Testa seleção de múltiplos arquivos simultâneos e acúmulo entre fontes
const attachmentList = document.getElementById('attachment-list');
const multiPhoto1 = new window.File(['bytes foto 1'], 'foto1.jpg', { type: 'image/jpeg' });
const multiPhoto2 = new window.File(['bytes foto 2'], 'foto2.png', { type: 'image/png' });
Object.defineProperty(chatGalleryInput, 'files', {
value: [multiPhoto1, multiPhoto2],
writable: true
});
chatGalleryInput.dispatchEvent(new window.Event('change'));
await new Promise(r => setTimeout(r, 120));
assert.strictEqual(attachmentPreviewBar.style.display, 'flex', 'Preview deve abrir para múltiplos arquivos');
assert.strictEqual(attachmentList.children.length, 2, 'Deve ter renderizado 2 chips na lista');
// Acúmulo: adiciona mais um documento via chatFileInput
const docFile = new window.File(['log de erro'], 'erro.log', { type: 'text/plain' });
Object.defineProperty(chatFileInput, 'files', {
value: [docFile],
writable: true
});
chatFileInput.dispatchEvent(new window.Event('change'));
await new Promise(r => setTimeout(r, 60));
assert.strictEqual(attachmentList.children.length, 3, 'Deve ter acumulado 3 anexos na lista');
// Remoção individual: remove o primeiro item (foto1.jpg)
const firstRemoveBtn = attachmentList.children[0].querySelector('.attachment-chip-remove');
assert.ok(firstRemoveBtn, 'Chip deve conter botão de remoção individual');
firstRemoveBtn.click();
assert.strictEqual(attachmentList.children.length, 2, 'Deve restar 2 itens após remoção individual');
// Envio de mensagem com múltiplos anexos
chatInput.value = 'Mensagem com dois anexos acumulados';
chatForm.dispatchEvent(new window.Event('submit'));
const multiSendMsg = sentWsMessages.find(m => m.type === 'CHAT_SEND' && Array.isArray(m.attachments) && m.attachments.length === 2);
assert.ok(multiSendMsg, 'Deve ter despachado CHAT_SEND contendo array attachments com 2 itens');
assert.ok(multiSendMsg.attachments.some(a => a.name === 'foto2.png'), 'Deve conter foto2.png');
assert.ok(multiSendMsg.attachments.some(a => a.name === 'erro.log'), 'Deve conter erro.log');
assert.strictEqual(attachmentPreviewBar.style.display, 'none', 'Preview deve fechar após envio');
// 8. Testa clique no botão de voz / microfone
btnVoice.click();
assert.ok(btnVoice, 'Botão de voz deve responder ao clique com segurança');
});
test('7. Multi-Estações Agrupadas — Listagem de Máquinas e Roteamento de Ações por Estação', async () => {
// 1. Cadastra duas estações (como 161818 com apelido e 895830 com apelido amigável)
const pinStationNameInput = document.getElementById('pin-station-name-input');
if (pinStationNameInput) {
pinStationNameInput.value = 'Nitro Gamer';
}
document.getElementById('pin-input').value = '161818';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
// Adiciona a segunda estação com apelido amigável (Notebook Aliare) diferente do hostname físico (NTB-4VCYNG4)
const btnAddStation = document.getElementById('btn-add-station');
const stationNameInput = document.getElementById('station-name-input');
const stationPinInput = document.getElementById('station-pin-input');
const btnSaveStation = document.getElementById('btn-save-station');
btnAddStation.click();
stationNameInput.value = 'Notebook Aliare';
stationPinInput.value = '895830';
btnSaveStation.click();
await new Promise(r => setTimeout(r, 30));
// 2. Simula INIT_STATE para a estação 161818 (machineName: nitro) e 895830 (machineName físico: NTB-4VCYNG4)
const ws161818 = mockWsInstances[0];
const ws895830 = mockWsInstances[1];
ws161818.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'nitro',
agents: [
{ name: 'gp200mod', isSelf: false },
{ name: 'maestri-remote-agent', isSelf: true }
],
pendingPrompts: [
{ requestId: 'req-nitro-1', agentName: 'gp200mod', prompt: 'Executar build do robô?', options: ['Sim', 'Não'] }
]
})
});
ws895830.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'NTB-4VCYNG4',
agents: [
{ name: 'maestro-remote-agent', isSelf: true }
],
pendingPrompts: []
})
});
const card161818 = document.getElementById('station-card-161818');
const card895830 = document.getElementById('station-card-895830');
assert.ok(card161818, 'Card agrupado da estação nitro (161818) deve existir');
assert.ok(card895830, 'Card agrupado da estação NTB-4VCYNG4 (895830) deve existir');
// Validação soberana do apelido: O título da estação DEVE ser o apelido cadastrado no pareamento
const titleEl895830 = card895830.querySelector('.station-group-name span');
assert.ok(titleEl895830, 'Elemento de título da estação 895830 deve existir');
assert.strictEqual(titleEl895830.textContent.trim(), 'Notebook Aliare', 'O título da estação deve exibir o nome cadastrado no pareamento (Notebook Aliare), e NÃO o hostname real (NTB-4VCYNG4)');
// O localStorage não deve ter sido corrompido com o hostname
const savedStations = JSON.parse(window.localStorage.getItem('maestri_stations') || '[]');
const st895830 = savedStations.find(s => s.pin === '895830');
assert.ok(st895830, 'Estação 895830 deve estar salva no localStorage');
assert.strictEqual(st895830.name, 'Notebook Aliare', 'Nome persistido no localStorage deve ser o apelido cadastrado');
assert.ok(card161818.textContent.includes('gp200mod'));
assert.strictEqual(card161818.querySelector('.station-prompts-list'), null, 'Seção de solicitações pendentes deve ter sido removida do card da estação');
// 3. Testa renomeação dinâmica da estação
window.renameStation('895830', 'Meu PC Gamer');
const updatedCard895830 = document.getElementById('station-card-895830');
assert.strictEqual(updatedCard895830.querySelector('.station-group-name span').textContent.trim(), 'Meu PC Gamer');
const reloadedStations = JSON.parse(window.localStorage.getItem('maestri_stations') || '[]');
assert.strictEqual(reloadedStations.find(s => s.pin === '895830').name, 'Meu PC Gamer');
// 4. Testa resposta ao card de prompt da estação nitro
const cardsContainer = document.getElementById('cards-container');
const btnOptionSim = cardsContainer.querySelector('.btn-option[data-val="Sim"]');
assert.ok(btnOptionSim, 'Botão Sim deve estar renderizado no card de ação de nitro');
btnOptionSim.click();
const resolveMsg = sentWsMessages.find(m => m.type === 'RESOLVE_PROMPT' && m.requestId === 'req-nitro-1');
assert.ok(resolveMsg, 'Deve ter despachado RESOLVE_PROMPT com sucesso');
assert.strictEqual(resolveMsg.response, 'Sim');
// 5. Testa remoção individual da estação 895830 sem perder a outra
const btnRemove895830 = updatedCard895830.querySelector('.btn-station-remove');
btnRemove895830.click();
// Apenas card 161818 permanece
assert.ok(document.getElementById('station-card-161818'), 'Estação 161818 deve permanecer conectada');
assert.strictEqual(document.getElementById('station-card-895830'), null, 'Estação 895830 removida deve desaparecer da tela');
});
test('8. Modal de Informações de Versão — Abertura pelo Header e Exibição de Data/Hora e Build', async () => {
const brandHeader = document.getElementById('brand-header');
const modalVersion = document.getElementById('modal-version');
const appVersionVal = document.getElementById('app-version-val');
const appBuildVal = document.getElementById('app-build-val');
const appDateVal = document.getElementById('app-date-val');
const btnClose = document.getElementById('btn-close-version-modal');
assert.ok(brandHeader, 'Elemento brand-header no topo deve existir');
assert.ok(modalVersion, 'Modal de versão deve existir');
// Ao clicar no brand header, abre o modal
brandHeader.click();
assert.strictEqual(modalVersion.style.display, 'flex', 'Modal de versão deve abrir ao clicar no brand header');
assert.ok(appVersionVal.textContent.includes('1.0.2'), 'Versão do app deve estar preenchida');
assert.ok(appBuildVal.textContent.length > 0, 'Build ID deve estar preenchido');
assert.ok(appDateVal.textContent.length > 0, 'Data e hora devem estar preenchidas');
// Fecha pelo botão fechar
btnClose.click();
assert.strictEqual(modalVersion.style.display, 'none', 'Modal de versão deve fechar ao clicar no botão fechar');
});
test('9. Detecção e Exibição de Agente Pensando / Executando (Claude Code, AGY, Kiro)', async () => {
// Autentica previamente
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'Estacao Alpha',
agents: [{ name: 'SREOracle #2', isSelf: false }]
})
});
window.openChatWithAgent('SREOracle #2', '712000');
const chatAgentStatusDot = document.getElementById('chat-agent-status-dot');
const chatThinkingBanner = document.getElementById('chat-thinking-banner');
const chatThinkingText = document.getElementById('chat-thinking-text');
// 1. Simula terminal emitindo atividade do Claude Code: '⠇ Working...'
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'SREOracle #2',
output: '> Atualizar pod\n⠇ Working...'
})
});
assert.ok(chatAgentStatusDot.classList.contains('thinking'), 'Status dot do header deve estar pulsando em amarelo (thinking)');
assert.strictEqual(chatThinkingBanner.style.display, 'flex', 'Banner de pensando deve estar visível');
assert.ok(chatThinkingText.textContent.includes('Trabalhando') || chatThinkingText.textContent.includes('Working'), 'Texto do banner deve indicar trabalho');
const statePill = document.querySelector('.agent-state-pill');
assert.ok(statePill, 'Pill de estado do agente no card deve existir');
assert.ok(statePill.classList.contains('thinking'), 'Pill deve estar em estado thinking');
// Valida card dinâmico no final da conversa
const thinkingCard = document.querySelector('.chat-bubble.thinking-card');
assert.ok(thinkingCard, 'Card dinâmico de agente pensando deve estar visível no final da conversa');
const thinkingTimer = document.getElementById('chat-thinking-elapsed');
assert.ok(thinkingTimer, 'Cronômetro do agente pensando deve existir');
const thinkingAction = document.querySelector('.thinking-action-badge');
assert.ok(thinkingAction, 'Linha de ação do agente pensando deve existir');
assert.ok(thinkingAction.textContent.includes('Working'), 'Linha de ação deve capturar a ação do terminal');
// 2. Simula término da tarefa e retorno ao prompt ocioso
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'SREOracle #2',
output: 'Comando finalizado com sucesso.\n> '
})
});
assert.ok(chatAgentStatusDot.classList.contains('active'), 'Status dot deve voltar para verde (active)');
assert.strictEqual(chatThinkingBanner.style.display, 'none', 'Banner de pensando deve desaparecer quando ocioso');
const idlePill = document.querySelector('.agent-state-pill');
assert.ok(idlePill.classList.contains('idle'), 'Pill deve voltar para ocioso / pronto');
assert.strictEqual(document.querySelector('.chat-bubble.thinking-card'), null, 'Card dinâmico de pensando deve desaparecer ao término');
window.closeChat();
});
test('10. Controle Inteligente de Scroll — Preservação de Posição ao Rolar para Cima e Botão Flutuante', async () => {
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'Estacao Alpha',
agents: [{ name: 'SREOracle #2', isSelf: false }]
})
});
window.openChatWithAgent('SREOracle #2', '712000');
const chatMessagesEl = document.getElementById('chat-messages');
const btnScrollBottom = document.getElementById('btn-chat-scroll-bottom');
assert.ok(btnScrollBottom, 'Botão flutuante de rolar para o fim deve existir');
assert.strictEqual(btnScrollBottom.style.display, 'none', 'Botão flutuante deve começar oculto no fundo');
// Simula usuário rolando para cima (scrollTop longe do final)
Object.defineProperty(chatMessagesEl, 'scrollHeight', { value: 1000, configurable: true });
Object.defineProperty(chatMessagesEl, 'clientHeight', { value: 400, configurable: true });
chatMessagesEl.scrollTop = 100;
chatMessagesEl.dispatchEvent(new window.Event('scroll'));
assert.strictEqual(btnScrollBottom.style.display, 'flex', 'Botão de rolar para o fim deve aparecer quando usuário rolar para cima');
// Simula atualização periódica de terminal enquanto usuário está lendo acima
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'SREOracle #2',
output: 'kubectl get pods\nNAME READY\npod-1 1/1'
})
});
// O scroll NÃO deve ser forçado para 1000 (deve preservar a leitura)
assert.notStrictEqual(chatMessagesEl.scrollTop, 1000, 'Scroll não deve ser forçado para o rodapé enquanto o usuário lê acima');
// Clica no botão flutuante para voltar ao fim
btnScrollBottom.click();
assert.strictEqual(btnScrollBottom.style.display, 'none', 'Botão flutuante deve sumir ao clicar');
window.closeChat();
});
test('11. Estabilidade Total de Scroll — Polling de Terminal Não Recria DOM e Não Arrasta Scroll Quando Ocioso', async () => {
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'Estacao Alpha',
agents: [{ name: 'SREOracle #2', isSelf: false }]
})
});
window.openChatWithAgent('SREOracle #2', '712000');
const chatMessagesEl = document.getElementById('chat-messages');
// 1. Simula resposta recebida (agente concluiu a fala)
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'CHAT_RESPONSE',
agentName: 'SREOracle #2',
response: 'Relatório de diagnóstico gerado com sucesso.'
})
});
// Marca elemento da resposta para detectar se o DOM é recriado
const agentBubbles = chatMessagesEl.querySelectorAll('.chat-bubble.agent:not(.terminal-snapshot)');
assert.ok(agentBubbles.length > 0, 'Deve ter bolha de resposta do agente');
const lastResponseBubble = agentBubbles[agentBubbles.length - 1];
lastResponseBubble.setAttribute('data-original-instance', 'true');
// 2. Simula usuário lendo e com scroll fixo
Object.defineProperty(chatMessagesEl, 'scrollHeight', { value: 1200, configurable: true });
Object.defineProperty(chatMessagesEl, 'clientHeight', { value: 400, configurable: true });
chatMessagesEl.scrollTop = 500;
chatMessagesEl.dispatchEvent(new window.Event('scroll'));
// 3. Chega poll periódico do terminal (agente ocioso, apenas cursor ou timestamp)
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'SREOracle #2',
output: '> kubectl get pods\nNAME pod-1 1/1\n> '
})
});
// 4. Valida que o DOM NÃO foi destruído e recriado
const bubbleAfterPoll = chatMessagesEl.querySelector('[data-original-instance="true"]');
assert.ok(bubbleAfterPoll, 'O DOM das mensagens de conversa não deve ser destruído no poll periódico de terminal');
// 5. Valida que o scroll permaneceu estritamente em 500 e NÃO foi arrastado para 1200
assert.strictEqual(chatMessagesEl.scrollTop, 500, 'O scrollTop deve permanecer exatamente onde o usuário deixou, sem auto-scroll');
// 6. Valida que o terminal snapshot atualizou in-place
const terminalBody = document.getElementById('chat-terminal-snapshot-body');
assert.ok(terminalBody, 'Corpo do snapshot do terminal deve existir');
assert.ok(terminalBody.textContent.includes('kubectl get pods'), 'Conteúdo do snapshot deve estar atualizado in-place');
window.closeChat();
});
test('12. Resposta de Terminal Assíncrono — Conclusão de Tarefa Gera Bolha do Agente Abaixo do Prompt Verde', async () => {
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'Estacao Alpha',
agents: [{ name: 'SREOracle #2', isSelf: false }]
})
});
window.openChatWithAgent('SREOracle #2', '712000');
const chatInput = document.getElementById('chat-input');
const chatForm = document.getElementById('chat-form');
// 1. Usuário envia prompt
chatInput.value = '@planner.md atue documentando tudo que fizemos';
chatForm.dispatchEvent(new window.Event('submit'));
const userBubble = document.querySelector('.chat-bubble.user');
assert.ok(userBubble, 'Prompt do usuário deve ser renderizado no chat');
// 2. Terminal entra em estado de execução / thinking
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'SREOracle #2',
output: 'Investigando e gerando documentacao...\n⠇ Working on spec...'
})
});
// 3. Terminal conclui a tarefa e volta para pronto com a resposta gerada
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'SREOracle #2',
output: '### Documentacao Concluida\nAmbos os artefatos foram commitados.\n> '
})
});
// 4. Valida que uma bolha de resposta do agente foi adicionada ABAIXO do prompt do usuário
const allBubbles = Array.from(document.querySelectorAll('.chat-messages .chat-bubble'));
const userBubbleIdx = allBubbles.findIndex(b => b.classList.contains('user'));
const agentReplyBubbles = allBubbles.filter((b, idx) => idx > userBubbleIdx && b.classList.contains('agent') && !b.classList.contains('terminal-snapshot'));
assert.ok(agentReplyBubbles.length > 0, 'Deve existir pelo menos uma bolha de resposta do agente após o prompt do usuário');
const replyText = agentReplyBubbles[agentReplyBubbles.length - 1].textContent;
assert.ok(replyText.includes('Documentacao Concluida'), 'A resposta gerada no terminal deve estar contida na bolha do agente');
window.closeChat();
});
test('13. Diferenciação Visual de Terminais: Bolinha Verde (IA Ativa) vs Cinza (Shell DOS/Bash/PS) vs Azul (Self)', async () => {
// Autentica previamente
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
// Simula AGENTS_UPDATE com múltiplos terminais de tipos distintos
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [
{ name: 'SREOracle #2', isSelf: false, hasAiActivity: true, aiType: 'agy' },
{ name: 'gp200mod', isSelf: false, hasAiActivity: false, shellType: 'powershell' },
{ name: 'Canal Dark', isSelf: false, hasAiActivity: false, shellType: 'bash' },
{ name: 'gado-forte', isSelf: false, hasAiActivity: false, shellType: 'cmd' },
{ name: 'maestri-remote-agent', isSelf: true, hasAiActivity: false }
]
})
});
const pills = Array.from(document.querySelectorAll('.agent-pill.agent-chip'));
assert.strictEqual(pills.length, 4, 'Deve renderizar 4 pills de terminais (isSelf ocultado)');
// 1. Agente IA Ativo: deve ter bolinha verde (#34d399 / rgb(52, 211, 153)) e classe ai-active
const aiPill = pills.find(p => p.textContent.includes('SREOracle #2'));
assert.ok(aiPill, 'Pill de SREOracle #2 deve existir');
assert.ok(aiPill.classList.contains('ai-active'), 'Pill com IA deve conter classe ai-active');
const aiDot = aiPill.querySelector('.status-dot');
assert.ok(aiDot.style.backgroundColor === '#34d399' || aiDot.style.backgroundColor === 'rgb(52, 211, 153)', 'Bolinha deve ser verde');
assert.ok(aiPill.getAttribute('title').includes('Agente de IA Ativo'));
// 2. Terminal PowerShell: deve ter bolinha cinza (#94a3b8 / rgb(148, 163, 184)) e classe shell-idle
const psPill = pills.find(p => p.textContent.includes('gp200mod'));
assert.ok(psPill, 'Pill de gp200mod deve existir');
assert.ok(psPill.classList.contains('shell-idle'), 'Terminal PS deve conter classe shell-idle');
const psDot = psPill.querySelector('.status-dot');
assert.ok(psDot.style.backgroundColor === '#94a3b8' || psDot.style.backgroundColor === 'rgb(148, 163, 184)', 'Bolinha deve ser cinza');
assert.ok(psPill.getAttribute('title').includes('Terminal PowerShell'));
// 3. Terminal Bash: deve ter bolinha cinza e classe shell-idle
const bashPill = pills.find(p => p.textContent.includes('Canal Dark'));
assert.ok(bashPill, 'Pill de Canal Dark deve existir');
assert.ok(bashPill.classList.contains('shell-idle'), 'Terminal Bash deve conter classe shell-idle');
const bashDot = bashPill.querySelector('.status-dot');
assert.ok(bashDot.style.backgroundColor === '#94a3b8' || bashDot.style.backgroundColor === 'rgb(148, 163, 184)', 'Bolinha deve ser cinza');
assert.ok(bashPill.getAttribute('title').includes('Terminal Bash'));
// 4. Terminal DOS/CMD: deve ter bolinha cinza e classe shell-idle
const cmdPill = pills.find(p => p.textContent.includes('gado-forte'));
assert.ok(cmdPill, 'Pill de gado-forte deve existir');
assert.ok(cmdPill.classList.contains('shell-idle'), 'Terminal CMD deve conter classe shell-idle');
const cmdDot = cmdPill.querySelector('.status-dot');
assert.ok(cmdDot.style.backgroundColor === '#94a3b8' || cmdDot.style.backgroundColor === 'rgb(148, 163, 184)', 'Bolinha deve ser cinza');
assert.ok(cmdPill.getAttribute('title').includes('Terminal DOS'));
// 5. Daemon Supervisor (isSelf): não deve ser renderizado no card da estação
const selfPill = pills.find(p => p.textContent.includes('maestri-remote-agent'));
assert.strictEqual(selfPill, undefined, 'Daemon supervisor (isSelf) não deve ser renderizado no card da estação');
});
test('14. Detecção e Exibição de Agente Pausado por Limite de Cota (Usage Limit / Rate Limit)', async () => {
// Autentica previamente
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'Notebook Trabalho',
agents: [{ name: 'engenheiro2', isSelf: false, hasAiActivity: true, aiType: 'claude' }]
})
});
window.openChatWithAgent('engenheiro2', '712000', 'Notebook Trabalho');
const chatAgentStatusDot = document.getElementById('chat-agent-status-dot');
const chatAgentSubtitle = document.getElementById('chat-agent-subtitle');
const chatThinkingBanner = document.getElementById('chat-thinking-banner');
// Simula terminal emitindo rate limit do Claude Code com 'Continuing automatically at 1:50pm • Esc to cancel'
const rateLimitedTerminalOutput = `
> continue
• Usage limit reached again • continuing automatically at 1:50pm • esc to cancel
↳ You've hit your 5-hour limit • resets 1:50pm (America/Sao_Paulo)
* Crunched for 0s • done 12:22 PM
⚠ Usage limit reached • limit resets 1:50pm
Continuing automatically at 1:50pm • Esc to cancel
`;
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'engenheiro2',
output: rateLimitedTerminalOutput
})
});
// 1. Status dot deve ser paused (laranja), NÃO thinking (amarelo)
assert.ok(chatAgentStatusDot.classList.contains('paused'), 'Status dot do header deve estar com a classe paused');
assert.strictEqual(chatAgentStatusDot.classList.contains('thinking'), false, 'Status dot NÃO deve conter classe thinking');
// 2. Banner de execução NÃO deve estar visível
assert.strictEqual(chatThinkingBanner.style.display, 'none', 'Banner de pensando/executando deve estar oculto quando pausado por cota');
// 3. Subtítulo deve avisar sobre limite de cota com horário de reset
assert.ok(chatAgentSubtitle.textContent.includes('Limite de cota atingido'), 'Subtítulo deve avisar que o limite foi atingido');
assert.ok(chatAgentSubtitle.textContent.includes('1:50pm'), 'Subtítulo deve exibir horário de reset (1:50pm)');
// 4. Card dinâmico de "engenheiro2 está trabalhando" NÃO deve ser criado
const thinkingCard = document.querySelector('.chat-bubble.thinking-card');
assert.strictEqual(thinkingCard, null, 'NÃO deve exibir card "está trabalhando" quando o agente está pausado por limite de uso');
// 5. Pill no terminal snapshot deve estar em paused com o horário
const statePill = document.querySelector('.agent-state-pill');
assert.ok(statePill, 'Pill de estado do agente no card deve existir');
assert.ok(statePill.classList.contains('paused'), 'Pill deve estar em estado paused');
assert.ok(statePill.textContent.includes('1:50pm'), 'Pill deve exibir o horário de reset (1:50pm)');
window.closeChat();
});
test('15. Home: Exibição Prioritária de Agentes com Atividade (Sinal Verde) e Agrupamento de Outros Terminais', async () => {
// Autentica previamente
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
// Simula estado da estação com 2 agentes de IA ativos e 2 shells ociosos
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [
{ name: 'SREOracle #2', isSelf: false, hasAiActivity: true, aiType: 'agy' },
{ name: 'ClaudeAgent', isSelf: false, hasAiActivity: true, aiType: 'claude' },
{ name: 'shell-bash', isSelf: false, hasAiActivity: false, shellType: 'bash' },
{ name: 'shell-cmd', isSelf: false, hasAiActivity: false, shellType: 'cmd' },
{ name: 'maestri-supervisor', isSelf: true }
]
})
});
// 1. O label da seção deve informar o total de agentes com atividade
const sectionLabel = document.querySelector('.station-section-label');
assert.ok(sectionLabel.textContent.includes('Agentes com Atividade (2)'), 'Label deve contabilizar 2 agentes com atividade');
// 2. Os agentes com sinal verde devem estar no container principal
const activePills = Array.from(document.querySelectorAll('.station-agents-list > .agent-pill.agent-chip'));
assert.strictEqual(activePills.length, 2, 'Devem existir 2 pills no container principal de ativos');
assert.ok(activePills.some(p => p.textContent.includes('SREOracle #2')));
assert.ok(activePills.some(p => p.textContent.includes('ClaudeAgent')));
// 3. Os outros terminais (shells) devem estar agrupados na subseção (supervisor isSelf é ocultado)
const otherWrapper = document.querySelector('.station-other-terminals-wrapper');
assert.ok(otherWrapper, 'Wrapper de outros terminais deve existir');
assert.ok(otherWrapper.textContent.includes('Outros Terminais (2)'), 'Header deve contabilizar 2 outros terminais');
const otherPills = Array.from(otherWrapper.querySelectorAll('.agent-pill.agent-chip'));
assert.strictEqual(otherPills.length, 2, 'Devem existir 2 pills na seção secundária de outros terminais');
assert.ok(otherPills.some(p => p.textContent.includes('shell-bash')));
assert.ok(otherPills.some(p => p.textContent.includes('shell-cmd')));
assert.strictEqual(otherPills.some(p => p.textContent.includes('maestri-supervisor')), false, 'maestri-supervisor (isSelf) não deve ser renderizado');
// 4. Se todos os agentes ficarem inativos (hasAiActivity = false)
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [
{ name: 'shell-bash', isSelf: false, hasAiActivity: false, shellType: 'bash' }
]
})
});
const emptyActiveNotice = document.querySelector('.station-empty-active-agents');
assert.ok(emptyActiveNotice, 'Deve exibir aviso amigável quando não houver agentes em atividade');
assert.ok(emptyActiveNotice.textContent.includes('Nenhum agente em atividade'));
});
test('16. Home: Agente em Execução (isThinking) Exibe Status Dot Amarelo Pulsante e Badge em Tempo Real', async () => {
// Autentica previamente
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
// Simula agente em execução (isThinking: true)
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [
{ name: 'maestri-remote', isSelf: false, hasAiActivity: true, isThinking: true, aiType: 'agy' },
{ name: 'SREOracle #2', isSelf: false, hasAiActivity: true, isThinking: false, aiType: 'agy' }
]
})
});
const pills = Array.from(document.querySelectorAll('.agent-pill.agent-chip'));
const thinkingPill = pills.find(p => p.textContent.includes('maestri-remote'));
assert.ok(thinkingPill, 'Pill de maestri-remote deve existir');
assert.ok(thinkingPill.classList.contains('thinking'), 'Pill do agente em execução deve ter classe thinking');
const dot = thinkingPill.querySelector('.status-dot');
assert.ok(dot.classList.contains('thinking'), 'Status dot deve conter classe thinking');
assert.ok(dot.style.backgroundColor === '#f59e0b' || dot.style.backgroundColor === 'rgb(245, 158, 11)', 'Bolinha do agente em execução deve ser amarela (#f59e0b)');
assert.ok(thinkingPill.getAttribute('title').includes('Agente em Execução'));
assert.ok(thinkingPill.textContent.includes('⚡'), 'Pill deve exibir o badge ⚡ de execução');
// O agente pronto (idle) deve continuar com bolinha verde
const idlePill = pills.find(p => p.textContent.includes('SREOracle #2'));
assert.ok(idlePill.classList.contains('ai-active'), 'Agente ocioso deve permanecer como ai-active (verde)');
const idleDot = idlePill.querySelector('.status-dot');
assert.ok(idleDot.style.backgroundColor === '#34d399' || idleDot.style.backgroundColor === 'rgb(52, 211, 153)', 'Bolinha do agente ocioso deve ser verde');
// Simula transição para ocioso (término de execução)
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [
{ name: 'maestri-remote', isSelf: false, hasAiActivity: true, isThinking: false, aiType: 'agy' },
{ name: 'SREOracle #2', isSelf: false, hasAiActivity: true, isThinking: false, aiType: 'agy' }
]
})
});
const updatedPills = Array.from(document.querySelectorAll('.agent-pill.agent-chip'));
const finishedPill = updatedPills.find(p => p.textContent.includes('maestri-remote'));
assert.ok(finishedPill.classList.contains('ai-active'), 'Pill deve voltar para ai-active (verde)');
const finishedDot = finishedPill.querySelector('.status-dot');
assert.ok(finishedDot.style.backgroundColor === '#34d399' || finishedDot.style.backgroundColor === 'rgb(52, 211, 153)', 'Bolinha deve voltar para verde');
assert.strictEqual(finishedPill.textContent.includes('⚡'), false, 'Badge ⚡ deve sumir ao terminar execução');
});
test('17. Home: Respostas Não Lidas de Agentes Ficam Visíveis com Badge, Banner e Priorização no Topo', async () => {
// Autentica previamente
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
// Inicializa estação com dois agentes
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [
{ name: 'SREOracle #2', isSelf: false, hasAiActivity: true, aiType: 'agy' },
{ name: 'maestri-remote', isSelf: false, hasAiActivity: true, aiType: 'agy' }
]
})
});
// Garante que o chat está fechado na Home
window.closeChat();
// 1. Simula chegada de resposta de maestri-remote enquanto usuário está na Home
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'CHAT_RESPONSE',
agentName: 'maestri-remote',
response: 'Rollout concluído e pods saudáveis no cluster.'
})
});
// 2. Valida que o banner de respostas não lidas foi exibido na estação
const unreadBanner = document.querySelector('.station-unread-banner');
assert.ok(unreadBanner, 'Deve exibir o banner de respostas novas na estação');
assert.ok(unreadBanner.textContent.includes('respostas novas para ler'));
// 3. Valida que o pill de maestri-remote recebeu a classe has-unread-reply e o badge
const unreadPill = document.querySelector('.agent-pill.has-unread-reply');
assert.ok(unreadPill, 'Deve existir pill com classe has-unread-reply');
assert.ok(unreadPill.textContent.includes('maestri-remote'));
assert.ok(unreadPill.textContent.includes('Resposta nova'));
const tag = unreadPill.querySelector('.unread-response-tag');
assert.ok(tag, 'Tag visual de resposta nova deve estar visível no pill');
assert.ok(unreadPill.getAttribute('title').includes('Nova resposta'));
// 4. Ao tocar no agente para abrir a conversa, a resposta deve ser marcada como lida
unreadPill.click();
assert.strictEqual(document.getElementById('chat-drawer').style.display, 'flex', 'Chat Drawer deve abrir');
// Fecha o chat para voltar à Home e validar a limpeza do badge
window.closeChat();
assert.strictEqual(document.querySelector('.station-unread-banner'), null, 'Banner de não lidas deve ter desaparecido');
assert.strictEqual(document.querySelector('.agent-pill.has-unread-reply'), null, 'Classe has-unread-reply deve ter sido removida');
assert.strictEqual(document.querySelector('.unread-response-tag'), null, 'Tag de resposta nova deve ter desaparecido');
});
test('18. Precedência de Prompt Ocioso não fica preso em thinking mesmo com menção a .thinking e conclui resposta no chat', async () => {
// 1. Loga com PIN 712000
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 25));
// Estação online com agente maestri-remote
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
machineName: 'nitro',
agents: [{ name: 'maestri-remote', status: 'idle', isThinking: false, hasAiActivity: true }]
})
});
// 2. Abre o chat de maestri-remote
window.openChatWithAgent('maestri-remote', '712000');
assert.strictEqual(document.getElementById('chat-drawer').style.display, 'flex');
// 3. Simula envio de prompt pelo usuário
const chatInput = document.getElementById('chat-input');
const chatForm = document.getElementById('chat-form');
chatInput.value = 'qual classe usamos para thinking?';
chatForm.dispatchEvent(new window.Event('submit'));
// Valida que o card de thinking está visível
assert.ok(document.getElementById('chat-typing-indicator'), 'Card de thinking deve estar ativo');
// 4. Chega snapshot de terminal onde o agente menciona .thinking, #f59e0b e termina no prompt ocioso de IA
const terminalOutput = `
────────────────────────────────────────────────────────────
Para alterar o status usamos a classe .thinking e a cor #f59e0b.
Também verificamos running command e compiling no buffer.
────────────────────────────────────────────────────────────
│ >
? for shortcuts
`;
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'maestri-remote',
output: terminalOutput
})
});
// 5. Valida que o card de thinking foi encerrado e a resposta foi adicionada na conversa
assert.strictEqual(document.getElementById('chat-typing-indicator'), null, 'Card de thinking deve sumir após prompt ocioso');
const bubbles = document.querySelectorAll('.chat-bubble.agent');
assert.ok(bubbles.length > 0, 'Resposta do agente deve ser renderizada na conversa');
const lastBubble = bubbles[bubbles.length - 1];
assert.ok(lastBubble.textContent.includes('.thinking'), 'Resposta deve conter o texto gerado pelo terminal');
});
test('19. Ditado Contínuo por Voz (SpeechRecognition) — Modo Contínuo, Tolerância a Pausas de Respiração e Acumulação Fluida', async () => {
// 1. Abre chat com um agente
document.getElementById('pin-input').value = '123456';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'Estacao Dev',
agents: [{ name: 'dev-agent', isSelf: false }]
})
});
const agentPill = document.querySelector('.agent-pill');
assert.ok(agentPill, 'Pill do agente deve existir');
agentPill.click();
const btnVoice = document.getElementById('btn-voice');
const btnSend = document.getElementById('btn-chat-send');
const chatInput = document.getElementById('chat-input');
const chatForm = document.getElementById('chat-form');
assert.ok(btnVoice, 'Botão de voz deve existir');
assert.ok(btnSend, 'Botão de envio deve existir');
assert.ok(window.SpeechRecognition.instance, 'Instância de SpeechRecognition deve ter sido criada');
const recognizer = window.SpeechRecognition.instance;
assert.strictEqual(recognizer.continuous, true, 'SpeechRecognition deve estar configurado com continuous = true');
assert.strictEqual(recognizer.interimResults, true, 'SpeechRecognition deve estar configurado com interimResults = true');
assert.strictEqual(recognizer.lang, 'pt-BR', 'Idioma deve ser pt-BR');
// 2. Pré-preenche texto no input para validar preservação de prefixo
chatInput.value = 'Olá agente, ';
// 3. Inicia gravação pelo botão de voz
btnVoice.click();
assert.ok(btnVoice.classList.contains('recording'), 'Botão de voz deve receber classe .recording');
assert.strictEqual(btnVoice.style.display, 'inline-flex', 'Botão de parar/gravação deve permanecer visível');
assert.strictEqual(btnSend.style.display, 'none', 'Botão de envio deve estar estritamente oculto durante a gravação');
assert.strictEqual(btnVoice.getAttribute('aria-label'), 'Parar gravação de voz');
assert.ok(chatInput.placeholder.includes('Ouvindo'), 'Placeholder deve indicar que está ouvindo');
// 4. Simula chegada de fala em tempo real (primeira frase: interim e final)
recognizer.onresult({
resultIndex: 0,
results: [
Object.assign([{ transcript: 'execute os testes' }], { isFinal: true })
]
});
assert.strictEqual(chatInput.value, 'Olá agente, execute os testes ');
assert.strictEqual(btnVoice.style.display, 'inline-flex', 'Botão de parar deve continuar visível durante a transcrição');
assert.strictEqual(btnSend.style.display, 'none', 'Botão de envio continua oculto até gravação ser interrompida');
// 5. Simula pausa para respirar que emite erro 'no-speech' e 'onend' pelo motor nativo
recognizer.onerror({ error: 'no-speech' });
assert.ok(btnVoice.classList.contains('recording'), 'Erro no-speech (pausa para respirar) NÃO deve cancelar o ditado contínuo');
// Dispara onend fingindo timeout do motor de fala nativo (enquanto usuário ainda não clicou para parar)
recognizer.onend();
assert.ok(btnVoice.classList.contains('recording'), 'onend não-voluntário deve auto-reiniciar recognizer sem desligar gravação');
assert.strictEqual(recognizer.started, true, 'Recognizer deve ter sido reiniciado');
// 6. Simula continuação da fala após a pausa para respirar
recognizer.onresult({
resultIndex: 0,
results: [
Object.assign([{ transcript: 'e gere o relatório' }], { isFinal: true })
]
});
assert.strictEqual(chatInput.value, 'Olá agente, execute os testes e gere o relatório ');
assert.strictEqual(btnVoice.style.display, 'inline-flex', 'Botão de parar deve continuar visível com mais texto transcrito');
assert.strictEqual(btnSend.style.display, 'none', 'Botão de envio continua oculto durante a gravação contínua');
// Tentativa de submissão do formulário enquanto grava deve ser bloqueada
chatForm.dispatchEvent(new window.Event('submit', { cancelable: true }));
assert.strictEqual(recognizer.started, true, 'Gravação não deve ser cancelada por submit acidental');
// 7. Encerra o ditado clicando novamente no microfone (toggle voluntário)
btnVoice.click();
assert.strictEqual(btnVoice.classList.contains('recording'), false, 'Ao clicar novamente, deve desativar a gravação');
assert.strictEqual(recognizer.started, false, 'Deve invocar stop() no recognizer');
assert.strictEqual(chatInput.value, 'Olá agente, execute os testes e gere o relatório', 'Texto final deve ser trim() sem espaços sobrando');
assert.strictEqual(btnVoice.style.display, 'none', 'Após parar a gravação com texto presente, botão de microfone oculta');
assert.strictEqual(btnSend.style.display, 'inline-flex', 'Após parar a gravação com texto presente, botão de envio fica visível');
// 8. Envio da mensagem: ao enviar, o campo deve ser totalmente limpo (input reset)
chatForm.dispatchEvent(new window.Event('submit', { cancelable: true }));
assert.strictEqual(chatInput.value, '', 'Campo de texto deve ser totalmente limpo após o envio');
assert.strictEqual(btnSend.style.display, 'none', 'Após envio e input limpo, botão de envio é ocultado');
assert.strictEqual(btnVoice.style.display, 'inline-flex', 'Após envio e input limpo, botão de voz volta a ficar visível');
});
test('20. Resiliência do Ditado por Voz — Erros Transitórios (Network, Service-Not-Allowed) Preservam a Instância e Permitem Nova Tentativa', async () => {
const btnVoice = document.getElementById('btn-voice');
const recognizer = window.SpeechRecognition.instance;
assert.ok(btnVoice, 'Botão de microfone deve existir');
assert.ok(recognizer, 'Instância de recognizer deve existir');
// 1. Inicia gravação
btnVoice.click();
assert.strictEqual(btnVoice.classList.contains('recording'), true, 'Microfone deve estar ativo');
assert.strictEqual(recognizer.started, true, 'Recognizer deve estar iniciado');
// 2. Simula erro de rede (serviço do Google falhou temporariamente)
recognizer.onerror({ error: 'network' });
assert.strictEqual(btnVoice.classList.contains('recording'), false, 'UI deve parar modo de gravação após erro');
// 3. Verifica se toast de aviso foi exibido
const toast = document.getElementById('app-toast');
assert.ok(toast && toast.textContent.includes('Falha de conexão com o serviço de voz'), 'Toast de erro de rede deve ser exibido');
// 4. Garante que NÃO houve fallback invisível para anexo de áudio
const attachmentPreviewBar = document.getElementById('attachment-preview-bar');
assert.strictEqual(attachmentPreviewBar.style.display, 'none', 'Não deve criar anexo de áudio furtivo');
// 5. Tenta iniciar novamente (quando conexão restabelece)
btnVoice.click();
assert.strictEqual(btnVoice.classList.contains('recording'), true, 'Microfone deve conseguir iniciar novamente sem ser anulado');
assert.strictEqual(recognizer.started, true, 'Recognizer continua funcional para novas tentativas');
// 6. Simula erro service-not-allowed (permissão ou WebView temporário)
recognizer.onerror({ error: 'service-not-allowed' });
assert.strictEqual(btnVoice.classList.contains('recording'), false, 'UI deve parar modo de gravação após erro de serviço');
assert.ok(toast && toast.textContent.includes('Permissão de microfone/fala não concedida'), 'Toast de permissão deve ser exibido');
// 7. Nova tentativa subsequente ainda deve ser possível
btnVoice.click();
assert.strictEqual(btnVoice.classList.contains('recording'), true, 'Deve poder tentar novamente após erro de permissão');
// 8. Encerra voluntariamente
btnVoice.click();
assert.strictEqual(btnVoice.classList.contains('recording'), false);
});
test('21. Resiliência da Gravação contra Notificações, Perda de Foco e Enquadramento do Botão de Fechar', async () => {
// 1. Valida o enquadramento do botão de fechar do chat (#btn-close-chat)
const btnCloseChat = document.getElementById('btn-close-chat');
assert.ok(btnCloseChat, 'Botão #btn-close-chat deve existir no DOM');
assert.ok(btnCloseChat.classList.contains('btn-close-chat'), 'Botão de fechar deve possuir a classe .btn-close-chat');
assert.strictEqual(btnCloseChat.getAttribute('aria-label'), 'Fechar Chat');
// 2. Inicia gravação de voz
const btnVoice = document.getElementById('btn-voice');
const recognizer = window.SpeechRecognition.instance;
assert.ok(btnVoice, 'Botão de voz deve existir');
assert.ok(recognizer, 'Recognizer deve existir');
btnVoice.click();
assert.strictEqual(btnVoice.classList.contains('recording'), true, 'Microfone deve estar gravando');
assert.strictEqual(btnVoice.getAttribute('aria-pressed'), 'true');
// 3. Simula chegada de notificação no celular emitindo erro audio-capture
recognizer.onerror({ error: 'audio-capture' });
assert.strictEqual(btnVoice.classList.contains('recording'), true, 'Notificação/audio-capture NÃO deve parar a gravação');
// 4. Simula interrupção transitória por perda de foco (notificação shade / banner) emitindo aborted
recognizer.onerror({ error: 'aborted' });
assert.strictEqual(btnVoice.classList.contains('recording'), true, 'Perda de foco temporária (aborted) NÃO deve parar a gravação');
// 5. Simula onend gerado pelo sistema durante a notificação
recognizer.onend();
assert.strictEqual(btnVoice.classList.contains('recording'), true, 'onend transitório durante notificação NÃO deve desativar a gravação');
// 6. Simula retorno do foco (window focus / visibility visible)
window.dispatchEvent(new window.Event('focus'));
assert.strictEqual(btnVoice.classList.contains('recording'), true, 'Gravação permanece ativa após retomada de foco');
// 7. A gravação SÓ encerra estritamente quando o usuário toca novamente no botão
btnVoice.click();
assert.strictEqual(btnVoice.classList.contains('recording'), false, 'Gravação deve parar estritamente no clique voluntário do usuário');
});
test('9. Sincronização Determinística de Terminal e Telemetria de Estado de Tela', async () => {
// 1. Autentica previamente
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'Estacao Alpha',
agents: [
{ name: 'BotAssistente', isSelf: false }
],
pendingPrompts: []
})
});
// 2. Abre chat com o agente
window.openChatWithAgent('BotAssistente', '712000');
const chatInput = document.getElementById('chat-input');
const chatForm = document.getElementById('chat-form');
const chatThinkingBanner = document.getElementById('chat-thinking-banner');
const chatMessages = document.getElementById('chat-messages');
// 3. Envia um comando pelo formulário
chatInput.value = 'pesquise voos no skyscanner';
chatForm.dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
assert.strictEqual(chatThinkingBanner.style.display, 'flex', 'Banner de thinking deve ficar visível ao enviar');
// 4. Simula recebimento de AGENT_TERMINAL_OUTPUT vindo do Daemon com status determinístico isThinking=false
// mesmo que o output contenha menção a "Running command" no histórico residual
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'BotAssistente',
isThinking: false,
isPaused: false,
output: ':: Running command "skyscanner"...\nResultados carregados: R$ 450,00 voo direto.',
timestamp: new Date().toISOString()
})
});
// 5. Verifica que o banner amarelo foi desativado imediatamente
assert.strictEqual(chatThinkingBanner.style.display, 'none', 'Banner amarelo de thinking deve fechar quando isThinking=false');
// 6. Verifica que a resposta desceu como bolha de chat após o prompt do usuário
const bubbles = chatMessages.querySelectorAll('.chat-bubble');
const agentBubbles = Array.from(bubbles).filter(b => b.classList.contains('agent') && !b.classList.contains('terminal-snapshot'));
assert.ok(agentBubbles.length >= 1, 'Deve conter pelo menos uma bolha de chat do agente');
const lastAgentBubble = agentBubbles[agentBubbles.length - 1];
assert.ok(lastAgentBubble.textContent.includes('Resultados carregados'), 'Conteúdo do terminal deve ser inserido na bolha do agente');
// 7. Verifica se o snapshot de telemetria de tela foi emitido para o socket
const sentScreenSnapshots = sentWsMessages.filter(m => m.type === 'SCREEN_STATE_SNAPSHOT');
assert.ok(sentScreenSnapshots.length >= 1, 'Deve ter emitido SCREEN_STATE_SNAPSHOT para telemetria');
const latestSnapshot = sentScreenSnapshots[sentScreenSnapshots.length - 1];
assert.strictEqual(latestSnapshot.agentName, 'BotAssistente');
assert.strictEqual(latestSnapshot.payload.isThinking, false);
});
test('10. Painel TUI Interativo: abertura automática, teclas --raw, clique 1-toque em opção e toggle manual ⌨️', async () => {
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'Estacao TUI',
agents: [{ name: 'BotAssistente', isSelf: false, hasAiActivity: true }],
pendingPrompts: []
})
});
window.openChatWithAgent('BotAssistente', '712000');
const tuiPanel = document.getElementById('chat-tui-panel');
const tuiToggleBtn = document.getElementById('btn-tui-toggle');
const tuiOptionsEl = document.getElementById('chat-tui-options');
const chatThinkingBanner = document.getElementById('chat-thinking-banner');
assert.ok(tuiPanel, 'Deve existir o elemento #chat-tui-panel no DOM');
assert.ok(tuiToggleBtn, 'Deve existir o botão #btn-tui-toggle no DOM');
assert.strictEqual(tuiPanel.style.display, 'none', 'Painel TUI deve iniciar fechado');
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'BotAssistente',
isThinking: false,
isPaused: false,
hasInteractiveMenu: true,
interactiveMenu: {
hasInteractiveMenu: true,
menuTitle: 'Switch Model',
selectedIndex: 1,
rawHint: 'Keyboard: ↑/↓ Navigate enter Select esc Go Back',
options: [
{ index: 0, label: 'Gemini 4 Argon', selected: false, numberPrefix: null },
{ index: 1, label: 'Orchestrator (Argon) (current)', selected: true, numberPrefix: null },
{ index: 2, label: 'Gemini 3.8 Flash', selected: false, numberPrefix: null },
{ index: 3, label: 'Claude Opus 5.5', selected: false, numberPrefix: null }
]
},
output: 'Switch Model\n Gemini 4 Argon\n> Orchestrator (Argon) (current)\n Gemini 3.8 Flash\n Claude Opus 5.5\nKeyboard: ↑/↓ Navigate enter Select esc Go Back',
timestamp: new Date().toISOString()
})
});
assert.strictEqual(chatThinkingBanner.style.display, 'none', 'Banner amarelo NÃO deve aparecer quando há menu interativo');
assert.strictEqual(tuiPanel.style.display, 'flex', 'Painel TUI deve abrir automaticamente ao detectar menu');
const optionButtons = tuiOptionsEl.querySelectorAll('.btn-tui-option');
assert.strictEqual(optionButtons.length, 4, 'Deve renderizar todas as 4 opções detectadas');
assert.ok(optionButtons[1].classList.contains('selected'), 'Opção ativa no cursor deve ter classe .selected');
// Clique na opção 3 (delta = +2 -> duas setas p/ baixo + Enter)
optionButtons[3].click();
let rawMsgs = sentWsMessages.filter(m => m.type === 'TERMINAL_RAW_INPUT');
assert.strictEqual(rawMsgs.length, 1);
assert.deepStrictEqual(rawMsgs[0].keys, ['\\e[B', '\\e[B', '\\n']);
// Clique na opção 0 (delta = -1 -> uma seta p/ cima + Enter)
optionButtons[0].click();
rawMsgs = sentWsMessages.filter(m => m.type === 'TERMINAL_RAW_INPUT');
assert.strictEqual(rawMsgs.length, 2);
assert.deepStrictEqual(rawMsgs[1].keys, ['\\e[A', '\\n']);
// Clique no botão Esc do keypad
const escBtn = document.querySelector('.btn-tui-key.btn-tui-esc');
assert.ok(escBtn, 'Botão Esc deve existir no keypad');
escBtn.click();
rawMsgs = sentWsMessages.filter(m => m.type === 'TERMINAL_RAW_INPUT');
assert.strictEqual(rawMsgs.length, 3);
assert.strictEqual(rawMsgs[2].raw, '\\e');
// Menu fecha ao voltar ao prompt normal
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'BotAssistente',
isThinking: false,
isPaused: false,
hasInteractiveMenu: false,
interactiveMenu: null,
output: 'Model set to Claude Opus 5.5\n> \n? for shortcuts',
timestamp: new Date().toISOString()
})
});
assert.strictEqual(tuiPanel.style.display, 'none', 'Painel TUI deve fechar automaticamente quando menu some');
// Toggle manual via botão ⌨️
tuiToggleBtn.click();
assert.strictEqual(tuiPanel.style.display, 'flex', 'Botão ⌨️ deve abrir o painel TUI manualmente');
assert.ok(tuiToggleBtn.classList.contains('active'));
tuiToggleBtn.click();
assert.strictEqual(tuiPanel.style.display, 'none', 'Segundo clique no botão ⌨️ deve fechar o painel TUI');
assert.strictEqual(tuiToggleBtn.classList.contains('active'), false);
});
test('11. Home: badge 🎛️ Menu ativo, priorização no topo, alerta sonoro e fallback numérico', async () => {
let chimePlayed = false;
window.AudioContext = class {
constructor() { this.currentTime = 0; this.destination = {}; }
createOscillator() {
chimePlayed = true;
return { type: '', frequency: { setValueAtTime: () => {}, exponentialRampToValueAtTime: () => {} }, connect: () => {}, start: () => {}, stop: () => {} };
}
createGain() {
return { gain: { setValueAtTime: () => {}, exponentialRampToValueAtTime: () => {} }, connect: () => {} };
}
};
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'Estacao Alpha',
agents: [
{ name: 'AgentIdle', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: false },
{ name: 'AgentApproval', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: false }
],
pendingPrompts: []
})
});
// Confirma que o sino (🔔) nasce ativo por padrão para AgentApproval
const notifBtn = document.querySelector('.btn-terminal-notif-toggle[data-agent="AgentApproval"]');
assert.ok(notifBtn, 'Botão de notificação de AgentApproval deve existir');
assert.ok(!notifBtn.classList.contains('muted') && notifBtn.textContent.includes('🔔'), 'Sino deve nascer ativo por padrão');
// Transição false -> true para hasInteractiveMenu via AGENTS_UPDATE
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [
{ name: 'AgentIdle', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: false, interactiveMenu: null },
{
name: 'AgentApproval',
isSelf: false,
hasAiActivity: true,
isThinking: false,
hasInteractiveMenu: true,
interactiveMenu: {
hasInteractiveMenu: true,
menuTitle: 'Do you want to proceed?',
selectedIndex: 0,
options: [
{ index: 0, label: '1. Yes', selected: true, numberPrefix: '1' },
{ index: 1, label: '2. No', selected: false, numberPrefix: '2' }
],
rawHint: 'Enter to confirm · Esc to cancel'
}
}
]
})
});
const pills = Array.from(document.querySelectorAll('.station-agents-list .agent-pill'));
assert.ok(pills[0].textContent.includes('AgentApproval'), 'Agente com menu ativo deve ser priorizado no topo da lista');
assert.ok(pills[0].classList.contains('has-interactive-menu'), 'Pill deve ter classe .has-interactive-menu');
const menuTag = pills[0].querySelector('.menu-pending-tag');
assert.ok(menuTag, 'Pill deve exibir badge .menu-pending-tag');
assert.ok(menuTag.textContent.includes('Menu ativo'));
assert.strictEqual(chimePlayed, true, 'Deve tocar alerta sonoro na transição false -> true com sino ativo');
const toast = document.getElementById('app-toast');
assert.ok(toast && toast.textContent.includes('Aguardando ação em menu interativo!'));
// Verifica fallback numérico quando selectedIndex < 0 e numberPrefix presente
window.openChatWithAgent('AgentApproval', '712000');
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'AgentApproval',
isThinking: false,
hasInteractiveMenu: true,
interactiveMenu: {
hasInteractiveMenu: true,
menuTitle: 'Confirmação Numérica',
selectedIndex: -1,
options: [
{ index: 0, label: '1. Confirmar', selected: false, numberPrefix: '1' },
{ index: 1, label: '2. Recusar', selected: false, numberPrefix: '2' }
],
rawHint: 'Enter to confirm · Esc to cancel'
},
output: 'Confirmação Numérica\n1. Confirmar\n2. Recusar\nEnter to confirm · Esc to cancel',
timestamp: new Date().toISOString()
})
});
const optBtns = document.querySelectorAll('#chat-tui-options .btn-tui-option');
assert.strictEqual(optBtns.length, 2);
optBtns[1].click();
const lastRaw = sentWsMessages.filter(m => m.type === 'TERMINAL_RAW_INPUT').pop();
assert.strictEqual(lastRaw.raw, '2\\n');
});
test('12. Menu Horizontal Kilo CLI: teclas ← Esq / → Dir e clique 1-toque enviando \\e[C / \\e[D + \\n', async () => {
document.getElementById('pin-input').value = '712000';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'Estacao Kilo',
agents: [{ name: 'Kilo', isSelf: false, hasAiActivity: true }],
pendingPrompts: []
})
});
window.openChatWithAgent('Kilo', '712000');
const keypadBtns = Array.from(document.querySelectorAll('.chat-tui-keypad .btn-tui-key'));
const leftBtn = keypadBtns.find(b => b.getAttribute('data-raw') === '\\e[D');
const rightBtn = keypadBtns.find(b => b.getAttribute('data-raw') === '\\e[C');
assert.ok(leftBtn, 'Botão ← Esq deve existir no keypad');
assert.ok(rightBtn, 'Botão → Dir deve existir no keypad');
// Simula recepção de menu horizontal bruto (sem payload interactiveMenu prévio) para testar fallback local também
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'Kilo',
isThinking: false,
output: '△ Permission required\n # Verifica conectividade\n$ ping -n 4 google.com\n\nAllow once Allow always Reject ctrl+f fullscreen ⇆ select enter confirm',
timestamp: new Date().toISOString()
})
});
const tuiPanel = document.getElementById('chat-tui-panel');
assert.strictEqual(tuiPanel.style.display, 'flex', 'Painel TUI deve abrir automaticamente no menu horizontal do Kilo');
let optBtns = document.querySelectorAll('#chat-tui-options .btn-tui-option');
assert.strictEqual(optBtns.length, 3);
assert.ok(optBtns[0].classList.contains('selected'));
// Clique na opção 2 ("Reject", índice 2 a partir do índice 0 -> duas setas para direita \e[C + \n)
optBtns[2].click();
let rawMsgs = sentWsMessages.filter(m => m.type === 'TERMINAL_RAW_INPUT');
assert.strictEqual(rawMsgs.length, 1);
assert.deepStrictEqual(rawMsgs[0].keys, ['\\e[C', '\\e[C', '\\n']);
// Agora simula cursor selecionado em índice 2 ("Reject") e clique na opção 0 ("Allow once" -> duas setas esquerda \e[D + \n)
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'Kilo',
isThinking: false,
hasInteractiveMenu: true,
interactiveMenu: {
hasInteractiveMenu: true,
axis: 'horizontal',
menuTitle: 'Permission required',
selectedIndex: 2,
options: [
{ index: 0, label: 'Allow once', selected: false, numberPrefix: null },
{ index: 1, label: 'Allow always', selected: false, numberPrefix: null },
{ index: 2, label: 'Reject', selected: true, numberPrefix: null }
],
rawHint: 'ctrl+f fullscreen ⇆ select enter confirm'
},
output: '△ Permission required\n$ ping -n 4 google.com\n\nAllow once Allow always Reject ctrl+f fullscreen ⇆ select enter confirm',
timestamp: new Date().toISOString()
})
});
optBtns = document.querySelectorAll('#chat-tui-options .btn-tui-option');
optBtns[0].click();
rawMsgs = sentWsMessages.filter(m => m.type === 'TERMINAL_RAW_INPUT');
assert.strictEqual(rawMsgs.length, 2);
assert.deepStrictEqual(rawMsgs[1].keys, ['\\e[D', '\\e[D', '\\n']);
// Testa botões manuais ← Esq e → Dir
leftBtn.click();
rightBtn.click();
rawMsgs = sentWsMessages.filter(m => m.type === 'TERMINAL_RAW_INPUT');
assert.strictEqual(rawMsgs[2].raw, '\\e[D');
assert.strictEqual(rawMsgs[3].raw, '\\e[C');
});
test('13. Isolamento multi-estação em agentMenuStates, reset em INIT_STATE e fallback horizontal sanitizado', async () => {
let chimePlayedBeta = false;
window.AudioContext = class {
constructor() { this.currentTime = 0; this.destination = {}; }
createOscillator() {
chimePlayedBeta = true;
return { type: '', frequency: { setValueAtTime: () => {}, exponentialRampToValueAtTime: () => {} }, connect: () => {}, start: () => {}, stop: () => {} };
}
createGain() {
return { gain: { setValueAtTime: () => {}, exponentialRampToValueAtTime: () => {} }, connect: () => {} };
}
};
document.getElementById('pin-input').value = '111222';
const pinName = document.getElementById('pin-station-name-input');
if (pinName) pinName.value = 'Estacao Alpha';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
document.getElementById('btn-add-station').click();
document.getElementById('station-name-input').value = 'Estacao Beta';
document.getElementById('station-pin-input').value = '999888';
document.getElementById('btn-save-station').click();
await new Promise(r => setTimeout(r, 20));
assert.strictEqual(mockWsInstances.length, 2);
const wsAlpha = mockWsInstances[0];
const wsBeta = mockWsInstances[1];
wsAlpha.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: false }],
pendingPrompts: []
})
});
wsBeta.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: false }],
pendingPrompts: []
})
});
// Estação Alpha tem agente "Claude" com menu ativo; Estação Beta tem "Claude" ocioso sem menu
wsAlpha.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: true }]
})
});
wsBeta.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: false }]
})
});
const betaCard = document.getElementById('station-card-999888');
assert.ok(betaCard, 'Card da Estacao Beta deve estar renderizado');
assert.strictEqual(betaCard.querySelector('.menu-pending-tag'), null, 'Menu ativo de Alpha não deve vazar para agente de mesmo nome na Estacao Beta');
const alphaCardBefore = document.getElementById('station-card-111222');
assert.ok(alphaCardBefore.querySelector('.menu-pending-tag'), 'Estacao Alpha deve exibir tag pendente antes do reset');
// Mesmo com Claude=true chegando para Estacao Alpha logo antes, transição false -> true em Beta deve tocar alerta isolado por PIN
const betaBellBtn = betaCard.querySelector('.btn-terminal-notif-toggle[data-agent="Claude"]');
assert.ok(betaBellBtn, 'Botão de sino da Estacao Beta deve existir');
assert.ok(!betaBellBtn.classList.contains('muted') && betaBellBtn.textContent.includes('🔔'), 'Sino em Beta deve nascer ativo por padrão');
wsAlpha.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: true }]
})
});
chimePlayedBeta = false;
wsBeta.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: true }]
})
});
assert.strictEqual(chimePlayedBeta, true, 'Estado de menu em Alpha não deve suprimir transição false -> true de agente homônimo em Beta');
wsBeta.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: false }]
})
});
// INIT_STATE com hasInteractiveMenu: false na Estacao Alpha deve limpar estado antigo
wsAlpha.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: false }],
pendingPrompts: []
})
});
const alphaCard = document.getElementById('station-card-111222');
assert.ok(alphaCard, 'Card da Estacao Alpha deve estar renderizado');
assert.strictEqual(alphaCard.querySelector('.menu-pending-tag'), null, 'INIT_STATE sem menu ativo deve limpar tag pendente');
// Menu horizontal sanitizado (sem rawOutput) e reaberto via openChatWithAgent deve manter 3 opções separadas
wsBeta.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'Claude',
isThinking: false,
output: '△ Permission required\n$ ping -n 4 google.com\n\nAllow once Allow always Reject ctrl+f fullscreen ⇆ select enter confirm',
timestamp: new Date().toISOString()
})
});
window.openChatWithAgent('Claude', '999888');
const reopenedOpts = document.querySelectorAll('#chat-tui-options .btn-tui-option');
assert.strictEqual(reopenedOpts.length, 3, 'Fallback local pós-sanitização deve preservar as 3 opções horizontais');
// Saída terminada em prompt de shell PS não deve manter painel aberto no fallback local
wsBeta.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'Claude',
isThinking: false,
output: 'Switch Model\n> Gemini 4 Argon\nKeyboard: ↑/↓ Navigate enter Select esc Go Back\nPS /work/app> ',
timestamp: new Date().toISOString()
})
});
assert.strictEqual(document.getElementById('chat-tui-panel').style.display, 'none', 'Prompt de shell ao final não deve acionar menu no fallback local');
});
test('25. Regressão — openChatWithAgent não deve ressuscitar menu fechado nem vazar snapshot entre estações homônimas', async () => {
document.getElementById('pin-input').value = '111222';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
document.getElementById('btn-add-station').click();
document.getElementById('station-name-input').value = 'Estacao Beta';
document.getElementById('station-pin-input').value = '999888';
document.getElementById('btn-save-station').click();
await new Promise(r => setTimeout(r, 20));
assert.strictEqual(mockWsInstances.length, 2);
const wsAlpha = mockWsInstances[0];
const wsBeta = mockWsInstances[1];
wsAlpha.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
machineName: 'Estacao Alpha',
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: true }]
})
});
wsBeta.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
machineName: 'Estacao Beta',
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: false, interactiveMenu: null }]
})
});
// Estação Alpha recebe snapshot com menu ativo e o grava no histórico
wsAlpha.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'Claude',
isThinking: false,
hasInteractiveMenu: true,
output: 'Switch Model\n> Gemini 4 Argon\n Gemini 4 Flash\nKeyboard: ↑/↓ Navigate enter Select esc Go Back',
timestamp: new Date().toISOString()
})
});
// Cenário 1: abrir Claude na Estação Beta (sem histórico próprio e com hasInteractiveMenu: false) NÃO pode herdar snapshot da Estação Alpha
window.openChatWithAgent('Claude', '999888', 'Estacao Beta');
const tuiPanel = document.getElementById('chat-tui-panel');
const tuiOptions = document.getElementById('chat-tui-options');
assert.strictEqual(document.getElementById('chat-terminal-snapshot-body'), null, 'Histórico/snapshot de Estação Alpha não deve vazar para Estação Beta');
assert.strictEqual(tuiPanel.style.display, 'none', 'openChatWithAgent em Estação Beta não deve abrir painel TUI com snapshot da Estação Alpha');
assert.strictEqual(tuiOptions.querySelectorAll('.btn-tui-option').length, 0, 'Opções do menu da Estação Alpha não devem vazar para Estação Beta');
window.closeChat();
// Cenário 2: na Estação Alpha, usuário fecha o chat com menu ativo e AGENTS_UPDATE sinaliza encerramento do menu antes do próximo GET_AGENT_TERMINAL
wsAlpha.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: false, interactiveMenu: null }]
})
});
window.openChatWithAgent('Claude', '111222', 'Estacao Alpha');
assert.strictEqual(tuiPanel.style.display, 'none', 'openChatWithAgent não deve ressuscitar menu fechado quando AGENTS_UPDATE já reportou hasInteractiveMenu: false');
assert.strictEqual(tuiOptions.querySelectorAll('.btn-tui-option').length, 0, 'Não deve renderizar chips obsoletos após encerramento do menu');
window.closeChat();
// Cenário 3: quando snapshot tem menu TUI ativo mesmo com isWaitingChatReply=true, renderChatMessages não deve exibir card de thinking
wsBeta.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'Claude',
isThinking: false,
hasInteractiveMenu: true,
output: '△ Permission required\nExecuting tool...\nAllow once Allow always Reject ctrl+f fullscreen ⇆ select enter confirm',
timestamp: new Date().toISOString()
})
});
window.openChatWithAgent('Claude', '999888', 'Estacao Beta');
document.getElementById('chat-input').value = 'prosseguir';
document.getElementById('chat-form').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));
assert.strictEqual(document.querySelector('.chat-bubble.thinking-card'), null, 'Não deve exibir card de thinking enquanto um menu TUI estiver ativo');
});
test('26. Isolamento estrito por PIN em notificações/thinking multiestação, mute pelo chat e título sem spinner no fallback local', async () => {
let chimeCount = 0;
window.AudioContext = class MockAudioContext {
constructor() { this.currentTime = 0; }
createOscillator() {
chimeCount++;
return { type: '', frequency: { setValueAtTime: () => {}, exponentialRampToValueAtTime: () => {} }, connect: () => {}, start: () => {}, stop: () => {} };
}
createGain() {
return { gain: { setValueAtTime: () => {}, exponentialRampToValueAtTime: () => {} }, connect: () => {} };
}
};
document.getElementById('pin-input').value = '111222';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
document.getElementById('btn-add-station').click();
document.getElementById('station-name-input').value = 'Estacao Beta';
document.getElementById('station-pin-input').value = '999888';
document.getElementById('btn-save-station').click();
await new Promise(r => setTimeout(r, 20));
const wsAlpha = mockWsInstances[0];
const wsBeta = mockWsInstances[1];
wsAlpha.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
machineName: 'Estacao Alpha',
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: false }]
})
});
wsBeta.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
machineName: 'Estacao Beta',
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: false }]
})
});
// 1. Silenciar sino em Beta (999888) não deve silenciar sino em Alpha (111222) nem vazar estado
const betaBell = document.querySelector('#station-card-999888 .btn-terminal-notif-toggle[data-agent="Claude"]');
assert.ok(!betaBell.classList.contains('muted'), 'Sino em Beta nasce ativo por padrão');
betaBell.click();
const betaBellAfterClick = document.querySelector('#station-card-999888 .btn-terminal-notif-toggle[data-agent="Claude"]');
assert.ok(betaBellAfterClick.classList.contains('muted'), 'Sino de Claude na Estação Beta deve ficar silenciado');
const alphaBell = document.querySelector('#station-card-111222 .btn-terminal-notif-toggle[data-agent="Claude"]');
assert.ok(!alphaBell.classList.contains('muted'), 'Sino de Claude na Estação Alpha deve permanecer ativo');
wsBeta.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: true }]
})
});
assert.strictEqual(chimeCount, 0, 'Menu ativo em Beta silenciado não deve tocar alerta');
// 2. Silenciar pelo botão de sino no cabeçalho do chat deve refletir na Home e impedir alertas seguintes em Alpha
window.openChatWithAgent('Claude', '111222', 'Estacao Alpha');
const chatNotifBtn = document.getElementById('chat-notif-toggle-btn');
assert.strictEqual(chatNotifBtn.textContent, '🔔');
chatNotifBtn.click();
assert.strictEqual(chatNotifBtn.textContent, '🔕', 'Botão do chat deve alternar para silenciado');
const alphaBellAfterChatMute = document.querySelector('#station-card-111222 .btn-terminal-notif-toggle[data-agent="Claude"]');
assert.ok(alphaBellAfterChatMute.classList.contains('muted'), 'Mute pelo cabeçalho do chat deve silenciar também o sino da Home');
wsAlpha.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: true }]
})
});
assert.strictEqual(chimeCount, 0, 'Após silenciar pelo chat, novo menu em Alpha não deve disparar alerta');
window.closeChat();
// 3. agentThinkingStates em Alpha não deve vazar status ⚡ Pensando para agente homônimo ocioso em Beta
wsAlpha.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: true, hasInteractiveMenu: false }]
})
});
wsBeta.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
machineName: 'Estacao Beta',
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: false }]
})
});
const alphaClaudePill = document.querySelector('#station-card-111222 .agent-pill');
const betaClaudePill = document.querySelector('#station-card-999888 .agent-pill');
assert.strictEqual(alphaClaudePill.classList.contains('thinking'), true, 'Estação Alpha deve exibir Claude em thinking');
assert.strictEqual(betaClaudePill.classList.contains('thinking'), false, 'Status thinking de Alpha não deve vazar para Claude ocioso em Beta');
// 4. Fallback local extractMenuTitle deve pular linhas de spinner/execução ao buscar título acima das opções
const menuWithSpinner = window.detectInteractiveMenu(
'Do you want to proceed?\n⠋ Running command...\n❯ 1. Yes\n 2. No\nEnter to confirm · Esc to cancel'
);
assert.strictEqual(menuWithSpinner.hasInteractiveMenu, true);
assert.strictEqual(menuWithSpinner.menuTitle, 'Do you want to proceed?', 'extractMenuTitle do fallback local deve ignorar linhas de spinner/execução');
});
test('21. Botão #btn-restart-terminal no cabeçalho do Chat, proteção isSelf/reentrância, limpeza e AGENT_TERMINAL_RESTARTED', async () => {
const pinInput = document.getElementById('pin-input');
const btnConnect = document.getElementById('btn-connect');
pinInput.value = '808080';
btnConnect.click();
await new Promise(r => setTimeout(r, 30));
// Verifica posição no .chat-header: #btn-restart-terminal deve ficar antes de #btn-refresh-chat, e este antes de #btn-close-chat
const btnRefresh = document.getElementById('btn-refresh-chat');
const btnRestart = document.getElementById('btn-restart-terminal');
const btnClose = document.getElementById('btn-close-chat');
assert.ok(btnRestart, '#btn-restart-terminal deve existir no DOM');
assert.ok(btnRefresh && btnClose);
assert.strictEqual(btnRestart.nextElementSibling?.id, 'btn-refresh-chat', '#btn-restart-terminal deve ficar antes de #btn-refresh-chat');
assert.strictEqual(btnRefresh.nextElementSibling?.id, 'btn-close-chat', '#btn-refresh-chat deve ficar antes de #btn-close-chat');
assert.strictEqual(btnRestart.style.minWidth, '44px');
assert.strictEqual(btnRestart.style.minHeight, '44px');
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
machineName: 'Estacao-Dev',
agents: [
{ name: 'maestri-remote', isSelf: true, hasAiActivity: false },
{ name: 'Claude', isSelf: false, hasAiActivity: true, isThinking: true, hasInteractiveMenu: true }
]
})
});
// 1. Proteção isSelf: não envia RESTART_AGENT_TERMINAL nem ativa .restarting
window.openChatWithAgent('maestri-remote', '808080', 'Estacao-Dev');
sentWsMessages.length = 0;
btnRestart.click();
assert.strictEqual(btnRestart.classList.contains('restarting'), false);
assert.strictEqual(btnRestart.disabled, false);
assert.strictEqual(sentWsMessages.some(m => m.type === 'RESTART_AGENT_TERMINAL'), false, 'Não deve enviar RESTART_AGENT_TERMINAL para isSelf');
const selfToast = document.getElementById('app-toast');
assert.ok(selfToast && /daemon supervisor/i.test(selfToast.textContent));
assert.strictEqual(selfToast.style.borderColor, 'rgb(245, 158, 11)');
// 2. Abre chat com agente normal contendo menu TUI, banner thinking e indicador #chat-typing-indicator ativos
window.openChatWithAgent('Claude', '808080', 'Estacao-Dev');
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'Claude',
output: 'Thinking...\nDo you confirm?\n❯ 1. Yes\n 2. No\nEnter to confirm · Esc to cancel',
rawOutput: 'Thinking...\nDo you confirm?\n❯ 1. Yes\n 2. No\nEnter to confirm · Esc to cancel',
hasAiActivity: true,
isThinking: true,
hasInteractiveMenu: true,
interactiveMenu: {
hasInteractiveMenu: true,
menuTitle: 'Do you confirm?',
options: [
{ index: 0, label: 'Yes', selected: true },
{ index: 1, label: 'No', selected: false }
]
}
})
});
const chatMessagesEl = document.getElementById('chat-messages');
const fakeTyping = document.createElement('div');
fakeTyping.id = 'chat-typing-indicator';
chatMessagesEl.appendChild(fakeTyping);
const chatTuiPanel = document.getElementById('chat-tui-panel');
assert.strictEqual(chatTuiPanel.style.display, 'flex', 'Painel TUI deve estar visível antes do reinício');
assert.ok(document.getElementById('chat-typing-indicator'), '#chat-typing-indicator deve existir antes do reinício');
sentWsMessages.length = 0;
btnRestart.click();
// Verifica estado .restarting, toast informativo, envio de RESTART_AGENT_TERMINAL, limpeza de TUI/thinking e limpeza do chat
assert.strictEqual(btnRestart.classList.contains('restarting'), true);
assert.strictEqual(btnRestart.disabled, true);
assert.strictEqual(chatTuiPanel.style.display, 'none', 'Painel TUI pendente deve ser limpo ao iniciar reinício');
const chatThinkingBanner = document.getElementById('chat-thinking-banner');
assert.strictEqual(chatThinkingBanner.style.display, 'none', 'Banner de thinking deve ser limpo ao iniciar reinício');
assert.strictEqual(window.getAgentChatHistory('Claude', '808080').length, 0, 'Histórico do agente deve ser limpo ao reiniciar');
assert.ok(document.getElementById('chat-typing-indicator'), 'Deve exibir loading indicador de leitura da nova sessão');
assert.strictEqual(document.getElementById('chat-terminal-output-raw')?.textContent, 'Aguardando inicialização da nova sessão...', 'Buffer cru deve ser resetado');
const infoToast = document.getElementById('app-toast');
assert.ok(infoToast.textContent.includes('Reiniciando terminal Claude via Maestri'));
assert.strictEqual(infoToast.style.borderColor, 'rgb(56, 189, 248)');
const restartReqs = sentWsMessages.filter(m => m.type === 'RESTART_AGENT_TERMINAL');
assert.strictEqual(restartReqs.length, 1);
assert.strictEqual(restartReqs[0].agentName, 'Claude');
// Reentrância: segundo clique ou touchend enquanto .restarting não deve disparar novo envio
btnRestart.click();
btnRestart.dispatchEvent(new window.Event('touchend', { bubbles: true, cancelable: true }));
assert.strictEqual(sentWsMessages.filter(m => m.type === 'RESTART_AGENT_TERMINAL').length, 1);
// 3. Resposta AGENT_TERMINAL_RESTARTED ok: true reabilita botão, exibe toast verde e solicita releitura do terminal ativo
sentWsMessages.length = 0;
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_RESTARTED',
agentName: 'Claude',
ok: true,
method: 'recruit_replace',
error: null
})
});
assert.strictEqual(btnRestart.classList.contains('restarting'), false);
assert.strictEqual(btnRestart.disabled, false);
const okToast = document.getElementById('app-toast');
assert.ok(okToast.textContent.includes('Terminal Claude reiniciado'));
assert.strictEqual(okToast.style.borderColor, 'rgb(52, 211, 153)');
assert.strictEqual(sentWsMessages.some(m => m.type === 'GET_AGENT_TERMINAL' && m.agentName === 'Claude'), true);
// Resposta ok: true para outro agente não solicita GET_AGENT_TERMINAL para Claude
sentWsMessages.length = 0;
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_RESTARTED',
agentName: 'OutroAgente',
ok: true
})
});
assert.strictEqual(sentWsMessages.some(m => m.type === 'GET_AGENT_TERMINAL'), false);
// Snapshot subsequente atualiza saída no terminal
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'Claude',
output: 'Claude Code reiniciado e pronto',
rawOutput: 'Claude Code reiniciado e pronto',
hasAiActivity: true,
isThinking: false,
hasInteractiveMenu: false
})
});
assert.ok(document.getElementById('chat-terminal-output-raw').textContent.includes('Claude Code reiniciado e pronto'));
// 4. Resposta AGENT_TERMINAL_RESTARTED ok: false limpa .restarting e exibe toast de erro (específico e fallback)
btnRestart.click();
assert.strictEqual(btnRestart.classList.contains('restarting'), true);
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_RESTARTED',
agentName: 'Claude',
ok: false,
method: 'raw_restart',
error: 'IPC timeout'
})
});
assert.strictEqual(btnRestart.classList.contains('restarting'), false);
assert.strictEqual(btnRestart.disabled, false);
assert.ok(document.getElementById('app-toast').textContent.includes('IPC timeout'));
assert.strictEqual(document.getElementById('app-toast').style.borderColor, 'rgb(239, 68, 68)');
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_RESTARTED',
agentName: 'Claude',
ok: false
})
});
assert.ok(document.getElementById('app-toast').textContent.includes('erro desconhecido'));
// 5. Fechar chat, trocar de chat e evento touchend + WS offline
btnRestart.click();
assert.strictEqual(btnRestart.classList.contains('restarting'), true);
window.closeChat();
assert.strictEqual(btnRestart.classList.contains('restarting'), false);
assert.strictEqual(btnRestart.disabled, false);
// Sem chat aberto não faz nada
sentWsMessages.length = 0;
window.restartActiveAgentTerminal();
assert.strictEqual(sentWsMessages.length, 0);
window.openChatWithAgent('Claude', '808080', 'Estacao-Dev');
btnRestart.dispatchEvent(new window.Event('touchend', { bubbles: true, cancelable: true }));
assert.strictEqual(btnRestart.classList.contains('restarting'), true);
window.openChatWithAgent('maestri-remote', '808080', 'Estacao-Dev');
assert.strictEqual(btnRestart.classList.contains('restarting'), false);
assert.strictEqual(btnRestart.disabled, false);
// WS offline exibe toast warning sem iniciar .restarting e evento preventDefault funciona
window.openChatWithAgent('Claude', '808080', 'Estacao-Dev');
mockWsInstance.readyState = 3;
sentWsMessages.length = 0;
const evtClick = new window.Event('click', { bubbles: true, cancelable: true });
btnRestart.dispatchEvent(evtClick);
assert.strictEqual(evtClick.defaultPrevented, true);
assert.strictEqual(btnRestart.classList.contains('restarting'), false);
assert.ok(document.getElementById('app-toast').textContent.includes('Estação offline'));
assert.strictEqual(document.getElementById('app-toast').style.borderColor, 'rgb(245, 158, 11)');
// Cross-station PIN isolation: eventos de outro PIN não interferem no reinício em andamento da estação ativa, e queda do gateway/WS ativo destrava .restarting
mockWsInstances[0].readyState = 1;
document.getElementById('btn-add-station').click();
document.getElementById('station-name-input').value = 'Estacao-Remota';
document.getElementById('station-pin-input').value = '909090';
document.getElementById('btn-save-station').click();
await new Promise(r => setTimeout(r, 30));
const wsSecond = mockWsInstances[1];
assert.ok(wsSecond, 'Segunda estação deve ter socket próprio');
wsSecond.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
machineName: 'Estacao-Remota',
agents: [{ name: 'Claude', isSelf: false }]
})
});
window.openChatWithAgent('Claude', '808080', 'Estacao-Dev');
btnRestart.click();
assert.strictEqual(btnRestart.classList.contains('restarting'), true);
sentWsMessages.length = 0;
wsSecond.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_RESTARTED',
agentName: 'Claude',
ok: true
})
});
assert.strictEqual(btnRestart.classList.contains('restarting'), true, 'AGENT_TERMINAL_RESTARTED de outro PIN não pode destravar botão ativo');
assert.strictEqual(btnRestart.disabled, true);
assert.strictEqual(sentWsMessages.some(m => m.type === 'GET_AGENT_TERMINAL'), false, 'Evento de outro PIN não deve disparar GET_AGENT_TERMINAL no chat ativo');
// GATEWAY_STATUS offline em outro PIN também não destrava botão ativo
wsSecond.onmessage({ data: JSON.stringify({ type: 'GATEWAY_STATUS', connected: false }) });
assert.strictEqual(btnRestart.classList.contains('restarting'), true);
// GATEWAY_STATUS offline na estação ativa destrava o botão imediatamente
mockWsInstances[0].onmessage({ data: JSON.stringify({ type: 'GATEWAY_STATUS', connected: false }) });
assert.strictEqual(btnRestart.classList.contains('restarting'), false);
assert.strictEqual(btnRestart.disabled, false);
// Reativa estação e valida que socket.onclose na estação ativa destrava .restarting
mockWsInstances[0].onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
machineName: 'Estacao-Dev',
agents: [{ name: 'Claude', isSelf: false }]
})
});
btnRestart.click();
assert.strictEqual(btnRestart.classList.contains('restarting'), true);
mockWsInstances[0].onclose();
assert.strictEqual(btnRestart.classList.contains('restarting'), false);
assert.strictEqual(btnRestart.disabled, false);
});
test('22. Regressão E2E Kilo CLI com borda ┃: toque em "Allow always" envia 1 seta direita [\\e[C, \\n] e menu Always allow', async () => {
document.getElementById('pin-input').value = '717171';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 30));
const boxedKiloOutput = [
' ┃ △ Permission required',
' ┃ # List files in the current directory to identify build artifacts or project files.',
' ┃',
' ┃ $ Get-ChildItem -LiteralPath "."',
' ┃',
' ┃ Allow once Allow always Reject ctrl+f fullscreen ⇆ select enter confirm ',
' ┃'
].join('\n');
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
machineName: 'Estacao-Kilo',
agents: [{ name: 'cdcivel-sdlc-workflow', isSelf: false, hasAiActivity: true }]
})
});
window.openChatWithAgent('cdcivel-sdlc-workflow', '717171', 'Estacao-Kilo');
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'cdcivel-sdlc-workflow',
output: boxedKiloOutput,
rawOutput: boxedKiloOutput
})
});
const optionButtons = Array.from(document.querySelectorAll('#chat-tui-options .btn-tui-option'));
assert.deepStrictEqual(
optionButtons.map(b => b.textContent),
['❯ Allow once', 'Allow always', 'Reject'],
'UI deve renderizar exatamente as 3 opções sem elemento espúrio ┃'
);
sentWsMessages.length = 0;
optionButtons[1].click(); // Toca em "Allow always"
const rawMsg = sentWsMessages.find(m => m.type === 'TERMINAL_RAW_INPUT');
assert.ok(rawMsg, 'Clique em "Allow always" deve emitir TERMINAL_RAW_INPUT');
assert.deepStrictEqual(rawMsg.keys, ['\\e[C', '\\n'], 'Deve enviar exatamente 1 seta para direita + Enter (nunca 2 setas para Reject)');
assert.strictEqual(rawMsg.raw, '\\e[C\\n');
// Segundo diálogo subsequente: Always allow -> Confirm / Cancel
const boxedAlwaysAllow = [
' ┃ △ Always allow',
' ┃ - Get-ChildItem *',
' ┃ Confirm Cancel ⇆ select enter confirm ',
' ┃'
].join('\n');
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'cdcivel-sdlc-workflow',
output: boxedAlwaysAllow,
rawOutput: boxedAlwaysAllow
})
});
const tuiTitle = document.getElementById('chat-tui-title');
assert.ok(tuiTitle.textContent.includes('Always allow'));
assert.strictEqual(tuiTitle.textContent.includes('Get-ChildItem'), false);
const confirmCancelBtns = Array.from(document.querySelectorAll('#chat-tui-options .btn-tui-option'));
assert.deepStrictEqual(confirmCancelBtns.map(b => b.textContent), ['❯ Confirm', 'Cancel']);
sentWsMessages.length = 0;
confirmCancelBtns[1].click(); // Cancel
const cancelMsg = sentWsMessages.find(m => m.type === 'TERMINAL_RAW_INPUT');
assert.deepStrictEqual(cancelMsg.keys, ['\\e[C', '\\n']);
// Kilo 2 linhas dentro de caixa com linha ┃ vazia separadora e título sem RE_APPROVAL_HEADER + sanitização preservando 2+ espaços
const boxedTwoLineFallback = [
' ┃ Escopo personalizado',
' ┃ - Get-ChildItem *',
' ┃ Confirm Cancel',
' ┃',
' ┃ ⇆ select enter confirm',
' ┃'
].join('\n');
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'cdcivel-sdlc-workflow',
output: boxedTwoLineFallback,
rawOutput: boxedTwoLineFallback
})
});
assert.ok(document.getElementById('chat-tui-title').textContent.includes('Escopo personalizado'));
assert.strictEqual(document.getElementById('chat-tui-title').textContent.includes('Get-ChildItem'), false);
assert.deepStrictEqual(
Array.from(document.querySelectorAll('#chat-tui-options .btn-tui-option')).map(b => b.textContent),
['❯ Confirm', 'Cancel']
);
assert.match(document.getElementById('chat-terminal-output-raw').textContent, /Confirm\s{2,}Cancel/);
// Kilo com destaque ANSI em "Allow always" e borda ┃ amarela: toque em "Allow once" envia 1 seta para esquerda [\e[D, \n]
const boxedAnsiHighlight =
' \x1B[33m┃\x1B[0m △ Permission required\n' +
' \x1B[33m┃\x1B[0m \x1B[48;5;236mAllow once\x1B[0m \x1B[48;5;214;30mAllow always\x1B[0m \x1B[48;5;236mReject\x1B[0m ctrl+f fullscreen ⇆ select enter confirm \n' +
' ┃';
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'cdcivel-sdlc-workflow',
output: boxedAnsiHighlight,
rawOutput: boxedAnsiHighlight
})
});
const ansiBtns = Array.from(document.querySelectorAll('#chat-tui-options .btn-tui-option'));
assert.deepStrictEqual(ansiBtns.map(b => b.textContent), ['Allow once', '❯ Allow always', 'Reject']);
sentWsMessages.length = 0;
ansiBtns[0].click();
const leftMsg = sentWsMessages.find(m => m.type === 'TERMINAL_RAW_INPUT');
assert.deepStrictEqual(leftMsg.keys, ['\\e[D', '\\n']);
});
test('27. AGENTS_UPDATE destrava ⚡ congelado em lastTerminalOutputs, notifica 🔔 na conclusão e detectAgentThinking cobre Kiro CLI/subagentes', async () => {
let chimeCount = 0;
window.AudioContext = class MockAudioContext {
constructor() { this.currentTime = 0; }
createOscillator() {
chimeCount++;
return { type: '', frequency: { setValueAtTime: () => {}, exponentialRampToValueAtTime: () => {} }, connect: () => {}, start: () => {}, stop: () => {} };
}
createGain() {
return { gain: { setValueAtTime: () => {}, exponentialRampToValueAtTime: () => {} }, connect: () => {} };
}
};
document.getElementById('pin-input').value = '161818';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
machineName: 'nitro',
agents: [
{ name: 'gp200mod', isSelf: false, hasAiActivity: true, aiType: 'kiro', isThinking: true },
{ name: 'KiroLive', isSelf: false, hasAiActivity: true, aiType: 'kiro', isThinking: true }
],
pendingPrompts: []
})
});
const bellGp200 = document.querySelector('#station-card-161818 .btn-terminal-notif-toggle[data-agent="gp200mod"]');
assert.ok(bellGp200, 'Botão de sino do gp200mod deve existir');
assert.ok(!bellGp200.classList.contains('muted'), 'Sino do gp200mod deve nascer ativo por padrão');
const bellKiroLive = document.querySelector('#station-card-161818 .btn-terminal-notif-toggle[data-agent="KiroLive"]');
assert.ok(bellKiroLive, 'Botão de sino do KiroLive deve existir');
assert.ok(!bellKiroLive.classList.contains('muted'), 'Sino do KiroLive deve nascer ativo por padrão');
// Popula lastTerminalOutputs com frame do Kiro trabalhando e fecha o chat (caso real gp200mod)
window.openChatWithAgent('gp200mod', '161818', 'nitro');
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'gp200mod',
output: 'in your working directory\nᗥ Thinking... (esc to cancel)\n› Kiro is working · 1m 47s',
rawOutput: 'in your working directory\nᗥ Thinking... (esc to cancel)\n› Kiro is working · 1m 47s',
hasAiActivity: true,
aiType: 'kiro',
isThinking: true
})
});
window.closeChat();
// Gateway reporta conclusão na Home (AGENTS_UPDATE): não pode ser sobrescrito por lastTerminalOutputs congelado
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [
{ name: 'gp200mod', isSelf: false, hasAiActivity: true, aiType: 'kiro', isThinking: false, isPaused: false, hasInteractiveMenu: false },
{ name: 'KiroLive', isSelf: false, hasAiActivity: true, aiType: 'kiro', isThinking: true, isPaused: false, hasInteractiveMenu: false }
]
})
});
const gp200Pill = Array.from(document.querySelectorAll('#station-card-161818 .agent-pill'))
.find(p => p.textContent.includes('gp200mod'));
assert.ok(gp200Pill, 'Pill do gp200mod deve existir na Home');
assert.strictEqual(gp200Pill.classList.contains('thinking'), false, 'Home não pode manter ⚡ travado quando Gateway reporta isThinking: false');
assert.ok(gp200Pill.classList.contains('has-unread-reply'), 'Home deve exibir marcador de resposta nova após conclusão fora do chat');
const toastAfterAgentsUpdate = document.getElementById('app-toast');
assert.ok(toastAfterAgentsUpdate && toastAfterAgentsUpdate.textContent.includes('gp200mod'), 'Toast 🔔 deve notificar conclusão na Home via AGENTS_UPDATE');
assert.strictEqual(chimeCount, 1, 'Deve tocar chime exatamente 1 vez para gp200mod');
// Transição isThinking true -> false via AGENT_TERMINAL_OUTPUT em outro agente com chat fechado/minimizado sem CHAT_RESPONSE
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'KiroLive',
output: 'Tarefas concluídas.\n▸ Credits: turn 2.41 • session 115.28 | Time: 37s\n› ask a question or describe a task ↵',
rawOutput: 'Tarefas concluídas.\n▸ Credits: turn 2.41 • session 115.28 | Time: 37s\n› ask a question or describe a task ↵',
hasAiActivity: true,
aiType: 'kiro',
isThinking: false
})
});
assert.strictEqual(chimeCount, 2, 'AGENT_TERMINAL_OUTPUT com transição true -> false deve notificar conclusão via 🔔');
// Detector frontend alinhado ao Kiro CLI moderno e subagente AGY
assert.strictEqual(typeof window.detectAgentThinking, 'function', 'detectAgentThinking deve estar exposto em window');
const idleKiro = window.detectAgentThinking([
'Running command npm test',
'The file will have its original line endings in your working directory',
'▸ Credits: turn 4.76 • session 101.34 | Time: 33s',
'Default · claude-sonnet-5.5 · medium · ◑ 36%',
'› ask a question or describe a task ↵'
].join('\n'));
assert.strictEqual(idleKiro.isThinking, false, 'Kiro CLI em prompt › ask a question... deve ser detectado como ocioso sobre scrollback anterior');
const workingKiro = window.detectAgentThinking('ᗥ Thinking... (esc to cancel)\n› Kiro is working · 1m 47s');
assert.strictEqual(workingKiro.isThinking, true, 'Spinner Pac-Man / Kiro is working deve ser detectado como trabalhando');
const workingDirOnly = window.detectAgentThinking('Arquivo salvo em your working directory.');
assert.strictEqual(workingDirOnly.isThinking, false, 'Frase working directory fora de execução não pode gerar falso positivo ⚡');
const activeSubagentAgy = window.detectAgentThinking([
'>',
'● Agent(self: Builder) · 3m1s',
'? for shortcuts auto · 1 subagent(s)'
].join('\n'));
assert.strictEqual(activeSubagentAgy.isThinking, true, 'Subagente ativo no Antigravity deve manter isThinking: true mesmo com > acima');
});
test('28. renderTuiPanel oculta .chat-tui-keypad quando há ações detectadas, alterna via ⌨️ e sanitiza borda ┃ legado', async () => {
document.getElementById('pin-input').value = '161818';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
machineName: 'nitro',
agents: [{ name: 'cdcivel-sdlc-workflow', isSelf: false, hasAiActivity: true, isThinking: false }],
pendingPrompts: []
})
});
window.openChatWithAgent('cdcivel-sdlc-workflow', '161818', 'nitro');
const tuiPanel = document.getElementById('chat-tui-panel');
const tuiOptions = document.getElementById('chat-tui-options');
const tuiKeypad = document.querySelector('.chat-tui-keypad');
const tuiHint = document.getElementById('chat-tui-hint');
const tuiTitle = document.getElementById('chat-tui-title');
const btnTuiToggle = document.getElementById('btn-tui-toggle');
// 1. Menu detectado sem rawHint e sem abertura manual -> keypad oculto e hint direto
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'cdcivel-sdlc-workflow',
output: 'Permission required\nAllow once Allow always Reject',
hasInteractiveMenu: true,
interactiveMenu: {
hasInteractiveMenu: true,
axis: 'horizontal',
menuTitle: 'Permission required',
selectedIndex: 0,
options: [
{ index: 0, label: 'Allow once', selected: true },
{ index: 1, label: 'Allow always', selected: false },
{ index: 2, label: 'Reject', selected: false }
],
rawHint: ''
}
})
});
assert.strictEqual(tuiPanel.style.display, 'flex');
assert.strictEqual(tuiOptions.style.display, 'flex');
assert.strictEqual(tuiKeypad.style.display, 'none', 'Keypad manual deve ficar oculto no fluxo automático de ações detectadas');
assert.strictEqual(tuiHint.textContent, 'Toque na ação desejada', 'Hint padrão deve orientar apenas toque na ação quando keypad estiver oculto');
// 2. Toggle manual ⌨️ exibe e oculta o keypad mesmo com opções detectadas
btnTuiToggle.click();
assert.strictEqual(tuiKeypad.style.display, 'grid', 'Clique em ⌨️ deve exibir keypad manualmente');
btnTuiToggle.click();
assert.strictEqual(tuiKeypad.style.display, 'none', 'Novo clique em ⌨️ deve voltar a ocultar o keypad');
// 3. Sem menu detectado, abrir manualmente ⌨️ mostra keypad e esconde opções
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'cdcivel-sdlc-workflow',
output: '>\n? for shortcuts',
hasInteractiveMenu: false
})
});
assert.strictEqual(tuiPanel.style.display, 'none');
btnTuiToggle.click();
assert.strictEqual(tuiPanel.style.display, 'flex');
assert.strictEqual(tuiOptions.style.display, 'none');
assert.strictEqual(tuiKeypad.style.display, 'grid');
assert.strictEqual(tuiHint.textContent, 'Envio direto de setas e atalhos (--raw)');
btnTuiToggle.click();
// 4. Payload legado com borda ┃ como opção 0 e no título deve ser sanitizado defensivamente em AGENT_TERMINAL_OUTPUT (recuperando destaque real de rawOutput)
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'cdcivel-sdlc-workflow',
output: 'Permission required',
rawOutput: [
' \x1B[33m┃\x1B[0m △ Permission required',
' \x1B[33m┃\x1B[0m \x1B[48;5;236mAllow once\x1B[0m \x1B[48;5;214;30mAllow always\x1B[0m \x1B[48;5;236mReject\x1B[0m ctrl+f fullscreen ⇆ select enter confirm'
].join('\n'),
hasInteractiveMenu: true,
interactiveMenu: {
hasInteractiveMenu: true,
axis: 'horizontal',
menuTitle: '┃ △ Permission required',
selectedIndex: 0,
options: [
{ index: 0, label: '┃', selected: true },
{ index: 1, label: 'Allow once', selected: false },
{ index: 2, label: 'Allow always', selected: false },
{ index: 3, label: 'Reject', selected: false }
],
rawHint: '┃ ctrl+f fullscreen ⇆ select enter confirm'
}
})
});
assert.strictEqual(tuiTitle.textContent, '🎛️ △ Permission required', 'Título TUI deve remover borda ┃ legada');
const cleanBtns = Array.from(tuiOptions.querySelectorAll('.btn-tui-option')).map(b => b.textContent);
assert.deepStrictEqual(cleanBtns, ['Allow once', '❯ Allow always', 'Reject'], 'Sanitização deve descartar botão ┃ e recuperar Allow always selecionado via rawOutput');
assert.strictEqual(tuiKeypad.style.display, 'none');
// 5. Payload legado em AGENTS_UPDATE antes de openChatWithAgent também deve ser sanitizado
window.closeChat();
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENTS_UPDATE',
agents: [{
name: 'cdcivel-sdlc-workflow',
isSelf: false,
hasAiActivity: true,
isThinking: false,
hasInteractiveMenu: true,
interactiveMenu: {
hasInteractiveMenu: true,
axis: 'horizontal',
menuTitle: '┃ △ Permission required',
selectedIndex: 0,
options: [
{ index: 0, label: '┃', selected: true },
{ index: 1, label: 'Confirm', selected: false },
{ index: 2, label: 'Cancel', selected: false }
],
rawHint: 'ctrl+f fullscreen'
}
}]
})
});
window.openChatWithAgent('cdcivel-sdlc-workflow', '161818', 'nitro');
const fallbackCleanBtns = Array.from(tuiOptions.querySelectorAll('.btn-tui-option')).map(b => b.textContent);
assert.strictEqual(fallbackCleanBtns.some(t => t.includes('┃')), false, 'openChatWithAgent não deve exibir botão ┃ de AGENTS_UPDATE legado');
assert.deepStrictEqual(fallbackCleanBtns, ['❯ Confirm', 'Cancel']);
});
test('27. Interação com Menu de Modelos TUI do Antigravity e Kilo no Frontend', async () => {
window.openChatWithAgent('AgyAgent', '161818', 'nitro');
const tuiPanel = document.getElementById('chat-tui-panel');
const tuiOptions = document.getElementById('chat-tui-options');
const tuiTitle = document.getElementById('chat-tui-title');
// 1. Recebe saída do terminal com Switch Model do Antigravity
const agySwitchModel = [
'Switch Model',
'',
' Search: ',
' ────────────────────',
'',
' Gemini 4 Argon',
' Gemini 4 Hydrogen',
' Orchestrator (Argon)',
'> Gemini 3.8 Flash (current)',
' Claude Opus 5.5',
' Claude Sonnet 5.5',
' GPT-OSS 120B (Medium)',
' Gemini 4 Carbon ',
'',
'Keyboard: ↑/↓ Navigate enter Select esc Go Back'
].join('\n');
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'AgyAgent',
rawOutput: agySwitchModel,
hasInteractiveMenu: true,
isThinking: false
})
});
assert.strictEqual(tuiPanel.style.display, 'flex');
assert.strictEqual(tuiTitle.textContent, '🎛️ Switch Model');
const optionBtns = Array.from(tuiOptions.querySelectorAll('.btn-tui-option'));
assert.strictEqual(optionBtns.length, 8);
assert.strictEqual(optionBtns[3].textContent, '❯ Gemini 3.8 Flash (current)');
assert.strictEqual(optionBtns[4].textContent, 'Claude Opus 5.5');
// 2. Clicar em Claude Opus 5.5 (delta = 4 - 3 = 1 -> seta para baixo + Enter)
sentWsMessages.length = 0;
optionBtns[4].click();
const rawSent = sentWsMessages.find(m => m.type === 'TERMINAL_RAW_INPUT');
assert.ok(rawSent, 'Deve despachar TERMINAL_RAW_INPUT ao clicar na opção');
assert.strictEqual(rawSent.agentName, 'AgyAgent');
assert.deepStrictEqual(rawSent.keys, ['\\e[B', '\\n']);
// 3. Recebe saída do Kilo CLI com Select model
const kiloSelectModel = [
' Select model esc ',
'',
' Recent ',
' ● Gemini 3.1 Flash Lite (LiteLLM) OmniRoute (chaves Gemini via LiteLLM) ',
' NVIDIA: Nemotron 3 Ultra (free) Kilo Gateway May train ',
' Anthropic: Claude Opus 5.5 ',
'',
' Connect provider ctrl+a Favorite ctrl+f '
].join('\n');
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'AgyAgent',
rawOutput: kiloSelectModel,
hasInteractiveMenu: true,
isThinking: false
})
});
assert.strictEqual(tuiTitle.textContent, '🎛️ Select model');
const kiloBtns = Array.from(tuiOptions.querySelectorAll('.btn-tui-option'));
assert.strictEqual(kiloBtns.length, 3);
assert.strictEqual(kiloBtns[0].textContent, '❯ Gemini 3.1 Flash Lite (LiteLLM) OmniRoute (chaves Gemini via LiteLLM)');
assert.strictEqual(kiloBtns[1].textContent, 'NVIDIA: Nemotron 3 Ultra (free) Kilo Gateway');
assert.strictEqual(kiloBtns[2].textContent, 'Anthropic: Claude Opus 5.5');
window.closeChat();
});
test('28. Interação com Menu Set Effort TUI (Horizontal) no Frontend', async () => {
window.openChatWithAgent('AgyAgent', '161818', 'nitro');
const tuiPanel = document.getElementById('chat-tui-panel');
const tuiOptions = document.getElementById('chat-tui-options');
const tuiTitle = document.getElementById('chat-tui-title');
// 1. Recebe saída do terminal com Set Effort (medium selecionado)
const agyEffort = [
'Set Effort',
'',
' ◂ ●━━━━━━━━━━━━━━◉──────────────○ ▸',
' low medium high ',
' Balanced speed and reasoning quality for most tasks (current)',
'',
'Keyboard: ←/→ Effort enter Select esc Go Back'
].join('\n');
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_TERMINAL_OUTPUT',
agentName: 'AgyAgent',
rawOutput: agyEffort,
hasInteractiveMenu: true,
isThinking: false
})
});
assert.strictEqual(tuiPanel.style.display, 'flex');
assert.strictEqual(tuiTitle.textContent, '🎛️ Set Effort');
assert.ok(tuiOptions.classList.contains('horizontal'), 'Deve adicionar classe horizontal no container de opções');
const optionBtns = Array.from(tuiOptions.querySelectorAll('.btn-tui-option'));
assert.strictEqual(optionBtns.length, 3);
assert.strictEqual(optionBtns[0].textContent, 'low');
assert.strictEqual(optionBtns[1].textContent, '❯ medium');
assert.strictEqual(optionBtns[2].textContent, 'high');
// 2. Clicar em high (delta = 2 - 1 = 1 horizontal -> seta para direita \\e[C + Enter)
sentWsMessages.length = 0;
optionBtns[2].click();
const rawSentHigh = sentWsMessages.find(m => m.type === 'TERMINAL_RAW_INPUT');
assert.ok(rawSentHigh, 'Deve despachar TERMINAL_RAW_INPUT');
assert.deepStrictEqual(rawSentHigh.keys, ['\\e[C', '\\n']);
// 3. Clicar em low (delta = 0 - 1 = -1 horizontal -> seta para esquerda \\e[D + Enter)
sentWsMessages.length = 0;
optionBtns[0].click();
const rawSentLow = sentWsMessages.find(m => m.type === 'TERMINAL_RAW_INPUT');
assert.ok(rawSentLow, 'Deve despachar TERMINAL_RAW_INPUT');
assert.deepStrictEqual(rawSentLow.keys, ['\\e[D', '\\n']);
window.closeChat();
});
test('29. Login Google SSO obrigatório — bloqueia acesso sem token e conclui via polling + sync de estações', async () => {
const htmlContent = fs.readFileSync(path.resolve('public', 'index.html'), 'utf8');
const appJsContent = fs.readFileSync(path.resolve('public', 'app.js'), 'utf8');
const freshDom = new JSDOM(htmlContent, {
runScripts: 'dangerously',
url: 'https://remote.winicomw.ddnsfree.com/?pin=654321'
});
try {
const w = freshDom.window;
const doc = w.document;
const openedUrls = [];
const fetchCalls = [];
let pollCount = 0;
w.WebSocket = window.WebSocket;
w.open = (url) => {
const winObj = {
closed: false,
_location: url,
set location(nextUrl) {
this._location = nextUrl;
openedUrls.push(nextUrl);
},
get location() {
return this._location;
},
close() {
this.closed = true;
}
};
if (url && url !== 'about:blank') {
openedUrls.push(url);
}
return winObj;
};
w.fetch = async (url, opts = {}) => {
const target = String(url);
fetchCalls.push({ url: target, method: opts.method || 'GET', headers: opts.headers || {}, body: opts.body });
if (target.includes('/api/auth/start')) {
return {
ok: true,
status: 200,
json: async () => ({
flowId: 'flow-e2e-1',
authUrl: 'https://auth.winicomw.ddnsfree.com/realms/maestri/protocol/openid-connect/auth?kc_idp_hint=google'
})
};
}
if (target.includes('/api/auth/poll')) {
pollCount += 1;
return {
ok: true,
status: 200,
json: async () => ({
status: 'completed',
token: 'jwt-novo-123',
user: { id: 'g-1', name: 'Winicius', email: 'wini@example.com' }
})
};
}
if (target.includes('/api/stations') && (!opts.method || opts.method === 'GET')) {
return {
ok: true,
status: 200,
json: async () => ({
stations: [
{ pin: '112233', name: 'Workstation Nuvem', machineName: 'NITRO' }
]
})
};
}
return {
ok: true,
status: 200,
json: async () => ({ status: 'ok', buildId: 'test-123', version: '1.0.2', stations: [] })
};
};
const scriptEl = doc.createElement('script');
scriptEl.textContent = appJsContent;
doc.body.appendChild(scriptEl);
await new Promise(r => setTimeout(r, 20));
const authScreen = doc.getElementById('auth-screen');
const pinScreen = doc.getElementById('pin-screen');
const appScreen = doc.getElementById('app-screen');
const userBadge = doc.getElementById('user-badge');
const userName = doc.getElementById('user-name');
// 1. Sem sessão: exibe #auth-screen, oculta #pin-screen e #app-screen, salva ?pin no sessionStorage
assert.strictEqual(authScreen.style.display, 'flex');
assert.strictEqual(pinScreen.style.display, 'none');
assert.strictEqual(appScreen.style.display, 'none');
assert.strictEqual(w.sessionStorage.getItem('maestri_pending_pin'), '654321');
// 2. Clica em Entrar com Google -> start -> window.open -> poll (focus) -> /api/stations
doc.getElementById('btn-google-login').click();
await new Promise(r => setTimeout(r, 30));
w.dispatchEvent(new w.Event('focus'));
await new Promise(r => setTimeout(r, 40));
assert.strictEqual(openedUrls.length, 1);
assert.ok(openedUrls[0].includes('kc_idp_hint=google'));
assert.ok(pollCount >= 1);
assert.strictEqual(w.localStorage.getItem('maestri_auth_token'), 'jwt-novo-123');
assert.strictEqual(authScreen.style.display, 'none');
assert.strictEqual(appScreen.style.display, 'block');
assert.strictEqual(userBadge.style.display, 'inline-flex');
assert.strictEqual(userName.textContent, 'Winicius');
// Estação carregada do servidor + pendingPin salvo no servidor
const postStationCall = fetchCalls.find(c => c.url.includes('/api/stations') && c.method === 'POST');
assert.ok(postStationCall, 'Deve persistir pendingPin no servidor via POST /api/stations');
assert.strictEqual(postStationCall.headers.Authorization, 'Bearer jwt-novo-123');
} finally {
freshDom.window.close();
}
});
test('26. Regressão — Home e seletor de estações ordenam online primeiro, depois connecting, depois offline preservando ordem cadastrada', async () => {
// Cadastra 4 estações na ordem: [111111 (offlineA), 222222 (offlineB), 333333 (connectingC), 444444 (onlineD)]
document.getElementById('pin-input').value = '111111';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
const addStation = async (name, pin) => {
document.getElementById('btn-add-station').click();
document.getElementById('station-name-input').value = name;
document.getElementById('station-pin-input').value = pin;
document.getElementById('btn-save-station').click();
await new Promise(r => setTimeout(r, 380));
};
await addStation('Offline B', '222222');
await addStation('Connecting C', '333333');
await addStation('Online D', '444444');
assert.strictEqual(mockWsInstances.length, 4);
const [ws1, ws2, , ws4] = mockWsInstances;
// 111111 e 222222 ficam offline; 333333 permanece connecting; 444444 fica online
ws1.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: false,
machineName: 'Offline A',
agents: []
})
});
ws2.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: false,
machineName: 'Offline B',
agents: []
})
});
ws4.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
gatewayConnected: true,
machineName: 'Online D',
agents: [{ name: 'Claude', isSelf: false, hasAiActivity: true }]
})
});
const getCardPins = () => Array.from(document.querySelectorAll('#stations-container .station-group-card'))
.map(el => el.id.replace('station-card-', ''));
const getSelectPins = () => Array.from(document.querySelectorAll('#station-select option'))
.map(o => o.value)
.filter(v => v && v !== '__add_new__');
// Ordem esperada: online (444444) -> connecting (333333) -> offline na ordem original (111111, 222222)
assert.deepStrictEqual(getCardPins(), ['444444', '333333', '111111', '222222']);
assert.deepStrictEqual(getSelectPins(), ['444444', '333333', '111111', '222222']);
assert.strictEqual(document.getElementById('stations-count-badge').textContent, '1/4');
assert.strictEqual(document.getElementById('station-select').value, '444444');
assert.strictEqual(document.getElementById('machine-name').textContent, 'Online D');
// localStorage não deve ser reordenado (ordem original preservada)
const savedPinsBefore = JSON.parse(window.localStorage.getItem('maestri_stations')).map(s => s.pin);
assert.deepStrictEqual(savedPinsBefore, ['111111', '222222', '333333', '444444']);
// Transição de 111111 de offline -> online deve movê-la imediatamente para o topo (antes de 444444 pela ordem de cadastro)
ws1.onmessage({
data: JSON.stringify({
type: 'GATEWAY_STATUS',
connected: true
})
});
assert.deepStrictEqual(getCardPins(), ['111111', '444444', '333333', '222222']);
assert.deepStrictEqual(getSelectPins(), ['111111', '444444', '333333', '222222']);
assert.strictEqual(document.getElementById('stations-count-badge').textContent, '2/4');
});
test('35. Regressão Hotfix — Precedência autoritativa de isThinking e detecção no frontend sem falso positivo', async () => {
// 35.1 Validação direta de detectAgentThinking no frontend
const agyInterrupted = [
'> execute comando demorado',
'○ Thought for 44.0s (Analyzing code...)',
'↳ Interrupted • What should Antigravity CLI do instead?'
].join('\n');
const f1 = window.detectAgentThinking(agyInterrupted, false);
assert.strictEqual(f1.isThinking, false, 'detectAgentThinking com Interrupted deve retornar isThinking = false');
const agySubagentFinished = [
'> implemente a task',
'● Agent(self: Builder de Implementação) · 3m1s',
'? for shortcuts Gemini 3.8 Flash · medium'
].join('\n');
const f2 = window.detectAgentThinking(agySubagentFinished, false);
assert.strictEqual(f2.isThinking, false, 'detectAgentThinking com subagente concluído e footer padrão deve retornar isThinking = false');
const agySubagentActive = [
'> implemente a task',
'● Agent(self: Builder de Implementação) · 10s',
'? for shortcuts auto · 1 subagent(s)'
].join('\n');
const f3 = window.detectAgentThinking(agySubagentActive, false);
assert.strictEqual(f3.isThinking, true, 'detectAgentThinking com 1 subagent(s) ativo deve retornar isThinking = true');
// 35.2 Validação de renderChatMessages com precedência autoritativa
// Conecta estação e abre chat
document.getElementById('pin-input').value = '161818';
document.getElementById('btn-connect').click();
await new Promise(r => setTimeout(r, 20));
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'INIT_STATE',
machineName: 'Estacao Nitro',
agents: [{ name: 'Builder', isSelf: false, isThinking: false }]
})
});
const agentPill = document.querySelector('.agent-pill');
assert.ok(agentPill, 'Pill do agente Builder deve existir');
agentPill.click();
await new Promise(r => setTimeout(r, 20));
// Simula mensagem final entregue pelo agente
mockWsInstance.onmessage({
data: JSON.stringify({
type: 'AGENT_CHAT_REPLY',
agentName: 'Builder',
text: 'Tarefa implementada com sucesso.',
terminalSnapshot: agySubagentFinished,
timestamp: Date.now()
})
});
await new Promise(r => setTimeout(r, 20));
// Valida que o card dinâmico de thinking (.thinking-card) NÃO está presente no DOM
const thinkingCard = document.querySelector('.chat-bubble.thinking-card');
assert.strictEqual(thinkingCard, null, 'Card de thinking não deve existir quando resposta já chegou e agente está autoritativamente ocioso');
// 35.3 removeAgentTyping(false) não destrói .thinking-card (evita flicker a cada 350ms do polling)
const chatMessagesEl = document.getElementById('chat-messages');
const dummyThinking = document.createElement('div');
dummyThinking.id = 'chat-typing-indicator';
dummyThinking.className = 'chat-bubble thinking-card';
dummyThinking.innerHTML = '<span>Trabalhando...</span>';
chatMessagesEl.appendChild(dummyThinking);
// Chamada normal durante streaming de terminal (removeAgentTyping(false))
window.removeAgentTyping(false);
assert.ok(document.getElementById('chat-typing-indicator'), 'removeAgentTyping(false) deve preservar o card de thinking para permitir update in-place sem flicker');
// Chamada forçada ao concluir/fechar (removeAgentTyping(true))
window.removeAgentTyping(true);
assert.strictEqual(document.getElementById('chat-typing-indicator'), null, 'removeAgentTyping(true) deve remover completamente o card ao encerrar');
});
test('36. Layout e Usabilidade do Cabeçalho do Chat (UX Craft - Espaçamento, Safe-Area e Áreas de Toque)', async () => {
// 1. Elementos do cabeçalho
const chatHeader = document.querySelector('.chat-header');
const agentInfo = document.querySelector('.chat-agent-info');
const chatAgentName = document.getElementById('chat-agent-name');
const chatAgentSubtitle = document.getElementById('chat-agent-subtitle');
const headerActions = document.querySelector('.chat-header-actions');
const btnDownloads = document.getElementById('btn-session-downloads');
const btnTui = document.getElementById('btn-tui-toggle');
const btnNotif = document.getElementById('chat-notif-toggle-btn');
const btnRestart = document.getElementById('btn-restart-terminal');
const btnRefresh = document.getElementById('btn-refresh-chat');
const btnClose = document.getElementById('btn-close-chat');
assert.ok(chatHeader, '.chat-header deve existir');
assert.ok(agentInfo, '.chat-agent-info deve existir');
assert.ok(chatAgentName, '#chat-agent-name deve existir');
assert.ok(chatAgentSubtitle, '#chat-agent-subtitle deve existir');
assert.ok(headerActions, '.chat-header-actions deve existir');
// 2. Todos os 6 botões interativos devem ter área mínima de toque de 44x44px
const buttons = [btnDownloads, btnTui, btnNotif, btnRestart, btnRefresh, btnClose];
for (const btn of buttons) {
assert.ok(btn, `Botão ${btn?.id} deve existir no DOM`);
assert.strictEqual(btn.style.minWidth, '44px', `Botão ${btn.id} deve ter min-width de 44px`);
assert.strictEqual(btn.style.minHeight, '44px', `Botão ${btn.id} deve ter min-height de 44px`);
}
// 3. Ordem dos elementos no DOM preservada
assert.strictEqual(btnRestart.nextElementSibling?.id, 'btn-refresh-chat');
assert.strictEqual(btnRefresh.nextElementSibling?.id, 'btn-close-chat');
// 4. Validação das regras de CSS do cabeçalho no arquivo style.css
const cssContent = fs.readFileSync(path.resolve('public', 'style.css'), 'utf8');
assert.ok(cssContent.includes('.chat-header {'), 'Deve conter definição de .chat-header no CSS');
assert.ok(cssContent.includes('gap: 8px;'), 'Deve conter espaçamento mínimo de 8px entre os botões de ação');
assert.ok(cssContent.includes('padding-right: 52px;'), 'chat-agent-info deve reservar espaço para o botão fechar');
assert.ok(cssContent.includes('.chat-header-actions .btn-icon {'), 'Deve conter estilos para os botões do header');
assert.ok(cssContent.includes('min-width: 44px;'), 'CSS deve garantir min-width de 44px');
assert.ok(cssContent.includes('min-height: 44px;'), 'CSS deve garantir min-height de 44px');
});
test('37. Blindagem contra crash no boot nativo: PushNotifications resiliente e fluxo Google SSO seguro no Capacitor', async () => {
const htmlContent = fs.readFileSync(path.resolve('public', 'index.html'), 'utf8');
const appJsContent = fs.readFileSync(path.resolve('public', 'app.js'), 'utf8');
const freshDom = new JSDOM(htmlContent, {
runScripts: 'dangerously',
url: 'https://remote.winicomw.ddnsfree.com/'
});
try {
const w = freshDom.window;
const doc = w.document;
let browserOpenedUrl = null;
let windowOpenedArgs = null;
// Simula Capacitor nativo Android onde FirebaseApp NÃO foi inicializado (google-services.json ausente)
let registerCalled = false;
w.Capacitor = {
isNativePlatform: () => true,
getPlatform: () => 'android',
isPluginAvailable: (name) => name === 'PushNotifications' || name === 'Browser',
Plugins: {
PushNotifications: {
createChannel: async () => {},
addListener: (event, cb) => {},
requestPermissions: async () => ({ receive: 'granted' }),
checkPermissions: async () => ({ receive: 'granted' }),
register: async () => {
registerCalled = true;
throw new Error('Default FirebaseApp is not initialized in this process com.maestri.remote.');
}
},
Browser: {
open: async ({ url }) => {
browserOpenedUrl = url;
}
}
}
};
w.open = (url, target, features) => {
windowOpenedArgs = { url, target, features };
return { closed: false, location: url };
};
w.fetch = async (url) => {
const target = String(url);
if (target.includes('/api/auth/start')) {
return {
ok: true,
status: 200,
json: async () => ({
flowId: 'flow-native-test',
authUrl: 'https://auth.winicomw.ddnsfree.com/realms/maestri/protocol/openid-connect/auth?flow=1'
})
};
}
return {
ok: true,
status: 200,
json: async () => ({ status: 'ok' })
};
};
// Avalia o script no DOM com Capacitor nativo
const scriptEl = doc.createElement('script');
scriptEl.textContent = appJsContent;
doc.body.appendChild(scriptEl);
await new Promise(r => setTimeout(r, 30));
// 1. initNativePushNotifications no boot não deve derrubar o app mesmo com FirebaseApp lançando IllegalStateException
assert.strictEqual(registerCalled, true, 'PushNotifications.register deve ter sido tentado');
const authScreen = doc.getElementById('auth-screen');
assert.strictEqual(authScreen.style.display, 'flex', 'Tela de autenticação deve continuar visível e funcional sem crash');
// 2. Fluxo Google SSO em ambiente nativo: deve usar Browser plugin e NUNCA substituir window.location.href
const initialLocation = w.location.href;
const btnGoogle = doc.getElementById('btn-google-login');
assert.ok(btnGoogle, 'Botão de login Google deve existir');
btnGoogle.click();
await new Promise(r => setTimeout(r, 40));
assert.strictEqual(browserOpenedUrl, 'https://auth.winicomw.ddnsfree.com/realms/maestri/protocol/openid-connect/auth?flow=1', 'Browser.open deve ser chamado para abrir no navegador externo');
assert.strictEqual(w.location.href, initialLocation, 'window.location.href NUNCA deve ser sobrescrito na WebView nativa para evitar quebra do app');
// Limpa timers ativos do teste
if (typeof w.activeAuthPollCleanup === 'function') {
w.activeAuthPollCleanup();
}
} finally {
freshDom.window.close();
}
});
test('30. Renovação Silenciosa de Sessão (Refresh Token) no Frontend e Resiliência contra 401', async () => {
const appJsContent = fs.readFileSync(path.resolve('public', 'app.js'), 'utf8');
const htmlTemplate = fs.readFileSync(path.resolve('public/index.html'), 'utf8');
const freshDom = new JSDOM(htmlTemplate, {
url: 'https://remote.winicomw.ddnsfree.com/',
runScripts: 'dangerously'
});
const w = freshDom.window;
const doc = w.document;
// Configura localStorage com token de acesso expirado e refresh token válido
w.localStorage.setItem('maestri_auth_token', 'expired-access-token');
w.localStorage.setItem('maestri_refresh_token', 'valid-refresh-token');
w.localStorage.setItem('maestri_user', JSON.stringify({ id: 'u-1', name: 'User 1', email: 'u1@example.com' }));
let refreshCalls = 0;
let meCalls = 0;
w.fetch = async (url, opts = {}) => {
const target = String(url);
if (target.includes('/api/auth/me')) {
meCalls += 1;
const authHeader = opts.headers?.Authorization || opts.headers?.authorization;
if (authHeader === 'Bearer renewed-access-token') {
return {
ok: true,
status: 200,
json: async () => ({ user: { id: 'u-1', name: 'User 1', email: 'u1@example.com' } })
};
}
return {
ok: false,
status: 401,
json: async () => ({ error: 'Não autenticado' })
};
}
if (target.includes('/api/auth/refresh')) {
refreshCalls += 1;
const body = JSON.parse(opts.body || '{}');
if (body.refreshToken === 'valid-refresh-token') {
return {
ok: true,
status: 200,
json: async () => ({
token: 'renewed-access-token',
refreshToken: 'new-refresh-token',
user: { id: 'u-1', name: 'User 1', email: 'u1@example.com' }
})
};
}
return {
ok: false,
status: 401,
json: async () => ({ error: 'Refresh token inválido' })
};
}
if (target.includes('/api/stations')) {
return {
ok: true,
status: 200,
json: async () => ({ stations: [{ pin: '998877', name: 'Estação Teste' }] })
};
}
return {
ok: true,
status: 200,
json: async () => ({ status: 'ok', buildId: 'test-30', version: '1.0.3' })
};
};
try {
const scriptEl = doc.createElement('script');
scriptEl.textContent = appJsContent;
doc.body.appendChild(scriptEl);
await new Promise(r => setTimeout(r, 60));
const authScreen = doc.getElementById('auth-screen');
const appScreen = doc.getElementById('app-screen');
// 1. Deve ter renovado silenciosamente via /api/auth/refresh sem exibir a tela de login
assert.strictEqual(refreshCalls, 1, 'Deve ter acionado a rota /api/auth/refresh uma vez');
assert.strictEqual(w.localStorage.getItem('maestri_auth_token'), 'renewed-access-token', 'Novo token de acesso deve ser salvo');
assert.strictEqual(w.localStorage.getItem('maestri_refresh_token'), 'new-refresh-token', 'Novo refresh token deve ser salvo');
assert.strictEqual(authScreen.style.display, 'none', 'Tela de login NÃO deve ser exibida ao renovar com sucesso');
assert.strictEqual(appScreen.style.display, 'block', 'Tela do aplicativo deve ser exibida normalmente');
// 2. Quando o refresh token for inválido, deve limpar storage e exibir #auth-screen
w.localStorage.setItem('maestri_refresh_token', 'invalid-token');
const refreshedFailed = await w.refreshAuthSession();
assert.strictEqual(refreshedFailed, false, 'refreshAuthSession deve retornar false com refresh token inválido');
assert.strictEqual(w.localStorage.getItem('maestri_refresh_token'), null, 'Refresh token inválido deve ser limpo do localStorage');
// 3. logoutUser() deve limpar também maestri_refresh_token
w.localStorage.setItem('maestri_refresh_token', 'dummy-refresh');
w.logoutUser();
assert.strictEqual(w.localStorage.getItem('maestri_refresh_token'), null, 'logoutUser deve remover maestri_refresh_token');
} finally {
freshDom.window.close();
}
});
});