Repository navigation
fix: don't allow adding condition in condition or loop in the loop - #3651
Conversation
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
|
@coderabbitai review |
📝 WalkthroughWalkthroughThis pull request updates various workflow modules to improve type safety and clarity. Unused imports are removed and several function signatures are updated to adopt new YAML-based types. The changes introduce new Zod schemas for enrich data, consolidate step and action types, and refine node data structures. UI components, utility functions, and tests have been modified to work with the new types and naming conventions (e.g., renaming getWorkflowFromDefinition to getYamlWorkflowDefinition), while edge validations and branch processing in workflow reconstruction are enhanced. Changes
Sequence Diagram(s)sequenceDiagram
participant UI as Editor UI
participant Store as WorkflowStore
participant Utils as Workflow Utils
participant YAML as getYamlWorkflowDefinition
UI->>Store: addNodeBetween(nodeId, step)
Store->>Utils: Validate edge addition (trigger, step, condition, foreach)
Utils-->>Store: Return validation result
Store->>YAML: Generate YAML workflow definition
YAML-->>Store: Return workflow definition
Suggested labels
Suggested reviewers
Poem
✨ Finishing Touches
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (11)
keep-ui/features/workflows/builder/ui/Editor/ReactFlowEditor.tsx (1)
2-6: Consider adding a type check for selectedNode.While the changes improve type safety with new imports, consider adding a type guard for
selectedNodeto ensure it matches the expected V2ActionOrStep type before rendering StepEditorV2.- {isStepEditor && <StepEditorV2 key={selectedNode} />} + {isStepEditor && selectedNode && ( + <StepEditorV2 + key={selectedNode} + /> + )}Also applies to: 93-93
keep-ui/features/workflows/builder/ui/WorkflowNode.tsx (1)
161-165: Consider using a more stable key for NodeTriggerIcon.The current key implementation might cause unnecessary re-renders if the alert source changes frequently.
Consider using a composite key or memoizing the key generation:
-key={ - data?.type === "alert" - ? data?.properties?.alert?.source - : data?.id -} +key={`${data?.id}-${data?.type === "alert" ? data?.properties?.alert?.source : ""}`}keep-ui/features/workflows/builder/ui/Editor/StepEditor.tsx (2)
479-559: Condensed logic for StepEditorV2
This newly introducedStepEditorV2function parses node data withNodeDataStepSchemaand conditionally renders editors for threshold, assert, foreach, or default cases. Consider adding a fallback for unexpectedcomponentTypeortypeto prevent uncaught parse errors, and ensure comprehensive unit tests for each branch.
600-600: Type assertion in update
Casting toConditionsAndMiscFormDataTypemight be unnecessary ifupdatedFormDatais always the correct shape. Consider refining the type to remove the need for this assertion.keep-ui/utils/reactFlow.ts (2)
199-200: Consider removing TODO comments and improving type assertions.The TODO comments for type assertions could be replaced with proper type definitions or interfaces.
- // FIX: type assertion - } as NodeData, + } satisfies NodeData,Also applies to: 218-219
253-254: Consider adding type annotation for TODO comment.The TODO comment about fixing types should be addressed with a proper type definition.
- // TODO: fix type - steps={group.steps as any} + steps={group.steps as V2StepTrigger[] | Omit<V2Step, "id">[]}keep-ui/entities/workflows/model/yaml.types.ts (1)
17-21: Consider adding JSDoc comments for the YamlCondition interface.The interface would benefit from documentation explaining the purpose of the
aliasproperty and its relationship with conditions.+/** + * Represents a base condition in a YAML workflow. + * @property id - Optional unique identifier for the condition + * @property name - Display name of the condition + * @property alias - Optional alias for condition reference + */ interface YamlCondition { id?: string; name: string; alias?: string; }keep-ui/features/workflows/builder/ui/WorkflowToolbox.tsx (1)
178-183: Consider removing explicit any type.The explicit
anytype in the reduce function could be replaced with a more specific type.- (obj: any, node) => { + (obj: Record<string, boolean>, node) => {keep-ui/entities/workflows/model/types.ts (1)
179-180: Address TODO comment with generic type.The TODO comment about making a generic sequence type should be implemented.
- // TODO: make a generic sequence type - sequence: z.array(z.union([V2ActionOrStepSchema, V2StepConditionSchema])), + sequence: z.array( + z.union([V2ActionOrStepSchema, V2StepConditionSchema]) + ).describe('Sequence of workflow steps or conditions'),keep-ui/entities/workflows/lib/parser.ts (2)
81-111: Consider reducing duplication in threshold vs assert logic.
Both condition branches repeat several fields (e.g.,id,name,componentType,alias), which can be factored out into a shared object.For example, you could unify repeated fields and then apply condition-specific properties:
function generateCondition(condition, action, stepType, providers) { + const baseCondition = { + id: condition.id || uuidv4(), + name: condition.name, + componentType: "switch" as const, + alias: condition.alias + }; const generatedConditionStep = condition.type === "threshold" ? { - id: condition.id || uuidv4(), - name: condition.name, type: "condition-threshold" as const, - componentType: "switch" as const, - alias: condition.alias, + ...baseCondition, properties: { ... }, branches: { true: [getActionOrStepObj(action, stepType, providers)], false: [], }, } : { - id: condition.id || uuidv4(), - name: condition.name, type: "condition-assert" as const, - componentType: "switch" as const, - alias: condition.alias, + ...baseCondition, properties: { ... }, branches: { ... }, }; ... }
293-306: Refactor or unify repeated condition-building logic.
Similar to earlier threshold vs. assert duplication, consolidating logic forgetActionsFromConditioncan streamline maintainability.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (20)
keep-ui/entities/workflows/lib/getLayoutedWorkflowElements.ts(0 hunks)keep-ui/entities/workflows/lib/parser.ts(11 hunks)keep-ui/entities/workflows/model/__tests__/types.test.ts(1 hunks)keep-ui/entities/workflows/model/__tests__/workflow-store.test.tsx(4 hunks)keep-ui/entities/workflows/model/types.ts(9 hunks)keep-ui/entities/workflows/model/useWorkflowActions.ts(3 hunks)keep-ui/entities/workflows/model/workflow-store.ts(7 hunks)keep-ui/entities/workflows/model/yaml.types.ts(1 hunks)keep-ui/entities/workflows/ui/NodeTriggerIcon.tsx(1 hunks)keep-ui/features/workflows/ai-assistant/lib/utils.ts(1 hunks)keep-ui/features/workflows/builder/lib/utils.tsx(1 hunks)keep-ui/features/workflows/builder/ui/Editor/ReactFlowEditor.tsx(2 hunks)keep-ui/features/workflows/builder/ui/Editor/StepEditor.tsx(3 hunks)keep-ui/features/workflows/builder/ui/Editor/TriggerEditor.tsx(1 hunks)keep-ui/features/workflows/builder/ui/WorkflowEdge.tsx(1 hunks)keep-ui/features/workflows/builder/ui/WorkflowNode.tsx(4 hunks)keep-ui/features/workflows/builder/ui/WorkflowToolbox.tsx(8 hunks)keep-ui/features/workflows/test-run/ui/workflow-test-run-modal.tsx(2 hunks)keep-ui/utils/reactFlow.ts(8 hunks)keep-ui/widgets/workflow-builder/workflow-builder.tsx(3 hunks)
💤 Files with no reviewable changes (1)
- keep-ui/entities/workflows/lib/getLayoutedWorkflowElements.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
- GitHub Check: tests-e2e (postgres)
- GitHub Check: tests-e2e (mysql)
🔇 Additional comments (73)
keep-ui/features/workflows/ai-assistant/lib/utils.ts (1)
39-40: LGTM! Improved node data handling with fallback mechanism.The changes consolidate the data spreading operation while adding a robust fallback mechanism for node IDs. This maintains backward compatibility while making the code more resilient.
keep-ui/features/workflows/builder/ui/WorkflowEdge.tsx (1)
33-33: LGTM! Enhanced debug information accessibility and presentation.The changes improve the debugging experience by:
- Enabling interaction with debug info through pointer events
- Adding a collapsible UI for cleaner presentation
- Structuring the debug data in a readable JSON format
Also applies to: 37-40
keep-ui/features/workflows/test-run/ui/workflow-test-run-modal.tsx (1)
13-13: LGTM! Aligned with YAML-based workflow definition standard.The changes consistently adopt the new YAML-based workflow definition approach while maintaining the same functionality.
Also applies to: 52-52
keep-ui/entities/workflows/model/useWorkflowActions.ts (1)
8-8: LGTM! Function renaming is consistent.The renaming of
getWorkflowFromDefinitiontogetYamlWorkflowDefinitionis applied consistently across the file.Also applies to: 37-37, 67-67
keep-ui/features/workflows/builder/ui/Editor/TriggerEditor.tsx (1)
38-38: LGTM! Alert filter data structure is properly updated.The change ensures alert filters are correctly structured under the 'alert' key in the node properties, maintaining consistency with the updated NodeData structure.
keep-ui/features/workflows/builder/ui/WorkflowNode.tsx (1)
65-66: LGTM! Improved trigger node identification.The updated condition properly checks both
componentTypeandtype, making trigger identification more robust.keep-ui/entities/workflows/ui/NodeTriggerIcon.tsx (3)
7-7: LGTM! Improved type safety with NodeData.The change from
FlowNode["data"]toNodeDataprovides better type safety and clarity.Also applies to: 9-9
10-12: LGTM! Added performance optimization.Early return for non-trigger components prevents unnecessary processing.
19-19: LGTM! Updated alert source path.The alert source path now correctly reflects the updated data structure.
keep-ui/widgets/workflow-builder/workflow-builder.tsx (3)
15-19: LGTM! Import statement updated for better clarity.The renaming from
getWorkflowFromDefinitiontogetYamlWorkflowDefinitionimproves code readability by being more explicit about the function's purpose.
100-113: LGTM! Workflow definition generation is properly structured.The workflow definition generation is well-organized with clear parameter separation and proper spreading into the
wrapDefinitionV2function.
155-155: LGTM! YAML workflow definition is properly stringified.The use of
getYamlWorkflowDefinitionin theworkflowYamlmemoized value ensures consistent YAML generation.keep-ui/entities/workflows/model/__tests__/workflow-store.test.tsx (2)
265-265: LGTM! Switch node type updated to be more specific.The change from
type: "switch"totype: "condition-threshold"improves type safety and better represents the node's purpose.
370-374: LGTM! Node data structure improved.The node data structure has been enhanced to include:
- Explicit
componentTypefield- Properties encapsulation
- Better type organization
This change improves type safety and code organization.
Also applies to: 400-406
keep-ui/entities/workflows/model/__tests__/types.test.ts (5)
1-12: LGTM! Well-organized imports and dependencies.The imports are properly structured, separating schema imports from utility imports.
13-87: LGTM! Comprehensive action schema validation tests.The tests thoroughly validate:
- Jira ticket creation with enrichment
- Multiple enrichment types
- Complex nested properties
89-134: LGTM! Thorough condition and foreach schema tests.Tests properly validate:
- Condition threshold templates
- Required fields (ID)
- Branch structures
- Foreach step validation
136-204: LGTM! Comprehensive step schema validation.Tests cover:
- Basic step validation
- Optional fields
- Invalid cases
- Type prefix validation
206-294: LGTM! Thorough condition assert schema tests.Tests validate:
- Basic assertions
- Branch structures
- Required fields
- Error cases
keep-ui/features/workflows/builder/ui/Editor/StepEditor.tsx (5)
26-26: Use of additional React hooks
This import ofuseState,useCallback, anduseMemoensures local state, memoization, and callback optimizations.
29-29: Imported NodeDataStepSchema
This new import helps parse and validate the node data. Ensure that schema parsing errors are handled gracefully in the calling code.
35-35: Imported V2StepSchema
Usage ofV2StepSchemais consistent with the approach of validating steps before rendering.
561-576: Required name property for conditions & foreach
These updates make thenamefield mandatory inConditionsAndMiscFormDataType. Verify that all call sites provide a non-emptynameto avoid runtime errors.Would you like me to generate a script to confirm references to
ConditionsAndMiscEditorare always passed a validname?
581-583: Initialize condition or foreach form data
AcceptinginitialFormDatainto local state ensures type safety for condition or foreach properties. This approach looks good; confirm that all usage points pass the required fields.keep-ui/features/workflows/builder/lib/utils.tsx (4)
200-202: Ensure trigger placement
canAddTriggerBeforeEdgecorrectly restricts triggers to edges betweentrigger_startandtrigger_end, preserving workflow logic.
204-210: Prevent step insertion before start or trigger end
canAddStepBeforeEdgedisallows steps at disallowed positions, avoiding conflicts with the start node or a trigger endpoint.
212-214: Block condition usage on empty branches
canAddConditionBeforeEdgeprevents conditions if a target ends inempty_trueorempty_false, enforcing valid condition usage.
216-218: Restrict nested foreach
canAddForeachBeforeEdgedisallows adding a foreach immediately before another foreach target, preserving simpler control flow.keep-ui/entities/workflows/model/workflow-store.ts (8)
41-44: Import new helper functions
These imports integrate the condition, foreach, step, and trigger checks for restricting node insertion.
71-71: Extended rawStep parameter
AllowingV2StepTemplate | V2StepTrigger | Omit<V2Step, "id">supports more flexible insertion scenarios. Confirm that any new usage aligns with these types.
128-131: Trigger insertion guard
UsingcanAddTriggerBeforeEdgeprevents placing triggers in invalid positions, aligning with workflow constraints.
132-137: Condition insertion guard
Refusing to add conditions ifcanAddConditionBeforeEdgefails ensures condition nodes appear only in valid contexts.
139-145: Foreach insertion check
Forbids adding a foreach ifcanAddForeachBeforeEdgedisallows it, reducing potential nesting issues.
159-159: Step insertion check
RequiringcanAddStepBeforeEdgefor non-trigger components enforces consistent step placement rules.
327-327: Refined addNodeBetween signature
Accepting triggers or partial steps in thestepparameter supports a unified approach to node insertion.
336-337: Safe insertion logic
addNodeBetweenSafemirrors the broader signature fromaddNodeBetween, catching and rendering Zod or runtime errors gracefully.keep-ui/utils/reactFlow.ts (2)
79-81: Enhance type safety in condition node handling.The type definition for
conditionNodehas been improved to explicitly include thebranchesproperty with strongly typed arrays for true/false branches.
93-93: Add type assertions for better type safety.Type assertions have been added to ensure proper type checking:
- Line 93:
tempSequenceis explicitly typed asV2Step[]- Line 117-118: Node data is properly typed as
V2Step- Line 132: Node data is properly typed as
V2StepAlso applies to: 117-117, 132-132
keep-ui/entities/workflows/model/yaml.types.ts (2)
7-15: Improve type safety with consolidated step and action interface.The
YamlStepOrActioninterface effectively combines step and action functionality while maintaining type safety through optional properties.
35-46: Enhance type safety in workflow definition interface.The
YamlWorkflowDefinitioninterface has been updated to use the consolidatedYamlStepOrActiontype, improving type consistency across the workflow definition.keep-ui/features/workflows/builder/ui/WorkflowToolbox.tsx (2)
12-28: Well-structured type definitions for menu props.The separation of base props and specific props using discriminated unions provides excellent type safety and clarity.
154-164: Clear and descriptive control flow conditions.The conditions for showing different workflow components are well-documented and logically structured:
showOnlyTriggersfor trigger-specific viewsshowConditionsprevents nested conditionsshowForeachprevents nested foreach loopskeep-ui/entities/workflows/model/types.ts (2)
67-79: Well-structured schemas for data enrichment.The
EnrichAlertSchemaandEnrichIncidentSchemaprovide clear and consistent validation for enrichment data.
307-332: Well-defined node data types for conditions.The addition of specific node data types for condition ends improves type safety and clarity in the workflow system.
keep-ui/entities/workflows/lib/parser.ts (29)
15-17: Nice introduction of typed condition references.
These new imports clearly separate threshold and assert conditions, improving readability and maintainability.
21-22: Well-typed function parameter.
ChangingactionOrStepfromanytoYamlStepOrActionstrengthens type safety.
51-59: Strong typing for foreach generation.
Using an intersection type (YamlStepOrAction & { foreach: string }) ensures the required field is present, which helps prevent runtime errors.
75-80: Enhanced type coverage for condition generation.
AcceptingYamlAssertCondition | YamlThresholdConditionand returning the union type is a clear approach to condition handling. Make sure to expand this union if new condition types emerge.
115-120: Good use of foreach fallback.
Condition steps automatically become part of a foreach sequence whenaction.foreachis defined. This is a clear structure for nested logic.
123-123: No further comment.
This simple return statement is self-explanatory.
175-175: No content changed of significance.
177-178: Mapping steps to typed objects.
Assigningtype: "step"here keeps the code consistent when building step definitions.
179-183: Clear separation of logic for workflow actions.
By mapping actions totype: "action", you unify their shape for downstream processing.
185-185: No content changed of significance.
186-188: Consolidating steps and actions.
Merging them into one array streamlines iteration without losing type specificity.
189-189: No content changed of significance.
190-191: Dual-purpose iteration.
Differentiating between a ‘step’ vs. an ‘action’ inside the loop is straightforward and effective.
194-194: Straightforward push.
steps.push(getActionOrStepObj(...))is clear.
195-195: Conditional branching.
This else-if properly handles items that rely onifconditions.
203-203: Appending to existing condition.
Pushing toexistingCondition.branches.trueis a good approach for reusing condition branches.
207-213: Foreach branch logic.
Wrapping an action in a foreach container is consistent with your typed approach.
215-215: Fallback push.
UsinggetActionOrStepObjagain ensures consistent creation of step/action objects.
219-225: Foreach logic repeated for new condition block.
Good reuse ofgenerateForeachfor any item with aforeachproperty.
226-226: Condition-based expansion.
Thiselse if (action.condition)helps keep condition actions separate from standard steps.
227-230: Iterating over multi-condition arrays.
Pushing each generated condition intoconditionsis a solid approach for layered scenario coverage.
319-319: Compiled action typed as YamlStepOrAction.
This promotes a consistent shape when returning compiled actions.
323-323: Storing condition array.
Nestling each compiled condition incondition: [compiledCondition]is a neat, consistent structure.
330-330: Typed function for step conversion.
ReturningYamlStepOrActionfrom aV2StepStepensures uniform usage throughout the codebase.
340-340: Inline object creation.
Initializingstepas aYamlStepOrActionclarifies the type mapping from V2 step fields.
350-350: Exporting typed action conversion.
This preserves clarity and consistency in how V2 actions are transformed into YAML-based objects.
361-361: Constructing the final action object.
Once again, relying onYamlStepOrActionavoids confusion about which fields are allowed.
375-380: Accurate documentation.
Renaming the function's purpose in this docstring clarifies the transformation is specifically for YAML workflow definitions.
406-406: Foreach actions array typed.
Explicitly indicating[] as YamlStepOrAction[]ensures consistent usage with your typed approach.
Closes #3639