Added Various API Functionality

This commit is contained in:
2025-05-10 16:23:32 -06:00
parent 6ff4170894
commit bce39d355f
14 changed files with 538 additions and 1 deletions

View File

@ -0,0 +1,193 @@
////////// PROJECT FILE SEPARATION LINE ////////// CODE AFTER THIS LINE ARE FROM: <ProjectRoot>/Data/WebUI/src/nodes/Data Collection/Node_API_Request.jsx
import React, { useState, useEffect, useRef } from "react";
import { Handle, Position, useReactFlow } from "reactflow";
const APIRequestNode = ({ id, data }) => {
const { setNodes } = useReactFlow();
if (!window.BorealisValueBus) window.BorealisValueBus = {};
// Stored URL (actual fetch target)
const [url, setUrl] = useState(data?.url || "http://localhost:5000/health");
// Editable URL text
const [editUrl, setEditUrl] = useState(data?.url || "http://localhost:5000/health");
const [useProxy, setUseProxy] = useState(data?.useProxy || true);
const [body, setBody] = useState(data?.body || "");
const [intervalSec, setIntervalSec] = useState(data?.intervalSec ?? 10);
const [error, setError] = useState(null);
const [statusCode, setStatusCode] = useState(null);
const [statusText, setStatusText] = useState("");
const resultRef = useRef(null);
const handleUrlInputChange = (e) => setEditUrl(e.target.value);
const handleToggleProxy = (e) => {
const flag = e.target.checked;
setUseProxy(flag);
setNodes((nds) =>
nds.map((n) =>
n.id === id
? { ...n, data: { ...n.data, useProxy: flag } }
: n
)
);
};
const handleUpdateUrl = () => {
setUrl(editUrl);
setError(null);
setStatusCode(null);
setStatusText("");
resultRef.current = null;
window.BorealisValueBus[id] = undefined;
setNodes((nds) =>
nds.map((n) =>
n.id === id
? { ...n, data: { ...n.data, url: editUrl, result: undefined } }
: n
)
);
};
// ... other handlers unchanged ...
const handleBodyChange = (e) => {
const newBody = e.target.value;
setBody(newBody);
setNodes((nds) =>
nds.map((n) =>
n.id === id
? { ...n, data: { ...n.data, body: newBody } }
: n
)
);
};
const handleIntervalChange = (e) => {
const sec = parseInt(e.target.value, 10) || 1;
setIntervalSec(sec);
setNodes((nds) =>
nds.map((n) =>
n.id === id
? { ...n, data: { ...n.data, intervalSec: sec } }
: n
)
);
};
useEffect(() => {
let cancelled = false;
const runNodeLogic = async () => {
try {
setError(null);
let target = url;
if (useProxy) {
target = `/api/proxy?url=${encodeURIComponent(url)}`;
}
const options = {};
if (body.trim()) {
options.method = "POST";
options.headers = { "Content-Type": "application/json" };
options.body = body;
}
const res = await fetch(target, options);
setStatusCode(res.status);
setStatusText(res.statusText);
if (!res.ok) {
// clear on error
resultRef.current = null;
window.BorealisValueBus[id] = undefined;
setNodes((nds) =>
nds.map((n) =>
n.id === id
? { ...n, data: { ...n.data, result: undefined } }
: n
)
);
throw new Error(`HTTP ${res.status}`);
}
const json = await res.json();
const pretty = JSON.stringify(json, null, 2);
if (!cancelled && resultRef.current !== pretty) {
resultRef.current = pretty;
window.BorealisValueBus[id] = json;
setNodes((nds) =>
nds.map((n) =>
n.id === id
? { ...n, data: { ...n.data, result: pretty } }
: n
)
);
}
} catch (err) {
console.error("API Request node fetch error:", err);
setError(err.message);
}
};
runNodeLogic();
const ms = Math.max(intervalSec, 1) * 1000;
const iv = setInterval(runNodeLogic, ms);
return () => {
cancelled = true;
clearInterval(iv);
};
}, [url, body, intervalSec, useProxy, id, setNodes]);
return (
<div className="borealis-node">
<div className="borealis-node-header">API Request</div>
<div className="borealis-node-content">
{/* URL input */}
<label style={{ fontSize: "9px", display: "block", marginBottom: "4px" }}>Request URL:</label>
<input
type="text"
value={editUrl}
onChange={handleUrlInputChange}
style={{ fontSize: "9px", padding: "4px", width: "100%", background: "#1e1e1e", color: "#ccc", border: "1px solid #444", borderRadius: "2px" }}
/>
<button onClick={handleUpdateUrl} style={{ fontSize: "9px", marginTop: "6px", padding: "2px 6px", background: "#333", color: "#ccc", border: "1px solid #444", borderRadius: "2px", cursor: "pointer" }}>
Update URL
</button>
{/* Proxy toggle */}
<div style={{ marginTop: "6px" }}>
<input
id={`${id}-proxy-toggle`}
type="checkbox"
checked={useProxy}
onChange={handleToggleProxy}
/>
<label
htmlFor={`${id}-proxy-toggle`}
title="Query a remote API server using internal Borealis mechanisms to bypass CORS limitations."
style={{ fontSize: "8px", marginLeft: "4px", cursor: "help" }}
>
Remote API Endpoint
</label>
</div>
{/* body & interval unchanged... */}
<label style={{ fontSize: "9px", display: "block", margin: "8px 0 4px" }}>Request Body:</label>
<textarea value={body} onChange={handleBodyChange} rows={4} style={{ fontSize: "9px", padding: "4px", width: "100%", background: "#1e1e1e", color: "#ccc", border: "1px solid #444", borderRadius: "2px", resize: "vertical" }} />
<label style={{ fontSize: "9px", display: "block", margin: "8px 0 4px" }}>Polling Interval (sec):</label>
<input type="number" min="1" value={intervalSec} onChange={handleIntervalChange} style={{ fontSize: "9px", padding: "4px", width: "100%", background: "#1e1e1e", color: "#ccc", border: "1px solid #444", borderRadius: "2px" }} />
{/* indicators unchanged... */}
{statusCode !== null && statusCode >= 200 && statusCode < 300 && (
<div style={{ color: "#6f6", fontSize: "8px", marginTop: "6px" }}>Status: {statusCode} {statusText}</div>
)}
{error && (
<div style={{ color: "#f66", fontSize: "8px", marginTop: "6px" }}>Error: {error}</div>
)}
</div>
<Handle type="source" position={Position.Right} className="borealis-handle" />
</div>
);
};
export default {
type: "API_Request",
label: "API Request",
description: "Fetch JSON from an API endpoint with optional body, proxy toggle, and polling interval.",
content: "Fetch JSON from HTTP or remote API via internal proxy to bypass CORS.",
component: APIRequestNode
};

