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 { fileURLToPath } from 'node:url'; import { detectTerminalActivity, detectInteractiveMenu } from '../src/utils/activity-detector.js'; import { GatewayDaemon } from '../src/gateway/daemon.js'; import { MaestriAdapter, resolveTerminalLaunchSpec } from '../src/gateway/maestri-adapter.js'; // Fixtures reais colhidas do kilo 7.8.32 e do kiro-cli 3.5.0 em terminais Maestri (change maestri-remote-kilo-code-homologation). const FIXTURES = path.join(path.dirname(fileURLToPath(import.meta.url)), 'fixtures'); const kilo = (name) => fs.readFileSync(path.join(FIXTURES, 'kilo', `${name}.txt`), 'utf8'); const kiro = (name) => fs.readFileSync(path.join(FIXTURES, 'kiro', `${name}.txt`), 'utf8'); test('Kilo CLI - detector reconhece o TUI ocioso como aiType kilo (não agy, apesar do modelo Gemini)', () => { for (const name of ['idle', 'answered', 'ask-result']) { const act = detectTerminalActivity(kilo(name)); assert.equal(act.hasAiActivity, true, name); assert.equal(act.aiType, 'kilo', name); assert.equal(act.isThinking, false, name); assert.equal(act.isPaused, false, name); assert.equal(act.hasInteractiveMenu, false, name); assert.equal(act.details, 'Kilo CLI pronto', name); } }); test('Kilo CLI - detector marca pensando e execução de ferramenta pelo "esc interrupt" no rodapé', () => { for (const name of ['thinking', 'tool-exec']) { const act = detectTerminalActivity(kilo(name)); assert.equal(act.aiType, 'kilo', name); assert.equal(act.isThinking, true, name); assert.equal(act.details, 'Kilo CLI ativo', name); } }); test('Kilo CLI - popup de comandos digitado (/models, /effort) segue como Kilo pronto, sem menu', () => { for (const name of ['models-popup', 'effort-absent']) { const act = detectTerminalActivity(kilo(name)); assert.equal(act.aiType, 'kilo', name); assert.equal(act.isThinking, false, name); assert.equal(act.hasInteractiveMenu, false, name); } }); test('Kilo CLI - Permission required (shell e diretório externo) vira menu horizontal aiType kilo', () => { for (const name of ['permission-bash', 'permission-external']) { const act = detectTerminalActivity(kilo(name)); assert.equal(act.aiType, 'kilo', name); assert.equal(act.hasInteractiveMenu, true, name); assert.equal(act.isThinking, false, name); assert.equal(act.interactiveMenu.axis, 'horizontal', name); assert.deepEqual(act.interactiveMenu.options.map(o => o.label), ['Allow once', 'Allow always', 'Reject'], name); assert.match(act.interactiveMenu.menuTitle, /Permission required/, name); } }); test('Kilo CLI - confirmação "Always allow" tem Confirm e Cancel', () => { const act = detectTerminalActivity(kilo('permission-always-confirm')); assert.equal(act.aiType, 'kilo'); assert.equal(act.hasInteractiveMenu, true); assert.deepEqual(act.interactiveMenu.options.map(o => o.label), ['Confirm', 'Cancel']); }); test('Kilo CLI - seletor /models (Select model) vira menu vertical aiType kilo', () => { const text = kilo('models'); const act = detectTerminalActivity(text); assert.equal(act.aiType, 'kilo'); assert.equal(act.hasInteractiveMenu, true); const menu = detectInteractiveMenu(text); assert.equal(menu.axis, 'vertical'); assert.equal(menu.menuTitle, 'Select model'); const labels = menu.options.map(o => o.label); assert.ok(labels.includes('Anthropic: Claude Opus 5.5 Kilo Gateway')); assert.ok(labels.includes('OpenAI: GPT-6.2 Sol (new)')); }); test('Kilo CLI - saída por /exit devolve o prompt do shell (não é agente de IA)', () => { const act = detectTerminalActivity(kilo('exit-after')); assert.equal(act.hasAiActivity, false); assert.equal(act.aiType, null); assert.equal(act.shellType, 'powershell'); }); test('Kilo CLI - rate limit/cota temporario nunca vira pausa (sem estado de pausa no Kilo)', () => { for (const msg of ['rate limit reached', 'quota exceeded']) { const act = detectTerminalActivity(kilo('idle') + '\n' + msg + '\n ctrl+p commands'); assert.equal(act.aiType, 'kilo', msg); assert.equal(act.isPaused, false, msg); assert.equal(act.pauseReason, null, msg); assert.equal(act.pauseResetTime, null, msg); assert.equal(act.details, 'Kilo CLI pronto', msg); } // Em execucao (esc interrupt no rodape) com rate limit: segue ativo/pensando, nao pausado const busy = detectTerminalActivity(kilo('thinking') + '\nrate limit reached\n esc interrupt'); assert.equal(busy.aiType, 'kilo'); assert.equal(busy.isPaused, false); assert.equal(busy.isThinking, true); assert.equal(busy.details, 'Kilo CLI ativo'); }); test('Claude/Antigravity/Kiro - regressao: rate limit e cota continuam marcando pausa', () => { const screens = { claude: 'Claude Code v2\n> trabalhando\nrate limit reached', agy: 'Antigravity CLI\nGemini 3.1 Pro\nquota exceeded', kiro: kiro('idle') + '\nrate limit reached' }; for (const [aiType, screen] of Object.entries(screens)) { const act = detectTerminalActivity(screen); assert.equal(act.aiType, aiType, aiType); assert.equal(act.isPaused, true, aiType); assert.equal(act.pauseReason, 'usage_limit', aiType); } }); test('Kiro CLI - regressão: tela real do kiro-cli segue aiType kiro e não vira kilo', () => { const act = detectTerminalActivity(kiro('idle')); assert.equal(act.hasAiActivity, true); assert.equal(act.aiType, 'kiro'); assert.equal(act.isThinking, false); assert.equal(act.details, 'Kiro CLI pronto'); assert.doesNotMatch(kiro('idle'), /Kilo Gateway|ctrl\+x m|at top for controls/i, 'assinaturas do Kilo não aparecem no Kiro CLI'); }); test('resolveTerminalLaunchSpec - kilo e kiro-cli têm comando próprio e saída por /exit', () => { assert.deepEqual( resolveTerminalLaunchSpec(kilo('idle'), { aiType: 'kilo', hasAiActivity: true }), { preset: null, command: 'kilo', exitSequence: '/exit\\n' } ); // Kiro nunca vira kilo/opencode por texto de tela assert.deepEqual( resolveTerminalLaunchSpec('Permission required\nctrl+f fullscreen opencode kilo', { aiType: 'kiro', hasAiActivity: true }), { preset: null, command: 'kiro-cli', exitSequence: '/exit\\n' } ); }); test('MaestriAdapter.listAgents - metadados do canvas mapeiam kilo, kilo e kiro-cli', async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-kilo-ws-')); const workspacePath = path.join(tmpDir, 'workspace.json'); const term = (name, command) => ({ id: name, content: { terminal: { _0: { name, command, agentType: 'custom' } } } }); fs.writeFileSync(workspacePath, JSON.stringify({ payload: { nodes: [ term('k1', 'kilo'), term('k2', 'kilo --continue'), term('r1', 'kiro-cli'), term('s1', 'node app.js') ] } }), 'utf8'); const adapter = new MaestriAdapter({ workspaceFilePath: workspacePath, syncCanvasTerminals: true }); adapter.runMaestri = async (args) => { if (args[0] === 'list') return { ok: true, output: 'You:\n - name: "maestri-remote"\n\nConnected agents:\n' }; return { ok: false, output: '', error: 'No connection' }; }; const agents = await adapter.listAgents(); const byName = Object.fromEntries(agents.map(a => [a.name, a])); assert.equal(byName.k1.aiType, 'kilo'); assert.equal(byName.k2.aiType, 'kilo'); assert.equal(byName.r1.aiType, 'kiro'); assert.equal(byName.s1.hasAiActivity, false); fs.rmSync(tmpDir, { recursive: true, force: true }); }); function makeDaemon(agentList) { const sent = []; const rawCalls = []; let askCalled = false; const adapter = { wait: async () => {}, sendRawInput: async (agentName, seq) => { rawCalls.push({ agentName, seq }); return { ok: true, output: 'raw_ok' }; }, askAgent: async () => { askCalled = true; return { ok: true, output: 'x' }; }, checkAgent: async () => kilo('idle'), listAgents: async () => agentList }; const daemon = new GatewayDaemon({ adapter }); daemon.ws = { send: (s) => sent.push(JSON.parse(s)) }; daemon.connected = true; return { daemon, sent, rawCalls, asked: () => askCalled }; } test('GatewayDaemon - /effort no Kilo não envia nada ao terminal e informa que o comando não existe', async () => { const { daemon, sent, rawCalls, asked } = makeDaemon([{ name: 'KiloAgent', aiType: 'kilo' }]); await daemon.syncAgents(); sent.length = 0; await daemon.handleRelayMessage({ type: 'CHAT_SEND', chatId: 'c1', agentName: 'KiloAgent', message: '/effort high' }); assert.deepEqual(rawCalls, []); assert.equal(asked(), false); const resp = sent.find(m => m.type === 'CHAT_RESPONSE'); assert.ok(resp); assert.equal(resp.ok, false); assert.match(resp.reply, /Kilo CLI não tem o comando \/effort/); }); test('GatewayDaemon - /models no Kilo envia o texto e o Enter em escritas separadas, com filtro opcional', async () => { const { daemon, rawCalls } = makeDaemon([{ name: 'KiloAgent', aiType: 'kilo' }]); await daemon.syncAgents(); await daemon.handleRelayMessage({ type: 'CHAT_SEND', chatId: 'c2', agentName: 'KiloAgent', message: '/models' }); assert.deepEqual(rawCalls, [ { agentName: 'KiloAgent', seq: '\\x15/model' }, { agentName: 'KiloAgent', seq: '\\n' } ]); rawCalls.length = 0; await daemon.handleRelayMessage({ type: 'CHAT_SEND', chatId: 'c3', agentName: 'KiloAgent', message: '/models claude' }); assert.deepEqual(rawCalls, [ { agentName: 'KiloAgent', seq: '\\x15/model' }, { agentName: 'KiloAgent', seq: '\\n' }, { agentName: 'KiloAgent', seq: 'claude' } ]); }); test('GatewayDaemon - /effort no Kiro CLI segue enviando o comando (regressão)', async () => { const { daemon, rawCalls } = makeDaemon([{ name: 'KiroAgent', aiType: 'kiro' }]); daemon.adapter.checkAgent = async () => kiro('idle'); await daemon.syncAgents(); await daemon.handleRelayMessage({ type: 'CHAT_SEND', chatId: 'c4', agentName: 'KiroAgent', message: '/effort' }); assert.deepEqual(rawCalls, [{ agentName: 'KiroAgent', seq: '\\x15/effort\\n' }]); }); // Task 8: tocar em "Allow always" escolhia Reject. O pipe do Maestri entrega a tecla e responde EPIPE (igual a falha), // e o adapter caia no CLI e enviava a mesma tecla de novo (seta+seta, Enter+Enter). Raw agora so vai pelo CLI. test('MaestriAdapter.sendRawInput - mesmo com pipe configurado, cada tecla vai uma unica vez pelo CLI (sem pipe, sem repeticao)', async () => { const adapter = new MaestriAdapter({ pipePath: 'pipe-falso' }); const pipeCalls = []; const cliCalls = []; adapter.requestPipe = async (method, route) => { pipeCalls.push({ method, route }); return { ok: false, error: 'read EPIPE', status: 500 }; }; adapter.runMaestri = async (args) => { cliCalls.push(args); return { ok: true, output: 'tela', error: null }; }; for (const key of ['\\e[C', '\\n']) { const res = await adapter.sendRawInput('Kilo', key); assert.equal(res.ok, true); assert.equal(res.output, 'tela'); } assert.equal(pipeCalls.length, 0, 'raw nao pode passar pelo pipe'); assert.deepEqual(cliCalls, [['ask', 'Kilo', '--raw', '\\e[C'], ['ask', 'Kilo', '--raw', '\\n']]); }); test('Kilo CLI - Permission required: tela real sem ANSI parte de Allow once e o destaque ANSI em cada posicao vira selectedIndex 0, 1 e 2', () => { const real = detectInteractiveMenu(kilo('permission-external')); assert.equal(real.axis, 'horizontal'); assert.equal(real.selectedIndex, 0); assert.deepEqual(real.options.map(o => o.selected), [true, false, false]); const labels = ['Allow once', 'Allow always', 'Reject']; labels.forEach((_, pos) => { const bar = labels.map((l, i) => (i === pos ? `\x1B[48;5;214;30m${l}\x1B[0m` : l)).join(' '); const screen = `\u25B3 Permission required\n \u2190 Access external directory \n\n${bar} ctrl+f fullscreen \u21C6 select enter confirm`; const menu = detectInteractiveMenu(screen); assert.equal(menu.selectedIndex, pos, labels[pos]); assert.deepEqual(menu.options.map(o => o.label), labels); }); }); test('Kilo CLI - "Reject permission" (pedido de feedback apos Reject) nao e menu e nao fica pendurado como permissao', () => { const act = detectTerminalActivity(kilo('permission-reject-feedback')); assert.equal(act.hasInteractiveMenu, false); });