375 lines
14 KiB
JavaScript
375 lines
14 KiB
JavaScript
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('Resiliência Mobile, Chat Conversacional e Notificações com Mute Granular', () => {
|
|
let dom;
|
|
let window;
|
|
let document;
|
|
let sentWsMessages = [];
|
|
let mockWsInstance;
|
|
let mockWsInstances = [];
|
|
|
|
afterEach(() => {
|
|
if (dom && dom.window) {
|
|
dom.window.close();
|
|
}
|
|
});
|
|
|
|
beforeEach(() => {
|
|
sentWsMessages = [];
|
|
mockWsInstances = [];
|
|
|
|
const htmlContent = fs.readFileSync(path.resolve('public', 'index.html'), 'utf8');
|
|
const appJsContent = fs.readFileSync(path.resolve('public', 'app.js'), 'utf8');
|
|
|
|
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();
|
|
}, 5);
|
|
}
|
|
send(data) {
|
|
sentWsMessages.push(JSON.parse(data));
|
|
}
|
|
close() {
|
|
this.readyState = 3;
|
|
if (this.onclose) this.onclose();
|
|
}
|
|
}
|
|
MockWebSocket.OPEN = 1;
|
|
MockWebSocket.CLOSED = 3;
|
|
window.WebSocket = MockWebSocket;
|
|
|
|
// Mock de Web Audio API
|
|
window.AudioContext = class MockAudioContext {
|
|
constructor() {
|
|
this.state = 'running';
|
|
}
|
|
createOscillator() {
|
|
return {
|
|
type: 'sine',
|
|
frequency: {
|
|
setValueAtTime: () => {},
|
|
exponentialRampToValueAtTime: () => {}
|
|
},
|
|
connect: () => {},
|
|
start: () => {},
|
|
stop: () => {}
|
|
};
|
|
}
|
|
createGain() {
|
|
return {
|
|
gain: {
|
|
setValueAtTime: () => {},
|
|
exponentialRampToValueAtTime: () => {}
|
|
},
|
|
connect: () => {}
|
|
};
|
|
}
|
|
get destination() {
|
|
return {};
|
|
}
|
|
get currentTime() {
|
|
return 0;
|
|
}
|
|
};
|
|
|
|
window.fetch = async () => ({
|
|
ok: true,
|
|
json: async () => ({ status: 'ok', buildId: 'test-ota-100', version: '1.0.9' }),
|
|
text: async () => ''
|
|
});
|
|
|
|
const scriptEl = document.createElement('script');
|
|
scriptEl.textContent = appJsContent;
|
|
document.body.appendChild(scriptEl);
|
|
});
|
|
|
|
test('Task 1: Detecção de visibilidade e ciclo de vida móvel (Auto-Resume de WebSocket)', async () => {
|
|
document.getElementById('pin-input').value = '123456';
|
|
document.getElementById('btn-connect').click();
|
|
await new Promise(r => setTimeout(r, 20));
|
|
|
|
assert.strictEqual(mockWsInstances.length, 1);
|
|
const initialWs = mockWsInstances[0];
|
|
|
|
// Simula tela desligando / app indo para background (socket entra em half-open/closed)
|
|
initialWs.readyState = 3; // CLOSED
|
|
|
|
// Dispara evento visibilitychange indicando retorno do operador à tela
|
|
Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true });
|
|
document.dispatchEvent(new window.Event('visibilitychange'));
|
|
await new Promise(r => setTimeout(r, 30));
|
|
|
|
// Deve ter disparado auto-reconexão imediata criando novo WebSocket sem esperar timers longos
|
|
assert.ok(mockWsInstances.length >= 2, 'Deve ter reconectado imediatamente ao voltar ao primeiro plano');
|
|
const newWs = mockWsInstances[mockWsInstances.length - 1];
|
|
assert.strictEqual(newWs.readyState, 1);
|
|
});
|
|
|
|
test('Task 2: Chat Conversacional com Terminal Recolhível e Envio Contínuo Não Bloqueante', async () => {
|
|
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: 'agente-chat', isSelf: false, hasAiActivity: true }]
|
|
})
|
|
});
|
|
|
|
window.openChatWithAgent('agente-chat', '123456', 'Estacao-Dev');
|
|
|
|
// 1. Deve possuir o componente recolhível de terminal no topo do chat
|
|
const collapsibleHeader = document.getElementById('chat-terminal-toggle-btn');
|
|
const collapsibleContent = document.getElementById('chat-terminal-collapsible-content');
|
|
assert.ok(collapsibleHeader, 'Botão/Header do terminal recolhível deve existir');
|
|
assert.ok(collapsibleContent, 'Conteúdo recolhível do terminal deve existir');
|
|
|
|
// Estado inicial deve ser recolhido
|
|
assert.strictEqual(collapsibleContent.style.display, 'none');
|
|
|
|
// Ao clicar, expande o terminal
|
|
collapsibleHeader.click();
|
|
assert.strictEqual(collapsibleContent.style.display, 'block');
|
|
|
|
// Ao clicar novamente, recolhe
|
|
collapsibleHeader.click();
|
|
assert.strictEqual(collapsibleContent.style.display, 'none');
|
|
|
|
// 2. Envio contínuo: enviar mensagem do usuário
|
|
const chatInput = document.getElementById('chat-input');
|
|
const chatForm = document.getElementById('chat-form');
|
|
chatInput.value = 'Primeira mensagem';
|
|
chatForm.dispatchEvent(new window.Event('submit'));
|
|
|
|
// O campo de digitação NUNCA deve ser desabilitado
|
|
assert.strictEqual(chatInput.disabled, false, 'Campo de texto deve permanecer habilitado para envio contínuo');
|
|
|
|
// Permite enviar uma segunda mensagem enquanto o agente ainda pensa
|
|
chatInput.value = 'Segunda mensagem complementar';
|
|
chatForm.dispatchEvent(new window.Event('submit'));
|
|
assert.strictEqual(chatInput.disabled, false, 'Campo deve continuar ativo após segunda mensagem');
|
|
|
|
// Mensagens devem estar presentes na timeline
|
|
const bubbles = document.querySelectorAll('.chat-bubble.user');
|
|
assert.strictEqual(bubbles.length, 2, 'Ambas as mensagens do usuário devem estar na timeline');
|
|
assert.ok(bubbles[0].textContent.includes('Primeira mensagem'));
|
|
assert.ok(bubbles[1].textContent.includes('Segunda mensagem complementar'));
|
|
});
|
|
|
|
test('Task 3: Sistema de Notificações com Mute Granular por Agente (Default Ativado com Persistência)', async () => {
|
|
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: 'agente-silencioso', isSelf: false, hasAiActivity: true },
|
|
{ name: 'agente-notificado', isSelf: false, hasAiActivity: true }
|
|
]
|
|
})
|
|
});
|
|
|
|
// 1. Cada agente na Home deve ter o botão de alternância de notificação (sino)
|
|
const toggleBtns = document.querySelectorAll('.btn-terminal-notif-toggle');
|
|
assert.strictEqual(toggleBtns.length, 2, 'Cada card de agente deve ter o botão de notificação');
|
|
|
|
// 2. Default DEVE ser ATIVADO (ícone de sino ligado 🔔 e sem classe muted)
|
|
assert.ok(
|
|
!toggleBtns[0].classList.contains('muted') && toggleBtns[0].textContent.includes('🔔'),
|
|
'Por padrão a notificação deve ser ativada'
|
|
);
|
|
assert.ok(
|
|
!toggleBtns[1].classList.contains('muted') && toggleBtns[1].textContent.includes('🔔'),
|
|
'Por padrão a notificação deve ser ativada'
|
|
);
|
|
|
|
// 3. Silencia notificação (mute) para o primeiro agente
|
|
toggleBtns[0].click();
|
|
const updatedBtns = document.querySelectorAll('.btn-terminal-notif-toggle');
|
|
assert.ok(
|
|
updatedBtns[0].classList.contains('muted') && updatedBtns[0].textContent.includes('🔕'),
|
|
'Ao clicar, deve silenciar notificação com sino mutado'
|
|
);
|
|
assert.ok(
|
|
!updatedBtns[1].classList.contains('muted') && updatedBtns[1].textContent.includes('🔔'),
|
|
'O segundo agente permanece ativado'
|
|
);
|
|
|
|
// 4. No chat, o header também reflete o estado sincronizado
|
|
window.openChatWithAgent('agente-notificado', '123456', 'Estacao-Dev');
|
|
const headerToggle = document.getElementById('chat-notif-toggle-btn');
|
|
assert.ok(headerToggle, 'Botão de notificação deve existir no cabeçalho do chat');
|
|
assert.ok(headerToggle.textContent.includes('🔔'), 'Deve refletir estado ativado');
|
|
|
|
window.openChatWithAgent('agente-silencioso', '123456', 'Estacao-Dev');
|
|
assert.ok(headerToggle.textContent.includes('🔕'), 'Deve refletir estado silenciado para agente silenciado');
|
|
});
|
|
|
|
test('Task 4: Reabertura de chat com dados salvos mantém sincronização via WebSocket e reconecta caso inativo', async () => {
|
|
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: 'agente-persistente', isSelf: false, hasAiActivity: true }]
|
|
})
|
|
});
|
|
|
|
// 1. Abre chat e envia mensagem
|
|
window.openChatWithAgent('agente-persistente', '123456', 'Estacao-Dev');
|
|
const chatInput = document.getElementById('chat-input');
|
|
const chatForm = document.getElementById('chat-form');
|
|
chatInput.value = 'Mensagem anterior salva';
|
|
chatForm.dispatchEvent(new window.Event('submit'));
|
|
|
|
// Resposta do agente
|
|
mockWsInstance.onmessage({
|
|
data: JSON.stringify({
|
|
type: 'CHAT_RESPONSE',
|
|
agentName: 'agente-persistente',
|
|
response: 'Resposta anterior salva'
|
|
})
|
|
});
|
|
|
|
// 2. Fecha o chat (sai para a Home)
|
|
window.closeChat();
|
|
assert.strictEqual(document.getElementById('chat-drawer').style.display, 'none');
|
|
|
|
// 3. Simula que a conexão caiu enquanto estava fora do chat
|
|
const currentWs = mockWsInstances[mockWsInstances.length - 1];
|
|
currentWs.readyState = 3; // CLOSED
|
|
|
|
// 4. Reabre o chat do mesmo agente com dados já existentes
|
|
window.openChatWithAgent('agente-persistente', '123456', 'Estacao-Dev');
|
|
await new Promise(r => setTimeout(r, 20));
|
|
|
|
// Deve ter reaberto o chat exibindo as mensagens salvas
|
|
assert.strictEqual(document.getElementById('chat-drawer').style.display, 'flex');
|
|
const bubbles = document.querySelectorAll('.chat-bubble:not(.typing)');
|
|
assert.ok(bubbles.length >= 2, 'Mensagens anteriores devem ser restauradas');
|
|
|
|
// O socket deve ter sido reestabelecido automaticamente ao abrir o chat
|
|
const activeWs = mockWsInstances[mockWsInstances.length - 1];
|
|
assert.strictEqual(activeWs.readyState, 1, 'WebSocket deve estar OPEN e ativo');
|
|
|
|
// Simula chegada de AGENT_TERMINAL_OUTPUT
|
|
activeWs.onmessage({
|
|
data: JSON.stringify({
|
|
type: 'AGENT_TERMINAL_OUTPUT',
|
|
agentName: 'agente-persistente',
|
|
output: 'Saída atualizada do terminal em tempo real'
|
|
})
|
|
});
|
|
|
|
// Loading residual deve ser removido
|
|
const loadingBubble = document.getElementById('chat-typing-indicator');
|
|
assert.strictEqual(loadingBubble, null, 'Loading de leitura do terminal deve ter sido removido');
|
|
|
|
// Terminal raw deve conter a saída
|
|
const rawTerminal = document.getElementById('chat-terminal-output-raw');
|
|
assert.ok(rawTerminal.textContent.includes('Saída atualizada do terminal'));
|
|
});
|
|
|
|
test('Task 5: Retomada mobile com WebSocket OPEN envia GET_AGENTS e atualiza a Home sem reconexão redundante', async () => {
|
|
document.getElementById('pin-input').value = '123456';
|
|
document.getElementById('btn-connect').click();
|
|
await new Promise(r => setTimeout(r, 20));
|
|
|
|
const initialWs = mockWsInstances[0];
|
|
assert.strictEqual(initialWs.readyState, 1);
|
|
sentWsMessages = [];
|
|
|
|
// Simula visibilidade retornando com WebSocket ainda OPEN
|
|
Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true });
|
|
document.dispatchEvent(new window.Event('visibilitychange'));
|
|
await new Promise(r => setTimeout(r, 40));
|
|
|
|
// Deve ter enviado GET_AGENTS sem abrir nova conexão WebSocket
|
|
assert.strictEqual(mockWsInstances.length, 1, 'Não deve criar nova conexão se socket está OPEN');
|
|
assert.ok(sentWsMessages.some(m => m.type === 'GET_AGENTS'), 'Deve enviar GET_AGENTS para sincronizar estado');
|
|
|
|
// Ao receber AGENTS_UPDATE de resposta do Relay, atualiza os chips da Home
|
|
initialWs.onmessage({
|
|
data: JSON.stringify({
|
|
type: 'AGENTS_UPDATE',
|
|
agents: [
|
|
{ name: 'bot-retomado', isSelf: false, isThinking: true, hasAiActivity: true }
|
|
]
|
|
})
|
|
});
|
|
|
|
const agentPill = document.querySelector('.agent-pill');
|
|
assert.ok(agentPill, 'Pill do agente deve existir na Home');
|
|
assert.ok(agentPill.textContent.includes('bot-retomado'));
|
|
assert.ok(agentPill.classList.contains('thinking'), 'Deve refletir status de thinking atualizado');
|
|
});
|
|
|
|
test('Task 6: INIT_STATE preserva status de pausa de cota (isPaused) nos agentes da Home', async () => {
|
|
document.getElementById('pin-input').value = '123456';
|
|
document.getElementById('btn-connect').click();
|
|
await new Promise(r => setTimeout(r, 20));
|
|
|
|
const ws = mockWsInstances[mockWsInstances.length - 1];
|
|
ws.onmessage({
|
|
data: JSON.stringify({
|
|
type: 'INIT_STATE',
|
|
machineName: 'Estacao-Pausa',
|
|
agents: [
|
|
{ name: 'bot-pausado', isSelf: false, isPaused: true, pauseResetTime: '19:30', hasAiActivity: true }
|
|
]
|
|
})
|
|
});
|
|
|
|
const agentPill = document.querySelector('.agent-pill');
|
|
assert.ok(agentPill, 'Pill do agente pausado deve existir');
|
|
assert.ok(agentPill.classList.contains('ai-paused'), 'Pill deve possuir classe ai-paused');
|
|
assert.ok(agentPill.innerHTML.includes('⏸️'), 'Pill deve exibir ícone de pausa');
|
|
});
|
|
|
|
test('Task 7: Cache em localStorage de agentes permite renderização instantânea da Home no boot', async () => {
|
|
// Configura localStorage com uma estação contendo agentes em cache
|
|
window.localStorage.setItem('maestri_stations', JSON.stringify([
|
|
{
|
|
id: 'station-999888',
|
|
name: 'Estação Cacheada',
|
|
pin: '999888',
|
|
cachedAgents: [
|
|
{ name: 'agente-instantaneo', isSelf: false, hasAiActivity: true }
|
|
]
|
|
}
|
|
]));
|
|
|
|
// Chama renderAllStations simulando arranque a frio após descarte da WebView
|
|
window.renderAllStations();
|
|
|
|
const pills = document.querySelectorAll('.agent-pill');
|
|
assert.ok(pills.length >= 1, 'Deve renderizar imediatamente o agente a partir do cache local');
|
|
assert.ok(document.body.textContent.includes('agente-instantaneo'), 'Nome do agente cacheado deve estar visível');
|
|
});
|
|
});
|