View File

@ -0,0 +1,188 @@
////////// PROJECT FILE SEPARATION LINE ////////// CODE AFTER THIS LINE ARE FROM: <ProjectRoot>/Data/WebUI/src/nodes/Agent/Node_Agent.jsx
import React, { useEffect, useState, useCallback, useMemo, useRef } from "react";
import { Handle, Position, useReactFlow, useStore } from "reactflow";
const BorealisAgentNode = ({ id, data }) => {
const { getNodes, setNodes } = useReactFlow();
const edges = useStore((state) => state.edges);
const [agents, setAgents] = useState({});
const [selectedAgent, setSelectedAgent] = useState(data.agent_id || "");
const [isConnected, setIsConnected] = useState(false);
const prevRolesRef = useRef([]);
// ---------------- Agent List & Sorting ----------------
const agentList = useMemo(() => {
if (!agents || typeof agents !== "object") return [];
return Object.entries(agents)
.map(([aid, info]) => ({
id: aid,
status: info?.status || "offline",
last_seen: info?.last_seen || 0
}))
.filter(({ status }) => status !== "offline")
.sort((a, b) => b.last_seen - a.last_seen);
}, [agents]);
// ---------------- Periodic Agent Fetching ----------------
useEffect(() => {
const fetchAgents = () => {
fetch("/api/agents")
.then((res) => res.json())
.then(setAgents)
.catch(() => {});
};
fetchAgents();
const interval = setInterval(fetchAgents, 4000);
return () => clearInterval(interval);
}, []);
// ---------------- Node Data Sync ----------------
useEffect(() => {
setNodes((nds) =>
nds.map((n) =>
n.id === id ? { ...n, data: { ...n.data, agent_id: selectedAgent } } : n
)
);
setIsConnected(false);
}, [selectedAgent]);
// ---------------- Attached Role Collection ----------------
const attachedRoleIds = useMemo(
() =>
edges
.filter((e) => e.source === id && e.sourceHandle === "provisioner")
.map((e) => e.target),
[edges, id]
);
const getAttachedRoles = useCallback(() => {
const allNodes = getNodes();
return attachedRoleIds
.map((nid) => {
const fn = window.__BorealisInstructionNodes?.[nid];
return typeof fn === "function" ? fn() : null;
})
.filter((r) => r);
}, [attachedRoleIds, getNodes]);
// ---------------- Provision Role Logic ----------------
const provisionRoles = useCallback((roles) => {
if (!selectedAgent) return; // Allow empty roles but require agent
fetch("/api/agent/provision", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ agent_id: selectedAgent, roles })
})
.then(() => {
setIsConnected(true);
prevRolesRef.current = roles;
})
.catch(() => {});
}, [selectedAgent]);
const handleConnect = useCallback(() => {
const roles = getAttachedRoles();
provisionRoles(roles); // Always call even with empty roles
}, [getAttachedRoles, provisionRoles]);
const handleDisconnect = useCallback(() => {
if (!selectedAgent) return;
fetch("/api/agent/provision", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ agent_id: selectedAgent, roles: [] })
})
.then(() => {
setIsConnected(false);
prevRolesRef.current = [];
})
.catch(() => {});
}, [selectedAgent]);
// ---------------- Auto-Provision When Roles Change ----------------
useEffect(() => {
const newRoles = getAttachedRoles();
const prevSerialized = JSON.stringify(prevRolesRef.current || []);
const newSerialized = JSON.stringify(newRoles);
if (isConnected && newSerialized !== prevSerialized) {
provisionRoles(newRoles);
}
}, [attachedRoleIds, isConnected, getAttachedRoles, provisionRoles]);
// ---------------- Status Label ----------------
const selectedAgentStatus = useMemo(() => {
if (!selectedAgent) return "Unassigned";
const agent = agents[selectedAgent];
if (!agent) return "Reconnecting...";
return agent.status === "provisioned" ? "Connected" : "Available";
}, [agents, selectedAgent]);
// ---------------- Render ----------------
return (
<div className="borealis-node">
<Handle
type="source"
position={Position.Bottom}
id="provisioner"
className="borealis-handle"
style={{ top: "100%", background: "#58a6ff" }}
/>
<div className="borealis-node-header">Borealis Agent</div>
<div className="borealis-node-content" style={{ fontSize: "9px" }}>
<label>Agent:</label>
<select
value={selectedAgent}
onChange={(e) => setSelectedAgent(e.target.value)}
style={{ width: "100%", marginBottom: "6px", fontSize: "9px" }}
>
<option value="">-- Select --</option>
{agentList.map(({ id: aid, status }) => (
<option key={aid} value={aid}>
{aid} ({status})
</option>
))}
</select>
{isConnected ? (
<button
onClick={handleDisconnect}
style={{ width: "100%", fontSize: "9px", padding: "4px", marginTop: "4px" }}
>
Disconnect from Agent
</button>
) : (
<button
onClick={handleConnect}
style={{ width: "100%", fontSize: "9px", padding: "4px", marginTop: "4px" }}
disabled={!selectedAgent}
>
Connect to Agent
</button>
)}
<hr style={{ margin: "6px 0", borderColor: "#444" }} />
<div style={{ fontSize: "8px", color: "#aaa" }}>
Status: <strong>{selectedAgentStatus}</strong>
<br />
Attach <strong>Agent Role Nodes</strong> to define live behavior.
</div>
</div>
</div>
);
};
export default {
type: "Borealis_Agent",
label: "Borealis Agent",
description: `
Main Agent Node
- Selects an available agent
- Connect/disconnects via button
- Auto-updates roles when attached roles change
`.trim(),
content: "Select and manage an Agent with dynamic roles",
component: BorealisAgentNode,
};

