Skip to content

Conversation

@ogabrielluiz
Copy link
Contributor

@ogabrielluiz ogabrielluiz commented Nov 28, 2025

Introduce an endpoint to expand a compact flow format into a full flow format, along with unit tests to ensure the functionality works as intended. This enhancement allows for better integration with AI-generated flows.

Summary by CodeRabbit

  • New Features

    • Added new API endpoint to expand compact AI-generated flow representations into complete, usable flow format.
    • System now validates component availability and handles errors gracefully during flow expansion.
  • Tests

    • Added comprehensive unit and integration tests for flow expansion functionality, including error handling and endpoint validation scenarios.

✏️ Tip: You can customize this high-level summary in your review settings.

@github-actions github-actions bot added the community Pull Request from an external contributor label Nov 28, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 28, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This change introduces a new API endpoint (POST /flows/expand/) that expands compact AI-generated flow representations into full Langflow-compatible flows. It includes a new processing module with data models, utility functions for node and edge expansion, and comprehensive unit/integration tests.

Changes

Cohort / File(s) Summary
API Endpoint
src/backend/base/langflow/api/v1/flows.py
Adds POST /flows/expand/ endpoint that accepts compact flow data, validates user authentication, loads component cache, and calls expand_compact_flow to produce expanded flow representation. Includes error handling for ValueError (400) and other exceptions (500).
Core Expansion Logic
src/backend/base/langflow/processing/expand_flow.py
New module defining CompactNode, CompactEdge, and CompactFlowData models. Provides utility functions to flatten components, expand nodes (merging user values with templates), encode handles, and expand edges (computing source/target handle metadata). Main expand_compact_flow function orchestrates full flow expansion.
Test Coverage
src/backend/tests/unit/test_expand_flow.py
Unit and integration tests covering component flattening, node expansion (simple/edited/with-values scenarios), edge expansion with handle encoding, full flow expansion, and endpoint authentication/error handling. Uses synthetic component dataset to validate expansion paths.

Sequence Diagram

sequenceDiagram
    participant Client
    participant API as API Endpoint<br/>/flows/expand/
    participant Auth as Authentication
    participant Cache as Component Cache
    participant Expand as expand_compact_flow
    participant Response

    Client->>API: POST compact_data
    API->>Auth: get_current_active_user
    Auth-->>API: authenticated user
    
    API->>Cache: get_and_cache_all_types_dict
    alt Cache needs load
        Cache-->>Cache: load all component types
    end
    Cache-->>API: all_types_dict
    
    API->>Expand: expand_compact_flow(compact_data, all_types_dict)
    
    Expand->>Expand: _get_flat_components (flatten templates)
    Expand->>Expand: _expand_node (for each node)<br/>merge values & templates
    Expand->>Expand: _expand_edge (for each edge)<br/>encode handles
    
    alt Success
        Expand-->>API: expanded flow dict
        API-->>Response: 200 OK {nodes, edges}
    else ValueError (invalid component)
        Expand-->>API: ValueError
        API-->>Response: 400 Bad Request
    else Other Error
        API-->>Response: 500 Internal Server Error
    end
    
    Response-->>Client: response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • expand_flow.py: Contains multiple interdependent functions with handle encoding logic, component template resolution, and nested data structure manipulation requiring careful validation
  • Edge expansion logic: Complex sourceHandle/targetHandle formatting with JSON encoding and special character handling warrants close inspection
  • Error handling paths: Multiple validation scenarios (unknown components, missing nodes/edges) need thorough tracing
  • API integration: Endpoint handler coordinates cache initialization and expansion orchestration—verify dependency injection and error status codes are correct

Pre-merge checks and finishing touches

Important

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

