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 { autoWireWorkspace, CanvasAutoWiringMonitor, getWorkspaceTerminalNodes } from '../src/gateway/canvas-auto-wiring.js'; test('autoWireWorkspace deve conectar terminais soltos ao nó concentrador e persistir atomicamente', () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-autowire-')); const workspacePath = path.join(tmpDir, 'workspace.json'); const initialWorkspace = { id: 'ws-100', title: 'Workspace Teste', payload: { nodes: [ { id: 'node-concentrador', type: 'terminal', title: 'maestri-remote', content: { terminal: { _0: { name: 'maestri-remote' } } } }, { id: 'node-terminal-1', type: 'terminal', title: 'Engenheiro #1', content: { terminal: { _0: { name: 'engenheiro1' } } } }, { id: 'node-terminal-2', type: 'terminal', title: 'Engenheiro #2', content: { terminal: { _0: { name: 'engenheiro2' } } } } ], connections: [ // terminal-1 já conectado { from: 'node-concentrador', to: 'node-terminal-1' } ] } }; fs.writeFileSync(workspacePath, JSON.stringify(initialWorkspace, null, 2), 'utf8'); // Executa autoWireWorkspace const result = autoWireWorkspace(workspacePath, { concentratorName: 'maestri-remote' }); assert.equal(result.modified, true); assert.equal(result.connectedCount, 1); assert.equal(result.newConnections.length, 1); assert.equal(result.newConnections[0].from, 'node-concentrador'); assert.equal(result.newConnections[0].to, 'node-terminal-2'); assert.equal(result.newConnections[0].terminalIdA, 'node-concentrador'); assert.equal(result.newConnections[0].terminalIdB, 'node-terminal-2'); assert.ok(result.newConnections[0].id, 'Conexão deve conter id nativo'); assert.ok(result.newConnections[0].createdAt, 'Conexão deve conter createdAt'); // Relê o arquivo e valida integridade const updated = JSON.parse(fs.readFileSync(workspacePath, 'utf8')); assert.equal(updated.payload.connections.length, 2); const conn2 = updated.payload.connections.find(c => c.to === 'node-terminal-2' || c.terminalIdB === 'node-terminal-2'); assert.ok(conn2, 'Deve ter criado conexão com node-terminal-2'); assert.equal(conn2.from, 'node-concentrador'); assert.equal(conn2.terminalIdA, 'node-concentrador'); // Segunda execução imediata não deve duplicar nem modificar o arquivo const secondResult = autoWireWorkspace(workspacePath, { concentratorName: 'maestri-remote' }); assert.equal(secondResult.modified, false); assert.equal(secondResult.connectedCount, 0); // Limpeza fs.rmSync(tmpDir, { recursive: true, force: true }); }); test('autoWireWorkspace deve reconhecer conexões nativas do Maestri (terminalIdA/terminalIdB) e evitar reconexão', () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-autowire-native-')); const workspacePath = path.join(tmpDir, 'workspace.json'); const workspaceData = { payload: { nodes: [ { id: 'hub-id', content: { terminal: { _0: { name: 'maestri-remote' } } } }, { id: 'term-native-1', content: { terminal: { _0: { name: 'Assistente' } } } }, { id: 'term-native-2', content: { terminal: { _0: { name: 'SREOracleAgent' } } } } ], connections: [ { id: 'conn-native-1', terminalIdA: 'hub-id', terminalIdB: 'term-native-1', createdAt: '2026-11-21T12:00:00Z' } ] } }; fs.writeFileSync(workspacePath, JSON.stringify(workspaceData, null, 2), 'utf8'); // Deve conectar apenas term-native-2, reconhecendo que term-native-1 já está conectado nativamente const res = autoWireWorkspace(workspacePath, { concentratorName: 'maestri-remote' }); assert.equal(res.modified, true); assert.equal(res.connectedCount, 1); assert.equal(res.newConnections[0].terminalIdB, 'term-native-2'); // Re-executa: já que ambos estão conectados, não deve modificar const res2 = autoWireWorkspace(workspacePath, { concentratorName: 'maestri-remote' }); assert.equal(res2.modified, false); assert.equal(res2.connectedCount, 0); fs.rmSync(tmpDir, { recursive: true, force: true }); }); test('autoWireWorkspace deve normalizar conexões legadas para formato nativo com id e createdAt', () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-autowire-upgrade-')); const workspacePath = path.join(tmpDir, 'workspace.json'); const legacyWorkspace = { payload: { nodes: [ { id: 'hub-id', content: { terminal: { _0: { name: 'maestri-remote' } } } }, { id: 'term-1', content: { terminal: { _0: { name: 'Worker-1' } } } } ], connections: [ { from: 'hub-id', to: 'term-1' } // Legado sem id, createdAt, terminalIdA/B ] } }; fs.writeFileSync(workspacePath, JSON.stringify(legacyWorkspace, null, 2), 'utf8'); const res = autoWireWorkspace(workspacePath, { concentratorName: 'maestri-remote' }); assert.equal(res.modified, true); assert.equal(res.connectedCount, 0); // Já estava conectado assert.ok(res.upgradedCount >= 1, 'Deve ter atualizado conexão legada'); const updated = JSON.parse(fs.readFileSync(workspacePath, 'utf8')); const conn = updated.payload.connections[0]; assert.ok(conn.id); assert.equal(conn.terminalIdA, 'hub-id'); assert.equal(conn.terminalIdB, 'term-1'); assert.ok(conn.createdAt); fs.rmSync(tmpDir, { recursive: true, force: true }); }); test('getWorkspaceTerminalNodes deve extrair nós de terminais e ignorar portais/outros nós', () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-autowire-nodes-')); const workspacePath = path.join(tmpDir, 'workspace.json'); const sampleData = { payload: { nodes: [ { id: '1', content: { terminal: { _0: { name: 'TermA' } } } }, { id: '2', content: { portal: { url: 'http://localhost' } } }, { id: '3', type: 'terminal', title: 'TermB' }, { id: '4', content: { note: { text: 'Ola' } } } ] } }; fs.writeFileSync(workspacePath, JSON.stringify(sampleData, null, 2), 'utf8'); const terminals = getWorkspaceTerminalNodes(workspacePath); assert.equal(terminals.length, 2); assert.equal(terminals[0].name, 'TermA'); assert.equal(terminals[1].name, 'TermB'); fs.rmSync(tmpDir, { recursive: true, force: true }); }); test('CanvasAutoWiringMonitor deve observar alterações no workspace.json e acionar auto-wiring com debounce', async () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-autowire-mon-')); const workspacePath = path.join(tmpDir, 'workspace.json'); const workspaceData = { id: 'ws-monitor', payload: { nodes: [ { id: 'hub', type: 'terminal', title: 'maestri-remote', content: { terminal: { _0: { name: 'maestri-remote' } } } } ], connections: [] } }; fs.writeFileSync(workspacePath, JSON.stringify(workspaceData, null, 2), 'utf8'); let wiringEvents = 0; const monitor = new CanvasAutoWiringMonitor({ workspaceFilePath: workspacePath, concentratorName: 'maestri-remote', debounceMs: 50, onWired: (res) => { if (res.modified) wiringEvents++; } }); monitor.start(); // Adiciona novo nó terminal workspaceData.payload.nodes.push({ id: 'novo-agente', type: 'terminal', title: 'Agente Novo', content: { terminal: { _0: { name: 'agente_novo' } } } }); fs.writeFileSync(workspacePath, JSON.stringify(workspaceData, null, 2), 'utf8'); // Aguarda debounce e processamento await new Promise(r => setTimeout(r, 150)); monitor.stop(); assert.ok(wiringEvents >= 1, 'Deve ter acionado evento de wiring'); const finalJson = JSON.parse(fs.readFileSync(workspacePath, 'utf8')); const conn = finalJson.payload.connections.find(c => c.to === 'novo-agente' || c.terminalIdB === 'novo-agente'); assert.ok(conn, 'Conexão para novo-agente deve existir no disco'); // Limpeza fs.rmSync(tmpDir, { recursive: true, force: true }); });