1435 lines
53 KiB
JavaScript
1435 lines
53 KiB
JavaScript
import test from 'node:test';
|
||
import assert from 'node:assert/strict';
|
||
import fs from 'node:fs';
|
||
import path from 'node:path';
|
||
import os from 'node:os';
|
||
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 anexo de vídeo (.mp4 e .webm) com extensão sanitizada e injetar no prompt do askAgent', async () => {
|
||
const fs = await import('node:fs');
|
||
const mockAdapter = new MockAdapter();
|
||
const daemon = new GatewayDaemon({
|
||
adapter: mockAdapter
|
||
});
|
||
|
||
const videoBinary = Buffer.from('fake mp4 video bytes header');
|
||
const sampleBase64 = videoBinary.toString('base64');
|
||
let savedFile = null;
|
||
|
||
await daemon.handleRelayMessage({
|
||
type: 'CHAT_SEND',
|
||
chatId: 'chat-video-1',
|
||
agentName: 'TestAgent',
|
||
message: 'Assista a este vídeo do bug em execução',
|
||
attachment: {
|
||
name: 'bug_animacao:teste?.mp4',
|
||
mimeType: 'video/mp4',
|
||
size: videoBinary.length,
|
||
dataBase64: sampleBase64
|
||
}
|
||
});
|
||
|
||
assert.equal(mockAdapter.responses.length, 1);
|
||
assert.equal(mockAdapter.responses[0].agentName, 'TestAgent');
|
||
assert.ok(mockAdapter.responses[0].message.includes('[Anexo recebido do operador:'));
|
||
assert.ok(mockAdapter.responses[0].message.includes('Assista a este vídeo do bug em execução'));
|
||
|
||
const match = mockAdapter.responses[0].message.match(/\[Anexo recebido do operador: (.*?)\]/);
|
||
assert.ok(match, 'Deve ter injetado o path do vídeo');
|
||
savedFile = match[1];
|
||
assert.ok(savedFile.endsWith('.mp4'), 'Deve terminar com extensão .mp4');
|
||
// Confere só o nome do arquivo: no Windows o caminho completo traz o ':' da unidade (D:\\...)
|
||
assert.ok(!path.basename(savedFile).includes(':') && !path.basename(savedFile).includes('?'), 'Caracteres perigosos devem estar sanitizados');
|
||
assert.ok(fs.existsSync(savedFile), 'Arquivo de vídeo deve existir no diretório de uploads');
|
||
assert.deepEqual(fs.readFileSync(savedFile), videoBinary);
|
||
|
||
// Limpeza
|
||
if (savedFile && fs.existsSync(savedFile)) {
|
||
fs.unlinkSync(savedFile);
|
||
}
|
||
});
|
||
|
||
test('GatewayDaemon deve inferir extensão de vídeo a partir do mimeType quando nome vier sem extensão', async () => {
|
||
const fs = await import('node:fs');
|
||
const mockAdapter = new MockAdapter();
|
||
const daemon = new GatewayDaemon({
|
||
adapter: mockAdapter
|
||
});
|
||
|
||
const videoBinary = Buffer.from('webm binary stream');
|
||
let savedFile = null;
|
||
|
||
await daemon.handleRelayMessage({
|
||
type: 'CHAT_SEND',
|
||
chatId: 'chat-video-no-ext',
|
||
agentName: 'TestAgent',
|
||
message: 'Vídeo gravado sem extensão',
|
||
attachment: {
|
||
name: 'video_gravado_blob',
|
||
mimeType: 'video/webm',
|
||
size: videoBinary.length,
|
||
dataBase64: videoBinary.toString('base64')
|
||
}
|
||
});
|
||
|
||
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(savedFile.endsWith('.webm'), 'Deve ter inferido extensão .webm');
|
||
assert.ok(fs.existsSync(savedFile), 'Arquivo deve existir');
|
||
|
||
// 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({ syncCanvasTerminals: false });
|
||
|
||
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('MaestriAdapter.listAgents deve listar só agentes diretos (- name:), ignorando transitivos (⎿ agent:), notas e portais', 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: "direto-1"\n ⎿ agent: "transitivo-1"\n ⎿ agent: "transitivo-2"\n - name: 'direto-2'\n - name: direto-sem-aspas\n\nConnected notes:\n - name: "Nota Solta"\n\nConnected portals:\n - name: "Portal Web"`
|
||
};
|
||
}
|
||
if (args[0] === 'check') {
|
||
return { ok: true, output: 'shell prompt > ' };
|
||
}
|
||
return { ok: true, output: '' };
|
||
};
|
||
|
||
const agents = await adapter.listAgents();
|
||
const names = agents.map(a => a.name);
|
||
|
||
assert.ok(names.includes('maestri-remote'));
|
||
assert.ok(names.includes('direto-1'));
|
||
assert.ok(!names.includes('transitivo-1'));
|
||
assert.ok(!names.includes('transitivo-2'));
|
||
assert.ok(names.includes('direto-2'));
|
||
assert.ok(names.includes('direto-sem-aspas'));
|
||
|
||
// Não deve conter notas nem portais
|
||
assert.ok(!names.includes('Nota Solta'));
|
||
assert.ok(!names.includes('Portal Web'));
|
||
});
|
||
|
||
function writeMixedWorkspace(prefix) {
|
||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
|
||
const workspacePath = path.join(tmpDir, 'workspace.json');
|
||
const wsData = {
|
||
payload: {
|
||
nodes: [
|
||
{ id: 'hub-1', type: 'terminal', title: 'maestri-remote', terminal: { _0: { name: 'maestri-remote' } } },
|
||
{ id: 'cabled-1', terminal: { _0: { name: 'CabledAgent1', command: 'bash' } } },
|
||
{ id: 'cabled-2', terminal: { _0: { name: 'CabledAgent2', command: 'cmd' } } },
|
||
{ id: 'loose-1', terminal: { _0: { name: 'LooseAiAgent', command: 'agy', agentType: 'antigravity_cli' } } },
|
||
{ id: 'loose-2', content: { terminal: { _0: { name: 'LooseClaude', command: 'claude', agentType: 'claude_code' } } } },
|
||
{ id: 'loose-3', terminal: { _0: { name: 'LooseShell', command: 'pwsh' } } }
|
||
]
|
||
}
|
||
};
|
||
fs.writeFileSync(workspacePath, JSON.stringify(wsData), 'utf8');
|
||
return { tmpDir, workspacePath };
|
||
}
|
||
|
||
function mockWiredSubsetCli(adapter) {
|
||
adapter.runMaestri = async (args) => {
|
||
if (args[0] === 'list') {
|
||
return {
|
||
ok: true,
|
||
output: `You:\n - name: "maestri-remote"\n\nConnected agents:\n - name: "CabledAgent1"\n - name: "CabledAgent2"`
|
||
};
|
||
}
|
||
if (args[0] === 'check') {
|
||
const target = args[1];
|
||
if (target === 'CabledAgent1') return { ok: true, output: 'bash$ ' };
|
||
if (target === 'CabledAgent2') return { ok: true, output: 'C:\\> ' };
|
||
return { ok: false, output: '', error: `No connection to '${target}'` };
|
||
}
|
||
return { ok: true, output: '' };
|
||
};
|
||
}
|
||
|
||
test('MaestriAdapter.listAgents por padrão lista só terminais com cabo (maestri list) e ignora soltos do workspace.json', async () => {
|
||
const { tmpDir, workspacePath } = writeMixedWorkspace('maestri-adapter-wired-');
|
||
const adapter = new MaestriAdapter({ workspaceFilePath: workspacePath, terminalId: 'hub-1' });
|
||
mockWiredSubsetCli(adapter);
|
||
|
||
const agents = await adapter.listAgents();
|
||
const names = agents.map(a => a.name).sort();
|
||
assert.deepEqual(names, ['CabledAgent1', 'CabledAgent2', 'maestri-remote']);
|
||
assert.ok(!agents.some(a => a.fromCanvas));
|
||
|
||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||
});
|
||
|
||
test('MaestriAdapter.listAgents por padrão não completa com workspace.json quando maestri list falha', async () => {
|
||
const { tmpDir, workspacePath } = writeMixedWorkspace('maestri-adapter-fail-');
|
||
const adapter = new MaestriAdapter({ workspaceFilePath: workspacePath });
|
||
adapter.runMaestri = async () => ({ ok: false, output: '', error: 'Pipe closed' });
|
||
adapter.checkAgent = async () => 'shell prompt';
|
||
|
||
const agents = await adapter.listAgents();
|
||
assert.equal(agents.length, 0);
|
||
|
||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||
});
|
||
|
||
test('GatewayDaemon não liga o auto-wiring do canvas por padrão', () => {
|
||
const daemon = new GatewayDaemon({ adapter: new MockAdapter() });
|
||
assert.equal(daemon.autoWiringMonitor, null);
|
||
assert.doesNotThrow(() => daemon.stop?.());
|
||
});
|
||
|
||
test('GatewayDaemon liga o auto-wiring do canvas só com autoWireCanvas: true', () => {
|
||
const daemon = new GatewayDaemon({ adapter: new MockAdapter(), autoWireCanvas: true });
|
||
assert.ok(daemon.autoWiringMonitor);
|
||
assert.equal(typeof daemon.autoWiringMonitor.start, 'function');
|
||
});
|
||
|
||
test('MaestriAdapter.listAgents com syncCanvasTerminals: true completa com workspace.json caso maestri list falhe', async () => {
|
||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-adapter-ws-'));
|
||
const workspacePath = path.join(tmpDir, 'workspace.json');
|
||
|
||
const wsData = {
|
||
payload: {
|
||
nodes: [
|
||
{ id: '1', content: { terminal: { _0: { name: 'FallbackWorker1' } } } },
|
||
{ id: '2', content: { terminal: { _0: { name: 'FallbackWorker2' } } } }
|
||
]
|
||
}
|
||
};
|
||
fs.writeFileSync(workspacePath, JSON.stringify(wsData), 'utf8');
|
||
|
||
const adapter = new MaestriAdapter({ workspaceFilePath: workspacePath, syncCanvasTerminals: true });
|
||
adapter.runMaestri = async () => ({ ok: false, output: '', error: 'Pipe closed' });
|
||
adapter.checkAgent = async () => 'shell prompt';
|
||
|
||
const agents = await adapter.listAgents();
|
||
assert.equal(agents.length, 2);
|
||
assert.ok(agents.some(a => a.name === 'FallbackWorker1'));
|
||
assert.ok(agents.some(a => a.name === 'FallbackWorker2'));
|
||
|
||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||
});
|
||
|
||
test('MaestriAdapter.listAgents com syncCanvasTerminals: true mescla todos os terminais do canvas mesmo quando maestri list retornar apenas subconjunto cabeado', async () => {
|
||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-adapter-merge-'));
|
||
const workspacePath = path.join(tmpDir, 'workspace.json');
|
||
|
||
const wsData = {
|
||
payload: {
|
||
nodes: [
|
||
{ id: 'hub-1', type: 'terminal', title: 'maestri-remote', terminal: { _0: { name: 'maestri-remote' } } },
|
||
{ id: 'cabled-1', terminal: { _0: { name: 'CabledAgent1', command: 'bash' } } },
|
||
{ id: 'cabled-2', terminal: { _0: { name: 'CabledAgent2', command: 'cmd' } } },
|
||
{ id: 'loose-1', terminal: { _0: { name: 'LooseAiAgent', command: 'agy', agentType: 'antigravity_cli' } } },
|
||
{ id: 'loose-2', content: { terminal: { _0: { name: 'LooseClaude', command: 'claude', agentType: 'claude_code' } } } },
|
||
{ id: 'loose-3', terminal: { _0: { name: 'LooseShell', command: 'pwsh' } } }
|
||
]
|
||
}
|
||
};
|
||
fs.writeFileSync(workspacePath, JSON.stringify(wsData), 'utf8');
|
||
|
||
const adapter = new MaestriAdapter({
|
||
workspaceFilePath: workspacePath,
|
||
terminalId: 'hub-1',
|
||
syncCanvasTerminals: true
|
||
});
|
||
|
||
// maestri list só conhece You + os 2 agentes cabeados (3 no total)
|
||
adapter.runMaestri = async (args) => {
|
||
if (args[0] === 'list') {
|
||
return {
|
||
ok: true,
|
||
output: `You:\n - name: "maestri-remote"\n\nConnected agents:\n - name: "CabledAgent1"\n - name: "CabledAgent2"`
|
||
};
|
||
}
|
||
if (args[0] === 'check') {
|
||
const target = args[1];
|
||
if (target === 'CabledAgent1') return { ok: true, output: 'bash$ ' };
|
||
if (target === 'CabledAgent2') return { ok: true, output: 'C:\\> ' };
|
||
// Para nós soltos, maestri check falha com 'No connection'
|
||
return { ok: false, output: '', error: `No connection to '${target}'` };
|
||
}
|
||
return { ok: true, output: '' };
|
||
};
|
||
|
||
const agents = await adapter.listAgents();
|
||
|
||
// Deve listar todos os 6 terminais da partitura/canvas
|
||
assert.equal(agents.length, 6);
|
||
|
||
const hub = agents.find(a => a.name === 'maestri-remote');
|
||
assert.ok(hub);
|
||
assert.equal(hub.isSelf, true);
|
||
|
||
const looseAi = agents.find(a => a.name === 'LooseAiAgent');
|
||
assert.ok(looseAi);
|
||
assert.equal(looseAi.isSelf, false);
|
||
assert.equal(looseAi.hasAiActivity, true);
|
||
assert.equal(looseAi.aiType, 'agy');
|
||
assert.equal(looseAi.status, 'active');
|
||
|
||
const looseClaude = agents.find(a => a.name === 'LooseClaude');
|
||
assert.ok(looseClaude);
|
||
assert.equal(looseClaude.isSelf, false);
|
||
assert.equal(looseClaude.hasAiActivity, true);
|
||
assert.equal(looseClaude.aiType, 'claude');
|
||
assert.equal(looseClaude.status, 'active');
|
||
|
||
const looseShell = agents.find(a => a.name === 'LooseShell');
|
||
assert.ok(looseShell);
|
||
assert.equal(looseShell.isSelf, false);
|
||
assert.equal(looseShell.hasAiActivity, false);
|
||
assert.equal(looseShell.status, 'idle_shell');
|
||
|
||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||
});
|
||
|
||
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: 'kilo', hasAiActivity: true }),
|
||
{ preset: null, command: 'kilo', exitSequence: '/exit\\n' }
|
||
);
|
||
// Kiro não vira kilo nem opencode por texto de tela (são ferramentas diferentes)
|
||
assert.deepEqual(
|
||
resolveTerminalLaunchSpec('△ Permission required\nctrl+f fullscreen opencode kilo', { aiType: 'kiro', hasAiActivity: true }),
|
||
{ preset: null, command: 'kiro-cli', 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, 'interrupt_ai');
|
||
|
||
const forcedAllowSelfFalse = await adapter.restartAgentTerminal('maestri-remote-self', { isSelf: false });
|
||
assert.equal(forcedAllowSelfFalse.ok, true);
|
||
assert.equal(forcedAllowSelfFalse.method, 'interrupt_ai');
|
||
});
|
||
|
||
test('MaestriAdapter.restartAgentTerminal deve encerrar a IA com Ctrl+C e deixar o terminal no shell, sem recruit nem relançar', async () => {
|
||
const rawInputs = [];
|
||
const calls = [];
|
||
const adapter = new MaestriAdapter({ restartDelayMs: 0 });
|
||
let checkSeq = 0;
|
||
const setup = (checks) => {
|
||
rawInputs.length = 0;
|
||
checkSeq = 0;
|
||
adapter.runMaestri = async (args) => {
|
||
calls.push(args);
|
||
if (args[0] === 'ask' && args[2] === '--raw') {
|
||
rawInputs.push(args[3]);
|
||
return { ok: true, output: '' };
|
||
}
|
||
if (args[0] === 'check') {
|
||
const out = checks[Math.min(checkSeq, checks.length - 1)];
|
||
checkSeq++;
|
||
return { ok: true, output: out };
|
||
}
|
||
return { ok: false, output: '' };
|
||
};
|
||
};
|
||
const AI = 'Claude Code v2.1\nshift+tab to cycle';
|
||
const SH = 'PS C:\\Users\\dev> ';
|
||
|
||
// 1. Ctrl+C basta
|
||
setup([AI, SH]);
|
||
const r1 = await adapter.restartAgentTerminal('Claude');
|
||
assert.equal(r1.ok, true);
|
||
assert.equal(r1.method, 'interrupt_ai');
|
||
assert.deepEqual(rawInputs, ['\\x03']);
|
||
assert.equal(calls.some((c) => c[0] === 'recruit'), false, 'Nunca deve acionar recruit');
|
||
|
||
// 2. Ctrl+C -> /exit
|
||
setup([AI, AI, SH]);
|
||
const r2 = await adapter.restartAgentTerminal('Claude');
|
||
assert.equal(r2.ok, true);
|
||
assert.deepEqual(rawInputs, ['\\x03', '/exit\\n']);
|
||
|
||
// 3. Ctrl+C -> /exit -> Ctrl+D
|
||
setup([AI, AI, AI, SH]);
|
||
const r3 = await adapter.restartAgentTerminal('Claude');
|
||
assert.equal(r3.ok, true);
|
||
assert.deepEqual(rawInputs, ['\\x03', '/exit\\n', '\\x04']);
|
||
|
||
// 4. Shell puro: só Ctrl+C, nenhum \n nem relançamento
|
||
setup([SH]);
|
||
const r4 = await adapter.restartAgentTerminal('TermShell');
|
||
assert.equal(r4.ok, true);
|
||
assert.deepEqual(rawInputs, ['\\x03']);
|
||
|
||
// 5. IA que não fecha: ok false
|
||
setup([AI]);
|
||
const r5 = await adapter.restartAgentTerminal('Claude');
|
||
assert.equal(r5.ok, false);
|
||
assert.equal(r5.method, 'interrupt_ai');
|
||
assert.deepEqual(rawInputs, ['\\x03', '/exit\\n', '\\x04']);
|
||
assert.match(r5.error, /Não foi possível encerrar/);
|
||
|
||
// 6. Falha ao enviar Ctrl+C inicial preserva a saída anterior
|
||
adapter.runMaestri = async (args) => {
|
||
if (args[0] === 'check') return { ok: true, output: 'PS D:\\proj> travado' };
|
||
if (args[0] === 'ask' && args[2] === '--raw') return { ok: false, output: '', error: 'IPC timeout' };
|
||
return { ok: false, output: '' };
|
||
};
|
||
const r6 = await adapter.restartAgentTerminal('TermTravado');
|
||
assert.equal(r6.ok, false);
|
||
assert.equal(r6.output, 'PS D:\\proj> travado');
|
||
assert.match(r6.error, /IPC timeout/);
|
||
|
||
// 7. Falha na sequência de saída ou no EOF retorna ok false
|
||
for (const [failingSeq, expectedCount] of [['/exit\\n', 2], ['\\x04', 3]]) {
|
||
const seqLog = [];
|
||
adapter.runMaestri = async (args) => {
|
||
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') return { ok: true, output: AI };
|
||
return { ok: false, output: '' };
|
||
};
|
||
const rf = await adapter.restartAgentTerminal('Claude');
|
||
assert.equal(rf.ok, false);
|
||
assert.equal(seqLog.length, expectedCount);
|
||
}
|
||
|
||
// 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: 'kilo' }]
|
||
};
|
||
|
||
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' },
|
||
{ agentName: 'KiloAgent', seq: '\\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
|
||
// Raw nao passa pelo pipe (ele entrega e responde EPIPE; o fallback repetia a tecla): vai so pelo CLI
|
||
const cliArgs = [];
|
||
adapter.runMaestri = async (args) => { cliArgs.push(args); return { ok: true, output: 'Raw via CLI', error: null }; };
|
||
const rawRes = await adapter.sendRawInput('AgentAlpha', '\\x1b');
|
||
assert.equal(rawRes.ok, true);
|
||
assert.equal(rawRes.output, 'Raw via CLI');
|
||
assert.equal(receivedRequests.length, 1, 'nenhum POST /raw no pipe');
|
||
assert.deepEqual(cliArgs, [['ask', 'AgentAlpha', '--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');
|
||
});
|
||
|