View File

@ -0,0 +1,200 @@
import React, { useEffect, useRef, useState } from "react";
import { Handle, Position, useReactFlow, useStore } from "reactflow";
import ShareIcon from "@mui/icons-material/Share";
import IconButton from "@mui/material/IconButton";
if (!window.BorealisValueBus) {
window.BorealisValueBus = {};
}
if (!window.BorealisUpdateRate) {
window.BorealisUpdateRate = 100;
}
const ScreenshotInstructionNode = ({ id, data }) => {
const { setNodes, getNodes } = useReactFlow();
const edges = useStore(state => state.edges);
const [interval, setInterval] = useState(data?.interval || 1000);
const [region, setRegion] = useState({
x: data?.x ?? 250,
y: data?.y ?? 100,
w: data?.w ?? 300,
h: data?.h ?? 200,
});
const [visible, setVisible] = useState(data?.visible ?? true);
const [alias, setAlias] = useState(data?.alias || "");
const [imageBase64, setImageBase64] = useState("");
const base64Ref = useRef("");
const regionRef = useRef(region);
// Push current state into BorealisValueBus at intervals
useEffect(() => {
const intervalId = setInterval(() => {
const val = base64Ref.current;
if (val) {
window.BorealisValueBus[id] = val;
setNodes(nds =>
nds.map(n =>
n.id === id ? { ...n, data: { ...n.data, value: val } } : n
)
);
}
}, window.BorealisUpdateRate || 100);
return () => clearInterval(intervalId);
}, [id, setNodes]);
// Listen for agent screenshot + overlay updates
useEffect(() => {
const socket = window.BorealisSocket;
if (!socket) return;
const handleScreenshot = (payload) => {
if (payload?.node_id !== id) return;
// image update (optional)
if (payload.image_base64) {
base64Ref.current = payload.image_base64;
setImageBase64(payload.image_base64);
window.BorealisValueBus[id] = payload.image_base64;
}
// geometry update
const { x, y, w, h } = payload;
if (x !== undefined && y !== undefined && w !== undefined && h !== undefined) {
const newRegion = { x, y, w, h };
const prev = regionRef.current;
const changed = Object.entries(newRegion).some(([k, v]) => prev[k] !== v);
if (changed) {
regionRef.current = newRegion;
setRegion(newRegion);
setNodes(nds =>
nds.map(n =>
n.id === id ? { ...n, data: { ...n.data, ...newRegion } } : n
)
);
}
}
};
socket.on("agent_screenshot_task", handleScreenshot);
return () => socket.off("agent_screenshot_task", handleScreenshot);
}, [id, setNodes]);
// Bi-directional instruction export
window.__BorealisInstructionNodes = window.__BorealisInstructionNodes || {};
window.__BorealisInstructionNodes[id] = () => ({
node_id: id,
role: "screenshot",
interval,
visible,
alias,
...regionRef.current
});
// Manual live view copy
const handleCopyLiveViewLink = () => {
const agentEdge = edges.find(e => e.target === id && e.sourceHandle === "provisioner");
const agentNode = getNodes().find(n => n.id === agentEdge?.source);
const selectedAgentId = agentNode?.data?.agent_id;
if (!selectedAgentId) {
alert("No valid agent connection found.");
return;
}
const liveUrl = `${window.location.origin}/api/agent/${selectedAgentId}/node/${id}/screenshot/live`;
navigator.clipboard.writeText(liveUrl)
.then(() => console.log(`[Clipboard] Live View URL copied: ${liveUrl}`))
.catch(err => console.error("Clipboard copy failed:", err));
};
return (
<div className="borealis-node" style={{ position: "relative" }}>
<Handle type="target" position={Position.Left} className="borealis-handle" />
<Handle type="source" position={Position.Right} className="borealis-handle" />
<div className="borealis-node-header">Agent Role: Screenshot</div>
<div className="borealis-node-content" style={{ fontSize: "9px" }}>
<label>Update Interval (ms):</label>
<input
type="number"
min="100"
step="100"
value={interval}
onChange={(e) => setInterval(Number(e.target.value))}
style={{ width: "100%", marginBottom: "4px" }}
/>
<label>Region X / Y / W / H:</label>
<div style={{ display: "flex", gap: "4px", marginBottom: "4px" }}>
<input type="number" value={region.x} onChange={(e) => {
const x = Number(e.target.value);
const updated = { ...region, x }; setRegion(updated); regionRef.current = updated;
}} style={{ width: "25%" }} />
<input type="number" value={region.y} onChange={(e) => {
const y = Number(e.target.value);
const updated = { ...region, y }; setRegion(updated); regionRef.current = updated;
}} style={{ width: "25%" }} />
<input type="number" value={region.w} onChange={(e) => {
const w = Number(e.target.value);
const updated = { ...region, w }; setRegion(updated); regionRef.current = updated;
}} style={{ width: "25%" }} />
<input type="number" value={region.h} onChange={(e) => {
const h = Number(e.target.value);
const updated = { ...region, h }; setRegion(updated); regionRef.current = updated;
}} style={{ width: "25%" }} />
</div>
<div style={{ marginBottom: "4px" }}>
<label>
<input
type="checkbox"
checked={visible}
onChange={() => setVisible(!visible)}
style={{ marginRight: "4px" }}
/>
Show Overlay on Agent
</label>
</div>
<label>Overlay Label:</label>
<input
type="text"
value={alias}
onChange={(e) => setAlias(e.target.value)}
placeholder="Label (optional)"
style={{ width: "100%", fontSize: "9px", marginBottom: "6px" }}
/>
<div style={{ textAlign: "center", fontSize: "8px", color: "#aaa" }}>
{imageBase64
? `Last image: ${Math.round(imageBase64.length / 1024)} KB`
: "Awaiting Screenshot Data..."}
</div>
</div>
<div style={{ position: "absolute", top: 4, right: 4 }}>
<IconButton size="small" onClick={handleCopyLiveViewLink}>
<ShareIcon style={{ fontSize: 14 }} />
</IconButton>
</div>
</div>
);
};
export default {
type: "Agent_Role_Screenshot",
label: "Agent Role: Screenshot",
description: `
Agent Role Node: Screenshot Region
- Defines a single region capture role
- Allows custom update interval and overlay
- Emits captured base64 PNG data from agent
`.trim(),
content: "Capture screenshot region via agent",
component: ScreenshotInstructionNode
};

