Skip to content

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.

triggers update Component : add checkConnectivity function and input/output editor ready events APIEndpoint connections validity fixes

alaa-eddinecf0b880bb4bd
diff --git a/packages/app/src/backend/routes/api/page/builder.ts b/packages/app/src/backend/routes/api/page/builder.ts
index 300f05bf..722d335d 100644
--- a/packages/app/src/backend/routes/api/page/builder.ts
+++ b/packages/app/src/backend/routes/api/page/builder.ts
@@ -1361,15 +1361,16 @@ router.post('/trigger/:id/register', async (req, res) => {
const { id } = req.params;
const { payload } = req.body;
- const url = `${config.env.API_SERVER}/trigger/${id}/register`;
+ const url = `${config.env.API_SERVER}/user/trigger/${id}/register`;
const headers = {
'X-AGENT-ID': req.headers['x-agent-id'],
+ ...(await authHeaders(req)), //add auth headers
};
console.log('trigger register url', url, headers);
- const result: any = await axios.post(url, { ...payload }, { headers });
+ const result: any = await axios.post(url, { ...payload }, headers);
console.log('>>> trigger register result', result.data);
diff --git a/packages/app/src/backend/routes/pages/builder-sidebar.ts b/packages/app/src/backend/routes/pages/builder-sidebar.ts
index 908fd655..c72c093e 100644
--- a/packages/app/src/backend/routes/pages/builder-sidebar.ts
+++ b/packages/app/src/backend/routes/pages/builder-sidebar.ts
@@ -94,11 +94,11 @@ const baseMenu: Menu = {
],
//hide triggers for now
- Triggers: [
- { name: 'GmailTrigger', label: 'Gmail Trigger', description: '' },
- { name: 'WhatsAppTrigger', label: 'Whatsapp Trigger', description: '' },
- { name: 'JobSchedulerTrigger', label: 'Job Scheduler Trigger', description: '' },
- ],
+ // Triggers: [
+ // { name: 'GmailTrigger', label: 'Gmail Trigger', description: '' },
+ // { name: 'WhatsAppTrigger', label: 'Whatsapp Trigger', description: '' },
+ // { name: 'JobSchedulerTrigger', label: 'Job Scheduler Trigger', description: '' },
+ // ],
Integrations: [],
};
diff --git a/packages/app/src/builder-ui/components/APIEndpoint.class.ts b/packages/app/src/builder-ui/components/APIEndpoint.class.ts
index 0c4cb5c1..d234cd58 100644
--- a/packages/app/src/builder-ui/components/APIEndpoint.class.ts
+++ b/packages/app/src/builder-ui/components/APIEndpoint.class.ts
@@ -3,7 +3,7 @@ import { debounce } from 'lodash-es';
import { EMBODIMENT_DESCRIPTIONS } from '../../shared/constants/general';
import EventEmitter from '../EventEmitter.class';
import { openEmbodimentDialog } from '../pages/builder/agent-settings';
-import { confirm } from '../ui/dialogs';
+import { alert, confirm } from '../ui/dialogs';
import { renderEndpointFormPreviewSidebar } from '../ui/react-injects';
import { delay } from '../utils';
import { Component } from './Component.class';
@@ -491,7 +491,8 @@ export class APIEndpoint extends Component {
if (prop === 'name') {
const oldName = oldValue;
const newName = newValue;
- const newOutputName = `_.${newName}`;
+ //const newOutputName = `_.${newName}`;
+ const newOutputName = newName;
const inputName = inputDiv.getAttribute('smt-name');
const outputName = outputDiv.getAttribute('smt-name');
@@ -564,7 +565,8 @@ export class APIEndpoint extends Component {
const outputDiv: any = await super.addOutput(
outputParent,
- `_.${name}`,
+ //`_.${name}`,
+ name,
{
expression: `body.${name}`,
},
@@ -984,4 +986,21 @@ export class APIEndpoint extends Component {
// Sync default values after redraw
setTimeout(() => this.syncAllDefaultValues(), 100);
}
+
+ checkConnValidity(info: any) {
+ console.log('checkConnValidity', info);
+ const sourceDomComponent = info.source.closest('.component');
+ const targetDomComponent = info.target.closest('.component');
+ if (!sourceDomComponent || !targetDomComponent) return false;
+ if (!sourceDomComponent.classList.contains('agent-card')) {
+ alert(
+ 'Unsupported Connection',
+ 'Skills can only be connected to the agent card',
+ 'OK',
+ 'error',
+ );
+ return false;
+ }
+ return true;
+ }
}
diff --git a/packages/app/src/builder-ui/components/Component.class/index.ts b/packages/app/src/builder-ui/components/Component.class/index.ts
index 45055abf..d0acfff0 100644
--- a/packages/app/src/builder-ui/components/Component.class/index.ts
+++ b/packages/app/src/builder-ui/components/Component.class/index.ts
@@ -427,6 +427,10 @@ export class Component extends EventEmitter {
}, 15);
});
}
+
+ checkConnValidity(info: any) {
+ return true;
+ }
protected async repaint(redrawConnectors = false) {
if (redrawConnectors) {
let connections = [...this.domElement.querySelectorAll('.endpoint')]
@@ -857,6 +861,7 @@ export class Component extends EventEmitter {
const propSettings = this.outputSettings[propName];
switch (propSettings?.type) {
+ case 'text':
case 'string':
return outputProps?.[propName] || propSettings?.default || _default;
case 'number':
@@ -867,7 +872,8 @@ export class Component extends EventEmitter {
}
public async addOutput(parent, name, outputProperties: any = {}, options: any = {}) {
if (this.outputNameExists(name)) {
- errorToast(`${name} already exists`);
+ errorToast(`Output "${name}" already exists`);
+ console.warn(`Output "${name}" already exists`, this);
return;
}
const jsPlumbInstance = this.workspace.jsPlumbInstance;
@@ -994,6 +1000,7 @@ export class Component extends EventEmitter {
: '<span class="text-xl">Edit Output</span>';
const orderedValConfig = getOrderedValConfig(valConfig, [
+ 'name',
'description',
'expression',
'additionalOptionsLabel',
@@ -1015,7 +1022,7 @@ export class Component extends EventEmitter {
titleElm.appendChild(buttonElm);
}
- this.emit('inputEditorReady', dialog);
+ this.emit('outputEditorReady', dialog);
// requires a tiny delay to make sure the input is focused
delay(50).then(() => focusField(nameElm));
@@ -1184,6 +1191,7 @@ export class Component extends EventEmitter {
switch (propSettings?.type) {
case 'string':
+ case 'text':
return inputProps?.[propName] || propSettings?.default || _default;
case 'number':
return inputProps?.[propName] || propSettings?.default || _default;
@@ -1194,7 +1202,8 @@ export class Component extends EventEmitter {
public async addInput(parent, name, inputProperties: any = {}) {
if (this.inputNameExists(name)) {
- errorToast(`${name} already exists`);
+ errorToast(`Input "${name}" already exists`);
+ console.warn(`Input "${name}" already exists`, this);
return;
}
const jsPlumbInstance: any = this.workspace.jsPlumbInstance;
@@ -2891,6 +2900,7 @@ export class Component extends EventEmitter {
: '<span class="text-xl">Add Output</span>';
const orderedValConfig = getOrderedValConfig(valConfig, [
+ 'name',
'description',
'expression',
'additionalOptionsLabel',
@@ -2912,7 +2922,7 @@ export class Component extends EventEmitter {
titleElm.appendChild(buttonElm);
}
- this.emit('inputEditorReady', dialog);
+ this.emit('outputEditorReady', dialog);
// requires a tiny delay to make sure the input is focused
delay(50).then(() => focusField(nameElm));
diff --git a/packages/app/src/builder-ui/components/Triggers/Gmail.trigger.ts b/packages/app/src/builder-ui/components/Triggers/Gmail.trigger.ts
index e42b61d5..8e13003d 100644
--- a/packages/app/src/builder-ui/components/Triggers/Gmail.trigger.ts
+++ b/packages/app/src/builder-ui/components/Triggers/Gmail.trigger.ts
@@ -70,6 +70,23 @@ export class GmailTrigger extends Trigger {
...this.oauth?.configure(),
};
+ // this.properties.defaultOutputs = [
+ // 'Payload',
+ // 'id',
+ // 'headers.subject',
+ // 'body.text',
+ // 'attachments',
+ // 'isUnread',
+ // ];
+ // for (let output of this.properties.defaultOutputs) {
+ // this.properties.outputProps.push({
+ // name: output,
+ // type: 'string',
+ // color: '#95f562',
+ // expression: output == 'Payload' ? 'Payload' : `Payload.email.${output}`,
+ // });
+ // }
+
this.drawSettings.icon = `/img/triggers/gmail.svg`;
this.drawSettings.color = '#00ff00';
diff --git a/packages/app/src/builder-ui/components/Triggers/JobScheduler.trigger.ts b/packages/app/src/builder-ui/components/Triggers/JobScheduler.trigger.ts
index aba87392..322dba31 100644
--- a/packages/app/src/builder-ui/components/Triggers/JobScheduler.trigger.ts
+++ b/packages/app/src/builder-ui/components/Triggers/JobScheduler.trigger.ts
@@ -1,3 +1,5 @@
+import { COMP_NAMES } from '@src/builder-ui/config';
+import { handleKvFieldEditBtn } from '@src/builder-ui/utils';
import { oAuthSettings } from '../../helpers/oauth/oauth-settings.helper';
import { Trigger } from './Trigger.class';
@@ -11,9 +13,7 @@ declare var Metro;
* for better separation of concerns and reusability.
*/
export class JobSchedulerTrigger extends Trigger {
- public schema: any = {
- job: 'object',
- };
+ public schema: any = {};
private oauth: oAuthSettings | undefined;
protected async init(): Promise<void> {
@@ -23,16 +23,39 @@ export class JobSchedulerTrigger extends Trigger {
this.settings = {
...this.settings,
interval: {
- type: 'range',
+ type: 'input',
label: 'Interval',
min: 1,
max: 720,
value: 5,
step: 1,
- validate: 'min=1 max=720',
+ validate: 'required min=1 max=720',
validateMessage: 'Allowed range 1 to 720',
desc: 'Interval in minutes',
},
+ payload: {
+ type: 'textarea',
+ label: 'Job Parameters',
+ readonly: true,
+ help: 'Use this to configure your job with custom parameters to pass to your workflow',
+ tooltipClasses: 'w-64',
+ arrowClasses: '-ml-13',
+ validate: `custom=isValidJson`,
+ validateMessage: 'Provide a Valid JSON with non-empty keys',
+ actions: [
+ {
+ label: '',
+ icon: 'fa-regular fa-pen-to-square',
+ id: 'editPayload',
+ events: {
+ click: handleKvFieldEditBtn.bind(this, 'payload', {
+ showVault: true,
+ vaultScope: COMP_NAMES.apiCall,
+ }),
+ },
+ },
+ ],
+ },
};
this.drawSettings.icon = `/img/triggers/job-scheduler.svg`;
@@ -52,4 +75,38 @@ export class JobSchedulerTrigger extends Trigger {
destroy(): void {
super.destroy?.();
}
+
+ protected async run(): Promise<any> {
+ super.run();
+ //get the jobScheduler schema from the payload field
+ const payload = this.data.payload || '{}';
+ this.schema = JSON.parse(payload);
+
+ this.addEventListener('settingsSaved', async (settingsValues) => {
+ //first update the jobScheduler schema
+ // Job scheduler schema is dynamic, and is used to provide Trigger variables to the trigger outputs
+ //we need to read it from the payload field
+ const payload = settingsValues.payload || '{}';
+ this.schema = JSON.parse(payload);
+
+ /*
+ await this.workspace.waitServerData();
+ await this.workspace.saveAgent();
+ const base = this.workspace.serverData.frontUrl;
+ const id = this.uid;
+ const url = `${base}/api/page/builder/trigger/${id}/register`;
+ //const result: any = await axios.post(url, { data: '123' });
+ const headers = {
+ 'X-AGENT-ID': this.workspace.agent.id,
+ };
+ const result: any = await fetch(url, {
+ method: 'POST',
+ body: JSON.stringify({ data: '123' }),
+ headers,
+ });
+ const json = await result.json();
+ console.log('JobSchedulerTrigger result', json);
+ */
+ });
+ }
}
diff --git a/packages/app/src/builder-ui/components/Triggers/Trigger.class.ts b/packages/app/src/builder-ui/components/Triggers/Trigger.class.ts
index 73c72cfb..4ba4d0cd 100644
--- a/packages/app/src/builder-ui/components/Triggers/Trigger.class.ts
+++ b/packages/app/src/builder-ui/components/Triggers/Trigger.class.ts
@@ -13,6 +13,29 @@ export class Trigger extends Component {
},
};
+ this.outputSettings = {
+ ...this.outputSettings,
+ expression: {
+ type: 'text',
+ label: 'Field Mapping',
+ editConfig: {
+ validate: 'required custom=isValidOutputName',
+ validateMessage: `Field Mapping is required for triggers, Use a valid JSON path notation, e.g., Payload.id, Payload.name, etc.`,
+
+ // fieldCls:
+ // 'bg-white border text-gray-900 rounded block w-full outline-none focus:outline-none focus:ring-0 focus:ring-offset-0 focus:ring-shadow-none text-sm font-normal placeholder:text-sm placeholder:font-normal py-2 px-3 transition-all duration-150 ease-in-out border-gray-300 border-b-gray-500 focus:border-b-2 focus:border-b-blue-500 focus-visible:border-b-2 focus-visible:border-b-blue-500',
+ attributes: {
+ 'data-trigger-vars': 'true',
+ 'data-auto-size': 'true',
+ rows: '2',
+ placeholder: `Map the triggers variables to this input`,
+ }, // Enable auto-size for consistent UX with 2-line default
+ //section: 'Advanced_Options',
+ hintPosition: 'after_label',
+ },
+ },
+ };
+
// #region [ I/O config ] ==================
this.properties.defaultOutputs = ['Payload'];
this.properties.defaultInputs = [];
@@ -26,9 +49,9 @@ export class Trigger extends Component {
// #region [ Draw config ] ==================
- this.drawSettings.addOutputButton = null;
+ //this.drawSettings.addOutputButton = null;
this.drawSettings.addInputButton = null;
- this.drawSettings.addOutputButtonLabel = '';
+ this.drawSettings.addOutputButtonLabel = ' ';
this.drawSettings.addInputButtonLabel = '';
this.drawSettings.componentDescription = ' ';
@@ -37,6 +60,25 @@ export class Trigger extends Component {
// #endregion
}
+ protected async run(): Promise<any> {
+ this.addEventListener('outputEditorReady', (dialog) => {
+ console.log('outputEditorReady', dialog);
+
+ const triggerName = dialog.querySelector('.form-box [name="name"]');
+ if (triggerName) {
+ //ensure that the trigger name is available in the expression
+ triggerName.setAttribute('data-triggers', this.uid);
+ }
+
+ //try to find the triggerExpression field by name
+ const triggerExpression = dialog.querySelector('.form-box [name="expression"]');
+ if (triggerExpression) {
+ //ensure that the trigger variables are available in the expression
+ triggerExpression.setAttribute('data-triggers', this.uid);
+ }
+ });
+ }
+
public redraw(triggerSettings?: boolean): any {
super.redraw(triggerSettings);
@@ -44,10 +86,35 @@ export class Trigger extends Component {
this.domElement.classList.add('Trigger');
this.domElement.setAttribute('smt-trigger', '');
+ //bind trigger variables
+
// const _ResultOutput = document.createElement('div');
// _ResultOutput.className = 'smyth endpoint output-endpoint GmailTrigger';
// _ResultOutput.setAttribute('smt-name', 'Result');
// _ResultOutput.innerHTML = `<span class="name"><span class="label">Result</span></span>`;
// this.outputContainer.appendChild(_ResultOutput);
+
+ const toggleOutputContainer = document.createElement('button');
+ toggleOutputContainer.className = 'toggle-output-container';
+ const toggleIcon = document.createElement('i');
+ toggleIcon.className = this.domElement.classList.contains('collapsed')
+ ? 'fa-solid fa-chevron-right text-gray-300'
+ : 'fa-solid fa-chevron-left text-gray-300';
+
+ toggleOutputContainer.appendChild(toggleIcon);
+ toggleOutputContainer.onclick = (event: MouseEvent) => {
+ event.stopPropagation();
+ event.stopImmediatePropagation();
+ event.preventDefault();
+ this.domElement.classList.toggle('collapsed');
+ if (this.domElement.classList.contains('collapsed')) {
+ toggleIcon.className = 'fa-solid fa-chevron-right text-gray-300';
+ } else {
+ toggleIcon.className = 'fa-solid fa-chevron-left text-gray-300';
+ }
+
+ this.repaint();
+ };
+ this.outputContainer.appendChild(toggleOutputContainer);
}
}
diff --git a/packages/app/src/builder-ui/ui/form/misc.ts b/packages/app/src/builder-ui/ui/form/misc.ts
index fd75e30d..8b5ada3f 100644
--- a/packages/app/src/builder-ui/ui/form/misc.ts
+++ b/packages/app/src/builder-ui/ui/form/misc.ts
@@ -373,7 +373,10 @@ export function handleTemplateVars(targetElm, component = null) {
!clickedElm?.hasAttribute('readonly')
) {
console.log('clicked elm', clickedElm);
- const triggersList = clickedElm.getAttribute('data-triggers')?.split(',');
+ let dataTriggers = clickedElm.getAttribute('data-triggers');
+ if (!dataTriggers) return;
+
+ const triggersList = Array.isArray(dataTriggers) ? dataTriggers.split(',') : [dataTriggers];
const triggersSchema = triggersList.map((triggerId) => {
const component = document.getElementById(triggerId);
const control = (component as any)?._control;
@@ -407,7 +410,7 @@ function extractTriggerVariables(schema: any, path = '') {
for (const key in schema) {
const fullPath = `${path?.trim() ? `${path}.` : ''}${key}`;
- variables.set(fullPath, { var: `{{${fullPath}}}`, type: 'trigger' });
+ variables.set(fullPath, { var: `${fullPath}`, type: 'trigger' });
if (typeof schema[key] === 'object') {
const nestedVariables = extractTriggerVariables(schema[key], fullPath);
for (const [nestedKey, nestedValue] of nestedVariables) {
diff --git a/packages/app/src/builder-ui/workspace/Workspace.class.ts b/packages/app/src/builder-ui/workspace/Workspace.class.ts
index e4bb0f2a..2e10379a 100644
--- a/packages/app/src/builder-ui/workspace/Workspace.class.ts
+++ b/packages/app/src/builder-ui/workspace/Workspace.class.ts
@@ -248,8 +248,8 @@ export class Workspace extends EventEmitter {
if (conflict) this.jsPlumbInstance.deleteConnection(info.connection);
- const agentCardValid = AgentCard.checkConnValidity(info);
- if (!agentCardValid) this.jsPlumbInstance.deleteConnection(info.connection);
+ // const agentCardValid = AgentCard.checkConnValidity(info);
+ // if (!agentCardValid) this.jsPlumbInstance.deleteConnection(info.connection);
//! SHOULDN'T WE ABORT EARLY IF THERE WAS A CONFLICT!!?? I feel like it aborts and works correctly
//! but cannot detect how and where does it abort if a conflict or non-valid conn was detected
@@ -257,6 +257,12 @@ export class Workspace extends EventEmitter {
const sourceComponent = info.source.closest('.component')?._control;
const targetComponent = info.target.closest('.component')?._control;
+ const validSourceConn = sourceComponent?.checkConnValidity(info);
+ if (!validSourceConn) this.jsPlumbInstance.deleteConnection(info.connection);
+
+ const validTargetConn = targetComponent?.checkConnValidity(info);
+ if (!validTargetConn) this.jsPlumbInstance.deleteConnection(info.connection);
+
sourceComponent?.emit(
'connectionAttached',
info.source.getAttribute('smt-name'),
@@ -1382,16 +1388,7 @@ export class Workspace extends EventEmitter {
);
}
} else {
- //handle the special case of triggers connecting to APIEndpoints
-
- if (
- sourceComponent.classList.contains('Trigger') &&
- targetComponent.classList.contains('APIEndpoint')
- ) {
- targetEndpoint = targetComponent.querySelector(`.endpoint-connection`);
- } else {
- targetEndpoint = [...targetComponent.querySelectorAll(`.input-endpoint`)][targetEndpointID];
- }
+ targetEndpoint = [...targetComponent.querySelectorAll(`.input-endpoint`)][targetEndpointID];
}
// @ts-ignore