feat: asked-field envelope, standalone form components, branched forms

This commit is contained in:
Jonas Miederer 2026-09-28 14:07:09 +02:00
parent 0d43b0e8fb
commit f27be044b4
26 changed files with 3651 additions and 104 deletions

View file

@ -17,6 +17,12 @@ removed in the Langflow code editor without touching this method.
``name`` is the stable JSON key (freely renamable, must stay unique and
non-empty); downstream components read the keys as-is.
When the run envelope names the asked fields (``fields`` list, sent by
the API from the version's form schema), defaults are emitted only for
asked fields — the template may declare fields unknown to this code and
unasked code defaults stay out of the output. Without the list (raw dict,
Langflow playground), all declared defaults apply.
``collect()`` returns ``Data`` (the LFX JSON type), not ``Message``: the
values travel as a real JSON object. A terminal ``ChatOutput`` renders it
as a fenced ```json block; components consuming it should read ``.data``
@ -29,6 +35,7 @@ upload comes later.
from __future__ import annotations
import json
import re
from typing import ClassVar
from lfx.custom import Component
@ -75,8 +82,71 @@ def _json_safe(value):
return str(value)
#: Inputs that are plumbing, not form fields (never part of the output).
PLUMBING_INPUTS = frozenset({"form_values", "code"})
def _split_conditions(text: str) -> list:
parts: list = []
buf: list = []
quoted = False
for char in text:
if char == '"':
quoted = not quoted
buf.append(char)
elif char == "&" and not quoted:
parts.append("".join(buf))
buf = []
else:
buf.append(char)
parts.append("".join(buf))
return [part.strip() for part in parts if part.strip()]
def _parse_condition(token: str):
field, sep, value = token.partition("=")
field, value = field.strip(), value.strip()
if not sep or not field or not value:
return None
if len(value) >= 2 and value.startswith('"') and value.endswith('"'):
value = value[1:-1]
lowered = value.lower()
if lowered == "true":
return field, True
if lowered == "false":
return field, False
try:
return field, int(value)
except ValueError:
pass
try:
return field, float(value)
except ValueError:
pass
return field, value
def _field_conditions(info: object) -> list:
"""``[(trigger, value)]`` from a field's ``info`` markers."""
conditions: list = []
def _collect(match) -> str:
for token in _split_conditions(match.group(1)):
parsed = _parse_condition(token)
if parsed is not None:
conditions.append(parsed)
return ""
_VISIBLE_RE.sub(_collect, info if isinstance(info, str) else "")
return conditions
#: Reserved input carrying the run envelope — a real runtime input, so it
#: must stay out of the output (otherwise the whole envelope JSON would
#: leak in as a field value on every path without an asked-fields list).
#: Never name a form field ``form_values``.
PLUMBING_INPUTS = frozenset({"form_values"})
#: ``[visible_if ...]`` marker (same syntax as the backend parser in
#: ``app/flows/input_schema.py`` — keep the two in sync; this module must
#: stay import-light for the LFX runtime and cannot import it).
_VISIBLE_RE = re.compile(r"\[visible_if\s+([^\]]+)\]")
class CustomInputForm(Component):
@ -193,22 +263,63 @@ class CustomInputForm(Component):
except (AttributeError, ValueError):
return None
def _is_visible(self, name: str, effective: dict) -> bool:
"""Whether a field's branch conditions hold.
Single pass over effective values (submitted first, code defaults
after): no recursion, so trigger cycles cannot hang — a stale or
cyclic marker simply matches or not. Unknown triggers never match.
"""
inputs = getattr(self, "_inputs", None)
info = ""
if isinstance(inputs, dict) and name in inputs:
info = getattr(inputs[name], "info", "") or ""
for trigger, expected in _field_conditions(info):
if trigger == name or trigger not in effective:
# Self-reference or unknown trigger: fail open (visible),
# mirroring the backend parser.
continue
actual = effective[trigger]
if isinstance(actual, list):
if expected not in actual:
return False
elif actual != expected:
return False
return True
def collect(self) -> Data:
data = {}
for name in self._field_names():
data[name] = _json_safe(self._field_value(name))
# Submitted values (via form_values) win over the field defaults.
# Accepts the raw dict or the run envelope {"payload": {...}}.
# Unknown keys are kept: the frontend may already know renamed
# fields this code revision does not declare.
try:
override = json.loads(_text(self.form_values) or "{}")
envelope = json.loads(_text(self.form_values) or "{}")
except (json.JSONDecodeError, ValueError, AttributeError):
override = {}
if isinstance(override, dict):
if isinstance(override.get("payload"), dict):
override = override["payload"]
for key, val in override.items():
if isinstance(key, str) and key:
data[key] = _json_safe(val)
envelope = {}
payload: dict = {}
asked: list | None = None
if isinstance(envelope, dict):
# Asked-field list counts only in true envelope shape
# ({"payload": {...}, "fields": [...]}); a raw dict or a form
# field literally named "fields" must not confuse it.
if isinstance(envelope.get("payload"), dict):
payload = envelope["payload"]
fields = envelope.get("fields")
if isinstance(fields, list) and all(isinstance(item, str) for item in fields):
asked = [item for item in fields if item]
else:
payload = envelope
# Effective trigger values: submitted first, code defaults after.
declared = self._field_names()
effective = {name: _json_safe(self._field_value(name)) for name in declared}
for key, val in payload.items():
if isinstance(key, str) and key:
effective[key] = _json_safe(val)
# Defaults only for asked AND visible fields (hidden branch fields
# stay out, like the frontend never submits them); without an asked
# list, all visible declared fields (Langflow playground).
scope = [name for name in (asked if asked is not None else declared) if name in declared]
data = {name: effective[name] for name in scope if self._is_visible(name, effective)}
# Submitted values win over the field defaults. Unknown keys are
# kept: the frontend may already know renamed fields this code
# revision does not declare.
for key, val in payload.items():
if isinstance(key, str) and key:
data[key] = _json_safe(val)
return Data(data=data)