1316 lines
49 KiB
JavaScript
1316 lines
49 KiB
JavaScript
import test from 'node:test';
|
||
import assert from 'node:assert/strict';
|
||
import fs from 'node:fs';
|
||
import path from 'node:path';
|
||
import { GatewayDaemon } from '../src/gateway/daemon.js';
|
||
import * as maestriAdapterModule from '../src/gateway/maestri-adapter.js';
|
||
const { MaestriAdapter } = maestriAdapterModule;
|
||
|
||
class MockAdapter {
|
||
constructor() {
|
||
this.responses = [];
|
||
}
|
||
async listAgents() {
|
||
return [{ name: 'TestAgent', isSelf: false, status: 'active' }];
|
||
}
|
||
async sendResponse(agentName, response) {
|
||
this.responses.push({ agentName, response });
|
||
return true;
|
||
}
|
||
async askAgent(agentName, message) {
|
||
this.responses.push({ agentName, message });
|
||
return { ok: true, output: 'Comando executado com sucesso.' };
|
||
}
|
||
}
|
||
|
||
test('GatewayDaemon deve gerar PIN de 6 dígitos e Magic Link válido', () => {
|
||
const daemon = new GatewayDaemon({
|
||
pin: '987654',
|
||
publicHost: 'https://remote.test.com'
|
||
});
|
||
|
||
assert.equal(daemon.pin, '987654');
|
||
assert.equal(daemon.getMagicLink(), 'https://remote.test.com/?pin=987654');
|
||
});
|
||
|
||
test('GatewayDaemon deve repassar RESOLVE_PROMPT ao adapter', async () => {
|
||
const mockAdapter = new MockAdapter();
|
||
const daemon = new GatewayDaemon({
|
||
adapter: mockAdapter
|
||
});
|
||
|
||
await daemon.handleRelayMessage({
|
||
type: 'RESOLVE_PROMPT',
|
||
requestId: 'req-42',
|
||
agentName: 'SREOracle #2',
|
||
response: '1b'
|
||
});
|
||
|
||
assert.equal(mockAdapter.responses.length, 1);
|
||
assert.equal(mockAdapter.responses[0].agentName, 'SREOracle #2');
|
||
assert.equal(mockAdapter.responses[0].response, '1b');
|
||
});
|
||
|
||
test('GatewayDaemon deve salvar anexo e injetar path no prompt do askAgent', async () => {
|
||
const fs = await import('node:fs');
|
||
const mockAdapter = new MockAdapter();
|
||
const daemon = new GatewayDaemon({
|
||
adapter: mockAdapter
|
||
});
|
||
|
||
const sampleBase64 = Buffer.from('conteudo do print de teste').toString('base64');
|
||
let savedFile = null;
|
||
|
||
await daemon.handleRelayMessage({
|
||
type: 'CHAT_SEND',
|
||
chatId: 'chat-999',
|
||
agentName: 'TestAgent',
|
||
message: 'Veja este print de erro',
|
||
attachment: {
|
||
name: 'screenshot_erro.png',
|
||
mimeType: 'image/png',
|
||
size: 26,
|
||
dataBase64: sampleBase64
|
||
}
|
||
});
|
||
|
||
assert.equal(mockAdapter.responses.length, 1);
|
||
assert.equal(mockAdapter.responses[0].agentName, 'TestAgent');
|
||
assert.ok(mockAdapter.responses[0].message.includes('screenshot_erro.png'));
|
||
assert.ok(mockAdapter.responses[0].message.includes('[Anexo recebido do operador:'));
|
||
assert.ok(mockAdapter.responses[0].message.includes('Veja este print de erro'));
|
||
|
||
// Extrai o caminho e valida que o arquivo existe fisicamente
|
||
const match = mockAdapter.responses[0].message.match(/\[Anexo recebido do operador: (.*?)\]/);
|
||
assert.ok(match, 'Deve ter injetado o path do anexo');
|
||
savedFile = match[1];
|
||
assert.ok(fs.existsSync(savedFile), 'Arquivo do anexo deve existir no disco');
|
||
assert.equal(fs.readFileSync(savedFile, 'utf-8'), 'conteudo do print de teste');
|
||
|
||
// Limpeza
|
||
if (savedFile && fs.existsSync(savedFile)) {
|
||
fs.unlinkSync(savedFile);
|
||
}
|
||
});
|
||
|
||
test('GatewayDaemon deve salvar múltiplos anexos e injetar lista de paths no prompt do askAgent', async () => {
|
||
const fs = await import('node:fs');
|
||
const mockAdapter = new MockAdapter();
|
||
const daemon = new GatewayDaemon({
|
||
adapter: mockAdapter
|
||
});
|
||
|
||
const base64Img1 = Buffer.from('imagem 1').toString('base64');
|
||
const base64Img2 = Buffer.from('imagem 2').toString('base64');
|
||
const base64Doc = Buffer.from('documento texto').toString('base64');
|
||
|
||
await daemon.handleRelayMessage({
|
||
type: 'CHAT_SEND',
|
||
chatId: 'chat-multiple',
|
||
agentName: 'TestAgent',
|
||
message: 'Analise os 3 arquivos',
|
||
attachments: [
|
||
{ name: 'tela1.png', mimeType: 'image/png', size: 8, dataBase64: base64Img1 },
|
||
{ name: 'tela2.png', mimeType: 'image/png', size: 8, dataBase64: base64Img2 },
|
||
{ name: 'log.txt', mimeType: 'text/plain', size: 15, dataBase64: base64Doc }
|
||
]
|
||
});
|
||
|
||
assert.equal(mockAdapter.responses.length, 1);
|
||
assert.equal(mockAdapter.responses[0].agentName, 'TestAgent');
|
||
assert.ok(mockAdapter.responses[0].message.includes('[Anexos recebidos do operador:'));
|
||
assert.ok(mockAdapter.responses[0].message.includes('tela1.png'));
|
||
assert.ok(mockAdapter.responses[0].message.includes('tela2.png'));
|
||
assert.ok(mockAdapter.responses[0].message.includes('log.txt'));
|
||
assert.ok(mockAdapter.responses[0].message.includes('Analise os 3 arquivos'));
|
||
});
|
||
|
||
test('GatewayDaemon deve responder CHAT_ACK imediatamente ao receber CHAT_SEND', async () => {
|
||
const mockAdapter = new MockAdapter();
|
||
const daemon = new GatewayDaemon({
|
||
adapter: mockAdapter
|
||
});
|
||
|
||
const sentMessages = [];
|
||
daemon.ws = {
|
||
send: (data) => sentMessages.push(JSON.parse(data))
|
||
};
|
||
daemon.connected = true;
|
||
|
||
await daemon.handleRelayMessage({
|
||
type: 'CHAT_SEND',
|
||
chatId: 'chat-ack-test',
|
||
agentName: 'TestAgent',
|
||
message: 'Olá agente'
|
||
});
|
||
|
||
const ackMsg = sentMessages.find(m => m.type === 'CHAT_ACK');
|
||
assert.ok(ackMsg, 'Deve ter emitido CHAT_ACK imediatamente');
|
||
assert.equal(ackMsg.chatId, 'chat-ack-test');
|
||
assert.equal(ackMsg.agentName, 'TestAgent');
|
||
});
|
||
|
||
test('MaestriAdapter deve salvar mensagem em arquivo texto quando exceder limite de console', async () => {
|
||
const customMessagesDir = path.resolve(process.cwd(), '.maestri-remote', 'test-messages');
|
||
let executedArgs = null;
|
||
|
||
const adapter = new MaestriAdapter({
|
||
maxConsoleLength: 100, // Limite baixo para teste
|
||
messagesDir: customMessagesDir
|
||
});
|
||
|
||
// Mock do runMaestri
|
||
adapter.runMaestri = async (args) => {
|
||
executedArgs = args;
|
||
return { ok: true, output: 'Executado com sucesso', error: null };
|
||
};
|
||
|
||
const longText = 'Esta é uma mensagem intencionalmente longa enviada pelo operador que ultrapassa cem caracteres para teste de limitação de console.';
|
||
const res = await adapter.askAgent('TestAgent', longText);
|
||
|
||
assert.equal(res.ok, true);
|
||
assert.ok(executedArgs, 'Deve ter executado o comando');
|
||
assert.equal(executedArgs[0], 'ask');
|
||
assert.equal(executedArgs[1], 'TestAgent');
|
||
|
||
const payload = executedArgs[2];
|
||
assert.ok(payload.includes('[Mensagem longa do operador salva em arquivo texto:'));
|
||
assert.ok(payload.includes('Instrução: A mensagem do operador excedeu a limitação de console'));
|
||
|
||
// Extrai o caminho e valida que o arquivo existe
|
||
const match = payload.match(/\[Mensagem longa do operador salva em arquivo texto: (.*?)\]/);
|
||
assert.ok(match, 'Deve ter indicado o caminho do arquivo gerado');
|
||
const filePath = match[1];
|
||
assert.ok(fs.existsSync(filePath), 'O arquivo de texto deve existir no disco');
|
||
assert.equal(fs.readFileSync(filePath, 'utf8'), longText);
|
||
|
||
// Limpeza
|
||
if (fs.existsSync(filePath)) {
|
||
fs.unlinkSync(filePath);
|
||
}
|
||
if (fs.existsSync(customMessagesDir)) {
|
||
fs.rmSync(customMessagesDir, { recursive: true, force: true });
|
||
}
|
||
});
|
||
|
||
test('MaestriAdapter deve acionar fallback para arquivo texto se ocorrer erro de limite de console', async () => {
|
||
const customMessagesDir = path.resolve(process.cwd(), '.maestri-remote', 'test-messages-fallback');
|
||
const callHistory = [];
|
||
|
||
const adapter = new MaestriAdapter({
|
||
maxConsoleLength: 5000, // Limite alto para não salvar no primeiro passo
|
||
messagesDir: customMessagesDir
|
||
});
|
||
|
||
adapter.runMaestri = async (args) => {
|
||
callHistory.push(args);
|
||
if (callHistory.length === 1) {
|
||
// Primeira chamada simula erro de limitação de console do Windows
|
||
return { ok: false, output: '', error: 'Linha de comando muito longa.' };
|
||
}
|
||
// Segunda chamada (com o arquivo salvo) é bem sucedida
|
||
return { ok: true, output: 'Resposta apos ler arquivo', error: null };
|
||
};
|
||
|
||
const text = 'Prompt que estourou o buffer do console no shell legado.';
|
||
const res = await adapter.askAgent('TestAgent', text);
|
||
|
||
assert.equal(res.ok, true);
|
||
assert.equal(callHistory.length, 2, 'Deve ter tentado novamente com o fallback');
|
||
assert.equal(callHistory[0][2], text);
|
||
assert.ok(callHistory[1][2].includes('[Mensagem longa do operador salva em arquivo texto:'));
|
||
|
||
// Limpeza
|
||
if (fs.existsSync(customMessagesDir)) {
|
||
fs.rmSync(customMessagesDir, { recursive: true, force: true });
|
||
}
|
||
});
|
||
|
||
test('MaestriAdapter.listAgents deve enriquecer agentes com hasAiActivity e shellType', async () => {
|
||
const adapter = new MaestriAdapter();
|
||
|
||
adapter.runMaestri = async (args) => {
|
||
if (args[0] === 'list') {
|
||
return {
|
||
ok: true,
|
||
output: `You:\n - name: "maestri-remote"\n\nConnected agents:\n - name: "agent-ai"\n - name: "terminal-ps"`
|
||
};
|
||
}
|
||
if (args[0] === 'check') {
|
||
const target = args[1];
|
||
if (target === 'agent-ai') {
|
||
return {
|
||
ok: true,
|
||
output: 'Antigravity CLI 1.5.4\n> execute a tarefa\n? for shortcuts'
|
||
};
|
||
}
|
||
if (target === 'terminal-ps') {
|
||
return {
|
||
ok: true,
|
||
output: 'Windows PowerShell\nCopyright (C) Microsoft Corporation.\n\nPS C:\\Users\\winic> '
|
||
};
|
||
}
|
||
}
|
||
return { ok: true, output: '' };
|
||
};
|
||
|
||
const agents = await adapter.listAgents();
|
||
|
||
assert.equal(agents.length, 3);
|
||
|
||
const selfAgent = agents.find(a => a.name === 'maestri-remote');
|
||
assert.equal(selfAgent.isSelf, true);
|
||
assert.equal(selfAgent.hasAiActivity, false);
|
||
|
||
const aiAgent = agents.find(a => a.name === 'agent-ai');
|
||
assert.equal(aiAgent.isSelf, false);
|
||
assert.equal(aiAgent.hasAiActivity, true);
|
||
assert.equal(aiAgent.aiType, 'agy');
|
||
assert.equal(aiAgent.status, 'active');
|
||
|
||
const psAgent = agents.find(a => a.name === 'terminal-ps');
|
||
assert.equal(psAgent.isSelf, false);
|
||
assert.equal(psAgent.hasAiActivity, false);
|
||
assert.equal(psAgent.shellType, 'powershell');
|
||
assert.equal(psAgent.status, 'idle_shell');
|
||
});
|
||
|
||
test('GatewayDaemon deve calcular e incluir status determinístico ao responder GET_AGENT_TERMINAL', async () => {
|
||
const sentMessages = [];
|
||
const mockWs = {
|
||
send: (str) => sentMessages.push(JSON.parse(str))
|
||
};
|
||
|
||
const mockAdapter = {
|
||
checkAgent: async (agentName) => {
|
||
// Simula terminal com prompt ocioso de IA após término de comando
|
||
return `:: Running command "skyscanner search"...\nResultados encontrados com sucesso.\nAntigravity CLI\n> \n? for shortcuts`;
|
||
}
|
||
};
|
||
|
||
const daemon = new GatewayDaemon({ adapter: mockAdapter });
|
||
daemon.ws = mockWs;
|
||
daemon.connected = true;
|
||
|
||
await daemon.handleRelayMessage({
|
||
type: 'GET_AGENT_TERMINAL',
|
||
agentName: 'BotAssistente'
|
||
});
|
||
|
||
assert.equal(sentMessages.length, 1);
|
||
const msg = sentMessages[0];
|
||
assert.equal(msg.type, 'AGENT_TERMINAL_OUTPUT');
|
||
assert.equal(msg.agentName, 'BotAssistente');
|
||
assert.equal(typeof msg.isThinking, 'boolean');
|
||
// Como termina em "> \n? for shortcuts", isThinking deve ser estritamente false
|
||
assert.equal(msg.isThinking, false, 'Terminal em prompt de IA deve reportar isThinking=false');
|
||
assert.equal(msg.isPaused, false);
|
||
assert.equal(msg.hasAiActivity, true);
|
||
assert.ok(msg.rawOutput.includes('? for shortcuts'));
|
||
});
|
||
|
||
test('MaestriAdapter.sendRawInput deve invocar maestri ask <agent> --raw <seq> e rejeitar sequências inválidas', async () => {
|
||
const adapter = new MaestriAdapter();
|
||
let executedArgs = null;
|
||
|
||
adapter.runMaestri = async (args) => {
|
||
executedArgs = args;
|
||
return { ok: true, output: 'Switch Model\n> Gemini 3.8 Flash\nKeyboard: ↑/↓ Navigate', error: null };
|
||
};
|
||
|
||
const invalidRes = await adapter.sendRawInput('AgenteX', '');
|
||
assert.equal(invalidRes.ok, false);
|
||
assert.equal(executedArgs, null);
|
||
|
||
const res = await adapter.sendRawInput('AgenteX', '\\e[B');
|
||
assert.equal(res.ok, true);
|
||
assert.deepEqual(executedArgs, ['ask', 'AgenteX', '--raw', '\\e[B']);
|
||
assert.ok(res.output.includes('Gemini 3.8 Flash'));
|
||
});
|
||
|
||
test('MaestriAdapter.listAgents deve propagar hasInteractiveMenu e interactiveMenu', async () => {
|
||
const adapter = new MaestriAdapter();
|
||
|
||
adapter.runMaestri = async (args) => {
|
||
if (args[0] === 'list') {
|
||
return {
|
||
ok: true,
|
||
output: `You:\n - name: "maestri-remote"\n\nConnected agents:\n - name: "menu-agent"`
|
||
};
|
||
}
|
||
if (args[0] === 'check' && args[1] === 'menu-agent') {
|
||
return {
|
||
ok: true,
|
||
output: `Do you want to proceed?\n❯ 1. Yes\n 2. No\nEnter to confirm · Esc to cancel`
|
||
};
|
||
}
|
||
return { ok: true, output: '' };
|
||
};
|
||
|
||
const agents = await adapter.listAgents();
|
||
const menuAgent = agents.find(a => a.name === 'menu-agent');
|
||
assert.equal(menuAgent.hasInteractiveMenu, true);
|
||
assert.equal(menuAgent.isThinking, false);
|
||
assert.equal(menuAgent.interactiveMenu.selectedIndex, 0);
|
||
assert.equal(menuAgent.interactiveMenu.options.length, 2);
|
||
});
|
||
|
||
test('GatewayDaemon deve propagar hasInteractiveMenu em GET_AGENT_TERMINAL e executar TERMINAL_RAW_INPUT (keys e raw)', async () => {
|
||
const sentMessages = [];
|
||
const rawCalls = [];
|
||
let currentTerminal = `Switch Model\n> Gemini 4 Argon\n Gemini 3.8 Flash\nKeyboard: ↑/↓ Navigate enter Select esc Go Back`;
|
||
|
||
const mockWs = {
|
||
send: (str) => sentMessages.push(JSON.parse(str))
|
||
};
|
||
|
||
const mockAdapter = {
|
||
checkAgent: async () => currentTerminal,
|
||
sendRawInput: async (agentName, seq) => {
|
||
rawCalls.push({ agentName, seq });
|
||
if (seq === '\\n') {
|
||
currentTerminal = `Model set to Gemini 3.8 Flash\n> \n? for shortcuts`;
|
||
} else if (seq === '\\e[B') {
|
||
currentTerminal = `Switch Model\n Gemini 4 Argon\n> Gemini 3.8 Flash\nKeyboard: ↑/↓ Navigate enter Select esc Go Back`;
|
||
}
|
||
return { ok: true, output: currentTerminal };
|
||
},
|
||
listAgents: async () => [
|
||
{ name: 'BotMenu', isSelf: false, hasAiActivity: true, isThinking: false, hasInteractiveMenu: false, interactiveMenu: null }
|
||
]
|
||
};
|
||
|
||
const daemon = new GatewayDaemon({ adapter: mockAdapter });
|
||
daemon.ws = mockWs;
|
||
daemon.connected = true;
|
||
|
||
await daemon.handleRelayMessage({
|
||
type: 'GET_AGENT_TERMINAL',
|
||
agentName: 'BotMenu'
|
||
});
|
||
|
||
const terminalMsg = sentMessages.find(m => m.type === 'AGENT_TERMINAL_OUTPUT');
|
||
assert.equal(terminalMsg.hasInteractiveMenu, true);
|
||
assert.equal(terminalMsg.isThinking, false);
|
||
assert.equal(terminalMsg.interactiveMenu.options.length, 2);
|
||
|
||
sentMessages.length = 0;
|
||
|
||
await daemon.handleRelayMessage({
|
||
type: 'TERMINAL_RAW_INPUT',
|
||
agentName: 'BotMenu',
|
||
keys: ['\\e[B', '\\n']
|
||
});
|
||
|
||
assert.deepEqual(rawCalls, [
|
||
{ agentName: 'BotMenu', seq: '\\e[B' },
|
||
{ agentName: 'BotMenu', seq: '\\n' }
|
||
]);
|
||
const updatedTerminalMsg = sentMessages.find(m => m.type === 'AGENT_TERMINAL_OUTPUT');
|
||
assert.ok(updatedTerminalMsg, 'Deve emitir AGENT_TERMINAL_OUTPUT atualizado após TERMINAL_RAW_INPUT');
|
||
assert.equal(updatedTerminalMsg.hasInteractiveMenu, false);
|
||
assert.equal(updatedTerminalMsg.isThinking, false);
|
||
|
||
const agentsUpdateMsg = sentMessages.find(m => m.type === 'AGENTS_UPDATE');
|
||
assert.ok(agentsUpdateMsg, 'Deve disparar syncAgents() atualizando AGENTS_UPDATE');
|
||
|
||
// Testa envio com propriedade raw única
|
||
rawCalls.length = 0;
|
||
sentMessages.length = 0;
|
||
await daemon.handleRelayMessage({
|
||
type: 'TERMINAL_RAW_INPUT',
|
||
agentName: 'BotMenu',
|
||
raw: '\\e'
|
||
});
|
||
assert.deepEqual(rawCalls, [{ agentName: 'BotMenu', seq: '\\e' }]);
|
||
assert.ok(sentMessages.some(m => m.type === 'AGENT_TERMINAL_OUTPUT'));
|
||
});
|
||
|
||
test('GatewayDaemon deve abortar keys restantes se sendRawInput falhar no meio e validar entrada', async () => {
|
||
const sentMessages = [];
|
||
const rawCalls = [];
|
||
let checkCalled = 0;
|
||
|
||
const mockWs = {
|
||
send: (str) => sentMessages.push(JSON.parse(str))
|
||
};
|
||
|
||
const mockAdapter = {
|
||
checkAgent: async () => {
|
||
checkCalled++;
|
||
return '△ Permission required\n$ git push\n\nAllow once Reject ctrl+f fullscreen ⇆ select enter confirm';
|
||
},
|
||
sendRawInput: async (agentName, seq) => {
|
||
rawCalls.push({ agentName, seq });
|
||
if (seq === '\\e[C') {
|
||
return { ok: false, output: '', error: 'IPC timeout' };
|
||
}
|
||
return { ok: true, output: 'confirmed' };
|
||
},
|
||
listAgents: async () => []
|
||
};
|
||
|
||
const daemon = new GatewayDaemon({ adapter: mockAdapter });
|
||
daemon.ws = mockWs;
|
||
daemon.connected = true;
|
||
|
||
await daemon.handleRelayMessage({
|
||
type: 'TERMINAL_RAW_INPUT',
|
||
agentName: 'Kilo',
|
||
keys: ['\\e[C', '\\n']
|
||
});
|
||
|
||
assert.deepEqual(rawCalls, [{ agentName: 'Kilo', seq: '\\e[C' }], 'Não deve enviar \\n após falha em seta intermediária');
|
||
assert.equal(checkCalled, 1);
|
||
|
||
rawCalls.length = 0;
|
||
checkCalled = 0;
|
||
sentMessages.length = 0;
|
||
|
||
await daemon.handleRelayMessage({
|
||
type: 'TERMINAL_RAW_INPUT',
|
||
agentName: '',
|
||
keys: []
|
||
});
|
||
|
||
assert.equal(rawCalls.length, 0);
|
||
assert.equal(checkCalled, 0, 'Entrada inválida/vazia não deve consultar checkAgent');
|
||
assert.equal(sentMessages.length, 0);
|
||
});
|
||
|
||
test('resolveTerminalLaunchSpec deve mapear perfis de IA e shell puro corretamente', () => {
|
||
const resolveTerminalLaunchSpec = maestriAdapterModule.resolveTerminalLaunchSpec;
|
||
assert.equal(typeof resolveTerminalLaunchSpec, 'function');
|
||
|
||
assert.deepEqual(
|
||
resolveTerminalLaunchSpec('Antigravity terminal output', { aiType: 'agy', hasAiActivity: true }),
|
||
{ preset: 'Antigravity', command: 'agy', exitSequence: '/exit\\n' }
|
||
);
|
||
assert.deepEqual(
|
||
resolveTerminalLaunchSpec('Claude Code output', { aiType: 'claude', hasAiActivity: true }),
|
||
{ preset: 'Claude Code', command: 'claude', exitSequence: '/exit\\n' }
|
||
);
|
||
assert.deepEqual(
|
||
resolveTerminalLaunchSpec('△ Permission required\nctrl+f fullscreen', { aiType: 'kiro', hasAiActivity: true }),
|
||
{ preset: null, command: 'kilo', exitSequence: '/exit\\n' }
|
||
);
|
||
assert.deepEqual(
|
||
resolveTerminalLaunchSpec('Running opencode agent', { aiType: 'kiro', hasAiActivity: true }),
|
||
{ preset: null, command: 'opencode', exitSequence: '/exit\\n' }
|
||
);
|
||
assert.deepEqual(
|
||
resolveTerminalLaunchSpec('Kiro CLI session', { aiType: 'kiro', hasAiActivity: true }),
|
||
{ preset: null, command: 'kiro-cli', exitSequence: '/exit\\n' }
|
||
);
|
||
assert.deepEqual(
|
||
resolveTerminalLaunchSpec('Gemini CLI output', { aiType: 'gemini', hasAiActivity: true }),
|
||
{ preset: null, command: 'gemini', exitSequence: '/exit\\n' }
|
||
);
|
||
assert.deepEqual(
|
||
resolveTerminalLaunchSpec('Aider prompt', { aiType: 'aider', hasAiActivity: true }),
|
||
{ preset: null, command: 'aider', exitSequence: '/exit\\n' }
|
||
);
|
||
assert.deepEqual(
|
||
resolveTerminalLaunchSpec('PS D:\\workspace>', { aiType: 'powershell', hasAiActivity: false }),
|
||
{ preset: 'Shell', command: null, exitSequence: null }
|
||
);
|
||
assert.deepEqual(
|
||
resolveTerminalLaunchSpec('codex running', { aiType: 'generic_ai', hasAiActivity: true }),
|
||
{ preset: 'Codex', command: 'codex', exitSequence: '/exit\\n' }
|
||
);
|
||
assert.deepEqual(
|
||
resolveTerminalLaunchSpec('Unknown AI CLI', { aiType: 'generic_ai', hasAiActivity: true }),
|
||
{ preset: null, command: null, exitSequence: '\\x03' }
|
||
);
|
||
// Só os últimos 3000 chars entram na heurística de codex
|
||
assert.deepEqual(
|
||
resolveTerminalLaunchSpec('codex ' + 'x'.repeat(3100), { aiType: 'generic_ai', hasAiActivity: true }),
|
||
{ preset: null, command: null, exitSequence: '\\x03' }
|
||
);
|
||
assert.deepEqual(
|
||
resolveTerminalLaunchSpec(null, { aiType: 'generic_ai', hasAiActivity: true }),
|
||
{ preset: null, command: null, exitSequence: '\\x03' }
|
||
);
|
||
});
|
||
|
||
test('MaestriAdapter.restartAgentTerminal deve bloquear reinício do próprio daemon (isSelf) sem enviar Ctrl+C', async () => {
|
||
const defaultAdapter = new MaestriAdapter();
|
||
assert.equal(defaultAdapter.restartDelayMs, 400);
|
||
const clampedAdapter = new MaestriAdapter({ restartDelayMs: -15 });
|
||
assert.equal(clampedAdapter.restartDelayMs, 0);
|
||
|
||
const cliCalls = [];
|
||
const adapter = new MaestriAdapter({ restartDelayMs: 0 });
|
||
adapter.runMaestri = async (args) => {
|
||
cliCalls.push(args);
|
||
return { ok: true, output: '' };
|
||
};
|
||
|
||
const invalidEmpty = await adapter.restartAgentTerminal(' ');
|
||
assert.equal(invalidEmpty.ok, false);
|
||
assert.equal(invalidEmpty.method, 'invalid_agent');
|
||
assert.equal(invalidEmpty.output, '');
|
||
assert.equal(invalidEmpty.error, 'Nome de agente inválido.');
|
||
|
||
const invalidType = await adapter.restartAgentTerminal(null);
|
||
assert.equal(invalidType.ok, false);
|
||
assert.equal(invalidType.method, 'invalid_agent');
|
||
|
||
const blocked = await adapter.restartAgentTerminal('maestri-remote-channel', { isSelf: true });
|
||
assert.equal(blocked.ok, false);
|
||
assert.equal(blocked.method, 'blocked_self');
|
||
assert.equal(blocked.output, '');
|
||
assert.match(blocked.error, /próprio terminal/i);
|
||
assert.equal(cliCalls.length, 0, 'Nunca deve enviar \\x03 ou recruit quando isSelf for true');
|
||
|
||
// Também bloqueia quando descoberto previamente via listAgents(), sem bloquear Worker comum
|
||
adapter.runMaestri = async (args) => {
|
||
cliCalls.push(args);
|
||
if (args[0] === 'list') {
|
||
return {
|
||
ok: true,
|
||
output: 'You:\n- name: "maestri-remote-self", maestro: false\nConnected agents:\n- name: "Worker"\n'
|
||
};
|
||
}
|
||
if (args[0] === 'check') {
|
||
return { ok: true, output: 'PS D:\\proj> ' };
|
||
}
|
||
if (args[0] === 'recruit') {
|
||
return { ok: true, output: 'Recreated Worker' };
|
||
}
|
||
return { ok: true, output: '' };
|
||
};
|
||
await adapter.listAgents();
|
||
cliCalls.length = 0;
|
||
|
||
const blockedCached = await adapter.restartAgentTerminal('maestri-remote-self');
|
||
assert.equal(blockedCached.ok, false);
|
||
assert.equal(blockedCached.method, 'blocked_self');
|
||
assert.equal(cliCalls.length, 0);
|
||
|
||
const workerOk = await adapter.restartAgentTerminal('Worker');
|
||
assert.equal(workerOk.ok, true);
|
||
assert.equal(workerOk.method, 'recruit_replace');
|
||
|
||
const forcedAllowSelfFalse = await adapter.restartAgentTerminal('maestri-remote-self', { isSelf: false });
|
||
assert.equal(forcedAllowSelfFalse.ok, true);
|
||
assert.equal(forcedAllowSelfFalse.method, 'recruit_replace');
|
||
});
|
||
|
||
test('MaestriAdapter.restartAgentTerminal deve tentar recruit --replace com preset ou comando quando em Maestro Mode', async () => {
|
||
const cliCalls = [];
|
||
const adapter = new MaestriAdapter({ restartDelayMs: 0 });
|
||
let checkCount = 0;
|
||
|
||
adapter.runMaestri = async (args) => {
|
||
cliCalls.push(args);
|
||
if (args[0] === 'check') {
|
||
checkCount++;
|
||
if (checkCount === 1) {
|
||
return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle\n❯ ' };
|
||
}
|
||
return { ok: true, output: 'Claude Code reiniciado\n❯ ' };
|
||
}
|
||
if (args[0] === 'recruit') {
|
||
return { ok: true, output: 'Recreated Claude' };
|
||
}
|
||
return { ok: false, output: '' };
|
||
};
|
||
|
||
const resPreset = await adapter.restartAgentTerminal('Claude');
|
||
assert.equal(resPreset.ok, true);
|
||
assert.equal(resPreset.method, 'recruit_replace');
|
||
assert.equal(resPreset.error, null);
|
||
assert.ok(resPreset.output.includes('Claude Code reiniciado'));
|
||
assert.deepEqual(cliCalls[1], ['recruit', 'Claude', '--preset', 'Claude Code', '--replace', 'Claude']);
|
||
|
||
// Caso sem preset mapeado (gemini): usa --command
|
||
cliCalls.length = 0;
|
||
checkCount = 0;
|
||
adapter.runMaestri = async (args) => {
|
||
cliCalls.push(args);
|
||
if (args[0] === 'check') {
|
||
checkCount++;
|
||
return checkCount === 1
|
||
? { ok: true, output: 'Gemini CLI\nType your message or @path/to/file' }
|
||
: { ok: true, output: 'Gemini CLI pronto' };
|
||
}
|
||
if (args[0] === 'recruit') {
|
||
return { ok: true, output: 'Recreated Gemini' };
|
||
}
|
||
return { ok: false, output: '' };
|
||
};
|
||
|
||
const resCmd = await adapter.restartAgentTerminal('Gemini');
|
||
assert.equal(resCmd.ok, true);
|
||
assert.equal(resCmd.method, 'recruit_replace');
|
||
assert.deepEqual(cliCalls[1], ['recruit', 'Gemini', '--command', 'gemini', '--replace', 'Gemini']);
|
||
});
|
||
|
||
test('MaestriAdapter.restartAgentTerminal deve usar fallback --raw (\\x03 -> /exit -> \\x04 -> relançar) ou \\n em shell e tratar falha', async () => {
|
||
const rawInputs = [];
|
||
const adapter = new MaestriAdapter({ restartDelayMs: 0 });
|
||
let checkSeq = 0;
|
||
|
||
// 1. Fluxo completo IA: recruit falha -> \x03 -> ainda IA -> /exit\n -> ainda IA -> \x04 -> shell -> claude\n
|
||
adapter.runMaestri = async (args) => {
|
||
if (args[0] === 'recruit') {
|
||
return { ok: false, output: '', error: 'Maestro Mode is required for recruit' };
|
||
}
|
||
if (args[0] === 'ask' && args[2] === '--raw') {
|
||
rawInputs.push(args[3]);
|
||
return { ok: true, output: '' };
|
||
}
|
||
if (args[0] === 'check') {
|
||
checkSeq++;
|
||
if (checkSeq === 1) return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle' };
|
||
if (checkSeq === 2) return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle' }; // após \x03 ainda ativo
|
||
if (checkSeq === 3) return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle' }; // após /exit\n ainda ativo
|
||
if (checkSeq === 4) return { ok: true, output: 'PS C:\\Users\\dev> ' }; // após \x04 voltou ao shell
|
||
return { ok: true, output: 'Claude Code reiniciado via raw\n❯ ' }; // após claude\n
|
||
}
|
||
return { ok: false, output: '' };
|
||
};
|
||
|
||
const aiFallbackRes = await adapter.restartAgentTerminal('Claude');
|
||
assert.equal(aiFallbackRes.ok, true);
|
||
assert.equal(aiFallbackRes.method, 'raw_restart');
|
||
assert.equal(aiFallbackRes.error, null);
|
||
assert.deepEqual(rawInputs, ['\\x03', '/exit\\n', '\\x04', 'claude\\n']);
|
||
assert.ok(aiFallbackRes.output.includes('Claude Code reiniciado via raw'));
|
||
|
||
// 2. Shell puro: recruit falha -> \x03 -> \n
|
||
rawInputs.length = 0;
|
||
checkSeq = 0;
|
||
adapter.runMaestri = async (args) => {
|
||
if (args[0] === 'recruit') {
|
||
return { ok: false, output: '', error: 'Not in maestro mode' };
|
||
}
|
||
if (args[0] === 'ask' && args[2] === '--raw') {
|
||
rawInputs.push(args[3]);
|
||
return { ok: true, output: '' };
|
||
}
|
||
if (args[0] === 'check') {
|
||
checkSeq++;
|
||
if (checkSeq <= 2) return { ok: true, output: 'PS D:\\proj> ' };
|
||
return { ok: true, output: 'PS D:\\proj> prompt limpo' };
|
||
}
|
||
return { ok: false, output: '' };
|
||
};
|
||
|
||
const shellFallbackRes = await adapter.restartAgentTerminal('TermShell');
|
||
assert.equal(shellFallbackRes.ok, true);
|
||
assert.equal(shellFallbackRes.method, 'raw_restart');
|
||
assert.deepEqual(rawInputs, ['\\x03', '\\n']);
|
||
assert.ok(shellFallbackRes.output.includes('prompt limpo'));
|
||
|
||
// 3. Falha ao enviar \x03 inicial deve abortar e retornar ok: false preservando rawBefore quando output vier vazio
|
||
rawInputs.length = 0;
|
||
adapter.runMaestri = async (args) => {
|
||
if (args[0] === 'check') return { ok: true, output: 'PS D:\\proj> travado' };
|
||
if (args[0] === 'recruit') return { ok: false, output: '', error: 'No maestro' };
|
||
if (args[0] === 'ask' && args[2] === '--raw') {
|
||
return { ok: false, output: '', error: 'IPC timeout' };
|
||
}
|
||
return { ok: false, output: '' };
|
||
};
|
||
|
||
const failRes = await adapter.restartAgentTerminal('TermTravado');
|
||
assert.equal(failRes.ok, false);
|
||
assert.equal(failRes.method, 'raw_restart');
|
||
assert.equal(failRes.output, 'PS D:\\proj> travado');
|
||
assert.match(failRes.error, /IPC timeout/);
|
||
|
||
// 4. Quando generic_ai não tem preset/command, pula recruit e usa fallback --raw sem erro
|
||
const calledRecruit = [];
|
||
rawInputs.length = 0;
|
||
checkSeq = 0;
|
||
adapter.runMaestri = async (args) => {
|
||
if (args[0] === 'recruit') {
|
||
calledRecruit.push(args);
|
||
return { ok: true, output: 'should not happen' };
|
||
}
|
||
if (args[0] === 'ask' && args[2] === '--raw') {
|
||
rawInputs.push(args[3]);
|
||
return { ok: true, output: '' };
|
||
}
|
||
if (args[0] === 'check') {
|
||
checkSeq++;
|
||
if (checkSeq === 1) return { ok: true, output: '⠋ thinking...' }; // generic_ai
|
||
return { ok: true, output: '⠋ thinking still...' };
|
||
}
|
||
return { ok: false, output: '' };
|
||
};
|
||
const genericRawRes = await adapter.restartAgentTerminal('GenericAgent');
|
||
assert.equal(calledRecruit.length, 0, 'Sem preset/command não deve acionar recruit');
|
||
assert.deepEqual(rawInputs, ['\\x03', '\\n'], 'Sem command não deve chamar /exit mesmo se ainda ativo');
|
||
assert.equal(genericRawRes.ok, true);
|
||
|
||
// 5. Quando \x03 sozinho já volta ao shell, não envia /exit\n nem \x04; apenas relança claude\n
|
||
rawInputs.length = 0;
|
||
checkSeq = 0;
|
||
adapter.runMaestri = async (args) => {
|
||
if (args[0] === 'recruit') return { ok: false, output: '', error: 'No maestro' };
|
||
if (args[0] === 'ask' && args[2] === '--raw') {
|
||
rawInputs.push(args[3]);
|
||
return { ok: true, output: '' };
|
||
}
|
||
if (args[0] === 'check') {
|
||
checkSeq++;
|
||
if (checkSeq === 1) return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle' };
|
||
if (checkSeq === 2) return { ok: true, output: 'PS D:\\proj> ' };
|
||
return { ok: true, output: 'Claude Code ok' };
|
||
}
|
||
return { ok: false, output: '' };
|
||
};
|
||
await adapter.restartAgentTerminal('Claude');
|
||
assert.deepEqual(rawInputs, ['\\x03', 'claude\\n']);
|
||
|
||
// 6. Quando /exit\n volta ao shell, não envia \x04; apenas relança claude\n
|
||
rawInputs.length = 0;
|
||
checkSeq = 0;
|
||
adapter.runMaestri = async (args) => {
|
||
if (args[0] === 'recruit') return { ok: false, output: '', error: 'No maestro' };
|
||
if (args[0] === 'ask' && args[2] === '--raw') {
|
||
rawInputs.push(args[3]);
|
||
return { ok: true, output: '' };
|
||
}
|
||
if (args[0] === 'check') {
|
||
checkSeq++;
|
||
if (checkSeq <= 2) return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle' };
|
||
if (checkSeq === 3) return { ok: true, output: 'PS D:\\proj> ' };
|
||
return { ok: true, output: 'Claude Code ok' };
|
||
}
|
||
return { ok: false, output: '' };
|
||
};
|
||
await adapter.restartAgentTerminal('Claude');
|
||
assert.deepEqual(rawInputs, ['\\x03', '/exit\\n', 'claude\\n']);
|
||
|
||
// 7. Quando spec.command existe e ainda continua em IA após \x04, não envia \n solto e retorna ok: false
|
||
rawInputs.length = 0;
|
||
adapter.runMaestri = async (args) => {
|
||
if (args[0] === 'recruit') return { ok: false, output: '', error: 'No maestro' };
|
||
if (args[0] === 'ask' && args[2] === '--raw') {
|
||
rawInputs.push(args[3]);
|
||
return { ok: true, output: '' };
|
||
}
|
||
if (args[0] === 'check') {
|
||
return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle' };
|
||
}
|
||
return { ok: false, output: '' };
|
||
};
|
||
const stuckRes = await adapter.restartAgentTerminal('Claude');
|
||
assert.deepEqual(rawInputs, ['\\x03', '/exit\\n', '\\x04']);
|
||
assert.equal(stuckRes.ok, false);
|
||
assert.equal(stuckRes.method, 'raw_restart');
|
||
assert.match(stuckRes.error, /Não foi possível encerrar/);
|
||
|
||
// 8. Falha intermediária em exitSequence, EOF (\x04), relançamento ou \n de shell deve retornar ok: false sem silenciosamente passar
|
||
for (const [failingSeq, agentLabel, expectedCount, checkOut] of [
|
||
['/exit\\n', 'Claude', 2, 'Claude Code v2.1\nshift+tab to cycle'],
|
||
['\\x04', 'Claude', 3, 'Claude Code v2.1\nshift+tab to cycle'],
|
||
['\\n', 'TermShell', 2, 'PS D:\\proj> ']
|
||
]) {
|
||
const seqLog = [];
|
||
let checks = 0;
|
||
adapter.runMaestri = async (args) => {
|
||
if (args[0] === 'recruit') return { ok: false, output: '', error: 'No maestro' };
|
||
if (args[0] === 'ask' && args[2] === '--raw') {
|
||
seqLog.push(args[3]);
|
||
if (args[3] === failingSeq) return { ok: false, output: '', error: `falha_${failingSeq}` };
|
||
return { ok: true, output: '' };
|
||
}
|
||
if (args[0] === 'check') {
|
||
checks++;
|
||
return { ok: true, output: checkOut };
|
||
}
|
||
return { ok: false, output: '' };
|
||
};
|
||
const midFailRes = await adapter.restartAgentTerminal(agentLabel);
|
||
assert.equal(midFailRes.ok, false, `Falha em ${failingSeq} deve retornar ok: false`);
|
||
assert.equal(seqLog.length, expectedCount);
|
||
assert.match(midFailRes.error, new RegExp(`falha_${failingSeq.replace('\\', '\\\\')}`));
|
||
}
|
||
|
||
rawInputs.length = 0;
|
||
checkSeq = 0;
|
||
adapter.runMaestri = async (args) => {
|
||
if (args[0] === 'recruit') return { ok: false, output: '', error: 'No maestro' };
|
||
if (args[0] === 'ask' && args[2] === '--raw') {
|
||
rawInputs.push(args[3]);
|
||
if (args[3] === 'claude\\n') return { ok: false, output: '', error: 'relaunch_timeout' };
|
||
return { ok: true, output: '' };
|
||
}
|
||
if (args[0] === 'check') {
|
||
checkSeq++;
|
||
if (checkSeq === 1) return { ok: true, output: 'Claude Code v2.1\nshift+tab to cycle' };
|
||
return { ok: true, output: 'PS D:\\proj> ' };
|
||
}
|
||
return { ok: false, output: '' };
|
||
};
|
||
const relaunchFail = await adapter.restartAgentTerminal('Claude');
|
||
assert.equal(relaunchFail.ok, false);
|
||
assert.match(relaunchFail.error, /relaunch_timeout/);
|
||
|
||
// 9. Atraso positivo real no wait() quando restartDelayMs > 0
|
||
const timedAdapter = new MaestriAdapter({ restartDelayMs: 15 });
|
||
const t0 = Date.now();
|
||
await timedAdapter.wait(15);
|
||
assert.ok(Date.now() - t0 >= 10);
|
||
});
|
||
|
||
test('GatewayDaemon deve tratar RESTART_AGENT_TERMINAL, detectar isSelf no cache e emitir AGENT_TERMINAL_RESTARTED + output', async () => {
|
||
const sentMessages = [];
|
||
const restartCalls = [];
|
||
let checkFallbackCalled = 0;
|
||
|
||
const mockWs = {
|
||
send: (str) => sentMessages.push(JSON.parse(str))
|
||
};
|
||
|
||
const mockAdapter = {
|
||
listAgents: async () => [
|
||
{ name: 'maestri-remote', isSelf: true, status: 'active' },
|
||
{ name: 'Claude', isSelf: false, status: 'active' }
|
||
],
|
||
checkAgent: async () => {
|
||
checkFallbackCalled++;
|
||
return 'PS D:\\workspace> fallback check';
|
||
},
|
||
restartAgentTerminal: async (agentName, opts) => {
|
||
restartCalls.push({ agentName, opts });
|
||
if (opts?.isSelf) {
|
||
return {
|
||
ok: false,
|
||
method: 'blocked_self',
|
||
output: '',
|
||
error: 'Não é possível reiniciar o próprio terminal do daemon remoto por este comando.'
|
||
};
|
||
}
|
||
return {
|
||
ok: true,
|
||
method: 'recruit_replace',
|
||
output: 'Claude Code reiniciado com sucesso\n❯ ',
|
||
error: null
|
||
};
|
||
}
|
||
};
|
||
|
||
const daemon = new GatewayDaemon({ adapter: mockAdapter });
|
||
daemon.ws = mockWs;
|
||
daemon.connected = true;
|
||
|
||
// Popula lastAgents via syncAgents
|
||
await daemon.syncAgents();
|
||
sentMessages.length = 0;
|
||
|
||
// 1. Reinício bem-sucedido
|
||
await daemon.handleRelayMessage({
|
||
type: 'RESTART_AGENT_TERMINAL',
|
||
agentName: ' Claude '
|
||
});
|
||
|
||
assert.deepEqual(restartCalls[0], { agentName: 'Claude', opts: { isSelf: false } });
|
||
const restartedEvt = sentMessages.find(m => m.type === 'AGENT_TERMINAL_RESTARTED');
|
||
assert.ok(restartedEvt, 'Deve enviar AGENT_TERMINAL_RESTARTED');
|
||
assert.equal(restartedEvt.agentName, 'Claude');
|
||
assert.equal(restartedEvt.ok, true);
|
||
assert.equal(restartedEvt.method, 'recruit_replace');
|
||
assert.equal(restartedEvt.error, null);
|
||
|
||
const outputEvt = sentMessages.find(m => m.type === 'AGENT_TERMINAL_OUTPUT');
|
||
assert.ok(outputEvt, 'Deve emitir AGENT_TERMINAL_OUTPUT atualizado');
|
||
assert.equal(outputEvt.agentName, 'Claude');
|
||
assert.ok(sentMessages.some(m => m.type === 'AGENTS_UPDATE'), 'Deve disparar syncAgents');
|
||
assert.equal(checkFallbackCalled, 0, 'Não precisa chamar checkAgent se restartAgentTerminal já retornou output');
|
||
|
||
// 2. Reinício do próprio daemon identificado via lastAgents (isSelf: true)
|
||
sentMessages.length = 0;
|
||
restartCalls.length = 0;
|
||
await daemon.handleRelayMessage({
|
||
type: 'RESTART_AGENT_TERMINAL',
|
||
agentName: 'maestri-remote'
|
||
});
|
||
assert.deepEqual(restartCalls[0], { agentName: 'maestri-remote', opts: { isSelf: true } });
|
||
const selfEvt = sentMessages.find(m => m.type === 'AGENT_TERMINAL_RESTARTED');
|
||
assert.equal(selfEvt.ok, false);
|
||
assert.equal(selfEvt.method, 'blocked_self');
|
||
assert.equal(checkFallbackCalled, 1, 'Sem output no retorno, busca checkAgent para emitir snapshot');
|
||
|
||
// 3. agentName vazio ou não-string é ignorado; tipo desconhecido também não aciona restartAgentTerminal
|
||
sentMessages.length = 0;
|
||
restartCalls.length = 0;
|
||
await daemon.handleRelayMessage({ type: 'RESTART_AGENT_TERMINAL', agentName: ' ' });
|
||
await daemon.handleRelayMessage({ type: 'RESTART_AGENT_TERMINAL', agentName: 123 });
|
||
await daemon.handleRelayMessage({ type: 'UNKNOWN_EVENT', agentName: 'Claude' });
|
||
assert.equal(restartCalls.length, 0);
|
||
assert.equal(sentMessages.length, 0);
|
||
|
||
// 4. Agente fora do cache usa msg.isSelf === true vs undefined e trata exceção lançada por restartAgentTerminal
|
||
sentMessages.length = 0;
|
||
restartCalls.length = 0;
|
||
await daemon.handleRelayMessage({ type: 'RESTART_AGENT_TERMINAL', agentName: 'Adhoc', isSelf: true });
|
||
assert.deepEqual(restartCalls[0], { agentName: 'Adhoc', opts: { isSelf: true } });
|
||
|
||
restartCalls.length = 0;
|
||
sentMessages.length = 0;
|
||
await daemon.handleRelayMessage({ type: 'RESTART_AGENT_TERMINAL', agentName: 'Adhoc', isSelf: false });
|
||
assert.deepEqual(restartCalls[0], { agentName: 'Adhoc', opts: { isSelf: undefined } });
|
||
|
||
const throwingDaemon = new GatewayDaemon({
|
||
adapter: {
|
||
listAgents: async () => [],
|
||
checkAgent: async () => 'PS D:\\fallback>',
|
||
restartAgentTerminal: async () => {
|
||
throw new Error('CLI crashed');
|
||
}
|
||
}
|
||
});
|
||
const thrownSent = [];
|
||
assert.deepEqual(throwingDaemon.lastAgents, []);
|
||
throwingDaemon.ws = { send: (s) => thrownSent.push(JSON.parse(s)) };
|
||
throwingDaemon.connected = true;
|
||
await throwingDaemon.handleRelayMessage({ type: 'RESTART_AGENT_TERMINAL', agentName: 'Claude' });
|
||
const errEvt = thrownSent.find(m => m.type === 'AGENT_TERMINAL_RESTARTED');
|
||
assert.equal(errEvt.ok, false);
|
||
assert.equal(errEvt.method, 'raw_restart');
|
||
assert.equal(errEvt.error, 'CLI crashed');
|
||
const errFallbackOut = thrownSent.find(m => m.type === 'AGENT_TERMINAL_OUTPUT');
|
||
assert.ok(errFallbackOut && errFallbackOut.output.includes('fallback'));
|
||
|
||
// Exceção sem message conectado devolve erro padrão
|
||
const emptyErrSent = [];
|
||
const silentErrDaemon = new GatewayDaemon({
|
||
adapter: {
|
||
listAgents: async () => null,
|
||
checkAgent: async () => 'PS D:\\fallback>',
|
||
restartAgentTerminal: async () => { throw {}; }
|
||
}
|
||
});
|
||
silentErrDaemon.ws = { send: (s) => emptyErrSent.push(JSON.parse(s)) };
|
||
silentErrDaemon.connected = true;
|
||
await silentErrDaemon.syncAgents();
|
||
assert.deepEqual(silentErrDaemon.lastAgents, []);
|
||
await silentErrDaemon.handleRelayMessage({ type: 'RESTART_AGENT_TERMINAL', agentName: 'Claude' });
|
||
assert.equal(emptyErrSent.find(m => m.type === 'AGENT_TERMINAL_RESTARTED').error, 'Erro interno ao reiniciar terminal');
|
||
|
||
// Gateway desconectado não envia pelo socket
|
||
silentErrDaemon.connected = false;
|
||
silentErrDaemon.ws = { send: () => { throw new Error('should not send disconnected'); } };
|
||
await silentErrDaemon.handleRelayMessage({ type: 'RESTART_AGENT_TERMINAL', agentName: 'Claude' });
|
||
});
|
||
|
||
test('GatewayDaemon intercepta comandos /modelo, /model e /models no CHAT_SEND e despacha em modo raw sem enter prematuro', async () => {
|
||
const sentMessages = [];
|
||
const rawCalls = [];
|
||
let askCalled = false;
|
||
|
||
const mockWs = {
|
||
send: (str) => sentMessages.push(JSON.parse(str))
|
||
};
|
||
|
||
let menuOpen = false;
|
||
const mockAdapter = {
|
||
wait: async () => {},
|
||
sendRawInput: async (agentName, seq) => {
|
||
rawCalls.push({ agentName, seq });
|
||
if (seq.includes('/model')) menuOpen = true;
|
||
else if (seq === '\\x1b') menuOpen = false;
|
||
return { ok: true, output: 'raw_ok' };
|
||
},
|
||
askAgent: async () => {
|
||
askCalled = true;
|
||
return { ok: true, output: 'should not be called' };
|
||
},
|
||
checkAgent: async () => menuOpen
|
||
? 'Switch Model\n\n Search: \n> Gemini 3.8 Flash (current)\n\nKeyboard: ↑/↓ Navigate enter Select esc Go Back'
|
||
: 'Antigravity CLI\n> \n? for shortcuts',
|
||
listAgents: async () => [{ name: 'AgyAgent', aiType: 'agy' }, { name: 'KiloAgent', aiType: 'kiro' }]
|
||
};
|
||
|
||
const daemon = new GatewayDaemon({ adapter: mockAdapter });
|
||
daemon.ws = mockWs;
|
||
daemon.connected = true;
|
||
await daemon.syncAgents();
|
||
|
||
// 1. Antigravity com /modelo em português e filtro de busca
|
||
sentMessages.length = 0;
|
||
rawCalls.length = 0;
|
||
await daemon.handleRelayMessage({
|
||
type: 'CHAT_SEND',
|
||
chatId: 'chat-1',
|
||
agentName: 'AgyAgent',
|
||
message: '/modelo claude'
|
||
});
|
||
|
||
assert.equal(askCalled, false, 'Comando de modelo não deve chamar askAgent com enter síncrono');
|
||
assert.deepEqual(rawCalls, [
|
||
{ agentName: 'AgyAgent', seq: '\\x15/model\\n' },
|
||
{ agentName: 'AgyAgent', seq: 'claude' }
|
||
]);
|
||
|
||
const ackMsg = sentMessages.find(m => m.type === 'CHAT_ACK');
|
||
assert.ok(ackMsg, 'Deve enviar CHAT_ACK imediato');
|
||
|
||
const termMsg = sentMessages.find(m => m.type === 'AGENT_TERMINAL_OUTPUT');
|
||
assert.ok(termMsg, 'Deve emitir AGENT_TERMINAL_OUTPUT com o menu aberto');
|
||
assert.equal(termMsg.hasInteractiveMenu, true);
|
||
|
||
const respMsg = sentMessages.find(m => m.type === 'CHAT_RESPONSE');
|
||
assert.ok(respMsg && respMsg.ok);
|
||
assert.ok(respMsg.reply.includes('Menu de modelos interativo aberto'));
|
||
|
||
// 2. Kilo com /models ou /model
|
||
menuOpen = false;
|
||
sentMessages.length = 0;
|
||
rawCalls.length = 0;
|
||
await daemon.handleRelayMessage({
|
||
type: 'CHAT_SEND',
|
||
chatId: 'chat-2',
|
||
agentName: 'KiloAgent',
|
||
message: '/models'
|
||
});
|
||
|
||
assert.deepEqual(rawCalls, [
|
||
{ agentName: 'KiloAgent', seq: '\\x15/model\\n' }
|
||
]);
|
||
});
|
||
|
||
test('GatewayDaemon intercepta comandos /effort, /esforco e /esforço no CHAT_SEND e despacha em modo raw', async () => {
|
||
const sentMessages = [];
|
||
const rawCalls = [];
|
||
let askCalled = false;
|
||
let menuOpen = false;
|
||
|
||
const mockWs = {
|
||
send: (str) => sentMessages.push(JSON.parse(str))
|
||
};
|
||
|
||
const mockAdapter = {
|
||
wait: async () => {},
|
||
sendRawInput: async (agentName, seq) => {
|
||
rawCalls.push({ agentName, seq });
|
||
if (seq === '\\x15/effort\\n') menuOpen = true;
|
||
else if (seq === '\\x1b') menuOpen = false;
|
||
return { ok: true, output: 'raw_ok' };
|
||
},
|
||
askAgent: async () => {
|
||
askCalled = true;
|
||
return { ok: true, output: 'should not be called' };
|
||
},
|
||
checkAgent: async () => menuOpen
|
||
? 'Set Effort\n\n ◂ ●━━━━━━━━━━━━━━◉──────────────○ ▸\n low medium high\n\nKeyboard: ←/→ Effort enter Select esc Go Back'
|
||
: 'Antigravity CLI\n> \n? for shortcuts',
|
||
listAgents: async () => [{ name: 'AgyAgent', aiType: 'agy' }]
|
||
};
|
||
|
||
const daemon = new GatewayDaemon({ adapter: mockAdapter });
|
||
daemon.ws = mockWs;
|
||
daemon.connected = true;
|
||
await daemon.syncAgents();
|
||
|
||
// 1. /effort puro abre menu interativo
|
||
sentMessages.length = 0;
|
||
rawCalls.length = 0;
|
||
await daemon.handleRelayMessage({
|
||
type: 'CHAT_SEND',
|
||
chatId: 'chat-effort-1',
|
||
agentName: 'AgyAgent',
|
||
message: '/effort'
|
||
});
|
||
|
||
assert.equal(askCalled, false);
|
||
assert.deepEqual(rawCalls, [
|
||
{ agentName: 'AgyAgent', seq: '\\x15/effort\\n' }
|
||
]);
|
||
|
||
const respMsg = sentMessages.find(m => m.type === 'CHAT_RESPONSE');
|
||
assert.ok(respMsg && respMsg.ok);
|
||
assert.ok(respMsg.reply.includes('Menu de esforço de raciocínio aberto'));
|
||
|
||
// 2. /esforço alto normaliza para high e aplica direto
|
||
menuOpen = false;
|
||
sentMessages.length = 0;
|
||
rawCalls.length = 0;
|
||
await daemon.handleRelayMessage({
|
||
type: 'CHAT_SEND',
|
||
chatId: 'chat-effort-2',
|
||
agentName: 'AgyAgent',
|
||
message: '/esforço alto'
|
||
});
|
||
|
||
assert.deepEqual(rawCalls, [
|
||
{ agentName: 'AgyAgent', seq: '\\x15/effort high\\n' }
|
||
]);
|
||
const respMsg2 = sentMessages.find(m => m.type === 'CHAT_RESPONSE');
|
||
assert.ok(respMsg2 && respMsg2.ok);
|
||
assert.ok(respMsg2.reply.includes('high'));
|
||
|
||
// 3. Agente Kiro CLI: /effort puro envia /effort\n
|
||
menuOpen = false;
|
||
sentMessages.length = 0;
|
||
rawCalls.length = 0;
|
||
mockAdapter.listAgents = async () => [{ name: 'KiroAgent', aiType: 'kiro' }];
|
||
daemon.lastAgents = [{ name: 'KiroAgent', aiType: 'kiro' }];
|
||
|
||
await daemon.handleRelayMessage({
|
||
type: 'CHAT_SEND',
|
||
chatId: 'chat-effort-3',
|
||
agentName: 'KiroAgent',
|
||
message: '/effort'
|
||
});
|
||
|
||
assert.deepEqual(rawCalls, [
|
||
{ agentName: 'KiroAgent', seq: '\\x15/effort\\n' }
|
||
]);
|
||
const respMsg3 = sentMessages.find(m => m.type === 'CHAT_RESPONSE');
|
||
assert.ok(respMsg3 && respMsg3.ok);
|
||
assert.ok(respMsg3.reply.includes('Painel de controles/esforço do modelo aberto'));
|
||
|
||
// 4. Agente Kiro CLI: /esforço medium envia /effort medium\n
|
||
menuOpen = false;
|
||
sentMessages.length = 0;
|
||
rawCalls.length = 0;
|
||
await daemon.handleRelayMessage({
|
||
type: 'CHAT_SEND',
|
||
chatId: 'chat-effort-4',
|
||
agentName: 'KiroAgent',
|
||
message: '/effort medium'
|
||
});
|
||
|
||
assert.deepEqual(rawCalls, [
|
||
{ agentName: 'KiroAgent', seq: '\\x15/effort medium\\n' }
|
||
]);
|
||
const respMsg4 = sentMessages.find(m => m.type === 'CHAT_RESPONSE');
|
||
assert.ok(respMsg4 && respMsg4.ok);
|
||
assert.ok(respMsg4.reply.includes('medium'));
|
||
|
||
// 5. Sequência combinada: se o menu anterior ainda estiver aberto (menuOpen = true), fecha com ESC (\x1b) antes de enviar /effort
|
||
menuOpen = true;
|
||
sentMessages.length = 0;
|
||
rawCalls.length = 0;
|
||
await daemon.handleRelayMessage({
|
||
type: 'CHAT_SEND',
|
||
chatId: 'chat-effort-5',
|
||
agentName: 'KiroAgent',
|
||
message: '/effort'
|
||
});
|
||
|
||
assert.deepEqual(rawCalls, [
|
||
{ agentName: 'KiroAgent', seq: '\\x1b' },
|
||
{ agentName: 'KiroAgent', seq: '\\x15/effort\\n' }
|
||
]);
|
||
});
|
||
|
||
test('MaestriAdapter deve consultar checkAgent e sendRawInput via Named Pipe direto e fazer fallback se indisponível', async () => {
|
||
const net = await import('node:net');
|
||
const pipeName = process.platform === 'win32'
|
||
? `\\\\.\\pipe\\test-maestri-pipe-${Date.now()}`
|
||
: `/tmp/test-maestri-pipe-${Date.now()}.sock`;
|
||
|
||
const receivedRequests = [];
|
||
const server = net.createServer((socket) => {
|
||
let raw = '';
|
||
socket.on('data', (chunk) => {
|
||
raw += chunk.toString();
|
||
if (raw.includes('\r\n\r\n')) {
|
||
const [headers, ...bodyParts] = raw.split('\r\n\r\n');
|
||
const body = bodyParts.join('\r\n\r\n');
|
||
const firstLine = headers.split('\r\n')[0];
|
||
receivedRequests.push({ firstLine, headers, body });
|
||
|
||
if (firstLine.startsWith('GET /check')) {
|
||
socket.write('HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\nOutput do agente via pipe direto');
|
||
socket.end();
|
||
} else if (firstLine.startsWith('POST /raw')) {
|
||
socket.write('HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\n\r\nRaw enviado com sucesso');
|
||
socket.end();
|
||
} else {
|
||
socket.write('HTTP/1.0 404 Not Found\r\n\r\n');
|
||
socket.end();
|
||
}
|
||
}
|
||
});
|
||
});
|
||
|
||
await new Promise((resolve) => server.listen(pipeName, resolve));
|
||
|
||
try {
|
||
const adapter = new MaestriAdapter({
|
||
pipePath: pipeName,
|
||
terminalId: 'term-123',
|
||
workspaceId: 'ws-456'
|
||
});
|
||
|
||
// 1. checkAgent via Named Pipe
|
||
const checkOut = await adapter.checkAgent('AgentAlpha');
|
||
assert.equal(checkOut, 'Output do agente via pipe direto');
|
||
assert.equal(receivedRequests.length, 1);
|
||
assert.ok(receivedRequests[0].firstLine.includes('GET /check'));
|
||
assert.ok(receivedRequests[0].headers.includes('X-Agent-Name: AgentAlpha'));
|
||
assert.ok(receivedRequests[0].headers.includes('X-Terminal-ID: term-123'));
|
||
assert.ok(receivedRequests[0].headers.includes('X-Workspace-ID: ws-456'));
|
||
|
||
// 2. sendRawInput via Named Pipe
|
||
const rawRes = await adapter.sendRawInput('AgentAlpha', '\\x1b');
|
||
assert.equal(rawRes.ok, true);
|
||
assert.equal(rawRes.output, 'Raw enviado com sucesso');
|
||
assert.equal(receivedRequests.length, 2);
|
||
assert.ok(receivedRequests[1].firstLine.includes('POST /raw'));
|
||
const parsedBody = JSON.parse(receivedRequests[1].body);
|
||
assert.equal(parsedBody.to, 'AgentAlpha');
|
||
assert.equal(parsedBody.raw, '\\x1b');
|
||
|
||
// 3. Fallback transparente quando o pipe falha / está indisponível
|
||
const brokenAdapter = new MaestriAdapter({
|
||
pipePath: process.platform === 'win32' ? '\\\\.\\pipe\\non-existent-pipe-xyz' : '/tmp/non-existent.sock'
|
||
});
|
||
// Mock runMaestri no brokenAdapter para simular o CLI
|
||
brokenAdapter.runMaestri = async (args) => {
|
||
if (args[0] === 'check') return { ok: true, output: 'Fallback CLI check', error: null };
|
||
if (args[0] === 'ask') return { ok: true, output: 'Fallback CLI ask', error: null };
|
||
return { ok: false, output: '', error: 'unknown' };
|
||
};
|
||
|
||
const fallbackCheck = await brokenAdapter.checkAgent('AgentBeta');
|
||
assert.equal(fallbackCheck, 'Fallback CLI check');
|
||
|
||
const fallbackRaw = await brokenAdapter.sendRawInput('AgentBeta', '\\x03');
|
||
assert.equal(fallbackRaw.ok, true);
|
||
assert.equal(fallbackRaw.output, 'Fallback CLI ask');
|
||
} finally {
|
||
await new Promise((resolve) => server.close(resolve));
|
||
}
|
||
});
|
||
|
||
test('GatewayDaemon deve disparar checagem adaptativa imediata após CHAT_SEND e RESOLVE_PROMPT', async () => {
|
||
const mockAdapter = new MockAdapter();
|
||
let checkCalls = 0;
|
||
mockAdapter.checkAgent = async () => {
|
||
checkCalls++;
|
||
return 'Prompt do agente pronto';
|
||
};
|
||
mockAdapter.listAgents = async () => [
|
||
{ name: 'ActiveWorker', isThinking: true, hasAiActivity: true }
|
||
];
|
||
|
||
const daemon = new GatewayDaemon({
|
||
adapter: mockAdapter
|
||
});
|
||
daemon.connected = true;
|
||
daemon.ws = { send: () => {} };
|
||
|
||
// Dispara CHAT_SEND
|
||
await daemon.handleRelayMessage({
|
||
type: 'CHAT_SEND',
|
||
chatId: 'chat-adapt',
|
||
agentName: 'ActiveWorker',
|
||
message: 'Executa tarefa'
|
||
});
|
||
|
||
// Aguarda 100ms para o trigger adaptativo disparar
|
||
await new Promise(r => setTimeout(r, 120));
|
||
assert.ok(checkCalls >= 1, 'Deve ter disparado checagem imediata após envio de chat');
|
||
});
|
||
|