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(builder): leave the run view when Edit flow is clicked in an embed (#17181)

Othman Abu Ajamieh048d72165cfb
diff --git a/brain/knowledge/platform-editions-ee/embed.md b/brain/knowledge/platform-editions-ee/embed.md
index 157b105f684..b2680a9382d 100644
--- a/brain/knowledge/platform-editions-ee/embed.md
+++ b/brain/knowledge/platform-editions-ee/embed.md
@@ -74,6 +74,7 @@ The Embed Onboarding stepper at `/platform/embedding`. Four steps exist as files
- **"GTM does nothing" in the embed usually means an empty or unpublished container, not a loader bug.** `gtm.js?id=…` is ~330 KB even for a container with zero tags, so size proves nothing. Verify in three steps: inside the iframe `window.google_tag_manager['GTM-…']` exists and `dataLayer` shows `gtm.js` → `gtm.dom` → `gtm.load` (GTM booted); then fetch the same `gtm.js` and parse the `var data = {…};` blob — `resource.tags` / `resource.rules` empty means nothing can fire; GTM serves only the published Live version, so workspace edits change nothing until Submit. Verified 2026-09-10 against `GTM-5KZNZGMN` (version 1, 0 tags).
- **Third-party tag failures surface as `Script error.` with no stack.** A cross-origin script (GTM tag, Clarity) that throws reaches `window.onerror` with `event.error == null` and the message `Script error.`; nothing in it is actionable. We deliberately left frontend error reporting untouched (2026-09-10: a global or embed-scoped filter was tried on #15442 and reverted to keep the change contained), so a vendor's broken tag shows up in Sentry as that opaque message. A tag script that fails to *load* removes its own `<script>` element and warns, so `isScriptLoaded` does not mistake a dead element for a loaded one.
- **Embed analytics see one page per session.** The embedded app runs on a memory router, so `location` stays at `/embed` while the user moves between the flows list and the builder. GTM's History Change trigger and GA4's page_view therefore fire once at load, and Clarity records one long page. We push nothing but GTM's required `gtm.js` start event; DOM-level tracking (clicks, scroll, visibility) is the vendor's GTM configuration and needs no code from us. Route-level or app-semantic events (`route_change`, `flow_published`, …) would be small `dataLayer.push` calls mirroring what `handleClientNavigation` already posts to the vendor over `CLIENT_ROUTE_CHANGED` — not built until a customer asks.
+- **In app code, `window.location` is not the app route in the embed.** The memory router keeps `window.location` at `/embed`, so any check of `/runs` or a query param through it is always false there while the browser app works. Read the route from `react-router-dom` (`useLocation`, `useSearchParams`). Lint blocks `useLocation` from `react-use` in `packages/web`, but not a direct `window.location` read (ENG-1397 tracks one in the builder canvas).
- **`VENDOR_INIT` trusts `event.source`, not `event.origin`.** The client accepts the message from `window.opener ?? window.parent`; the real trust gate is the external-token exchange succeeding. Gate anything sensitive (script injection, storage) on that `onSuccess`, not on receipt of `VENDOR_INIT`.
- **Links to activepieces.com docs must be hidden in the embed.** The embed is white-labeled, so hide any in-app "Learn more" or docs link when `useEmbedding().embedState.isEmbedded` is true. Existing examples: the formula search popover's "See All", the pieces selector's request-piece button, the table import dialog's template-format link.
diff --git a/packages/web/.eslintrc.json b/packages/web/.eslintrc.json
index 798c0919cfd..2702aebf8a1 100644
--- a/packages/web/.eslintrc.json
+++ b/packages/web/.eslintrc.json
@@ -57,6 +57,19 @@
"rules": {
"react-hooks/rules-of-hooks": "error",
"react-hooks/exhaustive-deps": "warn",
+ "no-restricted-imports": [
+ "error",
+ {
+ "patterns": ["lodash", "lodash/*"],
+ "paths": [
+ {
+ "name": "react-use",
+ "importNames": ["useLocation"],
+ "message": "Use useLocation from react-router-dom. The embed mounts a memory router, so window.location is not the app route."
+ }
+ ]
+ }
+ ],
"import/no-restricted-paths": [
"error",
{
diff --git a/packages/web/src/app/builder/builder-header/flow-status/view-draft-or-edit-flow-button.tsx b/packages/web/src/app/builder/builder-header/flow-status/view-draft-or-edit-flow-button.tsx
index 52517a7cb02..bc6982c00c0 100644
--- a/packages/web/src/app/builder/builder-header/flow-status/view-draft-or-edit-flow-button.tsx
+++ b/packages/web/src/app/builder/builder-header/flow-status/view-draft-or-edit-flow-button.tsx
@@ -2,8 +2,7 @@ import { Permission } from '@activepieces/core-utils';
import { FlowVersionState } from '@activepieces/shared';
import { t } from 'i18next';
import { EyeIcon, PencilIcon } from 'lucide-react';
-import { useNavigate } from 'react-router-dom';
-import { useLocation } from 'react-use';
+import { useLocation, useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { useAuthorization } from '@/hooks/authorization-hooks';
diff --git a/packages/web/src/app/builder/flow-canvas/hooks.tsx b/packages/web/src/app/builder/flow-canvas/hooks.tsx
index 4e94cdb646e..61b4afbcd39 100644
--- a/packages/web/src/app/builder/flow-canvas/hooks.tsx
+++ b/packages/web/src/app/builder/flow-canvas/hooks.tsx
@@ -12,7 +12,8 @@ import { useMutation, useQuery } from '@tanstack/react-query';
import { useReactFlow } from '@xyflow/react';
import { t } from 'i18next';
import { useCallback, useEffect, useRef } from 'react';
-import { useLocation, usePrevious } from 'react-use';
+import { useLocation } from 'react-router-dom';
+import { usePrevious } from 'react-use';
import { useDebouncedCallback } from 'use-debounce';
import { useEmbedding } from '@/components/providers/embed-provider';
@@ -59,6 +60,7 @@ const useListenToExistingRun = () => {
}
const flowRun = await flowRunsApi.getPopulated(run.id);
setRun(flowRun, flowVersion);
+ return flowRun;
},
enabled:
!isNil(run) &&
diff --git a/packages/web/src/app/builder/flow-canvas/widgets/use-flow-lock.ts b/packages/web/src/app/builder/flow-canvas/widgets/use-flow-lock.ts
index 4707ea6b585..a6e8b07e4a4 100644
--- a/packages/web/src/app/builder/flow-canvas/widgets/use-flow-lock.ts
+++ b/packages/web/src/app/builder/flow-canvas/widgets/use-flow-lock.ts
@@ -31,11 +31,9 @@ function useFlowLock() {
const canEditFlow = checkAccess(Permission.WRITE_FLOW);
// refresh the flow in place after a successful take-over; a full-page
- // reload would break the embed SDK handshake inside an iframe. When viewing
- // a run, mirror EditFlowOrViewDraftButton: navigate to the flow
- // (client-side, embed-safe) instead of editing a draft under the run view.
- // Branch on the builder run state, not the URL: embed mounts a memory
- // router, so window.location never reflects the in-app route.
+ // reload would break the embed SDK handshake inside an iframe. When a run
+ // is shown, navigate to the flow (client-side, embed-safe) instead of
+ // editing a draft under the run view.
const onTakeOver = useCallback(() => {
if (!isNil(run)) {
navigate(`/flows/${flowId}`);
diff --git a/packages/web/test/app/builder/builder-header/flow-status/view-draft-or-edit-flow-button.test.tsx b/packages/web/test/app/builder/builder-header/flow-status/view-draft-or-edit-flow-button.test.tsx
new file mode 100644
index 00000000000..8fa567ff456
--- /dev/null
+++ b/packages/web/test/app/builder/builder-header/flow-status/view-draft-or-edit-flow-button.test.tsx
@@ -0,0 +1,163 @@
+// @vitest-environment jsdom
+import {
+ FlowOperationStatus,
+ FlowRun,
+ FlowRunStatus,
+ FlowStatus,
+ FlowTriggerType,
+ FlowVersionState,
+ PopulatedFlow,
+ RunEnvironment,
+} from '@activepieces/shared';
+import { QueryClient } from '@tanstack/react-query';
+import { fireEvent, render, screen } from '@testing-library/react';
+import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
+import { io } from 'socket.io-client';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { EditFlowOrViewDraftButton } from '@/app/builder/builder-header/flow-status/view-draft-or-edit-flow-button';
+import {
+ BuilderStateContext,
+ createBuilderStore,
+} from '@/app/builder/builder-hooks';
+
+const harness = vi.hoisted(() => ({
+ switchToDraft: vi.fn(),
+ pathname: '',
+}));
+
+vi.mock('i18next', () => ({ t: (key: string) => key }));
+
+vi.mock('@/hooks/authorization-hooks', () => ({
+ useAuthorization: () => ({ checkAccess: () => true }),
+}));
+
+vi.mock('@/app/builder/flow-canvas/hooks', () => ({
+ flowCanvasHooks: {
+ useSwitchToDraft: () => ({
+ switchToDraft: harness.switchToDraft,
+ isSwitchingToDraftPending: false,
+ }),
+ },
+}));
+
+describe('EditFlowOrViewDraftButton', () => {
+ beforeEach(() => {
+ harness.switchToDraft.mockReset();
+ });
+
+ it('leaves the run route through the app router, whatever window.location says', () => {
+ renderButton({ route: '/projects/project-1/runs/run-1' });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Edit flow' }));
+
+ expect(harness.pathname).toBe('/flows/flow-1');
+ expect(harness.switchToDraft).not.toHaveBeenCalled();
+ });
+
+ it('switches to the draft in place after a test run in the builder', () => {
+ renderButton({ route: '/projects/project-1/flows/flow-1' });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Edit flow' }));
+
+ expect(harness.pathname).toBe('/projects/project-1/flows/flow-1');
+ expect(harness.switchToDraft).toHaveBeenCalledTimes(1);
+ });
+});
+
+function renderButton({ route }: { route: string }) {
+ const flow = publishedFlow();
+ const store = createBuilderStore({
+ flow,
+ flowVersion: flow.version,
+ readonly: true,
+ hideTestWidget: false,
+ run: flowRun(),
+ outputSampleData: {},
+ inputSampleData: {},
+ socket: io({ autoConnect: false }),
+ queryClient: new QueryClient(),
+ });
+ render(
+ <MemoryRouter initialEntries={[route]}>
+ <BuilderStateContext.Provider value={store}>
+ <Routes>
+ <Route
+ path="*"
+ element={
+ <>
+ <EditFlowOrViewDraftButton onCanvas={false} />
+ <Pathname />
+ </>
+ }
+ />
+ </Routes>
+ </BuilderStateContext.Provider>
+ </MemoryRouter>,
+ );
+}
+
+function Pathname() {
+ harness.pathname = useLocation().pathname;
+ return null;
+}
+
+function flowRun(): FlowRun {
+ return {
+ id: 'run-1',
+ created: '2026-01-01T00:00:00.000Z',
+ updated: '2026-01-01T00:00:00.000Z',
+ projectId: 'project-1',
+ flowId: 'flow-1',
+ flowVersionId: 'version-1',
+ failParentOnFailure: false,
+ logsFileId: null,
+ status: FlowRunStatus.SUCCEEDED,
+ environment: RunEnvironment.PRODUCTION,
+ steps: {},
+ tags: [],
+ archivedAt: null,
+ };
+}
+
+function publishedFlow(): PopulatedFlow {
+ return {
+ id: 'flow-1',
+ created: '2026-01-01T00:00:00.000Z',
+ updated: '2026-01-01T00:00:00.000Z',
+ projectId: 'project-1',
+ externalId: 'flow-1',
+ ownerId: null,
+ folderId: null,
+ status: FlowStatus.ENABLED,
+ publishedVersionId: 'version-1',
+ metadata: null,
+ operationStatus: FlowOperationStatus.NONE,
+ timeSavedPerRun: null,
+ templateId: null,
+ createdBy: null,
+ version: {
+ id: 'version-1',
+ created: '2026-01-01T00:00:00.000Z',
+ updated: '2026-01-01T00:00:00.000Z',
+ flowId: 'flow-1',
+ displayName: 'Order lookup',
+ trigger: {
+ name: 'trigger',
+ valid: true,
+ displayName: 'Catch Webhook',
+ type: FlowTriggerType.EMPTY,
+ settings: {},
+ lastUpdatedDate: '2026-01-01T00:00:00.000Z',
+ },
+ updatedBy: null,
+ valid: true,
+ schemaVersion: null,
+ agentIds: [],
+ state: FlowVersionState.LOCKED,
+ connectionIds: [],
+ backupFiles: null,
+ notes: [],
+ },
+ };
+}
diff --git a/packages/web/test/app/builder/flow-canvas/use-listen-to-existing-run.test.tsx b/packages/web/test/app/builder/flow-canvas/use-listen-to-existing-run.test.tsx
new file mode 100644
index 00000000000..3df184765f1
--- /dev/null
+++ b/packages/web/test/app/builder/flow-canvas/use-listen-to-existing-run.test.tsx
@@ -0,0 +1,149 @@
+// @vitest-environment jsdom
+import {
+ FlowOperationStatus,
+ FlowRun,
+ FlowRunStatus,
+ FlowStatus,
+ FlowTriggerType,
+ FlowVersionState,
+ PopulatedFlow,
+ RunEnvironment,
+} from '@activepieces/shared';
+import {
+ QueryCache,
+ QueryClient,
+ QueryClientProvider,
+} from '@tanstack/react-query';
+import { render, waitFor } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+import { io } from 'socket.io-client';
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ BuilderStateContext,
+ createBuilderStore,
+} from '@/app/builder/builder-hooks';
+import { flowCanvasHooks } from '@/app/builder/flow-canvas/hooks';
+
+const flowRunsApiMock = vi.hoisted(() => ({
+ getPopulated: vi.fn<(runId: string) => Promise<FlowRun>>(),
+}));
+
+vi.mock('@/features/flow-runs', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/features/flow-runs')>();
+ return {
+ ...actual,
+ flowRunsApi: { ...actual.flowRunsApi, ...flowRunsApiMock },
+ };
+});
+
+describe('useListenToExistingRun', () => {
+ it('refreshes a running production run on the run route without a query error', async () => {
+ flowRunsApiMock.getPopulated.mockResolvedValue(
+ flowRun({ status: FlowRunStatus.SUCCEEDED }),
+ );
+ const onQueryError = vi.fn();
+ const queryClient = new QueryClient({
+ queryCache: new QueryCache({ onError: onQueryError }),
+ defaultOptions: { queries: { retry: false } },
+ });
+ const flow = publishedFlow();
+ const store = createBuilderStore({
+ flow,
+ flowVersion: flow.version,
+ readonly: true,
+ hideTestWidget: false,
+ run: flowRun({ status: FlowRunStatus.RUNNING }),
+ outputSampleData: {},
+ inputSampleData: {},
+ socket: io({ autoConnect: false }),
+ queryClient,
+ });
+
+ render(
+ <MemoryRouter initialEntries={['/projects/project-1/runs/run-1']}>
+ <QueryClientProvider client={queryClient}>
+ <BuilderStateContext.Provider value={store}>
+ <ListenToExistingRun />
+ </BuilderStateContext.Provider>
+ </QueryClientProvider>
+ </MemoryRouter>,
+ );
+
+ await waitFor(() =>
+ expect(store.getState().run?.status).toBe(FlowRunStatus.SUCCEEDED),
+ );
+ expect(flowRunsApiMock.getPopulated).toHaveBeenCalledWith('run-1');
+ await waitFor(() =>
+ expect(
+ queryClient.getQueryState(['refetched-run', 'run-1'])?.status,
+ ).toBe('success'),
+ );
+ expect(onQueryError).not.toHaveBeenCalled();
+ });
+});
+
+function ListenToExistingRun() {
+ flowCanvasHooks.useListenToExistingRun();
+ return null;
+}
+
+function flowRun({ status }: { status: FlowRunStatus }): FlowRun {
+ return {
+ id: 'run-1',
+ created: '2026-01-01T00:00:00.000Z',
+ updated: '2026-01-01T00:00:00.000Z',
+ projectId: 'project-1',
+ flowId: 'flow-1',
+ flowVersionId: 'version-1',
+ failParentOnFailure: false,
+ logsFileId: null,
+ status,
+ environment: RunEnvironment.PRODUCTION,
+ steps: {},
+ tags: [],
+ archivedAt: null,
+ };
+}
+
+function publishedFlow(): PopulatedFlow {
+ return {
+ id: 'flow-1',
+ created: '2026-01-01T00:00:00.000Z',
+ updated: '2026-01-01T00:00:00.000Z',
+ projectId: 'project-1',
+ externalId: 'flow-1',
+ ownerId: null,
+ folderId: null,
+ status: FlowStatus.ENABLED,
+ publishedVersionId: 'version-1',
+ metadata: null,
+ operationStatus: FlowOperationStatus.NONE,
+ timeSavedPerRun: null,
+ templateId: null,
+ createdBy: null,
+ version: {
+ id: 'version-1',
+ created: '2026-01-01T00:00:00.000Z',
+ updated: '2026-01-01T00:00:00.000Z',
+ flowId: 'flow-1',
+ displayName: 'Order lookup',
+ trigger: {
+ name: 'trigger',
+ valid: true,
+ displayName: 'Catch Webhook',
+ type: FlowTriggerType.EMPTY,
+ settings: {},
+ lastUpdatedDate: '2026-01-01T00:00:00.000Z',
+ },
+ updatedBy: null,
+ valid: true,
+ schemaVersion: null,
+ agentIds: [],
+ state: FlowVersionState.LOCKED,
+ connectionIds: [],
+ backupFiles: null,
+ notes: [],
+ },
+ };
+}