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): an in-builder import purges every cached query of the flow, including its sample data (#15381)

Bartosz Majewski761c6695e062
diff --git a/brain/knowledge/engineering/web-feature-anatomy.md b/brain/knowledge/engineering/web-feature-anatomy.md
index 9ad73f14c0a..a44355a55a0 100644
--- a/brain/knowledge/engineering/web-feature-anatomy.md
+++ b/brain/knowledge/engineering/web-feature-anatomy.md
@@ -169,6 +169,7 @@ way back was to stash the handful of intended edits, `git checkout` the package,
- **An alpha wash over white is far lighter than the colour it names, so a mock's flat grey slab is not what an opacity class renders.** A neutral at 40% over a white card resolves to a shade nobody would call grey. This matters when a design review compares a mock to the app: the MCP Pieces action panel *looked* like low-contrast text on a grey ground in Paper, while the shipped panel was already near-white and its real contrast problem was elsewhere (10px labels, a faint count ≈ 2.3:1). Resolve the alpha before concluding anything about contrast, and prefer an opaque step, which renders the same in the mock and the app. For a *tinted* pill or frame, reach for the `Badge` variants (`destructive` / `warning` / `success` / `info` in `components/ui/badge.tsx`) — each is a step-3 fill, step-11 ink and step-7 border that holds in both themes with no `dark:`.
- **Two everyday building blocks carry a hidden per-instance cost, so a long list gets expensive well before anyone notices — and `VirtualizedList` only helps if the list has a scrollable ancestor.** `TextWithTooltip` registers its own `window` resize listener and does a `scrollWidth`/`clientWidth` layout read per instance (`components/custom/text-with-tooltip.tsx`), and `PieceIcon` wraps every logo in a Radix `Tooltip` (`features/pieces/components/piece-icon.tsx`). A row using one icon and two tooltips therefore costs an image fetch, a tooltip root and two resize listeners; the MCP Pieces list hits ~740 rows behind its "Show N more" button, which is a thousand-plus listeners from one click. Reach for `components/ui/virtualized-list.tsx` (already on `@tanstack/react-virtual`) rather than rolling one: its `virtualizeThreshold` defaults to 100 so a short list keeps its plain inline render, and it measures rows with `measureElement`, so variable heights work. The prerequisite is that `findScrollParent` locates an `overflow: auto|scroll` ancestor or a Radix `data-slot="scroll-area-viewport"` — dashboard pages get one from `app/components/project-layout` — because with no scroll element the virtualizer keeps its seeded viewport and never responds to scrolling. Note also that virtualization does nothing for a *re-render* storm: deriving rows in the render body (filter + sort + fresh objects) and un-memoised rows re-do that work on every keystroke, which is a `useMemo`/`memo` problem, not a windowing one.
- **Virtualizing an existing list silently kills every `:last-child` style on its rows.** `VirtualizedList` wraps each row in its own absolutely-positioned element, so a row that was one of many siblings becomes an only child — `last:border-b-0`, meant to drop the final separator, then matches *every* row and removes all of them. Nothing errors and the list still renders; the borders are just gone. Its non-virtualized branch wraps items in fragments, which create no DOM, so `:last-child` keeps working below the threshold and the two paths disagree — the bug appears only once the list crosses 100 items. Make the separator explicit (pass the row its index or an `isLastRow` flag) before wrapping an existing bordered list, and check the same styles for `:first-child`, `:nth-child` and sibling combinators like `space-y-*`.
+- **A `removeQueries` filter written as a whole key silently stops matching the moment that key is reshaped, `gcTime: 0` does not save you, and the flow key is not the only cache the builder reads.** In-builder import bounces `/flows/:id → /flow-import-redirect/:id → /flows/:id` so the builder remounts, and the guard purges the flow's cache on the way through. For 0.84.0–0.90.3 the filter was built from a helper that returned a different shape than the builder page's literal key, so it matched nothing: the import persisted server-side and the canvas kept rendering the pre-import flow (GIT-1863, Pylon 5914). #13178 had fixed it once and #13086 reshaped the page key six days later inside the same 0.84.0 release; #15142 restored the match by accident in 0.90.4. Do not assume the builder's `gcTime: 0` makes the purge redundant: collection is scheduled on a `setTimeout` after the last observer unmounts, so the remount in the same tick reads the stale entry first. A fresh canvas is also not enough: the import rewrites the draft in place, so its version id survives and so do `['sampleData', versionId]` / `['sampleDataInput', versionId]`, and `BuilderStateProvider` copies sample data into its store once through `useRef`, so the background refetch never reaches it and the store keeps the pre-import sample data. Most of the UI hides it, because the server clears `lastTestDate` on every imported step and the test panel and advanced data selector gate on that field; it leaks only where nothing checks `lastTestDate`, such as the friendly data-selector view for a primitive or array output and the formula preview in step inputs. `flowHooks.removeFlowFromCache` is the one owner of the purge: it removes the `['flow', flowId]` prefix and the sample data of every cached version of that flow. Pin it with a test that renders the real `FlowBuilderPage` through the redirect, never one that rebuilds the page key from the helper — that is circular and stays green when the page goes back to a literal key. A stub of `BuilderStateProvider` in such a test must keep its first props, or the refetch re-renders it with fresh data and hides the bug.
- **`placeholderData: keepPreviousData` reuses the last result on *any* query-key change, so on a scoped query it renders one scope's data under another scope's label.** It is reached for to stop a debounced search flashing a skeleton on every settle, which is the transition it earns its keep on — but the key usually carries a scope segment too (a `projectId`), and switching that is treated identically. The MCP Reach tab showed the previous project's pieces under the newly picked project until the replacement landed, and for a project the user cannot see, until the denial swapped in the access alert. Nothing crosses a permission boundary (the rows were fetched and authorised under the previous scope, and the pending request can only return the new scope's data or a denial) so it is misattribution, not disclosure — but on a page whose claim is "this is what a client can reach in *this* project", an admin reads a restricted project as wide open. Scope the placeholder instead of dropping it: the v5 form takes a second argument, so `(previousData, previousQuery) => previousQuery?.queryKey[SCOPE] === scope ? previousData : undefined` keeps the search behaviour and restores the loading state on a scope switch, where it is the correct feedback anyway. Put the scope segment early in the key so the comparison is stable, and cover it with a test — the positional index is exactly what a later key reorder breaks silently. A filter-driven list (a multi-select of projects in the URL, as on the Connections tab) is *not* the same case and wants the plain `keepPreviousData`.
- **`<label for>` never gives an accessible name to a `contenteditable` div — only `aria-label`/`aria-labelledby` does.** HTML restricts `for` to *labelable* elements (`input`, `select`, `textarea`, `button`, `meter`, `output`, `progress`), so `HTMLLabelElement.control()` returns null for a `div[role="textbox"]` and no browser feeds that label into the accname computation. This bites every piece property in the builder: `FormLabel` mints `htmlFor={formItemId}` ([components/ui/form.tsx](packages/web/src/components/ui/form.tsx)) but the mention editor is a ProseMirror contenteditable, so the field is announced as "edit text, blank". The trap in verifying it is that `document.getElementById(label.getAttribute('for'))` resolving proves *id resolution*, not naming — an a11y probe built on `getElementById` reports a fix that screen readers do not see. Check Chrome DevTools → Elements → Accessibility → Computed Properties → Name instead. Attributes reach the editable node through tiptap's `editorProps.attributes`, not through `FormControl`: Radix `Slot` targets `TiptapEditor`'s wrapper div, and prosemirror-view's `computeDocDeco` copies every key of `attributes` onto the contenteditable except `class`/`style`/`contenteditable`/`nodeName`. See [#15217](https://github.com/activepieces/activepieces/pull/15217).
- **`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.
diff --git a/packages/web/src/app/guards/after-import-flow-redirect.tsx b/packages/web/src/app/guards/after-import-flow-redirect.tsx
index 38f8a3cec56..9339303432d 100644
--- a/packages/web/src/app/guards/after-import-flow-redirect.tsx
+++ b/packages/web/src/app/guards/after-import-flow-redirect.tsx
@@ -9,15 +9,11 @@ export const AfterImportFlowRedirect = () => {
const navigate = useNavigate();
const queryClient = useQueryClient();
useEffect(() => {
- if (flowId) {
- queryClient.removeQueries({
- queryKey: flowHooks.createFlowQueryKeys({
- flowId,
- versionId: undefined,
- }),
- });
+ if (!flowId) {
+ return;
}
+ flowHooks.removeFlowFromCache({ flowId, queryClient });
navigate(`/flows/${flowId}`, { replace: true });
}, []);
- return <></>;
+ return null;
};
diff --git a/packages/web/src/app/routes/flows/id/index.tsx b/packages/web/src/app/routes/flows/id/index.tsx
index c8bb3cbe137..c4c35cf4219 100644
--- a/packages/web/src/app/routes/flows/id/index.tsx
+++ b/packages/web/src/app/routes/flows/id/index.tsx
@@ -10,7 +10,7 @@ import { BuilderPage } from '@/app/builder';
import { BuilderStateProvider } from '@/app/builder/state/builder-state-provider';
import { LoadingSpinner } from '@/components/custom/spinner';
import { buttonVariants } from '@/components/ui/button';
-import { flowsApi, sampleDataHooks } from '@/features/flows';
+import { flowHooks, flowsApi, sampleDataHooks } from '@/features/flows';
import { authenticationSession } from '@/lib/authentication-session';
import { cn } from '@/lib/utils';
@@ -24,7 +24,10 @@ const FlowBuilderPage = () => {
isLoading,
isError,
} = useQuery<PopulatedFlow, Error>({
- queryKey: ['flow', flowId, versionId, authenticationSession.getProjectId()],
+ queryKey: [
+ ...flowHooks.createFlowQueryKeys({ flowId: flowId!, versionId }),
+ authenticationSession.getProjectId(),
+ ],
queryFn: () => flowsApi.get(flowId!, versionId ? { versionId } : undefined),
gcTime: 0,
retry: false,
diff --git a/packages/web/src/features/flows/hooks/flow-hooks.tsx b/packages/web/src/features/flows/hooks/flow-hooks.tsx
index a5ad4e86ace..0c96171f4a9 100644
--- a/packages/web/src/features/flows/hooks/flow-hooks.tsx
+++ b/packages/web/src/features/flows/hooks/flow-hooks.tsx
@@ -49,7 +49,10 @@ import { NEW_FLOW_QUERY_PARAM } from '@/lib/route-utils';
import { flowsApi } from '../api/flows-api';
import { flowsUtils } from '../utils/flows-utils';
+import { sampleDataHooks } from './sample-data-hooks';
+
const createFlowsQueryKey = (projectId: string) => ['flows', projectId];
+const createFlowQueryKeyPrefix = (flowId: string) => ['flow', flowId];
export const flowHooks = {
invalidateFlowsQuery: (queryClient: QueryClient) => {
queryClient.invalidateQueries({
@@ -598,7 +601,27 @@ export const flowHooks = {
}: {
flowId: string;
versionId: string | undefined;
- }) => ['flow', flowId, versionId],
+ }) => [...createFlowQueryKeyPrefix(flowId), versionId],
+ removeFlowFromCache: ({
+ flowId,
+ queryClient,
+ }: {
+ flowId: string;
+ queryClient: QueryClient;
+ }) => {
+ const flowQueryKeyPrefix = createFlowQueryKeyPrefix(flowId);
+ queryClient
+ .getQueriesData<PopulatedFlow | null>({ queryKey: flowQueryKeyPrefix })
+ .forEach(([, flow]) => {
+ if (!isNil(flow)) {
+ sampleDataHooks.removeSampleData({
+ flowVersionId: flow.version.id,
+ queryClient,
+ });
+ }
+ });
+ queryClient.removeQueries({ queryKey: flowQueryKeyPrefix });
+ },
};
type UseChangeFlowStatusParams = {
diff --git a/packages/web/src/features/flows/hooks/sample-data-hooks.ts b/packages/web/src/features/flows/hooks/sample-data-hooks.ts
index d2aee8c2923..971f7505207 100644
--- a/packages/web/src/features/flows/hooks/sample-data-hooks.ts
+++ b/packages/web/src/features/flows/hooks/sample-data-hooks.ts
@@ -80,6 +80,16 @@ export const sampleDataHooks = {
queryKey: ['sampleDataInput', flowVersionId],
});
},
+ removeSampleData: ({
+ flowVersionId,
+ queryClient,
+ }: {
+ flowVersionId: string;
+ queryClient: QueryClient;
+ }) => {
+ queryClient.removeQueries({ queryKey: ['sampleData', flowVersionId] });
+ queryClient.removeQueries({ queryKey: ['sampleDataInput', flowVersionId] });
+ },
};
async function getSampleData(
diff --git a/packages/web/test/app/guards/after-import-flow-redirect.test.tsx b/packages/web/test/app/guards/after-import-flow-redirect.test.tsx
new file mode 100644
index 00000000000..ccbf464d549
--- /dev/null
+++ b/packages/web/test/app/guards/after-import-flow-redirect.test.tsx
@@ -0,0 +1,148 @@
+// @vitest-environment jsdom
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act, render, screen } from '@testing-library/react';
+import {
+ MemoryRouter,
+ NavigateFunction,
+ Route,
+ Routes,
+ useNavigate,
+} from 'react-router-dom';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { AfterImportFlowRedirect } from '@/app/guards/after-import-flow-redirect';
+import { FlowBuilderPage } from '@/app/routes/flows/id';
+import { flowHooks } from '@/features/flows';
+
+const server = vi.hoisted(() => ({
+ displayName: 'old_draft_marker',
+ triggerSampleData: 'old_sample_data',
+}));
+
+vi.mock('i18next', () => ({ t: (key: string) => key }));
+vi.mock('@/features/flows/api/flows-api', () => ({
+ flowsApi: {
+ get: async (flowId: string) => ({
+ id: flowId,
+ projectId: 'project_1',
+ version: {
+ id: 'version_1',
+ flowId,
+ displayName: server.displayName,
+ state: 'DRAFT',
+ trigger: { name: 'trigger', type: 'EMPTY', settings: {}, valid: true },
+ },
+ }),
+ },
+}));
+vi.mock('@/features/flows/api/sample-data-api', () => ({
+ sampleDataApi: {
+ get: async () => server.triggerSampleData,
+ },
+}));
+vi.mock('@/app/builder', () => ({ BuilderPage: () => null }));
+vi.mock('@/app/builder/state/builder-state-provider', async () => {
+ const { useRef } = await import('react');
+ return {
+ BuilderStateProvider: (props: {
+ flowVersion: { displayName: string };
+ outputSampleData: Record<string, unknown>;
+ }) => {
+ const propsAtMount = useRef(props).current;
+ return (
+ <div data-testid="builder">
+ {propsAtMount.flowVersion.displayName}:
+ {String(propsAtMount.outputSampleData['trigger'])}
+ </div>
+ );
+ },
+ };
+});
+
+const FLOW_ID = 'flow_1';
+const OTHER_FLOW_ID = 'flow_2';
+const cachedFlow = (flowId: string) => ({
+ id: flowId,
+ version: { id: `${flowId}_version` },
+});
+
+const openBuilderOnFlow = () => {
+ const navigation: { navigate?: NavigateFunction } = {};
+ const CaptureNavigate = () => {
+ navigation.navigate = useNavigate();
+ return null;
+ };
+ render(
+ <QueryClientProvider client={new QueryClient()}>
+ <MemoryRouter initialEntries={[`/flows/${FLOW_ID}`]}>
+ <CaptureNavigate />
+ <Routes>
+ <Route path="/flows/:flowId" element={<FlowBuilderPage />} />
+ <Route
+ path="/flow-import-redirect/:flowId"
+ element={<AfterImportFlowRedirect />}
+ />
+ </Routes>
+ </MemoryRouter>
+ </QueryClientProvider>,
+ );
+ return navigation;
+};
+
+describe('AfterImportFlowRedirect', () => {
+ afterEach(() => {
+ server.displayName = 'old_draft_marker';
+ server.triggerSampleData = 'old_sample_data';
+ });
+
+ it('remounts the builder page on the imported flow instead of its cached pre-import copy', async () => {
+ const navigation = openBuilderOnFlow();
+ expect(
+ await screen.findByText('old_draft_marker:old_sample_data'),
+ ).toBeTruthy();
+
+ server.displayName = 'imported_marker';
+ server.triggerSampleData = 'imported_sample_data';
+ act(() => {
+ navigation.navigate?.(`/flow-import-redirect/${FLOW_ID}`);
+ });
+
+ expect(
+ await screen.findByText('imported_marker:imported_sample_data'),
+ ).toBeTruthy();
+ });
+
+ it('purges version-pinned queries of the imported flow and keeps other flows', () => {
+ const queryClient = new QueryClient();
+ const versionPinnedKey = flowHooks.createFlowQueryKeys({
+ flowId: FLOW_ID,
+ versionId: 'version_1',
+ });
+ const otherFlowKey = flowHooks.createFlowQueryKeys({
+ flowId: OTHER_FLOW_ID,
+ versionId: undefined,
+ });
+ queryClient.setQueryData(versionPinnedKey, cachedFlow(FLOW_ID));
+ queryClient.setQueryData(otherFlowKey, cachedFlow(OTHER_FLOW_ID));
+
+ render(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={[`/flow-import-redirect/${FLOW_ID}`]}>
+ <Routes>
+ <Route
+ path="/flow-import-redirect/:flowId"
+ element={<AfterImportFlowRedirect />}
+ />
+ <Route path="/flows/:flowId" element={<div>builder</div>} />
+ </Routes>
+ </MemoryRouter>
+ </QueryClientProvider>,
+ );
+
+ expect(queryClient.getQueryData(versionPinnedKey)).toBeUndefined();
+ expect(queryClient.getQueryData(otherFlowKey)).toEqual(
+ cachedFlow(OTHER_FLOW_ID),
+ );
+ expect(screen.getByText('builder')).toBeTruthy();
+ });
+});