❌ Failed checks (1 error, 3 warnings)
Check name Status Explanation Resolution
Test Coverage For New Implementations ❌ Error Four async test methods in TestExpandFlowEndpoint class are missing required @pytest.mark.asyncio decorator, preventing pytest-asyncio from executing them. Add @pytest.mark.asyncio decorator to test_expand_flow_endpoint_requires_auth, test_expand_flow_endpoint_success, test_expand_flow_endpoint_invalid_component, and test_expand_flow_endpoint_invalid_edge methods.
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Test Quality And Coverage ⚠️ Warning Async test methods in TestExpandFlowEndpoint class are missing @pytest.mark.asyncio decorators required for proper pytest-asyncio integration. Add @pytest.mark.asyncio decorator to all four async test methods (test_expand_flow_endpoint_requires_auth, test_expand_flow_endpoint_success, test_expand_flow_endpoint_invalid_component, test_expand_flow_endpoint_invalid_edge) and verify pytest-asyncio configuration.
Test File Naming And Structure ⚠️ Warning Test file test_expand_flow.py has 4 async test methods missing @pytest.mark.asyncio decorators required for proper execution. Add @pytest.mark.asyncio decorator to all async test methods in TestExpandFlowEndpoint class to enable proper pytest async test execution.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding functionality to expand compact flow formats, which is the core feature introduced across the new endpoint and processing module.
Excessive Mock Usage Warning ✅ Passed Test file uses appropriate mocks only for external dependencies (AsyncClient, auth headers) while testing real core logic functions directly with synthetic test data fixtures.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions bot added the enhancement New feature or request label Nov 28, 2025
@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Nov 28, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/backend/tests/unit/test_expand_flow.py (1)

554-565: Consider strengthening the success test assertion.

The test accepts both 200 OK and 400 Bad Request as valid outcomes, which weakens the test's ability to catch regressions. Consider either:

  1. Mocking component_cache.all_types_dict with SAMPLE_COMPONENTS to ensure deterministic behavior
  2. Adding a docstring explaining why both statuses are acceptable

Example approach with mocking:

@pytest.mark.asyncio
async def test_expand_flow_endpoint_success(self, client: AsyncClient, logged_in_headers, monkeypatch):
    """Test successful flow expansion with mocked components."""
    from lfx.interface.components import component_cache
    monkeypatch.setattr(component_cache, "all_types_dict", SAMPLE_COMPONENTS)
    
    compact_data = {
        "nodes": [{"id": "1", "type": "ChatInput"}],
        "edges": [],
    }
    
    response = await client.post("api/v1/flows/expand/", json=compact_data, headers=logged_in_headers)
    assert response.status_code == status.HTTP_200_OK
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 271c7ff and 9c2893c.

📒 Files selected for processing (3)
  • src/backend/base/langflow/api/v1/flows.py (2 hunks)
  • src/backend/base/langflow/processing/expand_flow.py (1 hunks)
  • src/backend/tests/unit/test_expand_flow.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
src/backend/**/*.py

📄 CodeRabbit inference engine (.cursor/rules/backend_development.mdc)

src/backend/**/*.py: Use FastAPI async patterns with await for async operations in component execution methods
Use asyncio.create_task() for background tasks and implement proper cleanup with try/except for asyncio.CancelledError
Use queue.put_nowait() for non-blocking queue operations and asyncio.wait_for() with timeouts for controlled get operations

Files:

  • src/backend/base/langflow/api/v1/flows.py
  • src/backend/tests/unit/test_expand_flow.py
  • src/backend/base/langflow/processing/expand_flow.py
src/backend/base/langflow/api/**/*.py

📄 CodeRabbit inference engine (.cursor/rules/backend_development.mdc)

Backend API endpoints should be organized by version (v1/, v2/) under src/backend/base/langflow/api/ with specific modules for features (chat.py, flows.py, users.py, etc.)

Files:

  • src/backend/base/langflow/api/v1/flows.py
src/backend/tests/**/*.py

📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)