View File

@ -0,0 +1,123 @@
////////// PROJECT FILE SEPARATION LINE ////////// CODE AFTER THIS LINE ARE FROM: <ProjectRoot>/Data/WebUI/src/nodes/Data/Node_Upload_Text.jsx
/**
* Upload Text File Node
* --------------------------------------------------
* A node to upload a text file (TXT/LOG/INI/ETC) and store it as a multi-line text array.
* No input edges. Outputs an array of text lines via the shared value bus.
*/
import React, { useEffect, useState, useRef } from "react";
import { Handle, Position, useReactFlow, useStore } from "reactflow";
const UploadTextFileNode = ({ id, data }) => {
const { setNodes } = useReactFlow();
const edges = useStore((state) => state.edges);
// Initialize lines from persisted data or empty
const initialLines = data?.lines || [];
const [lines, setLines] = useState(initialLines);
const linesRef = useRef(initialLines);
const fileInputRef = useRef(null);
// Handle file selection and reading
const handleFileChange = (e) => {
const file = e.target.files && e.target.files[0];
if (!file) return;
file.text().then((text) => {
const arr = text.split(/\r\n|\n/);
linesRef.current = arr;
setLines(arr);
// Broadcast to shared bus
window.BorealisValueBus[id] = arr;
// Persist data for workflow serialization
setNodes((nds) =>
nds.map((n) =>
n.id === id
? { ...n, data: { ...n.data, lines: arr } }
: n
)
);
});
};
// Trigger file input click
const handleUploadClick = () => {
fileInputRef.current?.click();
};
// Periodically broadcast current lines to bus
useEffect(() => {
let currentRate = window.BorealisUpdateRate;
const intervalId = setInterval(() => {
window.BorealisValueBus[id] = linesRef.current;
}, currentRate);
// Monitor for rate changes
const monitorId = setInterval(() => {
const newRate = window.BorealisUpdateRate;
if (newRate !== currentRate) {
clearInterval(intervalId);
clearInterval(monitorId);
}
}, 250);
return () => {
clearInterval(intervalId);
clearInterval(monitorId);
};
}, [id]);
return (
<div className="borealis-node">
{/* No input handle for this node */}
<div className="borealis-node-header">
{data?.label || "Upload Text File"}
</div>
<div className="borealis-node-content">
<div style={{ marginBottom: "8px", fontSize: "9px", color: "#ccc" }}>
{data?.content ||
"Upload a text-based file, output a multi-line string array."}
</div>
<button
onClick={handleUploadClick}
style={{
width: "100%",
padding: "6px",
fontSize: "9px",
background: "#1e1e1e",
color: "#ccc",
border: "1px solid #444",
borderRadius: "2px",
cursor: "pointer"
}}
>
Select File...
</button>
<input
type="file"
accept=".txt,.log,.ini,text/*"
style={{ display: "none" }}
ref={fileInputRef}
onChange={handleFileChange}
/>
</div>
{/* Output connector on right */}
<Handle
type="source"
position={Position.Right}
className="borealis-handle"
/>
</div>
);
};
// Export node metadata for Borealis
export default {
type: "Upload_Text_File",
label: "Upload Text File",
description: "A node to upload a text file (TXT/LOG/INI/ETC) and store it as a multi-line text array.",
content: "Upload a text-based file, output a multi-line string array.",
component: UploadTextFileNode
};