SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.
JavaScript a2aagentic-aiai-agentsdevtoolsmcp-clientn8n-alternativeno-codeopen-sourceorchestrationsmythosvisual-builder
feat: implement cycle detection in APIEndpoint and improve error handling
Muhammad Hamza Khan88587b22fb03
diff --git a/packages/app/src/builder-ui/components/APIEndpoint.class.ts b/packages/app/src/builder-ui/components/APIEndpoint.class.tsindex 30f154dd..33a00441 100644--- a/packages/app/src/builder-ui/components/APIEndpoint.class.ts+++ b/packages/app/src/builder-ui/components/APIEndpoint.class.ts@@ -6,6 +6,7 @@ import { openEmbodimentDialog } from '../pages/builder/agent-settings';import { alert, confirm } from '../ui/dialogs';import { renderEndpointFormPreviewSidebar } from '../ui/react-injects';import { delay } from '../utils';+import { hasGraphCycle } from '../workspace/ComponentSort';import { Component } from './Component.class';declare var Metro;@@ -781,7 +782,10 @@ export class APIEndpoint extends Component {EMBODIMENT_DESCRIPTIONS.agent_skill.tooltipTitle,);- const skillErrors = this.getSkillErrors();+ // Skip skill errors for cyclic workflows (e.g., retry loops, polling)+ // These are intentional cycles and don't need settings validation+ const hasCycle = this.hasConnectionCycle();+ const skillErrors = hasCycle ? null : this.getSkillErrors();// this.workspace.@@ -812,6 +816,40 @@ export class APIEndpoint extends Component {}}+ /**+ * Checks if the current workflow has circular dependencies.+ * Builds a connection graph and uses DFS to detect cycles.+ * @returns true if a cycle is detected, false otherwise+ */+ private hasConnectionCycle(): boolean {+ const connections = this.workspace.jsPlumbInstance+ .getAllConnections()+ .map((connection) => {+ const source = connection.source;+ const target = connection.target;+ const sourceComponent = source.closest('.component');+ const targetComponent = target.closest('.component');++ if (!sourceComponent || !targetComponent) return null;+ return {+ sourceId: sourceComponent.id,+ targetId: targetComponent.id,+ };+ })+ .filter((c): c is { sourceId: string; targetId: string } => c !== null);++ // Build adjacency list with Set for deduplication+ const connectionGraph = new Map<string, Set<string>>();+ for (const conn of connections) {+ if (!connectionGraph.has(conn.sourceId)) {+ connectionGraph.set(conn.sourceId, new Set());+ }+ connectionGraph.get(conn.sourceId)?.add(conn.targetId);+ }++ return hasGraphCycle(this.uid, connectionGraph);+ }+private getSkillErrors() {type SkillErrorType = {error_slug: 'missing_connection' | 'connected_components_settings_err';@@ -848,124 +886,140 @@ export class APIEndpoint extends Component {}}- const skillErrors = new SkillError();- const checkConnections = () => {- let connections = this.workspace.jsPlumbInstance- .getAllConnections()- .map((connection) => {- const source = connection.source;- const target = connection.target;- const sourceComponent = source.closest('.component');- const targetComponent = target.closest('.component');-- if (!sourceComponent || !targetComponent) return null; //exclude connections that are not connected to components, these can be used for other visual stuff- return {- sourceId: source.closest('.component').id,- sourceIndex: [...source.parentElement.querySelectorAll('.output-endpoint')].findIndex(- (c) => c === source,- ),- targetId: target.closest('.component').id,- targetIndex: [...target.parentElement.querySelectorAll('.input-endpoint')].findIndex(- (r) => r === target,- ),- };- })- .filter((c) => c);- const sourceConnections = connections.filter((c) => c.sourceId === this.uid);-- // if no connections, then we need to add a default connection- if (sourceConnections.length === 0) {- skillErrors.addError({- error_slug: 'missing_connection',- error_message:- 'Tip: Add or connect components to bring your workflow to life. Components work together seamlessly to create a powerful, intuitive agent experience.',- });- } else {- skillErrors.removeError('missing_connection');- }- };- this.workspace.jsPlumbInstance.bind('connection', debounce(checkConnections, 100));- this.workspace.jsPlumbInstance.bind('connectionDetached', debounce(checkConnections, 100));-- checkConnections();-- const checkSettingsErr = () => {- let connections = this.workspace.jsPlumbInstance- .getAllConnections()- .map((connection) => {- const source = connection.source;- const target = connection.target;- const sourceComponent = source.closest('.component');- const targetComponent = target.closest('.component');-- if (!sourceComponent || !targetComponent) return null; //exclude connections that are not connected to components, these can be used for other visual stuff- return {- sourceId: source.closest('.component').id,- sourceIndex: [...source.parentElement.querySelectorAll('.output-endpoint')].findIndex(- (c) => c === source,- ),- targetId: target.closest('.component').id,- targetIndex: [...target.parentElement.querySelectorAll('.input-endpoint')].findIndex(- (r) => r === target,- ),- };- })- .filter((c) => c);-- // BFS to see if any node has an err- let hasError = false;- let compsToVisit = [this.uid];- let visited = [];- while (compsToVisit.length > 0) {- let cId = compsToVisit.shift();- visited.push(cId);-- const cmpCtrl = (document.querySelector(`.component#${cId}`) as any)?._control;- if (!cmpCtrl) continue;-- // check settings- let requiredSettings = [];- for (let settingId in cmpCtrl.settings) {- const setting = cmpCtrl.settings[settingId];- if (setting.validate?.includes('required')) {- requiredSettings.push({ id: settingId, name: setting.label || settingId });- }+ try {+++ const skillErrors = new SkillError();+ const checkConnections = () => {+ let connections = this.workspace.jsPlumbInstance+ .getAllConnections()+ .map((connection) => {+ const source = connection.source;+ const target = connection.target;+ const sourceComponent = source.closest('.component');+ const targetComponent = target.closest('.component');++ if (!sourceComponent || !targetComponent) return null; //exclude connections that are not connected to components, these can be used for other visual stuff+ return {+ sourceId: source.closest('.component').id,+ sourceIndex: [...source.parentElement.querySelectorAll('.output-endpoint')].findIndex(+ (c) => c === source,+ ),+ targetId: target.closest('.component').id,+ targetIndex: [...target.parentElement.querySelectorAll('.input-endpoint')].findIndex(+ (r) => r === target,+ ),+ };+ })+ .filter((c) => c);+ const sourceConnections = connections.filter((c) => c.sourceId === this.uid);++ // if no connections, then we need to add a default connection+ if (sourceConnections.length === 0) {+ skillErrors.addError({+ error_slug: 'missing_connection',+ error_message:+ 'Tip: Add or connect components to bring your workflow to life. Components work together seamlessly to create a powerful, intuitive agent experience.',+ });+ } else {+ skillErrors.removeError('missing_connection');}+ };+ this.workspace.jsPlumbInstance.bind('connection', debounce(checkConnections, 100));+ this.workspace.jsPlumbInstance.bind('connectionDetached', debounce(checkConnections, 100));++ checkConnections();++ const checkSettingsErr = () => {+ let connections = this.workspace.jsPlumbInstance+ .getAllConnections()+ .map((connection) => {+ const source = connection.source;+ const target = connection.target;+ const sourceComponent = source.closest('.component');+ const targetComponent = target.closest('.component');++ if (!sourceComponent || !targetComponent) return null; //exclude connections that are not connected to components, these can be used for other visual stuff+ return {+ sourceId: source.closest('.component').id,+ sourceIndex: [...source.parentElement.querySelectorAll('.output-endpoint')].findIndex(+ (c) => c === source,+ ),+ targetId: target.closest('.component').id,+ targetIndex: [...target.parentElement.querySelectorAll('.input-endpoint')].findIndex(+ (r) => r === target,+ ),+ };+ })+ .filter((c) => c);++ // BFS to see if any node has an error+ // Using Set for O(1) lookup (cycle check is done before getSkillErrors is called)+ let hasError = false;+ let compsToVisit = [this.uid];+ const visited = new Set<string>();+ while (compsToVisit.length > 0) {+ let cId = compsToVisit.shift();+ if (!cId) continue;++ // Skip if already visited+ if (visited.has(cId)) continue;+ visited.add(cId);++ const cmpCtrl = (document.querySelector(`.component#${cId}`) as Element & { _control?: Component })?.['_control'];+ if (!cmpCtrl) continue;++ // Check settings for required fields+ const requiredSettings: Array<{ id: string; name: string }> = [];+ for (const settingId in cmpCtrl.settings) {+ const setting = cmpCtrl.settings[settingId];+ if (setting.validate?.includes('required')) {+ requiredSettings.push({ id: settingId, name: setting.label ?? settingId });+ }+ }- const missingSettings = requiredSettings.filter((setting) => !cmpCtrl.data[setting.id]);-- if (missingSettings.length > 0) {- hasError = true;- // if there an error, listen on cmp settingsSaved event to re-trigger the check- const listener = () => {- checkSettingsErr();- cmpCtrl.off('settingsSaved', listener);- };- cmpCtrl.on('settingsSaved', listener);- break;- }+ const missingSettings = requiredSettings.filter((setting) => !cmpCtrl.data[setting.id]);++ if (missingSettings.length > 0) {+ hasError = true;+ // if there an error, listen on cmp settingsSaved event to re-trigger the check+ const listener = () => {+ checkSettingsErr();+ cmpCtrl.off('settingsSaved', listener);+ };+ cmpCtrl.on('settingsSaved', listener);+ break;+ }- // add connected- const connectedCmpIds = connections- .filter((c) => c.sourceId === cId && !visited.includes(c.targetId))- .map((c) => c.targetId);- compsToVisit.push(...connectedCmpIds);- }+ // Add connected component IDs (deduplicated)+ const connectedCmpIds = [+ ...new Set(+ connections+ .filter((c) => c.sourceId === cId && !visited.has(c.targetId))+ .map((c) => c.targetId),+ ),+ ];+ compsToVisit.push(...connectedCmpIds);+ }- if (hasError) {- skillErrors.addError({- error_slug: 'connected_components_settings_err',- error_message:- 'Tip: resolve missing information from components (the red boxes) first, otherwise the agent will get stuck at that step and not return anything useful.',- });- } else {- skillErrors.removeError('connected_components_settings_err');- }- };+ if (hasError) {+ skillErrors.addError({+ error_slug: 'connected_components_settings_err',+ error_message:+ 'Tip: resolve missing information from components (the red boxes) first, otherwise the agent will get stuck at that step and not return anything useful.',+ });+ } else {+ skillErrors.removeError('connected_components_settings_err');+ }+ };- checkSettingsErr();+ checkSettingsErr();- return skillErrors;+ return skillErrors;+ } catch (error) {+ console.log('error', error);+ return null;+ }}public redraw(triggerSettings?: boolean): any {diff --git a/packages/app/src/builder-ui/workspace/ComponentSort.ts b/packages/app/src/builder-ui/workspace/ComponentSort.tsindex 36967c14..e5d9548e 100644--- a/packages/app/src/builder-ui/workspace/ComponentSort.ts+++ b/packages/app/src/builder-ui/workspace/ComponentSort.ts@@ -4,6 +4,45 @@ import { delay } from '../utils';declare var workspace: any;let isSorting = false;+/**+ * Detects if there's a cycle in the graph starting from the given node.+ * Uses DFS with recursion stack tracking to detect back-edges.+ * @param startId - The node ID to start the cycle detection from+ * @param graph - Adjacency list representation of the graph (Map with Set or Array values)+ * @returns true if a cycle is detected, false otherwise+ */+export function hasGraphCycle(+ startId: string,+ graph: Map<string, Set<string> | string[]>,+): boolean {+ const visited = new Set<string>();+ const inStack = new Set<string>();++ const dfs = (nodeId: string): boolean => {+ if (inStack.has(nodeId)) {+ return true; // Cycle detected (back-edge found)+ }+ if (visited.has(nodeId)) {+ return false; // Already processed, no cycle from this path+ }++ visited.add(nodeId);+ inStack.add(nodeId);++ const neighbors = graph.get(nodeId) ?? [];+ for (const neighbor of neighbors) {+ if (dfs(neighbor)) {+ return true;+ }+ }++ inStack.delete(nodeId);+ return false;+ };++ return dfs(startId);+}+/** Bounding box type for elements */interface Bounds {left: number;@@ -281,6 +320,7 @@ export async function extractWorkflows(data) {const { components, connections } = data;// Build adjacency list for graph representation+ // Note: Uses arrays and initializes all component IDs for level calculationfunction buildGraph() {const graph = new Map();components.forEach((component) => {@@ -296,41 +336,11 @@ export async function extractWorkflows(data) {return graph;}- // Check if the graph has a cycle starting from a given node- function hasCycle(startId, graph) {- const visited = new Set();- const inStack = new Set();-- function dfs(nodeId) {- if (inStack.has(nodeId)) {- return true; // Cycle detected- }- if (visited.has(nodeId)) {- return false; // Already processed, no cycle from this path- }-- visited.add(nodeId);- inStack.add(nodeId);-- const neighbors = graph.get(nodeId) || [];- for (const neighbor of neighbors) {- if (dfs(neighbor)) {- return true;- }- }-- inStack.delete(nodeId);- return false;- }-- return dfs(startId);- }-// Perform Topological Sort and Calculate Levels// Throws an error if a cycle is detectedfunction calculateLevels(startId, graph) {// Check for cycles first - if found, throw error- const _hasCycle = hasCycle(startId, graph);+ const _hasCycle = hasGraphCycle(startId, graph);if (_hasCycle) {throw new Error('Circular dependency detected in the workflow');