src/backend/tests/**/*.py: Place backend unit tests in src/backend/tests/ directory, component tests in src/backend/tests/unit/components/ organized by component subdirectory, and integration tests accessible via make integration_tests
Use same filename as component with appropriate test prefix/suffix (e.g., my_component.pytest_my_component.py)
Use the client fixture (FastAPI Test Client) defined in src/backend/tests/conftest.py for API tests; it provides an async httpx.AsyncClient with automatic in-memory SQLite database and mocked environment variables. Skip client creation by marking test with @pytest.mark.noclient
Inherit from the correct ComponentTestBase family class located in src/backend/tests/base.py based on API access needs: ComponentTestBase (no API), ComponentTestBaseWithClient (needs API), or ComponentTestBaseWithoutClient (pure logic). Provide three required fixtures: component_class, default_kwargs, and file_names_mapping
Create comprehensive unit tests for all new backend components. If unit tests are incomplete, create a corresponding Markdown file documenting manual testing steps and expected outcomes
Test both sync and async code paths, mock external dependencies appropriately, test error handling and edge cases, validate input/output behavior, and test component initialization and configuration
Use @pytest.mark.asyncio decorator for async component tests and ensure async methods are properly awaited
Test background tasks using asyncio.create_task() and verify completion with asyncio.wait_for() with appropriate timeout constraints
Test queue operations using non-blocking queue.put_nowait() and asyncio.wait_for(queue.get(), timeout=...) to verify queue processing without blocking
Use @pytest.mark.no_blockbuster marker to skip the blockbuster plugin in specific tests
For database tests that may fail in batch runs, run them sequentially using uv run pytest src/backend/tests/unit/test_database.py r...

Files:

  • src/backend/tests/unit/test_expand_flow.py
**/{test_*.py,*.test.ts,*.test.tsx}

📄 CodeRabbit inference engine (Custom checks)

Check that test files follow the project's naming conventions (test_*.py for backend, *.test.ts for frontend)

Files:

  • src/backend/tests/unit/test_expand_flow.py
**/test_*.py

📄 CodeRabbit inference engine (Custom checks)

**/test_*.py: Backend tests should follow pytest structure with proper test_*.py naming
For async functions, ensure proper async testing patterns are used with pytest for backend

Files:

  • src/backend/tests/unit/test_expand_flow.py
🧠 Learnings (13)
📓 Common learnings
Learnt from: ogabrielluiz
Repo: langflow-ai/langflow PR: 0
File: :0-0
Timestamp: 2025-06-26T19:43:18.260Z
Learning: In langflow custom components, the `module_name` parameter is now propagated through template building functions to add module metadata and code hashes to frontend nodes for better component tracking and debugging.
📚 Learning: 2025-11-24T19:46:09.104Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-11-24T19:46:09.104Z
Learning: Applies to src/backend/base/langflow/api/**/*.py : Backend API endpoints should be organized by version (v1/, v2/) under `src/backend/base/langflow/api/` with specific modules for features (chat.py, flows.py, users.py, etc.)

Applied to files:

  • src/backend/base/langflow/api/v1/flows.py
📚 Learning: 2025-11-24T19:47:28.997Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-24T19:47:28.997Z
Learning: Applies to src/backend/tests/**/*.py : Test component versioning and backward compatibility using `file_names_mapping` fixture with `VersionComponentMapping` objects mapping component files across Langflow versions

Applied to files:

  • src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:47:28.997Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-24T19:47:28.997Z
Learning: Applies to src/backend/tests/**/*.py : Use predefined JSON flows and utility functions from `tests.unit.build_utils` (create_flow, build_flow, get_build_events, consume_and_assert_stream) for flow execution testing

Applied to files:

  • src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:47:28.997Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-24T19:47:28.997Z
Learning: Applies to src/backend/tests/**/*.py : Create comprehensive unit tests for all new backend components. If unit tests are incomplete, create a corresponding Markdown file documenting manual testing steps and expected outcomes

Applied to files:

  • src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:47:28.997Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-24T19:47:28.997Z
Learning: Applies to src/backend/tests/**/*.py : Test Langflow REST API endpoints using the `client` fixture with appropriate HTTP methods (GET, POST, etc.), headers (logged_in_headers), and payload validation

Applied to files:

  • src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:47:28.997Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-24T19:47:28.997Z
