Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

fix(flows): dropdown values are no longer erased when switching off dynamic mode (#14936)

Bartosz Majewski2bbf3ce4f995
diff --git a/brain/knowledge/engineering/web-feature-anatomy.md b/brain/knowledge/engineering/web-feature-anatomy.md
index 423dd6fed46..e3e4161a193 100644
--- a/brain/knowledge/engineering/web-feature-anatomy.md
+++ b/brain/knowledge/engineering/web-feature-anatomy.md
@@ -118,6 +118,7 @@ Verify with `npx turbo run lint --filter=web`, or `npm run lint-dev` for the who
- **`useFormField()` outside a `FormItem` silently yields `id: "undefined-form-item"` instead of throwing.** Its `if (!fieldContext) throw` guard in [components/ui/form.tsx](packages/web/src/components/ui/form.tsx) is dead code — both `FormFieldContext` and `FormItemContext` default to `{} as …`, which is truthy — so a component that reads `formItemId` outside a `FormItem` gets a *shared constant string*, and two of them on one page are duplicate DOM ids with no error anywhere. Any wrapper that reads `formItemId` to label a control has to be rendered inside the same `<FormItem>` as its `<FormLabel>`; check the call sites, the hook will not tell you. This is why the builder's mention editor is *two* components — `TextInputWithMentions` (plain) and `FormFieldMentionInput` (reads `formItemId`) — and not one: `formItemId` is one id per `FormItem`, but several sites render **many** editors under a single one (`DictionaryInput`'s `renderValueInput` fires once per row inside the one `FormItem` for `settings.input` in `step-settings/code-settings`, likewise `OBJECT` properties in `properties-utils`; `customInputNode` once per item in `array-property`; `property-group-tabs` adds `MentionChipsInput`, itself two more). Folding the hook into the shared component would give all of them the same `id`, so `label[for]` would resolve to the *wrong* editor instead of to nothing — worse than the bug. A flag prop does not rescue it either: hooks cannot be conditional, so the shared component would call `useFormField()` for every caller, including `mention-chips-input`, which imports nothing from react-hook-form and survives only because its one caller happens to sit in a form. The *other* direction fails harder and is not guarded: outside a react-hook-form `FormProvider` entirely, `useFormField()` does `const { getFieldState } = useFormContext()` on a `null` return and throws a TypeError, so a wrapper reused outside a form white-screens its subtree rather than degrading. Nothing warns you before it happens, and nothing can: the throw is during render, so no effect-based guard ever runs. In the builder the three property call sites sit inside `AutoFormFielWrapperErrorBoundary`, so they surface the “input value is invalid, please contact support” box instead; `RichTextProperty` renders its own `FormItem` outside that boundary and has no such net.
- **`DialogContent` sets no max-height, so nothing stops a tall dialog growing past the viewport.** It is `grid` + `fixed top-1/2 left-1/2 -translate-1/2` under a fixed overlay, so any overflow hangs off the screen where the page behind cannot scroll it into view — and capping the inner body alone (`max-h-[60vh] overflow-y-auto`) does not help, because the dialog box itself is still unbounded. Put a `ScrollArea` between the header and the footer instead, the way `connect-provider-dialog.tsx` and `event-destination-dialog.tsx` do: `<ScrollArea viewPortClassName="max-h-[60vh] p-px">`, `DialogContent` left alone. Radix puts the cap and the overflow on its own viewport element, so it does not depend on the parent chain being height-constrained. When checking whether a dialog scrolls, read `clientHeight` vs `scrollHeight` off `[data-slot="scroll-area-viewport"]` rather than trusting a screenshot — browser zoom scales `vh`, so a zoomed-in window makes a correctly-capped dialog look like it overflows.
- **`MultiSelectPieceProperty` resolves the selection by *index* over `[...cachedOptions, ...options]` but renders items and writes values indexed into `options` alone, so the two lists must stay identical or the widget renders a raw index string and the next click throws.** [components/custom/multi-select-piece-property.tsx](packages/web/src/components/custom/multi-select-piece-property.tsx) computes `selectedIndicies` with `findIndex` over the *merged* list, while `items` is `options.map((_, i) => String(i))` and `sendChanges` does `options[Number(index)].value`. An index found in the `cachedOptions` half therefore addresses the wrong option — or none, and then `MultiSelectValue` falls back to `item?.label || value` and paints the literal string `"2"` as a badge, and because the primitive *appends* the newly picked index to the existing controlled value (radix `useControllableState` computes the updater against the `prop` **synchronously in the event handler**), the next selection evaluates `options[2].value` on a shorter array and throws. **No error boundary catches it** — the throw is in an event handler, not in render, so React reports it as an unhandled error, `onChange` is never called, and the click is silently discarded: the control is dead with no visible error at all. **This crash is already live on `main`** for any multi-select with `refreshOnSearch`, where a server-filtered response narrows `options` while `cachedOptions` keeps the full first list — same `"2"` badge, same uncaught `TypeError`. Treating it as cosmetic under-rates it. The lists happen to be identical today only because `cachedOptions` is `firstDropdownState.current`, seeded from the first successful fetch — so **anything that lets a value survive a refresher change breaks the invariant**: a dropdown restore after a connection switch hands the widget the *new* option list next to the *old* cached one. Reset `firstDropdownState.current = undefined` wherever the refreshers change; `onSuccess` re-seeds it from the new response before `setDropdownState`, which realigns the two lists and also stops single-select showing the *old* connection's label for a restored value (`searchable-select.tsx` merges `cachedOptions` first, so the stale label wins the `find`). The trap in testing it is that both renderers are usually mocked to `() => null` in `test/app/builder/piece-properties/`, so a suite can be 101/101 green with the widget never rendered — assert on the props handed to `MultiSelectPieceProperty` (`cachedOptions` length matching `options`), not just on the form value. **The fix is to flip the merge order — `allOptions = [...options, ...cachedOptions]` — and drive selection, `items`, item keys and `sendChanges` off that one list.** `findIndex` then lands in the options half for any value the current list still has, which is the index the rendered row uses, and in the tail for a value only the cached list can label, where `items` still resolves it; duplicates in the tail are simply unreachable. **Do not dedupe the two lists to build that basis.** `cachedOptions.filter(c => !options.some(o => deepEqual(o.value, c.value)))` is O(c·m) `deepEqual` calls *per render*, and the `deep-equal` package costs roughly **70µs per object comparison** — measured on 800 options with `{id, name}` values, that one line took **19 seconds per render** (0.02ms → 21ms even for plain string values). Option lists that big are ordinary, `refreshOnSearch` exists precisely for them, and the component re-renders on every keystroke. The ordering-only version measures *faster* than the code it replaces. General rule: `deepEqual` belongs in an O(n) scan that short-circuits, never inside a nested loop over two option lists. `searchable-select.tsx` needed the same merge order flipped for the label; it resolves by value, so it never had the crash.
+- **The f(x) toggle round-trips a property's value through a text box, and only the types named in `parseDynamicValue` survive it.** Toggling f(x) *on* stringifies the current value; toggling *off* runs `formUtils.parseDynamicValue` and falls back to `getDefaultPropertyValue` on `undefined` — so any type the switch does not name has its value silently replaced by the type's default. That is how a Dropdown holding `{{ variables['X'] }}` became `null` and, toggled back, the literal string `"null"` (GIT-1767, hit by a customer on Slack's Channel field, whose own markdown tells people to click (F) and type the id). **Do not generalize the `default:` branch to "keep any string that has a mustache token"**, which is the obvious cleanup and is wrong: `ARRAY` also carries the toggle, and `array-property.tsx` calls `formValues.map(...)`, so a preserved string throws straight into the wrapper's "input value is invalid, please contact support" boundary. Add types one at a time, checking that the manual editor tolerates a string it did not produce — `SearchableSelect` and `MultiSelectPieceProperty` just fail to match and show the placeholder (the value survives, invisibly), `ColorPicker` renders any string, `Switch` shows a non-empty string as ON. Still unhandled and still losing data: `OBJECT` and `JSON`, where a plain `{a: 1}` comes back as `{}` because only the `[`/`{` JSON restore in the dropdown branch reverses `JSON.stringify`. The toggle is offered wherever `allowDynamicValues` is true in `properties-utils.tsx`, which is the list to check against — the text-like types pass `false` there because their manual editor already accepts mentions.
- **`deepEqual` from the `deep-equal` package is LOOSE by default, so matching an option is not the same as matching its type.** Verified on `[email protected]`: `deepEqual('5', 5)`, `deepEqual(0, false)`, `deepEqual('', 0)` and `deepEqual({a:'1'}, {a:1})` are all `true`. Every option-matching call in the web dropdowns relies on this (`searchable-select.tsx`, `multi-select-piece-property.tsx`, `dynamic-dropdown-piece-property.tsx`), which is fine while the result is only used to *find* a row. It stops being fine the moment you write the matched option's value back into the form: `restoreValueIfStillInOptions` restoring `matchingOption.value` instead of the stored value silently rewrites a saved `'12345'` into `12345` when a connection switch re-resolves the dropdown, and the piece — or the backend schema — then sees a number where a string was persisted. Decide deliberately: canonicalize to the option's value (what the option list says is correct) or echo back the value the form already held; if you need the strict comparison, `deep-equal` takes `{ strict: true }`. The same looseness means a stored `0` can match an option whose value is `false`.
- **CI never type checked `packages/web`, so a `tsc` error could sit on `main` while every check stayed green.** The web build script is `vite build`, and esbuild transpiles without reading types — `packages/server/{api,worker,sandbox,utils}` build with `tsc -p` and so get the type check for free from the build step, but `packages/server/engine` is bundled by esbuild and has the same hole — it carries pre-existing type errors today, so it cannot just be added to the step. Nothing else in `ci.yml` ran `tsc` against web. The failure mode is that the author's editor is the only thing that sees the error, and it reaches whoever pulls next: [#15524](https://github.com/activepieces/activepieces/pull/15524) landed a `'message' in apError.params` on a union where `INVALID_CREDENTIALS` declares `params: null`, and `main` was red in every contributor's IDE for hours with no CI signal. **Read that class of error as a runtime bug, not a lint nit**: `in` throws a `TypeError` on `null` and `undefined`, so the suppressed complaint was describing a real crash inside a React Query `onError` — the toast never rendered and the user got no feedback at all. The narrowing was honest and the cast was not: `error.response.data as ApErrorParams` promises a `params` object that a proxy 500, a gateway HTML page or a bare `{ message }` body does not carry, so the property is `undefined` at runtime no matter what the cast says. `ci.yml` now runs `npx turbo run typecheck --filter=web` (the `typecheck` task already existed in `turbo.json`) before the core build. When adding a package that builds through a bundler rather than `tsc`, give it the same explicit step.
- **The UI theme default is `light`, not `system` — and the embed pins to light too.** `ThemeProvider` ([components/providers/theme-provider.tsx](packages/web/src/components/providers/theme-provider.tsx)) falls back to `light` when `vite-ui-theme` is unset, and the embed route calls `setThemeWithoutPersisting(event.data.data.mode ?? 'light')` so a vendor that passes no `styling.mode` never inherits the *viewer's* OS theme inside the iframe. **The embed must use the non-persisting setter**: the iframe is same-origin with the main app, so the plain `setTheme` writes the vendor's styling choice into the shared `vite-ui-theme` key and the user's own UI silently loses the theme they picked — one visit to a customer's embed and their dark mode is gone. Anything that is a *surface's* display choice rather than the user's preference wants that setter (or `forceLightMode`, which the auth pages use). The flip side is that non-persisted theme state only survives while the provider does, and `app.tsx` remounts its subtree on every language change via `<React.Fragment key={i18n.language}>` — a fresh `ThemeProvider` re-reads `vite-ui-theme` and the override is gone. So `ThemeProvider` sits *outside* that keyed fragment, and any other provider holding state that is not written to storage has to as well. The embed hits this exactly: `VENDOR_INIT` applies `styling.mode` and then `i18n.changeLanguage(locale)` inside the same handler, so a vendor asking for dark plus a non-`en` locale is the case that breaks. `system` is still a real option, but only when a user picks it in Settings > Appearance. The default used to be `system` and nobody noticed, because `system` was silently broken — it read `prefers-color-scheme` once at mount and never re-read it, so in practice everyone landed on light; fixing that (GIT-1478, #15463) flipped every dark-OS user with no stored preference into dark overnight, which is what GIT-1888 reverses. So a "dark mode is the default now" report is not a regression in the toggle, it is this default. Note the resolution happens in one `useEffect` that also depends on `branding`: with no branding loaded it returns early and *no* theme class is on `<html>` at all, which reads as light because that is the unclassed stylesheet.
diff --git a/packages/web/src/app/builder/piece-properties/auto-form-field-wrapper.tsx b/packages/web/src/app/builder/piece-properties/auto-form-field-wrapper.tsx
index 0cdef2c229f..c5e11876f9e 100644
--- a/packages/web/src/app/builder/piece-properties/auto-form-field-wrapper.tsx
+++ b/packages/web/src/app/builder/piece-properties/auto-form-field-wrapper.tsx
@@ -177,6 +177,9 @@ export function getValueForInputOnDynamicToggleChange(
) {
return currentValue;
}
+ if (currentValue === null) {
+ return '';
+ }
return JSON.stringify(currentValue);
}
case PropertyExecutionType.MANUAL: {
diff --git a/packages/web/src/features/pieces/utils/form-utils.tsx b/packages/web/src/features/pieces/utils/form-utils.tsx
index 2694473cc4f..b66a9fe7e50 100644
--- a/packages/web/src/features/pieces/utils/form-utils.tsx
+++ b/packages/web/src/features/pieces/utils/form-utils.tsx
@@ -1,5 +1,6 @@
import {
Metadata,
+ extractMustacheTokens,
isNil,
parseToJsonIfPossible,
} from '@activepieces/core-utils';
@@ -105,14 +106,36 @@ function parseDynamicValue({
}: {
property: PieceProperty;
value: unknown;
-}): unknown[] | boolean | undefined {
+}): unknown {
const parsed = parseToJsonIfPossible(value);
+ const isExpression =
+ typeof value === 'string' && extractMustacheTokens(value).length > 0;
switch (property.type) {
case PropertyType.MULTI_SELECT_DROPDOWN:
case PropertyType.STATIC_MULTI_SELECT_DROPDOWN:
- return Array.isArray(parsed) ? parsed : undefined;
+ if (Array.isArray(parsed)) {
+ return parsed;
+ }
+ return isExpression ? value : undefined;
case PropertyType.CHECKBOX:
- return typeof parsed === 'boolean' ? parsed : undefined;
+ if (typeof parsed === 'boolean') {
+ return parsed;
+ }
+ return isExpression ? value : undefined;
+ case PropertyType.DROPDOWN:
+ case PropertyType.STATIC_DROPDOWN: {
+ if (typeof value === 'number') {
+ return value;
+ }
+ if (typeof value !== 'string' || value === '') {
+ return undefined;
+ }
+ const restoredJsonStringifiedValue =
+ /^\s*[[{]/.test(value) && parsed !== value;
+ return restoredJsonStringifiedValue ? parsed : value;
+ }
+ case PropertyType.COLOR:
+ return typeof value === 'string' && value !== '' ? value : undefined;
default:
return undefined;
}
diff --git a/packages/web/test/features/pieces/parse-dynamic-value.test.ts b/packages/web/test/features/pieces/parse-dynamic-value.test.ts
index 3828261d063..1f428b4da56 100644
--- a/packages/web/test/features/pieces/parse-dynamic-value.test.ts
+++ b/packages/web/test/features/pieces/parse-dynamic-value.test.ts
@@ -14,6 +14,12 @@ const checkbox = Property.Checkbox({
required: false,
});
const shortText = Property.ShortText({ displayName: 'Text', required: false });
+const color = Property.Color({ displayName: 'Brand', required: false });
+const staticDropdown = Property.StaticDropdown({
+ displayName: 'Channel',
+ required: true,
+ options: { options: [{ label: 'General', value: 'C0123' }] },
+});
describe('formUtils.parseDynamicValue', () => {
it.each([
@@ -26,11 +32,48 @@ describe('formUtils.parseDynamicValue', () => {
});
it.each([
+ ["{{ variables['channel'] }}", staticDropdown],
+ ['{{ trigger.body.channel || "C0123" }}', staticDropdown],
['{{ trigger.body.units }}', multiSelect],
+ ['{{ trigger.body.enabled }}', checkbox],
+ ['{{ trigger.body.brandColor }}', color],
+ ['#8142E3', color],
+ ])('preserves the value %s across the toggle', (value, property) => {
+ expect(formUtils.parseDynamicValue({ property, value })).toEqual(value);
+ });
+
+ it('restores a stringified array whose item holds an expression', () => {
+ expect(
+ formUtils.parseDynamicValue({
+ property: multiSelect,
+ value: '["{{ trigger.body.unit }}","year"]',
+ }),
+ ).toEqual(['{{ trigger.body.unit }}', 'year']);
+ });
+
+ it.each([
+ ['C0123', staticDropdown, 'C0123'],
+ ['5', staticDropdown, '5'],
+ [5, staticDropdown, 5],
+ ['true', staticDropdown, 'true'],
+ ['null', staticDropdown, 'null'],
+ ['price {{high', staticDropdown, 'price {{high'],
+ ['{"tier":"pro"}', staticDropdown, { tier: 'pro' }],
+ ['["a","b"]', staticDropdown, ['a', 'b']],
+ ])('keeps the dropdown literal %s as %s', (value, property, expected) => {
+ expect(formUtils.parseDynamicValue({ property, value })).toEqual(expected);
+ });
+
+ it.each([
['year', multiSelect],
['{"not":"an array"}', multiSelect],
+ ['price {{high', multiSelect],
['1', checkbox],
['["year","day"]', shortText],
+ ['', staticDropdown],
+ [undefined, staticDropdown],
+ ['', color],
+ [undefined, color],
])('has nothing unambiguous to restore in %s', (value, property) => {
expect(formUtils.parseDynamicValue({ property, value })).toBeUndefined();
});