fix(gateway): corrigir loop de auto-wiring no canvas e sincronizacao de terminais
- Ajusta autoWireWorkspace para utilizar conexoes no formato nativo do Maestri (terminalIdA, terminalIdB, id, createdAt) - Identifica conexoes existentes em ambos os sentidos e formatos, prevenindo loops de auto-wiring - Habilita suporte a multiplos concentradores (maestri-remote e maestri-remote-channel) - Enriquece listAgents para capturar agentes transitivos e sincronizar todos os terminais do canvas - Adiciona testes cobrindo auto-wiring nativo, atualizacao de formato legado e deteccao de agentes
This commit is contained in:
parent
0bdf47a28f
commit
8555935403
2
.gitignore
vendored
2
.gitignore
vendored
@ -33,3 +33,5 @@ android/.cxx/
|
|||||||
.maestri-remote-session.json
|
.maestri-remote-session.json
|
||||||
.maestri-agent-state.json
|
.maestri-agent-state.json
|
||||||
.maestri-remote/
|
.maestri-remote/
|
||||||
|
.tmp-*
|
||||||
|
*.tmp*
|
||||||
|
|||||||
Binary file not shown.
@ -1,6 +1,7 @@
|
|||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import os from 'node:os';
|
import os from 'node:os';
|
||||||
|
import crypto from 'node:crypto';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve o caminho do workspace.json padrão do Maestri se não fornecido explicitamente.
|
* Resolve o caminho do workspace.json padrão do Maestri se não fornecido explicitamente.
|
||||||
@ -33,6 +34,46 @@ export function resolveWorkspaceFilePath(explicitPath = null, workspaceId = null
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extrai todos os nós de terminais definidos no workspace.json.
|
||||||
|
*/
|
||||||
|
export function getWorkspaceTerminalNodes(workspacePath) {
|
||||||
|
if (!workspacePath || !fs.existsSync(workspacePath)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const raw = fs.readFileSync(workspacePath, 'utf8');
|
||||||
|
const data = JSON.parse(raw);
|
||||||
|
const payload = data.payload || data;
|
||||||
|
if (!payload || !Array.isArray(payload.nodes)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const terminals = [];
|
||||||
|
for (const node of payload.nodes) {
|
||||||
|
if (!node) continue;
|
||||||
|
const isTerminal = node.type === 'terminal' || Boolean(node.content?.terminal) || Boolean(node.terminal);
|
||||||
|
if (!isTerminal) continue;
|
||||||
|
const name = (
|
||||||
|
node.content?.terminal?._0?.name ||
|
||||||
|
node.content?.terminal?.name ||
|
||||||
|
node.terminal?.name ||
|
||||||
|
node.title ||
|
||||||
|
node.name ||
|
||||||
|
''
|
||||||
|
).trim();
|
||||||
|
if (name) {
|
||||||
|
terminals.push({
|
||||||
|
id: node.id,
|
||||||
|
name
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return terminals;
|
||||||
|
} catch (err) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Inspeciona o workspace.json e conecta automaticamente terminais soltos ao nó concentrador.
|
* Inspeciona o workspace.json e conecta automaticamente terminais soltos ao nó concentrador.
|
||||||
*/
|
*/
|
||||||
@ -59,70 +100,152 @@ export function autoWireWorkspace(workspacePath, options = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const concentratorName = (options.concentratorName || process.env.MAESTRI_CONCENTRATOR_NAME || 'maestri-remote').toLowerCase();
|
const concentratorName = (options.concentratorName || process.env.MAESTRI_CONCENTRATOR_NAME || 'maestri-remote').toLowerCase();
|
||||||
const concentratorId = options.concentratorId || process.env.MAESTRI_CONCENTRATOR_ID;
|
const concentratorId = options.concentratorId || process.env.MAESTRI_TERMINAL_ID || process.env.MAESTRI_CONCENTRATOR_ID;
|
||||||
|
|
||||||
// 1. Identifica o nó concentrador
|
const isTerminalNode = (n) => {
|
||||||
let hubNode = null;
|
if (!n) return false;
|
||||||
|
return n.type === 'terminal' || Boolean(n.content?.terminal) || Boolean(n.terminal);
|
||||||
|
};
|
||||||
|
|
||||||
|
const getTerminalName = (n) => {
|
||||||
|
return (
|
||||||
|
n.content?.terminal?._0?.name ||
|
||||||
|
n.content?.terminal?.name ||
|
||||||
|
n.terminal?.name ||
|
||||||
|
n.title ||
|
||||||
|
n.name ||
|
||||||
|
''
|
||||||
|
).toLowerCase();
|
||||||
|
};
|
||||||
|
|
||||||
|
// 1. Identifica o(s) nó(s) concentrador(es)
|
||||||
|
let hubNodes = [];
|
||||||
if (concentratorId) {
|
if (concentratorId) {
|
||||||
hubNode = payload.nodes.find(n => n.id === concentratorId);
|
const hub = payload.nodes.find(n => n && n.id === concentratorId);
|
||||||
|
if (hub) hubNodes.push(hub);
|
||||||
}
|
}
|
||||||
if (!hubNode) {
|
|
||||||
hubNode = payload.nodes.find(n => {
|
if (hubNodes.length === 0) {
|
||||||
|
// Busca nós concentradores por nome/título conhecido
|
||||||
|
const matches = payload.nodes.filter(n => {
|
||||||
|
if (!isTerminalNode(n)) return false;
|
||||||
const title = (n.title || '').toLowerCase();
|
const title = (n.title || '').toLowerCase();
|
||||||
const termName = (n.content?.terminal?._0?.name || '').toLowerCase();
|
const termName = getTerminalName(n);
|
||||||
const nodeType = (n.type || '').toLowerCase();
|
|
||||||
return (
|
return (
|
||||||
title === concentratorName ||
|
title === concentratorName ||
|
||||||
|
title === 'maestri-remote' ||
|
||||||
title === 'maestri-remote-channel' ||
|
title === 'maestri-remote-channel' ||
|
||||||
termName === concentratorName ||
|
termName === concentratorName ||
|
||||||
|
termName === 'maestri-remote' ||
|
||||||
termName === 'maestri-remote-channel' ||
|
termName === 'maestri-remote-channel' ||
|
||||||
(nodeType === 'terminal' && (title.includes('remote') || termName.includes('remote')))
|
(title.includes('remote') || termName.includes('remote'))
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (matches.length > 0) {
|
||||||
|
hubNodes = matches;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!hubNode) {
|
if (hubNodes.length === 0) {
|
||||||
|
const fallbackHub = payload.nodes.find(n => {
|
||||||
|
if (!n) return false;
|
||||||
|
const title = (n.title || '').toLowerCase();
|
||||||
|
const termName = getTerminalName(n);
|
||||||
|
return title === concentratorName || termName === concentratorName;
|
||||||
|
});
|
||||||
|
if (fallbackHub) hubNodes.push(fallbackHub);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hubNodes.length === 0) {
|
||||||
return { modified: false, connectedCount: 0, newConnections: [], error: 'Nó concentrador não encontrado no workspace' };
|
return { modified: false, connectedCount: 0, newConnections: [], error: 'Nó concentrador não encontrado no workspace' };
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Mapeia conexões existentes
|
// 2. Mapeia e normaliza conexões existentes para o formato nativo do Maestri
|
||||||
const connectedPairs = new Set();
|
const connectedPairs = new Set();
|
||||||
|
let upgradedCount = 0;
|
||||||
|
|
||||||
for (const conn of payload.connections) {
|
for (const conn of payload.connections) {
|
||||||
const from = conn.from || conn.source;
|
if (!conn) continue;
|
||||||
const to = conn.to || conn.target;
|
let modifiedConn = false;
|
||||||
if (from && to) {
|
|
||||||
connectedPairs.add(`${from}->${to}`);
|
if (!conn.id) {
|
||||||
connectedPairs.add(`${to}->${from}`);
|
conn.id = typeof crypto.randomUUID === 'function'
|
||||||
|
? crypto.randomUUID()
|
||||||
|
: `conn-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
||||||
|
modifiedConn = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const a = conn.terminalIdA || conn.nodeIdA || conn.from || conn.source;
|
||||||
|
const b = conn.terminalIdB || conn.nodeIdB || conn.to || conn.target;
|
||||||
|
|
||||||
|
if (!conn.terminalIdA && a) {
|
||||||
|
conn.terminalIdA = a;
|
||||||
|
modifiedConn = true;
|
||||||
|
}
|
||||||
|
if (!conn.terminalIdB && b) {
|
||||||
|
conn.terminalIdB = b;
|
||||||
|
modifiedConn = true;
|
||||||
|
}
|
||||||
|
if (!conn.from && a) {
|
||||||
|
conn.from = a;
|
||||||
|
modifiedConn = true;
|
||||||
|
}
|
||||||
|
if (!conn.to && b) {
|
||||||
|
conn.to = b;
|
||||||
|
modifiedConn = true;
|
||||||
|
}
|
||||||
|
if (!conn.createdAt) {
|
||||||
|
conn.createdAt = new Date().toISOString();
|
||||||
|
modifiedConn = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (modifiedConn) {
|
||||||
|
upgradedCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (a && b) {
|
||||||
|
connectedPairs.add(`${a}->${b}`);
|
||||||
|
connectedPairs.add(`${b}->${a}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. Identifica todos os nós terminais
|
// 3. Identifica todos os nós terminais que não são concentradores
|
||||||
const terminalNodes = payload.nodes.filter(n => {
|
const hubIds = new Set(hubNodes.map(h => h.id));
|
||||||
if (n.id === hubNode.id) return false;
|
const terminalNodes = payload.nodes.filter(n => isTerminalNode(n) && !hubIds.has(n.id));
|
||||||
const isTerminal = n.type === 'terminal' || Boolean(n.content?.terminal);
|
|
||||||
return isTerminal;
|
|
||||||
});
|
|
||||||
|
|
||||||
|
// 4. Cria novas conexões no padrão nativo do Maestri (com terminalIdA, terminalIdB, id, createdAt, from, to)
|
||||||
const newConnections = [];
|
const newConnections = [];
|
||||||
|
for (const hub of hubNodes) {
|
||||||
for (const term of terminalNodes) {
|
for (const term of terminalNodes) {
|
||||||
const isConnectedToHub = connectedPairs.has(`${hubNode.id}->${term.id}`) || connectedPairs.has(`${term.id}->${hubNode.id}`);
|
const isConnected = connectedPairs.has(`${hub.id}->${term.id}`) || connectedPairs.has(`${term.id}->${hub.id}`);
|
||||||
if (!isConnectedToHub) {
|
if (!isConnected) {
|
||||||
|
const connId = typeof crypto.randomUUID === 'function'
|
||||||
|
? crypto.randomUUID()
|
||||||
|
: `conn-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
||||||
|
|
||||||
const newConn = {
|
const newConn = {
|
||||||
from: hubNode.id,
|
id: connId,
|
||||||
to: term.id
|
terminalIdA: hub.id,
|
||||||
|
terminalIdB: term.id,
|
||||||
|
from: hub.id,
|
||||||
|
to: term.id,
|
||||||
|
createdAt: new Date().toISOString()
|
||||||
};
|
};
|
||||||
|
|
||||||
payload.connections.push(newConn);
|
payload.connections.push(newConn);
|
||||||
connectedPairs.add(`${hubNode.id}->${term.id}`);
|
connectedPairs.add(`${hub.id}->${term.id}`);
|
||||||
connectedPairs.add(`${term.id}->${hubNode.id}`);
|
connectedPairs.add(`${term.id}->${hub.id}`);
|
||||||
newConnections.push(newConn);
|
newConnections.push(newConn);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (newConnections.length === 0) {
|
if (newConnections.length === 0 && upgradedCount === 0) {
|
||||||
return { modified: false, connectedCount: 0, newConnections: [] };
|
return { modified: false, connectedCount: 0, newConnections: [] };
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Salva atomicamente no disco
|
// 5. Salva atomicamente no disco
|
||||||
const tmpFile = `${workspacePath}.tmp.${Date.now()}`;
|
const tmpFile = `${workspacePath}.tmp.${Date.now()}`;
|
||||||
try {
|
try {
|
||||||
fs.writeFileSync(tmpFile, JSON.stringify(data, null, 2), 'utf8');
|
fs.writeFileSync(tmpFile, JSON.stringify(data, null, 2), 'utf8');
|
||||||
@ -135,6 +258,7 @@ export function autoWireWorkspace(workspacePath, options = {}) {
|
|||||||
return {
|
return {
|
||||||
modified: true,
|
modified: true,
|
||||||
connectedCount: newConnections.length,
|
connectedCount: newConnections.length,
|
||||||
|
upgradedCount,
|
||||||
newConnections
|
newConnections
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@ -146,11 +270,13 @@ export class CanvasAutoWiringMonitor {
|
|||||||
constructor(options = {}) {
|
constructor(options = {}) {
|
||||||
this.workspaceFilePath = resolveWorkspaceFilePath(options.workspaceFilePath, options.workspaceId);
|
this.workspaceFilePath = resolveWorkspaceFilePath(options.workspaceFilePath, options.workspaceId);
|
||||||
this.concentratorName = options.concentratorName || 'maestri-remote';
|
this.concentratorName = options.concentratorName || 'maestri-remote';
|
||||||
|
this.concentratorId = options.concentratorId || process.env.MAESTRI_TERMINAL_ID || process.env.MAESTRI_CONCENTRATOR_ID;
|
||||||
this.debounceMs = Number.isFinite(options.debounceMs) ? options.debounceMs : 300;
|
this.debounceMs = Number.isFinite(options.debounceMs) ? options.debounceMs : 300;
|
||||||
this.onWired = typeof options.onWired === 'function' ? options.onWired : null;
|
this.onWired = typeof options.onWired === 'function' ? options.onWired : null;
|
||||||
this.watcher = null;
|
this.watcher = null;
|
||||||
this.debounceTimer = null;
|
this.debounceTimer = null;
|
||||||
this.isWiring = false;
|
this.isWiring = false;
|
||||||
|
this.lastWriteTime = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
start() {
|
start() {
|
||||||
@ -163,6 +289,9 @@ export class CanvasAutoWiringMonitor {
|
|||||||
try {
|
try {
|
||||||
this.watcher = fs.watch(this.workspaceFilePath, (eventType) => {
|
this.watcher = fs.watch(this.workspaceFilePath, (eventType) => {
|
||||||
if (eventType === 'change' || eventType === 'rename') {
|
if (eventType === 'change' || eventType === 'rename') {
|
||||||
|
if (Date.now() - this.lastWriteTime < 200) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
clearTimeout(this.debounceTimer);
|
clearTimeout(this.debounceTimer);
|
||||||
this.debounceTimer = setTimeout(() => {
|
this.debounceTimer = setTimeout(() => {
|
||||||
this.checkAndWire();
|
this.checkAndWire();
|
||||||
@ -179,12 +308,19 @@ export class CanvasAutoWiringMonitor {
|
|||||||
this.isWiring = true;
|
this.isWiring = true;
|
||||||
try {
|
try {
|
||||||
const res = autoWireWorkspace(this.workspaceFilePath, {
|
const res = autoWireWorkspace(this.workspaceFilePath, {
|
||||||
concentratorName: this.concentratorName
|
concentratorName: this.concentratorName,
|
||||||
|
concentratorId: this.concentratorId
|
||||||
});
|
});
|
||||||
if (res.modified) {
|
if (res && res.modified) {
|
||||||
console.log(`[CanvasAutoWiring] Auto-wiring conectou ${res.connectedCount} novo(s) terminal(is) ao concentrador.`);
|
this.lastWriteTime = Date.now();
|
||||||
|
if (res.connectedCount > 0 || res.upgradedCount > 0) {
|
||||||
|
const detail = res.connectedCount > 0
|
||||||
|
? `${res.connectedCount} novo(s) terminal(is)`
|
||||||
|
: `${res.upgradedCount} conexao(oes) atualizada(s)`;
|
||||||
|
console.log(`[CanvasAutoWiring] Auto-wiring sincronizou ${detail} no concentrador.`);
|
||||||
}
|
}
|
||||||
if (this.onWired) {
|
}
|
||||||
|
if (this.onWired && res) {
|
||||||
this.onWired(res);
|
this.onWired(res);
|
||||||
}
|
}
|
||||||
return res;
|
return res;
|
||||||
|
|||||||
@ -29,11 +29,17 @@ export class GatewayDaemon {
|
|||||||
this.publicHost = options.publicHost || process.env.PUBLIC_HOST || 'https://remote.winicomw.ddnsfree.com';
|
this.publicHost = options.publicHost || process.env.PUBLIC_HOST || 'https://remote.winicomw.ddnsfree.com';
|
||||||
this.pin = options.pin || this.loadOrGeneratePin(options.resetPin);
|
this.pin = options.pin || this.loadOrGeneratePin(options.resetPin);
|
||||||
this.machineName = options.machineName || os.hostname() || 'Dev-Machine';
|
this.machineName = options.machineName || os.hostname() || 'Dev-Machine';
|
||||||
this.adapter = options.adapter || new MaestriAdapter();
|
this.adapter = options.adapter || new MaestriAdapter({
|
||||||
|
workspaceFilePath: options.workspaceFilePath,
|
||||||
|
workspaceId: options.workspaceId,
|
||||||
|
syncCanvasTerminals: options.syncCanvasTerminals !== undefined ? options.syncCanvasTerminals : true
|
||||||
|
});
|
||||||
this.updater = options.updater || new AgentUpdater({ publicHost: this.publicHost });
|
this.updater = options.updater || new AgentUpdater({ publicHost: this.publicHost });
|
||||||
this.autoWiringMonitor = options.autoWiringMonitor || new CanvasAutoWiringMonitor({
|
this.autoWiringMonitor = options.autoWiringMonitor || new CanvasAutoWiringMonitor({
|
||||||
workspaceFilePath: options.workspaceFilePath,
|
workspaceFilePath: options.workspaceFilePath,
|
||||||
workspaceId: options.workspaceId,
|
workspaceId: options.workspaceId || this.adapter?.workspaceId,
|
||||||
|
concentratorId: options.concentratorId || this.adapter?.terminalId || process.env.MAESTRI_TERMINAL_ID,
|
||||||
|
concentratorName: options.concentratorName,
|
||||||
onWired: (res) => {
|
onWired: (res) => {
|
||||||
if (res.modified) {
|
if (res.modified) {
|
||||||
this.syncAgents();
|
this.syncAgents();
|
||||||
|
|||||||
@ -4,6 +4,7 @@ import fs from 'node:fs';
|
|||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import net from 'node:net';
|
import net from 'node:net';
|
||||||
import { detectTerminalActivity } from '../utils/activity-detector.js';
|
import { detectTerminalActivity } from '../utils/activity-detector.js';
|
||||||
|
import { resolveWorkspaceFilePath, getWorkspaceTerminalNodes } from './canvas-auto-wiring.js';
|
||||||
|
|
||||||
const execFileAsync = promisify(execFile);
|
const execFileAsync = promisify(execFile);
|
||||||
|
|
||||||
@ -53,6 +54,8 @@ export class MaestriAdapter {
|
|||||||
this.pipePath = options.pipePath || process.env.MAESTRI_PIPE;
|
this.pipePath = options.pipePath || process.env.MAESTRI_PIPE;
|
||||||
this.terminalId = options.terminalId || process.env.MAESTRI_TERMINAL_ID;
|
this.terminalId = options.terminalId || process.env.MAESTRI_TERMINAL_ID;
|
||||||
this.workspaceId = options.workspaceId || process.env.MAESTRI_WORKSPACE_ID;
|
this.workspaceId = options.workspaceId || process.env.MAESTRI_WORKSPACE_ID;
|
||||||
|
this.workspaceFilePath = options.workspaceFilePath;
|
||||||
|
this.syncCanvasTerminals = options.syncCanvasTerminals ?? (Boolean(this.workspaceFilePath));
|
||||||
this.maxConsoleLength = options.maxConsoleLength || DEFAULT_MAX_CONSOLE_LENGTH;
|
this.maxConsoleLength = options.maxConsoleLength || DEFAULT_MAX_CONSOLE_LENGTH;
|
||||||
this.messagesDir = options.messagesDir || path.resolve(process.cwd(), '.maestri-remote', 'messages');
|
this.messagesDir = options.messagesDir || path.resolve(process.cwd(), '.maestri-remote', 'messages');
|
||||||
this.restartDelayMs = Number.isFinite(options.restartDelayMs) ? Math.max(0, options.restartDelayMs) : 400;
|
this.restartDelayMs = Number.isFinite(options.restartDelayMs) ? Math.max(0, options.restartDelayMs) : 400;
|
||||||
@ -170,31 +173,71 @@ export class MaestriAdapter {
|
|||||||
|
|
||||||
async listAgents() {
|
async listAgents() {
|
||||||
const res = await this.runMaestri(['list']);
|
const res = await this.runMaestri(['list']);
|
||||||
if (!res.ok) {
|
|
||||||
console.warn('[Gateway:MaestriAdapter] Falha ao executar maestri list:', res.error);
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const lines = res.output.split('\n');
|
|
||||||
const rawList = [];
|
const rawList = [];
|
||||||
|
const seenNames = new Set();
|
||||||
let isSelf = false;
|
let isSelf = false;
|
||||||
|
let inAgentsSection = true;
|
||||||
|
|
||||||
|
if (res && res.ok && typeof res.output === 'string') {
|
||||||
|
const lines = res.output.split('\n');
|
||||||
for (const line of lines) {
|
for (const line of lines) {
|
||||||
const trimmed = line.trim();
|
const trimmed = line.trim();
|
||||||
if (trimmed.startsWith('You:')) {
|
if (trimmed.startsWith('You:')) {
|
||||||
isSelf = true;
|
isSelf = true;
|
||||||
} else if (trimmed.startsWith('Connected agents:')) {
|
inAgentsSection = true;
|
||||||
|
} else if (
|
||||||
|
trimmed.startsWith('Connected agents:') ||
|
||||||
|
trimmed.startsWith('Connected terminals:') ||
|
||||||
|
trimmed.startsWith('Agents:') ||
|
||||||
|
trimmed.startsWith('Terminals:')
|
||||||
|
) {
|
||||||
isSelf = false;
|
isSelf = false;
|
||||||
} else if (trimmed.startsWith('- name:')) {
|
inAgentsSection = true;
|
||||||
const match = trimmed.match(/- name:\s*"([^"]+)"/);
|
} else if (
|
||||||
|
trimmed.startsWith('Connected notes:') ||
|
||||||
|
trimmed.startsWith('Connected portals:') ||
|
||||||
|
trimmed.startsWith('Notes:') ||
|
||||||
|
trimmed.startsWith('Portals:')
|
||||||
|
) {
|
||||||
|
inAgentsSection = false;
|
||||||
|
} else if (inAgentsSection) {
|
||||||
|
// Suporta formatos de conexão direta (- name: "...") e conexões transitivas/árvores no Maestri (⎿ agent: "...")
|
||||||
|
const match = trimmed.match(/^(?:-\s*name:|[⎿\u23BF-]\s*(?:agent|terminal):)\s*["']?([^"',\r\n]+)["']?/i);
|
||||||
if (match) {
|
if (match) {
|
||||||
|
const name = match[1].trim();
|
||||||
|
if (name && !seenNames.has(name)) {
|
||||||
|
seenNames.add(name);
|
||||||
rawList.push({
|
rawList.push({
|
||||||
name: match[1],
|
name,
|
||||||
isSelf
|
isSelf
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
} else if (res && !res.ok) {
|
||||||
|
console.warn('[Gateway:MaestriAdapter] Falha ao executar maestri list:', res.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Se solicitado explicitamente ou se maestri list falhar/retornar lista restrita,
|
||||||
|
// complementa com os terminais do canvas para garantir visibilidade de todos no app móvel
|
||||||
|
if (this.syncCanvasTerminals || !res?.ok || rawList.length <= 1) {
|
||||||
|
try {
|
||||||
|
const wsPath = resolveWorkspaceFilePath(this.workspaceFilePath, this.workspaceId);
|
||||||
|
if (wsPath) {
|
||||||
|
const canvasTerminals = getWorkspaceTerminalNodes(wsPath);
|
||||||
|
for (const term of canvasTerminals) {
|
||||||
|
if (!seenNames.has(term.name)) {
|
||||||
|
seenNames.add(term.name);
|
||||||
|
rawList.push({
|
||||||
|
name: term.name,
|
||||||
|
isSelf: false
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
// Inspeciona os terminais conectados em paralelo para determinar se possuem agente de IA ativo
|
// Inspeciona os terminais conectados em paralelo para determinar se possuem agente de IA ativo
|
||||||
this.selfAgentNames = new Set(rawList.filter(item => item.isSelf).map(item => item.name));
|
this.selfAgentNames = new Set(rawList.filter(item => item.isSelf).map(item => item.name));
|
||||||
|
|||||||
@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
|
|||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import os from 'node:os';
|
import os from 'node:os';
|
||||||
import { autoWireWorkspace, CanvasAutoWiringMonitor } from '../src/gateway/canvas-auto-wiring.js';
|
import { autoWireWorkspace, CanvasAutoWiringMonitor, getWorkspaceTerminalNodes } from '../src/gateway/canvas-auto-wiring.js';
|
||||||
|
|
||||||
test('autoWireWorkspace deve conectar terminais soltos ao nó concentrador e persistir atomicamente', () => {
|
test('autoWireWorkspace deve conectar terminais soltos ao nó concentrador e persistir atomicamente', () => {
|
||||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-autowire-'));
|
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-autowire-'));
|
||||||
@ -52,13 +52,18 @@ test('autoWireWorkspace deve conectar terminais soltos ao nó concentrador e per
|
|||||||
assert.equal(result.newConnections.length, 1);
|
assert.equal(result.newConnections.length, 1);
|
||||||
assert.equal(result.newConnections[0].from, 'node-concentrador');
|
assert.equal(result.newConnections[0].from, 'node-concentrador');
|
||||||
assert.equal(result.newConnections[0].to, 'node-terminal-2');
|
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
|
// Relê o arquivo e valida integridade
|
||||||
const updated = JSON.parse(fs.readFileSync(workspacePath, 'utf8'));
|
const updated = JSON.parse(fs.readFileSync(workspacePath, 'utf8'));
|
||||||
assert.equal(updated.payload.connections.length, 2);
|
assert.equal(updated.payload.connections.length, 2);
|
||||||
const conn2 = updated.payload.connections.find(c => c.to === 'node-terminal-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.ok(conn2, 'Deve ter criado conexão com node-terminal-2');
|
||||||
assert.equal(conn2.from, 'node-concentrador');
|
assert.equal(conn2.from, 'node-concentrador');
|
||||||
|
assert.equal(conn2.terminalIdA, 'node-concentrador');
|
||||||
|
|
||||||
// Segunda execução imediata não deve duplicar nem modificar o arquivo
|
// Segunda execução imediata não deve duplicar nem modificar o arquivo
|
||||||
const secondResult = autoWireWorkspace(workspacePath, {
|
const secondResult = autoWireWorkspace(workspacePath, {
|
||||||
@ -71,6 +76,117 @@ test('autoWireWorkspace deve conectar terminais soltos ao nó concentrador e per
|
|||||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
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 () => {
|
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 tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'maestri-autowire-mon-'));
|
||||||
const workspacePath = path.join(tmpDir, 'workspace.json');
|
const workspacePath = path.join(tmpDir, 'workspace.json');
|
||||||
@ -119,7 +235,7 @@ test('CanvasAutoWiringMonitor deve observar alterações no workspace.json e aci
|
|||||||
|
|
||||||
assert.ok(wiringEvents >= 1, 'Deve ter acionado evento de wiring');
|
assert.ok(wiringEvents >= 1, 'Deve ter acionado evento de wiring');
|
||||||
const finalJson = JSON.parse(fs.readFileSync(workspacePath, 'utf8'));
|
const finalJson = JSON.parse(fs.readFileSync(workspacePath, 'utf8'));
|
||||||
const conn = finalJson.payload.connections.find(c => c.to === 'novo-agente');
|
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');
|
assert.ok(conn, 'Conexão para novo-agente deve existir no disco');
|
||||||
|
|
||||||
// Limpeza
|
// Limpeza
|
||||||
|
|||||||
@ -2,6 +2,7 @@ import test from 'node:test';
|
|||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import fs from 'node:fs';
|
import fs from 'node:fs';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
|
import os from 'node:os';
|
||||||
import { GatewayDaemon } from '../src/gateway/daemon.js';
|
import { GatewayDaemon } from '../src/gateway/daemon.js';
|
||||||
import * as maestriAdapterModule from '../src/gateway/maestri-adapter.js';
|
import * as maestriAdapterModule from '../src/gateway/maestri-adapter.js';
|
||||||
const { MaestriAdapter } = maestriAdapterModule;
|
const { MaestriAdapter } = maestriAdapterModule;
|
||||||
@ -275,6 +276,63 @@ test('MaestriAdapter.listAgents deve enriquecer agentes com hasAiActivity e shel
|
|||||||
assert.equal(psAgent.status, 'idle_shell');
|
assert.equal(psAgent.status, 'idle_shell');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('MaestriAdapter.listAgents deve analisar agentes diretos (- name:), transitivos (⎿ agent:) e ignorar notas/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'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('MaestriAdapter.listAgents deve realizar fallback para 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 });
|
||||||
|
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('GatewayDaemon deve calcular e incluir status determinístico ao responder GET_AGENT_TERMINAL', async () => {
|
test('GatewayDaemon deve calcular e incluir status determinístico ao responder GET_AGENT_TERMINAL', async () => {
|
||||||
const sentMessages = [];
|
const sentMessages = [];
|
||||||
const mockWs = {
|
const mockWs = {
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user