Learning: Applies to src/backend/tests/**/*.py : Test both sync and async code paths, mock external dependencies appropriately, test error handling and edge cases, validate input/output behavior, and test component initialization and configuration

Applied to files:

  • src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:47:28.997Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-24T19:47:28.997Z
Learning: Applies to src/backend/tests/**/*.py : Test component build config updates by calling `to_frontend_node()` to get the node template, then calling `update_build_config()` to apply configuration changes

Applied to files:

  • src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:47:28.997Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-24T19:47:28.997Z
Learning: Applies to src/backend/tests/**/*.py : Test Langflow's `Message` objects using `langflow.schema.message.Message` and validate text, sender, sender_name, session_id, files, and properties attributes

Applied to files:

  • src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:46:09.104Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-11-24T19:46:09.104Z
Learning: Applies to src/backend/base/langflow/components/**/*.py : Add new components to the appropriate subdirectory under `src/backend/base/langflow/components/` (agents/, data/, embeddings/, input_output/, models/, processing/, prompts/, tools/, or vectorstores/)

Applied to files:

  • src/backend/tests/unit/test_expand_flow.py
  • src/backend/base/langflow/processing/expand_flow.py
📚 Learning: 2025-11-24T19:46:09.104Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-11-24T19:46:09.104Z
Learning: Applies to tests/unit/**/*.py : Database and flow integration tests should use helper functions from `tests.unit.build_utils` such as `create_flow`, `build_flow`, and `get_build_events`

Applied to files:

  • src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:46:09.104Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-11-24T19:46:09.104Z
Learning: Applies to src/backend/base/langflow/components/**/__init__.py : Update `__init__.py` with alphabetically sorted imports when adding new components

Applied to files:

  • src/backend/tests/unit/test_expand_flow.py
  • src/backend/base/langflow/processing/expand_flow.py
📚 Learning: 2025-06-26T19:43:18.260Z
Learnt from: ogabrielluiz
Repo: langflow-ai/langflow PR: 0
File: :0-0
Timestamp: 2025-06-26T19:43:18.260Z
Learning: In langflow custom components, the `module_name` parameter is now propagated through template building functions to add module metadata and code hashes to frontend nodes for better component tracking and debugging.

Applied to files:

  • src/backend/base/langflow/processing/expand_flow.py
🧬 Code graph analysis (2)
src/backend/tests/unit/test_expand_flow.py (1)
src/backend/base/langflow/processing/expand_flow.py (6)
  • CompactEdge (26-32)
  • CompactNode (15-23)
  • _expand_edge (154-235)
  • _expand_node (52-111)
  • _get_flat_components (42-49)
  • expand_compact_flow (238-283)
src/backend/base/langflow/processing/expand_flow.py (1)
src/lfx/src/lfx/utils/util.py (1)
  • escape_json_dump (617-618)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (18)
  • GitHub Check: Lint Backend / Run Mypy (3.13)
  • GitHub Check: Run Backend Tests / LFX Tests - Python 3.10
  • GitHub Check: Lint Backend / Run Mypy (3.11)
  • GitHub Check: Lint Backend / Run Mypy (3.10)
  • GitHub Check: Lint Backend / Run Mypy (3.12)
  • GitHub Check: Test Docker Images / Test docker images
  • GitHub Check: Run Frontend Tests / Determine Test Suites and Shard Distribution
  • GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 5
  • GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 3
  • GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 2
  • GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 4
  • GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 1
  • GitHub Check: Run Backend Tests / Integration Tests - Python 3.10
  • GitHub Check: Test Starter Templates
  • GitHub Check: Update Component Index
  • GitHub Check: Run Ruff Check and Format
  • GitHub Check: Update Starter Projects
  • GitHub Check: Optimize new Python code in this PR
🔇 Additional comments (6)
src/backend/base/langflow/api/v1/flows.py (1)

592-637: LGTM! New endpoint follows established patterns.

