Commit Graph

17889 Commits

Author SHA1 Message Date
71d3438d2a fix: frozen vertices crash with TypeError when no cache service available (#12409)
* fix: return CacheMiss() from fallback cache func so frozen vertices rebuild when no cache service

Fixes #12408

* fix: address review feedback on frozen vertex fix

- Use graph.arun() in test to exercise the process() path
- Make set_cache_func in process() return True for consistency with astep()

* [autofix.ci] apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-08 13:14:21 +00:00
5ea4cfcac2 fix: add missing ownership checks in projects API (GHSA-rpf3-3973-4gjr) (#12462)
* fix: enforce ownership check on flow assignment and paginated project read (GHSA-rpf3-3973-4gjr)

Prevent authenticated users from reassigning flows they don't own by adding
`Flow.user_id == current_user.id` to the UPDATE statements in `create_project`.
Also fix the paginated path in `read_project` which was missing the same filter,
allowing cross-user flow exfiltration via the `?page=&size=` query parameters.

* test: add security regression tests for GHSA-rpf3-3973-4gjr

- test_create_project_cannot_steal_other_users_flow: asserts that
  flows_list in create_project does not move flows owned by another user
- test_read_project_paginated_does_not_leak_other_users_flows: asserts
  that paginated GET /projects/{id} only returns flows owned by the
  requesting user

* test: improve security test naming and style for project ownership checks

Remove advisory IDs from test names and docstrings, rename helper and
test functions to match the existing codebase conventions.

* [autofix.ci] apply automated fixes

* fix: address ruff linting errors in ownership security tests

* test: add coverage for legitimate flows_list and paginated read assignments

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Carlos Coelho <80289056+carlosrcoelho@users.noreply.github.com>
2026-04-08 13:07:11 +00:00
cde9f23001 feat: deployment page and stepper UI with watsonx Orchestrate integration (#12303)
* feat: deployment page list

* feat: add deployment stepper modal with context-based state management

Implement a multi-step deployment creation flow with 4 steps (Provider,
Type, Attach Flows, Review). State is centralized in a scoped
DeploymentStepperContext to avoid prop-drilling across step components.
Includes bug fixes for version re-selection and connection pre-selection.

* feat: replace mock flows and versions with real API data in deployment stepper

Fetch real flows from the API (scoped to current folder) and versions
per-flow lazily when selected. Enrich selectedVersionByFlow context to
store versionTag alongside versionId so the review step can display it
without re-fetching. Remove MOCK_FLOWS_WITH_VERSIONS from mock-data.

* refactor: improve deployment stepper code quality and conventions

Rename all new deployment files to kebab-case per project conventions,
fix context re-render issues with useMemo/useCallback, replace raw
Tailwind colors with design tokens, add missing data-testid and ARIA
attributes, fix Deploy button disabled on review step, and move shared
FlowTabType to a dedicated types file.

* refactor: align deployment provider types and UI to backend contracts

- Rename ProviderInstance -> ProviderAccount to match backend naming
- Update ProviderAccount fields to match DeploymentProviderAccountGetResponse (provider_key, provider_url, provider_tenant_id, created_at, updated_at)
- Update ProviderCredentials fields to match DeploymentProviderAccountCreateRequest (provider_key, provider_url, api_key)
- Rename all "instance" UI terminology to "environment" (tabs, labels, components)
- Auto-select watsonx Orchestrate on mount as the only supported provider
- Remove Kubernetes from mock providers; update mock data to use watsonx_orchestrate only

* feat: add react-query hooks for deployments and provider accounts with mock data

- Add useGetProviderAccounts hook (GET /deployments/providers) replacing direct MOCK_PROVIDER_INSTANCES import in step-provider.tsx
- Add useGetDeployments hook (GET /deployments) replacing direct MOCK_DEPLOYMENTS import in deployments-page.tsx
- Replace fake setTimeout loading state with hook isLoading state
- Register DEPLOYMENTS and DEPLOYMENT_PROVIDER_ACCOUNTS URL constants
- Real API calls are commented out with TODO markers for easy swap when backend is ready

* chore: remove stale biome-ignore suppression in step-attach-flows

* fix: replace button role=radio with semantic input type=radio in ProviderCard

* fix: replace button role=radio with semantic radio inputs across deployment stepper

- Extract RadioSelectItem component (label + sr-only input + checkbox indicator)
  used by version, connection, and environment selectors
- Fix step-type.tsx type cards with label/input pattern (matching ProviderCard)
- Add role="radiogroup" wrapper to EnvironmentList
- Fix envVars key: use stable crypto.randomUUID() id instead of array index

* feat: add name field to provider accounts, multi-select connections, and real API call

- Add `name` field to ProviderAccount, ProviderCredentials, and mock data
- Switch connection selection from single to multi-select (CheckboxSelectItem)
- Allow creating new connections inline from the attach flows step
- Lift connections state up to DeploymentStepperContext
- Move ConnectionItem type from step-attach-flows to shared types.ts
- Wire up real API call in useGetProviderAccounts (remove mock)

* feat: wire deploy button and populate deployments page with real API data

- Add usePostDeployment and usePostProviderAccount mutation hooks
- Wire Deploy button in stepper modal: creates provider account if needed,
  then POSTs to /api/v1/deployments with WXO provider_data shape
- Fix environment_variables payload: wrap values as { value, source: "raw" }
  to satisfy EnvVarValueSpec schema
- Fix connection app_id: prefix with conn_ so WXO name validation passes
  (names must start with a letter)
- Multi-select connections with checkbox UI; persist connections in context
  so they survive back/forward navigation
- Update Deployment type to match API response shape; remove mock fields
  (url, status, health, lastModifiedBy)
- Wire useGetDeployments to real API; load provider ID from useGetProviderAccounts
- Update deployments table to display real fields: name, type, attached_count,
  provider name, updated_at

* refactor: extract DeploymentsContent component to eliminate nested ternary

* feat: add Test Deployment chat modal for deployed agents

Implements a chat interface to test deployments directly from the UI.
Wires up two entry points: the stepper modal "Test" button (inline
transition) and the deployments table play button (standalone dialog).

- Add usePostDeploymentExecution and useGetDeploymentExecution hooks
  hitting POST/GET /api/v1/deployments/executions
- Build test-deployment-modal: ChatHeader, ChatMessages, ChatInput,
  ChatMessageBubble with user/bot avatars, loading dots, tool traces
- useDeploymentChat hook: recursive setTimeout polling (max 30 × 1.5s),
  thread_id persistence for multi-turn, watsonx response parsing
  (response_type/type text, wxo_thread_id extraction)
- Stepper modal transitions inline to TestDeploymentContent on Test click
- Deployments table play button opens standalone TestDeploymentModal

* feat: add syntax highlighting to chat code blocks using SimplifiedCodeTabComponent

* feat: add action menu and icon-based type badge to deployments table

- Add dropdown action menu (Duplicate, Update, Delete) to each row
- Replace left-border type badge with icon-based badge (Bot for Agent, Plug for MCP)

* refactor: remove connected status from provider card in stepper

* feat: auto-detect flow env vars in deployment connection form

- Add POST /deployments/variables/detections backend endpoint that scans
  flow version data for credential fields (load_from_db=True globals and
  password=True fallbacks) and returns detected variable names
- Derive meaningful env var names from the model field's category when no
  global variable is linked (e.g. OPENAI_API_KEY from category "OpenAI")
- Add DetectEnvVarsRequest/DetectedEnvVar/DetectEnvVarsResponse schemas
- Add usePostDetectDeploymentEnvVars frontend mutation hook
- Pre-populate Create Connection env var rows with detected keys/values
  when attaching a flow version; global variable selections render as tags
  via InputComponent with global variable picker support

* feat: add empty state and smart default tab for available connections

- Default to "Create Connection" tab when no connections exist
- Show empty state with icon, description, and shortcut link when
  the Available Connections tab has no items

* feat: redesign review step with two-column layout and env vars section

Match new design reference with Deployment/Attached Flows columns
and a masked Configuration section showing env variable keys.

* feat: integrate delete deployment with loading state and fix test modal flow

- Add useDeleteDeployment hook (DELETE /deployments/{id}, refetches list)
- Show spinner + faded row while deletion is in progress; fix race where
  deleteTarget was cleared before isPending resolved by using separate deletingId state
- Redesign StepDeployStatus with animated spinner, ping ring, and success checkmark
- After deploy, "Test" closes the stepper and opens the standalone TestDeploymentModal
  (consistent UI, correct providerId, chat reset on close)
- Prevent closing the stepper modal while deployment is in progress

* refactor: address PR review concerns for deployment UI

- Split step-attach-flows.tsx (656→274 lines) into FlowListPanel,
  VersionPanel, and ConnectionPanel sub-components
- Extract Watsonx parser utilities into watsonx-result-parsers.ts,
  reducing use-deployment-chat.ts from 384 to 277 lines
- Surface detectEnvVars errors via setErrorData instead of silently
  resetting state
- Add EnvVarEntry named type to types.ts, replacing inline shape
  repeated across two files
- Move import json to module level in deployments.py (PEP 8)
- Fix URL construction in useGetDeploymentExecution to use axios
  params option, consistent with other hooks
- Remove commented-out MOCK_CONNECTIONS dead code
- Add TODO comment to hardcoded "watsonx-orchestrate" provider key

* refactor: apply React best practices and remove mock data from deployment UI

- Fix barrel imports: import directly from source files in deployments-page,
  step-provider, and step-attach-flows
- Replace useEffect auto-select with derived effectiveFlowId in step-attach-flows
- Fix async state init bug for environmentTab using useRef guard pattern
- Fix stale closure in handleAddEnvVar with functional setState
- Wrap useState initial value in lazy initializer for envVars
- Wrap all 8 handlers in useCallback; wrap panel components in memo()
- Remove mock-data.ts; move PROVIDERS constant inline to step-provider
- Drop MOCK_CONNECTIONS (was empty array) from context
- Simplify step-provider UI: remove provider selection radio group since
  only one provider exists; show watsonx Orchestrate as a static display

* feat: add Deploy button to canvas toolbar

Adds a primary-colored Deploy button at the far right of the canvas toolbar.
Clicking it saves the flow, creates a version snapshot, and opens the
deployment stepper modal with the current flow and version pre-selected in
the Attach Flows step, including auto-detection of environment variable keys.

* chore: disable ENABLE_DEPLOYMENTS feature flag

* fix: forward LANGFLOW_FEATURE_WXO_DEPLOYMENTS env var to frontend

The feature flag was reading from import.meta.env but the variable
was never injected by Vite's define config, so the deployments
feature was always disabled regardless of the .env value.

* feat: implement providers tab with environment list

Replace the "coming soon" placeholder in the Providers sub-tab with a
real table showing existing provider accounts (name, URL, provider key,
created date) fetched from the API, including loading skeleton and
empty state.

* feat: add provider creation modal with tab-aware action button

Create AddProviderModal with name, API key, and URL fields matching
the deploy modal. The top-right button now switches between
"New Deployment" and "New Environment" based on the active sub-tab.

* feat: implement provider account deletion with confirmation modal

Add useDeleteProviderAccount hook, wire it through ProvidersContent
and ProvidersTable with loading/disabled row state on delete, and
reuse DeleteConfirmationModal for the confirmation flow.

* fix: correct provider_key to watsonx-orchestrate and add API key visibility toggle

Fix the provider_key value sent to the API. Add eye/eye-off toggle
to the API Key input in both the add provider modal and the deploy
stepper's provider step.

* feat: navigate to deployments tab and open test modal after canvas deploy

After a successful deployment from the canvas deploy button, clicking
"Test" navigates to the deployments tab and auto-opens the test modal.
Also adds eye toggle to the deploy stepper's API Key field.

* Add llm config to deployment creation workflow

* [autofix.ci] apply automated fixes

* feat: add useGetDeploymentLlms query hook

Add missing query hook for the GET /deployments/llms endpoint,
resolving the broken import in step-type.tsx.

* Create provider env inline of step

Ensures the list llm call has an authed provider account to use

* feat: add extensibility for wxo tools in deployments api (#12425)

* feat(deployments): surface tool_ids in WXO API for explicit tool control
- Fix bind to reuse existing WXO tools via attachment lookup instead of
  always creating new ones
- Add tool_id-based operations (bind_tool, unbind_tool, remove_tool_by_id)
  alongside existing flow_version_id operations
- Add PATCH /deployments/snapshots/{provider_snapshot_id} endpoint to
  update snapshot content with a new flow version (blast-radius bounded
  to Langflow-tracked tools only)
- Add update_snapshot method to WXO adapter
- Enrich flow version list with deployment info (tool_id, tool_name,
  app_ids) via FlowVersionReadWithDeployments API schema
- Surface tool_id in WatsonxApiToolAppBinding responses; flow_version_id
  becomes optional for tool-id-based operations

* Revert "feat: Add Langflow Assistant chat panel for component generation (#11636)"

This reverts commit 61fac94139.

* Add some comments

* Reapply "feat: Add Langflow Assistant chat panel for component generation (#11636)"

This reverts commit d7f08791f0.

* fix(deployments): review fixes for wxo tools extensibility PR

- Add best-effort compensating rollback to update_snapshot endpoint
- Add N+1 TODO for provider account batch-fetch in build_deployment_info_map
- Remove unpopulated app_ids field from FlowVersionDeploymentInfo
- Use elif chains in validate_operation_references for tool-id ops
- Strip provider_snapshot_id once at function entry
- Add note about WXO-only update_snapshot adapter method
- Replace call-count-based _MultiQueryFakeDb with table-name dispatch
- Fix SnapshotUpdateRequest docstring route path

* fix doc

---------

Co-authored-by: Jordan Frazier <jordan.frazier@datastax.com>

* feat: allow attaching flows without connections in deployment stepper

Connections are now optional when attaching flows in step 3. Users can
skip the connection panel and proceed with just a version selected.
The deploy payload iterates selectedVersionByFlow so flows without
connections are included with an empty app_ids array.

* feat: show attached connections per flow in deployment stepper

Display connection names under each flow in the flow list panel so
users can see what's attached at a glance. Refactor the review step
to show configuration scoped per flow instead of a flat list.

* remove unused enriched flow version data. to be replaced by a new endpoint in /deployments

* Allow nonraw env vars wxo (#12435)

Allow vars to be interpreted through global vars

* feat: add update existing deployment from canvas deploy button (#12440)

* feat: add update existing deployment from canvas deploy button

When clicking Deploy on the canvas, if the flow already has existing
deployments, a choice dialog is shown allowing the user to either
update an existing deployment or create a new one. Updating calls
PATCH /deployments/snapshots/{provider_snapshot_id} with the new
flow version.

Backend changes:
- New GET /deployments/flow-attachments/{flow_id} endpoint to discover
  existing deployments for a flow
- New CRUD function list_attachments_for_flow_with_deployment_info
- New schemas FlowDeploymentAttachmentItem/FlowDeploymentAttachmentsResponse
- Fix update_snapshot to properly construct flow_definition with nested
  data structure, name, description, and last_tested_version
- Fix rollback path to cache ORM values before session.rollback()

Frontend changes:
- New useGetFlowDeploymentAttachments and usePatchSnapshot hooks
- New DeployChoiceDialog component with radio selection
- Modified deploy button to check for existing deployments on click

* feat: add flow_ids filter to deployments endpoint and fix snapshot update
Add a `flow_ids` query parameter to GET /deployments so the frontend can
discover which deployments a flow is part of. The response includes a new
`matched_attachments` field with per-attachment `flow_version_id` and
`provider_snapshot_id`, replacing the non-existent flow-attachments endpoint.
Refactor PATCH /snapshots to accept BaseFlowArtifact (via the mapper's new
resolve_snapshot_update_artifact method) instead of a raw dict, fixing the
misleading "Deployment name must include at least one alphanumeric character"
error that occurred because flow_version.data lacks a name field.
Frontend: rewrite useGetFlowDeploymentAttachments to query the real
GET /deployments endpoint per provider account.

* feat: refactor deploy dialog with update-snapshot flow and phased UI

Restructure deploy-choice-dialog into modular phases (provider, review,
deployment, update) to support both new deployments and snapshot updates.
Add use-get-deployments-by-providers query replacing the removed
flow-attachments endpoint, extract provider-credentials-form component,
and add error/navigation helpers. Backend: validate flow_id as string
in WatsonX Orchestrate service before deployment.

* [autofix.ci] apply automated fixes

* ruff

---------

Co-authored-by: Hamza Rashid <hzarashid@gmail.com>
Co-authored-by: Hamza Rashid <74062092+HzaRashid@users.noreply.github.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>

* feat: reorder model field and add scrollable dropdown in deploy wizard type step

Move Model select to appear after Agent Name (before Description) and
constrain the dropdown with max-height + scroll. A bouncing chevron
indicator fades in/out to signal more items below.

* feat(deployments): add paginated deployment flow-version listing (#12453)

* feat(deployments): add paginated deployment flow-version listing with snapshot sync
Add a new read path for listing flow versions attached to a deployment:
- introduces GET /deployments/{deployment_id}/flows with page/size pagination
- returns attachment-scoped metadata (flow_version id, flow_id, version_number, attached_at, provider_snapshot_id)
- keeps provider-owned fields under provider_data on each item
Implement snapshot-aware synchronization behavior for this list endpoint:
- loads deployment attachments from DB, extracts provider_snapshot_id values, and verifies them via adapter list_snapshots(snapshot_ids=...)
- removes stale attachment rows when snapshot IDs no longer exist on the provider
- falls back to DB-only response without enrichment on any sync failure (including partial failures after list_snapshots)
Refactor mapper boundaries to follow shape_* contract conventions:
- helper now passes through SnapshotListResult | None instead of pre-building enrichment maps
- route delegates full response shaping to mapper.shape_flow_version_list_result(...)
- base mapper performs direct DB->API mapping for flow-version list items
- WXO mapper overrides list shaping to enrich provider_data with connection_app_ids from snapshot binding.langflow.connections
Normalize WXO connection extraction into a shared read-path helper:
- add extract_langflow_connections_binding(...) in core/tools.py
- reuse it in verify_tools_by_ids and service config listing to avoid duplicated nested payload parsing
Add/adjust persistence and tests:
- add CRUD helpers for paginated attachment+flow_version join and attachment counting
- extend schema and route tests for new response models/endpoint behavior
- add mapper tests for base direct mapping and WXO-specific enrichment
- add sync tests for snapshot-id verification, stale-row cleanup, and fallback semantics

* fix(deployments): normalize wxo snapshot provider_data contracts
Validate and normalize snapshot connection payloads across mapper/service flows, and align flow-version item provider_data to use app_ids.
Add typed snapshot-item schema support in lfx and expand tests for missing/malformed snapshot provider_data behavior.

* add flow name

* return empty app_ids list instead of null

---------

Co-authored-by: Jordan Frazier <jordan.frazier@datastax.com>

* ref: remove resource name prefix (#12459)

* refactor: remove resource_name_prefix from all naming paths

Remove the resource_name_prefix concept entirely. Tool names now use the
exact flow name (or user-provided name in the future). Agent names use the
deployment name directly with no prefix.

BE:
- Delete resource_name_prefix.py
- Remove field + validators from API schemas (create + update)
- Remove field + validators from adapter schemas (create + update)
- Remove from mapper _build_provider_payload_body
- Remove resource_prefix from ProviderCreatePlan and ProviderUpdatePlan
- Remove tool_name_prefix from all tool creation functions
- Remove resolve_resource_name_prefix from utils
- Remove prefix constants from constants.py
- Remove prefixed_deployment_name from config.py
- Clean 5 test files (remove prefix-only tests, update payloads)

FE:
- Remove toResourceNamePrefix function from types.ts
- Remove resource_name_prefix from DeploymentCreateRequest type
- Remove usage from deployment-stepper-context.tsx payload builder

* [autofix.ci] apply automated fixes

* refactor: remove resource_name_prefix from all naming paths

Remove the resource_name_prefix concept entirely. Tool names now use the
exact flow name (or user-provided name in the future). Agent names use the
deployment name directly with no prefix.

BE:
- Delete resource_name_prefix.py
- Remove field + validators from API schemas (create + update)
- Remove field + validators from adapter schemas (create + update)
- Remove from mapper _build_provider_payload_body
- Remove resource_prefix from ProviderCreatePlan and ProviderUpdatePlan
- Remove tool_name_prefix from all tool creation functions
- Remove resolve_resource_name_prefix from utils
- Remove prefix constants from constants.py
- Remove prefixed_deployment_name from config.py
- Clean 5 test files (remove prefix-only tests, update payloads)

FE:
- Remove toResourceNamePrefix function from types.ts
- Remove resource_name_prefix from DeploymentCreateRequest type
- Remove usage from deployment-stepper-context.tsx payload builder

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>

* feat: wxo custom tool naming (#12460)

feat: custom tool naming when attaching flows to deployments

Users can now name tools when attaching flows in the deployment stepper.
If left blank, the flow name is used as the tool name.

BE:
- Add optional tool_name field to WatsonxApiBindOperation
- Mapper overrides raw_name_by_flow_version_id with user-provided tool_name
- Apply custom name to both raw payloads and provider bind operations

FE:
- Add toolNameByFlow state + setToolNameByFlow to stepper context
- Include tool_name in bind operations when set (trimmed, omitted if empty)
- Tool Name input in version panel (shown when a version is selected)
- Review step shows tool name (custom or flow name) in config cards
  with flow name + version underneath

* feat(deployments): derive connection ID from user-provided name

Replace random UUID generation with a sanitized version of the
connection name. Input is restricted to alphanumeric, underscore,
and space characters; spaces are converted to underscores in the ID.

* feat(deployments): prevent duplicate connection names

Disable the Create Connection button and show a validation error
when a connection with the same name (case-insensitive) already exists.

* refactor(deployments): extract page logic into custom hooks and self-contained tab components

Extract state management from the monolithic DeploymentsPage into focused
custom hooks (useDeleteWithConfirmation, useProviderFilter, useTestDeploymentModal)
and consolidate each tab's modals into its own content component, reducing the
page from 270 to 62 lines.

* fix(deployments): forward thread_id through WxO execution lifecycle

* fix(deployments): extract WxO tool call traces from actual step_history format

The parser expected tool_use/tool_result fields but WxO returns
type: "tool_calls" with tool_calls[] and type: "tool_response" —
traces were never being extracted. Rewrites extractToolTraces to
correlate calls with responses via tool_call_id, captures
agent_display_name, and makes each trace individually expandable.

* feat(deployments): refactor WXO deployment schemas and create response mapping (#12454)

* feat(deployments): add paginated deployment flow-version listing with snapshot sync
Add a new read path for listing flow versions attached to a deployment:
- introduces GET /deployments/{deployment_id}/flows with page/size pagination
- returns attachment-scoped metadata (flow_version id, flow_id, version_number, attached_at, provider_snapshot_id)
- keeps provider-owned fields under provider_data on each item
Implement snapshot-aware synchronization behavior for this list endpoint:
- loads deployment attachments from DB, extracts provider_snapshot_id values, and verifies them via adapter list_snapshots(snapshot_ids=...)
- removes stale attachment rows when snapshot IDs no longer exist on the provider
- falls back to DB-only response without enrichment on any sync failure (including partial failures after list_snapshots)
Refactor mapper boundaries to follow shape_* contract conventions:
- helper now passes through SnapshotListResult | None instead of pre-building enrichment maps
- route delegates full response shaping to mapper.shape_flow_version_list_result(...)
- base mapper performs direct DB->API mapping for flow-version list items
- WXO mapper overrides list shaping to enrich provider_data with connection_app_ids from snapshot binding.langflow.connections
Normalize WXO connection extraction into a shared read-path helper:
- add extract_langflow_connections_binding(...) in core/tools.py
- reuse it in verify_tools_by_ids and service config listing to avoid duplicated nested payload parsing
Add/adjust persistence and tests:
- add CRUD helpers for paginated attachment+flow_version join and attachment counting
- extend schema and route tests for new response models/endpoint behavior
- add mapper tests for base direct mapping and WXO-specific enrichment
- add sync tests for snapshot-id verification, stale-row cleanup, and fallback semantics

* fix(deployments): normalize wxo snapshot provider_data contracts
Validate and normalize snapshot connection payloads across mapper/service flows, and align flow-version item provider_data to use app_ids.
Add typed snapshot-item schema support in lfx and expand tests for missing/malformed snapshot provider_data behavior.

* add flow name

* return empty app_ids list instead of null

* feat(deployments): refactor WXO deployment schemas and create response mapping
Restructure the Watsonx Orchestrate deployment contracts to remove redundant connection declaration and make create responses explicit and typed.
- Remove `existing_app_ids` from API and adapter `connections` payload schemas.
- Replace shared API payload base with separate create/update models and focused validators.
- Keep validation strict (no legacy/backward-compat handling for removed fields).
- Derive provider-side `existing_app_ids` in plan builders from:
  operation app_ids - connections.raw_payloads[*].app_id
- Stop passing `existing_app_ids` through mapper payload translation.
- Add explicit create response shaping via mapper (`shape_deployment_create_result`) and route integration.
- Introduce typed create provider_data structure with `created_app_ids` and `tool_app_bindings`.
- Document and enforce `source_ref` normalization semantics:
  UUID refs map to `flow_version_id`; non-UUID refs map to `None`; empty refs error.
- Remove obsolete create-response helper path and align mapper interface signatures.
- Update unit tests and assertions to reflect the new contract and validation wording.

* improve api error logs (remove internal details and surface more informative message when an invalid field is provided

* feat(deployments): API contract updates, bug fixes, and observability improvements
BREAKING CHANGES (API):
- Move variable detection endpoint from POST /deployments/variables/detections
  to POST /variables/detections (variables router)
- Rename `reference_ids` to `flow_version_ids` in DetectVarsRequest schema
- Remove `existing_app_ids` from WXO create/update connection payloads
- Remove `resource_name_prefix` from WXO create/update payloads
- Add optional `tool_name` field to WXO bind operations
Backend:
- Rename DetectEnvVarsRequest/Response to DetectVarsRequest/Response (internal)
- Fix tool name mismatch (`name_of_raw not found in tools.raw_payloads`) during
  deployment updates by applying tool_name override and aligning
  filtered_raw_payloads with name-updated artifacts in the WXO mapper
- Fix "Missing snapshot bindings for added flow versions on update" by filtering
  out already-attached flow version IDs in the route handler before calling
  resolve_added_snapshot_bindings_for_update (stateless, DB-backed filtering)
- Switch WXO adapter core modules (retry, update, shared, create, tools) from
  stdlib logging to lfx.log.logger (structlog) for consistent log output
- Upgrade rollback log calls from info to warning level for visibility
- Add logger.exception() calls in handle_adapter_errors() for
  DeploymentServiceError, NotImplementedError, and ValueError to surface
  provider errors (e.g. validation failures) in backend logs with tracebacks
Frontend:
- Remove existingAppIds from deployment stepper context and create payload
- Move detect-env-vars hook from deployments/ to variables/ query directory
- Update step-attach-flows import path and payload field (flow_version_ids)
Tests:
- Add 15 unit tests for detect_env_vars endpoint and _derive_env_var_name helper
- Add 3 route-handler tests for already-attached flow version filtering on update
- Update WXO adapter tests: drop existing_app_ids, fix agent name assertions,
  fix mock signatures, adapt logging test for structlog

* fix: harden detect_env_vars endpoint against abuse
- Add max_length=50 on flow_version_ids to prevent resource exhaustion
- Hide /detections from OpenAPI schema (consistent with other variable routes)
- Return unresolved_ids in response so callers know which version IDs were skipped

* feat: add update agent impl (#12475)

* Allow updating an agent

ONLY allows attaching and detaching Flows.
Does NOT allow attaching / detaching connections, or editing attached
tool names.

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* remove print

* add missing files

* mypy

* Add edit flow tests

* [autofix.ci] apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>

* feat: add list all conns impl for wxo create deploy workflow (#12476)

* feat(deployments): list all WXO tenant connections in create workflow

- Fix backend list_configs to handle SDK Pydantic model objects (not just dicts)
- Add useGetDeploymentConfigs hook to fetch tenant connections by provider
- Seed existing connections into the attach-flows step on mount
- Add search/filter input for the available connections list
- Raise configs endpoint page size cap to 10k for large tenants

* test(deployments): add list_configs tests for Pydantic model handling

Cover the fix where SDK ConnectionsClient.list() returns Pydantic
model objects instead of dicts: pure models, mixed dicts+models,
deduplication, and non-dict/non-model skip behavior.

* add todo

* [autofix.ci] apply automated fixes

* fix(tests): update imports for removed to_deployment_create_response helper

The helper was replaced by BaseDeploymentMapper.shape_deployment_create_result
in the schema refactor (#12454). Update both test files to use the new method.

* fix(tests): remove shape_deployment_create_result from passthrough test

Method signature changed from single-arg passthrough to (result, deployment_row)
in the schema refactor (#12454). It's now tested in test_deployment_description_and_type.py.

* tests

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>

* feat(deployments): improve attach flow step UX in deploy modal (#12482)

- Add detach flow button in both create and edit modes
- Defer version attachment until connection step is completed (skip/attach)
- Replace radio indicators with clickable version items that auto-advance to connections
- Move tool name editing to review page with inline edit/confirm pattern
- Sort newly created connections to top of list and remove variable count display
- Add visual distinction (blue border/bg) for attached versions
- Split review page connections into "Existing" and "New" sections

* feat(deployments): add expandable rows to show attached flows (#12483)

Allow users to click the "Attached" count in the deployments table to
expand a row showing the flow names and versions. Flows are fetched
lazily via GET /deployments/{id}/flows only when the row is expanded.

* feat(deployments): replace Duplicate with Details modal (#12492)

feat(deployments): replace Duplicate action with Details modal

Replace the unused "Duplicate" action menu item with a "Details" option
that opens a read-only modal showing deployment info, attached flows,
and their connections. Data is fetched via useGetDeployment,
useGetDeploymentAttachments, and useGetDeploymentConfigs.

* Add wxo lfx req override

* feat(wxo): tool name handling, rename support, and ownership safety (#12502)

* feat(wxo): tool name handling, rename support, and ownership safety

- Fix update_snapshot to preserve existing wxO tool name instead of
  deriving from flow name (prevents overwriting custom tool names)
- Add _validate_tool_name at API boundary with deferred validation so
  user-provided tool_name overrides aren't blocked by invalid flow names
- Add rename_tool operation (API + provider + plan + apply) with safety
  checks: tool must be on agent, must exist, must have binding.langflow
- Add verify_langflow_owned guard to all tool mutation paths (create,
  update, rename) to prevent modifying non-Langflow-managed tools
- Add WXO_LFX_REQUIREMENT_OVERRIDE env var for lfx version pinning
- Pre-seed resolved_connections from existing agent tools during update
- Surface tool_name in /flows endpoint response from wxO snapshot data
- Pre-populate tool names and connections in edit mode stepper (FE)
- Emit rename_tool operations from FE when pre-existing tool name changes
- Sort attached flows to top of flow list in edit mode (FE)
- Fix FE sending unsupported existing_app_ids field in update payload
- Add 24 backend + 6 frontend tests covering ownership checks, rename
  safety, name validation, plan building, env var override, and payloads

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* chore(wxo): trim verbose pre-seeding logs, add plan entry/exit logging

- Condense per-tool pre-seeding debug logs into a single summary line
- Add plan summary log at entry of apply_provider_create_plan_with_rollback
- Add plan summary log at entry of apply_provider_update_plan_with_rollback
- Add agent creation result log in create path

* fix(wxo): resolve mypy, ruff, and lint errors

- Fix dict[str, str] → dict[UUID, str] type annotation for
  raw_name_by_flow_version_id in mapper create/update paths (mypy)
- Move logger assignment after imports in config.py (ruff E402)
- Remove unnecessary result variable in shared.py (ruff TRY300/RET504)
- Add raise-from chain in tools.py _resolve_lfx_requirement (ruff B904)
- Hoist class aliases to module level in tests (ruff N806)

* fix(wxo): resolve mypy, ruff, and lint errors

- Fix dict[str, str] → dict[UUID, str] type annotation for
  raw_name_by_flow_version_id in mapper create/update paths (mypy)
- Use .items() for dict iteration instead of key-only loop (ruff PLC0206)
- Move logger assignment after imports in config.py (ruff E402)
- Remove unnecessary result variable in shared.py (ruff TRY300/RET504)
- Add raise-from chain in tools.py _resolve_lfx_requirement (ruff B904)
- Split long log format string in create.py (ruff E501)
- Hoist class aliases to module level in tests (ruff N806)

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>

* refactor(deployments): Revise v1 deployments API (#12478)

* refactor(deployments): trim top-level deployment API surface for WXO-first flow
- Remove unused deployment stub routes and schemas:
  - drop POST /deployments/{deployment_id}/redeploy and /duplicate handlers
  - remove DeploymentRedeployResponse and DeploymentDuplicateResponse usage
  - remove corresponding route-handler unit tests
- Simplify deployment list response contract:
  - remove deployment_type from DeploymentListResponse
  - update deployments route and base/WXO mapper list shapers to stop passing deployment_type
- Make deployment request schemas API-owned and stricter:
  - replace shared-kernel strict wrappers with DeploymentSpec / DeploymentSpecUpdate
  - remove create/update top-level config and flow-version mutation fields
    (flow_version_ids, add_flow_version_ids, remove_flow_version_ids, config)
  - tighten update validation to only accept spec and/or provider_data
- Align mapper behavior with trimmed API contracts:
  - base mapper create/update now maps spec explicitly to BaseDeploymentData/BaseDeploymentDataUpdate
  - remove base create/update handling for top-level snapshot/config/flow-version passthrough
  - make base util_create_flow_version_ids and util_flow_version_patch return empty results by default
  - update WXO mapper to use explicit spec mapping and provider_data-only operation reconciliation
  - remove WXO 422 guards tied to removed top-level config/flow-version request fields
- Remove obsolete provider_spec plumbing in adapter schema/utilities:
  - drop ProviderSpecModel and T_DeploymentSpec usage from lfx deployment schema
  - make BaseDeploymentData inherit directly from BaseModel
  - remove unused build_agent_payload helper that depended on provider_spec from WXO utils
- Update tests to reflect the trimmed contracts and current behavior:
  - remove schema tests for removed config/flow-version helper models
  - update schema compatibility tests to reject provider_spec in API deployment spec
  - update base mapper tests for new create-result shaping and provider payload validation expectations
  - remove WXO mapper tests asserting rejected top-level config/flow-version inputs
  - adjust WXO mapper naming assertions to current flow/tool naming behavior
  - update sync/service/payload formalization tests for provider_data-driven operations and provider_spec removal

* refactor(deployments): normalize deployment metadata and list payload contracts
- Source `get_deployment` name/description/type/timestamps from DB deployment rows and stop injecting `resource_key` into provider payloads.
- Clarify schema docs that `resource_key` is provider-originated but Langflow-owned once persisted.
- Replace `DeploymentConfigListItem`/`DeploymentSnapshotListItem` response envelopes with paginated `provider_data` payloads in API schemas.
- Update base deployment mapper to serialize config/snapshot items directly into paginated `provider_data.configs` and `provider_data.snapshots`.
- Add WXO API payload models and validation slots for config-list and snapshot-list provider result metadata.
- Add WXO adapter payload result contracts (`WatsonxConfigListResultData`, `WatsonxSnapshotListResultData`) and register them in deployment payload schemas.
- Update WXO service list-config/list-snapshot flows to parse and emit normalized provider result metadata (tenant scope now `{}`, deployment scope includes `deployment_id` and optional `tool_ids`).
- Remove `provider_data` from `lfx` `ConfigListItem` to align with the new list response contract.
- Update mapper registration tests to assert config/snapshot payload slots are wired.
- Update route-handler tests for new provider-result expectations and add regression coverage that `resource_key` is not injected into `provider_data`.
- Rewrite deployment schema tests around provider-data-only config/snapshot list responses and field-surface checks.
- Update WXO service tests for tenant-scope provider-result normalization.
- Update `lfx` schema tests to remove obsolete config-item `provider_data` assertions.

* feat(deployments): add WXO mapper shaping for config-list and snapshot-list responses
- Add `shape_config_list_result` and `shape_snapshot_list_result` to WXO
  deployment mapper with pagination, slot validation, and HTTP 500 on
  malformed payloads.
- Add `WatsonxApiConfigListItem` and `WatsonxApiSnapshotListItem` strict
  payload models with string normalization validators.
- Wire `configs` and `snapshots` item lists into the existing
  `WatsonxApiConfigListProviderData` and `WatsonxApiSnapshotListProviderData`
  provider-data envelopes.
- Add mapper unit tests for config-list slot validation, snapshot-list
  connections extraction, and malformed-payload rejection.
- Remove obsolete `resource_name_prefix` and `connections` from
  deployment-sync update test fixture.

* feat(deployments): add provider identity to responses, nest execution endpoints under deployments
Surface provider_id and provider_key on all deployment responses so
clients can identify which provider owns a deployment without a side
lookup. Nest execution endpoints under their parent deployment path
and drop redundant deployment_id / provider_id parameters that clients
previously had to supply.
Deployment responses:
- Add provider_id (UUID) and provider_key (str) to _DeploymentResponseBase,
  propagating to DeploymentGetResponse, DeploymentCreateResponse,
  DeploymentUpdateResponse, DeploymentStatusResponse, and DeploymentListItem.
- Add provider_key parameter to BaseDeploymentMapper.shape_deployment_create_result,
  shape_deployment_update_result, and shape_deployment_list_items.
- Update WatsonxOrchestrateDeploymentMapper overrides to match.
- Update resolve_adapter_from_deployment to return (row, adapter, provider_key)
  and resolve_adapter_mapper_from_deployment to return
  (row, adapter, mapper, provider_key).
- All route handlers pass provider_key through to shape methods and
  response constructors.
Execution endpoints:
- POST /executions → POST /deployments/{deployment_id}/executions.
  deployment_id moves from the request body to the URL path.
- GET /executions/{execution_id}?deployment_id=...
  → GET /deployments/{deployment_id}/executions/{execution_id}.
  deployment_id moves from a query param to the URL path.
- Remove deployment_id from ExecutionCreateRequest schema.
- Remove unused resolve_adapter_mapper_from_provider_id import.
Tests:
- Update all mapper tests to pass provider_key and assert provider_id /
  provider_key on shaped responses.
- Update route handler mocks for new helper return tuple sizes.
- Remove deployment_id from ExecutionCreateRequest test constructions.
- Fix pre-existing broken test_deployments_response_mapping.py (was
  importing removed to_deployment_create_response helper; now uses
  BaseDeploymentMapper.shape_deployment_create_result).

* refactor(deployments): delegate conflict error messaging to provider mappers
Move provider-specific conflict formatting out of shared helpers by adding a base mapper hook and a Watsonx override, thread mapper-aware conflict formatting through adapter error handling, and add tests for mapper delegation and fallback behavior.

* refactor(deployments): rename provider-account API fields and make update identifiers immutable
- rename provider-account API fields for cleaner contracts:
  - create/get: provider_tenant_id -> tenant_id
  - create/get: provider_url -> url
  - keep provider_key and provider_data unchanged
- enforce immutable provider-account identifiers on PATCH:
  - remove tenant_id and url from DeploymentProviderAccountUpdateRequest
  - remove update-path URL allowlist validation
  - trigger update credential verification only when provider_data changes
  - limit provider-account updates to name and provider_data
- simplify mapper update behavior:
  - resolve_provider_tenant_id now uses tenant_id parameter naming
  - remove no-op WXO resolve_provider_account_update override
  - remove dead auth_utils/decrypt path in WXO update verification
- align frontend deployment-provider-account usage with new API fields:
  - POST payload now sends url
  - ProviderAccount/ProviderCredentials now use tenant_id/url
  - deployment provider UI components now read/write url consistently
- update deployment mapper rules and backend tests for new contract
- verify with targeted backend tests: 245 passed

* fix(deployments): flatten API payloads, normalize execution routes, and trim null response fields
- flatten v1 deployment API request contracts by removing nested `spec` from create/update payloads
  - create now uses top-level `name`, `description`, `type`
  - update now uses top-level `name`, `description`, `provider_data`
- update backend handlers and mapper wiring to consume top-level deployment fields end-to-end
- fix execution route paths to avoid duplicated segment:
  - `/api/v1/deployments/{deployment_id}/executions`
  - `/api/v1/deployments/{deployment_id}/executions/{execution_id}`
- align frontend execution query hooks/chat flow with deployment-id path params and remove provider-id execution params
- add response null-trimming tweaks in deployment read/list endpoints:
  - set `response_model_exclude_none=True` on deployment list route
  - set `response_model_exclude_none=True` on deployment get route
  - normalize empty/non-dict `provider_data` to `None` before shaping detail response
- tighten watsonx API mapper payload contract:
  - type `connections.raw_payloads[*].environment_variables` as `dict[EnvVarKey, EnvVarValueSpec]`
  - remove unused API-level `provider_config` field from update raw connection payload
- refresh backend/frontend tests and deployment endpoint docs to match current API shapes and routes

* feat(deployments): redesign list contracts and normalize WXO payloads
Rework deployment list and flow attachment contracts to support flow-filtered list responses and lazy flow-version lookup in the frontend deploy dialog. Normalize WXO provider payload shapes by flattening provider entries, renaming identifier fields, and tightening adapter/API validation.
- replace deployment list-item matched_attachments with conditional flow_version_ids (omitted when no flow filter is provided)
- add flow_ids support to GET /api/v1/deployments/{id}/flows and propagate it through deployment sync helpers and flow_version_deployment_attachment CRUD filters
- flatten load_from_provider deployment entries, rename provider resource_key to id, and validate WXO entries with explicit fields
- rename WXO provider_data snapshot_ids to tool_ids for provider list/config metadata payloads
- inline WXO provider list entry model_validate payload construction for cleaner mapper logic
- add deployment description max-length contract in adapter/API schemas and enforce it in deployment CRUD create/update paths
- update frontend deploy-choice dialog to a two-request flow (list deployments first, fetch /flows on selection) and align FE deployment types/query hook params
- refresh mapper/route/schema/sync/frontend tests and add dedicated CRUD tests for deployment description length validation

* feat(deployments): align WXO provider_data list and connection payload contracts
- make provider-only deployment list responses use provider_data.deployments and omit top-level deployments/pagination fields
- rename config/snapshot provider_data list keys to connections and tools, and move page/size/total into provider_data
- remove provider_data.deployment_id from config/snapshot list payload shaping
- rename API connection input fields from raw_payloads to key_value and environment_variables to credentials
- add explicit credential item model (key/value/source) with duplicate-key validation
- map API credentials list back to adapter environment_variables dict in mapper for adapter compatibility
- make shared pagination fields optional in deployment response schemas and update config-list provider_data description to "connections"
- set response_model_exclude_none on /configs and /snapshots list routes to suppress unused top-level null pagination fields
- apply formatter quote normalization in WXO config validation debug log

* feat(deployments): add connection type to config listings, enforce security_scheme, and trim leaked adapter fields
- Config list items now expose a `type` field derived from the provider's
  `security_scheme`, enabling callers to distinguish connection types
  (e.g. `key_value_creds`) without a separate lookup
- Requests that return provider_data without a valid `security_scheme`
  now fail fast with HTTP 500 instead of silently omitting the type
- Config list responses no longer leak `tool_ids` or `deployment_id` —
  these were adapter-internal fields with no frontend or API consumers
- Snapshot list responses no longer leak `deployment_id`

* feat(deployments): flatten WXO API operations into per-entity keyed fields
Replace the discriminated `operations` array with explicit per-entity
fields for better type safety and developer experience:
- Create: `add_flows` + `upsert_tools` (create-only item, no remove_app_ids)
- Update: `upsert_flows` + `upsert_tools` + `remove_flows` + `remove_tools`
Each item carries its own add/remove app-id deltas instead of relying on
op-tag dispatch. The mapper consumes the new shapes directly and produces
unchanged adapter-layer operations, eliminating all isinstance dispatch.
Also corrects FlowVersionPatch semantics: upsert_flows.remove_app_ids
now only unbinds connections without detaching the flow from the agent;
detachment is exclusively driven by remove_flows.

* feat(deployments): align watsonx create/update payloads and created-tools responses
- Add `resource_key` to deployment create/update API responses and mapper output.
- Replace API-facing `tool_app_bindings` with `created_tools` in watsonx mapper responses.
- Shape `created_tools` from created snapshot/tool refs only (not all referenced tools).
- Flatten request `provider_data.connections` from nested `connections.key_value` to a direct list.
- Add duplicate `connections.app_id` validation using Counter and update related validation messages.
- Document connection typing strategy: implicit key_value today, future type field with default.
- Add strict `flow_version_id` validation on `WatsonxApiCreatedTool`
  (accept UUID or UUID string; reject other types/invalid UUIDs).
- Update mapper/unit tests for new response contract, flattened connections, and non-UUID rejection.

* fix(deployments): allow watsonx updates without llm
Make PATCH provider_data.llm optional in the Watsonx deployment flow while preserving create-time llm requirements.
- allow missing llm in the API update payload model
- only include llm in mapper-built provider payloads when explicitly provided
- remove adapter update-schema validation that required llm for update operations
- clarify validator docs for empty/no-op provider_data handling
- update mapper/service/schema tests to accept update payloads without llm

* fix(deployments): normalize wxo config list to connection_id/app_id and fix provider_accounts naming
Align the config-list contract end-to-end so that items are keyed by
connection_id + app_id (matching the upstream SDK model) instead of
opaque id/name pairs derived from dict introspection.
Backend:
- Reshape mapper/payloads to emit connection_id/app_id/type.
- Replace loose dict/model_dump parsing with strict ListConfigsResponse
  type checks; add _build_config_list_item factory and
  _normalize_optional_text with documented SDK quirk guards.
- Enrich deployment-scope configs with security_scheme type via
  get_drafts_by_ids.
- Rename DeploymentProviderAccountListResponse.providers to
  provider_accounts for consistency with the entity name.
- Remove leftover debug print/hardcoded requirements in core/tools.
Frontend:
- Migrate DeploymentConfigItem to connection_id/app_id/type and
  unwrap provider_data.connections in the query hook.
- Access provider_accounts instead of providers on the list response.
- Add onBlur confirm for editable tool names; fix overflow/truncation
  in the connection panel.
Tests:
- Use real ListConfigsResponse SDK model in service tests.
- Add scope-shape consistency, type preservation, dict-filtering, and
  mapper contract tests.

* fix(deployments): remove stale-tool fallback in list_snapshots and log unresolved IDs
Replace the phantom-stub fallback that synthesized SnapshotItems for
agent-referenced tool IDs when get_drafts_by_ids returned no results.
Those tools were likely deleted on the provider, and returning stubs
with the ID as the name and empty connections masked stale references
and risked corrupting downstream attachment sync.
Now returns only snapshots that actually resolve from the provider and
logs a warning with the stale tool IDs for observability. Also handles
partial resolution (some tools found, some not).
Update existing test to provide real tool data and add coverage for
all-stale and partial-resolution scenarios.

* fix(deployments): fail fast on invalid wxo config entries and trust provider identifiers
Fail fast when wxO returns unexpected config-list entry types, and preserve provider-provided connection/app identifiers without local normalization or deduplication. Also narrow conflict-detail mapping for connection errors to real conflict messages and update tests to match the new behavior.

* refactor: move tenant_id from top-level into provider_data for provider accounts
tenant_id is a provider-specific concept (e.g., WXO tenant vs Azure AD
tenant vs AWS account_id) and does not have universal semantics across
deployment providers. Moving it into provider_data keeps the top-level
API surface limited to Langflow-universal fields (id, name, provider_key,
url, timestamps) and lets each provider define its own metadata shape.
API schema changes:
- DeploymentProviderAccountCreateRequest: remove top-level tenant_id
  field; tenant_id now arrives inside provider_data alongside api_key
- DeploymentProviderAccountGetResponse: remove top-level tenant_id;
  add provider_data field for non-sensitive provider metadata (e.g.
  {"tenant_id": "..."} for WXO); credentials are excluded
- DeploymentProviderAccountUpdateRequest: unchanged (already uses
  provider_data for credential rotation)
Base mapper (base.py):
- resolve_provider_tenant_id: signature changed from (provider_url,
  tenant_id) to (provider_url, provider_data); delegates to new
  resolve_provider_tenant_id_from_data() for extraction/validation
- shape_provider_account_response: now includes provider_data via new
  shape_provider_account_provider_data() method that returns non-sensitive
  metadata (tenant_id when present)
WXO mapper (watsonx_orchestrate/mapper.py):
- resolve_provider_tenant_id: updated signature; extracts tenant_id
  from provider_data first, falls back to URL extraction
- _validate_provider_data: strips mapper-owned metadata keys (tenant_id)
  before passing to WatsonxVerifyCredentialsPayload slot (extra=forbid)
- New _credential_provider_data() helper for metadata/credential separation
Route + helpers:
- deployments.py create_provider_account: passes payload.provider_data
  (not payload.tenant_id) to resolve_provider_tenant_id
- helpers.py resolve_provider_tenant_id: updated parameter from
  tenant_id to provider_data
Frontend:
- ProviderAccount type: replaced tenant_id with optional provider_data
RULES.md: updated credential flow and defense-in-depth sections to
reflect provider_data as the source for provider metadata.
Tests: updated schema, base mapper, WXO mapper, and route handler tests
to use provider_data for tenant_id. Added tests for tenant metadata
passthrough, credential field filtering, and top-level tenant_id
rejection. Fixed two pre-existing test stubs missing resource_key.
No DB model or migration changes -- provider_tenant_id column remains;
the mapper extracts it from provider_data and stores it as before.

* fix: follow deployment boundary rules and fail fast (wxo) (#12539)

* feat(wxo): filter configs to key_value_creds, surface type and environment, harden mapper contract
Service layer (service.py):
- Filter list_configs to only return connections with security_scheme == "key_value_creds" in both tenant and deployment scopes
- Surface `environment` field alongside `type` in provider_data for config list items
- Normalize security_scheme via _normalize_optional_text to handle SDK enum/tuple quirks
- Extract _warn_if_expected_ids_missing helper to deduplicate staleness warnings
- Remove defensive isinstance checks on provider responses (trust the provider)
- Replace conflicting-binding error with last-write-wins (app_to_connection_id.update)
- Deduplicate connection IDs before calling get_drafts_by_ids
Mapper layer (mapper.py):
- Fail fast with HTTP 500 if config list item is missing a truthy `type`
- Conditionally include `environment` in shaped config list payload
Payloads (payloads.py):
- Add `environment: str | None` field to WatsonxApiConfigListItem with normalizing validator
Tests:
- Add test for deployment-scope key_value_creds filtering (mixed security schemes)
- Add test for tenant-scope key_value_creds filtering (oauth2 excluded)
- Add test for environment metadata passthrough in mapper and service
- Add tests for provider failure paths (tenant list failure, None response, tool fetch failure)
- Add tests for edge cases (latest-binding-wins, skip enrichment with no connections, malformed detailed connection)
- Update mapper tests to assert fail-fast on missing type
- Update existing fixtures to include security_scheme where required by new filtering

* refactor(deployments): move flow-version tool_name into provider_data
Move provider tool_name from a top-level flow-version response field into
provider_data, aligning API ownership boundaries for provider-originated
non-persisted fields.
- Remove top-level tool_name from DeploymentFlowVersionListItem
- Add tool_name to WatsonxApiDeploymentFlowVersionItemData with normalization
- Update WXO mapper to shape tool_name under provider_data
- Update frontend attachments type and consumer to read provider_data.tool_name
- Update backend tests for new response contract location
- Add explicit RULES.md requirement for non-persisted provider data placement

* make environment required

* refactor list configs method and fix broken tests

* feat(deployments): type-to-confirm dialog for deployment deletion (#12546)

* feat(deployments): replace simple delete confirm with type-to-confirm dialog

Deleting a deployment is irreversible — it removes the agent from both
Langflow and Watsonx Orchestrate permanently. Require the user to type
the deployment name before the Delete button activates, matching
industry-standard patterns (GitHub, AWS).

- Add `TypeToConfirmDeleteDialog` component (deployment-specific, not shared)
- Input resets on close; label + placeholder for accessibility
- Replace `DeleteConfirmationModal` in `deployments-content.tsx`
- 6 unit tests covering all confirmation behaviours

* fix(deployments): address PR review findings on type-to-confirm dialog

- Fix icon spacing: replace pr-1 with mr-2 on AlertTriangle (padding
  was compressing the SVG viewport instead of creating sibling spacing)
- Fix label copy: "agent name" → "deployment name" to cover both agent
  and MCP deployment types
- Remove unused cancelDelete from useDeleteWithConfirmation — callers
  close the dialog via setModalOpen; the export was dead code
- Add case-sensitivity test to type-to-confirm-delete-dialog tests
- Add unit tests for useDeleteWithConfirmation hook (8 tests covering
  requestDelete, confirmDelete, onSettled, onError, and setModalOpen)

* test(deployments): add comprehensive frontend test suite for WXO deployments (#12535)

* test(deployments): add unit tests for all deployment API query and mutation hooks

16 test files covering deployment queries, mutations, provider accounts,
execution hooks, and env var detection (59 tests total).

* test(deployments): add stepper context create-mode tests and expand edit-mode/tool-naming coverage

Step 2 of the frontend deployment test plan — 63 new tests (93 total)
covering create-mode payload builders, step validation, provider
selection, multi-flow scenarios, partial update payloads, detach/re-attach
flows, and tool naming edge cases.

* test(deployments): add component rendering tests for Step 3 (163 tests, 10 files)

Covers tables, stepper steps, connection panel, and modals with data-testid additions to source components for reliable targeting.

* test(deployments): add custom hook unit tests for Step 4 (121 tests, 7 files)

Covers useErrorAlert, useProviderFilter, useNavigateToTest, useDeleteWithConfirmation,
useTestDeploymentModal, useDeploymentChat (polling, thread_id, timeouts, tool traces),
and watsonx-result-parsers (extractText, extractToolTraces, extractThreadId).

* test(deployments): add deploy button and choice dialog unit tests for Step 5 (76 tests, 3 files)

- deploy-button.test.tsx (12 tests): feature-flag rendering, disabled states
  (no flow/preparing/dialog open), handleDeploy click, animate-pulse on icon
- deploy-choice-dialog/index.test.tsx (30 tests): phase transitions
  (provider → deployments → review → update), auto-select single attachment,
  provider key mapping, patchSnapshot args, update/error flows, onUpdateComplete
- deploy-choice-dialog/hooks/use-prepare-deploy.test.ts (34 tests): handleDeploy
  save/snapshot/provider fetch, no-flow bail-out, deployModal vs choiceDialog
  branching, error handling, handleChooseNew, handleUpdateComplete, resetChoiceState

* test(deployments): add E2E Playwright tests for Step 6 (28 tests, 5 files)

- deployments-page.spec.ts: page nav, empty/loaded states (5 tests)
- deployment-create.spec.ts: full create wizard, POST, deploy status (6 tests)
- deployment-edit.spec.ts: edit mode, PATCH, cancel (5 tests)
- deployment-providers.spec.ts: add/delete providers, confirmation (6 tests)
- deployment-test-modal.spec.ts: chat, polling, multi-turn, reset (6 tests)

Add shared deployment-mocks.ts for mock data reuse across all specs.

Add data-testid to stepper modal title, add-provider modal title, and
test-deployment modal title to avoid strict-mode selector violations.

Add data-testid to provider radio items in step-provider.tsx.

Set LANGFLOW_FEATURE_WXO_DEPLOYMENTS=true in CI workflow env.

* fix(tests): update deployment E2E mocks for wxo-fe API changes

- provider_accounts field rename: { providers } → { provider_accounts }
- ProviderAccount.provider_url → ProviderAccount.url
- Execution endpoints moved to deployment-scoped URLs:
  POST /deployments/executions → /deployments/{id}/executions
  GET /deployments/executions/{exec_id} → /deployments/{id}/executions/{exec_id}
- Remove deployment_id from POST execution request body (now in URL path)

* fix(tests): update unit tests for wxo-fe API shape changes

- ProviderAccount: provider_url → url, removed provider_tenant_id
- Provider list response: { providers } → { provider_accounts }
- ProviderCredentials: provider_url → url
- Deployment payload: spec.{name,description,type} → top-level fields
- Provider data: operations → add_flows/upsert_flows/remove_flows
- Connections: raw_payloads[].environment_variables → connections[].credentials
- DeploymentConfigItem: { id, name } → { app_id, connection_id }

* fix(tests): align frontend tests with revised deployments API shape

Update unit tests, E2E mocks, and the ProviderAccountListResponse type
to match the API changes from the v1 deployments revision (#12478):
- execution endpoints now use deployment_id in URL path
- getExecution uses deployment_id + execution_id (no provider_id)
- provider accounts response key changed to provider_accounts
- deployment configs response wrapped in provider_data
- deploy-choice-dialog now uses useGetDeploymentAttachments

* fix(ci): read LANGFLOW_FEATURE_WXO_DEPLOYMENTS from process.env fallback

Vite config only read feature flags from the .env file via dotenv,
ignoring CI workflow environment variables. This caused all 28
deployment E2E tests to fail because the flag was never enabled.

* fix(tests): add missing resource_key to deployment mapper test mocks

The SimpleNamespace mocks in TestCreateResponse and TestMapperUpdateResult
were missing the resource_key attribute now required by the mapper.

* test(deployments): add E2E tests for type-to-confirm deployment deletion

Adds testid to the delete dropdown item and four Playwright tests covering:
- dialog opens on delete action
- confirm button disabled until name matches exactly
- confirming with correct name calls DELETE /api/v1/deployments/{id}
- cancel dismisses without calling DELETE

* chore: trigger CI

* fix(deployments): remove unused description field from connection panel (#12549)

The Description input in the Create Connection tab was never persisted —
ConnectionItem has no description field and the value was not sent to any API.

* fix(deployments): enforce single-environment filter on deployments page (#12551)

fix(deployments): enforce single-environment filter and reorder provider form fields

Remove the "All environments" global listing mode from the deployments
page. Deployments are now always fetched for a single selected
environment, avoiding N parallel API calls that each trigger a backend
sync. Also differentiates empty states (no providers vs no deployments)
and reorders the provider credentials form to show URL before API key.

* be test

* be test

---------

Co-authored-by: Jordan Frazier <jordan.frazier@datastax.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Hamza Rashid <74062092+HzaRashid@users.noreply.github.com>
Co-authored-by: Hamza Rashid <hzarashid@gmail.com>
Co-authored-by: Jordan Frazier <122494242+jordanrfrazier@users.noreply.github.com>
2026-04-08 10:00:41 +00:00
094b4c3882 fix: Accept appropriate types in OpenSearch mm (#12547)
* fix: Accept appropriate types in OpenSearch mm

* [autofix.ci] apply automated fixes

* Update opensearch_multimodal.py

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* [autofix.ci] apply automated fixes (attempt 3/3)

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-08 00:12:44 +00:00
6ac84d4745 fix: Indefinitely loading KB page for errors (#12295)
* fix indefinitely loading KB page

* [autofix.ci] apply automated fixes

* retry for 5XX error

* [autofix.ci] apply automated fixes

* improved testcase name

---------

Co-authored-by: Olayinka Adelakun <olayinkaadelakun@mac.war.can.ibm.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Carlos Coelho <80289056+carlosrcoelho@users.noreply.github.com>
Co-authored-by: Olayinka Adelakun <olayinkaadelakun@Olayinkas-MacBook-Pro.local>
2026-04-08 00:00:02 +00:00
f30b291f80 fix: Replace aiofile with aiofiles to prevent caio context leak under concurrent execution (#12525)
* fix: replace aiofile with aiofiles to prevent caio context leak under concurrent execution

aiofile uses caio (kernel AIO) which creates contexts in a global dict
that are never cleaned up. Under concurrent execution these accumulate
until the OS aio-max-nr limit is exhausted, causing
SystemError(11, 'Resource temporarily unavailable'). aiofiles uses
thread pools instead and does not have this issue.

Migrates all aiofile.async_open usages across both backend and lfx
packages to aiofiles.open.

Based on #12433 by @manav2000, extended to cover all remaining usages.

Co-Authored-By: manav2000 <manav2000@users.noreply.github.com>

* test: add concurrent write-then-read regression test for caio EAGAIN fix

Exercises the exact failure pattern from #12414: multiple concurrent
save-then-immediately-read operations on the storage service. This
would previously trigger SystemError(11, EAGAIN) after ~150-200 runs
with the aiofile/caio backend.

Co-Authored-By: manav2000 <manav2000@users.noreply.github.com>

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

---------

Co-authored-by: manav2000 <manav2000@users.noreply.github.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-07 23:12:19 +00:00
23eebd037d fix: Restore MCP tool dropdown visibility when adding component from sidebar (#12550)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-07 19:48:06 -03:00
ca5fe56e1b feat(agentics): Refactor bundle components to agenerate/amap/areduce pattern for Langflow 1.9 (#12518)
Co-authored-by: Alfio Gliozzo <gliozzo@us.ibm.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-07 17:13:06 -03:00
8c50fca825 feat(playground): Add auth gate, session persistence and token display to shareable playground (#12519)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-07 17:03:05 -03:00
4f9beebc00 fix: add trailing newline to component_index.json (#12545)
The build_component_index.py script was generating component_index.json
without a trailing newline, causing CI failures when autofix.ci tried to
add the missing newline. This fix ensures the generated JSON file always
ends with a newline character, following POSIX text file standards.

Fixes the 'No newline at end of file' error in the update-component-index
workflow job.
2026-04-07 15:22:36 -04:00
dbd31e0472 fix: Preserve MCP tool selection on flow reload (#12363)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-07 11:18:35 -03:00
74f17b40e0 fix(ui): Fix update banner hidden behind canvas controls (#12527) 2026-04-07 11:17:33 -03:00
6938fd1d17 fix: Display proper error messages and strip null params from tool calls (#12437) 2026-04-07 11:17:23 -03:00
a2e2b44087 feat: add telemetry service to lfx MCP server (#12422)
* feat: add telemetry service to lfx MCP server

Replace the no-op telemetry stub with a real async implementation
that sends lightweight analytics to Scarf via GET query params.

- New schema.py with MCPToolPayload and standard payload types
- TelemetryService with async queue, httpx client, DO_NOT_TRACK support
- @_tracked decorator on all 31 MCP tools for automatic tracking
- Failure-safe: suppress(BaseException) ensures telemetry never breaks tools
- Worker guards against task_done without get, flush has 5s timeout

* fix: address telemetry review feedback

- Replace str(exc)[:200] with type(exc).__name__ to avoid leaking
  sensitive user data in GET query params sent to Scarf
- Manage telemetry lifecycle via FastMCP lifespan hook instead of
  lazy module-level singleton that never called stop()
- Change duration tracking from int(seconds) to milliseconds to
  preserve sub-second granularity
- Update tests to exercise start/stop lifecycle, DO_NOT_TRACK gating,
  enqueue behavior, and teardown after start

---------

Co-authored-by: Eric Hare <ericrhare@gmail.com>
2026-04-07 12:01:44 +00:00
4b64f20b3a docs: investigate deprecated macOS support and impact on Langflow (LE-265) (#12477)
docs: add deprecated macOS support investigation (LE-265)
2026-04-06 22:07:51 +00:00
f4a3e5fd08 fix: Search beyond the first page of users (#12203)
* fix: Search beyond the first page of users

* Add a test for search functionality

* Update users.py

* Update index.tsx

* Update index.tsx

* Update auto-login-off.spec.ts

* Update auto-login-off.spec.ts

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-06 22:02:41 +00:00
13bfd4f8bc docs: investigate PyTorch macOS AMD64 + Python 3.13 CI failure (LE-172) (#12469)
* docs: add PyTorch macOS AMD64 + Python 3.13 investigation (LE-172)

Investigate why the experimental CI job fails on macOS x86_64 + Python 3.13.

Root cause: PyTorch dropped macOS Intel wheel builds after v2.2.2 (before
Python 3.13 existed). The altk and langchain-huggingface extras pull in
torch without platform guards, causing installation failures.

Includes analysis of dependency chains, lockfile resolution behavior,
and 4 actionable options (A-D) with tradeoffs for the team to decide on.

* fix: exclude torch-dependent extras on macOS x86_64 (LE-172)

Add platform exclusion markers to altk and langchain-huggingface extras
to prevent torch from being pulled in on macOS Intel where no wheel exists.

This matches the existing pattern used for easyocr and docling extras.
PyTorch dropped macOS x86_64 binary support after v2.2.2, so these
features cannot work on Intel Macs regardless.
2026-04-06 21:52:06 +00:00
c6b87e7595 fix: preserve nested dictionaries in MCP tool parameters (#11970)
* fix: preserve nested dictionaries in MCP tool parameters (#9881)

When MCP tool schemas define object-type fields without explicit properties,
the system now treats them as free-form dictionaries (dict[str, Any]) instead
of creating empty Pydantic models. This preserves nested data structures that
were previously being lost during validation.

Before this fix:
  Input:  {'msg': {'linear': {'x': 1}}}
  Output: {'msg': {}}  # nested data lost!

After this fix:
  Input:  {'msg': {'linear': {'x': 1}}}
  Output: {'msg': {'linear': {'x': 1}}}  # preserved!

Changes:
- Modified parse_type() in json_schema.py to detect objects without properties
  and use dict[str, Any] instead of creating empty BaseModel subclasses
- Added regression test test_nested_dict_preservation_issue_9881()
- All existing tests pass (94 passed, 7 skipped)

Fixes #9881

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

---------

Co-authored-by: Claude Sonnet 4.5 <noreply@anthropic.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-06 21:22:35 +00:00
f8aa12d404 fix(ci): add missing SDK build step to cross-platform workflow_dispatch (#12536)
The build-if-needed job (used for workflow_dispatch) was not building
the langflow-sdk package. Since lfx depends on langflow-sdk>=0.1.0
and langflow-sdk is not yet published to PyPI, all test jobs failed
during lfx installation with 'No solution found'.

Changes:
- Build langflow-sdk wheel in build-if-needed job
- Upload SDK artifact and output sdk-artifact-name
- Update SDK download conditions with build-if-needed fallback
- Update SDK+LFX combined/individual install conditions to properly
  route through the combined installer when both are available
2026-04-06 17:29:14 -04:00
f557b06c3b fix: upgrade vulnerable dependencies with override enforcement (#12526)
security: upgrade vulnerable dependencies with override enforcement

- Add security overrides for orjson, gunicorn, pypdf, nltk, markdown, dynaconf, pillow
- Update base pyproject.toml: pillow>=12.0.0, pypdf>=6.9.0
- Selective upgrade: only orjson (3.11.7->3.11.8) and pillow (11.3.0->12.2.0)
- Resolves 7/8 flagged CVEs (diskcache awaiting upstream fix)
- Defense-in-depth: TOML minimums + override enforcement

Co-authored-by: Janardan S Kavia <janardanskavia@Janardans-MacBook-Pro.local>
2026-04-06 20:26:04 +00:00
4ee94e6ce6 fix(ci): add missing lfx build step to cross-platform workflow_dispatch (#12524)
The build-if-needed job (used by workflow_dispatch) was missing the
lfx package build, causing all cross-platform tests to fail with:

  'No solution found: lfx>=0.4.0 required but only <=0.3.4 available'

Changes:
- Build lfx wheel in build-if-needed job
- Upload lfx artifact (adhoc-dist-lfx)
- Add lfx-artifact-name to job outputs
- Update all test jobs to fallback to build-if-needed outputs
  for lfx artifact (matching existing base/main pattern)
2026-04-06 15:58:54 -04:00
1e61ac4ebe Merge remote-tracking branch 'origin/release-1.8.4'
# Conflicts:
#	src/backend/base/langflow/api/v1/chat.py
#	src/backend/tests/unit/test_chat_endpoint.py
1.9.0
2026-04-06 15:28:41 -04:00
7f44894b77 Merge remote-tracking branch 'origin/release-1.8.3'
# Conflicts:
#	src/backend/tests/unit/test_unified_models.py
2026-04-06 15:22:06 -04:00
2fa3b360d0 Merge remote-tracking branch 'origin/release-1.8.2'
# Conflicts:
#	.secrets.baseline
#	pyproject.toml
#	src/backend/base/langflow/initial_setup/starter_projects/Hybrid Search RAG.json
#	src/backend/base/langflow/initial_setup/starter_projects/Knowledge Retrieval.json
#	src/backend/base/langflow/initial_setup/starter_projects/Research Translation Loop.json
#	src/backend/base/langflow/initial_setup/starter_projects/Vector Store RAG.json
#	src/backend/base/langflow/services/database/models/traces/model.py
#	src/backend/base/langflow/services/tracing/native.py
#	src/backend/base/pyproject.toml
#	src/backend/tests/unit/services/tracing/test_native_tracer.py
#	src/frontend/package-lock.json
#	src/frontend/package.json
#	src/frontend/src/components/core/playgroundComponent/chat-view/chat-header/components/chat-sidebar.tsx
#	src/frontend/src/components/core/playgroundComponent/chat-view/chat-header/components/session-selector.tsx
#	src/frontend/src/components/core/playgroundComponent/chat-view/chat-header/hooks/use-edit-session-info.ts
#	src/frontend/src/components/core/playgroundComponent/chat-view/chat-header/hooks/use-get-add-sessions.ts
#	src/frontend/src/components/core/playgroundComponent/sliding-container/components/flow-page-sliding-container.tsx
#	src/frontend/src/components/ui/__tests__/dialog.test.tsx
#	src/frontend/src/components/ui/sidebar.tsx
#	src/frontend/src/modals/addMcpServerModal/index.tsx
#	src/frontend/src/pages/FlowPage/components/flowSidebarComponent/components/__tests__/sidebarSegmentedNav.test.tsx
#	src/frontend/src/pages/FlowPage/components/flowSidebarComponent/components/sidebarSegmentedNav.tsx
#	src/frontend/src/pages/FlowPage/components/flowSidebarComponent/helpers/__tests__/disable-item.test.ts
#	src/frontend/src/pages/FlowPage/components/flowSidebarComponent/helpers/__tests__/get-disabled-tooltip.test.ts
#	src/frontend/src/pages/FlowPage/components/flowSidebarComponent/index.tsx
#	src/frontend/tests/core/integrations/Market Research.spec.ts
#	src/frontend/tests/core/regression/general-bugs-invalid-json-upload.spec.ts
#	src/frontend/tests/core/regression/session-deletion-data-leakage.spec.ts
#	src/lfx/pyproject.toml
#	src/lfx/src/lfx/_assets/component_index.json
#	src/lfx/src/lfx/_assets/stable_hash_history.json
#	src/lfx/src/lfx/base/models/unified_models.py
#	src/lfx/src/lfx/components/deactivated/ingestion.py
#	uv.lock
2026-04-06 15:16:43 -04:00
cabaa2ef19 feat: add LANGFLOW_MCP_BASE_URL config for MCP server URL override (#12523)
* feat: add mcp_base_url to config endpoint for MCP server URL override

Add LANGFLOW_MCP_BASE_URL setting that the frontend uses as a fallback
when building MCP server URLs in the UI configuration JSON. This allows
deployments behind reverse proxies to specify the correct external URL.

Priority chain: mcp_base_url > api.defaults.baseURL > window.location.origin

* test: add tests for mcp_base_url config and URL fallback priority
2026-04-06 18:56:41 +00:00
2f6400db89 fix: enforce IDOR protection on v2 workflow job endpoints (#12398)
* fix: enforce ownership check and pass user_id in workflow job creation

- Add _assert_job_owner helper that raises 403 for non-owners (legacy jobs with user_id=None are allowed through)
- Move ownership check before job type check in stop_workflow to avoid leaking job.type to non-owners
- Pass user_id to create_job in both sync and background execution paths
- Add user_id parameter to JobService.create_job signature

* test: add ownership and legacy job coverage for workflow endpoints

- Add TestWorkflowIDORProtection class with tests for 403 on cross-user access
- Add test for stop_workflow with legacy user_id=None job (should not return 403)

* fix: pass user_id to create_job in knowledge_bases ingestion endpoint

Prevents IDOR vulnerability where ingestion jobs created without user_id
would bypass ownership checks, matching the fix applied to workflow jobs.

* refactor: move job ownership check to JobService layer

Moves _assert_job_owner from workflow.py into JobService.assert_job_owner
so any future job-consuming endpoint can reuse the check without duplicating
logic. Both get_workflow_status and stop_workflow now delegate to the service.

* test: fix mocks for assert_job_owner after service layer refactor

MagicMock blocks attributes starting with 'assert' by default.
Added explicit mock_service.assert_job_owner = MagicMock() to each
test that mocks get_job_service so the ownership check is a no-op
for tests not focused on IDOR behavior.

* refactor: enforce job ownership at SQL level, remove assert_job_owner

Move IDOR ownership check from application layer into the DB query.
`get_job_by_job_id` now accepts an optional `user_id` and filters by
`job_id AND (user_id = ? OR user_id IS NULL)`, so unauthorized access
returns 404 instead of 403. Removes `JobService.assert_job_owner`.

- Strengthen legacy-job test assertions (!=403 → ==200)
- Add missing GET test for non-WORKFLOW job type → 404
2026-04-06 18:15:11 +00:00
acf2ae0605 fix: Accept inputs for the URL component (#12474)
* fix: Accept inputs for the URL component

* [autofix.ci] apply automated fixes

* Update src/lfx/tests/unit/components/data_source/test_url_component.py

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

* rebuild comp index

* Update component_index.json

* [autofix.ci] apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-04-06 16:28:43 +00:00
66c206740e fix: upgrade fastmcp to 3.2.0 to fix SSRF vulnerability (CVE) (#12516)
security: upgrade fastmcp to 3.2.0 to fix SSRF vulnerability (CVE)

Co-authored-by: Janardan S Kavia <janardanskavia@Janardans-MacBook-Pro.local>
2026-04-06 14:39:23 +00:00
8d01ba4240 feat: add var to block custom component execution (#11893)
* add var to block custom component execution

* [autofix.ci] apply automated fixes

* swaps generic check for a specific legacy name check for prompt

* [autofix.ci] apply automated fixes

* Add missing endpoint checks

* fix language

* Add flow validation and tests

* [autofix.ci] apply automated fixes

* Add a few more tests and validation to other endpoints

* clean up test and import logic

* [autofix.ci] apply automated fixes

* ensure flow is saved after upgrade

* Use hash instead of code

* Fix review issues: type safety, error handling, and test coverage

- Change ComponentCache hash fields to None default (was {}) to make
  "not yet loaded" explicit in the type system and eliminate the error-prone
  `or None` pattern at 8+ callsites
- Narrow frontend 403 suppression to only match custom component errors,
  preventing unrelated auth/permission 403s from being swallowed
- Add console.warn logging to waitForNodeUpdates timeout, saveFlow catch,
  and 403 suppression paths for debuggability
- Document security invariants (build_vertex cache-hit, nodes-without-code)
- Add server-side logging to MCP validation failures
- Add TestBuildCodeHashLookups test class (9 tests) for _build_code_hash_lookups

* remove divider when new cust comp button is removed

* syntax fix in ui

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes

* DRY

* [autofix.ci] apply automated fixes

* fix imports

* add field order to script updates

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* fix: harden custom component lockdown across api, lfx, and editor

- enforce custom-component validation before lfx and backend flow execution
- normalize legacy built-in aliases like Prompt and URL during validation and refresh
- surface blocked custom nodes in the editor without mutating persisted edited state
- prevent empty-flow save/build hangs when custom components are disabled
- add regression coverage for api, lfx, starter project refresh, and frontend guards

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* Add legacy type mapping back for prompt component

* Fix missing import and add real run tests

* fix(flow): Centralize custom component validation

Route payload and prebuilt graph checks through one shared validator so
backend and lfx execution surfaces enforce the same custom-component
policy.

Keep Graph.from_payload as the fresh-build guard, revalidate cached and
script-loaded graphs before execution, and extend coverage for MCP,
workflow reconstruction, agentic flows, and real lfx runs.

Co-Authored-By: OpenAI Codex <noreply@openai.com>

* remove useless function

* remove double validation cases

* remove outdated hash history refs

* fix(frontend): preserve custom component recovery paths

Clear dismissed state after successful bulk restores and make the toolbar Code entrypoint follow config transitions.

Add regressions for bulk restore cleanup, toolbar config changes, and single-node restore of dismissed outdated components.

* fix(frontend): Block uploaded custom components in editor

Surface uploaded CustomComponent nodes as blocked when custom
components are disabled so the editor warns before build
and refresh paths hit backend rejections.

Recompute component warnings when config loads and tighten
the disabled-mode guard so allowed custom components are
not treated as blocked.

* Add parser to legacy type analysis

* fix: update components on render consolidate config reads

Replace scattered useGetConfig reads with useUtilityStore
for a single source of truth.

- chat.py: use elif so request data validation skips stale DB flow;
  reorder build_public_tmp to check public access before validation
- flow_validation.py: surface loader failures instead of swallowing them
- use-get-types.ts: recompute componentsToUpdate after templates load
- Frontend: read allowCustomComponents from utilityStore in code area,
  sidebar, and node toolbar components

* Add tiny guard to not update on zero length nodes

* DRY ref for compute update function

* Remove redundant validations (for now)

* refactor: replace string-matching error classification with CustomComponentValidationError

Introduce CustomComponentValidationError(ValueError) so API handlers can
catch validation errors by type instead of matching error message strings.
This eliminates the fragile is_custom_component_validation_error_message
function and makes error routing explicit across all endpoints.

- Add CustomComponentValidationError in flow_validation.py
- check_flow_and_raise now raises CustomComponentValidationError
- Replace all is_custom_component_validation_error_message call sites
  with except CustomComponentValidationError in chat.py, endpoints.py,
  openai_responses.py, mcp_utils.py, and flow_executor.py
- Add except RuntimeError -> 503 in build_flow for startup race
- Remove redundant validation in session/service.py load_session
- Update all test assertions to use the new exception type

* Add beta flag to env var

* Use raw graph data to extract and better exc handling

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* [autofix.ci] apply automated fixes (attempt 3/3)

* obfuscate exceptoin details

* log error message

* ruff

* fix be test

* [autofix.ci] apply automated fixes

* fix tests

* [autofix.ci] apply automated fixes

* tests

* [autofix.ci] apply automated fixes

* enhance hash checks to allow cust components to run

* Add comment

* Add comment

* [autofix.ci] apply automated fixes

* ruff

* Update more tests

* [autofix.ci] apply automated fixes

* be tests

* be tests

* [autofix.ci] apply automated fixes

* revert changes to fe tests that were causing failures'

* comp index?

* comp index?

* comp index?

* changes FE tests to expect 5 necessary updates after prompt comp was added to checks

* update one more fe test with new error message

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: OpenAI Codex <noreply@openai.com>
2026-04-05 14:54:32 +00:00
d6c2ec3ab7 feat: Remove deprecated Astra Assistants to support latest docling package versions (#12442)
* feat: Latest docling package versions

* [autofix.ci] apply automated fixes

* Template updates

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* Update uv.lock

* Update uv.lock

* Template update

* Revert the changes to starter projects

* Revert the changes to starter projects

* Update component_index.json

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* Update test_dynamic_import_integration.py

* Update component_index.json

* Restore versioned docs

* Lessen the scope of the version updates

* Update component_index.json

* [autofix.ci] apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-04 17:53:59 +00:00
7e74d33ae7 docs: enhance Agentics documentation with embedded video (#12272)
docs: enhance Agentics documentation with embedded video and full paper citations

- Add embedded YouTube tutorial video at the top of the page
- Add introductory text for the video
- Group research papers under Publications section
- Add full academic citations for both Agentics papers
- Remove redundant schema table from introduction
- Improve overall readability and structure

Co-authored-by: Alfio Gliozzo <gliozzo@us.ibm.com>
Co-authored-by: Mendon Kissling <59585235+mendonk@users.noreply.github.com>
2026-04-03 18:54:25 +00:00
c1bffa8f4f docs: Flow DevOps Toolkit SDK (#12472)
* flow-devops-sdk-basic-usage

* peer-review

* shorthand-for-sidebars
2026-04-03 18:42:42 +00:00
e555e470d9 fix: Cherry-pick nightly SDK build fixes to main (#12491)
* fix: Build and install the langflow-sdk for lfx (fixes nightly) (#12481)

* fix: Build and install the langflow-sdk for lfx

* Publish sdk as a nightly

* Update ci.yml

* Update python_test.yml

* Update ci.yml

* fix: Properly grep for the langflow version (#12486)

* fix: Properly grep for the langflow version

* Mount the sdk where needed

* Skip the sdk

* [autofix.ci] apply automated fixes

* Update setup.py

* fix(docker): Remove broken npm self-upgrade from Docker images (#12309)

* fix: replace grep -oP with sed for Node.js version extraction in Docker builds (#12331)

The grep -oP (PCRE regex) command fails in the python:3.12.12-slim-trixie
Docker base image because PCRE support is not available in the slim variant.

This replaces grep -oP with portable sed -nE in all 5 Dockerfiles and adds
an empty version guard to fail fast with a clear error message instead of
producing a broken download URL.

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Cristhian Zanforlin Lousa <cristhian.lousa@gmail.com>
Co-authored-by: vjgit96 <vijay.katuri@ibm.com>
2026-04-03 14:25:33 -04:00
ed3820bced docs: increase padding for sidebars icons (#12480)
increase-padding-for-sidebar-icons
2026-04-03 17:39:22 +00:00
3ee4bd57eb docs: test harness for api reference code samples (#12338)
* curl-examples-and-tests

* move-curl-examples

* docs-add-existing-js-and-python-examples

* add-python-and-js-examples

* use-code-snippet-not-code-block

* remove-unused-ts-files

* add-gitignore-for-docs-pycache

* test-api-commands-with-langflow-env-var

* add-fixtures-and-makefile-tests-pass

* no-action

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes

* block-ruff-check-for-docs-examples

* add-horizontal-scrolling-and-pin-copy-button

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-03 16:45:15 +00:00
32c72b02e4 fix(mcp): stop sending API key as Bearer token in MCP client (#12441)
* fix(mcp): Stop sending API key as Bearer token in MCP client  (#12349)

* fix: replace unnecessary dict comprehension with dict() call

* Update test_mcp_client.py

---------

Co-authored-by: Cristhian Zanforlin Lousa <cristhian.lousa@gmail.com>
Co-authored-by: Eric Hare <ericrhare@gmail.com>
2026-04-03 16:30:18 +00:00
6eaa938535 fix: add SSRF protection to URL component (PVR0699081) (#11996)
* fix: add SSRF protection to URL component (PVR0699081)

Add Server-Side Request Forgery (SSRF) protection to the URL component
by integrating the existing validate_url_for_ssrf function. This prevents
the component from being used to access internal resources like localhost,
private IP ranges, and cloud metadata endpoints.

The fix uses warn_only=True for backwards compatibility, matching the
behavior of the API Request component. Full blocking will be enabled
in the next major version (2.0).

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* fix: enforce SSRF blocking and add env variables to .env.example

- Change warn_only=False to actually block internal URLs when SSRF protection is enabled
- Add LANGFLOW_SSRF_PROTECTION_ENABLED and LANGFLOW_SSRF_ALLOWED_HOSTS to .env.example
- Update tests to reflect blocking mode

When LANGFLOW_SSRF_PROTECTION_ENABLED=true, requests to private IPs,
localhost, and cloud metadata endpoints will be blocked.

* fix: correct .env.example to show empty default for SSRF protection

The default is false, so .env.example should be empty (not true).

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* fix: add SSRF protection to URL component (PVR0699081)

Add Server-Side Request Forgery (SSRF) protection to the URL component
by integrating the existing validate_url_for_ssrf function. This prevents
the component from being used to access internal resources like localhost,
private IP ranges, and cloud metadata endpoints.

The fix uses warn_only=True for backwards compatibility, matching the
behavior of the API Request component. Full blocking will be enabled
in the next major version (2.0).

* fix: enforce SSRF blocking and add env variables to .env.example

- Change warn_only=False to actually block internal URLs when SSRF protection is enabled
- Add LANGFLOW_SSRF_PROTECTION_ENABLED and LANGFLOW_SSRF_ALLOWED_HOSTS to .env.example
- Update tests to reflect blocking mode

When LANGFLOW_SSRF_PROTECTION_ENABLED=true, requests to private IPs,
localhost, and cloud metadata endpoints will be blocked.

* fix: correct .env.example to show empty default for SSRF protection

The default is false, so .env.example should be empty (not true).

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-03 15:51:05 +00:00
68642a8a86 fix: Properly grep for the langflow version (#12486)
* fix: Properly grep for the langflow version

* Mount the sdk where needed

* Skip the sdk
2026-04-03 15:02:11 +00:00
63e6a1d269 fix: upgrade dependencies to address CVE vulnerabilities (#12470)
security: upgrade dependencies to address CVE vulnerabilities

Co-authored-by: Janardan S Kavia <janardanskavia@Janardans-MacBook-Pro.local>
2026-04-03 11:44:12 +00:00
abd772f780 fix: Build and install the langflow-sdk for lfx (fixes nightly) (#12481)
* fix: Build and install the langflow-sdk for lfx

* Publish sdk as a nightly

* Update ci.yml

* Update python_test.yml

* Update ci.yml
2026-04-03 05:59:09 +00:00
cea8b1aa12 feat: flow event polling for real-time MCP agent activity (#12340)
* feat: add Langflow MCP Client settings page

Add a new settings page that shows coding agents how to connect to
Langflow via the lfx.mcp client. Includes setup instructions and
JSON config for Bob (IBM) and Claude Code.

* fix: clipboard guard and per-button copied state in MCP client page

- Guard navigator.clipboard availability before calling writeText
- Track copied state per button (command vs json) so visual feedback
  matches the action the user took

* feat: add flow events queue for MCP agent activity polling

In-memory event queue service with cursor-based polling endpoint
at GET/POST /api/v1/flows/{flow_id}/events. Enables the frontend
to detect when MCP agents modify flows in near real-time.

* feat: emit flow events from MCP tools and add notify_done tool

Each mutating MCP tool now posts an event to the flow events queue
after successful PATCH. Adds notify_done tool for explicit settle
signaling to the frontend.

* feat: add frontend flow event polling with canvas locking and toast

- useFlowEvents hook with adaptive polling (5s idle, 1s active)
- Canvas locks with "Agent is working..." badge during agent activity
- Flow reloads and summary toast on settle

* test: add tests for flow events hook and MCP event emission

- 9 frontend tests for useFlowEvents hook (polling, accumulation, settle, errors)
- 4 lfx tests for LangflowClient.post_event (payload, defaults, error suppression)
- 7 lfx tests for MCP tool event emission (add/remove/configure/connect/disconnect/notify_done)

* fix: add flow ownership check and fix thread-safety in event queue

Endpoints now verify the authenticated user owns the flow before
allowing event reads or writes. Also copies the event list inside
the lock to prevent concurrent mutation during iteration.

* fix: log warnings on event posting and polling failures

Replace silent error suppression with logger.warning (backend) and
console.warn (frontend) so failures are diagnosable while keeping
best-effort semantics.

* fix: show toast only on successful flow reload after agent settle

Move toast into reloadFlow's onSuccess callback so users aren't told
about changes that failed to load. Also fixes stale closure by adding
missing useEffect dependencies.

* test: improve coverage for flow events

- Add cursor-ahead-of-events tests for get_since settle logic
- Add flow ownership 404 test for events endpoints
- Add event emission tests for freeze/unfreeze/layout/update_flow_from_spec
- Use real flow IDs (from created flows) in API tests

* test: add edge case coverage for flow events

- flow_settled before cursor should not trigger settlement
- create_flow_from_spec emits flow_settled after batch
- Polling resumes at idle interval after settle
- Simultaneous events + settled in single poll

* fix: UX improvements for agent activity polling

- Clear events after settle to prevent stale toast messages
- Truncate toast to 3 summaries max ("and N more")
- Block keyboard shortcuts (undo/redo/copy/paste/cut) during agent lock
- Poll immediately on mount (no 5s blind spot)
- Add concurrency guard to prevent overlapping polls
- Guard against setState on unmounted component

* test: add Playwright E2E test for agent events banner

Verifies that posting events via the API triggers the "Agent is
working..." banner on the canvas, and that a flow_settled event
dismisses it.

* refactor: consolidate lfx event tests into parameterized tests

- Server tests: 10 identical copy-paste classes -> 1 parameterized test
  covering 9 tools, assertions check event type not exact summary
- Client tests: merge redundant exception tests, test multiple error
  types in one test
- Keep distinct tests for create_flow_from_spec and notify_done since
  they have unique behavior (batch settle vs explicit settle)

* fix: UX improvements for agent events banner

- Show latest event summary in banner (e.g. "Agent: Added Memory")
- Slide-in entrance and slide-out exit animations
- Minimum 2s display time so banner doesn't flash
- Freeze banner text during exit animation
- Text eases in when new events arrive

* fix: canvas reload, locking, and toast formatting

- Use applyFlowToCanvas for proper canvas reload on settle
- Zoom to fit after reload instead of zooming to 200%
- Lock icon shows "Agent Working" during agent activity
- ReactFlow nodesDraggable/nodesConnectable respect agent lock
- Toast shows grouped summary (e.g. "Agent removed 3 components")
- Events preserved for consumer, cleared via clearEvents callback

* fix: handle AUTO_LOGIN nullable user_id, remove double processFlows, fix pluralization

- _verify_flow_owner now accepts flows with user_id=None (AUTO_LOGIN)
- Remove redundant processFlows call (applyFlowToCanvas handles it)
- Toast says "connections" not "components" for connection events

* refactor: minor cleanup from code review

- Remove unused FlowEventType export (only used internally)
- Simplify nested ternary in toast pluralization

* chore: remove test artifact

* fix: harden flow events service and address review findings

- Rewrite FlowEventsService to use diskcache for cross-worker
  event visibility (replaces in-memory dict)
- Add Literal constraint and max_length to FlowEventCreate API model
- Restore manual lock toggle (disabled during agent activity),
  serialize saves to prevent race conditions
- Add AbortController to post-settle flow reload to prevent
  stale responses from overwriting wrong canvas
- Clear agent-working state on terminal poll errors (401/403/404)
  so UI doesn't get permanently stuck
- Make notify_done report warning status on delivery failure
- Emit settle event on create_flow_from_spec rollback
- Fix E2E test banner text assertion to match actual render
- Add 14 new tests: cross-worker visibility, validation 422s,
  terminal error unlock, notify_done warning, rollback settle

* fix: resolve CI failures in MemoizedCanvasControls and notify_done tests

- Add waitFor() to lock toggle tests for async handleToggleLock
- Patch logger in notify_done failure test to avoid I/O on closed file
- Replace any[] with unknown[] in test mock type

* fix: address remaining review feedback from erichare

- Fix stale closure in banner effect using bannerVisibleRef
- Add runtime event type validation in FlowEventsService.append()
- Document diskcache ephemeral storage and multi-tab limitations
2026-04-02 23:46:22 +00:00
4e8c5e7e0e feat: add Langflow MCP Client settings page (#12321)
* feat: add Langflow MCP Client settings page

Add a new settings page that shows coding agents how to connect to
Langflow via the lfx.mcp client. Includes setup instructions and
JSON config for Bob (IBM) and Claude Code.

* fix: clipboard guard and per-button copied state in MCP client page

- Guard navigator.clipboard availability before calling writeText
- Track copied state per button (command vs json) so visual feedback
  matches the action the user took
2026-04-02 22:57:12 +00:00
103ef7dcfa fix: Close popup when navigating to MCP settings (#12358) 2026-04-02 21:08:43 +00:00
e6846ea6e7 feat(ui): Add "Connect other models" option for model-type handles (#12466)
* Display proper error messages and strip null params from tool calls

* add connect other models option

* fix model provider selection state

* fix tests and ruff

* revert mcp changes

* [autofix.ci] apply automated fixes

* fix handle not appearing properly

* fix jest test

* [autofix.ci] apply automated fixes

* address qa fixes

* add tests to validate be and fe

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes (attempt 2/3)

* ruff style and checker

* fix tests failuer

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-02 19:59:54 +00:00
4bdc87dcc1 fix: Import and Statistics fixes for Knowledge Bases (#12446)
* fix: Access the appropriate attribute for chroma

* Fix display of chunk metadata

* [autofix.ci] apply automated fixes

* Add some unit tests

* Update ingestion.py

* [autofix.ci] apply automated fixes

* Review updates

* Update component_index.json

* Fix bug with ingestion

* [autofix.ci] apply automated fixes

* Update test_ingestion.py

* Update test_ingestion.py

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Carlos Coelho <80289056+carlosrcoelho@users.noreply.github.com>
2026-04-02 19:34:06 +00:00
b0a8662d24 docs: add CI optimization analysis for pre-release builds (#12207)
- Analyze 45-60 min CI bottleneck for pre-release builds
- Document that both PyPI publishing and Docker builds wait for CI
- Recommend skip_ci parameter with safeguards for urgent releases
- Show 50% time savings (100 min → 50 min) for pre-releases
- Include risk assessment and implementation guidelines

Addresses LE-517
2026-04-02 17:33:27 +00:00
45325f6376 feat: Langflow SDK and Flow DevOps API Toolkit (#12245)
* feat(sdk): add langflow-sdk Python client package

* feat(lfx): add Flow DevOps CLI toolkit

* feat(api): add flow upsert, export normalization, ZIP upload

* chore: CI coverage merge, Docker fixes, dependency updates

* Address CQ5 review / import bug

* Update test_status_command.py

* Update test_status_command.py

* Fix more tests

* Review edits

* Review edits

* Fix tests

* Follow up review updates

* Refactor common client code

* Update templates and comp index

* [autofix.ci] apply automated fixes

* Update test_database.py

* Updates from review comments

* Fix push interface to match the rest

* Update push.py

* Update push.py

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-02 16:13:13 +00:00
61bc076ab3 fix: restore langflow-logo-color-black-solid.svg removed in docs release (#12447)
Co-authored-by: Mendon Kissling <59585235+mendonk@users.noreply.github.com>
2026-04-02 15:19:20 +00:00
a2d3c18569 feat: MCP server UX improvements, batch, and spec-based flow creation (#12205)
* feat: add pure flow-builder utilities to lfx

Add flow_builder subpackage with pure functions for manipulating
flow JSON dicts — component ops, edge creation with ReactFlow
handle format, topological layout, and dynamic field detection.

* feat: add MCP server for operating Langflow via REST API

FastMCP server exposing 15 tools across auth, flow, component,
connection, and execution groups. Agents can create flows, add
and configure components, wire connections, and run flows against
a Langflow server through MCP tool calls.

* feat: add langflow-mcp-client console script entry point

* fix: use dict comprehension in setup.py to fix PERF403 lint

* fix: address PR review feedback on MCP client

- Add asyncio.Lock to prevent race condition in _client() under
  concurrent access
- Handle 204 No Content responses in delete() instead of calling
  resp.json() on empty body
- Fix weak assertion in test_default_values

* feat: auto-enable tool_mode when connecting component_as_tool

describe_component_type now shows component_as_tool as an output
for any component with tool_mode-capable outputs. When an agent
connects via component_as_tool, tool_mode is auto-enabled — no
extra step needed.

* refactor: move MCP server from langflow-base to lfx

The MCP server has no langflow dependencies — only httpx, mcp,
and lfx.graph.flow_builder. Moving it to lfx.mcp makes it usable
without installing langflow. Entry point: lfx-mcp.

* feat: improve MCP server UX for agents

- describe_component_type separates advanced fields from core ones
- search_component_types accepts output_type filter
- list_flows accepts query filter and includes ASCII graph repr
- get_flow_info includes ASCII graph repr
- add duplicate_flow tool
- add list_starter_projects tool

* feat: add use_starter_project tool and tests for new features

- use_starter_project creates a flow from a starter template by name
  (starter projects aren't fetchable by ID via /flows/)
- Tests for duplicate_flow, starter projects, graph repr, advanced
  fields, and output_type search

* docs: improve MCP tool descriptions for agent clarity

- Add server-level instructions with typical workflow guide
- Remove internal implementation details from tool descriptions
- Add cross-references between related tools
- Mention component_as_tool and graph diagrams where relevant

* docs: address subagent review feedback on tool descriptions

- Document return values for create_flow, add_component
- Clarify empty-query behavior for search_component_types
- Distinguish get_component_info (instance) vs describe_component_type (type)
- Explain connection type compatibility in instructions
- Clarify configure_component trigger field behavior
- State disconnect_components default when filters omitted

* feat: add batch tool for multi-action requests

Execute multiple actions in one call with $N.field references
to chain results. An agent can build a complete flow in a single
request instead of 6+ round trips.

* feat: add create_flow_from_spec tool for compact text-based flow creation

Accepts a compact text spec with nodes, edges (using real port names),
and config sections. Agents generate a simple string instead of
constructing nested JSON. Tool mode auto-enabled for component_as_tool.

Handles Prompt Template dynamic variables by parsing {var} from
template text and creating input fields. Cleans up flows on failure.
Type coercion for numeric/boolean config values.

* feat: add build_flow validation and create_flow_from_spec

build_flow validates flows by building the graph server-side.
create_flow_from_spec accepts a compact text spec with nodes,
edges, and config. Validates by default (optional).

Handles Prompt Template dynamic {variables}, auto-enables tool_mode
for component_as_tool, cleans up on failure, coerces config types.

* fix: isolate session state and harden MCP server

* fix: move test_flow_builder into tests/unit so CI collects coverage

* fix: address PR review feedback

- Fix test fixture to use contextvars instead of stale module attributes
- Raise ValueError on malformed spec lines instead of silently dropping
- Disambiguate duplicate component types in flow_graph_repr
- Narrow except Exception to ImportError in flow_graph_repr
- Add action-index context to batch error messages
- Fix stale/inaccurate docstrings (group count, "| ", field_name, category, build_flow)
- Mention create_flow_from_spec in MCP instructions

* feat: stream run_flow events via MCP progress notifications

run_flow now consumes Langflow's SSE stream and relays token events
to the MCP client via report_progress. Falls back to a regular POST
if the stream yields no result.

* test: add streaming integration tests for run_flow and stream_post

* chore: rebuild component index

* [autofix.ci] apply automated fixes

* fix: handle Message dicts in str field param processing, add MCP logger

param_handler's str case called unescape_string on list elements without
type checking. On subsequent agent calls, chat history stores Message dicts
in the list, causing 'dict' object has no attribute 'replace'.

Added _coerce_str_value that extracts .text from Message/Data/dict objects.
Added lfx logger to MCP server with streaming fallback warning.

* feat: add flow builder tools, propose_field_edit, and flow_to_spec_summary

- builder.py: builds flow dicts from text specs using local component
  registry with granular error handling per build phase
- flow_builder_tools.py: 9 Langflow components for agent tooling
  (search, describe, get_field_value, propose_field_edit, add_component,
  remove_component, connect_components, configure_component, build_flow)
- propose_field_edit generates validated JSON Patches with dry-run
- flow_to_spec_summary converts flow dicts to compact summaries with IDs
- Module-level event queue for real-time UI updates during streaming

* [autofix.ci] apply automated fixes

* feat: add get_build_results and get_component_output MCP tools

Exposes per-component build data from the vertex_builds table:
- get_build_results: returns all component outputs, validity, and errors
  from the last run -- useful for debugging which component failed
- get_component_output: inspect a specific component's output from the
  last run to trace where the pipeline broke

* feat: add flow management, iteration, and discovery MCP tools

Response improvements:
- spec_summary (component IDs + connection ports) in get_flow_info/list_flows
- Merged components() tool: search or describe in one call

Flow management tools:
- validate_flow: polls build results with timeout, structured per-component errors
- rename_flow: update name/description
- export_flow: serialize to JSON with sensitive field redaction
- update_flow_from_spec: declarative update with reference validation

Component iteration tools:
- freeze_component / unfreeze_component: skip re-execution during iteration
- layout_flow_tool: re-layout after modifications

Security: export_flow redacts API keys via redact_node before exposing to LLM.
Includes 18 integration tests covering all new tools.

* refactor: extract shared _node_id and validate_spec_references

- _utils.py: shared node_id helper (was duplicated in component.py and layout.py)
- spec.py: validate_spec_references extracted from three copies in
  create_flow_from_spec, update_flow_from_spec, and build_flow_from_spec

* fix: add trailing slash to /api_key endpoint in MCP client login

The FastAPI endpoint redirects /api_key to /api_key/ (307) and httpx
drops the POST body on redirect, causing API key creation to fail
silently during login.

* fix: isolate session state and harden MCP server

contextvars alone lose state between stdio tool calls. Add module-level
fallback so login credentials persist across calls while still
supporting per-session isolation for SSE transport.

* feat: improve MCP server UX for agents

- describe_component_type separates advanced fields from core ones
- search_component_types accepts output_type filter
- list_flows accepts query filter and includes ASCII graph repr
- get_flow_info includes ASCII graph repr
- add duplicate_flow tool
- add list_starter_projects tool

* feat: add use_starter_project tool and tests for new features

- use_starter_project creates a flow from a starter template by name
  (starter projects aren't fetchable by ID via /flows/)
- Tests for duplicate_flow, starter projects, graph repr, advanced
  fields, and output_type search

* docs: improve MCP tool descriptions for agent clarity

- Add server-level instructions with typical workflow guide
- Remove internal implementation details from tool descriptions
- Add cross-references between related tools
- Mention component_as_tool and graph diagrams where relevant

* docs: address subagent review feedback on tool descriptions

- Document return values for create_flow, add_component
- Clarify empty-query behavior for search_component_types
- Distinguish get_component_info (instance) vs describe_component_type (type)
- Explain connection type compatibility in instructions
- Clarify configure_component trigger field behavior
- State disconnect_components default when filters omitted

* feat: add batch tool for multi-action requests

Execute multiple actions in one call with $N.field references
to chain results. An agent can build a complete flow in a single
request instead of 6+ round trips.

* feat: add create_flow_from_spec tool for compact text-based flow creation

Accepts a compact text spec with nodes, edges (using real port names),
and config sections. Agents generate a simple string instead of
constructing nested JSON. Tool mode auto-enabled for component_as_tool.

Handles Prompt Template dynamic variables by parsing {var} from
template text and creating input fields. Cleans up flows on failure.
Type coercion for numeric/boolean config values.

* feat: add build_flow validation and create_flow_from_spec

build_flow validates flows by building the graph server-side.
create_flow_from_spec accepts a compact text spec with nodes,
edges, and config. Validates by default (optional).

Handles Prompt Template dynamic {variables}, auto-enables tool_mode
for component_as_tool, cleans up on failure, coerces config types.

* fix: address PR review feedback

- Fix test fixture to use contextvars instead of stale module attributes
- Raise ValueError on malformed spec lines instead of silently dropping
- Disambiguate duplicate component types in flow_graph_repr
- Narrow except Exception to ImportError in flow_graph_repr
- Add action-index context to batch error messages
- Fix stale/inaccurate docstrings (group count, "| ", field_name, category, build_flow)
- Mention create_flow_from_spec in MCP instructions

* feat: stream run_flow events via MCP progress notifications

run_flow now consumes Langflow's SSE stream and relays token events
to the MCP client via report_progress. Falls back to a regular POST
if the stream yields no result.

* test: add streaming integration tests for run_flow and stream_post

* chore: rebuild component index

* [autofix.ci] apply automated fixes

* fix: handle Message dicts in str field param processing, add MCP logger

param_handler's str case called unescape_string on list elements without
type checking. On subsequent agent calls, chat history stores Message dicts
in the list, causing 'dict' object has no attribute 'replace'.

Added _coerce_str_value that extracts .text from Message/Data/dict objects.
Added lfx logger to MCP server with streaming fallback warning.

* feat: add flow builder tools, propose_field_edit, and flow_to_spec_summary

- builder.py: builds flow dicts from text specs using local component
  registry with granular error handling per build phase
- flow_builder_tools.py: 9 Langflow components for agent tooling
  (search, describe, get_field_value, propose_field_edit, add_component,
  remove_component, connect_components, configure_component, build_flow)
- propose_field_edit generates validated JSON Patches with dry-run
- flow_to_spec_summary converts flow dicts to compact summaries with IDs
- Module-level event queue for real-time UI updates during streaming

* [autofix.ci] apply automated fixes

* feat: add get_build_results and get_component_output MCP tools

Exposes per-component build data from the vertex_builds table:
- get_build_results: returns all component outputs, validity, and errors
  from the last run -- useful for debugging which component failed
- get_component_output: inspect a specific component's output from the
  last run to trace where the pipeline broke

* feat: add flow management, iteration, and discovery MCP tools

Response improvements:
- spec_summary (component IDs + connection ports) in get_flow_info/list_flows
- Merged components() tool: search or describe in one call

Flow management tools:
- validate_flow: polls build results with timeout, structured per-component errors
- rename_flow: update name/description
- export_flow: serialize to JSON with sensitive field redaction
- update_flow_from_spec: declarative update with reference validation

Component iteration tools:
- freeze_component / unfreeze_component: skip re-execution during iteration
- layout_flow_tool: re-layout after modifications

Security: export_flow redacts API keys via redact_node before exposing to LLM.
Includes 18 integration tests covering all new tools.

* refactor: extract shared _node_id and validate_spec_references

- _utils.py: shared node_id helper (was duplicated in component.py and layout.py)
- spec.py: validate_spec_references extracted from three copies in
  create_flow_from_spec, update_flow_from_spec, and build_flow_from_spec

* fix: update test fixture to use contextvars-based server API

The mcp_client fixture was accessing mcp_server_module._client and
._registry directly, but these were replaced with contextvars
(_client_var, _shared_client, _set_client, etc.) in the server
module refactor.

* [autofix.ci] apply automated fixes

* fix: address review feedback on MCP server PR

- Move flow_builder_tools out of components/ into mcp/ (fixes test_get_all)
- Extract _set_frozen() helper to deduplicate freeze/unfreeze
- Add missing tools to batch _TOOL_MAP
- Fix sensitive field detection to use word-boundary matching
- Unify redaction logic via shared is_sensitive_field()
- Log skipped non-JSON SSE lines in stream_post
- Rebuild component index

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes

* fix: gracefully handle server refresh failure in configure_component

When a real_time_refresh field (e.g. model_name) is configured before
its dependency (e.g. api_key), the server-side refresh fails. Instead
of propagating a raw RuntimeError, the value is saved locally and a
warning is returned telling the agent to set the credential first.

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: Keval718 <kevalvirat@gmail.com>
Co-authored-by: Eric Hare <ericrhare@gmail.com>
2026-04-02 14:18:13 +00:00
c08a465e16 docs: block custom components with env var (#12413)
* initial-changes

* fix-broken-links

* Apply suggestions from code review

Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>
Co-authored-by: Mendon Kissling <59585235+mendonk@users.noreply.github.com>

---------

Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>
2026-04-02 14:00:48 +00:00