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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(event-streaming): destination-first setup page for OpenTelemetry tools and webhooks (#15874)
Othman Abu Ajamiehc02327c0aa9c
diff --git a/brain/knowledge/engineering/web-feature-anatomy.md b/brain/knowledge/engineering/web-feature-anatomy.mdindex 1c9e3fd8558..9ad73f14c0a 100644--- a/brain/knowledge/engineering/web-feature-anatomy.md+++ b/brain/knowledge/engineering/web-feature-anatomy.md@@ -118,6 +118,7 @@ way back was to stash the handful of intended edits, `git checkout` the package,- **`--mode=cloud` also floods the terminal with `[vite] http proxy error: /ingest/... ETIMEDOUT 127.0.0.1:3000`.** The mode only redirects the API (`API_BASE_URL` → `https://cloud.activepieces.com` in `lib/api.ts`); PostHog still posts to the *relative* `api_host: '/ingest'` (a same-origin reverse proxy so ad blockers don't drop ingestion — `providers/telemetry-provider.tsx`, mirrored in prod by the `fastifyHttpProxy` in `server.ts`). Vite proxies `/ingest` to `127.0.0.1:3000`, which isn't running. Cloud flags also turn telemetry *on* (`TELEMETRY_ENABLED` + `EDITION=cloud`), unlike a local CE backend — so posthog-js keeps polling `/ingest/flags` and flushing `/ingest/e` every few seconds. Harmless, but note the same setup sends real dev clicks to production PostHog whenever `/ingest` does resolve; the clean fix is skipping `posthog.init` under `import.meta.env.DEV`.- **A motion `layout` animation fired from inside a mutation's `.then()` fast-forwards and reads as a jump — defer the state write two frames.** Motion measures the FLIP offset at the commit that reorders the DOM, then tweens from the first animation frame. When the write happens synchronously after a mutation resolves, that frame arrives tens of ms late (the same commit is refetching a table, tearing down a dialog, re-rendering the page), motion sees a huge time delta and skips most of the tween: a rail row travelling 228px was measured collapsing to 103px in one 6ms frame, then limping through 13 frames. Wrapping the write in `requestAnimationFrame(() => requestAnimationFrame(write))` lets the mutation's re-render settle first, and the same interaction then gives up only 7.6% on the first frame and eases properly. Two traps when checking this: driving the write yourself from a console eval runs on a *quiet* main thread and always looks smooth, so it proves nothing — reproduce through the real UI action; and a route change in the same tick (creating a flow navigates straight to the builder) interrupts the projection outright, which no deferral fixes.- **`projectCollection` runs on its own private `QueryClient`, fetches once, and never refetches — so any server-derived field on `ProjectWithLimits` is frozen at page load.** `features/projects/stores/project-collection.ts` builds the collection with `queryCollectionOptions({ queryKey: ['projects'], queryClient: collectionQueryClient })`, where `collectionQueryClient` is a `new QueryClient()` local to that module, *not* the app's. So `invalidateQueries(['projects'])` from anywhere else is a no-op, there is no `refetchOnWindowFocus`, and a field like `analytics.lastFlowUpdated` keeps its page-load value until something calls `projectCollectionUtils.refetchProjects()`. Two ways to keep such a field live, and the choice matters: `refetchProjects()` refetches every project (fine for a rare event like a piece-set change — its four existing callers — but wrong on a hot path such as the builder's per-edit autosave), or `projectCollection.utils.writeUpdate({ ...project, ... })` patches the row locally with no request, letting the next natural refetch restore server truth. Note `projectCollection.update()` is a *different* thing: it routes through `onUpdate` and POSTs, and its field allowlist silently drops anything not named there. **A local patch of a server-side *aggregate* also has to reproduce that aggregate's semantics, or it desyncs in two directions.** `analytics.lastFlowUpdated` is a `MAX(flow.updated)` over living flows, so: stamp the value from the mutation response, never `new Date()` (a skewed browser clock reorders against every server-supplied sibling); write only when the incoming value is *newer*, because concurrent mutations on one project resolve out of timestamp order — builder autosaves, and the bulk paths in `use-automations-mutations.ts` that fan out `flowIds.map(id => flowsApi.update(...))` — and an unconditional write lets a late older response move the row backwards; and when the aggregate can *decrease*, a local patch cannot express it at all, so refetch instead (deleting the newest flow lowers the MAX to a value only the server knows — cheap there because deletes are user-initiated, unlike autosave). And if the patch is *deferred* at all — it is here, by two frames, so the reorder animation does not fast-forward — a refetch that lands inside that window must invalidate it, or the pending write reapplies the pre-refetch value over the authoritative one and the newer-than guard happily waves it through; stamp each scheduled write with a generation the refetch bumps.+- **A query collection reports a failed fetch as *ready*, so `useLiveQuery().isError` is never true.** `@tanstack/query-db-collection` calls `markReady()` in its error branch, and `useLiveQuery` sets `isError` only for collection status `error`: a failed load looks exactly like an empty collection (an empty table, or an edit page that treats the row as deleted). Read the failure from the collection's own `QueryClient` instead, as `eventDestinationsCollectionUtils.useAll` does (`useSyncExternalStore` over `getQueryCache().subscribe`, reading `getQueryState(key)?.status === 'error'`). For a retry button use `collection.utils.refetch()`, which resolves on failure; `utils.clearError()` refetches with `throwOnError` and rejects.- **Never format `packages/web` with bare `prettier` — the web formatting contract lives in the eslint rule, not in `.prettierrc`.** Root `.prettierrc` sets only `singleQuote`, while `packages/web/.eslintrc.json` configures `prettier/prettier` with `trailingComma: "all"`, `printWidth: 80`, `tabWidth: 2`. The repo pins prettier **2.8.4**, whose default `trailingComma` is `es5` — so `npx prettier --write` on a web file silently **strips the trailing commas out of every multi-line function call it touches**, including lines you never edited, turning a 15-line change into a 130-line diff that reviewers have to read past. Format with `npx turbo run lint --filter=web --force -- --fix` instead; that is also what `npm run lint-dev` runs. If you already ran bare prettier, `git checkout` the file and redo the edit rather than trying to hand-restore the commas. **And `lint-dev` repairs rather than reports, so a green run is not a verification on its own.** It runs `--fix`, so running it *after* `git commit` writes the correction into the working tree and leaves the broken content in the commit you push: the terminal says 33 tasks successful while CI fails on the pushed code. Run it before staging, and treat `git status` immediately afterwards as the real check. Clean tree means lint found nothing; a modified file means it just fixed something that is not in your commit.- **`packages/web`'s lint script only globs `src/**`, so nothing under `packages/web/test/` is ever linted** — not by CI's `lint` job, not by `npm run lint-dev`. Running `npx eslint 'test/**/*.{ts,tsx}'` from `packages/web` today reports 21 errors nobody has seen, so a new web test needs a manual eslint pass or it ships with errors. Most common trap: `testing-library/render-result-naming-convention` fires on any local helper whose name merely *starts with* `render` even when testing-library is not involved — renaming `render` to `renderTabText` does not silence it, only a name that doesn't begin with `render` does. **The trap compounds with the rule that sends tests there.** `packages/web/CLAUDE.md` requires a test under `packages/web/test/`, mirroring its source path, so tests do not ship in the app bundle — but `test/` is exactly what lint does not glob. So the moment you move a test out of `src/`, it leaves the lint pass, and `npx turbo run lint --filter=web` (or `--fix`) then reports **0 errors for a file it never opened**. Seen in one session: two `prettier/prettier` errors were live in a test at `src/...`, the file was moved to `test/...`, the next `lint --fix` went green, and both errors were still there — `npx eslint 'test/**'` from `packages/web` found them. Lint the moved path directly after any such move; a green turbo run is not the check. Note the conventions pull against each other: five test files still sit under `src/` (`src/lib/test/`, `src/app/builder/data-selector/`, `src/features/projects/stores/`), which is why a new test tends to land there by precedent — those five *are* linted, which is the only reason nobody has noticed.- **A settings page gets its always-visible Save bar by passing `footer` to `CenteredPage`, and passing it switches the whole layout mode.** Without `footer` the page is the original `py-6` block that scrolls with the dashboard container; with it, the page becomes `h-full flex flex-col`, children move into a `ScrollArea`, and the footer pins below — so the Save button stays reachable however long the settings list grows. The wrapper around it has to be a flex child with a definite height (`flex flex-1 flex-col min-h-0` on the `<form>`), because `PlatformLayout` hands the route a `flex-1 overflow-auto` container and an `h-full` that cannot resolve just collapses. Reach for the prop rather than hand-rolling a second page shell; the six pages that omit it render byte-identically.@@ -171,7 +172,7 @@ way back was to stash the handful of intended edits, `git checkout` the package,- **`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.-- **`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.+- **`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 `tracked-events-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`.@@ -186,3 +187,8 @@ way back was to stash the handful of intended edits, `git checkout` the package,- **A core step's picker copy (`buildCoreStepMetadata` in `step-utils.tsx`) is pinned in four places, and the test that guards it fails with a misleading message.** The English sentence is the i18n key, so it lives in `step-utils.tsx`, in `public/locales/en/translation.json`, in the matching `docs/flows/*.mdx` frontmatter, and as a key of the fake `JAPANESE_BUNDLE` inside `test/features/pieces/utils/step-utils.test.ts`. Reword the first three and the test fails with `expected ['コード', …] to include '<new sentence>'`, which reads as a locale problem; the fix is the test's own map, not a locale file. Nothing else in the repo carried the old key.- **A core step's icon is a CDN URL, not a bundled asset, and the SVGs under `packages/web/src/assets/img/piece/` are dead copies.** `buildCoreStepMetadata` in `step-utils.tsx` points Code, Loop, Router and Empty Trigger at `https://cdn.activepieces.com/pieces/new-core/<name>.svg`; the AI Router's is `https://cdn.activepieces.com/pieces/ai_router.png`, a PNG outside `new-core/`, so do not assume every core icon shares one folder or one format. A new core step therefore needs someone with bucket access to upload `pieces/new-core/<name>.svg` before the URL is changed — `curl -o /dev/null -w '%{http_code}'` it first, because a missing asset is a broken image that no test sees. A Vite asset import also satisfies `logoUrl` (the SSO page's Google icon does this) if the cross-team wait is not worth it. Nothing imports the local `img/piece/*.svg`; they are not the fallback.- **Rewriting a shared component silently drops whatever props it stops destructuring, and optional props make the compiler complicit.** Replacing `LockedFeatureGuard`'s body took the `RequestTrial` sales form off 17 pages at once: every caller still passed `featureKey` and `showContactSales`, the new component just never read them, and because both stayed `?:` in the props type nothing failed to compile and no call site changed in the diff. The prop a rewrite must not lose is the one to make **required** — the moment `featureKey` was, `tsc` listed exactly the call sites that had dropped it, across all three branches of the stack. When a component's props feed a business surface rather than styling, review the destructure, not the prop list.+- **With a resolver, react-hook-form in `onChange` mode re-checks only the field that changed.** It runs the whole schema but stores only that field's error, so a rule that spans fields (a header value that must be re-entered when the URL changes) shows nothing until the other field changes or the form submits. Give the triggering field `rules: { deps: ['other'] }`, or call `trigger('other')`.+- **A list-level zod issue moves between `name` and `name.root`, and the zod resolver keeps only the first issue per path.** `toNestErrors` re-homes an issue at `headers` to `headers.root` once fields like `headers.0.name` are registered (on change and submit), but not on `trigger('headers')`. Put field-array issues on row paths (`['headers', i, 'name']`); after `remove(i)` call `trigger('headers')`, because the field array does not refresh the other rows' errors.+- **`z.url(msg).min(1, required)` never shows `required`.** zod 4 runs the URL format check first and the resolver keeps the first issue. Write `z.string().min(1, required).pipe(z.url(msg))`.+- **The global `MutationCache.onError` toast stays quiet only when `onError` is set in the `useMutation` options.** An `onError` passed to `mutate()` is a per-call callback; the cache still sees a mutation without one and shows "Something went wrong".+- **A TanStack DB query collection on a private `QueryClient` must mount that client, or it never refetches on focus or reconnect.** Only `QueryClientProvider` calls `mount()`, and only for the app's client. Without it a retry that pauses on a hidden tab also never resumes. `event-destinations-collection.ts` mounts and unmounts its client in the live hook's effect; the call is reference-counted.diff --git a/brain/knowledge/eventing-webhooks/event-destinations.md b/brain/knowledge/eventing-webhooks/event-destinations.mdindex 5a11044945c..468c5a1c131 100644--- a/brain/knowledge/eventing-webhooks/event-destinations.md+++ b/brain/knowledge/eventing-webhooks/event-destinations.md@@ -4,10 +4,10 @@ icon: 📡# Event Destinations-Streams platform/project activity events to webhook URLs in real time. Internal Activepieces flow webhooks are valid targets, so operators can route events into a flow and fan out to Slack/Gmail/Teams/HTTP without leaving the platform. EE/Cloud only, gated by `eventStreamingEnabled` on both the API (402 preHandler) and delivery (`eventDestinationHooks`). Lives on the **Security** admin page as the `events` tab (`/platform/security?tab=events`).+Streams platform/project activity events to webhook URLs in real time. Internal Activepieces flow webhooks are valid targets, so operators can route events into a flow and fan out to Slack/Gmail/Teams/HTTP without leaving the platform. EE/Cloud only, gated by `eventStreamingEnabled` on both the API (402 preHandler) and delivery (`eventDestinationHooks`). Lives in platform admin at `/platform/audit-log/streaming` (Event Streaming), with the setup page at `/new` and `/:id`.### Entities & services-- **EventDestination**: one URL receiving a chosen subset of the 27 `ApplicationEventName` events, at PLATFORM or PROJECT scope.+- **EventDestination**: one URL receiving a chosen subset of the `ApplicationEventName` events, at PLATFORM or PROJECT scope.- **Scope**: PLATFORM (all platform events) or PROJECT (currently only `FLOW_RUN_FINISHED`).- **Format**: how a destination encodes each event on the wire — `RAW` (the event JSON, the default and what every pre-format destination sends), `OTLP_JSON`, or `OTLP_PROTOBUF` (an OTLP/HTTP logs `ExportLogsServiceRequest`, built by `otlpLogs` in `@activepieces/server-utils` on top of evlog's `toOTLPLogRecord`).- Delivery via BullMQ queue (`WorkerJobType.EVENT_DESTINATION`).@@ -25,10 +25,15 @@ Streams platform/project activity events to webhook URLs in real time. Internal- **An update is a partial patch: an omitted field keeps its stored value.** `url` and `events` are optional on `POST /:id` and `PATCH /:id`, like `enabled`, `format` and `headers`, so the listing's Enabled switch sends only `{ enabled }`. It used to send the whole cached row, and a stale row wrote back an old URL and events plus `headers: null`, which deleted a header added in another tab without an error. Both checks run on the resolved URL (`url ?? stored.url`, read under the row lock), never on `rest.url`: compare `rest.url` and every toggle on a destination with headers answers the rebinding 400 (`undefined !== stored.url`), while a `format`-only switch to `OTLP_PROTOBUF` on a webhook URL slips through (`new URL(undefined)` reads as "not a webhook"). `headers: null` still means "clear all", so a client that echoes a cached row's headers deletes values it never saw. An unreadable stored map counts as no headers: a toggle leaves it alone, and a save that sends `headers` replaces it.- **The delivery owns the framing headers.** `Content-Type`, `Content-Length`, `Content-Encoding`, `Transfer-Encoding`, `Host` and `Connection` are refused as custom header names in any letter case (`formErrors.reservedHeaderName`), and so are two names that differ only in case (`formErrors.duplicateHeaderName`). The format decides the body encoding, so a custom `Content-Type` could only mislabel it. Every send path also spreads the custom headers first and sets its own content type last.- **An internal handler flow gets the custom headers, with lowercase names, exactly as an HTTP delivery would.** A handler flow whose Catch Webhook trigger uses HEADER or BASIC auth reads `payload.headers`, and the same flow reached through the embed-domain URL already gets them over HTTP. The consequence: the values enter the webhook job and the flow run's trigger output, which project members can read, the same as any HTTP request to that webhook. `POST /test` forwards the typed headers the same way.-- **An OTLP destination URL is used exactly as pasted.** The OTLP spec says a signal-specific endpoint "MUST be used as-is", and vendor paths differ (`/v1/logs`, Loki `/otlp/v1/logs`, PostHog `/i/v1/logs`), so nothing appends `/v1/logs`.+- **An OTLP destination URL is used exactly as pasted.** The OTLP spec says a signal-specific endpoint "MUST be used as-is", and vendor paths differ (`/v1/logs`, Loki `/otlp/v1/logs`, PostHog `/i/v1/logs`), so nothing appends `/v1/logs`. The Connection step only warns when the path does not end in `/logs`.+- **Datadog, Dynatrace, and Elastic document protobuf only** for OTLP logs, so `OTLP_PROTOBUF` is the default when an admin picks OpenTelemetry. Datadog's AI assistant claims `http/json` works, but its source page is about the Datadog SDKs exporting to a local Agent, not the agentless `otlp.<site>` intake.- **The worker encodes protobuf, not the API**, because BullMQ stores job data as JSON and raw bytes do not survive the queue. The queued payload is always the OTLP/JSON object; `contentType: 'application/x-protobuf'` on the job tells the worker to encode it. A job without `contentType` posts JSON, which is exactly the pre-format job shape.- **The API refuses `OTLP_PROTOBUF` for any webhook URL** (400, `EVENT_DESTINATION_FORMAT_NOT_SUPPORTED_BY_WEBHOOK`), on create, on update and on `POST /test`, so a test cannot pass where delivery would fail. The webhook routes have no protobuf parser, so an HTTP POST of protobuf gets a 415, and the internal dispatch would hand the flow JSON anyway. The check uses `extractWebhookFlowIdCandidate`, host-agnostic like the cycle guard, so an embed-host URL is refused too. `OTLP_JSON` stays allowed: both paths deliver it as JSON.- **The worker calls `resolveEventDestinationHeaders` only for a job with `hasHeaders: true`.** A destination with no stored headers (every pre-format destination) posts exactly as before, with no RPC to the API and no new way to fail.+- **A handler flow expects `RAW`.** Generate handler flow sets the format to `RAW`, because the generated router branches read `body.action`. A handler flow on `OTLP_JSON` gets the OTLP/JSON object, and its routes will not match; the OpenTelemetry step warns about this. `OTLP_PROTOBUF` never reaches a webhook URL: the API refuses it, and the OpenTelemetry step disables Protobuf and switches to JSON when the pasted URL is a flow webhook (`destinationFormUtils.isWebhookUrl`, the same host-agnostic path match as the server). It switches back to Protobuf only after its own automatic switch (`destinationFormUtils.resolveOtlpFormat`), so a JSON choice the admin made stays.+- **The form's header rows are a react-hook-form field array of `{ name, value }`, never a record.** They become a record only in `toHeaderRequest` / `toTestHeaders`. A blank value means "keep the stored value" only when the row's name matches a stored name in any letter case, the server's own rule; every issue goes on `headers.<i>.name` or `.value`, and the URL field carries `rules.deps: ['headers']` so the re-entry message shows the moment the URL changes. The old `DictionaryInput` folded rows into a record (last key wins): exact duplicates merged silently, and a new value next to a blank copy of a saved header sent `null` and kept the OLD secret.+- **The listing's Enabled switch sends only `{ enabled }`.** The collection's `onUpdate` posts `mutation.changes`, never the cached row, and the edit page refetches before it fills the form (`useFreshDestination`, comparing the query's update counters). The collection's private `QueryClient` is mounted while the live hook runs, so focus and reconnect refetch; nothing else would. It sets `retry: false`: with the default three retries a failed first load held the skeleton for about seven seconds before the error state and its Retry button.+- **The test card shows a result only while the form still matches the request that produced it** (`isSameTestRequest` against the mutation's `variables`), and its mutation sets `onError` in the `useMutation` options so a 400 shows in the card instead of the global "Something went wrong" toast.- **The OTLP attribute keys are a customer contract.** Envelope fields keep their RAW names, and `data` is flattened to dotted keys (`data.flowRun.status`); the body is the raw event JSON, not evlog's wide event. `packages/server/utils/test/otlp-logs.test.ts` pins the whole request, so an evlog upgrade that changes `toOTLPLogRecord` fails a test instead of silently changing every customer's dashboards.- The old `assertUrlIsExternal` check was **removed** to support internal handler flows; recursion is instead prevented by a server-side **cycle guard** keyed on the target flow of any webhook URL, regardless of route suffix (so a self-targeting `/draft` destination is still dropped on its own run events).- **The cycle guard is host-agnostic on purpose — do not "tighten" it back to an origin check.** It matches any destination whose path contains `/v1/webhooks/<flowId>`, percent-decoding the id segment. It used to require `destination.origin === getPublicApiUrl().origin`, which is `AP_FRONTEND_URL`: platforms with an embed subdomain get `WEBHOOK_URL_PREFIX` rewritten to `https://<embed-hostname>/api/v1/webhooks`, so the origin never matched, the guard failed open, and a handler flow re-triggered on its own runs — one webhook POST produced 838 runs in ~3 min (GIT-1641, Pylon 5378). `domainHelper.getPublicApiUrl()` is called with no `platformId` here, so it can never resolve to the embed host. The path is the stable part (`/v1/webhooks` is fixed by the route registration and every URL builder); the host is not.@@ -47,7 +52,7 @@ Entry point: `eventDestinationService`, a log-scoped factory wired up in `platfo- `packages/server/utils/src/` — `otlpLogs`, the OTLP/JSON builder and the inline protobuf descriptor (field numbers from `opentelemetry-proto` v1.11.0)- `packages/core/shared/src/lib/ee/event-destinations/` — request/response zod schemas and barrel export- `packages/core/shared/src/lib/ee/audit-events/` — the `ApplicationEventName` enum plus `buildMockEvent()` for test deliveries-- `packages/web/src/app/routes/platform/infra/event-destinations/` — the page, its TanStack DB collection, handler-flow builder, and dialog/row/action components+- `packages/web/src/app/routes/platform/infra/event-destinations/` — the listing tab, the three-step destination form (Destination, Events, Connection), its TanStack DB collection, and the handler-flow builder- `packages/server/api/test/integration/cloud/event-destinations/` — integration tests covering CRUD and trigger dispatchPaths verified 2026-09-23.diff --git a/docs/admin-guide/guides/event-streaming.mdx b/docs/admin-guide/guides/event-streaming.mdxindex 9101bcccf51..d911833f88b 100644--- a/docs/admin-guide/guides/event-streaming.mdx+++ b/docs/admin-guide/guides/event-streaming.mdx@@ -1,6 +1,6 @@---title: "Event Streaming"-description: "Forward audit events to a webhook and build fully customizable alerts on top"+description: "Stream audit events to Datadog, PostHog, Grafana Loki, or any OpenTelemetry backend, or to a webhook as raw JSON"icon: "webhook"---@@ -8,59 +8,162 @@ icon: "webhook"## Overview-Event Streaming forwards platform [audit events](/admin-guide/security/audit-logs/overview) to a webhook URL of your choice. The most common pattern is to point that webhook at a flow inside Activepieces — your flow then routes each event to the channel you care about (Slack, Gmail, Microsoft Teams, custom HTTP, etc.).+Event Streaming sends every platform [audit event](/admin-guide/security/audit-logs/overview) to a destination of your choice, as it happens. Each destination has a **format**:-Use it to react to flow run failures, new sign-ins, project releases, or any other audit event with the alerting tool of your choice.+- **OpenTelemetry (OTLP).** Each event is sent as an OpenTelemetry log record over OTLP/HTTP. This works with Datadog, PostHog, Grafana Loki, Grafana Cloud, New Relic, Honeycomb, Dynatrace, Elastic, SigNoz, Axiom, Better Stack, and any other backend that accepts OTLP logs. No collector or agent is needed in between.+- **Raw JSON.** The audit event is posted as-is to any webhook URL. Point it at a flow inside Activepieces and route each event to Slack, Gmail, Microsoft Teams, custom HTTP, and so on.++Use it to react to flow run failures, new sign-ins, project releases, or any other audit event with the tools you already use.## Quick start-The fastest way to get going is the **Generate handler flow** button in the New destination dialog. It builds a webhook-triggered flow with one router branch per event you select, plus a nested branch for failed runs when you pick `flow.run.finished`.+Creating a destination is a three-step page: **Destination**, **Events**, and **Connection**.++1. Open **Platform Admin → Security → Audit Logs → Event Streaming** and click **New Destination**.+2. **Destination** — pick **Send to an OpenTelemetry tool** or **Send to a webhook**. This choice sets the format, and you cannot change it once the destination is created.+3. **Events** — select the events to send.+4. **Connection** — paste the endpoint URL and add any headers the endpoint needs, such as an API key. For an OpenTelemetry tool, also pick the encoding. For a webhook, you can click **Generate handler flow** instead of pasting a URL, and Activepieces builds a flow to handle the events (see below). Use **Send test event** to fire a sample of any selected event.+5. Click **Create destination**.++### Generate a handler flow++Pick **Send to a webhook** on the Destination step, then click **Generate handler flow** on the Connection step. It builds a webhook-triggered flow with one router branch per event you selected, plus a nested branch for failed runs when you pick `flow.run.finished`. It fills the endpoint URL in for you. A webhook destination sends **Raw JSON**, which is the shape the generated flow routes on.-1. Open **Platform Admin → Security → Audit Logs → Event Streaming**.-2. Click **New Destination**, pick the events you want to handle, and click **Generate handler flow**.--3. The flow lands in your personal project with a webhook trigger and a router branch per selected event. Sample data is pre-baked so you can hit Test right away, you can add a router step under any event branch to check for specific projects/flows ids.-4. Customize the branches with whatever pieces you like — Slack, Gmail, Microsoft Teams, custom HTTP, and so on.-5. Publish the flow, then go back to the New destination dialog and click **Create** to save the destination.-6. Use the **Test webhook** dropdown in the dialog to fire a sample of any selected event and confirm the round-trip.-## Available events+The flow lands in your personal project with sample data pre-baked, so you can hit Test right away. Add a router step under any event branch to check for specific project or flow ids, customize the branches with whatever pieces you like, then publish the flow and save the destination.++## Formats++### OpenTelemetry++Each event becomes one OTLP log record inside an `ExportLogsServiceRequest`, posted to the endpoint URL. Pick an encoding:++- **Protobuf** (recommended) — `Content-Type: application/x-protobuf`. This is the OTLP default and works with every backend listed below. Datadog, Dynatrace, and Elastic document only this encoding.+- **JSON** — `Content-Type: application/json`, the OTLP/JSON encoding. Pick it only when your receiver accepts JSON and not protobuf.++<Warning>+Paste the **full OTLP logs URL**, including its path — for example `https://otlp.datadoghq.com/v1/logs`. Activepieces posts to the URL exactly as you enter it and does not append `/v1/logs`. The path differs between vendors: Grafana Loki uses `/otlp/v1/logs` and PostHog uses `/i/v1/logs`.+</Warning>++Every log record carries:++| OTLP field | Value |+| --- | --- |+| `resource.attributes` | `service.name` = `activepieces` |+| `scope.name` | `activepieces.event-streaming` |+| `timeUnixNano` | when the event happened (the event's `created`) |+| `eventName` | the event name, for example `flow.run.finished` |+| `severityText` / `severityNumber` | `INFO` / `9` |+| `body` | the full audit event as a JSON string — the same bytes the Raw JSON format sends |+| `attributes` | `action`, `id`, `platformId`, `projectId`, `projectDisplayName`, `userId`, `userEmail`, `ip`, plus every field of `data` as a dotted key, for example `data.flowRun.status` |++An attribute is left out when the event does not have that field. Lists inside `data` are sent as one JSON string. Because every field is an attribute, you can filter and alert on it in your backend without a parser — for example `data.flowRun.status:FAILED` in Datadog.++Here is a `flow.run.finished` event in the OTLP/JSON encoding (the body string and some attributes are shortened):++```json+{+ "resourceLogs": [{+ "resource": { "attributes": [{ "key": "service.name", "value": { "stringValue": "activepieces" } }] },+ "scopeLogs": [{+ "scope": { "name": "activepieces.event-streaming" },+ "logRecords": [{+ "timeUnixNano": "1790158542318000000",+ "severityNumber": 9,+ "severityText": "INFO",+ "eventName": "flow.run.finished",+ "body": { "stringValue": "{\"id\":\"Qz3vN8kLp2XwR7tY1mB4c\",\"action\":\"flow.run.finished\",\"data\":{...}}" },+ "attributes": [+ { "key": "action", "value": { "stringValue": "flow.run.finished" } },+ { "key": "platformId", "value": { "stringValue": "Hd8sK2mWq9LxT4vB7nP1e" } },+ { "key": "projectDisplayName", "value": { "stringValue": "Finance Ops" } },+ { "key": "data.flowRun.duration", "value": { "intValue": "5214" } },+ { "key": "data.flowRun.flowDisplayName", "value": { "stringValue": "Invoice sync" } },+ { "key": "data.flowRun.status", "value": { "stringValue": "FAILED" } }+ ]+ }]+ }]+ }]+}+```++### OpenTelemetry endpoints++| Backend | Logs endpoint | Authentication header | Encoding |+| --- | --- | --- | --- |+| Datadog | `https://otlp.<site>/v1/logs` — `<site>` is `datadoghq.com`, `us3.datadoghq.com`, `us5.datadoghq.com`, `ap1.datadoghq.com`, `ap2.datadoghq.com`, `uk1.datadoghq.com`, `datadoghq.eu`, or `ddog-gov.com` | `dd-api-key: <API key>` | Protobuf |+| Datadog Agent (7.48+) | `http://<agent-host>:4318/v1/logs` — set `DD_OTLP_CONFIG_LOGS_ENABLED=true` on the Agent | none | Protobuf |+| PostHog | `https://us.i.posthog.com/i/v1/logs` | `Authorization: Bearer <project API key>` | Protobuf or JSON |+| Grafana Loki 3.x | `http://<loki-host>/otlp/v1/logs` — needs schema v13 with structured metadata | `X-Scope-OrgID: <tenant>` when multi-tenant | Protobuf or JSON |+| Grafana Cloud | `https://otlp-gateway-prod-<region>.grafana.net/otlp/v1/logs` — copy it from your stack's OpenTelemetry tile | `Authorization: Basic <base64 of instanceId:token>` | Protobuf or JSON |+| New Relic | `https://otlp.nr-data.net/v1/logs` (EU: `https://otlp.eu01.nr-data.net/v1/logs`) | `api-key: <license key>` | Protobuf |+| Honeycomb | `https://api.honeycomb.io/v1/logs` (EU: `https://api.eu1.honeycomb.io/v1/logs`) | `x-honeycomb-team: <API key>` | Protobuf or JSON |+| Dynatrace | `https://<environment-id>.live.dynatrace.com/api/v2/otlp/v1/logs` | `Authorization: Api-Token <token>` | Protobuf |+| Elastic Cloud | the managed OTLP endpoint from the Cloud console, plus `/v1/logs` | `Authorization: ApiKey <key>` | Protobuf |+| SigNoz Cloud | `https://ingest.<region>.signoz.cloud:443/v1/logs` | `signoz-ingestion-key: <key>` | Protobuf |+| Axiom | `https://<edge-domain>/v1/logs` | `Authorization: Bearer <token>` and `x-axiom-dataset: <dataset>` | Protobuf |+| Better Stack | `https://<ingesting-host>/v1/logs` | `Authorization: Bearer <source token>` | Protobuf |++Where the table says Protobuf, pick **Protobuf**: the backend documents no JSON support. Splunk has no direct OTLP logs endpoint: run your own OpenTelemetry Collector with the Splunk HEC exporter and point the destination at the collector.++### Raw JSON++The destination receives the audit event itself as the JSON body, with `Content-Type: application/json`. This is also what every destination created before formats existed keeps sending.-You can subscribe a destination to any audit event — flow lifecycle, run status, folder/connection changes, user activity, and platform admin actions. See the [Audit Log Events catalog](/admin-guide/security/audit-logs/overview#event-catalog) for the full list and per-event payload details.+- `action` — the event name (for example `flow.run.finished`).+- `data` — event-specific payload, including details like the flow id, run id, status, or affected user.+- `id`, `created`, `updated` — event identifiers and timestamps.+- `platformId`, `projectId` — context fields present on every event.+- `userId`, `userEmail`, `ip` — who did it and from where. These are filled in for events that come from a user request. The four `flow.run.*` events are emitted by a worker rather than a request, so they carry none of them.-## Use your own webhook URL+A handler flow on this instance gets the JSON of its destination's format: the raw event for Raw JSON, and the OTLP/JSON request for the OpenTelemetry JSON encoding. A flow webhook accepts only JSON, so a destination that points at one cannot use the Protobuf encoding: the setup page switches it to JSON (and back to Protobuf if you then enter a URL that is not a flow webhook, unless you picked JSON yourself), and the API rejects Protobuf for a flow webhook URL with a `400`.-If you already have a webhook URL — or you want to point Event Streaming at a SIEM, data warehouse, or any other external system — you can skip the handler flow and configure the destination by hand:+## Headers-1. Go to **Platform Admin → Security → Audit Logs → Event Streaming**.-2. Click **New Destination**.-3. Select the **Events** you want to forward.-4. Paste your **Webhook URL** (must be a valid HTTPS endpoint).-5. Use the **Test webhook** dropdown to fire a sample payload for any selected event.-6. Click **Create** to save.+Add any headers the endpoint requires — an `Authorization` bearer token, a `dd-api-key`, an `X-Scope-OrgID`, and so on. The delivery sets `Content-Type` from the format, and it also owns `Content-Length`, `Content-Encoding`, `Transfer-Encoding`, `Host`, and `Connection`, so none of these can be added as a custom header. A header name may appear only once, whatever its letter case.-## Payload shape+A handler flow on this instance receives the custom headers too, with lowercase names, exactly as an HTTP request to its webhook would. A Catch Webhook trigger that uses header or basic authentication can check them.-Every event is delivered as an HTTP POST with a JSON body. The top-level fields are:+Header values are **encrypted at rest and write-only**. When you reopen a destination, saved keys are listed with an empty value and the placeholder *Hidden — type to replace*:-- `action` — the event name (for example `flow.run.finished`).-- `data` — event-specific payload, including details like the flow id, run id, status, or affected user.-- `id`, `created`, `updated` — event identifiers and timestamps.-- `platformId`, `projectId`, `userId` — context fields shared across all events.+- Leave a value empty to keep the stored value.+- Type a new value to replace it.+- Delete the whole row to remove the header.++Values are masked as you type; select the eye icon to show one.++The API behaves the same way: `GET` returns each header key with a `null` value, and sending `null` for a key on update keeps whatever is stored.++A stored value is bound to the URL it was saved against. **If you change the URL, you must re-enter every header value in the same save** — as soon as you change the URL, the form asks for a new value on each saved header you have not retyped, and the API answers `400` if an update changes the URL while keeping a stored value. This is what makes "write-only" true: without it, anyone who can edit a destination could point it at their own endpoint and have the next audit event deliver the secret for them.++## Test, enable, and disable++**Send test event** on the Connection step builds a sample of the event you choose and delivers it in the selected format. It reports the HTTP status code, the round-trip time, and the body that was sent, so you can confirm the shape before you save. For the Protobuf encoding the body is shown in its OTLP/JSON form, since protobuf bytes are not readable.++A test never reads a stored header value. It sends only the values typed into the form, so on a saved destination you must retype a secret to test with it. The button stays disabled, with a note, while any header value is blank or a header has an error. If the API refuses the test request itself, the card shows the reason. A result stays on screen only while the URL, headers, encoding, and event still match what was sent.++Each destination has an **Enabled** switch on the listing page. A disabled destination keeps its configuration but receives nothing. The switch changes only that setting; if the change fails, it flips back and a message shows the reason.++## Available events++You can subscribe a destination to any audit event — flow lifecycle, run status, folder/connection changes, user activity, and platform admin actions. See the [Audit Log Events catalog](/admin-guide/security/audit-logs/overview#event-catalog) for the full list and per-event payload details.## Requirements-- **Enterprise Edition**: Event Streaming requires an enterprise plan with Audit Logs enabled.+- **Enterprise Edition**: Event Streaming requires a plan with Event Streaming enabled. Without it, no events are delivered.- **Platform admin**: only platform admins can configure destinations.-- **HTTPS endpoint**: webhook URLs must use HTTPS.+- **HTTPS endpoint**: use HTTPS for any external endpoint. Audit events carry user emails and IP addresses, and Activepieces does not reject an `http://` URL for you.- **Publicly accessible**: external endpoints must be reachable from your Activepieces server. Handler flows on this same instance are delivered internally, so they work even when the instance is not publicly reachable (for example, behind an internal load balancer).## Troubleshooting-- **Events not received**: for external endpoints, verify they are reachable from your server and return 2xx status codes. For a handler flow on this instance, make sure the flow is published and enabled.-- **Test fails**: check that your URL is valid and uses HTTPS.+- **Events not received**: check the destination is enabled. For external endpoints, verify they are reachable from your server and return 2xx status codes. For a handler flow on this instance, make sure the flow is published and enabled.+- **`404` from an OpenTelemetry backend**: the URL is missing the logs path. Paste the full logs URL from the table above, not the base URL.+- **`415` or a decode error from an OpenTelemetry backend**: the backend does not accept the selected encoding. Switch the encoding to **Protobuf**.+- **Test fails**: check that your URL is valid and uses HTTPS. The test reports the status code returned by the endpoint, which usually names the problem.- **Missing events**: make sure the event type is selected in your destination configuration.+- **A field is missing**: the field is not on that event. The four `flow.run.*` events carry no `userId`, `userEmail`, or `ip`, because a worker emits them rather than a user request.## See alsodiff --git a/packages/web/public/locales/en/translation.json b/packages/web/public/locales/en/translation.jsonindex c13640bc268..cd9d0025d29 100644--- a/packages/web/public/locales/en/translation.json+++ b/packages/web/public/locales/en/translation.json@@ -125,7 +125,6 @@"Ran from": "Ran from","A flow step": "A flow step","Agent ran an action": "Agent ran an action",- "Fires when an agent runs a configured action that is not a read.": "Fires when an agent runs a configured action that is not a read.","Agents need an AI provider": "Agents need an AI provider","Add a provider once, then I can build agents from a sentence.": "Add a provider once, then I can build agents from a sentence.","agentStillUsedNamed": "{count, plural, =1 {Still used by {flows}. Remove the agent from that flow first.} other {Still used by # published flows: {flows}. Remove the agent from each one first.}}",@@ -1184,14 +1183,15 @@"Global": "Global","{count, plural, =1 {1 project} other {# projects}}": "{count, plural, =1 {1 project} other {# projects}}","Delete destination": "Delete destination",- "Deleting this destination will stop all event notifications to its webhook.": "Deleting this destination will stop all event notifications to its webhook.","destination": "destination","Invalid URL": "Invalid URL",- "Webhook URL is required": "Webhook URL is required",+ "Endpoint URL is required": "Endpoint URL is required",+ "Enable {destination}": "Enable {destination}",+ "Re-enter every saved header value to change the URL. If someone else changed this destination, reload the page first.": "Re-enter every saved header value to change the URL. If someone else changed this destination, reload the page first.",+ "A flow webhook accepts only JSON. Choose the JSON encoding, or send to a webhook instead.": "A flow webhook accepts only JSON. Choose the JSON encoding, or send to a webhook instead.","Select at least one event": "Select at least one event","Destination created successfully": "Destination created successfully","Destination updated successfully": "Destination updated successfully",- "Failed to generate the handler flow. Please try again.": "Failed to generate the handler flow. Please try again.","Webhook URL prefix is not configured.": "Webhook URL prefix is not configured.","Event handler starter": "Event handler starter","Routes audit events into branches you can wire to Slack, Gmail, Teams, or any HTTP endpoint.": "Routes audit events into branches you can wire to Slack, Gmail, Teams, or any HTTP endpoint.",@@ -1201,31 +1201,22 @@"Failed run": "Failed run","**Audit event handler**\n\nThis flow runs whenever any of these events fire:\n\n{events}\n\n**Add your channel** (Slack, Gmail, Teams, HTTP…) inside each branch below.\n\nOnce you are done:\n\n1. **Publish this flow** so it can receive events.\n2. Head back to the **Event Streaming** tab and create the destination to start sending events here.": "**Audit event handler**\n\nThis flow runs whenever any of these events fire:\n\n{events}\n\n**Add your channel** (Slack, Gmail, Teams, HTTP…) inside each branch below.\n\nOnce you are done:\n\n1. **Publish this flow** so it can receive events.\n2. Head back to the **Event Streaming** tab and create the destination to start sending events here.","**Test different scenarios**\n\nOpen the trigger and edit its **Sample Data** to swap in a different event payload and test each branch without firing real audit events.": "**Test different scenarios**\n\nOpen the trigger and edit its **Sample Data** to swap in a different event payload and test each branch without firing real audit events.",- "Edit Destination": "Edit Destination","New Destination": "New Destination","Update the webhook endpoint and event subscriptions.": "Update the webhook endpoint and event subscriptions.","Send audit events to a webhook. Use an internal flow to route them to your notification channels — Slack, Gmail, Microsoft Teams, or any other channel.": "Send audit events to a webhook. Use an internal flow to route them to your notification channels — Slack, Gmail, Microsoft Teams, or any other channel.","Events": "Events",- "Webhook URL": "Webhook URL",- "Or generate an internal flow to handle the selected events:": "Or generate an internal flow to handle the selected events:","Generate handler flow": "Generate handler flow",- "Don't forget to publish your flow before creating the alert.": "Don't forget to publish your flow before creating the alert.",- "Test webhook": "Test webhook",- "Create alert": "Create alert","Destination (flow {flowId})": "Destination (flow {flowId})",- "Internal Flow": "Internal Flow",- "External": "External","Created": "Created",- "View flow": "View flow","Unlock Event Streaming": "Unlock Event Streaming",- "Forward every audit event we emit to a webhook, then handle it in a flow — wire it to Slack, Gmail, PagerDuty, or anywhere else.": "Forward every audit event we emit to a webhook, then handle it in a flow — wire it to Slack, Gmail, PagerDuty, or anywhere else.",- "Send a webhook for every audit event and build fully customizable alerts on top.": "Send a webhook for every audit event and build fully customizable alerts on top.","No destinations yet. Create one to get started.": "No destinations yet. Create one to get started.","You need a personal project to generate the handler flow.": "You need a personal project to generate the handler flow.","Flow import returned no flow.": "Flow import returned no flow.",+ "Agent created": "Agent created",+ "Agent updated": "Agent updated",+ "Agent taken offline": "Agent taken offline","Flow run started": "Flow run started","Flow run finished": "Flow run finished",- "Fires for every finished run — successful and failed.": "Fires for every finished run — successful and failed.","Flow run resumed": "Flow run resumed","Flow run retried": "Flow run retried","Flow created": "Flow created",@@ -1570,6 +1561,10 @@"Custom Headers": "Custom Headers","Header name": "Header name","Header value": "Header value",+ "Add header": "Add header",+ "Enter a header name": "Enter a header name",+ "Enter a value for this header": "Enter a value for this header",+ "Re-enter this value to change the URL": "Re-enter this value to change the URL","Models Configuration": "Models Configuration","This provider does not support listing models via API, please add models manually.": "This provider does not support listing models via API, please add models manually.","Image Model": "Image Model",@@ -2957,6 +2952,8 @@"The complete JSON key file for a service account with the Vertex AI User role.": "The complete JSON key file for a service account with the Vertex AI User role.","Connect a Google Cloud service account to call Vertex AI models inside your own GCP project.\n\n1. Open the [Google Cloud Console](https://console.cloud.google.com) and select the project you want to bill.\n2. Enable the **Vertex AI API** under *APIs & Services > Enabled APIs*.\n3. Go to **IAM & Admin > Service Accounts** and create a service account, granting it the **Vertex AI User** role. Avoid broader roles — follow least-privilege so a leaked key has limited blast radius.\n4. Open the service account, go to **Keys > Add Key > Create new key**, choose **JSON**, and download it.\n5. Paste the entire contents of that JSON file below, then set the project ID and the region your models are served from.\n6. Add the model ids you want to expose — Vertex model availability depends on your project, region and Model Garden access, so we cannot list them for you.": "Connect a Google Cloud service account to call Vertex AI models inside your own GCP project.\n\n1. Open the [Google Cloud Console](https://console.cloud.google.com) and select the project you want to bill.\n2. Enable the **Vertex AI API** under *APIs & Services > Enabled APIs*.\n3. Go to **IAM & Admin > Service Accounts** and create a service account, granting it the **Vertex AI User** role. Avoid broader roles — follow least-privilege so a leaked key has limited blast radius.\n4. Open the service account, go to **Keys > Add Key > Create new key**, choose **JSON**, and download it.\n5. Paste the entire contents of that JSON file below, then set the project ID and the region your models are served from.\n6. Add the model ids you want to expose — Vertex model availability depends on your project, region and Model Garden access, so we cannot list them for you.","invalidGcpResourceId": "Use lowercase letters, numbers and hyphens only",+ "Retype your header values to send a test. Saved values are never sent back.": "Retype your header values to send a test. Saved values are never sent back.",+ "Fix the header errors above to send a test.": "Fix the header errors above to send a test.","invalidHeaderName": "A header name may only contain letters, numbers and the characters ! # $ % & ' * + - . ^ _ ` | ~","reservedHeaderName": "Content-Type, Content-Length, Content-Encoding, Transfer-Encoding, Host and Connection are set by the delivery and cannot be added as custom headers","duplicateHeaderName": "A header name may appear only once, whatever its letter case",@@ -3196,6 +3193,75 @@"Control which built-in tools are available to agents via this MCP server.": "Control which built-in tools are available to agents via this MCP server.","Every piece you can use, in every project MCP reaches.": "Every piece you can use, in every project MCP reaches.","{count} pieces, ready to run in every project MCP reaches.": "{count} pieces, ready to run in every project MCP reaches.",+ "Create destination": "Create destination",+ "Edit destination": "Edit destination",+ "Endpoint URL": "Endpoint URL",+ "Header values are encrypted": "Header values are encrypted",+ "Hidden — type to replace": "Hidden — type to replace",+ "New destination": "New destination",+ "Search events": "Search events",+ "Select matching": "Select matching",+ "Clear matching": "Clear matching",+ "Send test event": "Send test event",+ "{duration} ms": "{duration} ms",+ "{selected} of {total} events selected": "{selected} of {total} events selected",+ "{selected} of {total} selected": "{selected} of {total} selected",+ "All {total}": "All {total}",+ "Destination": "Destination",+ "No destinations yet": "No destinations yet",+ "destinations": "destinations",+ "{count} of {total}": "{count} of {total}",+ "destinationsCount": "{count, plural, =1 {1 destination} other {# destinations}}",+ "Please fix the highlighted fields before saving": "Please fix the highlighted fields before saving",+ "Encoding": "Encoding",+ "Format": "Format",+ "OpenTelemetry": "OpenTelemetry",+ "Stream every audit event in OpenTelemetry (OTLP) format to Datadog, PostHog, Grafana Loki, or any OTLP backend. Or send it as raw JSON to a webhook or a handler flow.": "Stream every audit event in OpenTelemetry (OTLP) format to Datadog, PostHog, Grafana Loki, or any OTLP backend. Or send it as raw JSON to a webhook or a handler flow.",+ "This URL does not end in /logs. An OTLP receiver expects the full logs URL.": "This URL does not end in /logs. An OTLP receiver expects the full logs URL.",+ "This URL is a flow webhook, which accepts only JSON, so Protobuf is off. A generated handler flow reads Raw JSON: to use one, send to a webhook instead.": "This URL is a flow webhook, which accepts only JSON, so Protobuf is off. A generated handler flow reads Raw JSON: to use one, send to a webhook instead.",+ "Where should events go?": "Where should events go?",+ "This decides the format. You can't change it later.": "This decides the format. You can't change it later.",+ "Send to an OpenTelemetry tool": "Send to an OpenTelemetry tool",+ "OpenTelemetry tool": "OpenTelemetry tool",+ "Datadog, Grafana, Honeycomb, New Relic, or any OTLP backend. Sent as OTLP log records.": "Datadog, Grafana, Honeycomb, New Relic, or any OTLP backend. Sent as OTLP log records.",+ "Format · OTLP": "Format · OTLP",+ "Send to a webhook": "Send to a webhook",+ "Webhook": "Webhook",+ "Any endpoint that accepts JSON. Paste your own URL, or generate a handler flow to route events to Slack, Gmail, or any app.": "Any endpoint that accepts JSON. Paste your own URL, or generate a handler flow to route events to Slack, Gmail, or any app.",+ "Format · Raw JSON": "Format · Raw JSON",+ "Step {current} of {total}": "Step {current} of {total}",+ "{selected}/{total}": "{selected}/{total}",+ "No events match your search": "No events match your search",+ "Paste your tool's full OTLP logs URL.": "Paste your tool's full OTLP logs URL.",+ "Check your tool's docs if you're not sure.": "Check your tool's docs if you're not sure.",+ "Protobuf": "Protobuf",+ "After you save, a value can be replaced but not read back.": "After you save, a value can be replaced but not read back.",+ "Choose an event": "Choose an event",+ "Body sent": "Body sent",+ "Sends one of your selected events to the endpoint above. Shown as JSON; Protobuf sends the same content as binary.": "Sends one of your selected events to the endpoint above. Shown as JSON; Protobuf sends the same content as binary.",+ "Sends one of your selected events to the endpoint above.": "Sends one of your selected events to the endpoint above.",+ "Publish the flow before you create the destination": "Publish the flow before you create the destination",+ "Keep this flow published so it receives events": "Keep this flow published so it receives events",+ "The flow receives each selected event as a plain JSON object.": "The flow receives each selected event as a plain JSON object.",+ "Sends a sample to the handler flow, which runs it like any other event. Publish the flow first, or the test answers 404.": "Sends a sample to the handler flow, which runs it like any other event. Publish the flow first, or the test answers 404.",+ "This URL points to a private or internal address, so the test was not sent.": "This URL points to a private or internal address, so the test was not sent.",+ "This URL points to a private or internal address, so the test was not sent. To allow it, add the address to AP_SSRF_ALLOW_LIST on the server and restart the server.": "This URL points to a private or internal address, so the test was not sent. To allow it, add the address to AP_SSRF_ALLOW_LIST on the server and restart the server.",+ "The destination did not answer in time.": "The destination did not answer in time.",+ "The secure connection failed. Check the TLS certificate of the destination.": "The secure connection failed. Check the TLS certificate of the destination.",+ "Could not connect to the destination. Check the URL.": "Could not connect to the destination. Check the URL.",+ "The handler flow could not take the event.": "The handler flow could not take the event.",+ "Use your own webhook URL": "Use your own webhook URL",+ "Any endpoint that accepts a JSON POST. Headers and a test send appear after you paste a URL.": "Any endpoint that accepts a JSON POST. Headers and a test send appear after you paste a URL.",+ "Create a handler flow": "Create a handler flow",+ "We'll create a flow with a webhook trigger, loaded with sample data for {count, plural, =1 {the event} other {the # events}} you picked. Add steps for Slack, Gmail, or any app.": "We'll create a flow with a webhook trigger, loaded with sample data for {count, plural, =1 {the event} other {the # events}} you picked. Add steps for Slack, Gmail, or any app.",+ "Handler flow": "Handler flow",+ "Open flow": "Open flow",+ "Events will stop being sent to this destination.": "Events will stop being sent to this destination.",+ "Stream every audit event on your platform over OpenTelemetry (OTLP), or send it to a flow.": "Stream every audit event on your platform over OpenTelemetry (OTLP), or send it to a flow.",+ "Paste your tool's OTLP logs URL. Each event arrives as a log record.": "Paste your tool's OTLP logs URL. Each event arrives as a log record.",+ "Handle events in a flow": "Handle events in a flow",+ "Generate a webhook flow that routes each event to Slack, Gmail, or any app.": "Generate a webhook flow that routes each event to Slack, Gmail, or any app.",+ "{first}, {second}, and {count} more": "{first}, {second}, and {count} more","Reset {name}": "Reset {name}","Chat goes back to using {provider}.": "Chat goes back to using {provider}.","The assistant can't do this yet": "The assistant can't do this yet",diff --git a/packages/web/src/app/components/centered-page.tsx b/packages/web/src/app/components/centered-page.tsxindex 804112b2bde..5c649aaa228 100644--- a/packages/web/src/app/components/centered-page.tsx+++ b/packages/web/src/app/components/centered-page.tsx@@ -11,6 +11,7 @@ export const CenteredPage = ({description,actions,footer,+ breadcrumb,children,widthClassName = 'max-w-[40rem]',showHeaderSeparator = true,@@ -20,14 +21,16 @@ export const CenteredPage = ({description?: React.ReactNode;actions?: React.ReactNode;footer?: React.ReactNode;+ breadcrumb?: React.ReactNode;children: React.ReactNode;widthClassName?: string;showHeaderSeparator?: boolean;className?: string;}) => {const header =- title === undefined && !description && !actions ? null : (+ title === undefined && !description && !actions && !breadcrumb ? null : (<>+ {breadcrumb && <div className="pb-3">{breadcrumb}</div>}<divclassName={cn('flex items-start justify-between gap-4',diff --git a/packages/web/src/app/routes/platform-routes.tsx b/packages/web/src/app/routes/platform-routes.tsxindex fbe30678efe..5b9b93803a4 100644--- a/packages/web/src/app/routes/platform-routes.tsx+++ b/packages/web/src/app/routes/platform-routes.tsx@@ -9,7 +9,10 @@ import { PlatformLayout } from '../components/platform-layout';import { LegacyPathRedirect } from './platform/legacy-path-redirect';import { LegacyTabRedirect } from './platform/legacy-tab-redirect';-import { PlanFeatureSample } from './platform/plan-feature-sample';+import {+ PlanFeatureGuard,+ PlanFeatureSample,+} from './platform/plan-feature-sample';import { useAdminControlClicks } from './platform/use-admin-control-clicks';import { useAdminPageViewed } from './platform/use-admin-page-viewed';@@ -22,6 +25,9 @@ const SettingsUsage = React.lazy(() =>const EventDestinationsPage = React.lazy(() => import('./platform/infra/event-destinations'),);+const EventDestinationFormPage = React.lazy(+ () => import('./platform/infra/event-destinations/destination-form'),+);const SettingsHealthPage = React.lazy(() => import('./platform/infra/health'));const PlatformConfigurationsPage = React.lazy(() =>import('./platform/infra/configurations').then((m) => ({@@ -543,6 +549,23 @@ export const platformRoutes = [</PlatformLayout>),},+ ...[+ { path: '/platform/audit-log/streaming/new', title: 'New Destination' },+ { path: '/platform/audit-log/streaming/:id', title: 'Edit Destination' },+ ].map(({ path, title }) => ({+ path,+ element: (+ <PlatformLayout>+ <PageTitle title={title}>+ <PlanFeatureGuard feature="eventStreaming">+ <SuspenseWrapper>+ <EventDestinationFormPage />+ </SuspenseWrapper>+ </PlanFeatureGuard>+ </PageTitle>+ </PlatformLayout>+ ),+ })),...['/platform/setup/*','/platform/security/*',diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/components/destination-kind-card.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/components/destination-kind-card.tsxnew file mode 100644index 00000000000..5d7cc32cd90--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/components/destination-kind-card.tsx@@ -0,0 +1,43 @@+import { Badge } from '@/components/ui/badge';+import { cn } from '@/lib/utils';++import type { DestinationKindOption } from '../lib/destination-kinds';++export const DestinationKindCard = ({+ option,+ isSelected,+ trailing,+}: {+ option: DestinationKindOption;+ isSelected: boolean;+ trailing?: React.ReactNode;+}) => {+ const Icon = option.icon;+ return (+ <span className="flex gap-3 text-left">+ <span+ className={cn(+ 'flex size-8 shrink-0 items-center justify-center rounded-md',+ isSelected ? 'bg-accent-3 text-accent-11' : 'bg-gray-3',+ )}+ >+ <Icon className="size-4" />+ </span>+ <span className="flex min-w-0 flex-1 flex-col gap-2">+ <span className="flex items-center justify-between gap-2">+ <span className="text-sm font-medium">{option.title}</span>+ {trailing}+ </span>+ <span className="text-sm font-normal leading-normal text-gray-11">+ {option.description}+ </span>+ <Badge+ variant="outline"+ className="rounded-md font-normal text-gray-11"+ >+ {option.formatLabel}+ </Badge>+ </span>+ </span>+ );+};diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/components/destination-start-cards.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/components/destination-start-cards.tsxnew file mode 100644index 00000000000..708c87fee12--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/components/destination-start-cards.tsx@@ -0,0 +1,85 @@+import { t } from 'i18next';+import { Activity, Workflow } from 'lucide-react';+import { Link } from 'react-router-dom';++import { AdminControl, adminControl } from '@/lib/admin-control';+import { cn } from '@/lib/utils';++import {+ DESTINATION_KIND_SEARCH_PARAM,+ DestinationKind,+} from '../lib/destination-kinds';+import { EVENT_STREAMING_PATH } from '../lib/event-streaming-path';++import { VendorLogoStack } from './vendor-logo-stack';++export const DestinationStartCards = () => {+ return (+ <div className="mb-10 mt-4 grid w-full max-w-[640px] grid-cols-1 gap-3 sm:grid-cols-2 text-left">+ <StartCard+ to={newDestinationPath('otel')}+ icon={<Activity className="size-4" />}+ isPrimary={true}+ title={t('Send to an OpenTelemetry tool')}+ description={t(+ "Paste your tool's OTLP logs URL. Each event arrives as a log record.",+ )}+ >+ <VendorLogoStack />+ </StartCard>+ <StartCard+ to={newDestinationPath('webhook')}+ icon={<Workflow className="size-4" />}+ isPrimary={false}+ title={t('Handle events in a flow')}+ description={t(+ 'Generate a webhook flow that routes each event to Slack, Gmail, or any app.',+ )}+ />+ </div>+ );+};++const StartCard = ({+ to,+ icon,+ isPrimary,+ title,+ description,+ children,+}: {+ to: string;+ icon: React.ReactNode;+ isPrimary: boolean;+ title: string;+ description: string;+ children?: React.ReactNode;+}) => {+ return (+ <Link+ {...adminControl(AdminControl.EVENT_DESTINATIONS_DESTINATION_NEW_OPEN)}+ to={to}+ className="flex gap-3 rounded-lg border p-4 transition-colors hover:bg-gray-3"+ >+ <span+ className={cn(+ 'flex size-8 shrink-0 items-center justify-center rounded-md',+ isPrimary ? 'bg-accent-3 text-accent-11' : 'bg-gray-5 text-gray-12',+ )}+ >+ {icon}+ </span>+ <div className="flex min-w-0 flex-col gap-1">+ <span className="text-sm font-medium">{title}</span>+ <span className="text-sm leading-normal text-gray-11">+ {description}+ </span>+ {children}+ </div>+ </Link>+ );+};++function newDestinationPath(kind: DestinationKind): string {+ return `${EVENT_STREAMING_PATH}/new?${DESTINATION_KIND_SEARCH_PARAM}=${kind}`;+}diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-actions.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-actions.tsxindex 0ac34aa78ee..b96165f51ef 100644--- a/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-actions.tsx+++ b/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-actions.tsx@@ -2,6 +2,7 @@ import { EventDestination } from '@activepieces/shared';import { t } from 'i18next';import { MoreVertical, Pencil, Trash } from 'lucide-react';import { useState } from 'react';+import { Link } from 'react-router-dom';import { toast } from 'sonner';import { ConfirmationDeleteDialog } from '@/components/custom/delete-dialog';@@ -17,8 +18,7 @@ import { AdminControl, adminControl } from '@/lib/admin-control';import { api } from '@/lib/api';import { eventDestinationsCollectionUtils } from '../lib/event-destinations-collection';--import { EventDestinationDialog } from './event-destination-dialog';+import { EVENT_STREAMING_PATH } from '../lib/event-streaming-path';const EventDestinationActions = ({destination,@@ -28,52 +28,51 @@ const EventDestinationActions = ({const [dropdownOpen, setDropdownOpen] = useState(false);return (- <div className="flex justify-end">+ <div className="flex justify-end" onClick={(e) => e.stopPropagation()}><DropdownMenumodal={true}open={dropdownOpen}onOpenChange={setDropdownOpen}><DropdownMenuTrigger asChild>- <Button variant="ghost" className="h-8 w-8 p-0">+ <Button+ variant="ghost"+ className="h-8 w-8 p-0"+ aria-label={t('Open menu')}+ ><MoreVertical className="h-4 w-4" /></Button></DropdownMenuTrigger><DropdownMenuContent>- <EventDestinationDialog destination={destination}>- <DropdownMenuItem- {...adminControl(- AdminControl.EVENT_DESTINATIONS_DESTINATION_EDIT_OPEN,- )}- onSelect={(e) => {- e.preventDefault();- }}- >+ <DropdownMenuItem+ {...adminControl(+ AdminControl.EVENT_DESTINATIONS_DESTINATION_EDIT_OPEN,+ )}+ asChild+ >+ <Link to={`${EVENT_STREAMING_PATH}/${destination.id}`}><Pencil className="h-4 w-4 mr-2" />{t('Edit')}- </DropdownMenuItem>- </EventDestinationDialog>+ </Link>+ </DropdownMenuItem><ConfirmationDeleteDialogtitle={t('Delete destination')}- message={t(- 'Deleting this destination will stop all event notifications to its webhook.',- )}+ message={t('Events will stop being sent to this destination.')}entityName={t('destination')}buttonText={t('Delete')}showToast- mutationFn={async () => {- await eventDestinationsCollectionUtils.delete([destination.id])- .isPersisted.promise;- }}- onError={(error) => {+ mutationFn={() =>+ eventDestinationsCollectionUtils.delete([destination.id])+ }+ onError={(error) =>toast.error(t('Error'), {description: api.extractServerErrorMessage(error,INTERNAL_ERROR_MESSAGE,),- });- }}+ })+ }isDangercontrolId={AdminControl.EVENT_DESTINATIONS_DESTINATION_DELETE_CONFIRMdiff --git a/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-dialog.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-dialog.tsxdeleted file mode 100644index 4a36972a6e8..00000000000--- a/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-dialog.tsx+++ /dev/null@@ -1,391 +0,0 @@-import { isNil, tryCatch } from '@activepieces/core-utils';-import {- ApFlagId,- ApplicationEventName,- EventDestination,- CreatePlatformEventDestinationRequestBody,-} from '@activepieces/shared';-import { zodResolver } from '@hookform/resolvers/zod';-import { t } from 'i18next';-import { ChevronDown, Sparkles } from 'lucide-react';-import { useId, useState } from 'react';-import { useForm } from 'react-hook-form';-import { toast } from 'sonner';-import { z } from 'zod';--import { Button } from '@/components/ui/button';-import { Checkbox } from '@/components/ui/checkbox';-import {- Dialog,- DialogContent,- DialogDescription,- DialogFooter,- DialogTitle,- DialogTrigger,-} from '@/components/ui/dialog';-import {- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuTrigger,-} from '@/components/ui/dropdown-menu';-import {- Form,- FormControl,- FormField,- FormItem,- FormLabel,- FormMessage,-} from '@/components/ui/form';-import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';-import { ScrollArea } from '@/components/ui/scroll-area';-import { INTERNAL_ERROR_MESSAGE } from '@/components/ui/sonner';-import { flagsHooks } from '@/hooks/flags-hooks';-import { AdminControl, adminControl } from '@/lib/admin-control';-import { api } from '@/lib/api';--import { eventDestinationsCollectionUtils } from '../lib/event-destinations-collection';-import { handlerFlowBuilder } from '../lib/handler-flow-builder';-import { useEventLabels } from '../lib/use-event-labels';--interface EventDestinationDialogProps {- children: React.ReactNode;- destination: EventDestination | null;-}--export const EventDestinationDialog = ({- children,- destination,-}: EventDestinationDialogProps) => {- const [isOpen, setIsOpen] = useState(false);-- return (- <Dialog open={isOpen} onOpenChange={setIsOpen}>- <DialogTrigger asChild>{children}</DialogTrigger>- <DialogContent className="max-w-2xl gap-2">- <EventDestinationForm- key={isOpen ? 'open' : 'closed'}- destination={destination}- onClose={() => setIsOpen(false)}- />- </DialogContent>- </Dialog>- );-};--type EventDestinationFormProps = {- destination: EventDestination | null;- onClose: () => void;-};--const EventDestinationForm = ({- destination,- onClose,-}: EventDestinationFormProps) => {- const eventLabels = useEventLabels();- const { data: webhookPrefixUrl } = flagsHooks.useFlag<string>(- ApFlagId.WEBHOOK_URL_PREFIX,- );- const checkboxIdPrefix = useId();-- const formSchema = z.object({- url: z.url(t('Invalid URL')).min(1, t('Webhook URL is required')),- events: z- .array(z.enum(ApplicationEventName))- .min(1, t('Select at least one event')),- });-- const form = useForm<CreatePlatformEventDestinationRequestBody>({- resolver: zodResolver(formSchema),- mode: 'onChange',- defaultValues: {- url: destination?.url ?? '',- events: destination?.events ?? [],- },- });-- const watchedUrl = form.watch('url');- const watchedEvents = form.watch('events') ?? [];-- const { mutate: testDestination, isPending: isTesting } =- eventDestinationsCollectionUtils.useTestEventDestination();-- const { mutate: createDestination, isPending: isCreating } =- eventDestinationsCollectionUtils.useCreateEventDestination(- () => {- toast.success(t('Success'), {- description: t('Destination created successfully'),- });- onClose();- },- (error: Error) => {- toast.error(t('Error'), {- description: error.message,- });- },- );-- const handleSubmit = async (- data: CreatePlatformEventDestinationRequestBody,- ) => {- if (!destination) {- createDestination(data);- return;- }- const { error } = await tryCatch(- () =>- eventDestinationsCollectionUtils.update(destination.id, data)- .isPersisted.promise,- );- if (!isNil(error)) {- toast.error(t('Error'), {- description: api.extractServerErrorMessage(- error,- INTERNAL_ERROR_MESSAGE,- ),- });- return;- }- toast.success(t('Success'), {- description: t('Destination updated successfully'),- });- onClose();- };-- const { mutate: importHandlerFlow, isPending: isImporting } =- eventDestinationsCollectionUtils.useImportHandlerFlow(- (createdFlow) => {- form.setValue('url', `${webhookPrefixUrl}/${createdFlow.id}`, {- shouldValidate: true,- });- window.open(- `/flows/${createdFlow.id}`,- '_blank',- 'noopener,noreferrer',- );- },- (error) => {- toast.error(- error.message ||- t('Failed to generate the handler flow. Please try again.'),- );- },- );-- const handleImportHandlerFlow = () => {- const selectedEvents = form.getValues('events') ?? [];- if (selectedEvents.length === 0) {- form.setError('events', {- message: t('Select at least one event'),- });- return;- }- if (!webhookPrefixUrl) {- toast.error(t('Webhook URL prefix is not configured.'));- return;- }- const template = handlerFlowBuilder.buildHandlerFlowTemplate({- events: selectedEvents.map((name) => ({- name,- label: eventLabels[name].label,- })),- labels: {- flowDisplayName: t('Event handler starter'),- flowDescription: t(- 'Routes audit events into branches you can wire to Slack, Gmail, Teams, or any HTTP endpoint.',- ),- webhookTriggerDisplayName: t('Catch Webhook'),- eventTypeRouterDisplayName: t('Event type checker'),- runStatusRouterDisplayName: t('Run status check'),- failedRunBranchName: t('Failed run'),- otherwiseBranchName: t('Otherwise'),- noteContent: t(- '**Audit event handler**\n\nThis flow runs whenever any of these events fire:\n\n{events}\n\n**Add your channel** (Slack, Gmail, Teams, HTTP…) inside each branch below.\n\nOnce you are done:\n\n1. **Publish this flow** so it can receive events.\n2. Head back to the **Event Streaming** tab and create the destination to start sending events here.',- {- events: selectedEvents- .map((name) => `- ${eventLabels[name].label}`)- .join('\n'),- },- ),- sampleDataNoteContent: t(- '**Test different scenarios**\n\nOpen the trigger and edit its **Sample Data** to swap in a different event payload and test each branch without firing real audit events.',- ),- },- });- importHandlerFlow({ template, selectedEvents });- };-- const availableEvents = Object.values(ApplicationEventName);- const isSaving = isCreating || form.formState.isSubmitting;- const isSubmitDisabled = isSaving || isImporting;-- const isTestingButtonDisabled =- isTesting ||- !watchedUrl ||- !isNil(form.formState.errors.url) ||- watchedEvents.length === 0;-- return (- <>- <DialogTitle>- {destination ? t('Edit Destination') : t('New Destination')}- </DialogTitle>- <DialogDescription>- {destination- ? t('Update the webhook endpoint and event subscriptions.')- : t(- 'Send audit events to a webhook. Use an internal flow to route them to your notification channels — Slack, Gmail, Microsoft Teams, or any other channel.',- )}- </DialogDescription>- <Form {...form}>- <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-4">- <FormField- control={form.control}- name="events"- render={({ field }) => (- <FormItem>- <FormLabel showRequiredIndicator className="text-base">- {t('Events')}- </FormLabel>- <ScrollArea- className="h-48 rounded-md "- viewPortClassName="px-0"- >- <div className="grid grid-cols-2 gap-2">- {availableEvents.map((event) => {- const checkboxId = `${checkboxIdPrefix}-${event}`;- const isChecked = field.value?.includes(event) ?? false;- return (- <div- key={event}- className="flex flex-row items-center gap-3"- >- <Checkbox- id={checkboxId}- checked={isChecked}- onCheckedChange={(checked) => {- const current = field.value ?? [];- field.onChange(- checked- ? [...current, event]- : current.filter((value) => value !== event),- );- }}- />- <Label- htmlFor={checkboxId}- className="cursor-pointer text-sm font-normal"- >- {eventLabels[event]?.label ?? event}- </Label>- </div>- );- })}- </div>- </ScrollArea>- <FormMessage />- </FormItem>- )}- />-- <FormField- control={form.control}- name="url"- render={({ field }) => (- <FormItem>- <FormLabel showRequiredIndicator>{t('Webhook URL')}</FormLabel>- <FormControl>- <Input placeholder="https://example.com/webhook" {...field} />- </FormControl>- {!destination && (- <div className="flex flex-col gap-1 pt-1">- <div className="flex items-center justify-between gap-2">- <span className="text-xs text-gray-11">- {t(- 'Or generate an internal flow to handle the selected events:',- )}- </span>- <Button- {...adminControl(- AdminControl.EVENT_DESTINATIONS_HANDLER_FLOW_RUN,- )}- type="button"- variant="outline"- size="sm"- onClick={handleImportHandlerFlow}- disabled={isImporting || isCreating}- loading={isImporting}- >- <Sparkles className="size-4" />- {t('Generate handler flow')}- </Button>- </div>- <span className="text-xs text-gray-11">- {t(- "Don't forget to publish your flow before creating the alert.",- )}- </span>- </div>- )}- </FormItem>- )}- />-- <DialogFooter>- <Button- type="button"- variant="outline"- onClick={onClose}- disabled={isSubmitDisabled}- >- {t('Cancel')}- </Button>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- type="button"- variant="outline"- disabled={isTestingButtonDisabled}- >- {isTesting ? t('Testing...') : t('Test webhook')}- <ChevronDown className="size-4" />- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="end">- {watchedEvents.map((event) => (- <DropdownMenuItem- {...adminControl(- AdminControl.EVENT_DESTINATIONS_WEBHOOK_TEST_RUN,- )}- key={event}- onSelect={() =>- testDestination({- url: watchedUrl,- event,- })- }- >- {eventLabels[event]?.label ?? event}- </DropdownMenuItem>- ))}- </DropdownMenuContent>- </DropdownMenu>- <Button- {...adminControl(- destination- ? AdminControl.EVENT_DESTINATIONS_DESTINATION_UPDATE_SUBMIT- : AdminControl.EVENT_DESTINATIONS_DESTINATION_CREATE_SUBMIT,- )}- type="submit"- disabled={isSubmitDisabled}- loading={isSaving}- >- {destination ? t('Save changes') : t('Create alert')}- </Button>- </DialogFooter>- </form>- </Form>- </>- );-};diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-row.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-row.tsxdeleted file mode 100644index 15b0ce8cab8..00000000000--- a/packages/web/src/app/routes/platform/infra/event-destinations/components/event-destination-row.tsx+++ /dev/null@@ -1,114 +0,0 @@-import { EventDestination } from '@activepieces/shared';-import { t } from 'i18next';-import { ExternalLink, Globe, Workflow } from 'lucide-react';--import { TextWithTooltip } from '@/components/custom/text-with-tooltip';-import { Badge } from '@/components/ui/badge';-import { Button } from '@/components/ui/button';-import {- Item,- ItemActions,- ItemContent,- ItemDescription,- ItemMedia,- ItemTitle,-} from '@/components/ui/item';-import {- Tooltip,- TooltipContent,- TooltipTrigger,-} from '@/components/ui/tooltip';-import { AdminControl, adminControl } from '@/lib/admin-control';-import { formatUtils } from '@/lib/format-utils';--import { ParsedDestination } from '../lib/parse-flow-id-from-url';-import { EventLabelsMap } from '../lib/use-event-labels';--import EventDestinationActions from './event-destination-actions';--type EventDestinationRowProps = {- destination: EventDestination;- parsed: ParsedDestination;- flowDisplayName: string | undefined;- eventLabels: EventLabelsMap;-};--export const EventDestinationRow = ({- destination,- parsed,- flowDisplayName,- eventLabels,-}: EventDestinationRowProps) => {- const isInternal = parsed.kind === 'flow';- const flowId = parsed.kind === 'flow' ? parsed.flowId : undefined;- const title =- isInternal && flowDisplayName- ? flowDisplayName- : isInternal && flowId- ? t('Destination (flow {flowId})', { flowId })- : destination.url;-- return (- <Item variant="outline">- <ItemMedia variant="icon">- <Tooltip>- <TooltipTrigger asChild>- <span tabIndex={0} className="inline-flex">- {isInternal ? <Workflow /> : <Globe />}- </span>- </TooltipTrigger>- <TooltipContent>- {isInternal ? t('Internal Flow') : t('External')}- </TooltipContent>- </Tooltip>- </ItemMedia>- <ItemContent className="min-w-0">- <TextWithTooltip tooltipMessage={title}>- <ItemTitle- className={isInternal ? 'truncate' : 'truncate font-mono text-xs'}- >- {title}- </ItemTitle>- </TextWithTooltip>- <ItemDescription className="text-xs !flex flex-wrap items-center gap-x-1 gap-y-2 overflow-visible [text-wrap:unset] mt-1">- <span className="text-gray-11 shrink-0 mr-1.5">{t('Events')}</span>- {destination.events.map((event) => (- <Badge key={event} variant="outline" className="text-xs">- {eventLabels[event]?.label ?? event}- </Badge>- ))}- </ItemDescription>- <p className="text-xs text-gray-11 mt-2">- {t('Created')}{' '}- {formatUtils.formatDateToAgo(new Date(destination.created))}- </p>- </ItemContent>- <ItemActions>- {isInternal && flowId && (- <Tooltip>- <TooltipTrigger asChild>- <Button- {...adminControl(- AdminControl.EVENT_DESTINATIONS_HANDLER_FLOW_LINK,- )}- variant="ghost"- size="sm"- onClick={() =>- window.open(- `/flows/${flowId}`,- '_blank',- 'noopener,noreferrer',- )- }- >- <ExternalLink className="size-4" />- </Button>- </TooltipTrigger>- <TooltipContent>{t('View flow')}</TooltipContent>- </Tooltip>- )}- <EventDestinationActions destination={destination} />- </ItemActions>- </Item>- );-};diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/components/vendor-logo-stack.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/components/vendor-logo-stack.tsxnew file mode 100644index 00000000000..ac2e2773438--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/components/vendor-logo-stack.tsx@@ -0,0 +1,77 @@+import { t } from 'i18next';++export const VendorLogoStack = () => {+ return (+ <div className="flex items-center gap-2 pt-2">+ <div className="flex">+ {VENDOR_LOGOS.map((logo) => (+ <span key={logo.name} className="w-5 shrink-0 overflow-visible">+ <span+ title={logo.name}+ className="flex size-[26px] items-center justify-center rounded-full border-2 border-gray-1 bg-gray-5"+ >+ <svg+ role="img"+ aria-label={logo.name}+ viewBox="0 0 24 24"+ className="size-3.5"+ fill={logo.color}+ >+ <path d={logo.path} />+ </svg>+ </span>+ </span>+ ))}+ </div>+ <span className="pl-3 text-xs font-medium text-gray-11">+ {t('{first}, {second}, and {count} more', {+ first: OTLP_VENDOR_NAMES[0],+ second: OTLP_VENDOR_NAMES[1],+ count: OTLP_VENDOR_NAMES.length - 2,+ })}+ </span>+ </div>+ );+};++const VENDOR_LOGOS = [+ {+ name: 'Datadog',+ color: '#632CA6',+ path: 'M19.57 17.04l-1.997-1.316-1.665 2.782-1.937-.567-1.706 2.604.087.82 9.274-1.71-.538-5.794zm-8.649-2.498l1.488-.204c.241.108.409.15.697.223.45.117.97.23 1.741-.16.18-.088.553-.43.704-.625l6.096-1.106.622 7.527-10.444 1.882zm11.325-2.712l-.602.115L20.488 0 .789 2.285l2.427 19.693 2.306-.334c-.184-.263-.471-.581-.96-.989-.68-.564-.44-1.522-.039-2.127.53-1.022 3.26-2.322 3.106-3.956-.056-.594-.15-1.368-.702-1.898-.02.22.017.432.017.432s-.227-.289-.34-.683c-.112-.15-.2-.199-.319-.4-.085.233-.073.503-.073.503s-.186-.437-.216-.807c-.11.166-.137.48-.137.48s-.241-.69-.186-1.062c-.11-.323-.436-.965-.343-2.424.6.421 1.924.321 2.44-.439.171-.251.288-.939-.086-2.293-.24-.868-.835-2.16-1.066-2.651l-.028.02c.122.395.374 1.223.47 1.625.293 1.218.372 1.642.234 2.204-.116.488-.397.808-1.107 1.165-.71.358-1.653-.514-1.713-.562-.69-.55-1.224-1.447-1.284-1.883-.062-.477.275-.763.445-1.153-.243.07-.514.192-.514.192s.323-.334.722-.624c.165-.109.262-.178.436-.323a9.762 9.762 0 0 0-.456.003s.42-.227.855-.392c-.318-.014-.623-.003-.623-.003s.937-.419 1.678-.727c.509-.208 1.006-.147 1.286.257.367.53.752.817 1.569.996.501-.223.653-.337 1.284-.509.554-.61.99-.688.99-.688s-.216.198-.274.51c.314-.249.66-.455.66-.455s-.134.164-.259.426l.03.043c.366-.22.797-.394.797-.394s-.123.156-.268.358c.277-.002.838.012 1.056.037 1.285.028 1.552-1.374 2.045-1.55.618-.22.894-.353 1.947.68.903.888 1.609 2.477 1.259 2.833-.294.295-.874-.115-1.516-.916a3.466 3.466 0 0 1-.716-1.562 1.533 1.533 0 0 0-.497-.85s.23.51.23.96c0 .246.03 1.165.424 1.68-.039.076-.057.374-.1.43-.458-.554-1.443-.95-1.604-1.067.544.445 1.793 1.468 2.273 2.449.453.927.186 1.777.416 1.997.065.063.976 1.197 1.15 1.767.306.994.019 2.038-.381 2.685l-1.117.174c-.163-.045-.273-.068-.42-.153.08-.143.241-.5.243-.572l-.063-.111c-.348.492-.93.97-1.414 1.245-.633.359-1.363.304-1.838.156-1.348-.415-2.623-1.327-2.93-1.566 0 0-.01.191.048.234.34.383 1.119 1.077 1.872 1.56l-1.605.177.759 5.908c-.337.048-.39.071-.757.124-.325-1.147-.946-1.895-1.624-2.332-.599-.384-1.424-.47-2.214-.314l-.05.059a2.851 2.851 0 0 1 1.863.444c.654.413 1.181 1.481 1.375 2.124.248.822.42 1.7-.248 2.632-.476.662-1.864 1.028-2.986.237.3.481.705.876 1.25.95.809.11 1.577-.03 2.106-.574.452-.464.69-1.434.628-2.456l.714-.104.258 1.834 11.827-1.424zM15.05 6.848c-.034.075-.085.125-.007.37l.004.014.013.032.032.073c.14.287.295.558.552.696.067-.011.136-.019.207-.023.242-.01.395.028.492.08.009-.048.01-.119.005-.222-.018-.364.072-.982-.626-1.308-.264-.122-.634-.084-.757.068a.302.302 0 0 1 .058.013c.186.066.06.13.027.207m1.958 3.392c-.092-.05-.52-.03-.821.005-.574.068-1.193.267-1.328.372-.247.191-.135.523.047.66.511.382.96.638 1.432.575.29-.038.546-.497.728-.914.124-.288.124-.598-.058-.698m-5.077-2.942c.162-.154-.805-.355-1.556.156-.554.378-.571 1.187-.041 1.646.053.046.096.078.137.104a4.77 4.77 0 0 1 1.396-.412c.113-.125.243-.345.21-.745-.044-.542-.455-.456-.146-.749',+ },+ {+ name: 'PostHog',+ color: 'currentColor',+ path: 'M9.854 14.5 5 9.647.854 5.5A.5.5 0 0 0 0 5.854V8.44a.5.5 0 0 0 .146.353L5 13.647l.147.146L9.854 18.5l.146.147v-.049c.065.03.134.049.207.049h2.586a.5.5 0 0 0 .353-.854L9.854 14.5zm0-5-4-4a.487.487 0 0 0-.409-.144.515.515 0 0 0-.356.21.493.493 0 0 0-.089.288V8.44a.5.5 0 0 0 .147.353l9 9a.5.5 0 0 0 .853-.354v-2.585a.5.5 0 0 0-.146-.354l-5-5zm1-4a.5.5 0 0 0-.854.354V8.44a.5.5 0 0 0 .147.353l4 4a.5.5 0 0 0 .853-.354V9.854a.5.5 0 0 0-.146-.354l-4-4zm12.647 11.515a3.863 3.863 0 0 1-2.232-1.1l-4.708-4.707a.5.5 0 0 0-.854.354v6.585a.5.5 0 0 0 .5.5H23.5a.5.5 0 0 0 .5-.5v-.6c0-.276-.225-.497-.499-.532zm-5.394.032a.8.8 0 1 1 0-1.6.8.8 0 0 1 0 1.6zM.854 15.5a.5.5 0 0 0-.854.354v2.293a.5.5 0 0 0 .5.5h2.293c.222 0 .39-.135.462-.309a.493.493 0 0 0-.109-.545L.854 15.501zM5 14.647.854 10.5a.5.5 0 0 0-.854.353v2.586a.5.5 0 0 0 .146.353L4.854 18.5l.146.147h2.793a.5.5 0 0 0 .353-.854L5 14.647z',+ },+ {+ name: 'Grafana',+ color: '#F46800',+ path: 'M23.02 10.59a8.578 8.578 0 0 0-.862-3.034 8.911 8.911 0 0 0-1.789-2.445c.337-1.342-.413-2.505-.413-2.505-1.292-.08-2.113.4-2.416.62-.052-.02-.102-.044-.154-.064-.22-.089-.446-.172-.677-.247-.231-.073-.47-.14-.711-.197a9.867 9.867 0 0 0-.875-.161C14.557.753 12.94 0 12.94 0c-1.804 1.145-2.147 2.744-2.147 2.744l-.018.093c-.098.029-.2.057-.298.088-.138.042-.275.094-.413.143-.138.055-.275.107-.41.166a8.869 8.869 0 0 0-1.557.87l-.063-.029c-2.497-.955-4.716.195-4.716.195-.203 2.658.996 4.33 1.235 4.636a11.608 11.608 0 0 0-.607 2.635C1.636 12.677.953 15.014.953 15.014c1.926 2.214 4.171 2.351 4.171 2.351.003-.002.006-.002.006-.005.285.509.615.994.986 1.446.156.19.32.371.488.548-.704 2.009.099 3.68.099 3.68 2.144.08 3.553-.937 3.849-1.173a9.784 9.784 0 0 0 3.164.501h.08l.055-.003.107-.002.103-.005.003.002c1.01 1.44 2.788 1.646 2.788 1.646 1.264-1.332 1.337-2.653 1.337-2.94v-.058c0-.02-.003-.039-.003-.06.265-.187.52-.387.758-.6a7.875 7.875 0 0 0 1.415-1.7c1.43.083 2.437-.885 2.437-.885-.236-1.49-1.085-2.216-1.264-2.354l-.018-.013-.016-.013a.217.217 0 0 1-.031-.02c.008-.092.016-.18.02-.27.011-.162.016-.323.016-.48v-.253l-.005-.098-.008-.135a1.891 1.891 0 0 0-.01-.13c-.003-.042-.008-.083-.013-.125l-.016-.124-.018-.122a6.215 6.215 0 0 0-2.032-3.73 6.015 6.015 0 0 0-3.222-1.46 6.292 6.292 0 0 0-.85-.048l-.107.002h-.063l-.044.003-.104.008a4.777 4.777 0 0 0-3.335 1.695c-.332.4-.592.84-.768 1.297a4.594 4.594 0 0 0-.312 1.817l.003.091c.005.055.007.11.013.164a3.615 3.615 0 0 0 .698 1.82 3.53 3.53 0 0 0 1.827 1.282c.33.098.66.14.971.137.039 0 .078 0 .114-.002l.063-.003c.02 0 .041-.003.062-.003.034-.002.065-.007.099-.01.007 0 .018-.003.028-.003l.031-.005.06-.008a1.18 1.18 0 0 0 .112-.02c.036-.008.072-.013.109-.024a2.634 2.634 0 0 0 .914-.415c.028-.02.056-.041.085-.065a.248.248 0 0 0 .039-.35.244.244 0 0 0-.309-.06l-.078.042c-.09.044-.184.083-.283.116a2.476 2.476 0 0 1-.475.096c-.028.003-.054.006-.083.006l-.083.002c-.026 0-.054 0-.08-.002l-.102-.006h-.012l-.024.006c-.016-.003-.031-.003-.044-.006-.031-.002-.06-.007-.091-.01a2.59 2.59 0 0 1-.724-.213 2.557 2.557 0 0 1-.667-.438 2.52 2.52 0 0 1-.805-1.475 2.306 2.306 0 0 1-.029-.444l.006-.122v-.023l.002-.031c.003-.021.003-.04.005-.06a3.163 3.163 0 0 1 1.352-2.29 3.12 3.12 0 0 1 .937-.43 2.946 2.946 0 0 1 .776-.101h.06l.07.002.045.003h.026l.07.005a4.041 4.041 0 0 1 1.635.49 3.94 3.94 0 0 1 1.602 1.662 3.77 3.77 0 0 1 .397 1.414l.005.076.003.075c.002.026.002.05.002.075 0 .024.003.052 0 .07v.065l-.002.073-.008.174a6.195 6.195 0 0 1-.08.639 5.1 5.1 0 0 1-.267.927 5.31 5.31 0 0 1-.624 1.13 5.052 5.052 0 0 1-3.237 2.014 4.82 4.82 0 0 1-.649.066l-.039.003h-.287a6.607 6.607 0 0 1-1.716-.265 6.776 6.776 0 0 1-3.4-2.274 6.75 6.75 0 0 1-.746-1.15 6.616 6.616 0 0 1-.714-2.596l-.005-.083-.002-.02v-.056l-.003-.073v-.096l-.003-.104v-.07l.003-.163c.008-.22.026-.45.054-.678a8.707 8.707 0 0 1 .28-1.355c.128-.444.286-.872.473-1.277a7.04 7.04 0 0 1 1.456-2.1 5.925 5.925 0 0 1 .953-.763c.169-.111.343-.213.524-.306.089-.05.182-.091.273-.135.047-.02.093-.042.138-.062a7.177 7.177 0 0 1 .714-.267l.145-.045c.049-.015.098-.026.148-.041.098-.029.197-.052.296-.076.049-.013.1-.02.15-.033l.15-.032.151-.028.076-.013.075-.01.153-.024c.057-.01.114-.013.171-.023l.169-.021c.036-.003.073-.008.106-.01l.073-.008.036-.003.042-.002c.057-.003.114-.008.171-.01l.086-.006h.023l.037-.003.145-.007a7.999 7.999 0 0 1 1.708.125 7.917 7.917 0 0 1 2.048.68 8.253 8.253 0 0 1 1.672 1.09l.09.077.089.078c.06.052.114.107.171.159.057.052.112.106.166.16.052.055.107.107.159.164a8.671 8.671 0 0 1 1.41 1.978c.012.026.028.052.04.078l.04.078.075.156c.023.051.05.1.07.153l.065.15a8.848 8.848 0 0 1 .45 1.34.19.19 0 0 0 .201.142.186.186 0 0 0 .172-.184c.01-.246.002-.532-.024-.856z',+ },+ {+ name: 'New Relic',+ color: '#1CE783',+ path: 'M8.0015 14.3091v7.384L12.0008 24V12.0008L1.6078 5.9996v4.6167ZM12.0008 0 2.8232 5.2976 6.8209 7.606l5.1799-2.9893 6.3936 3.6913v7.384l-5.1783 2.9908v4.6167l9.176-5.2991V5.9996Z',+ },+ {+ name: 'Elastic',+ color: '#005571',+ path: 'M20.345 16.33l-3.959-.926-1.05-2.01 5.177-4.535a3.962 3.962 0 012.559 3.702 4.006 4.006 0 01-2.727 3.77m-2.976 4.68c-.616 0-1.22-.207-1.714-.587l.782-4.077 3.596.841c.115.31.172.642.172.987a2.839 2.839 0 01-2.836 2.836m-2.637-.586a5.92 5.92 0 01-4.908 2.6A5.947 5.947 0 014 15.905l5.167-4.67 5.272 2.403 1.167 2.23zM.928 11.443a4.007 4.007 0 012.726-3.77l3.95.933.927 1.98-5.05 4.565a3.97 3.97 0 01-2.553-3.708m5.703-8.45a2.841 2.841 0 011.723.58l-.789 4.092-3.598-.85a2.842 2.842 0 01-.172-.986A2.84 2.84 0 016.63 2.992m2.66.59A5.92 5.92 0 0120.1 6.93c0 .4-.038.781-.114 1.164l-5.299 4.643-5.251-2.394-1.026-2.19zM24 12.571a4.723 4.723 0 00-3.124-4.454 6.695 6.695 0 00.126-1.29A6.789 6.789 0 0014.22.047 6.769 6.769 0 008.727 2.86a3.586 3.586 0 00-2.204-.754A3.604 3.604 0 003.15 6.959 4.786 4.786 0 000 11.431 4.727 4.727 0 003.139 15.9a6.876 6.876 0 00-.124 1.289 6.773 6.773 0 006.765 6.765c2.19 0 4.22-1.052 5.49-2.824a3.568 3.568 0 002.207.769 3.603 3.603 0 003.374-4.854A4.785 4.785 0 0024 12.572',+ },+];++const OTLP_VENDOR_NAMES = [+ 'Datadog',+ 'PostHog',+ 'Grafana Loki',+ 'Grafana Cloud',+ 'New Relic',+ 'Honeycomb',+ 'Axiom',+ 'Better Stack',+ 'SigNoz',+ 'Dynatrace',+ 'Elastic',+];diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/connection-fields.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/connection-fields.tsxnew file mode 100644index 00000000000..a0bb05c81d3--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/connection-fields.tsx@@ -0,0 +1,130 @@+import { t } from 'i18next';+import { Lock, Plus, TrashIcon } from 'lucide-react';+import { useId } from 'react';+import { UseFormReturn, useFieldArray, useWatch } from 'react-hook-form';++import { MaskedInput } from '@/components/custom/masked-input';+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';+import { Button } from '@/components/ui/button';+import {+ FormControl,+ FormField,+ FormItem,+ FormMessage,+} from '@/components/ui/form';+import { Input } from '@/components/ui/input';++import type { DestinationFormValues } from '../lib/destination-form-utils';++export const HeadersField = ({+ form,+ storedHeaderNames,+ keyPlaceholder,+}: {+ form: UseFormReturn<DestinationFormValues>;+ storedHeaderNames: string[];+ keyPlaceholder: string;+}) => {+ const headingId = useId();+ const { fields, append, remove } = useFieldArray({+ control: form.control,+ name: 'headers',+ });+ const rows = useWatch({ control: form.control, name: 'headers' });+ const storedLowerCaseNames = new Set(+ storedHeaderNames.map((name) => name.toLowerCase()),+ );+ const isStoredRow = (index: number) =>+ storedLowerCaseNames.has((rows[index]?.name ?? '').toLowerCase());++ return (+ <div+ role="group"+ aria-labelledby={headingId}+ className="flex flex-col gap-2"+ >+ <span id={headingId} className="text-sm font-medium">+ {t('Headers')}+ </span>+ {fields.map((row, index) => (+ <div key={row.id} className="flex items-start gap-3">+ <FormField+ control={form.control}+ name={`headers.${index}.name`}+ rules={{ deps: ['headers'] }}+ render={({ field }) => (+ <FormItem className="flex-1">+ <FormControl>+ <Input+ {...field}+ aria-label={t('Header name')}+ placeholder={keyPlaceholder}+ autoComplete="off"+ spellCheck={false}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name={`headers.${index}.value`}+ rules={{ deps: ['headers'] }}+ render={({ field }) => (+ <FormItem className="flex-1">+ <FormControl>+ <MaskedInput+ {...field}+ aria-label={t('Header value')}+ placeholder={+ isStoredRow(index)+ ? t('Hidden — type to replace')+ : t('Value')+ }+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <Button+ type="button"+ variant="outline"+ size="icon"+ className="size-9 shrink-0"+ onClick={() => {+ remove(index);+ form.trigger('headers').catch(() => undefined);+ }}+ >+ <TrashIcon className="size-4 text-danger-11" aria-hidden="true" />+ <span className="sr-only">{t('Remove')}</span>+ </Button>+ </div>+ ))}+ <Button+ type="button"+ variant="outline"+ size="sm"+ className="self-start"+ onClick={() => append({ name: '', value: '' })}+ >+ <Plus className="size-4" />+ {t('Add header')}+ </Button>+ </div>+ );+};++export const EncryptedHeadersNotice = () => {+ return (+ <Alert>+ <Lock className="size-4" />+ <AlertTitle>{t('Header values are encrypted')}</AlertTitle>+ <AlertDescription>+ {t('After you save, a value can be replaced but not read back.')}+ </AlertDescription>+ </Alert>+ );+};diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/connection-step.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/connection-step.tsxnew file mode 100644index 00000000000..0ebd007f3ca--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/connection-step.tsx@@ -0,0 +1,36 @@+import { RefObject } from 'react';+import { UseFormReturn, useWatch } from 'react-hook-form';++import type { DestinationFormValues } from '../lib/destination-form-utils';+import { destinationKinds } from '../lib/destination-kinds';++import { OpenTelemetryConnection } from './open-telemetry-connection';+import { WebhookConnection } from './webhook-connection';++export const ConnectionStep = ({+ form,+ isEdit,+ storedHeaderNames,+ isFormatAutoSwitched,+}: {+ form: UseFormReturn<DestinationFormValues>;+ isEdit: boolean;+ storedHeaderNames: string[];+ isFormatAutoSwitched: RefObject<boolean>;+}) => {+ const format = useWatch({ control: form.control, name: 'format' });++ return destinationKinds.kindOf(format) === 'otel' ? (+ <OpenTelemetryConnection+ form={form}+ storedHeaderNames={storedHeaderNames}+ isFormatAutoSwitched={isFormatAutoSwitched}+ />+ ) : (+ <WebhookConnection+ form={form}+ isEdit={isEdit}+ storedHeaderNames={storedHeaderNames}+ />+ );+};diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/destination-step.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/destination-step.tsxnew file mode 100644index 00000000000..1a80c6a6af3--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/destination-step.tsx@@ -0,0 +1,85 @@+import { t } from 'i18next';+import { UseFormReturn } from 'react-hook-form';++import { FormField, FormItem, FormMessage } from '@/components/ui/form';+import { Label } from '@/components/ui/label';+import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';+import { cn } from '@/lib/utils';++import { DestinationKindCard } from '../components/destination-kind-card';+import type { DestinationFormValues } from '../lib/destination-form-utils';+import { destinationKinds } from '../lib/destination-kinds';++export const DestinationStep = ({+ form,+ isEdit,+}: {+ form: UseFormReturn<DestinationFormValues>;+ isEdit: boolean;+}) => {+ const options = destinationKinds.buildOptions();++ return (+ <FormField+ control={form.control}+ name="format"+ render={({ field }) => {+ const selectedKind = destinationKinds.kindOf(field.value);+ return (+ <FormItem className="flex flex-col gap-4">+ <div className="flex flex-col gap-0.5">+ <span className="text-sm font-medium">+ {t('Where should events go?')}+ </span>+ <span className="text-sm text-gray-11">+ {t("This decides the format. You can't change it later.")}+ </span>+ </div>+ <RadioGroup+ className="grid grid-cols-1 gap-3 sm:grid-cols-2"+ value={selectedKind}+ disabled={isEdit}+ onValueChange={(value) => {+ const kind = destinationKinds.parse(value);+ if (kind === null || kind === selectedKind) {+ return;+ }+ field.onChange(destinationKinds.defaultFormatOf(kind));+ form.setValue('url', '');+ form.setValue('headers', []);+ form.clearErrors(['url', 'headers']);+ }}+ >+ {options.map((option) => {+ const isSelected = option.kind === selectedKind;+ const itemId = `destination-kind-${option.kind}`;+ return (+ <Label+ key={option.kind}+ htmlFor={itemId}+ className={cn(+ 'block rounded-lg border p-4 font-normal transition-shadow',+ isEdit ? 'cursor-not-allowed' : 'cursor-pointer',+ isSelected &&+ 'border-accent-9 ring-[3px] ring-accent-9/15',+ isEdit && !isSelected && 'opacity-60',+ )}+ >+ <DestinationKindCard+ option={option}+ isSelected={isSelected}+ trailing={+ <RadioGroupItem id={itemId} value={option.kind} />+ }+ />+ </Label>+ );+ })}+ </RadioGroup>+ <FormMessage />+ </FormItem>+ );+ }}+ />+ );+};diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/events-step.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/events-step.tsxnew file mode 100644index 00000000000..d6a3f24e18d--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/events-step.tsx@@ -0,0 +1,227 @@+import { ApplicationEventName } from '@activepieces/shared';+import { t } from 'i18next';+import { useId, useState } from 'react';+import { UseFormReturn } from 'react-hook-form';++import { SearchInput } from '@/components/custom/search-input';+import { Button } from '@/components/ui/button';+import { Checkbox } from '@/components/ui/checkbox';+import { FormField, FormItem, FormMessage } from '@/components/ui/form';+import { Label } from '@/components/ui/label';+import { cn } from '@/lib/utils';++import { destinationFormUtils } from '../lib/destination-form-utils';+import type { DestinationFormValues } from '../lib/destination-form-utils';+import { eventGroupUtils } from '../lib/event-groups';+import { buildEventLabels } from '../lib/event-labels';++export const EventsStep = ({+ form,+}: {+ form: UseFormReturn<DestinationFormValues>;+}) => {+ const eventLabels = buildEventLabels();+ const eventGroups = eventGroupUtils.buildEventGroups();+ const checkboxIdPrefix = useId();+ const [search, setSearch] = useState('');+ const [activeGroupKey, setActiveGroupKey] = useState(+ eventGroups[0]?.key ?? '',+ );++ const matchesSearch = (event: ApplicationEventName) => {+ const needle = search.trim().toLowerCase();+ if (needle === '') {+ return true;+ }+ return (+ eventLabels[event].toLowerCase().includes(needle) ||+ event.toLowerCase().includes(needle)+ );+ };++ const visibleGroups = eventGroups+ .map((group) => ({+ ...group,+ events: group.events.filter(matchesSearch),+ }))+ .filter((group) => group.events.length > 0);++ const activeGroup =+ visibleGroups.find((group) => group.key === activeGroupKey) ??+ visibleGroups[0];++ const allEvents = eventGroups.flatMap((group) => group.events);+ const isSearching = search.trim() !== '';+ const scopeEvents = isSearching+ ? visibleGroups.flatMap((group) => group.events)+ : allEvents;++ return (+ <FormField+ control={form.control}+ name="events"+ render={({ field }) => {+ const toggleEvents = ({+ events,+ shouldSelect,+ }: {+ events: ApplicationEventName[];+ shouldSelect: boolean;+ }) => {+ const remaining = field.value.filter(+ (value) => !events.includes(value),+ );+ field.onChange(+ destinationFormUtils.inCanonicalOrder(+ shouldSelect ? [...remaining, ...events] : remaining,+ ),+ );+ };+ const isScopeSelected =+ scopeEvents.length > 0 &&+ scopeEvents.every((event) => field.value.includes(event));+ const scopeLabel = isSearching+ ? isScopeSelected+ ? t('Clear matching')+ : t('Select matching')+ : isScopeSelected+ ? t('Clear')+ : t('Select all');+ const selectedInActiveGroup =+ activeGroup?.events.filter((event) => field.value.includes(event)) ??+ [];+ const groupCheckboxId = `${checkboxIdPrefix}-group`;++ return (+ <FormItem className="flex flex-col gap-4">+ <div className="flex items-center gap-2">+ <SearchInput+ placeholder={t('Search events')}+ value={search}+ onChange={setSearch}+ />+ <Button+ type="button"+ variant="outline"+ disabled={scopeEvents.length === 0}+ onClick={() =>+ toggleEvents({+ events: scopeEvents,+ shouldSelect: !isScopeSelected,+ })+ }+ >+ {scopeLabel}+ </Button>+ </div>++ <div className="grid min-h-[340px] grid-cols-[240px_minmax(0,1fr)] overflow-hidden rounded-lg border">+ <nav className="flex flex-col gap-0.5 border-r bg-gray-3 p-1.5">+ {visibleGroups.map((group) => {+ const isActive = group.key === activeGroup?.key;+ const selectedCount = group.events.filter((event) =>+ field.value.includes(event),+ ).length;+ return (+ <button+ key={group.key}+ type="button"+ onClick={() => setActiveGroupKey(group.key)}+ aria-current={isActive ? 'true' : undefined}+ className={cn(+ 'flex h-[34px] items-center gap-2.5 rounded-md px-2.5 text-left text-sm transition-colors',+ isActive+ ? 'bg-panel font-semibold text-gray-12'+ : 'hover:bg-gray-4',+ )}+ >+ <span className="flex-1 truncate">{group.title}</span>+ <span className="text-xs font-normal text-gray-11">+ {t('{selected}/{total}', {+ selected: selectedCount,+ total: group.events.length,+ })}+ </span>+ </button>+ );+ })}+ </nav>++ <div className="flex flex-col gap-1 px-[18px] py-3.5">+ {activeGroup === undefined ? (+ <p className="py-6 text-center text-sm text-gray-11">+ {t('No events match your search')}+ </p>+ ) : (+ <>+ <div className="mb-1 flex h-8 items-center gap-2.5 border-b pb-2">+ <Checkbox+ id={groupCheckboxId}+ checked={+ selectedInActiveGroup.length === 0+ ? false+ : selectedInActiveGroup.length ===+ activeGroup.events.length+ ? true+ : 'indeterminate'+ }+ onCheckedChange={(checked) =>+ toggleEvents({+ events: activeGroup.events,+ shouldSelect: checked === true,+ })+ }+ />+ <Label+ htmlFor={groupCheckboxId}+ className="flex-1 cursor-pointer text-sm font-medium"+ >+ {activeGroup.title}+ </Label>+ <span className="text-sm text-gray-11">+ {t('{selected} of {total} selected', {+ selected: selectedInActiveGroup.length,+ total: activeGroup.events.length,+ })}+ </span>+ </div>+ {activeGroup.events.map((event) => {+ const checkboxId = `${checkboxIdPrefix}-${event}`;+ return (+ <div+ key={event}+ className="flex h-9 items-center gap-2.5"+ >+ <Checkbox+ id={checkboxId}+ checked={field.value.includes(event)}+ onCheckedChange={(checked) =>+ toggleEvents({+ events: [event],+ shouldSelect: checked === true,+ })+ }+ />+ <Label+ htmlFor={checkboxId}+ className="flex-1 cursor-pointer text-sm font-normal"+ >+ {eventLabels[event]}+ </Label>+ <span className="font-mono text-xs text-gray-11">+ {event}+ </span>+ </div>+ );+ })}+ </>+ )}+ </div>+ </div>+ <FormMessage />+ </FormItem>+ );+ }}+ />+ );+};diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/index.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/index.tsxnew file mode 100644index 00000000000..d658a002fd2--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/index.tsx@@ -0,0 +1,371 @@+import { isNil } from '@activepieces/core-utils';+import { EventDestination } from '@activepieces/shared';+import { zodResolver } from '@hookform/resolvers/zod';+import { t } from 'i18next';+import { Check } from 'lucide-react';+import { Fragment, useRef, useState } from 'react';+import { FieldErrors, useForm, useWatch } from 'react-hook-form';+import {+ Link,+ Navigate,+ useNavigate,+ useParams,+ useSearchParams,+} from 'react-router-dom';+import { toast } from 'sonner';++import { CenteredPage } from '@/app/components/centered-page';+import { DataFetchErrorState } from '@/components/custom/data-fetch-error-state';+import {+ LeaveWithoutSavingDialog,+ useWarnBeforeLosingChanges,+} from '@/components/custom/leave-without-saving';+import {+ Breadcrumb,+ BreadcrumbItem,+ BreadcrumbLink,+ BreadcrumbList,+ BreadcrumbPage,+ BreadcrumbSeparator,+} from '@/components/ui/breadcrumb';+import { Button } from '@/components/ui/button';+import { Form } from '@/components/ui/form';+import { SkeletonList } from '@/components/ui/skeleton';+import { AdminControl, adminControl } from '@/lib/admin-control';+import { cn } from '@/lib/utils';++import { destinationErrors } from '../lib/destination-errors';+import {+ destinationFormUtils,+ DestinationFormValues,+} from '../lib/destination-form-utils';+import {+ DESTINATION_KIND_SEARCH_PARAM,+ destinationKinds,+} from '../lib/destination-kinds';+import { eventDestinationsCollectionUtils } from '../lib/event-destinations-collection';+import { eventGroupUtils } from '../lib/event-groups';+import { EVENT_STREAMING_PATH } from '../lib/event-streaming-path';++import { ConnectionStep } from './connection-step';+import { DestinationStep } from './destination-step';+import { EventsStep } from './events-step';++const EventDestinationFormPage = () => {+ const { id } = useParams<{ id: string }>();+ return isNil(id) ? (+ <DestinationForm destination={null} />+ ) : (+ <EditDestination key={id} destinationId={id} />+ );+};++const EditDestination = ({ destinationId }: { destinationId: string }) => {+ const opened =+ eventDestinationsCollectionUtils.useFreshDestination(destinationId);++ switch (opened.status) {+ case 'loading':+ return (+ <div className="w-full mx-auto py-6 px-6">+ <SkeletonList numberOfItems={4} className="w-full h-[72px]" />+ </div>+ );+ case 'error':+ return (+ <DataFetchErrorState+ entity={t('destination')}+ onRetry={eventDestinationsCollectionUtils.refetch}+ />+ );+ case 'missing':+ return <Navigate to={EVENT_STREAMING_PATH} replace />;+ case 'ready':+ return <DestinationForm destination={opened.destination} />;+ }+};++const DestinationForm = ({+ destination,+}: {+ destination: EventDestination | null;+}) => {+ const navigate = useNavigate();+ const [searchParams] = useSearchParams();+ const isEdit = !isNil(destination);+ const presetKind = destinationKinds.parse(+ searchParams.get(DESTINATION_KIND_SEARCH_PARAM),+ );+ const [stepIndex, setStepIndex] = useState(+ isEdit+ ? CONNECTION_STEP+ : isNil(presetKind)+ ? DESTINATION_STEP+ : EVENTS_STEP,+ );++ const storedHeaderNames = Object.keys(destination?.headers ?? {});++ const form = useForm<DestinationFormValues>({+ resolver: zodResolver(+ destinationFormUtils.buildFormSchema({+ storedHeaderNames,+ storedUrl: destination?.url ?? null,+ }),+ ),+ mode: 'onChange',+ defaultValues: destinationFormUtils.toDefaultValues({+ destination,+ kind: presetKind ?? 'otel',+ }),+ });++ const isFormatAutoSwitched = useRef(false);+ const leavingOnPurpose = useRef(false);+ const leaveBlocker = useWarnBeforeLosingChanges({+ hasChanges: form.formState.isDirty,+ standDown: leavingOnPurpose,+ });+ const leaveAfterSave = () => {+ leavingOnPurpose.current = true;+ navigate(EVENT_STREAMING_PATH);+ };++ const { mutate: saveDestination, isPending: isSaving } =+ eventDestinationsCollectionUtils.useSaveEventDestination({+ onSuccess: () => {+ toast.success(t('Success'), {+ description: isEdit+ ? t('Destination updated successfully')+ : t('Destination created successfully'),+ });+ leaveAfterSave();+ },+ onError: (error) => {+ toast.error(t('Error'), {+ description: destinationErrors.describe(error),+ });+ },+ });++ const handleSubmit = (values: DestinationFormValues) =>+ saveDestination({+ destinationId: destination?.id ?? null,+ request: destinationFormUtils.toRequest(values),+ });++ const handleInvalidSubmit = (errors: FieldErrors<DestinationFormValues>) => {+ setStepIndex(isNil(errors.events) ? CONNECTION_STEP : EVENTS_STEP);+ toast.error(t('Error'), {+ description: t('Please fix the highlighted fields before saving'),+ });+ };++ const goToNextStep = async () => {+ if (stepIndex === CONNECTION_STEP) {+ return;+ }+ if (stepIndex === EVENTS_STEP && !(await form.trigger('events'))) {+ return;+ }+ setStepIndex(stepIndex + 1);+ };++ const watchedEvents = useWatch({ control: form.control, name: 'events' });+ const watchedFormat = useWatch({ control: form.control, name: 'format' });+ const selectedKind = destinationKinds.kindOf(watchedFormat);+ const selectedKindTitle =+ destinationKinds+ .buildOptions()+ .find((option) => option.kind === selectedKind)?.shortTitle ?? '';+ const isLastStep = stepIndex === CONNECTION_STEP;+ const showSubmit = isEdit || isLastStep;+ const footerStatus =+ stepIndex === EVENTS_STEP+ ? t('{selected} of {total} events selected', {+ selected: watchedEvents.length,+ total: eventGroupUtils.countEvents(),+ })+ : t('Step {current} of {total}', {+ current: stepIndex + 1,+ total: STEP_COUNT,+ });++ return (+ <CenteredPage+ widthClassName="max-w-full px-6"+ breadcrumb={+ <Breadcrumb>+ <BreadcrumbList>+ <BreadcrumbItem>+ <BreadcrumbLink asChild>+ <Link to={EVENT_STREAMING_PATH}>{t('Event Streaming')}</Link>+ </BreadcrumbLink>+ </BreadcrumbItem>+ <BreadcrumbSeparator />+ <BreadcrumbItem>+ <BreadcrumbPage>+ {isEdit ? t('Edit destination') : t('New destination')}+ </BreadcrumbPage>+ </BreadcrumbItem>+ </BreadcrumbList>+ </Breadcrumb>+ }+ title={isEdit ? t('Edit destination') : t('New destination')}+ footer={+ <>+ <Button+ type="button"+ variant="outline"+ onClick={() => navigate(EVENT_STREAMING_PATH)}+ disabled={isSaving}+ >+ {t('Cancel')}+ </Button>+ <span className="flex-1" />+ <span className="self-center pr-2 text-sm text-gray-11">+ {footerStatus}+ </span>+ {!isEdit && stepIndex > DESTINATION_STEP && (+ <Button+ type="button"+ variant="outline"+ onClick={() => setStepIndex(stepIndex - 1)}+ >+ {t('Back')}+ </Button>+ )}+ {!isEdit && !isLastStep && (+ <Button type="button" onClick={goToNextStep}>+ {t('Continue')}+ </Button>+ )}+ {showSubmit && (+ <Button+ {...adminControl(+ isEdit+ ? AdminControl.EVENT_DESTINATIONS_DESTINATION_UPDATE_SUBMIT+ : AdminControl.EVENT_DESTINATIONS_DESTINATION_CREATE_SUBMIT,+ )}+ type="button"+ loading={isSaving}+ disabled={isSaving}+ onClick={form.handleSubmit(handleSubmit, handleInvalidSubmit)}+ >+ {isEdit ? t('Save changes') : t('Create destination')}+ </Button>+ )}+ </>+ }+ >+ <Form {...form}>+ <form+ className="flex max-w-[50rem] flex-col gap-6"+ onSubmit={(event) => event.preventDefault()}+ >+ <StepHeader+ steps={[+ {+ title: t('Destination'),+ doneTitle: selectedKindTitle,+ },+ { title: t('Events'), doneTitle: t('Events') },+ { title: t('Connection'), doneTitle: t('Connection') },+ ]}+ activeIndex={stepIndex}+ canJump={isEdit}+ onSelect={setStepIndex}+ />+ {stepIndex === DESTINATION_STEP && (+ <DestinationStep form={form} isEdit={isEdit} />+ )}+ {stepIndex === EVENTS_STEP && <EventsStep form={form} />}+ {stepIndex === CONNECTION_STEP && (+ <ConnectionStep+ form={form}+ isEdit={isEdit}+ storedHeaderNames={storedHeaderNames}+ isFormatAutoSwitched={isFormatAutoSwitched}+ />+ )}+ </form>+ </Form>+ <LeaveWithoutSavingDialog+ open={leaveBlocker.state === 'blocked'}+ onKeepEditing={() => leaveBlocker.reset?.()}+ onDiscard={() => leaveBlocker.proceed?.()}+ />+ </CenteredPage>+ );+};++const StepHeader = ({+ steps,+ activeIndex,+ canJump,+ onSelect,+}: {+ steps: { title: string; doneTitle: string }[];+ activeIndex: number;+ canJump: boolean;+ onSelect: (index: number) => void;+}) => {+ return (+ <ol className="flex items-center gap-3">+ {steps.map(({ title, doneTitle }, index) => {+ const isActive = index === activeIndex;+ const isDone = index < activeIndex;+ const isLocked = !canJump && index > activeIndex;+ return (+ <Fragment key={title}>+ <li>+ <button+ type="button"+ disabled={isLocked}+ onClick={() => onSelect(index)}+ aria-current={isActive ? 'step' : undefined}+ className={cn(+ 'flex items-center gap-2 text-sm transition-colors',+ isActive ? 'font-medium text-gray-12' : 'text-gray-11',+ !isLocked && 'hover:text-gray-12',+ isLocked && 'cursor-not-allowed',+ )}+ >+ <span+ className={cn(+ 'flex size-6 items-center justify-center rounded-full text-xs',+ isActive && 'bg-accent-9 text-on-accent',+ isDone && 'bg-accent-3 text-accent-11',+ !isActive && !isDone && 'border',+ )}+ >+ {isDone ? (+ <Check className="size-3.5" strokeWidth={3} />+ ) : (+ index + 1+ )}+ </span>+ <span className={cn(!isActive && 'sr-only sm:not-sr-only')}>+ {isDone ? doneTitle : title}+ </span>+ </button>+ </li>+ {index < steps.length - 1 && (+ <li aria-hidden="true" className="h-px flex-1 bg-gray-6" />+ )}+ </Fragment>+ );+ })}+ </ol>+ );+};++const DESTINATION_STEP = 0;++const EVENTS_STEP = 1;++const CONNECTION_STEP = 2;++const STEP_COUNT = 3;++export default EventDestinationFormPage;diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/open-telemetry-connection.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/open-telemetry-connection.tsxnew file mode 100644index 00000000000..a9067f128ec--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/open-telemetry-connection.tsx@@ -0,0 +1,169 @@+import { isNil, tryCatchSync } from '@activepieces/core-utils';+import { EventDestinationFormat } from '@activepieces/shared';+import { t } from 'i18next';+import { RefObject } from 'react';+import { UseFormReturn, useWatch } from 'react-hook-form';++import { Badge } from '@/components/ui/badge';+import {+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from '@/components/ui/form';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';++import {+ destinationFormUtils,+ DestinationFormValues,+} from '../lib/destination-form-utils';++import { EncryptedHeadersNotice, HeadersField } from './connection-fields';+import { TestEventCard } from './test-event-card';++export const OpenTelemetryConnection = ({+ form,+ storedHeaderNames,+ isFormatAutoSwitched,+}: {+ form: UseFormReturn<DestinationFormValues>;+ storedHeaderNames: string[];+ isFormatAutoSwitched: RefObject<boolean>;+}) => {+ const url = useWatch({ control: form.control, name: 'url' });+ const isWebhookUrl = destinationFormUtils.isWebhookUrl(url);++ return (+ <div className="flex flex-col gap-6">+ <FormField+ control={form.control}+ name="url"+ rules={{ deps: ['headers'] }}+ render={({ field }) => (+ <FormItem>+ <FormLabel showRequiredIndicator>{t('Endpoint URL')}</FormLabel>+ <FormControl>+ <Input+ className="font-mono"+ placeholder="https://otlp.datadoghq.com/v1/logs"+ {...field}+ onChange={(event) => {+ field.onChange(event);+ const currentFormat = form.getValues('format');+ const next = destinationFormUtils.resolveOtlpFormat({+ url: event.target.value,+ format: currentFormat,+ isAutoSwitched: isFormatAutoSwitched.current,+ });+ isFormatAutoSwitched.current = next.isAutoSwitched;+ if (next.format !== currentFormat) {+ form.setValue('format', next.format, {+ shouldDirty: true,+ });+ }+ }}+ />+ </FormControl>+ <FormDescription>+ {t("Paste your tool's full OTLP logs URL.")}+ </FormDescription>+ {isWebhookUrl && (+ <p className="text-xs text-warning-11">+ {t(+ 'This URL is a flow webhook, which accepts only JSON, so Protobuf is off. A generated handler flow reads Raw JSON: to use one, send to a webhook instead.',+ )}+ </p>+ )}+ {!isWebhookUrl && !isLogsEndpoint(url) && (+ <p className="text-xs text-warning-11">+ {t(+ 'This URL does not end in /logs. An OTLP receiver expects the full logs URL.',+ )}+ </p>+ )}+ <FormMessage />+ </FormItem>+ )}+ />++ <HeadersField+ form={form}+ storedHeaderNames={storedHeaderNames}+ keyPlaceholder="DD-API-KEY"+ />++ <FormField+ control={form.control}+ name="format"+ render={({ field }) => (+ <FormItem className="flex flex-col gap-2.5">+ <div className="flex flex-col gap-0.5">+ <FormLabel>{t('Encoding')}</FormLabel>+ <FormDescription>+ {t("Check your tool's docs if you're not sure.")}+ </FormDescription>+ </div>+ <RadioGroup+ className="flex gap-6"+ value={field.value}+ onValueChange={(value) => {+ const encoding = OTLP_FORMATS.find(+ (candidate) => candidate === value,+ );+ if (!isNil(encoding)) {+ isFormatAutoSwitched.current = false;+ field.onChange(encoding);+ }+ }}+ >+ <div className="flex items-center gap-2">+ <RadioGroupItem+ id="otlp-protobuf"+ value={EventDestinationFormat.OTLP_PROTOBUF}+ disabled={isWebhookUrl}+ />+ <Label htmlFor="otlp-protobuf" className="font-normal">+ {t('Protobuf')}+ </Label>+ <Badge className="rounded-md">{t('Recommended')}</Badge>+ </div>+ <div className="flex items-center gap-2">+ <RadioGroupItem+ id="otlp-json"+ value={EventDestinationFormat.OTLP_JSON}+ />+ <Label htmlFor="otlp-json" className="font-normal">+ {t('JSON')}+ </Label>+ </div>+ </RadioGroup>+ </FormItem>+ )}+ />++ <EncryptedHeadersNotice />++ <TestEventCard+ form={form}+ description={t(+ 'Sends one of your selected events to the endpoint above. Shown as JSON; Protobuf sends the same content as binary.',+ )}+ storedHeaderNames={storedHeaderNames}+ />+ </div>+ );+};++function isLogsEndpoint(url: string): boolean {+ const { data: parsed } = tryCatchSync(() => new URL(url));+ return isNil(parsed) || parsed.pathname.replace(/\/+$/, '').endsWith('/logs');+}++const OTLP_FORMATS = [+ EventDestinationFormat.OTLP_PROTOBUF,+ EventDestinationFormat.OTLP_JSON,+];diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/test-event-card.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/test-event-card.tsxnew file mode 100644index 00000000000..d13360a130b--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/test-event-card.tsx@@ -0,0 +1,197 @@+import { isNil } from '@activepieces/core-utils';+import {+ ApEdition,+ ApFlagId,+ ApplicationEventName,+} from '@activepieces/shared';+import { t } from 'i18next';+import { Send } from 'lucide-react';+import { useState } from 'react';+import { UseFormReturn, useFormState, useWatch } from 'react-hook-form';++import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@/components/ui/select';+import { flagsHooks } from '@/hooks/flags-hooks';+import { AdminControl, adminControl } from '@/lib/admin-control';++import { destinationErrors } from '../lib/destination-errors';+import { destinationFormUtils } from '../lib/destination-form-utils';+import type { DestinationFormValues } from '../lib/destination-form-utils';+import { eventDestinationsCollectionUtils } from '../lib/event-destinations-collection';+import { buildEventLabels } from '../lib/event-labels';++export const TestEventCard = ({+ form,+ description,+ storedHeaderNames,+}: {+ form: UseFormReturn<DestinationFormValues>;+ description: string;+ storedHeaderNames: string[];+}) => {+ const eventLabels = buildEventLabels();+ const { data: edition } = flagsHooks.useFlag<ApEdition>(ApFlagId.EDITION);+ const url = useWatch({ control: form.control, name: 'url' });+ const events = useWatch({ control: form.control, name: 'events' });+ const headers = useWatch({ control: form.control, name: 'headers' });+ const format = useWatch({ control: form.control, name: 'format' });+ const { errors } = useFormState({ control: form.control, name: 'url' });+ const [chosenEvent, setChosenEvent] = useState<ApplicationEventName | null>(+ null,+ );++ const {+ mutate: sendTestEvent,+ data: testResult,+ error: testError,+ variables: sentRequest,+ isPending: isTesting,+ } = eventDestinationsCollectionUtils.useTestEventDestination();++ const activeEvent =+ !isNil(chosenEvent) && events.includes(chosenEvent)+ ? chosenEvent+ : events[0];+ const currentRequest = isNil(activeEvent)+ ? null+ : destinationFormUtils.toTestRequest({+ url,+ event: activeEvent,+ headers,+ format,+ });+ const isCurrent =+ !isNil(sentRequest) &&+ !isNil(currentRequest) &&+ destinationFormUtils.isSameTestRequest({+ sent: sentRequest,+ current: currentRequest,+ });+ const headerBlocker = destinationFormUtils.findTestHeaderBlocker({+ headers,+ storedHeaderNames,+ });+ const isSendDisabled =+ isTesting ||+ isNil(currentRequest) ||+ url === '' ||+ !isNil(errors.url) ||+ !isNil(headerBlocker);++ return (+ <div className="flex flex-col gap-3 rounded-lg border p-4">+ <div className="flex flex-col gap-0.5">+ <span className="text-sm font-medium">{t('Send test event')}</span>+ <span className="text-sm text-gray-11">{description}</span>+ </div>+ <div className="flex gap-2">+ <Select+ value={activeEvent ?? ''}+ onValueChange={(value) =>+ setChosenEvent(events.find((event) => event === value) ?? null)+ }+ disabled={events.length === 0}+ >+ <SelectTrigger className="flex-1">+ <SelectValue placeholder={t('Choose an event')} />+ </SelectTrigger>+ <SelectContent>+ {events.map((event) => (+ <SelectItem key={event} value={event}>+ {eventLabels[event]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Button+ {...adminControl(AdminControl.EVENT_DESTINATIONS_WEBHOOK_TEST_RUN)}+ type="button"+ variant="outline"+ disabled={isSendDisabled}+ loading={isTesting}+ onClick={() => {+ if (isNil(currentRequest)) {+ return;+ }+ sendTestEvent(currentRequest);+ }}+ >+ <Send className="size-4" />+ {t('Send test event')}+ </Button>+ </div>++ {!isNil(headerBlocker) && (+ <p className="text-xs text-gray-11">+ {headerBlocker === 'blankValue'+ ? t(+ 'Retype your header values to send a test. Saved values are never sent back.',+ )+ : t('Fix the header errors above to send a test.')}+ </p>+ )}++ {isCurrent && !isNil(testError) && (+ <div className="flex flex-col gap-2 border-t pt-3">+ <Badge className="self-start rounded-md" variant="destructive">+ {t('Failed')}+ </Badge>+ <p className="text-xs text-danger-11">+ {destinationErrors.describe(testError)}+ </p>+ </div>+ )}++ {isCurrent && !isNil(testResult) && (+ <div className="flex flex-col gap-2 border-t pt-3">+ <div className="flex items-center gap-2.5">+ {!isNil(testResult.status) && (+ <Badge+ className="rounded-md"+ variant={+ testResult.status < SUCCESS_STATUS_CEILING+ ? 'success'+ : 'destructive'+ }+ >+ <span className="size-1.5 rounded-full bg-current" />+ {testResult.status}+ </Badge>+ )}+ {!isNil(testResult.errorCode) && (+ <Badge className="rounded-md" variant="destructive">+ {t('Failed')}+ </Badge>+ )}+ <span className="text-sm text-gray-11">+ {t('{duration} ms', { duration: testResult.durationMs })}+ </span>+ </div>+ {!isNil(testResult.errorCode) && (+ <p className="text-xs text-danger-11">+ {destinationErrors.describeTestError({+ code: testResult.errorCode,+ isCloud: edition === ApEdition.CLOUD,+ })}+ </p>+ )}+ <span className="text-xs font-medium text-gray-11">+ {t('Body sent')}+ </span>+ <pre className="max-h-40 overflow-auto rounded-md border bg-gray-2 px-4 py-3 font-mono text-xs leading-relaxed text-gray-11">+ {JSON.stringify(testResult.renderedBody, null, 2)}+ </pre>+ </div>+ )}+ </div>+ );+};++const SUCCESS_STATUS_CEILING = 300;diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/webhook-connection.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/webhook-connection.tsxnew file mode 100644index 00000000000..c379e32547d--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/destination-form/webhook-connection.tsx@@ -0,0 +1,281 @@+import { isNil } from '@activepieces/core-utils';+import { ApFlagId, ApplicationEventName } from '@activepieces/shared';+import { t } from 'i18next';+import { ExternalLink, Info, Plus, Workflow } from 'lucide-react';+import { UseFormReturn, useWatch } from 'react-hook-form';+import { toast } from 'sonner';++import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';+import { Badge } from '@/components/ui/badge';+import { Button } from '@/components/ui/button';+import {+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from '@/components/ui/form';+import { Input } from '@/components/ui/input';+import { HorizontalSeparatorWithText } from '@/components/ui/separator';+import { flowHooks } from '@/features/flows';+import { flagsHooks } from '@/hooks/flags-hooks';+import { AdminControl, adminControl } from '@/lib/admin-control';+import { api } from '@/lib/api';++import { destinationErrors } from '../lib/destination-errors';+import {+ destinationFormUtils,+ DestinationFormValues,+} from '../lib/destination-form-utils';+import { eventDestinationsCollectionUtils } from '../lib/event-destinations-collection';+import { buildEventLabels } from '../lib/event-labels';+import { handlerFlowBuilder } from '../lib/handler-flow-builder';++import { EncryptedHeadersNotice, HeadersField } from './connection-fields';+import { TestEventCard } from './test-event-card';++export const WebhookConnection = ({+ form,+ isEdit,+ storedHeaderNames,+}: {+ form: UseFormReturn<DestinationFormValues>;+ isEdit: boolean;+ storedHeaderNames: string[];+}) => {+ const url = useWatch({ control: form.control, name: 'url' });+ const { data: webhookPrefixUrl } = flagsHooks.useFlag<string>(+ ApFlagId.WEBHOOK_URL_PREFIX,+ );+ const handlerFlowId = destinationFormUtils.toHandlerFlowId({+ url,+ webhookPrefixUrl: webhookPrefixUrl ?? null,+ });+ const isHandlerFlow = !isNil(handlerFlowId);++ return (+ <div className="flex flex-col gap-6">+ {!isEdit && !isHandlerFlow && (+ <>+ <GenerateHandlerFlowCard+ form={form}+ webhookPrefixUrl={webhookPrefixUrl ?? null}+ />+ <HorizontalSeparatorWithText className="text-gray-11">+ {t('or')}+ </HorizontalSeparatorWithText>+ </>+ )}++ <FormField+ control={form.control}+ name="url"+ rules={{ deps: ['headers'] }}+ render={({ field }) => (+ <FormItem>+ <FormLabel showRequiredIndicator>+ {isEdit || isHandlerFlow+ ? t('Endpoint URL')+ : t('Use your own webhook URL')}+ </FormLabel>+ <FormControl>+ <Input placeholder="https://" {...field} />+ </FormControl>+ {url === '' && (+ <FormDescription>+ {t(+ 'Any endpoint that accepts a JSON POST. Headers and a test send appear after you paste a URL.',+ )}+ </FormDescription>+ )}+ <FormMessage />+ </FormItem>+ )}+ />++ {isHandlerFlow && (+ <>+ <HandlerFlowCard flowId={handlerFlowId} />+ <Alert>+ <Info className="size-4" />+ <AlertTitle>+ {isEdit+ ? t('Keep this flow published so it receives events')+ : t('Publish the flow before you create the destination')}+ </AlertTitle>+ <AlertDescription>+ {t(+ 'The flow receives each selected event as a plain JSON object.',+ )}+ </AlertDescription>+ </Alert>+ </>+ )}++ {url !== '' && (+ <>+ <HeadersField+ form={form}+ storedHeaderNames={storedHeaderNames}+ keyPlaceholder="Authorization"+ />+ <EncryptedHeadersNotice />+ <TestEventCard+ form={form}+ description={+ isHandlerFlow+ ? t(+ 'Sends a sample to the handler flow, which runs it like any other event. Publish the flow first, or the test answers 404.',+ )+ : t('Sends one of your selected events to the endpoint above.')+ }+ storedHeaderNames={storedHeaderNames}+ />+ </>+ )}+ </div>+ );+};++const GenerateHandlerFlowCard = ({+ form,+ webhookPrefixUrl,+}: {+ form: UseFormReturn<DestinationFormValues>;+ webhookPrefixUrl: string | null;+}) => {+ const eventLabels = buildEventLabels();+ const selectedEvents = useWatch({ control: form.control, name: 'events' });++ const { mutate: importHandlerFlow, isPending: isImporting } =+ eventDestinationsCollectionUtils.useImportHandlerFlow({+ onSuccess: (createdFlow) => {+ form.setValue('url', `${webhookPrefixUrl}/${createdFlow.id}`, {+ shouldValidate: true,+ shouldDirty: true,+ });+ },+ onError: (error) => {+ toast.error(t('Error'), {+ description: api.isError(error)+ ? destinationErrors.describe(error)+ : error.message,+ });+ },+ });++ const handleGenerate = () => {+ if (isNil(webhookPrefixUrl) || webhookPrefixUrl === '') {+ toast.error(t('Webhook URL prefix is not configured.'));+ return;+ }+ importHandlerFlow({+ template: handlerFlowBuilder.buildHandlerFlowTemplate({+ events: selectedEvents.map((name) => ({+ name,+ label: eventLabels[name],+ })),+ labels: handlerFlowLabels({ selectedEvents, eventLabels }),+ }),+ selectedEvents,+ });+ };++ return (+ <div className="flex flex-col items-center gap-3 rounded-lg border p-6 text-center">+ <span className="flex size-10 items-center justify-center rounded-lg bg-accent-3 text-accent-11">+ <Workflow className="size-[18px]" />+ </span>+ <div className="flex max-w-[460px] flex-col gap-1">+ <span className="text-sm font-medium">+ {t('Create a handler flow')}+ </span>+ <span className="text-sm leading-normal text-gray-11">+ {t(+ "We'll create a flow with a webhook trigger, loaded with sample data for {count, plural, =1 {the event} other {the # events}} you picked. Add steps for Slack, Gmail, or any app.",+ { count: selectedEvents.length },+ )}+ </span>+ </div>+ <Button+ {...adminControl(AdminControl.EVENT_DESTINATIONS_HANDLER_FLOW_RUN)}+ type="button"+ onClick={handleGenerate}+ disabled={isImporting || selectedEvents.length === 0}+ loading={isImporting}+ >+ <Plus className="size-4" />+ {t('Generate handler flow')}+ </Button>+ </div>+ );+};++const HandlerFlowCard = ({ flowId }: { flowId: string }) => {+ const { data: flow } = flowHooks.useGetFlow({ flowId });++ return (+ <div className="flex w-full items-center gap-3 rounded-lg border p-4">+ <span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-accent-3 text-accent-11">+ <Workflow className="size-4" />+ </span>+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">+ <span className="truncate text-sm font-medium">+ {flow?.version.displayName ?? t('Handler flow')}+ </span>+ </div>+ {!isNil(flow) && (+ <Badge+ className="rounded-md"+ variant={isNil(flow.publishedVersionId) ? 'warning' : 'success'}+ >+ {isNil(flow.publishedVersionId) ? t('Draft') : t('Published')}+ </Badge>+ )}+ <Button+ {...adminControl(AdminControl.EVENT_DESTINATIONS_HANDLER_FLOW_LINK)}+ type="button"+ variant="outline"+ size="sm"+ asChild+ >+ <a href={`/flows/${flowId}`} target="_blank" rel="noopener noreferrer">+ {t('Open flow')}+ <ExternalLink className="size-3.5" />+ </a>+ </Button>+ </div>+ );+};++function handlerFlowLabels({+ selectedEvents,+ eventLabels,+}: {+ selectedEvents: ApplicationEventName[];+ eventLabels: ReturnType<typeof buildEventLabels>;+}) {+ return {+ flowDisplayName: t('Event handler starter'),+ flowDescription: t(+ 'Routes audit events into branches you can wire to Slack, Gmail, Teams, or any HTTP endpoint.',+ ),+ webhookTriggerDisplayName: t('Catch Webhook'),+ eventTypeRouterDisplayName: t('Event type checker'),+ runStatusRouterDisplayName: t('Run status check'),+ failedRunBranchName: t('Failed run'),+ otherwiseBranchName: t('Otherwise'),+ noteContent: t(+ '**Audit event handler**\n\nThis flow runs whenever any of these events fire:\n\n{events}\n\n**Add your channel** (Slack, Gmail, Teams, HTTP…) inside each branch below.\n\nOnce you are done:\n\n1. **Publish this flow** so it can receive events.\n2. Head back to the **Event Streaming** tab and create the destination to start sending events here.',+ {+ events: selectedEvents+ .map((name) => `- ${eventLabels[name]}`)+ .join('\n'),+ },+ ),+ sampleDataNoteContent: t(+ '**Test different scenarios**\n\nOpen the trigger and edit its **Sample Data** to swap in a different event payload and test each branch without firing real audit events.',+ ),+ };+}diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/index.tsx b/packages/web/src/app/routes/platform/infra/event-destinations/index.tsxindex 88336cd0b5b..3e6e6990b1d 100644--- a/packages/web/src/app/routes/platform/infra/event-destinations/index.tsx+++ b/packages/web/src/app/routes/platform/infra/event-destinations/index.tsx@@ -1,32 +1,51 @@-import { ApFlagId } from '@activepieces/shared';+import {+ isNil,+ tryCatch,+ tryCatchSync,+ unique,+} from '@activepieces/core-utils';+import { ApFlagId, EventDestination } from '@activepieces/shared';import { useQueries } from '@tanstack/react-query';+import { ColumnDef } from '@tanstack/react-table';import { t } from 'i18next';-import { Workflow } from 'lucide-react';-import { useMemo } from 'react';+import { Globe, ListChecks, Radio } from 'lucide-react';+import { useCallback, useMemo } from 'react';+import { Link, useNavigate } from 'react-router-dom';+import { toast } from 'sonner';-import { CenteredPage } from '@/app/components/centered-page';+import { DashboardPageHeader } from '@/app/components/dashboard-page-header';import { AnimatedIconButton } from '@/components/custom/animated-icon-button';+import { DataTable, RowDataWithActions } from '@/components/custom/data-table';+import { DataTableColumnHeader } from '@/components/custom/data-table/data-table-column-header';+import { TextWithTooltip } from '@/components/custom/text-with-tooltip';import { PlusIcon } from '@/components/icons/plus';-import { ItemGroup } from '@/components/ui/item';-import { SkeletonList } from '@/components/ui/skeleton';-import { flowsApi } from '@/features/flows';+import { Switch } from '@/components/ui/switch';+import { flowHooks, flowsApi } from '@/features/flows';import { flagsHooks } from '@/hooks/flags-hooks';import { platformHooks } from '@/hooks/platform-hooks';import { AdminControl, adminControl } from '@/lib/admin-control';+import { useNewWindow } from '@/lib/navigation-utils';import { sampleData } from '../../sample-data';-import { EventDestinationDialog } from './components/event-destination-dialog';-import { EventDestinationRow } from './components/event-destination-row';+import { DestinationStartCards } from './components/destination-start-cards';+import EventDestinationActions from './components/event-destination-actions';+import { destinationErrors } from './lib/destination-errors';import { eventDestinationsCollectionUtils } from './lib/event-destinations-collection';+import { eventGroupUtils } from './lib/event-groups';+import { EVENT_STREAMING_PATH } from './lib/event-streaming-path';import { parseFlowIdFromUrl } from './lib/parse-flow-id-from-url';-import { useEventLabels } from './lib/use-event-labels';const EventDestinationsPage = () => {+ const navigate = useNavigate();+ const openNewWindow = useNewWindow();const { platform } = platformHooks.useCurrentPlatform();const isEnabled = platform.plan.eventStreamingEnabled;- const { data: liveDestinations, isLoading } =- eventDestinationsCollectionUtils.useAll(isEnabled);+ const {+ data: liveDestinations,+ isLoading,+ isError,+ } = eventDestinationsCollectionUtils.useAll(isEnabled);const isSample = !isEnabled;const destinations = isSample? sampleData.eventDestinations()@@ -34,105 +53,208 @@ const EventDestinationsPage = () => {const { data: webhookPrefixUrl } = flagsHooks.useFlag<string>(ApFlagId.WEBHOOK_URL_PREFIX,);- const eventLabels = useEventLabels();-- const parsedDestinations = useMemo(- () =>- destinations.map((destination) => ({- destination,- parsed: parseFlowIdFromUrl({- url: destination.url,- webhookPrefixUrl: webhookPrefixUrl ?? null,- }),- })),- [destinations, webhookPrefixUrl],- );+ const totalEventCount = eventGroupUtils.countEvents();const flowIds = useMemo(() =>- Array.from(- new Set(- parsedDestinations- .map(({ parsed }) =>- parsed.kind === 'flow' ? parsed.flowId : null,- )- .filter((id): id is string => id !== null),- ),+ unique(+ destinations.flatMap((destination) => {+ const parsed = parseFlowIdFromUrl({+ url: destination.url,+ webhookPrefixUrl: webhookPrefixUrl ?? null,+ });+ return parsed.kind === 'flow' ? [parsed.flowId] : [];+ }),),- [parsedDestinations],+ [destinations, webhookPrefixUrl],);const flowQueries = useQueries({queries: flowIds.map((flowId) => ({- queryKey: ['flow-display-name', flowId],- queryFn: () => flowsApi.get(flowId),+ queryKey: flowHooks.createFlowQueryKeys({ flowId, versionId: undefined }),+ queryFn: () => flowsApi.get(flowId).catch(() => null),})),});const flowDisplayNameById = useMemo(() => {- const map = new Map<string, string>();- flowQueries.forEach((query, index) => {- const flow = query.data;- if (flow) {- map.set(flowIds[index], flow.version.displayName);- }- });- return map;+ const entries = flowQueries+ .map((query, index): [string, string] | null =>+ query.data ? [flowIds[index], query.data.version.displayName] : null,+ )+ .filter((entry): entry is [string, string] => entry !== null);+ return new Map(entries);}, [flowQueries, flowIds]);- return (- <CenteredPage- title={t('Event Streaming')}- description={t(- 'Send a webhook for every audit event and build fully customizable alerts on top.',- )}- actions={- <EventDestinationDialog destination={null}>- <AnimatedIconButton- {...adminControl(- AdminControl.EVENT_DESTINATIONS_DESTINATION_NEW_OPEN,- )}- icon={PlusIcon}- iconSize={16}- size="sm"- >- {t('New Destination')}- </AnimatedIconButton>- </EventDestinationDialog>+ const destinationTitle = useCallback(+ (destination: EventDestination) => {+ const parsed = parseFlowIdFromUrl({+ url: destination.url,+ webhookPrefixUrl: webhookPrefixUrl ?? null,+ });+ if (parsed.kind === 'flow') {+ return (+ flowDisplayNameById.get(parsed.flowId) ??+ t('Destination (flow {flowId})', { flowId: parsed.flowId })+ );}- >- {isLoading && (- <SkeletonList numberOfItems={3} className="w-full h-[72px]" />- )}+ const { data: url } = tryCatchSync(() => new URL(destination.url));+ return url?.host ?? destination.url;+ },+ [flowDisplayNameById, webhookPrefixUrl],+ );- {!isLoading && parsedDestinations.length === 0 && (- <div className="flex flex-col items-center gap-3 py-12 text-gray-11">- <Workflow className="size-10" />- <p className="text-sm">- {t('No destinations yet. Create one to get started.')}- </p>- </div>- )}+ const columns: ColumnDef<RowDataWithActions<EventDestination>>[] = useMemo(+ () => [+ {+ id: 'destination',+ header: ({ column }) => (+ <DataTableColumnHeader+ column={column}+ title={t('Destination')}+ icon={Globe}+ />+ ),+ cell: ({ row }) => (+ <div className="flex min-w-0 flex-col gap-0.5">+ <TextWithTooltip tooltipMessage={destinationTitle(row.original)}>+ <span className="truncate text-sm font-medium">+ {destinationTitle(row.original)}+ </span>+ </TextWithTooltip>+ <TextWithTooltip tooltipMessage={row.original.url}>+ <span className="truncate font-mono text-xs text-gray-11">+ {row.original.url}+ </span>+ </TextWithTooltip>+ </div>+ ),+ },+ {+ id: 'events',+ size: 120,+ header: ({ column }) => (+ <DataTableColumnHeader+ column={column}+ title={t('Events')}+ icon={ListChecks}+ />+ ),+ cell: ({ row }) => (+ <span className="text-sm text-gray-11">+ {row.original.events.length === totalEventCount+ ? t('All {total}', { total: totalEventCount })+ : t('{count} of {total}', {+ count: row.original.events.length,+ total: totalEventCount,+ })}+ </span>+ ),+ },+ {+ id: 'enabled',+ size: 100,+ notClickable: true,+ header: ({ column }) => (+ <DataTableColumnHeader column={column} title={t('Enabled')} />+ ),+ cell: ({ row }) => (+ <Switch+ checked={row.original.enabled}+ aria-label={t('Enable {destination}', {+ destination: destinationTitle(row.original),+ })}+ onCheckedChange={(enabled) =>+ toggleDestination({ destinationId: row.original.id, enabled })+ }+ />+ ),+ },+ {+ id: 'actions',+ size: 60,+ notClickable: true,+ header: () => null,+ cell: ({ row }) => (+ <EventDestinationActions destination={row.original} />+ ),+ },+ ],+ [destinationTitle, totalEventCount],+ );- {!isLoading && parsedDestinations.length > 0 && (- <ItemGroup className="gap-2">- {parsedDestinations.map(({ destination, parsed }) => (- <EventDestinationRow- key={destination.id}- destination={destination}- parsed={parsed}- flowDisplayName={- parsed.kind === 'flow'- ? flowDisplayNameById.get(parsed.flowId)- : undefined- }- eventLabels={eventLabels}- />- ))}- </ItemGroup>- )}- </CenteredPage>+ return (+ <>+ <DashboardPageHeader+ title={t('Event Streaming')}+ description={t(+ 'Stream every audit event in OpenTelemetry (OTLP) format to Datadog, PostHog, Grafana Loki, or any OTLP backend. Or send it as raw JSON to a webhook or a handler flow.',+ )}+ >+ <AnimatedIconButton+ {...adminControl(+ AdminControl.EVENT_DESTINATIONS_DESTINATION_NEW_OPEN,+ )}+ icon={PlusIcon}+ iconSize={16}+ size="sm"+ asChild+ >+ <Link to={`${EVENT_STREAMING_PATH}/new`}>{t('New Destination')}</Link>+ </AnimatedIconButton>+ </DashboardPageHeader>+ <div className="flex w-full flex-col px-4 pb-6">+ <DataTable+ bordered={true}+ columns={columns}+ page={{ data: destinations, next: null, previous: null }}+ isLoading={isLoading}+ isError={isError}+ errorStateEntity={t('destinations')}+ onRetry={eventDestinationsCollectionUtils.refetch}+ hidePagination={true}+ onRowClick={(row, newWindow) =>+ newWindow+ ? openNewWindow(`${EVENT_STREAMING_PATH}/${row.id}`)+ : navigate(`${EVENT_STREAMING_PATH}/${row.id}`)+ }+ toolbarButtons={[+ <span key="count" className="shrink-0 text-xs text-gray-11">+ {t('destinationsCount', { count: destinations.length })}+ </span>,+ ]}+ emptyStateTextTitle={t('No destinations yet')}+ emptyStateTextDescription={t(+ 'Stream every audit event on your platform over OpenTelemetry (OTLP), or send it to a flow.',+ )}+ emptyStateIcon={+ <span className="mb-1 mt-10 flex size-11 items-center justify-center rounded-lg bg-gray-3">+ <Radio className="size-5" />+ </span>+ }+ emptyStateAction={<DestinationStartCards />}+ />+ </div>+ </>);};+async function toggleDestination({+ destinationId,+ enabled,+}: {+ destinationId: string;+ enabled: boolean;+}): Promise<void> {+ const { error } = await tryCatch(+ () =>+ eventDestinationsCollectionUtils.update({+ destinationId,+ request: { enabled },+ }).isPersisted.promise,+ );+ if (!isNil(error)) {+ toast.error(destinationErrors.describe(error));+ }+}+export default EventDestinationsPage;diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/lib/destination-errors.ts b/packages/web/src/app/routes/platform/infra/event-destinations/lib/destination-errors.tsnew file mode 100644index 00000000000..081033835f4--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/lib/destination-errors.ts@@ -0,0 +1,63 @@+import { ErrorCode } from '@activepieces/core-utils';+import { EventDestinationTestError } from '@activepieces/shared';+import { t } from 'i18next';++import { api } from '@/lib/api';++function describe(error: unknown): string {+ if (+ api.isApError(+ error,+ ErrorCode.EVENT_DESTINATION_URL_CHANGE_REQUIRES_HEADERS,+ )+ ) {+ return t(+ 'Re-enter every saved header value to change the URL. If someone else changed this destination, reload the page first.',+ );+ }+ if (+ api.isApError(+ error,+ ErrorCode.EVENT_DESTINATION_FORMAT_NOT_SUPPORTED_BY_WEBHOOK,+ )+ ) {+ return t(+ 'A flow webhook accepts only JSON. Choose the JSON encoding, or send to a webhook instead.',+ );+ }+ return api.serverErrorMessage(error) ?? t('Something went wrong');+}++function describeTestError({+ code,+ isCloud,+}: {+ code: EventDestinationTestError;+ isCloud: boolean;+}): string {+ switch (code) {+ case EventDestinationTestError.BLOCKED:+ return isCloud+ ? t(+ 'This URL points to a private or internal address, so the test was not sent.',+ )+ : t(+ 'This URL points to a private or internal address, so the test was not sent. To allow it, add the address to AP_SSRF_ALLOW_LIST on the server and restart the server.',+ );+ case EventDestinationTestError.TIMEOUT:+ return t('The destination did not answer in time.');+ case EventDestinationTestError.TLS:+ return t(+ 'The secure connection failed. Check the TLS certificate of the destination.',+ );+ case EventDestinationTestError.CONNECTION_FAILED:+ return t('Could not connect to the destination. Check the URL.');+ case EventDestinationTestError.HANDLER_FLOW_FAILED:+ return t('The handler flow could not take the event.');+ }+}++export const destinationErrors = {+ describe,+ describeTestError,+};diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/lib/destination-form-utils.ts b/packages/web/src/app/routes/platform/infra/event-destinations/lib/destination-form-utils.tsnew file mode 100644index 00000000000..fd97c13c547--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/lib/destination-form-utils.ts@@ -0,0 +1,342 @@+import { ApId, isNil, tryCatchSync } from '@activepieces/core-utils';+import {+ ApplicationEventName,+ CreatePlatformEventDestinationRequestBody,+ EventDestination,+ EventDestinationFormat,+ EventDestinationHeaders,+ EventDestinationHeadersRequest,+ formErrors,+ TestPlatformEventDestinationRequestBody,+} from '@activepieces/shared';+import { z } from 'zod';++import { DestinationKind, destinationKinds } from './destination-kinds';+import { parseFlowIdFromUrl } from './parse-flow-id-from-url';++function toDefaultValues({+ destination,+ kind,+}: {+ destination: EventDestination | null;+ kind: DestinationKind;+}): DestinationFormValues {+ return {+ url: destination?.url ?? '',+ events: inCanonicalOrder(destination?.events ?? []),+ headers: toHeaderRows(destination?.headers),+ format: destination?.format ?? destinationKinds.defaultFormatOf(kind),+ };+}++function inCanonicalOrder(+ events: ApplicationEventName[],+): ApplicationEventName[] {+ return ALL_EVENT_NAMES.filter((event) => events.includes(event));+}++function toHeaderRows(+ headers: EventDestinationHeadersRequest | null | undefined,+): HeaderRow[] {+ if (isNil(headers)) {+ return [];+ }+ return Object.keys(headers)+ .sort((first, second) => first.localeCompare(second))+ .map((name) => ({ name, value: '' }));+}++function toHeaderRequest(rows: HeaderRow[]): EventDestinationHeadersRequest {+ return Object.fromEntries(+ rows+ .filter((row) => row.name !== '')+ .map((row) => [row.name, row.value === '' ? null : row.value]),+ );+}++function toTestHeaders(rows: HeaderRow[]): EventDestinationHeaders {+ return Object.fromEntries(+ rows+ .filter((row) => row.name !== '' && row.value !== '')+ .map((row) => [row.name, row.value]),+ );+}++function hasBlankHeaderValue(rows: HeaderRow[]): boolean {+ return rows.some((row) => row.name !== '' && row.value === '');+}++function findTestHeaderBlocker({+ headers,+ storedHeaderNames,+}: {+ headers: HeaderRow[];+ storedHeaderNames: string[];+}): TestHeaderBlocker | null {+ const issues = findHeaderIssues({+ headers,+ storedHeaderNames,+ isUrlChanged: false,+ });+ if (issues.length > 0) {+ return 'invalidHeader';+ }+ return hasBlankHeaderValue(headers) ? 'blankValue' : null;+}++function toTestRequest({+ url,+ event,+ headers,+ format,+}: {+ url: string;+ event: ApplicationEventName;+ headers: HeaderRow[];+ format: EventDestinationFormat;+}): TestPlatformEventDestinationRequestBody {+ return { url, event, headers: toTestHeaders(headers), format };+}++function isSameTestRequest({+ sent,+ current,+}: {+ sent: TestPlatformEventDestinationRequestBody;+ current: TestPlatformEventDestinationRequestBody;+}): boolean {+ const sentHeaders = sent.headers ?? {};+ const currentHeaders = current.headers ?? {};+ const sentNames = Object.keys(sentHeaders);+ return (+ sent.url === current.url &&+ sent.event === current.event &&+ sent.format === current.format &&+ sentNames.length === Object.keys(currentHeaders).length &&+ sentNames.every((name) => currentHeaders[name] === sentHeaders[name])+ );+}++function findHeaderIssues({+ headers,+ storedHeaderNames,+ isUrlChanged,+}: {+ headers: HeaderRow[];+ storedHeaderNames: string[];+ isUrlChanged: boolean;+}): HeaderIssue[] {+ const storedLowerCaseNames = new Set(+ storedHeaderNames.map((name) => name.toLowerCase()),+ );+ const lowerCaseNames = headers+ .filter((row) => row.name !== '')+ .map((row) => row.name.toLowerCase());+ return headers.flatMap((row, index) => {+ const lowerCaseName = row.name.toLowerCase();+ const nameMessage = findNameIssue({+ row,+ isDuplicate:+ lowerCaseNames.filter((name) => name === lowerCaseName).length > 1,+ });+ const valueMessage = findValueIssue({+ row,+ isStored: storedLowerCaseNames.has(lowerCaseName),+ isUrlChanged,+ });+ const nameIssues: HeaderIssue[] = isNil(nameMessage)+ ? []+ : [{ index, field: 'name', message: nameMessage }];+ const valueIssues: HeaderIssue[] = isNil(valueMessage)+ ? []+ : [{ index, field: 'value', message: valueMessage }];+ return [...nameIssues, ...valueIssues];+ });+}++function buildFormSchema({+ storedHeaderNames,+ storedUrl,+}: {+ storedHeaderNames: string[];+ storedUrl: string | null;+}) {+ return z+ .object({+ url: z+ .string()+ .min(1, 'Endpoint URL is required')+ .pipe(z.url('Invalid URL')),+ events: z+ .array(z.enum(ApplicationEventName))+ .min(1, 'Select at least one event'),+ headers: z.array(z.object({ name: z.string(), value: z.string() })),+ format: z.enum(EventDestinationFormat),+ })+ .superRefine((values, ctx) => {+ findHeaderIssues({+ headers: values.headers,+ storedHeaderNames,+ isUrlChanged: !isNil(storedUrl) && values.url !== storedUrl,+ }).forEach(({ index, field, message }) => {+ ctx.addIssue({+ code: 'custom',+ path: ['headers', index, field],+ message,+ });+ });+ });+}++function toRequest(+ values: DestinationFormValues,+): CreatePlatformEventDestinationRequestBody {+ return {+ url: values.url,+ events: values.events,+ headers: toHeaderRequest(values.headers),+ format: values.format,+ };+}++function isWebhookUrl(url: string): boolean {+ const { data: parsed } = tryCatchSync(() => new URL(url));+ if (isNil(parsed)) {+ return false;+ }+ const markerIndex = parsed.pathname.lastIndexOf(WEBHOOK_PATH_MARKER);+ if (markerIndex === -1) {+ return false;+ }+ const flowId = parsed.pathname+ .slice(markerIndex + WEBHOOK_PATH_MARKER.length)+ .split('/')[0];+ return flowId.length > 0;+}++function resolveOtlpFormat({+ url,+ format,+ isAutoSwitched,+}: OtlpFormatChoice & { url: string }): OtlpFormatChoice {+ const isWebhook = isWebhookUrl(url);+ if (isWebhook && format === EventDestinationFormat.OTLP_PROTOBUF) {+ return { format: EventDestinationFormat.OTLP_JSON, isAutoSwitched: true };+ }+ if (+ !isWebhook &&+ isAutoSwitched &&+ format === EventDestinationFormat.OTLP_JSON+ ) {+ return {+ format: EventDestinationFormat.OTLP_PROTOBUF,+ isAutoSwitched: false,+ };+ }+ return { format, isAutoSwitched: isAutoSwitched && isWebhook };+}++function toHandlerFlowId({+ url,+ webhookPrefixUrl,+}: {+ url: string;+ webhookPrefixUrl: string | null;+}): string | null {+ const parsed = parseFlowIdFromUrl({ url, webhookPrefixUrl });+ if (parsed.kind !== 'flow') {+ return null;+ }+ return ApId.safeParse(parsed.flowId).success ? parsed.flowId : null;+}++function findNameIssue({+ row,+ isDuplicate,+}: {+ row: HeaderRow;+ isDuplicate: boolean;+}): string | null {+ if (row.name === '') {+ return row.value === '' ? null : 'Enter a header name';+ }+ const parsed = EventDestinationHeadersRequest.safeParse({ [row.name]: null });+ if (!parsed.success) {+ const issue = parsed.error.issues[0];+ return issue.code === 'invalid_key'+ ? issue.issues[0]?.message ?? issue.message+ : issue.message;+ }+ return isDuplicate ? formErrors.duplicateHeaderName : null;+}++function findValueIssue({+ row,+ isStored,+ isUrlChanged,+}: {+ row: HeaderRow;+ isStored: boolean;+ isUrlChanged: boolean;+}): string | null {+ if (row.name === '') {+ return null;+ }+ if (row.value !== '') {+ const parsed = EventDestinationHeaders.safeParse({+ [VALUE_CHECK_HEADER_NAME]: row.value,+ });+ return parsed.success ? null : parsed.error.issues[0].message;+ }+ if (!isStored) {+ return 'Enter a value for this header';+ }+ return isUrlChanged ? 'Re-enter this value to change the URL' : null;+}++export const destinationFormUtils = {+ toDefaultValues,+ inCanonicalOrder,+ toHeaderRequest,+ toTestHeaders,+ findTestHeaderBlocker,+ toTestRequest,+ isSameTestRequest,+ findHeaderIssues,+ buildFormSchema,+ toRequest,+ isWebhookUrl,+ toHandlerFlowId,+ resolveOtlpFormat,+};++const WEBHOOK_PATH_MARKER = '/v1/webhooks/';++const VALUE_CHECK_HEADER_NAME = 'X-Value-Check';++const ALL_EVENT_NAMES = Object.values(ApplicationEventName);++export type TestHeaderBlocker = 'blankValue' | 'invalidHeader';++export type OtlpFormatChoice = {+ format: EventDestinationFormat;+ isAutoSwitched: boolean;+};++export type HeaderRow = {+ name: string;+ value: string;+};++export type HeaderIssue = {+ index: number;+ field: 'name' | 'value';+ message: string;+};++export type DestinationFormValues = {+ url: string;+ events: ApplicationEventName[];+ headers: HeaderRow[];+ format: EventDestinationFormat;+};diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/lib/destination-kinds.ts b/packages/web/src/app/routes/platform/infra/event-destinations/lib/destination-kinds.tsnew file mode 100644index 00000000000..428da70145e--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/lib/destination-kinds.ts@@ -0,0 +1,64 @@+import { EventDestinationFormat } from '@activepieces/shared';+import { t } from 'i18next';+import { Activity, LucideIcon, Workflow } from 'lucide-react';++function buildOptions(): DestinationKindOption[] {+ return [+ {+ kind: 'otel',+ icon: Activity,+ title: t('Send to an OpenTelemetry tool'),+ shortTitle: t('OpenTelemetry tool'),+ description: t(+ 'Datadog, Grafana, Honeycomb, New Relic, or any OTLP backend. Sent as OTLP log records.',+ ),+ formatLabel: t('Format · OTLP'),+ },+ {+ kind: 'webhook',+ icon: Workflow,+ title: t('Send to a webhook'),+ shortTitle: t('Webhook'),+ description: t(+ 'Any endpoint that accepts JSON. Paste your own URL, or generate a handler flow to route events to Slack, Gmail, or any app.',+ ),+ formatLabel: t('Format · Raw JSON'),+ },+ ];+}++function kindOf(format: EventDestinationFormat): DestinationKind {+ return format === EventDestinationFormat.RAW ? 'webhook' : 'otel';+}++function defaultFormatOf(kind: DestinationKind): EventDestinationFormat {+ return kind === 'webhook'+ ? EventDestinationFormat.RAW+ : EventDestinationFormat.OTLP_PROTOBUF;+}++function parse(value: string | null): DestinationKind | null {+ return DESTINATION_KINDS.find((kind) => kind === value) ?? null;+}++export const destinationKinds = {+ buildOptions,+ kindOf,+ defaultFormatOf,+ parse,+};++const DESTINATION_KINDS: DestinationKind[] = ['otel', 'webhook'];++export const DESTINATION_KIND_SEARCH_PARAM = 'destination';++export type DestinationKind = 'otel' | 'webhook';++export type DestinationKindOption = {+ kind: DestinationKind;+ icon: LucideIcon;+ title: string;+ shortTitle: string;+ description: string;+ formatLabel: string;+};diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-destinations-collection.ts b/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-destinations-collection.tsindex 6135e75d157..9e394f835f4 100644--- a/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-destinations-collection.ts+++ b/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-destinations-collection.ts@@ -1,4 +1,4 @@-import { SeekPage } from '@activepieces/core-utils';+import { isNil, SeekPage } from '@activepieces/core-utils';import {ApplicationEvent,ApplicationEventName,@@ -6,60 +6,51 @@ import {CreatePlatformEventDestinationRequestBody,EventDestination,FlowOperationType,+ ListPlatformEventDestinationsRequestBody,PopulatedFlow,ProjectType,SampleDataFileType,Template,TestPlatformEventDestinationRequestBody,+ TestPlatformEventDestinationResponse,UpdatePlatformEventDestinationRequestBody,} from '@activepieces/shared';import { queryCollectionOptions } from '@tanstack/query-db-collection';import { createCollection, useLiveQuery } from '@tanstack/react-db';-import { QueryClient, useMutation } from '@tanstack/react-query';+import { QueryClient, QueryState, useMutation } from '@tanstack/react-query';import { t } from 'i18next';+import { useEffect, useState, useSyncExternalStore } from 'react';import { flowHooks, flowsApi, triggerEventsApi } from '@/features/flows';import { projectCollectionUtils } from '@/features/projects';import { userHooks } from '@/hooks/user-hooks';import { api } from '@/lib/api';-const collectionQueryClient = new QueryClient();+const collectionQueryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+});++const DESTINATIONS_PAGE_SIZE = 100;++const DESTINATIONS_QUERY_KEY = ['event-destinations'];export const eventDestinationsCollection = createCollection<EventDestination,string>(queryCollectionOptions({- queryKey: ['event-destinations'],+ queryKey: DESTINATIONS_QUERY_KEY,queryClient: collectionQueryClient,- queryFn: async () => {- const response = await api.get<SeekPage<EventDestination>>(- '/v1/event-destinations',- );- return response.data;- },+ queryFn: () => fetchAllDestinations(),getKey: (item) => item.id,onUpdate: async ({ transaction }) => {- for (const { original, modified } of transaction.mutations) {- const request: UpdatePlatformEventDestinationRequestBody = {- url: modified.url,- events: modified.events,- };- await api.patch<EventDestination>(+ for (const { original, changes } of transaction.mutations) {+ await api.post<EventDestination>(`/v1/event-destinations/${original.id}`,- request,+ toUpdateRequestBody(changes),);}},- onInsert: async ({ transaction }) => {- for (const { modified } of transaction.mutations) {- const request: CreatePlatformEventDestinationRequestBody = {- url: modified.url,- events: modified.events,- };- await api.post<EventDestination>('/v1/event-destinations', request);- }- },onDelete: async ({ transaction }) => {for (const { original } of transaction.mutations) {await api.delete<void>(`/v1/event-destinations/${original.id}`);@@ -69,71 +60,88 @@ export const eventDestinationsCollection = createCollection<);export const eventDestinationsCollectionUtils = {- useAll: (enabled: boolean) => {- const queryResult = useLiveQuery(- (q) =>- q- .from({ destination: eventDestinationsCollection })- .select(({ destination }) => ({ ...destination })),- [],+ useAll: (enabled: boolean): LiveDestinations => useLiveDestinations(enabled),++ useFreshDestination: (destinationId: string): FreshDestination => {+ const { data: destinations } = useLiveDestinations(true);+ const queryState = useSyncExternalStore(+ subscribeToDestinationsQuery,+ readDestinationsQueryState,);- if (!enabled) {- return {- data: [],- isLoading: false,- isError: false,- isSuccess: true,- };+ const [countsAtOpen] = useState(() => ({+ data: queryState?.dataUpdateCount ?? 0,+ error: queryState?.errorUpdateCount ?? 0,+ }));+ useEffect(() => {+ eventDestinationsCollection.utils.refetch().catch(() => undefined);+ }, []);+ const dataUpdateCount = queryState?.dataUpdateCount ?? 0;+ if (dataUpdateCount <= countsAtOpen.data) {+ const hasFreshError =+ queryState?.status === 'error' &&+ queryState.errorUpdateCount > countsAtOpen.error;+ return { status: hasFreshError ? 'error' : 'loading' };}- return queryResult;+ const destination = destinations.find(+ (candidate) => candidate.id === destinationId,+ );+ return isNil(destination)+ ? { status: 'missing' }+ : { status: 'ready', destination };},- useCreateEventDestination: (- onSuccess: (destination: EventDestination) => void,- onError: (error: Error) => void,- ) => {+ refetch: () => eventDestinationsCollection.utils.refetch(),++ useSaveEventDestination: ({+ onSuccess,+ onError,+ }: MutationCallbacks<EventDestination>) => {return useMutation({- mutationFn: (request: CreatePlatformEventDestinationRequestBody) =>- api.post<EventDestination>('/v1/event-destinations', request),- onSuccess: (data) => {- eventDestinationsCollection.utils.writeInsert(data);+ mutationFn: ({ destinationId, request }: SaveEventDestinationParams) =>+ api.post<EventDestination>(+ isNil(destinationId)+ ? '/v1/event-destinations'+ : `/v1/event-destinations/${destinationId}`,+ request,+ ),+ onSuccess: async (data) => {+ await applySavedDestination(data).catch(() => undefined);onSuccess(data);},- onError: (error) => {- onError(error);- },+ onError,});},- update: (- destinationId: string,- request: UpdatePlatformEventDestinationRequestBody,- ) => {- return eventDestinationsCollection.update(destinationId, (draft) => {+ update: ({ destinationId, request }: UpdateEventDestinationParams) =>+ eventDestinationsCollection.update(destinationId, (draft) => {Object.assign(draft,Object.fromEntries(Object.entries(request).filter(([_, value]) => value !== undefined),),);- });- },+ }),- delete: (destinationIds: string[]) => {- return eventDestinationsCollection.delete(destinationIds);+ delete: async (destinationIds: string[]) => {+ const transaction = eventDestinationsCollection.delete(destinationIds);+ await transaction.isPersisted.promise;},useTestEventDestination: () => {return useMutation({mutationFn: (request: TestPlatformEventDestinationRequestBody) =>- api.post<void>(`/v1/event-destinations/test`, request),+ api.post<TestPlatformEventDestinationResponse>(+ `/v1/event-destinations/test`,+ request,+ ),+ onError: () => undefined,});},- useImportHandlerFlow: (- onSuccess: (flow: PopulatedFlow) => void,- onError: (error: Error) => void,- ) => {+ useImportHandlerFlow: ({+ onSuccess,+ onError,+ }: MutationCallbacks<PopulatedFlow>) => {const { data: currentUser } = userHooks.useCurrentUser();const { data: allProjects } = projectCollectionUtils.useAll();@@ -195,6 +203,92 @@ export const eventDestinationsCollectionUtils = {},};+async function applySavedDestination(+ destination: EventDestination,+): Promise<void> {+ await eventDestinationsCollection.preload();+ if (readHasLoadFailed()) {+ await eventDestinationsCollection.utils.refetch();+ return;+ }+ eventDestinationsCollection.utils.writeUpsert(destination);+}++function useLiveDestinations(enabled: boolean): LiveDestinations {+ const { data, isLoading } = useLiveQuery(+ (q) =>+ enabled+ ? q+ .from({ destination: eventDestinationsCollection })+ .select(({ destination }) => ({ ...destination }))+ : undefined,+ [enabled],+ );+ const hasLoadFailed = useSyncExternalStore(+ subscribeToDestinationsQuery,+ readHasLoadFailed,+ );+ useEffect(() => {+ if (!enabled) {+ return;+ }+ collectionQueryClient.mount();+ return () => collectionQueryClient.unmount();+ }, [enabled]);+ if (!enabled) {+ return { data: [], isLoading: false, isError: false };+ }+ return { data: data ?? [], isLoading, isError: hasLoadFailed };+}++function subscribeToDestinationsQuery(onChange: () => void): () => void {+ return collectionQueryClient.getQueryCache().subscribe(onChange);+}++function readDestinationsQueryState():+ | QueryState<EventDestination[]>+ | undefined {+ return collectionQueryClient.getQueryState<EventDestination[]>(+ DESTINATIONS_QUERY_KEY,+ );+}++function readHasLoadFailed(): boolean {+ return (+ collectionQueryClient.getQueryState(DESTINATIONS_QUERY_KEY)?.status ===+ 'error'+ );+}++async function fetchAllDestinations(): Promise<EventDestination[]> {+ const destinations: EventDestination[] = [];+ let cursor: string | undefined = undefined;+ do {+ const request: ListPlatformEventDestinationsRequestBody = {+ cursor,+ limit: DESTINATIONS_PAGE_SIZE,+ };+ const page: SeekPage<EventDestination> = await api.get<+ SeekPage<EventDestination>+ >('/v1/event-destinations', request);+ destinations.push(...page.data);+ cursor = page.next ?? undefined;+ } while (!isNil(cursor));+ return destinations;+}++function toUpdateRequestBody(+ changes: Partial<EventDestination>,+): UpdatePlatformEventDestinationRequestBody {+ return {+ url: changes.url,+ events: changes.events,+ enabled: changes.enabled,+ headers: changes.headers,+ format: changes.format,+ };+}+function buildWebhookTriggerPayload(event: ApplicationEvent,): WebhookTriggerPayload {@@ -215,3 +309,30 @@ type WebhookTriggerPayload = {headers: Record<string, string>;queryParams: Record<string, string>;};++export type LiveDestinations = {+ data: EventDestination[];+ isLoading: boolean;+ isError: boolean;+};++export type FreshDestination =+ | { status: 'loading' }+ | { status: 'error' }+ | { status: 'missing' }+ | { status: 'ready'; destination: EventDestination };++export type MutationCallbacks<T> = {+ onSuccess: (result: T) => void;+ onError: (error: Error) => void;+};++export type SaveEventDestinationParams = {+ destinationId: string | null;+ request: CreatePlatformEventDestinationRequestBody;+};++export type UpdateEventDestinationParams = {+ destinationId: string;+ request: UpdatePlatformEventDestinationRequestBody;+};diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-groups.ts b/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-groups.tsnew file mode 100644index 00000000000..487c60661c2--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-groups.ts@@ -0,0 +1,119 @@+import { ApplicationEventName } from '@activepieces/shared';+import { t } from 'i18next';++function buildEventGroups(): EventGroup[] {+ return [+ {+ key: 'flows',+ title: t('Flows'),+ events: [+ ApplicationEventName.FLOW_CREATED,+ ApplicationEventName.FLOW_UPDATED,+ ApplicationEventName.FLOW_DELETED,+ ApplicationEventName.FLOW_PUBLISHED,+ ApplicationEventName.FLOW_ACTIVATED,+ ApplicationEventName.FLOW_DEACTIVATED,+ ApplicationEventName.FLOW_PIECES_UPGRADED,+ ApplicationEventName.FLOW_PIECES_REVERTED,+ ],+ },+ {+ key: 'runs',+ title: t('Runs'),+ events: [+ ApplicationEventName.FLOW_RUN_STARTED,+ ApplicationEventName.FLOW_RUN_FINISHED,+ ApplicationEventName.FLOW_RUN_RESUMED,+ ApplicationEventName.FLOW_RUN_RETRIED,+ ],+ },+ {+ key: 'approvals',+ title: t('Approvals'),+ events: [+ ApplicationEventName.FLOW_APPROVAL_REQUESTED,+ ApplicationEventName.FLOW_APPROVAL_GRANTED,+ ApplicationEventName.FLOW_APPROVAL_REJECTED,+ ApplicationEventName.FLOW_APPROVAL_WITHDRAWN,+ ],+ },+ {+ key: 'agents',+ title: t('Agents'),+ events: [+ ApplicationEventName.AGENT_CREATED,+ ApplicationEventName.AGENT_UPDATED,+ ApplicationEventName.AGENT_DELETED,+ ApplicationEventName.AGENT_PUBLISHED,+ ApplicationEventName.AGENT_UNPUBLISHED,+ ApplicationEventName.AGENT_ACTION_EXECUTED,+ ],+ },+ {+ key: 'folders',+ title: t('Folders'),+ events: [+ ApplicationEventName.FOLDER_CREATED,+ ApplicationEventName.FOLDER_UPDATED,+ ApplicationEventName.FOLDER_DELETED,+ ],+ },+ {+ key: 'connections',+ title: t('Connections'),+ events: [+ ApplicationEventName.CONNECTION_UPSERTED,+ ApplicationEventName.CONNECTION_DELETED,+ ],+ },+ {+ key: 'variables',+ title: t('Variables'),+ events: [+ ApplicationEventName.VARIABLE_UPSERTED,+ ApplicationEventName.VARIABLE_DELETED,+ ApplicationEventName.VARIABLE_VALUE_REVEALED,+ ],+ },+ {+ key: 'users',+ title: t('Users & access'),+ events: [+ ApplicationEventName.USER_SIGNED_UP,+ ApplicationEventName.USER_SIGNED_IN,+ ApplicationEventName.USER_PASSWORD_RESET,+ ApplicationEventName.USER_EMAIL_VERIFIED,+ ApplicationEventName.SIGNING_KEY_CREATED,+ ],+ },+ {+ key: 'projects',+ title: t('Projects'),+ events: [+ ApplicationEventName.PROJECT_ROLE_CREATED,+ ApplicationEventName.PROJECT_ROLE_UPDATED,+ ApplicationEventName.PROJECT_ROLE_DELETED,+ ApplicationEventName.PROJECT_RELEASE_CREATED,+ ApplicationEventName.PROJECT_REPLACED,+ ],+ },+ ];+}++function countEvents(): number {+ return buildEventGroups().reduce(+ (total, group) => total + group.events.length,+ 0,+ );+}++export const eventGroupUtils = {+ buildEventGroups,+ countEvents,+};++export type EventGroup = {+ key: string;+ title: string;+ events: ApplicationEventName[];+};diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-labels.ts b/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-labels.tsnew file mode 100644index 00000000000..4335e3abaa8--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-labels.ts@@ -0,0 +1,57 @@+import { ApplicationEventName } from '@activepieces/shared';+import { t } from 'i18next';++export const buildEventLabels = (): EventLabelsMap => {+ return {+ [ApplicationEventName.AGENT_CREATED]: t('Agent created'),+ [ApplicationEventName.AGENT_UPDATED]: t('Agent updated'),+ [ApplicationEventName.AGENT_DELETED]: t('Agent deleted'),+ [ApplicationEventName.AGENT_PUBLISHED]: t('Agent published'),+ [ApplicationEventName.AGENT_UNPUBLISHED]: t('Agent taken offline'),+ [ApplicationEventName.AGENT_ACTION_EXECUTED]: t('Agent ran an action'),+ [ApplicationEventName.FLOW_RUN_STARTED]: t('Flow run started'),+ [ApplicationEventName.FLOW_RUN_FINISHED]: t('Flow run finished'),+ [ApplicationEventName.FLOW_RUN_RESUMED]: t('Flow run resumed'),+ [ApplicationEventName.FLOW_RUN_RETRIED]: t('Flow run retried'),+ [ApplicationEventName.FLOW_CREATED]: t('Flow created'),+ [ApplicationEventName.FLOW_UPDATED]: t('Flow updated'),+ [ApplicationEventName.FLOW_DELETED]: t('Flow deleted'),+ [ApplicationEventName.FLOW_PIECES_UPGRADED]: t('Flow pieces upgraded'),+ [ApplicationEventName.FLOW_PIECES_REVERTED]: t('Flow pieces reverted'),+ [ApplicationEventName.FOLDER_CREATED]: t('Folder created'),+ [ApplicationEventName.FOLDER_UPDATED]: t('Folder updated'),+ [ApplicationEventName.FOLDER_DELETED]: t('Folder deleted'),+ [ApplicationEventName.CONNECTION_UPSERTED]: t('Connection saved'),+ [ApplicationEventName.CONNECTION_DELETED]: t('Connection deleted'),+ [ApplicationEventName.VARIABLE_UPSERTED]: t('Variable saved'),+ [ApplicationEventName.VARIABLE_DELETED]: t('Variable deleted'),+ [ApplicationEventName.VARIABLE_VALUE_REVEALED]: t(+ 'Variable value revealed',+ ),+ [ApplicationEventName.USER_SIGNED_UP]: t('User signed up'),+ [ApplicationEventName.USER_SIGNED_IN]: t('User signed in'),+ [ApplicationEventName.USER_PASSWORD_RESET]: t('User password reset'),+ [ApplicationEventName.USER_EMAIL_VERIFIED]: t('User email verified'),+ [ApplicationEventName.SIGNING_KEY_CREATED]: t('Signing key created'),+ [ApplicationEventName.PROJECT_ROLE_CREATED]: t('Project role created'),+ [ApplicationEventName.PROJECT_ROLE_UPDATED]: t('Project role updated'),+ [ApplicationEventName.PROJECT_ROLE_DELETED]: t('Project role deleted'),+ [ApplicationEventName.PROJECT_RELEASE_CREATED]: t(+ 'Project release created',+ ),+ [ApplicationEventName.PROJECT_REPLACED]: t('Project replaced'),+ [ApplicationEventName.FLOW_PUBLISHED]: t('Flow published'),+ [ApplicationEventName.FLOW_ACTIVATED]: t('Flow activated'),+ [ApplicationEventName.FLOW_DEACTIVATED]: t('Flow deactivated'),+ [ApplicationEventName.FLOW_APPROVAL_REQUESTED]: t(+ 'Flow approval requested',+ ),+ [ApplicationEventName.FLOW_APPROVAL_GRANTED]: t('Flow approval granted'),+ [ApplicationEventName.FLOW_APPROVAL_REJECTED]: t('Flow approval rejected'),+ [ApplicationEventName.FLOW_APPROVAL_WITHDRAWN]: t(+ 'Flow approval withdrawn',+ ),+ };+};++export type EventLabelsMap = Record<ApplicationEventName, string>;diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-streaming-path.ts b/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-streaming-path.tsnew file mode 100644index 00000000000..6b5eb0392b0--- /dev/null+++ b/packages/web/src/app/routes/platform/infra/event-destinations/lib/event-streaming-path.ts@@ -0,0 +1 @@+export const EVENT_STREAMING_PATH = '/platform/audit-log/streaming';diff --git a/packages/web/src/app/routes/platform/infra/event-destinations/lib/use-event-labels.ts b/packages/web/src/app/routes/platform/infra/event-destinations/lib/use-event-labels.tsdeleted file mode 100644index 909ffbdf99c..00000000000--- a/packages/web/src/app/routes/platform/infra/event-destinations/lib/use-event-labels.ts+++ /dev/null@@ -1,114 +0,0 @@-import { ApplicationEventName } from '@activepieces/shared';-import { t } from 'i18next';--export const useEventLabels = (): EventLabelsMap => {- return {- [ApplicationEventName.AGENT_CREATED]: { label: t('Agent created') },- [ApplicationEventName.AGENT_UPDATED]: { label: t('Agent updated') },- [ApplicationEventName.AGENT_DELETED]: { label: t('Agent deleted') },- [ApplicationEventName.AGENT_PUBLISHED]: {- label: t('Agent published'),- description: t(- 'Fires when someone publishes an agent. Flow steps read the published copy, not the draft.',- ),- },- [ApplicationEventName.AGENT_UNPUBLISHED]: {- label: t('Agent taken offline'),- description: t('Fires when someone takes an agent offline.'),- },- [ApplicationEventName.AGENT_ACTION_EXECUTED]: {- label: t('Agent ran an action'),- description: t(- 'Fires when an agent runs a configured action that is not a read.',- ),- },- [ApplicationEventName.FLOW_RUN_STARTED]: { label: t('Flow run started') },- [ApplicationEventName.FLOW_RUN_FINISHED]: {- label: t('Flow run finished'),- description: t('Fires for every finished run — successful and failed.'),- },- [ApplicationEventName.FLOW_RUN_RESUMED]: { label: t('Flow run resumed') },- [ApplicationEventName.FLOW_RUN_RETRIED]: { label: t('Flow run retried') },- [ApplicationEventName.FLOW_CREATED]: { label: t('Flow created') },- [ApplicationEventName.FLOW_UPDATED]: { label: t('Flow updated') },- [ApplicationEventName.FLOW_DELETED]: { label: t('Flow deleted') },- [ApplicationEventName.FLOW_PIECES_UPGRADED]: {- label: t('Flow pieces upgraded'),- },- [ApplicationEventName.FLOW_PIECES_REVERTED]: {- label: t('Flow pieces reverted'),- },- [ApplicationEventName.FOLDER_CREATED]: { label: t('Folder created') },- [ApplicationEventName.FOLDER_UPDATED]: { label: t('Folder updated') },- [ApplicationEventName.FOLDER_DELETED]: { label: t('Folder deleted') },- [ApplicationEventName.CONNECTION_UPSERTED]: {- label: t('Connection saved'),- },- [ApplicationEventName.CONNECTION_DELETED]: {- label: t('Connection deleted'),- },- [ApplicationEventName.VARIABLE_UPSERTED]: {- label: t('Variable saved'),- },- [ApplicationEventName.VARIABLE_DELETED]: {- label: t('Variable deleted'),- },- [ApplicationEventName.VARIABLE_VALUE_REVEALED]: {- label: t('Variable value revealed'),- },- [ApplicationEventName.USER_SIGNED_UP]: { label: t('User signed up') },- [ApplicationEventName.USER_SIGNED_IN]: { label: t('User signed in') },- [ApplicationEventName.USER_PASSWORD_RESET]: {- label: t('User password reset'),- },- [ApplicationEventName.USER_EMAIL_VERIFIED]: {- label: t('User email verified'),- },- [ApplicationEventName.SIGNING_KEY_CREATED]: {- label: t('Signing key created'),- },- [ApplicationEventName.PROJECT_ROLE_CREATED]: {- label: t('Project role created'),- },- [ApplicationEventName.PROJECT_ROLE_UPDATED]: {- label: t('Project role updated'),- },- [ApplicationEventName.PROJECT_ROLE_DELETED]: {- label: t('Project role deleted'),- },- [ApplicationEventName.PROJECT_RELEASE_CREATED]: {- label: t('Project release created'),- },- [ApplicationEventName.PROJECT_REPLACED]: {- label: t('Project replaced'),- },- [ApplicationEventName.FLOW_PUBLISHED]: {- label: t('Flow published'),- },- [ApplicationEventName.FLOW_ACTIVATED]: {- label: t('Flow activated'),- },- [ApplicationEventName.FLOW_DEACTIVATED]: {- label: t('Flow deactivated'),- },- [ApplicationEventName.FLOW_APPROVAL_REQUESTED]: {- label: t('Flow approval requested'),- },- [ApplicationEventName.FLOW_APPROVAL_GRANTED]: {- label: t('Flow approval granted'),- },- [ApplicationEventName.FLOW_APPROVAL_REJECTED]: {- label: t('Flow approval rejected'),- },- [ApplicationEventName.FLOW_APPROVAL_WITHDRAWN]: {- label: t('Flow approval withdrawn'),- },- };-};--export type EventLabel = {- label: string;- description?: string;-};--export type EventLabelsMap = Record<ApplicationEventName, EventLabel>;diff --git a/packages/web/src/app/routes/platform/plan-feature-sample.tsx b/packages/web/src/app/routes/platform/plan-feature-sample.tsxindex c4572086dde..f6a80df5143 100644--- a/packages/web/src/app/routes/platform/plan-feature-sample.tsx+++ b/packages/web/src/app/routes/platform/plan-feature-sample.tsx@@ -2,7 +2,10 @@ import { PlatformWithoutSensitiveData } from '@activepieces/shared';import React from 'react';import { FeatureSample } from '@/app/components/feature-sample';-import { FeatureTeaserProps } from '@/app/components/feature-teaser';+import {+ FeatureTeaser,+ FeatureTeaserProps,+} from '@/app/components/feature-teaser';import { platformHooks } from '@/hooks/platform-hooks';export function PlanFeatureSample({@@ -27,6 +30,16 @@ export function PlanFeatureSample({);}+export function PlanFeatureGuard({+ feature,+ children,+}: PlanFeatureSampleProps) {+ const { platform } = platformHooks.useCurrentPlatform();+ const { isLocked, teaser } = PLAN_FEATURE_SAMPLES[feature];++ return isLocked(platform.plan) ? <FeatureTeaser {...teaser} /> : children;+}+const PLAN_FEATURE_SAMPLES: Record<PlanFeature, PlanFeatureSampleSpec> = {sso: {isLocked: (plan) => !plan.ssoEnabled,@@ -110,8 +123,10 @@ const PLAN_FEATURE_SAMPLES: Record<PlanFeature, PlanFeatureSampleSpec> = {featureKey: 'EVENT_DESTINATIONS',title: 'Unlock Event Streaming',description:- 'Forward every audit event we emit to a webhook, then handle it in a flow.',+ 'Stream every audit event in OpenTelemetry (OTLP) format to Datadog, PostHog, Grafana Loki, or any OTLP backend. Or send it as raw JSON to a webhook or a handler flow.',tier: 'enterprise',+ documentationUrl:+ 'https://www.activepieces.com/docs/admin-guide/guides/event-streaming',},},aiProviders: {diff --git a/packages/web/src/app/variables/variable-dialog.tsx b/packages/web/src/app/variables/variable-dialog.tsxindex 237f4460803..02712395ba9 100644--- a/packages/web/src/app/variables/variable-dialog.tsx+++ b/packages/web/src/app/variables/variable-dialog.tsx@@ -7,12 +7,12 @@ import {import { zodResolver } from '@hookform/resolvers/zod';import { useMutation } from '@tanstack/react-query';import { t } from 'i18next';-import { Eye, EyeOff } from 'lucide-react';import { useState } from 'react';import { useForm } from 'react-hook-form';import { toast } from 'sonner';import { z } from 'zod';+import { MaskedInput } from '@/components/custom/masked-input';import { Button } from '@/components/ui/button';import {Dialog,@@ -36,7 +36,6 @@ import { internalErrorToast } from '@/components/ui/sonner';import { variablesApi } from '@/features/variables/api/variables';import { api } from '@/lib/api';import { authenticationSession } from '@/lib/authentication-session';-import { cn } from '@/lib/utils';const FormSchema = z.object({name: z@@ -81,7 +80,6 @@ function VariableForm(props: VariableFormProps) {const { existing, onOpenChange, onSaved } = props;const isEdit = !!existing;const projectId = authenticationSession.getProjectId();- const [valueVisible, setValueVisible] = useState(false);const [showValueField, setShowValueField] = useState(!isEdit);const form = useForm<FormValues>({@@ -169,37 +167,12 @@ function VariableForm(props: VariableFormProps) {<FormItem><FormLabel>{t('Value')}</FormLabel><FormControl>- <div className="relative">- <Input- {...field}- type="text"- autoComplete="off"- spellCheck={false}- className={cn(- 'pr-10',- !valueVisible && '[-webkit-text-security:disc]',- )}- placeholder={- isEdit ? t('Enter new value') : t('Enter the value')- }- />- <Button- type="button"- variant="ghost"- size="sm"- className="absolute right-1 top-1/2 -translate-y-1/2 h-7 w-7 p-0"- onClick={() => setValueVisible((v) => !v)}- aria-label={- valueVisible ? t('Hide value') : t('Show value')- }- >- {valueVisible ? (- <EyeOff className="h-4 w-4" />- ) : (- <Eye className="h-4 w-4" />- )}- </Button>- </div>+ <MaskedInput+ {...field}+ placeholder={+ isEdit ? t('Enter new value') : t('Enter the value')+ }+ /></FormControl><FormMessage /></FormItem>diff --git a/packages/web/src/components/custom/animated-icon-button.tsx b/packages/web/src/components/custom/animated-icon-button.tsxindex 8c1cc6ff121..bb275d62c92 100644--- a/packages/web/src/components/custom/animated-icon-button.tsx+++ b/packages/web/src/components/custom/animated-icon-button.tsx@@ -1,3 +1,4 @@+import { Slot } from 'radix-ui';import React, { useCallback, useRef } from 'react';import { Button } from '@/components/ui/button';@@ -32,7 +33,11 @@ const AnimatedIconButton = React.forwardRef<onMouseLeave={handleMouseLeave}><Icon ref={iconRef} size={iconSize} />- {children}+ {buttonProps.asChild ? (+ <Slot.Slottable>{children}</Slot.Slottable>+ ) : (+ children+ )}</Button>);});diff --git a/packages/web/src/components/custom/data-table/index.tsx b/packages/web/src/components/custom/data-table/index.tsxindex b861b6a3a78..938f079ebe6 100644--- a/packages/web/src/components/custom/data-table/index.tsx+++ b/packages/web/src/components/custom/data-table/index.tsx@@ -90,6 +90,7 @@ interface DataTableProps<emptyStateTextTitle: string;emptyStateTextDescription: string;emptyStateIcon: React.ReactNode;+ emptyStateAction?: React.ReactNode;selectColumn?: boolean;initialSorting?: SortingState;clientPagination?: boolean;@@ -134,6 +135,7 @@ export function DataTable<emptyStateTextTitle,emptyStateTextDescription,emptyStateIcon,+ emptyStateAction,customFilters,selectColumn = false,initialSorting = [],@@ -656,6 +658,7 @@ export function DataTable<{emptyStateTextDescription}</p>)}+ {emptyStateAction}</div></TableCell></TableRow>diff --git a/packages/web/src/components/custom/masked-input.tsx b/packages/web/src/components/custom/masked-input.tsxnew file mode 100644index 00000000000..d2b035f8f96--- /dev/null+++ b/packages/web/src/components/custom/masked-input.tsx@@ -0,0 +1,42 @@+import { t } from 'i18next';+import { Eye, EyeOff } from 'lucide-react';+import { useState } from 'react';++import { Button } from '@/components/ui/button';+import { Input, InputProps } from '@/components/ui/input';+import { cn } from '@/lib/utils';++export function MaskedInput({ className, ...props }: MaskedInputProps) {+ const [isVisible, setIsVisible] = useState(false);++ return (+ <div className="relative">+ <Input+ {...props}+ type="text"+ autoComplete="off"+ spellCheck={false}+ className={cn(+ 'pr-10',+ !isVisible && '[-webkit-text-security:disc]',+ className,+ )}+ />+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2 p-0"+ onClick={() => setIsVisible((visible) => !visible)}+ aria-label={isVisible ? t('Hide value') : t('Show value')}+ >+ {isVisible ? <EyeOff className="size-4" /> : <Eye className="size-4" />}+ </Button>+ </div>+ );+}++export type MaskedInputProps = Omit<+ InputProps,+ 'type' | 'autoComplete' | 'spellCheck'+>;diff --git a/packages/web/test/app/routes/platform/infra/event-destinations/components/event-destination-mutations.test.tsx b/packages/web/test/app/routes/platform/infra/event-destinations/components/event-destination-actions.test.tsxsimilarity index 59%rename from packages/web/test/app/routes/platform/infra/event-destinations/components/event-destination-mutations.test.tsxrename to packages/web/test/app/routes/platform/infra/event-destinations/components/event-destination-actions.test.tsxindex ec885c43777..b8c9cbb349c 100644--- a/packages/web/test/app/routes/platform/infra/event-destinations/components/event-destination-mutations.test.tsx+++ b/packages/web/test/app/routes/platform/infra/event-destinations/components/event-destination-actions.test.tsx@@ -1,25 +1,16 @@/*** @vitest-environment jsdom*/-import {- ApplicationEventName,- EventDestination,- EventDestinationFormat,- EventDestinationScope,-} from '@activepieces/shared';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';import { fireEvent, render, screen, waitFor } from '@testing-library/react';import * as React from 'react';+import { MemoryRouter } from 'react-router-dom';import { beforeEach, describe, expect, it, vi } from 'vitest';const { toastMock, collectionUtilsMock } = vi.hoisted(() => ({toastMock: { success: vi.fn(), error: vi.fn() },collectionUtilsMock: {- update: vi.fn(),delete: vi.fn(),- useCreateEventDestination: () => ({ mutate: vi.fn(), isPending: false }),- useTestEventDestination: () => ({ mutate: vi.fn(), isPending: false }),- useImportHandlerFlow: () => ({ mutate: vi.fn(), isPending: false }),},}));@@ -38,51 +29,11 @@ vi.mock('@/lib/api', () => ({},}));-vi.mock('@/hooks/flags-hooks', () => ({- flagsHooks: { useFlag: () => ({ data: 'http://localhost/api/v1/webhooks' }) },-}));-vi.mock('@/app/routes/platform/infra/event-destinations/lib/event-destinations-collection',() => ({ eventDestinationsCollectionUtils: collectionUtilsMock }),);-vi.mock(- '@/app/routes/platform/infra/event-destinations/lib/handler-flow-builder',- () => ({ handlerFlowBuilder: {} }),-);--vi.mock(- '@/app/routes/platform/infra/event-destinations/lib/use-event-labels',- () => ({- useEventLabels: () =>- new Proxy({}, { get: (_, key) => ({ label: String(key) }) }),- }),-);--vi.mock('@/components/ui/scroll-area', () => ({- ScrollArea: ({ children }: React.PropsWithChildren) => <div>{children}</div>,-}));--vi.mock('@/components/ui/checkbox', () => ({- Checkbox: ({- checked,- onCheckedChange,- id,- }: {- checked: boolean;- onCheckedChange: (checked: boolean) => void;- id: string;- }) => (- <input- type="checkbox"- id={id}- checked={checked}- onChange={(event) => onCheckedChange(event.target.checked)}- />- ),-}));-vi.mock('@/components/ui/dropdown-menu', () => ({DropdownMenu: ({ children }: React.PropsWithChildren) => <>{children}</>,DropdownMenuTrigger: ({ children }: React.PropsWithChildren) => (@@ -159,36 +110,20 @@ vi.mock('@/components/ui/button', () => ({}));import EventDestinationActions from '@/app/routes/platform/infra/event-destinations/components/event-destination-actions';-import { EventDestinationDialog } from '@/app/routes/platform/infra/event-destinations/components/event-destination-dialog';-const destination: EventDestination = {- id: 'dest1',- created: '2026-01-01T00:00:00.000Z',- updated: '2026-01-01T00:00:00.000Z',- platformId: 'platform1',- scope: EventDestinationScope.PLATFORM,- events: [ApplicationEventName.FLOW_CREATED],- url: 'https://old.example.com/hook',- enabled: true,- headers: {},- format: EventDestinationFormat.RAW,-};--const serverError = new Error('Destination not reachable');+import { makeDestination } from '../event-destination-fixtures';-function persistedTransaction() {- return { isPersisted: { promise: Promise.resolve() } };-}+const destination = makeDestination();-function failedTransaction() {- return { isPersisted: { promise: Promise.reject(serverError) } };-}+const serverError = new Error('Destination not reachable');function mount(element: React.ReactElement) {render(- <QueryClientProvider client={new QueryClient()}>- {element}- </QueryClientProvider>,+ <MemoryRouter>+ <QueryClientProvider client={new QueryClient()}>+ {element}+ </QueryClientProvider>+ </MemoryRouter>,);}@@ -221,48 +156,6 @@ beforeEach(() => {vi.clearAllMocks();});-describe('EventDestinationDialog edit', () => {- function openAndSave() {- mount(- <EventDestinationDialog destination={destination}>- <button>open</button>- </EventDestinationDialog>,- );- click(findButton('open'));- click(findButton('Save changes'));- }-- it('shows the server error and keeps the dialog open when saving fails', async () => {- collectionUtilsMock.update.mockImplementation(failedTransaction);-- openAndSave();- await settle();-- expect(collectionUtilsMock.update).toHaveBeenCalledWith(destination.id, {- url: destination.url,- events: destination.events,- });- expect(toastMock.error).toHaveBeenCalledWith('Error', {- description: serverError.message,- });- expect(toastMock.success).not.toHaveBeenCalled();- expect(dialogs()).toHaveLength(1);- });-- it('shows success and closes the dialog only after saving succeeds', async () => {- collectionUtilsMock.update.mockImplementation(persistedTransaction);-- openAndSave();- await settle();-- expect(toastMock.success).toHaveBeenCalledWith('Success', {- description: 'Destination updated successfully',- });- expect(toastMock.error).not.toHaveBeenCalled();- expect(dialogs()).toHaveLength(0);- });-});-describe('EventDestinationActions delete', () => {function confirmDelete() {mount(<EventDestinationActions destination={destination} />);@@ -274,7 +167,7 @@ describe('EventDestinationActions delete', () => {}it('shows the server error instead of success when deleting fails', async () => {- collectionUtilsMock.delete.mockImplementation(failedTransaction);+ collectionUtilsMock.delete.mockRejectedValue(serverError);confirmDelete();await settle();@@ -288,7 +181,7 @@ describe('EventDestinationActions delete', () => {});it('shows success and closes the confirmation only after deleting succeeds', async () => {- collectionUtilsMock.delete.mockImplementation(persistedTransaction);+ collectionUtilsMock.delete.mockResolvedValue(undefined);confirmDelete();await settle();diff --git a/packages/web/test/app/routes/platform/infra/event-destinations/destination-form-utils.test.ts b/packages/web/test/app/routes/platform/infra/event-destinations/destination-form-utils.test.tsnew file mode 100644index 00000000000..d818570c275--- /dev/null+++ b/packages/web/test/app/routes/platform/infra/event-destinations/destination-form-utils.test.ts@@ -0,0 +1,612 @@+import {+ ApplicationEventName,+ EventDestinationFormat,+ formErrors,+} from '@activepieces/shared';+import { describe, expect, it } from 'vitest';++import { destinationFormUtils } from '@/app/routes/platform/infra/event-destinations/lib/destination-form-utils';++import { makeDestination } from './event-destination-fixtures';++describe('destinationFormUtils.isWebhookUrl', () => {+ it('matches a flow webhook URL on the instance host', () => {+ expect(+ destinationFormUtils.isWebhookUrl(+ 'https://cloud.example.com/api/v1/webhooks/abc123',+ ),+ ).toBe(true);+ });++ it('matches a flow webhook URL on another host, such as an embed subdomain', () => {+ expect(+ destinationFormUtils.isWebhookUrl(+ 'https://automations.customer.example/api/v1/webhooks/abc123/sync',+ ),+ ).toBe(true);+ });++ it('does not match an OTLP logs endpoint', () => {+ expect(+ destinationFormUtils.isWebhookUrl('https://otlp.datadoghq.com/v1/logs'),+ ).toBe(false);+ });++ it('does not match a webhook path without a flow id', () => {+ expect(+ destinationFormUtils.isWebhookUrl(+ 'https://cloud.example.com/api/v1/webhooks/',+ ),+ ).toBe(false);+ });++ it('does not match a value that is not a URL', () => {+ expect(destinationFormUtils.isWebhookUrl('not a url')).toBe(false);+ });+});++describe('destinationFormUtils.findHeaderIssues', () => {+ it('refuses a value with a hidden or control character that the delivery cannot send', () => {+ expect(+ destinationFormUtils.findHeaderIssues({+ headers: [+ { name: 'Authorization', value: 'Bearer token\u200b' },+ { name: 'X-Tenant', value: 'one\ntwo' },+ { name: 'X-Team', value: 'Équipe\tA' },+ ],+ storedHeaderNames: [],+ isUrlChanged: false,+ }),+ ).toEqual([+ { index: 0, field: 'value', message: formErrors.invalidHeaderValue },+ { index: 1, field: 'value', message: formErrors.invalidHeaderValue },+ ]);+ });++ it('accepts headers that each have a valid name and a value', () => {+ expect(+ destinationFormUtils.findHeaderIssues({+ headers: [+ { name: 'Authorization', value: 'Bearer token' },+ { name: 'DD-API-KEY', value: 'key' },+ ],+ storedHeaderNames: [],+ isUrlChanged: false,+ }),+ ).toEqual([]);+ });++ it('ignores an empty row the admin added and left blank', () => {+ expect(+ destinationFormUtils.findHeaderIssues({+ headers: [{ name: '', value: '' }],+ storedHeaderNames: [],+ isUrlChanged: false,+ }),+ ).toEqual([]);+ });++ it('refuses a header name the delivery sets itself, in any letter case', () => {+ expect(+ destinationFormUtils.findHeaderIssues({+ headers: [{ name: 'content-type', value: 'text/plain' }],+ storedHeaderNames: [],+ isUrlChanged: false,+ }),+ ).toEqual([{ index: 0, field: 'name', message: 'reservedHeaderName' }]);+ });++ it('refuses a header name that is not a valid token', () => {+ expect(+ destinationFormUtils.findHeaderIssues({+ headers: [{ name: 'X Api Key', value: 'key' }],+ storedHeaderNames: [],+ isUrlChanged: false,+ }),+ ).toEqual([{ index: 0, field: 'name', message: 'invalidHeaderName' }]);+ });++ it('flags both rows when two names differ only in letter case', () => {+ expect(+ destinationFormUtils.findHeaderIssues({+ headers: [+ { name: 'X-Team', value: 'a' },+ { name: 'x-team', value: 'b' },+ ],+ storedHeaderNames: [],+ isUrlChanged: false,+ }),+ ).toEqual([+ { index: 0, field: 'name', message: 'duplicateHeaderName' },+ { index: 1, field: 'name', message: 'duplicateHeaderName' },+ ]);+ });++ it('flags both rows when the same name is typed twice', () => {+ expect(+ destinationFormUtils.findHeaderIssues({+ headers: [+ { name: 'X-Team', value: 'a' },+ { name: 'X-Team', value: 'b' },+ ],+ storedHeaderNames: [],+ isUrlChanged: false,+ }),+ ).toEqual([+ { index: 0, field: 'name', message: 'duplicateHeaderName' },+ { index: 1, field: 'name', message: 'duplicateHeaderName' },+ ]);+ });++ it('flags a new value typed next to a blank copy of a saved header, so the old value is never kept by mistake', () => {+ expect(+ destinationFormUtils.findHeaderIssues({+ headers: [+ { name: 'Authorization', value: 'new-secret' },+ { name: 'Authorization', value: '' },+ ],+ storedHeaderNames: ['Authorization'],+ isUrlChanged: false,+ }),+ ).toEqual([+ { index: 0, field: 'name', message: 'duplicateHeaderName' },+ { index: 1, field: 'name', message: 'duplicateHeaderName' },+ ]);+ });++ it('refuses a value that has no header name', () => {+ expect(+ destinationFormUtils.findHeaderIssues({+ headers: [{ name: '', value: 'Bearer token' }],+ storedHeaderNames: [],+ isUrlChanged: false,+ }),+ ).toEqual([{ index: 0, field: 'name', message: 'Enter a header name' }]);+ });++ it('flags a nameless value even when a blank row follows it', () => {+ expect(+ destinationFormUtils.findHeaderIssues({+ headers: [+ { name: '', value: 'secret' },+ { name: '', value: '' },+ ],+ storedHeaderNames: [],+ isUrlChanged: false,+ }),+ ).toEqual([{ index: 0, field: 'name', message: 'Enter a header name' }]);+ });++ it('refuses a new header with no value, which the server would drop', () => {+ expect(+ destinationFormUtils.findHeaderIssues({+ headers: [{ name: 'Authorization', value: '' }],+ storedHeaderNames: [],+ isUrlChanged: false,+ }),+ ).toEqual([+ { index: 0, field: 'value', message: 'Enter a value for this header' },+ ]);+ });++ it('asks for a value when a saved header is renamed', () => {+ expect(+ destinationFormUtils.findHeaderIssues({+ headers: [{ name: 'X-Auth', value: '' }],+ storedHeaderNames: ['Authorization'],+ isUrlChanged: false,+ }),+ ).toEqual([+ { index: 0, field: 'value', message: 'Enter a value for this header' },+ ]);+ });++ it('reports both a reserved name and a missing value on the same row', () => {+ expect(+ destinationFormUtils.findHeaderIssues({+ headers: [{ name: 'Host', value: '' }],+ storedHeaderNames: [],+ isUrlChanged: false,+ }),+ ).toEqual([+ { index: 0, field: 'name', message: 'reservedHeaderName' },+ { index: 0, field: 'value', message: 'Enter a value for this header' },+ ]);+ });++ it('keeps a saved header value while the URL stays the same', () => {+ expect(+ destinationFormUtils.findHeaderIssues({+ headers: [{ name: 'Authorization', value: '' }],+ storedHeaderNames: ['Authorization'],+ isUrlChanged: false,+ }),+ ).toEqual([]);+ });++ it('asks again only for the saved values that were not retyped when the URL changes', () => {+ expect(+ destinationFormUtils.findHeaderIssues({+ headers: [+ { name: 'authorization', value: '' },+ { name: 'X-Team', value: 'ops' },+ ],+ storedHeaderNames: ['Authorization', 'X-Team'],+ isUrlChanged: true,+ }),+ ).toEqual([+ {+ index: 0,+ field: 'value',+ message: 'Re-enter this value to change the URL',+ },+ ]);+ });+});++describe('destinationFormUtils.buildFormSchema', () => {+ const validValues = {+ url: 'https://example.com/hook',+ events: [ApplicationEventName.FLOW_CREATED],+ headers: [],+ format: EventDestinationFormat.RAW,+ };++ it('says the URL is required when it is empty', () => {+ const result = destinationFormUtils+ .buildFormSchema({ storedHeaderNames: [], storedUrl: null })+ .safeParse({ ...validValues, url: '' });++ expect(result.error?.issues.map((issue) => issue.path)).toEqual([['url']]);+ expect(result.error?.issues[0].message).toBe('Endpoint URL is required');+ });++ it('says the URL is invalid when it is not a URL', () => {+ const result = destinationFormUtils+ .buildFormSchema({ storedHeaderNames: [], storedUrl: null })+ .safeParse({ ...validValues, url: 'not a url' });++ expect(result.error?.issues[0].message).toBe('Invalid URL');+ });++ it('puts each header issue on the row and field it belongs to', () => {+ const result = destinationFormUtils+ .buildFormSchema({ storedHeaderNames: [], storedUrl: null })+ .safeParse({+ ...validValues,+ headers: [+ { name: 'X-Team', value: 'a' },+ { name: 'x-team', value: 'b' },+ ],+ });++ expect(result.error?.issues.map((issue) => issue.path)).toEqual([+ ['headers', 0, 'name'],+ ['headers', 1, 'name'],+ ]);+ });++ it('asks for a saved value again only when the URL differs from the stored one', () => {+ const schema = destinationFormUtils.buildFormSchema({+ storedHeaderNames: ['Authorization'],+ storedUrl: 'https://example.com/hook',+ });+ const headers = [{ name: 'Authorization', value: '' }];++ expect(schema.safeParse({ ...validValues, headers }).success).toBe(true);+ expect(+ schema+ .safeParse({+ ...validValues,+ url: 'https://example.com/moved',+ headers,+ })+ .error?.issues.map((issue) => issue.path),+ ).toEqual([['headers', 0, 'value']]);+ });+});++describe('destinationFormUtils header conversion', () => {+ it('sends a blank value as null, which keeps the saved value, and skips a nameless row', () => {+ expect(+ destinationFormUtils.toHeaderRequest([+ { name: 'A', value: 't' },+ { name: 'B', value: '' },+ { name: '', value: '' },+ ]),+ ).toEqual({ A: 't', B: null });+ });++ it('tests only the headers that have both a name and a value', () => {+ expect(+ destinationFormUtils.toTestHeaders([+ { name: 'A', value: '1' },+ { name: 'B', value: '' },+ { name: '', value: 'x' },+ ]),+ ).toEqual({ A: '1' });+ });++ it('shows saved headers as sorted rows with blank values', () => {+ expect(+ destinationFormUtils.toDefaultValues({+ destination: makeDestination({+ headers: { 'X-Team': null, Authorization: null },+ }),+ kind: 'webhook',+ }).headers,+ ).toEqual([+ { name: 'Authorization', value: '' },+ { name: 'X-Team', value: '' },+ ]);+ });++ it('lists the saved events in one fixed order, so the form starts clean', () => {+ expect(+ destinationFormUtils.toDefaultValues({+ destination: makeDestination({+ events: [+ ApplicationEventName.FLOW_DELETED,+ ApplicationEventName.FLOW_CREATED,+ ],+ }),+ kind: 'webhook',+ }).events,+ ).toEqual([+ ApplicationEventName.FLOW_CREATED,+ ApplicationEventName.FLOW_DELETED,+ ]);+ });++ it('gives the same event list back after an event is cleared and selected again', () => {+ const saved = destinationFormUtils.inCanonicalOrder([+ ApplicationEventName.FLOW_CREATED,+ ApplicationEventName.FLOW_DELETED,+ ApplicationEventName.USER_SIGNED_IN,+ ]);+ const cleared = saved.filter(+ (event) => event !== ApplicationEventName.FLOW_CREATED,+ );++ expect(+ destinationFormUtils.inCanonicalOrder([+ ...cleared,+ ApplicationEventName.FLOW_CREATED,+ ]),+ ).toEqual(saved);+ });++ it('starts a new OpenTelemetry destination on Protobuf with no headers', () => {+ expect(+ destinationFormUtils.toDefaultValues({ destination: null, kind: 'otel' }),+ ).toEqual({+ url: '',+ events: [],+ headers: [],+ format: EventDestinationFormat.OTLP_PROTOBUF,+ });+ });+});++describe('destinationFormUtils.toHandlerFlowId', () => {+ const webhookPrefixUrl = 'https://cloud.example.com/api/v1/webhooks';+ const flowId = 'abcdefghijklmnopqrstu';++ it('returns the flow id of a complete handler flow URL', () => {+ expect(+ destinationFormUtils.toHandlerFlowId({+ url: `${webhookPrefixUrl}/${flowId}`,+ webhookPrefixUrl,+ }),+ ).toBe(flowId);+ });++ it('returns the flow id when a route suffix and a query follow it', () => {+ expect(+ destinationFormUtils.toHandlerFlowId({+ url: `${webhookPrefixUrl}/${flowId}/sync?x=1`,+ webhookPrefixUrl,+ }),+ ).toBe(flowId);+ });++ it('ignores a flow id that is still being typed', () => {+ expect(+ destinationFormUtils.toHandlerFlowId({+ url: `${webhookPrefixUrl}/abc`,+ webhookPrefixUrl,+ }),+ ).toBeNull();+ });++ it('ignores a URL outside the webhook prefix, or a missing prefix', () => {+ expect(+ destinationFormUtils.toHandlerFlowId({+ url: `https://other.example.com/hooks/${flowId}`,+ webhookPrefixUrl,+ }),+ ).toBeNull();+ expect(+ destinationFormUtils.toHandlerFlowId({+ url: `${webhookPrefixUrl}/${flowId}`,+ webhookPrefixUrl: null,+ }),+ ).toBeNull();+ });+});++describe('destinationFormUtils.findTestHeaderBlocker', () => {+ it('asks for a retyped value while a saved header is blank', () => {+ expect(+ destinationFormUtils.findTestHeaderBlocker({+ headers: [{ name: 'Authorization', value: '' }],+ storedHeaderNames: ['authorization'],+ }),+ ).toBe('blankValue');+ });++ it('treats a blank value on a new header as a header error', () => {+ expect(+ destinationFormUtils.findTestHeaderBlocker({+ headers: [{ name: 'Authorization', value: '' }],+ storedHeaderNames: [],+ }),+ ).toBe('invalidHeader');+ });++ it('reports a header error before a saved value to retype', () => {+ expect(+ destinationFormUtils.findTestHeaderBlocker({+ headers: [+ { name: 'Authorization', value: '' },+ { name: 'Host', value: 'x' },+ ],+ storedHeaderNames: ['Authorization'],+ }),+ ).toBe('invalidHeader');+ });++ it('blocks a test for a reserved name, a duplicate, or a nameless value', () => {+ expect(+ destinationFormUtils.findTestHeaderBlocker({+ headers: [{ name: 'Host', value: 'x' }],+ storedHeaderNames: [],+ }),+ ).toBe('invalidHeader');+ expect(+ destinationFormUtils.findTestHeaderBlocker({+ headers: [+ { name: 'X-Team', value: 'a' },+ { name: 'x-team', value: 'b' },+ ],+ storedHeaderNames: [],+ }),+ ).toBe('invalidHeader');+ expect(+ destinationFormUtils.findTestHeaderBlocker({+ headers: [{ name: '', value: 'x' }],+ storedHeaderNames: [],+ }),+ ).toBe('invalidHeader');+ });++ it('lets a test through with valid headers and a blank row', () => {+ expect(+ destinationFormUtils.findTestHeaderBlocker({+ headers: [],+ storedHeaderNames: [],+ }),+ ).toBeNull();+ expect(+ destinationFormUtils.findTestHeaderBlocker({+ headers: [+ { name: 'Authorization', value: 'Bearer token' },+ { name: '', value: '' },+ ],+ storedHeaderNames: ['Authorization'],+ }),+ ).toBeNull();+ });+});++describe('destinationFormUtils.isSameTestRequest', () => {+ const sent = destinationFormUtils.toTestRequest({+ url: 'https://example.com/hook',+ event: ApplicationEventName.FLOW_CREATED,+ headers: [+ { name: 'A', value: '1' },+ { name: 'B', value: '2' },+ ],+ format: EventDestinationFormat.RAW,+ });++ it('matches the same inputs, in any header order, ignoring a blank row', () => {+ expect(+ destinationFormUtils.isSameTestRequest({+ sent,+ current: destinationFormUtils.toTestRequest({+ url: 'https://example.com/hook',+ event: ApplicationEventName.FLOW_CREATED,+ headers: [+ { name: 'B', value: '2' },+ { name: 'A', value: '1' },+ { name: '', value: '' },+ ],+ format: EventDestinationFormat.RAW,+ }),+ }),+ ).toBe(true);+ });++ it('stops matching once the URL, event, format or a header value changes', () => {+ const changed = [+ { ...sent, url: 'https://example.com/other' },+ { ...sent, event: ApplicationEventName.FLOW_DELETED },+ { ...sent, format: EventDestinationFormat.OTLP_JSON },+ { ...sent, headers: { A: '1', B: '3' } },+ ];++ changed.forEach((current) => {+ expect(destinationFormUtils.isSameTestRequest({ sent, current })).toBe(+ false,+ );+ });+ });+});++describe('destinationFormUtils.resolveOtlpFormat', () => {+ const webhookUrl = 'https://cloud.example.com/api/v1/webhooks/abc123';+ const otlpUrl = 'https://otlp.datadoghq.com/v1/logs';++ it('switches Protobuf to JSON for a flow webhook URL and remembers it did', () => {+ expect(+ destinationFormUtils.resolveOtlpFormat({+ url: webhookUrl,+ format: EventDestinationFormat.OTLP_PROTOBUF,+ isAutoSwitched: false,+ }),+ ).toEqual({+ format: EventDestinationFormat.OTLP_JSON,+ isAutoSwitched: true,+ });+ });++ it('switches back to Protobuf once the URL is no longer a flow webhook', () => {+ expect(+ destinationFormUtils.resolveOtlpFormat({+ url: otlpUrl,+ format: EventDestinationFormat.OTLP_JSON,+ isAutoSwitched: true,+ }),+ ).toEqual({+ format: EventDestinationFormat.OTLP_PROTOBUF,+ isAutoSwitched: false,+ });+ });++ it('keeps JSON that the admin chose', () => {+ expect(+ destinationFormUtils.resolveOtlpFormat({+ url: otlpUrl,+ format: EventDestinationFormat.OTLP_JSON,+ isAutoSwitched: false,+ }),+ ).toEqual({+ format: EventDestinationFormat.OTLP_JSON,+ isAutoSwitched: false,+ });+ });++ it('stays on JSON while the URL is still a flow webhook', () => {+ expect(+ destinationFormUtils.resolveOtlpFormat({+ url: webhookUrl,+ format: EventDestinationFormat.OTLP_JSON,+ isAutoSwitched: true,+ }),+ ).toEqual({+ format: EventDestinationFormat.OTLP_JSON,+ isAutoSwitched: true,+ });+ });+});diff --git a/packages/web/test/app/routes/platform/infra/event-destinations/destination-form/destination-form-page.test.tsx b/packages/web/test/app/routes/platform/infra/event-destinations/destination-form/destination-form-page.test.tsxnew file mode 100644index 00000000000..e949fb46e37--- /dev/null+++ b/packages/web/test/app/routes/platform/infra/event-destinations/destination-form/destination-form-page.test.tsx@@ -0,0 +1,63 @@+// @vitest-environment jsdom+import { fireEvent, render, screen } from '@testing-library/react';+import { createMemoryRouter, RouterProvider } from 'react-router-dom';+import { describe, expect, it, vi } from 'vitest';++import EventDestinationFormPage from '@/app/routes/platform/infra/event-destinations/destination-form';+import { DESTINATION_KIND_SEARCH_PARAM } from '@/app/routes/platform/infra/event-destinations/lib/destination-kinds';+import { EVENT_STREAMING_PATH } from '@/app/routes/platform/infra/event-destinations/lib/event-streaming-path';++const { saveDestination } = vi.hoisted(() => ({ saveDestination: vi.fn() }));++vi.mock('i18next', () => ({ t: (key: string) => key }));++vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));++vi.mock('@/lib/api', () => ({+ API_BASE_URL: 'http://localhost',+ api: { isApError: () => false, serverErrorMessage: () => undefined },+}));++vi.mock(+ '@/app/routes/platform/infra/event-destinations/lib/event-destinations-collection',+ () => ({+ eventDestinationsCollectionUtils: {+ useSaveEventDestination: () => ({+ mutate: saveDestination,+ isPending: false,+ }),+ },+ }),+);++globalThis.ResizeObserver = class {+ observe() {}+ unobserve() {}+ disconnect() {}+};++describe('EventDestinationFormPage', () => {+ it('keeps the page when the browser submits the form on Enter in the event search', () => {+ const router = createMemoryRouter(+ [+ {+ path: `${EVENT_STREAMING_PATH}/new`,+ element: <EventDestinationFormPage />,+ },+ ],+ {+ initialEntries: [+ `${EVENT_STREAMING_PATH}/new?${DESTINATION_KIND_SEARCH_PARAM}=otel`,+ ],+ },+ );+ render(<RouterProvider router={router} />);++ const isNativeSubmitAllowed = fireEvent.submit(+ screen.getByPlaceholderText('Search events'),+ );++ expect(isNativeSubmitAllowed).toBe(false);+ expect(saveDestination).not.toHaveBeenCalled();+ });+});diff --git a/packages/web/test/app/routes/platform/infra/event-destinations/event-destination-fixtures.ts b/packages/web/test/app/routes/platform/infra/event-destinations/event-destination-fixtures.tsnew file mode 100644index 00000000000..0730ae82805--- /dev/null+++ b/packages/web/test/app/routes/platform/infra/event-destinations/event-destination-fixtures.ts@@ -0,0 +1,24 @@+import {+ ApplicationEventName,+ EventDestinationFormat,+ EventDestinationScope,+} from '@activepieces/shared';+import type { EventDestination } from '@activepieces/shared';++export function makeDestination(+ overrides: Partial<Omit<EventDestination, 'scope'>> = {},+): EventDestination {+ return {+ id: 'dest1',+ created: '2026-01-01T00:00:00.000Z',+ updated: '2026-01-01T00:00:00.000Z',+ platformId: 'platform1',+ scope: EventDestinationScope.PLATFORM,+ events: [ApplicationEventName.FLOW_CREATED],+ url: 'https://example.com/hook',+ enabled: true,+ headers: {},+ format: EventDestinationFormat.RAW,+ ...overrides,+ };+}diff --git a/packages/web/test/app/routes/platform/infra/event-destinations/event-destinations-plan-gate.test.ts b/packages/web/test/app/routes/platform/infra/event-destinations/event-destinations-plan-gate.test.tsnew file mode 100644index 00000000000..9659c26fa08--- /dev/null+++ b/packages/web/test/app/routes/platform/infra/event-destinations/event-destinations-plan-gate.test.ts@@ -0,0 +1,29 @@+// @vitest-environment jsdom+import { act, renderHook } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { eventDestinationsCollectionUtils } from '@/app/routes/platform/infra/event-destinations/lib/event-destinations-collection';+import { api } from '@/lib/api';++vi.mock('@/lib/api', () => ({+ API_BASE_URL: 'http://localhost',+ api: { get: vi.fn(), post: vi.fn(), delete: vi.fn() },+}));++describe('eventDestinationsCollectionUtils.useAll on a plan without event streaming', () => {+ it('reports no destinations and never asks the server for them', async () => {+ const { result } = renderHook(() =>+ eventDestinationsCollectionUtils.useAll(false),+ );+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 0));+ });++ expect(result.current).toEqual({+ data: [],+ isLoading: false,+ isError: false,+ });+ expect(api.get).not.toHaveBeenCalled();+ });+});diff --git a/packages/web/test/app/routes/platform/infra/event-destinations/lib/event-destinations-collection.test.ts b/packages/web/test/app/routes/platform/infra/event-destinations/lib/event-destinations-collection.test.tsindex 2ebac6e2b24..7fe71722608 100644--- a/packages/web/test/app/routes/platform/infra/event-destinations/lib/event-destinations-collection.test.ts+++ b/packages/web/test/app/routes/platform/infra/event-destinations/lib/event-destinations-collection.test.ts@@ -1,115 +1,337 @@// @vitest-environment jsdom-import {- ApplicationEventName,- EventDestination,- EventDestinationFormat,- EventDestinationScope,-} from '@activepieces/shared';-import { beforeEach, describe, expect, it, vi } from 'vitest';--const { apiMock } = vi.hoisted(() => ({- apiMock: {- get: vi.fn(),- post: vi.fn(),- patch: vi.fn(),- delete: vi.fn(),- },-}));--vi.mock('@/lib/api', () => ({ api: apiMock }));-vi.mock('@/features/flows', () => ({- flowHooks: {},- flowsApi: {},- triggerEventsApi: {},-}));-vi.mock('@/features/projects', () => ({ projectCollectionUtils: {} }));-vi.mock('@/hooks/user-hooks', () => ({ userHooks: {} }));+import { tryCatch } from '@activepieces/core-utils';+import type { SeekPage } from '@activepieces/core-utils';+import { ApplicationEventName } from '@activepieces/shared';+import type { EventDestination } from '@activepieces/shared';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act, renderHook, waitFor } from '@testing-library/react';+import { createElement, type ReactNode } from 'react';+import { afterEach, describe, expect, it, vi } from 'vitest';import {eventDestinationsCollection,eventDestinationsCollectionUtils,} from '@/app/routes/platform/infra/event-destinations/lib/event-destinations-collection';+import type { SaveEventDestinationParams } from '@/app/routes/platform/infra/event-destinations/lib/event-destinations-collection';+import { api } from '@/lib/api';-const destination: EventDestination = {- id: 'dest1',- created: '2026-01-01T00:00:00.000Z',- updated: '2026-01-01T00:00:00.000Z',- platformId: 'platform1',- scope: EventDestinationScope.PLATFORM,- events: [ApplicationEventName.FLOW_CREATED],- url: 'https://old.example.com/hook',- enabled: true,- headers: {},- format: EventDestinationFormat.RAW,-};+import { makeDestination } from '../event-destination-fixtures';-const serverError = new Error('Request failed with status code 500');+vi.mock('@/lib/api', () => ({+ API_BASE_URL: 'http://localhost',+ api: { get: vi.fn(), post: vi.fn(), delete: vi.fn() },+}));-describe('eventDestinationsCollectionUtils', () => {- beforeEach(async () => {- vi.clearAllMocks();- apiMock.get.mockResolvedValue({- data: [destination],- next: null,- previous: null,- });- await eventDestinationsCollection.utils.refetch();- await eventDestinationsCollection.toArrayWhenReady();+function makePage(+ data: EventDestination[],+ next: string | null,+): SeekPage<EventDestination> {+ return { data, next, previous: null };+}++function deferredPage(): DeferredPage {+ let resolvePage: (page: SeekPage<EventDestination>) => void = () => undefined;+ const promise = new Promise<SeekPage<EventDestination>>((resolve) => {+ resolvePage = resolve;});+ return { promise, resolve: (page) => resolvePage(page) };+}++async function seedDestinations(+ destinations: EventDestination[],+): Promise<void> {+ vi.mocked(api.get).mockResolvedValue(makePage(destinations, null));+ renderHook(() => eventDestinationsCollectionUtils.useAll(true));+ await act(() => eventDestinationsCollectionUtils.refetch());+}++function createMutationWrapper(): (props: WrapperProps) => ReactNode {+ const client = new QueryClient({+ defaultOptions: { mutations: { retry: false } },+ });+ function MutationWrapper({ children }: WrapperProps): ReactNode {+ return createElement(QueryClientProvider, { client }, children);+ }+ return MutationWrapper;+}++function renderListWithSave() {+ return renderHook(+ () => ({+ all: eventDestinationsCollectionUtils.useAll(true),+ save: eventDestinationsCollectionUtils.useSaveEventDestination({+ onSuccess: () => undefined,+ onError: () => undefined,+ }),+ }),+ { wrapper: createMutationWrapper() },+ );+}++async function failNextLoad(): Promise<void> {+ vi.mocked(api.get).mockRejectedValue(new Error('network down'));+ await act(() => eventDestinationsCollectionUtils.refetch());+}++function destinationRequests(): unknown[] {+ return vi+ .mocked(api.get)+ .mock.calls.filter((call) => call[0] === '/v1/event-destinations')+ .map((call) => call[1]);+}++describe('eventDestinationsCollection', () => {+ afterEach(() => {+ vi.mocked(api.get).mockReset();+ vi.mocked(api.post).mockReset();+ vi.mocked(api.delete).mockReset();+ });++ it('loads every page the server offers, not just the first one', async () => {+ vi.mocked(api.get)+ .mockResolvedValueOnce(+ makePage([makeDestination({ id: 'd1' })], 'cursor1'),+ )+ .mockResolvedValueOnce(+ makePage([makeDestination({ id: 'd2' })], 'cursor2'),+ )+ .mockResolvedValueOnce(makePage([makeDestination({ id: 'd3' })], null));++ await eventDestinationsCollection.preload();- it('update rejects and rolls back when the PATCH fails', async () => {- apiMock.patch.mockRejectedValue(serverError);+ expect(+ [...eventDestinationsCollection.values()].map((row) => row.id),+ ).toEqual(['d1', 'd2', 'd3']);+ expect(destinationRequests()).toEqual([+ { cursor: undefined, limit: 100 },+ { cursor: 'cursor1', limit: 100 },+ { cursor: 'cursor2', limit: 100 },+ ]);+ });- const transaction = eventDestinationsCollectionUtils.update(- destination.id,- { url: 'https://new.example.com/hook', events: destination.events },+ it('reports a failed load at once, and clears it once a retry succeeds', async () => {+ vi.mocked(api.get).mockRejectedValue(new Error('network down'));+ const { result } = renderHook(() =>+ eventDestinationsCollectionUtils.useAll(true),);- await expect(transaction.isPersisted.promise).rejects.toBe(serverError);- expect(eventDestinationsCollection.get(destination.id)?.url).toBe(- destination.url,+ await act(() => eventDestinationsCollectionUtils.refetch());+ expect(result.current.isError).toBe(true);+ expect(destinationRequests()).toHaveLength(1);++ vi.mocked(api.get).mockResolvedValue(+ makePage([makeDestination({ id: 'd4' })], null),);+ await act(() => eventDestinationsCollectionUtils.refetch());+ expect(result.current.isError).toBe(false);});- it('update resolves once the PATCH succeeds', async () => {- apiMock.patch.mockResolvedValue({- ...destination,- url: 'https://new.example.com/hook',+ it('sends only the changed field when a destination is toggled', async () => {+ const stored = makeDestination({+ id: 't1',+ headers: { Authorization: null },});+ vi.mocked(api.get).mockResolvedValue(makePage([stored], null));+ renderHook(() => eventDestinationsCollectionUtils.useAll(true));+ await act(() => eventDestinationsCollectionUtils.refetch());+ vi.mocked(api.post).mockResolvedValue({ ...stored, enabled: false });+ vi.mocked(api.get).mockResolvedValue(+ makePage([{ ...stored, enabled: false }], null),+ );++ await act(+ () =>+ eventDestinationsCollectionUtils.update({+ destinationId: 't1',+ request: { enabled: false },+ }).isPersisted.promise,+ );++ const postCalls = vi.mocked(api.post).mock.calls;+ expect(postCalls).toHaveLength(1);+ expect(postCalls[0][0]).toBe('/v1/event-destinations/t1');+ expect(JSON.stringify(postCalls[0][1])).toBe('{"enabled":false}');+ expect(eventDestinationsCollection.get('t1')?.enabled).toBe(false);+ });- const transaction = eventDestinationsCollectionUtils.update(- destination.id,- { url: 'https://new.example.com/hook', events: destination.events },+ it('rolls a failed toggle back and hands the error to the caller', async () => {+ vi.mocked(api.get).mockResolvedValue(+ makePage([makeDestination({ id: 't2' })], null),);+ renderHook(() => eventDestinationsCollectionUtils.useAll(true));+ await act(() => eventDestinationsCollectionUtils.refetch());+ const failure = new Error('server down');+ vi.mocked(api.post).mockRejectedValue(failure);- await expect(transaction.isPersisted.promise).resolves.toBeDefined();- expect(apiMock.patch).toHaveBeenCalledWith(- `/v1/event-destinations/${destination.id}`,- { url: 'https://new.example.com/hook', events: destination.events },+ const { error } = await act(() =>+ tryCatch(+ () =>+ eventDestinationsCollectionUtils.update({+ destinationId: 't2',+ request: { enabled: false },+ }).isPersisted.promise,+ ),);++ expect(error).toBe(failure);+ expect(eventDestinationsCollection.get('t2')?.enabled).toBe(true);});it('delete rejects and restores the row when the DELETE fails', async () => {- apiMock.delete.mockRejectedValue(serverError);+ await seedDestinations([makeDestination({ id: 'x1' })]);+ const failure = new Error('server down');+ vi.mocked(api.delete).mockRejectedValue(failure);++ await expect(eventDestinationsCollectionUtils.delete(['x1'])).rejects.toBe(+ failure,+ );+ expect(eventDestinationsCollection.has('x1')).toBe(true);+ });++ it('delete resolves once the DELETE succeeds', async () => {+ await seedDestinations([makeDestination({ id: 'x2' })]);+ vi.mocked(api.delete).mockResolvedValue(undefined);++ await expect(+ eventDestinationsCollectionUtils.delete(['x2']),+ ).resolves.toBeUndefined();+ expect(api.delete).toHaveBeenCalledWith('/v1/event-destinations/x2');+ });+});++describe('eventDestinationsCollectionUtils.useSaveEventDestination', () => {+ afterEach(() => {+ vi.mocked(api.get).mockReset();+ vi.mocked(api.post).mockReset();+ });- const transaction = eventDestinationsCollectionUtils.delete([- destination.id,+ it('reloads the list instead of patching it when a destination is created after a failed load', async () => {+ const { result } = renderListWithSave();+ await failNextLoad();+ expect(result.current.all.isError).toBe(true);+ vi.mocked(api.post).mockResolvedValue(makeDestination({ id: 'c2' }));+ vi.mocked(api.get).mockResolvedValue(+ makePage(+ [makeDestination({ id: 'c1' }), makeDestination({ id: 'c2' })],+ null,+ ),+ );++ await act(() => result.current.save.mutateAsync(CREATE_PARAMS));++ expect(result.current.all.isError).toBe(false);+ expect(result.current.all.data.map((row) => row.id).sort()).toEqual([+ 'c1',+ 'c2',]);+ });++ it('keeps reporting the failure when the reload after a create fails too', async () => {+ const { result } = renderListWithSave();+ await failNextLoad();+ vi.mocked(api.post).mockResolvedValue(makeDestination({ id: 'c3' }));- await expect(transaction.isPersisted.promise).rejects.toBe(serverError);- expect(eventDestinationsCollection.has(destination.id)).toBe(true);+ await act(() => result.current.save.mutateAsync(CREATE_PARAMS));++ expect(result.current.all.isError).toBe(true);+ expect(result.current.all.data.map((row) => row.id)).not.toContain('c3');});- it('delete resolves once the DELETE succeeds', async () => {- apiMock.delete.mockResolvedValue(undefined);+ it('writes the created destination without a reload when the list is healthy', async () => {+ await seedDestinations([makeDestination({ id: 'h1' })]);+ const { result } = renderListWithSave();+ const requestsBefore = destinationRequests().length;+ vi.mocked(api.post).mockResolvedValue(makeDestination({ id: 'h2' }));++ await act(() => result.current.save.mutateAsync(CREATE_PARAMS));- const transaction = eventDestinationsCollectionUtils.delete([- destination.id,+ expect(destinationRequests()).toHaveLength(requestsBefore);+ expect(result.current.all.data.map((row) => row.id).sort()).toEqual([+ 'h1',+ 'h2',]);+ });+});++describe('eventDestinationsCollectionUtils.useFreshDestination', () => {+ afterEach(() => {+ vi.mocked(api.get).mockReset();+ });++ it('waits for a reload before it hands the edit page a destination', async () => {+ await seedDestinations([makeDestination({ id: 'e1' })]);+ const reload = deferredPage();+ vi.mocked(api.get).mockReturnValue(reload.promise);++ const { result } = renderHook(() =>+ eventDestinationsCollectionUtils.useFreshDestination('e1'),+ );+ expect(result.current.status).toBe('loading');++ reload.resolve(+ makePage(+ [makeDestination({ id: 'e1', url: 'https://example.com/fresh' })],+ null,+ ),+ );+ await waitFor(() => expect(result.current.status).toBe('ready'));+ expect(result.current).toEqual({+ status: 'ready',+ destination: expect.objectContaining({+ url: 'https://example.com/fresh',+ }),+ });+ });- await expect(transaction.isPersisted.promise).resolves.toBeDefined();- expect(apiMock.delete).toHaveBeenCalledWith(- `/v1/event-destinations/${destination.id}`,+ it('reports a failed reload even though a cached row exists', async () => {+ await seedDestinations([makeDestination({ id: 'e2' })]);+ vi.mocked(api.get).mockRejectedValue(new Error('network down'));++ const { result } = renderHook(() =>+ eventDestinationsCollectionUtils.useFreshDestination('e2'),+ );++ await waitFor(() => expect(result.current.status).toBe('error'));+ });++ it('reports a destination the reload no longer returns as missing', async () => {+ await seedDestinations([makeDestination({ id: 'e3' })]);+ vi.mocked(api.get).mockResolvedValue(makePage([], null));++ const { result } = renderHook(() =>+ eventDestinationsCollectionUtils.useFreshDestination('e3'),);++ await waitFor(() => expect(result.current.status).toBe('missing'));+ });++ it('keeps an open destination ready when a later reload fails', async () => {+ await seedDestinations([makeDestination({ id: 'e4' })]);+ const { result } = renderHook(() =>+ eventDestinationsCollectionUtils.useFreshDestination('e4'),+ );+ await waitFor(() => expect(result.current.status).toBe('ready'));++ vi.mocked(api.get).mockRejectedValue(new Error('network down'));+ await act(() => eventDestinationsCollectionUtils.refetch());++ expect(result.current.status).toBe('ready');});});++const CREATE_PARAMS: SaveEventDestinationParams = {+ destinationId: null,+ request: {+ url: 'https://example.com/created',+ events: [ApplicationEventName.FLOW_RUN_FINISHED],+ },+};++type WrapperProps = {+ children: ReactNode;+};++type DeferredPage = {+ promise: Promise<SeekPage<EventDestination>>;+ resolve: (page: SeekPage<EventDestination>) => void;+};diff --git a/packages/web/test/components/custom/animated-icon-button.test.tsx b/packages/web/test/components/custom/animated-icon-button.test.tsxnew file mode 100644index 00000000000..5c2a5d9226c--- /dev/null+++ b/packages/web/test/components/custom/animated-icon-button.test.tsx@@ -0,0 +1,46 @@+// @vitest-environment jsdom+/* eslint-disable jest-dom/prefer-in-document, jest-dom/prefer-to-have-attribute -- @testing-library/jest-dom is not a dependency of packages/web */+import { render, screen, within } from '@testing-library/react';+import { forwardRef, useImperativeHandle } from 'react';+import { MemoryRouter, Link } from 'react-router-dom';+import { describe, expect, it } from 'vitest';++import { AnimatedIconButton } from '@/components/custom/animated-icon-button';++const FakeIcon = forwardRef<+ { startAnimation: () => void; stopAnimation: () => void },+ { size?: number }+>((_props, ref) => {+ useImperativeHandle(ref, () => ({+ startAnimation: () => undefined,+ stopAnimation: () => undefined,+ }));+ return <svg data-testid="icon" />;+});+FakeIcon.displayName = 'FakeIcon';++describe('AnimatedIconButton', () => {+ it('renders as its child link, with the icon inside and no button around it', () => {+ render(+ <MemoryRouter>+ <AnimatedIconButton icon={FakeIcon} asChild>+ <Link to="/destinations/new">New Destination</Link>+ </AnimatedIconButton>+ </MemoryRouter>,+ );++ const link = screen.getByRole('link', { name: 'New Destination' });+ expect(link.getAttribute('href')).toBe('/destinations/new');+ expect(within(link).getByTestId('icon')).not.toBeNull();+ expect(screen.queryByRole('button')).toBeNull();+ });++ it('renders a button when it is not given asChild', () => {+ render(+ <AnimatedIconButton icon={FakeIcon}>New Template</AnimatedIconButton>,+ );++ const button = screen.getByRole('button', { name: 'New Template' });+ expect(within(button).getByTestId('icon')).not.toBeNull();+ });+});