The endpoint correctly:

  • Requires authentication via Depends(get_current_active_user)
  • Handles cache initialization defensively
  • Returns appropriate HTTP status codes (400 for ValueError, 500 for other exceptions)

One minor observation: the endpoint returns a raw dict without a response_model. This is acceptable for flexibility with AI-generated flows, but consider adding a response model if schema validation becomes important.

src/backend/base/langflow/processing/expand_flow.py (5)

15-24: LGTM! Clean Pydantic models for compact flow representation.

The CompactNode model is well-designed with sensible defaults and clear documentation of the edited flag's contract.


93-101: Verify consistency in value assignment for non-dict template fields.

When template[field_name] is not a dict (line 97-98), the code assigns field_value directly, but when the field doesn't exist (line 100-101), it wraps it as {"value": field_value}. This inconsistency could cause issues if downstream code expects all template fields to have a consistent structure.

Is this intentional? If template fields should always be dicts with a value key, consider:

         if field_name in template:
             if isinstance(template[field_name], dict):
                 template[field_name]["value"] = field_value
             else:
-                template[field_name] = field_value
+                template[field_name] = {"value": field_value}
         else:
             # Add as new field if not in template
             template[field_name] = {"value": field_value}

180-190: Good defensive fallback to base_classes when output not found.

The logic correctly handles cases where the output name doesn't match any defined outputs by falling back to base_classes. This is a reasonable design choice for AI-generated flows that might use non-standard output names.


114-122: Good reuse of existing escape_json_dump utility.

Using the existing utility from lfx.utils.util maintains consistency with other parts of the codebase that generate handle strings.


238-283: LGTM! Clean orchestration of the expansion process.

The function follows a clear flow:

  1. Parse and validate input with Pydantic
  2. Flatten component lookup
  3. Expand nodes first (required for edge references)
  4. Expand edges
  5. Return the full structure

The docstring with example input is helpful for understanding the expected format.

@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Nov 28, 2025
@github-actions
Copy link
Contributor

Frontend Unit Test Coverage Report

Coverage Summary

Lines Statements Branches Functions
Coverage: 15%
15.24% (4188/27479) 8.46% (1778/20993) 9.57% (579/6049)

Unit Test Results

Tests Skipped Failures Errors Time
1638 0 💤 0 ❌ 0 🔥 19.953s ⏱️

@codecov
Copy link

codecov bot commented Nov 28, 2025

Codecov Report

❌ Patch coverage is 93.13725% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 32.48%. Comparing base (271c7ff) to head (17dc372).

Files with missing lines Patch % Lines
src/backend/base/langflow/api/v1/flows.py 68.75% 5 Missing ⚠️
...rc/backend/base/langflow/processing/expand_flow.py 97.67% 2 Missing ⚠️

❌ Your project check has failed because the head coverage (40.04%) is below the target coverage (60.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #10785      +/-   ##
==========================================
+ Coverage   32.39%   32.48%   +0.09%     
==========================================
  Files        1368     1369       +1     
  Lines       63414    63516     +102     
  Branches     9373     9373              
==========================================
+ Hits        20541    20633      +92     
- Misses      41840    41850      +10     
  Partials     1033     1033              
Flag Coverage Δ
backend 51.48% <93.13%> (+0.23%) ⬆️
frontend 14.08% <ø> (ø)
lfx 40.04% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...rc/backend/base/langflow/processing/expand_flow.py 97.67% <97.67%> (ø)
src/backend/base/langflow/api/v1/flows.py 45.36% <68.75%> (+1.36%) ⬆️

... and 4 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

…code-pre-built-component`) (#10786)

Co-authored-by: codeflash-ai[bot] <148906541+codeflash-ai[bot]@users.noreply.github.com>
@codeflash-ai
Copy link
Contributor

codeflash-ai bot commented Dec 11, 2025

@codeflash-ai
Copy link
Contributor

codeflash-ai bot commented Dec 11, 2025

This PR is now faster! 🚀 codeflash-ai[bot] accepted my code suggestion above.

@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Dec 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants