File size: 26,250 Bytes
5da4770 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 | 'use client';
import React, { useState, useCallback, useMemo } from 'react';
import {
Plus,
Trash2,
AlertTriangle,
ChevronsUpDown,
Check,
MoreHorizontal
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';
import { cn } from '@/lib/utils';
import { Input } from '@/components/ui/input';
export interface ConditionalStep {
id: string;
name: string;
description: string;
type: 'instruction' | 'condition' | 'parallel' | 'sequence';
config: Record<string, any>;
conditions?: {
type: 'if' | 'else' | 'elseif';
expression?: string;
};
children?: ConditionalStep[];
order: number;
enabled?: boolean;
hasIssues?: boolean;
}
interface ConditionalWorkflowBuilderProps {
steps: ConditionalStep[];
onStepsChange: (steps: ConditionalStep[]) => void;
agentTools?: {
agentpress_tools: Array<{ name: string; description: string; icon?: string; enabled: boolean }>;
mcp_tools: Array<{ name: string; description: string; icon?: string; server?: string }>;
};
isLoadingTools?: boolean;
}
const normalizeToolName = (toolName: string, toolType: 'agentpress' | 'mcp') => {
if (toolType === 'agentpress') {
const agentPressMapping: Record<string, string> = {
'sb_shell_tool': 'Shell Tool',
'sb_files_tool': 'Files Tool',
'sb_browser_tool': 'Browser Tool',
'sb_deploy_tool': 'Deploy Tool',
'sb_expose_tool': 'Expose Tool',
'web_search_tool': 'Web Search',
'sb_vision_tool': 'Vision Tool',
'data_providers_tool': 'Data Providers',
};
return agentPressMapping[toolName] || toolName;
} else {
return toolName
.split('_')
.map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
.join(' ');
}
};
export function ConditionalWorkflowBuilder({
steps,
onStepsChange,
agentTools,
isLoadingTools
}: ConditionalWorkflowBuilderProps) {
const [toolSearchOpen, setToolSearchOpen] = useState<{[key: string]: boolean}>({});
const [activeConditionTab, setActiveConditionTab] = useState<{[key: string]: string}>({});
steps.forEach((step, index) => {
console.log(`Step ${index}:`, {
name: step.name,
type: step.type,
hasChildren: !!step.children,
childrenCount: step.children?.length || 0,
children: step.children?.map(child => ({ name: child.name, type: child.type }))
});
});
const generateId = () => Math.random().toString(36).substr(2, 9);
const addStep = useCallback((parentId?: string, afterStepId?: string) => {
const newStep: ConditionalStep = {
id: generateId(),
name: 'Step',
description: '',
type: 'instruction',
config: {},
order: 0,
enabled: true,
};
const updateSteps = (items: ConditionalStep[]): ConditionalStep[] => {
if (!parentId) {
if (afterStepId) {
const index = items.findIndex(s => s.id === afterStepId);
return [...items.slice(0, index + 1), newStep, ...items.slice(index + 1)];
}
return [...items, newStep];
}
return items.map(step => {
if (step.id === parentId) {
return {
...step,
children: [...(step.children || []), newStep]
};
}
if (step.children) {
return {
...step,
children: updateSteps(step.children)
};
}
return step;
});
};
onStepsChange(updateSteps(steps));
}, [steps, onStepsChange]);
const addCondition = useCallback((afterStepId: string) => {
const ifStep: ConditionalStep = {
id: generateId(),
name: 'If',
description: '',
type: 'condition',
config: {},
conditions: { type: 'if', expression: '' },
children: [],
order: 0,
enabled: true,
hasIssues: true
};
const updateSteps = (items: ConditionalStep[]): ConditionalStep[] => {
const index = items.findIndex(s => s.id === afterStepId);
if (index !== -1) {
return [
...items.slice(0, index + 1),
ifStep,
...items.slice(index + 1)
];
}
return items.map(step => {
if (step.children) {
return {
...step,
children: updateSteps(step.children)
};
}
return step;
});
};
onStepsChange(updateSteps(steps));
}, [steps, onStepsChange]);
const addElseCondition = useCallback((siblingId: string) => {
const elseIfStep: ConditionalStep = {
id: generateId(),
name: 'Else If',
description: '',
type: 'condition',
config: {},
conditions: { type: 'elseif', expression: '' },
children: [],
order: 0,
enabled: true,
hasIssues: true
};
const updateSteps = (items: ConditionalStep[]): ConditionalStep[] => {
const index = items.findIndex(s => s.id === siblingId);
if (index !== -1) {
return [
...items.slice(0, index + 1),
elseIfStep,
...items.slice(index + 1)
];
}
return items.map(step => {
if (step.children) {
return {
...step,
children: updateSteps(step.children)
};
}
return step;
});
};
onStepsChange(updateSteps(steps));
}, [steps, onStepsChange]);
const addFinalElse = useCallback((siblingId: string) => {
const elseStep: ConditionalStep = {
id: generateId(),
name: 'Else',
description: '',
type: 'condition',
config: {},
conditions: { type: 'else' },
children: [],
order: 0,
enabled: true,
hasIssues: false
};
const updateSteps = (items: ConditionalStep[]): ConditionalStep[] => {
const index = items.findIndex(s => s.id === siblingId);
if (index !== -1) {
return [
...items.slice(0, index + 1),
elseStep,
...items.slice(index + 1)
];
}
return items.map(step => {
if (step.children) {
return {
...step,
children: updateSteps(step.children)
};
}
return step;
});
};
onStepsChange(updateSteps(steps));
}, [steps, onStepsChange]);
const updateStep = useCallback((stepId: string, updates: Partial<ConditionalStep>) => {
const updateSteps = (items: ConditionalStep[]): ConditionalStep[] => {
return items.map(step => {
if (step.id === stepId) {
const updatedStep = { ...step, ...updates };
if (updatedStep.type === 'instruction' && updatedStep.name && updatedStep.name !== 'New Step') {
updatedStep.hasIssues = false;
} else if (updatedStep.type === 'condition' &&
(updatedStep.conditions?.type === 'if' || updatedStep.conditions?.type === 'elseif') &&
updatedStep.conditions?.expression) {
updatedStep.hasIssues = false;
} else if (updatedStep.type === 'condition' && updatedStep.conditions?.type === 'else') {
updatedStep.hasIssues = false;
}
return updatedStep;
}
if (step.children) {
return {
...step,
children: updateSteps(step.children)
};
}
return step;
});
};
onStepsChange(updateSteps(steps));
}, [steps, onStepsChange]);
const removeStep = useCallback((stepId: string) => {
const removeFromSteps = (items: ConditionalStep[]): ConditionalStep[] => {
return items
.filter(step => step.id !== stepId)
.map(step => {
if (step.children) {
return {
...step,
children: removeFromSteps(step.children)
};
}
return step;
});
};
onStepsChange(removeFromSteps(steps));
}, [steps, onStepsChange]);
const getStepNumber = useCallback((stepId: string, items: ConditionalStep[] = steps, counter = { value: 0 }): number => {
for (const step of items) {
counter.value++;
if (step.id === stepId) {
return counter.value;
}
if (step.children && step.children.length > 0) {
const found = getStepNumber(stepId, step.children, counter);
if (found > 0) return found;
}
}
return 0;
}, [steps]);
const getConditionLetter = (index: number) => {
return String.fromCharCode(65 + index);
};
const renderConditionTabs = (conditionSteps: ConditionalStep[], groupKey: string) => {
const activeTabId = activeConditionTab[groupKey] || conditionSteps[0]?.id;
const activeStep = conditionSteps.find(s => s.id === activeTabId) || conditionSteps[0];
const hasElse = conditionSteps.some(step => step.conditions?.type === 'else');
const handleKeyDown = (e: React.KeyboardEvent, step: ConditionalStep) => {
if (e.key === 'Backspace' || e.key === 'Delete') {
e.preventDefault();
if (conditionSteps.length > 1 && !(conditionSteps.length === 1 && step.conditions?.type === 'if')) {
removeStep(step.id);
const remainingConditions = conditionSteps.filter(s => s.id !== step.id);
if (remainingConditions.length > 0) {
setActiveConditionTab(prev => ({ ...prev, [groupKey]: remainingConditions[0].id }));
}
}
}
};
return (
<div className="space-y-4">
<div className="flex items-center gap-2">
{conditionSteps.map((step, index) => {
const letter = getConditionLetter(index);
const isActive = step.id === activeTabId;
const conditionType = step.conditions?.type === 'if' ? 'If' :
step.conditions?.type === 'elseif' ? 'Else If' :
step.conditions?.type === 'else' ? 'Else' : 'If';
return (
<button
key={step.id}
onClick={() => setActiveConditionTab(prev => ({ ...prev, [groupKey]: step.id }))}
onKeyDown={(e) => handleKeyDown(e, step)}
tabIndex={0}
className={cn(
"flex items-center gap-2 px-3 py-2 rounded-md border text-sm font-medium transition-all",
isActive
? "bg-primary text-primary-foreground border-primary shadow-sm"
: "bg-background border-border text-foreground hover:bg-accent hover:text-accent-foreground"
)}
>
<span className="font-mono text-xs">{letter}</span>
<span>•</span>
<span>{conditionType}</span>
{step.hasIssues && (
<AlertTriangle className="h-3 w-3 text-destructive" />
)}
</button>
);
})}
{!hasElse && (
<Button
variant="outline"
size="sm"
onClick={() => addElseCondition(conditionSteps[conditionSteps.length - 1].id)}
className="h-9 px-3 border-dashed text-xs"
>
<Plus className="h-3 w-3 mr-1" />
Else If
</Button>
)}
{!hasElse && (
<Button
variant="outline"
size="sm"
onClick={() => addFinalElse(conditionSteps[conditionSteps.length - 1].id)}
className="h-9 px-3 border-dashed text-xs"
>
<Plus className="h-3 w-3 mr-1" />
Else
</Button>
)}
</div>
{activeStep && (
<div className="bg-muted/50 rounded-lg p-4 border">
{(activeStep.conditions?.type === 'if' || activeStep.conditions?.type === 'elseif') ? (
<div className="space-y-3">
<Label className="text-sm font-medium">
{activeStep.conditions?.type === 'if' ? 'Condition' : 'Else If Condition'}
</Label>
<Input
type="text"
value={activeStep.conditions.expression || ''}
onChange={(e) => updateStep(activeStep.id, {
conditions: { ...activeStep.conditions, expression: e.target.value }
})}
placeholder="e.g., user asks about pricing"
className="w-full bg-transparent text-sm px-3 py-2 rounded-md"
/>
</div>
) : (
<div className="text-sm text-muted-foreground font-medium">
Otherwise (fallback condition)
</div>
)}
<div className="mt-4 space-y-3">
{activeStep.children && activeStep.children.length > 0 && (
<>
{activeStep.children.map((child, index) => renderStep(child, index + 1, true, activeStep.id))}
</>
)}
<div className="flex justify-center pt-2">
<Button
variant="outline"
size="sm"
onClick={() => addStep(activeStep.id)}
className="border-dashed text-xs"
>
<Plus className="h-3 w-3" />
Add step
</Button>
</div>
</div>
</div>
)}
</div>
);
};
const renderStep = (step: ConditionalStep, stepNumber: number, isNested: boolean = false, parentId?: string) => {
const isCondition = step.type === 'condition';
const isSequence = step.type === 'sequence';
if (isCondition) {
return null;
}
return (
<div key={step.id} className="group">
<div className="bg-card rounded-lg border shadow-sm p-4 transition-shadow">
<div className="flex items-start gap-4">
<div className="flex items-center gap-2 shrink-0">
{step.hasIssues && (
<AlertTriangle className="h-4 w-4 text-destructive" />
)}
<div className="w-6 h-6 rounded-full bg-muted flex items-center justify-center text-sm font-medium text-muted-foreground">
{stepNumber}
</div>
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between mb-3">
{isSequence ? (
<div className="flex items-center gap-2">
<div className="w-5 h-5 rounded bg-primary/10 flex items-center justify-center">
<div className="w-2 h-2 rounded-full bg-primary" />
</div>
<span className="text-base font-medium">{step.description}</span>
</div>
) : (
<input
type="text"
value={step.name + ' ' + stepNumber}
onChange={(e) => updateStep(step.id, { name: e.target.value })}
placeholder="Step name"
className="w-full bg-transparent border-0 outline-none text-base font-medium placeholder:text-muted-foreground"
/>
)}
</div>
{!isSequence && step.description !== undefined && (
<input
type="text"
value={step.description}
onChange={(e) => updateStep(step.id, { description: e.target.value })}
placeholder="Add a description"
className="-mt-2 w-full bg-transparent border-0 outline-none text-sm text-muted-foreground placeholder:text-muted-foreground mb-3"
/>
)}
{!isSequence && (
<Popover
open={toolSearchOpen[step.id] || false}
onOpenChange={(open) => setToolSearchOpen(prev => ({ ...prev, [step.id]: open }))}
>
<PopoverTrigger asChild>
<Button
variant="outline"
role="combobox"
aria-expanded={toolSearchOpen[step.id] || false}
className="h-9 w-full justify-between text-sm"
>
{step.config.tool_name ? (
<span className="flex items-center gap-2 text-sm">
{(() => {
const agentpressTool = agentTools?.agentpress_tools.find(t => t.name === step.config.tool_name);
if (agentpressTool) {
return (
<>
<span>{agentpressTool.icon || '🔧'}</span>
<span>{normalizeToolName(agentpressTool.name, 'agentpress')}</span>
</>
);
}
const mcpTool = agentTools?.mcp_tools.find(t => `${t.server}:${t.name}` === step.config.tool_name);
if (mcpTool) {
return (
<>
<span>{mcpTool.icon || '🔧'}</span>
<span>{normalizeToolName(mcpTool.name, 'mcp')}</span>
</>
);
}
return step.config.tool_name;
})()}
</span>
) : (
<span className="text-muted-foreground">Select tool (optional)</span>
)}
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-[320px] p-0" align="start">
<Command>
<CommandInput placeholder="Search tools..." className="h-9" />
<CommandEmpty>No tools found.</CommandEmpty>
<CommandList>
{isLoadingTools ? (
<CommandItem disabled>Loading tools...</CommandItem>
) : agentTools ? (
<>
{agentTools.agentpress_tools.filter(tool => tool.enabled).length > 0 && (
<CommandGroup heading="Default Tools">
{agentTools.agentpress_tools.filter(tool => tool.enabled).map((tool) => (
<CommandItem
key={tool.name}
value={`${normalizeToolName(tool.name, 'agentpress')} ${tool.name}`}
onSelect={() => {
updateStep(step.id, { config: { ...step.config, tool_name: tool.name } });
setToolSearchOpen(prev => ({ ...prev, [step.id]: false }));
}}
>
<div className="flex items-center gap-2">
<span>{tool.icon || '🔧'}</span>
<span>{normalizeToolName(tool.name, 'agentpress')}</span>
</div>
<Check
className={cn(
"ml-auto h-4 w-4",
step.config.tool_name === tool.name ? "opacity-100" : "opacity-0"
)}
/>
</CommandItem>
))}
</CommandGroup>
)}
{agentTools.mcp_tools.length > 0 && (
<CommandGroup heading="External Tools">
{agentTools.mcp_tools.map((tool) => (
<CommandItem
key={`${tool.server || 'default'}-${tool.name}`}
value={`${normalizeToolName(tool.name, 'mcp')} ${tool.name} ${tool.server || ''}`}
onSelect={() => {
updateStep(step.id, { config: { ...step.config, tool_name: tool.server ? `${tool.server}:${tool.name}` : tool.name } });
setToolSearchOpen(prev => ({ ...prev, [step.id]: false }));
}}
>
<div className="flex items-center gap-2">
<span>{tool.icon || '🔧'}</span>
<span>{normalizeToolName(tool.name, 'mcp')}</span>
</div>
<Check
className={cn(
"ml-auto h-4 w-4",
step.config.tool_name === (tool.server ? `${tool.server}:${tool.name}` : tool.name) ? "opacity-100" : "opacity-0"
)}
/>
</CommandItem>
))}
</CommandGroup>
)}
</>
) : (
<CommandItem disabled>Failed to load tools</CommandItem>
)}
</CommandList>
</Command>
</PopoverContent>
</Popover>
)}
{step.children && step.children.length > 0 && (
<div className="mt-4 space-y-4">
{step.children.map((child, index) => renderStep(child, index + 1, true, step.id))}
</div>
)}
</div>
<Popover>
<PopoverTrigger asChild>
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 opacity-0 group-hover:opacity-100 transition-opacity">
<MoreHorizontal className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-48 p-1" align="end">
<Button
variant="ghost"
size="sm"
onClick={() => removeStep(step.id)}
className="w-full justify-start text-destructive hover:text-destructive hover:bg-destructive/10"
>
<Trash2 className="h-4 w-4 mr-2" />
Delete step
</Button>
</PopoverContent>
</Popover>
</div>
</div>
</div>
);
};
const renderSteps = () => {
const result: React.ReactNode[] = [];
let stepCounter = 0;
let i = 0;
while (i < steps.length) {
const step = steps[i];
if (step.type === 'condition') {
const conditionGroup: ConditionalStep[] = [];
while (i < steps.length && steps[i].type === 'condition') {
conditionGroup.push(steps[i]);
i++;
}
stepCounter++;
result.push(
<div key={conditionGroup[0].id} className="bg-card rounded-lg border shadow-sm p-4 transition-shadow">
<div className="flex items-start gap-4">
<div className="flex items-center gap-2 shrink-0">
<div className="w-6 h-6 rounded-full bg-muted flex items-center justify-center text-sm font-medium text-muted-foreground">
{stepCounter}
</div>
</div>
<div className="flex-1">
<div className="text-base font-medium mb-4">Add rule</div>
{renderConditionTabs(conditionGroup, conditionGroup[0].id)}
</div>
</div>
</div>
);
} else {
stepCounter++;
result.push(renderStep(step, stepCounter, false));
i++;
}
}
return result;
};
return (
<div className="space-y-6 max-w-4xl">
{steps.length === 0 ? (
<div className="text-center py-16">
<div className="w-16 h-16 bg-muted rounded-2xl flex items-center justify-center mx-auto mb-4">
<Plus className="h-8 w-8 text-muted-foreground" />
</div>
<h3 className="text-lg font-semibold mb-2">Start building your workflow</h3>
<p className="text-muted-foreground mb-6 max-w-md mx-auto">
Add steps and conditions to create a smart workflow that adapts to different scenarios.
</p>
<Button
onClick={() => addStep()}
>
<Plus className="h-4 w-4" />
Add step
</Button>
</div>
) : (
<div className="space-y-6">
{renderSteps()}
<div className="flex justify-center pt-4">
<div className="flex gap-3">
<Button
variant="outline"
onClick={() => addStep()}
className="border-dashed"
>
<Plus className="h-4 w-4" />
Add step
</Button>
<Button
variant="outline"
onClick={() => addCondition(steps[steps.length - 1]?.id || '')}
className="border-dashed"
>
<Plus className="h-4 w-4" />
Add rule
</Button>
</div>
</div>
</div>
)}
</div>
);
}
|