@aglyn/plugins-workflows 1.5.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,12 +3,12 @@
3
3
  The Automation plugin: the console's **Automation** section —
4
4
  Workflows, Actions and Webhooks — and the engine that runs what is built there.
5
5
 
6
- > Beta. Published from the Aglyn monorepo under the `beta` dist-tag; APIs can change between beta releases.
6
+ > Published to npm from the Aglyn monorepo. Versions follow [semantic versioning](https://semver.org).
7
7
 
8
8
  ## Install
9
9
 
10
10
  ```bash
11
- npm install @aglyn/plugins-workflows@beta
11
+ npm install @aglyn/plugins-workflows
12
12
  ```
13
13
 
14
14
  A plugin is loaded through Aglyn's plugin manager (`@aglyn/aglyn`) by the console and the tenant runtime; it is not a standalone library.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-workflows",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,17 +25,17 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.5.0",
29
- "@aglyn/shared-data-mdi": "1.5.0",
30
- "@aglyn/shared-ui-jsx": "1.5.0",
31
- "@aglyn/shared-ui-next": "1.5.0",
32
- "@aglyn/shared-ui-snackstack": "1.5.0",
33
- "@aglyn/shared-util-email": "1.5.0",
34
- "@aglyn/shared-util-http": "1.5.0",
35
- "@aglyn/shared-util-timestamp": "1.5.0",
36
- "@aglyn/tenant-data-admin": "1.5.0",
37
- "@aglyn/tenant-feature-instance": "1.5.0",
38
- "@aglyn/tenant-runtime": "1.5.0",
28
+ "@aglyn/aglyn": "1.7.0",
29
+ "@aglyn/shared-data-mdi": "1.7.0",
30
+ "@aglyn/shared-ui-jsx": "1.7.0",
31
+ "@aglyn/shared-ui-next": "1.7.0",
32
+ "@aglyn/shared-ui-snackstack": "1.7.0",
33
+ "@aglyn/shared-util-email": "1.7.0",
34
+ "@aglyn/shared-util-http": "1.7.0",
35
+ "@aglyn/shared-util-timestamp": "1.7.0",
36
+ "@aglyn/tenant-data-admin": "1.7.0",
37
+ "@aglyn/tenant-feature-instance": "1.7.0",
38
+ "@aglyn/tenant-runtime": "1.7.0",
39
39
  "@swc/helpers": "0.5.23"
40
40
  },
41
41
  "peerDependencies": {
@@ -130,7 +130,7 @@ const CUSTOM_EVENT_VALUE = '__custom__';
130
130
  *
131
131
  * The same shape the interaction builder guards (AGL-1066); this is its
132
132
  * card twin, and it was the one that never got the guard.
133
- */ fromCache: actionsFromCache } = useFirestoreCollection(/*
133
+ */ fromCache: actionsFromCache, listen: actionsListen } = useFirestoreCollection(/*
134
134
  * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501) —
135
135
  * the same decision as the workflows card beside it.
136
136
  *
@@ -515,7 +515,8 @@ const CUSTOM_EVENT_VALUE = '__custom__';
515
515
  const verdict = await writeGuardedBySeed({
516
516
  subject: 'action',
517
517
  unreadable: Boolean(draft.id) && actionsStatus === 'error',
518
- fromCache: Boolean(draft.id) && actionsFromCache
518
+ fromCache: Boolean(draft.id) && actionsFromCache,
519
+ listen: actionsListen
519
520
  }, async ()=>{
520
521
  await setDoc(doc(firestore, 'hosts', hostId, 'actions', id), _extends({}, siteInteractionDocument(candidate), {
521
522
  updatedAt: Timestamp.now()
@@ -551,6 +552,7 @@ const CUSTOM_EVENT_VALUE = '__custom__';
551
552
  hostId,
552
553
  enqueueSnackbar,
553
554
  actionsFromCache,
555
+ actionsListen,
554
556
  actionsStatus
555
557
  ]);
556
558
  const handleDelete = useCallback((action)=>async ()=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/host-actions-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n ACTION_MAX_STEPS,\n type AglynOrgBilling,\n checkEntitlement,\n createResourceUid,\n ELEMENT_SCOPED_SITE_EVENTS,\n HOST_EVENT_TYPES,\n hostEventLabel,\n HOST_EVENT_PAYLOAD_KEYS,\n hostEventPayloadHint,\n type HostEventType,\n isSiteEventType,\n pluginDocsHelp,\n SITE_EVENT_TYPES,\n type TriggerCombinator,\n triggerFilterProblem,\n} from '@aglyn/aglyn'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport {\n type InteractionRecipe,\n interactionRecipe,\n interactionRecipes,\n interactionRecipeStamp,\n} from '@aglyn/aglyn/plugin-manager/interaction-recipes'\nimport {\n pluginRecordListQuery,\n pluginRecordsFromRows,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-lists'\nimport {\n AUTOMATION_EDITOR_ZONE,\n HOST_AUTOMATIONS_ZONE,\n OPEN_ACTION_PARAM,\n requestedActionId,\n type AutomationTarget,\n} from './workflow-zones'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n ListItemText,\n Menu,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport {\n ceilingedWindow,\n collectionCeiling,\n useFirestore,\n useFirestoreCollection,\n useHostResourceApi,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { ACTION_TEST_RUN_API_ROUTE } from '../model/action-test-run'\nimport {\n AutomationStepFields,\n type AutomationStepKind,\n defaultStep,\n} from './automation-step-fields.component'\nimport { ElementSelectorField } from './element-selector-field.component'\nimport {\n conditionRowsFromTrigger,\n conditionsFromRows,\n type ConditionRowDraft,\n EMPTY_CONDITION_ROW,\n TriggerConditionRows,\n} from './automation-trigger-conditions.component'\nimport HostRunHistoryCard from './host-run-history-card.component'\nimport {\n EDITOR_OPTION_CEILING,\n useAutomationStepPickers,\n} from './use-automation-step-pickers'\nimport { siteInteractionDocument } from '@aglyn/aglyn/app-utils/site-interactions'\nimport {\n HOST_ACTION_STEP_LABELS,\n type HostAction,\n type HostActionStepType,\n stepRunsAfterWait,\n validateHostAction,\n} from '../model/host-actions'\nimport {\n describeInteractionPlaceholder,\n interactionPlaceholders,\n} from '@aglyn/aglyn/app-utils/draft-placeholders'\n\nconst CUSTOM_EVENT_VALUE = '__custom__'\n\n/**\n * How many action documents the card reads.\n *\n * A CEILING, not a page size — see the query, which explains why this one\n * collection cannot be sliced by the server without making the count beneath\n * the list a per-page number.\n *\n * `ACTIONS_MAX_PER_HOST` is 500, so the ceiling really can bite and the probe\n * beside it is what says when it has.\n */\nconst ACTION_CEILING = 100\n\ninterface ActionDraft extends HostAction {\n id: string | null\n /** Raw custom-event text when the trigger select is on \"custom\". */\n customEvent: string\n // Structured payload conditions (AGL-557), chainable with AND/OR\n // (AGL-565) — held as rows like the steps list; legacy\n // single-`condition` docs hydrate through normalizeTriggerConditions.\n conditionRows: ConditionRowDraft[]\n conditionCombinator: TriggerCombinator\n /**\n * The recipe this draft started from (AGL-2626), so the editor can say\n * so, and what Save writes back as the action's stamp (AGL-2639): null\n * for an action begun blank, and `undefined` for a stored action from\n * before the stamp existed — which Save leaves as it found it, so an\n * edit never turns \"unknown\" into \"no recipe\".\n */\n recipe: string | null | undefined\n}\n\n\n/** Every Actions step, as the builder's \"Do\" picker offers it. */\nconst ACTION_STEP_KINDS: AutomationStepKind[] = Object.entries(\n HOST_ACTION_STEP_LABELS,\n).map(([value, label]) => ({ value, label }))\n\n\n/**\n * A stored action — or one a recipe just built — as the editor holds it.\n *\n * One conversion for both doors, because they must agree: an action that\n * round-trips through Edit and one a recipe hands over are the same shape\n * to the editor, and a field the Edit path hydrated that the recipe path\n * forgot would be a recipe whose conditions vanished on open. Site events\n * are first-class (AGL-256/266): their selector/threshold/path config is\n * kept through an edit. Structured conditions (AGL-557; chained AGL-565)\n * become rows; a legacy single-condition doc normalizes to one row.\n */\nfunction draftFromAction(\n action: Record<string, any>,\n id: string | null,\n): ActionDraft {\n const builtIn =\n HOST_EVENT_TYPES.includes(action.trigger?.event) ||\n isSiteEventType(String(action.trigger?.event ?? ''))\n return {\n id,\n name: action.name ?? '',\n trigger: {\n event: builtIn ? action.trigger.event : CUSTOM_EVENT_VALUE,\n filter: action.trigger?.filter ?? '',\n selector: action.trigger?.selector ?? '',\n threshold: action.trigger?.threshold,\n pathPattern: action.trigger?.pathPattern ?? '',\n oncePerVisitor: action.trigger?.oncePerVisitor === true,\n oncePerSession: action.trigger?.oncePerSession === true,\n everyTime: action.trigger?.everyTime === true,\n ...(Number(action.trigger?.cooldownMinutes) >= 1\n ? { cooldownMinutes: Number(action.trigger?.cooldownMinutes) }\n : {}),\n },\n steps: action.steps ?? [],\n enabled: action.enabled !== false,\n customEvent: builtIn ? '' : (action.trigger?.event ?? ''),\n conditionRows: conditionRowsFromTrigger(action.trigger),\n conditionCombinator: action.trigger?.combinator === 'or' ? 'or' : 'and',\n // A recipe stamps what it builds, and a stored action carries what it\n // was saved with — one reader for both doors, unknown kept unknown.\n recipe: interactionRecipeStamp(action),\n }\n}\n\n/** A trigger bound to one element, which makes the row an interaction. */\nconst LEAF_SELECTOR = /^\\[data-aglyn=\"leaf:.+\"\\]$/\n\n/**\n * Actions builder (AGL-148): HubSpot-style enrollment — trigger event →\n * optional filter → ordered steps (run workflow, site alert, custom\n * event, dataset append). Runs server-side via runEventActions; paid\n * feature (`actions` flag, Pro+, `actionRunsPerMonth` metered).\n */\nexport function HostActionsCard(props: {\n hostId: string\n org?: Partial<AglynOrgBilling>\n}) {\n const { hostId, org } = props\n // Org-shared data root (AGL-237). Null until the org lookup settles\n // (AGL-1061), and for a host with no owning org — the pre-migration host\n // path is gone (AGL-1050), so the dataset and list pickers stay empty\n // instead of offering rows from a path nothing else reads.\n const firestore = useFirestore()\n // Action creation is server-owned since AGL-2266 (the cap); every other\n // action write on this surface stays client-direct.\n const createResource = useHostResourceApi()\n // The caller's token, for the test run's console door.\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n /**\n * The shell's zone renderer, for what other plugins add to automations\n * (AGL-2919); `null` outside the console shell, where there is no workspace\n * to gate on.\n */\n const ExtensionZone = useConsoleWidgetSlot()\n\n const {\n data: actionDocs,\n status: actionsStatus,\n /**\n * The action rows this card's editor is seeded from are unconfirmed by\n * the server (AGL-1358). Editing an action copies the whole stored row\n * into `draft` — name, trigger and every step — and writes all of it\n * back, so `merge: true` protects nothing and a cached seed reverts a\n * colleague's newer version of the steps nobody here touched.\n *\n * The same shape the interaction builder guards (AGL-1066); this is its\n * card twin, and it was the one that never got the guard.\n */\n fromCache: actionsFromCache,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501) —\n * the same decision as the workflows card beside it.\n *\n * `limit(100)` alone is answered in DOCUMENT-ID order, so the window was a\n * pseudo-random hundred that the `localeCompare` below arranged\n * alphabetically, and nothing said the list was bounded.\n *\n * `collectionCeiling` does not change WHICH hundred — document-id order is\n * what the bare cap already returned. What it changes is that the order is\n * NAMED, so the obvious next edit is caught: ordering on `name` would HIDE\n * every action written without one rather than mis-sorting the list, and\n * `/api/hosts/resources` validates no field for presence while\n * `IMPORTABLE_FIELDS.actions` copies one only if the export carried it.\n *\n * The QUERY is not paged because this collection holds TWO audiences. A\n * row whose trigger names a leaf selector is an element interaction, which\n * belongs to its document and is reported below as a count rather than\n * listed; the rest are the site's actions. Both partitions are derived\n * from the rows in hand, so a server page would make \"3 interactions are\n * set up on their own elements\" mean \"3 on this page\" — a count that is a\n * window length, which is the defect this sweep keeps finding rather than\n * a shape it should add.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'actions'),\n ACTION_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readActions, truncated: actionsTruncated } =\n ceilingedWindow<any>(actionDocs, ACTION_CEILING)\n const [draft, setDraft] = useState<ActionDraft | null>(null)\n /**\n * The editor has been opened at least once in this session.\n *\n * A LATCH rather than `draft` itself, because the pickers below key their\n * listeners on it. Tracking the dialog would tear those subscriptions down\n * on Cancel and pay for them again on the next Edit, so a merchant working\n * through ten actions would buy the same six windows ten times — worse than\n * the mount-time read this replaces. Latched, a reader who never edits pays\n * nothing and a reader who edits pays once.\n */\n const [editorOpened, setEditorOpened] = useState(false)\n if (draft && !editorOpened) setEditorOpened(true)\n /*\n * The step editor's six option lists, read on the same latch as the\n * Workflows builder's — one hook, because the two editors offer one set of\n * steps and a second copy would be a second read cost to keep in agreement.\n */\n const { pickers: stepPickers, truncated: truncatedPickers } =\n useAutomationStepPickers(hostId, editorOpened)\n const liveActions = readActions.filter((action: any) => !action.deletedAt)\n /*\n * Opens a listed action in the editor, for a widget in the `hostAutomations`\n * zone — one that drafted an action and offers to open it. Read through a\n * ref so the callback keeps one identity while the list changes beneath it,\n * and answers `false` for an id the list has not read yet.\n */\n const listedRef = useRef<any[]>(liveActions)\n listedRef.current = liveActions\n const openAction = useCallback((actionId: string) => {\n const action = listedRef.current.find((row: any) => row.$id === actionId)\n if (!action) return false\n setDraft(draftFromAction(action, action.$id))\n return true\n }, [])\n /*\n * An action the address names (AGL-3603): the Workflows section drafts one\n * there and sends the reader here to open it. Opened once the list has read\n * it, then dropped from the address so a reload does not reopen it.\n */\n const [requested, setRequested] = useState<string | null>(() =>\n typeof window === 'undefined' ? null : requestedActionId(window.location.search),\n )\n useEffect(() => {\n if (!requested || !openAction(requested)) return\n setRequested(null)\n const url = new URL(window.location.href)\n url.searchParams.delete(OPEN_ACTION_PARAM)\n window.history.replaceState(window.history.state, '', url.toString())\n }, [requested, openAction, liveActions.length])\n /**\n * Element interactions are not listed here.\n *\n * An ACTION is something the SITE does — an order was placed, a form was\n * submitted. An INTERACTION is something an ELEMENT does, and it belongs to\n * the document that holds the element: it publishes and rolls back with it,\n * travels with it, and is deleted with it. This page is the site's\n * automation list, and a nav menu's hover timing sitting in it beside \"when\n * an order is placed\" was the tell that the two had been conflated.\n *\n * These rows are the ones written BEFORE the move, still bound by selector.\n * They keep running and stay editable — on their element, in the besigner,\n * which is now the only place they appear. Counted rather than hidden\n * outright, so the page can say where they went instead of appearing to\n * have lost them.\n */\n const elementScoped = liveActions.filter((action: any) =>\n LEAF_SELECTOR.test(String(action?.trigger?.selector ?? '')),\n )\n // Sorting is safe here in a way it is not on a paged list: these rows are\n // the whole collection below the ceiling, not a slice of one.\n const actions = liveActions\n .filter((action: any) => !elementScoped.includes(action))\n .sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n )\n // The page is a SLICE: the rows are already in hand, and both the element\n // interaction count and the alphabetical order need all of them.\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const visibleActions = useMemo(\n () => actions.slice(page * pageSize, page * pageSize + pageSize),\n [actions, page, pageSize],\n )\n\n const patch = useCallback(\n (updater: (previous: ActionDraft) => ActionDraft) =>\n setDraft((previous) => (previous ? updater(previous) : previous)),\n [],\n )\n\n /** The saved action the editor has open, as the `automationEditor` zone names it. */\n const draftId = draft?.id ?? null\n const draftName = draft?.name ?? ''\n const editorTarget = useMemo<AutomationTarget | null>(\n () => (draftId ? { type: 'action', id: draftId, name: draftName } : null),\n // The name the editor opened with: the zone reads the automation as it is\n // stored, so a rename being typed does not make it a different one.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [draftId],\n )\n\n /**\n * Whether this workspace may open the editor at all. One gate for the\n * blank action and the recipes: a recipe is an action, so the plan that\n * carries one carries the other, and the refusal reads the same.\n */\n const actionsEntitled = useCallback(() => {\n if (checkEntitlement(org, 'actions')) return true\n enqueueSnackbar(\n 'The actions builder requires a Pro plan — see Billing to upgrade',\n { variant: 'warning', persist: false },\n )\n return false\n }, [org, enqueueSnackbar])\n\n const handleAdd = useCallback(() => {\n if (!actionsEntitled()) return\n setDraft({\n id: null,\n name: '',\n trigger: { event: 'formSubmission', filter: '' },\n steps: [defaultStep('siteAlert')],\n enabled: true,\n customEvent: '',\n conditionRows: [EMPTY_CONDITION_ROW],\n conditionCombinator: 'and',\n recipe: null,\n })\n }, [actionsEntitled])\n\n /*\n * THE RECIPES (AGL-2626).\n *\n * A recipe opens the editor prefilled and writes nothing: the draft it\n * builds is the one Save would persist, and until then it is state in\n * this card and nowhere else. The recipes are the plugins' that write them\n * (`interaction-recipes`, AGL-3080) — the CRM's \"Welcome a new lead\" is the\n * CRM's — and this card offers whatever they registered. Most open at once;\n * one that picks a record first opens a picker, and the records are listed\n * through the list source the plugin that keeps them publishes, for this\n * site — the one host-scoped piece of the feature, held here rather than in\n * the recipe.\n */\n const [recipesAnchor, setRecipesAnchor] = useState<HTMLElement | null>(null)\n const [pickFor, setPickFor] = useState<InteractionRecipe | null>(null)\n const [pickedId, setPickedId] = useState('')\n /**\n * The picker has been opened at least once — the `editorOpened` latch's\n * twin, and for the same reason: the records are read for this picker only,\n * and a reader who never opens it pays nothing.\n */\n const pickKind = pickFor?.picks?.kind ?? null\n const [pickedKind, setPickedKind] = useState<string | null>(null)\n if (pickKind && pickKind !== pickedKind) setPickedKind(pickKind)\n const { data: pickRead } = useFirestoreCollection<any>(\n () =>\n pickedKind\n ? pluginRecordListQuery(pickedKind, firestore, {\n hostId,\n limit: EDITOR_OPTION_CEILING + 1,\n })\n : null,\n [firestore, hostId, pickedKind],\n { idField: '$id' },\n )\n const { rows: pickRows, truncated: pickTruncated } = ceilingedWindow<any>(\n pickRead,\n EDITOR_OPTION_CEILING,\n )\n // What the owner leaves out (an archived form collects nothing, so a recipe\n // keyed on it would never fire) is not offered. The facts the owner shares\n // ride along to the recipe, which may shape its draft by them (AGL-3458).\n const pickOptions = pluginRecordsFromRows(pickedKind ?? '', pickRows)\n .map((record) => ({ id: record.id, name: record.name, facts: record.facts }))\n .sort((a, b) => a.name.localeCompare(b.name))\n\n /*\n * The site's forms for the trigger's \"Form is\" condition (AGL-3458), for an\n * event that carries the form's id — through the same list source the\n * recipe picker reads, latched like it: read once the editor is open on\n * such an event, and never before.\n */\n const eventCarriesFormId = Boolean(\n draft && HOST_EVENT_PAYLOAD_KEYS[draft.trigger.event as HostEventType]?.includes('formId'),\n )\n const [formConditionOpened, setFormConditionOpened] = useState(false)\n if (eventCarriesFormId && !formConditionOpened) setFormConditionOpened(true)\n const { data: formConditionRead } = useFirestoreCollection<any>(\n () =>\n formConditionOpened\n ? pluginRecordListQuery('form', firestore, {\n hostId,\n limit: EDITOR_OPTION_CEILING + 1,\n })\n : null,\n [firestore, hostId, formConditionOpened],\n { idField: '$id' },\n )\n const formOptions = pluginRecordsFromRows(\n 'form',\n ceilingedWindow<any>(formConditionRead, EDITOR_OPTION_CEILING).rows,\n )\n .map((record) => ({ id: record.id, name: record.name }))\n .sort((a, b) => a.name.localeCompare(b.name))\n\n const handleRecipe = useCallback(\n (recipe: InteractionRecipe) => {\n setRecipesAnchor(null)\n if (!actionsEntitled()) return\n if (recipe.picks) {\n setPickedId('')\n setPickFor(recipe)\n return\n }\n setDraft(draftFromAction(recipe.build(), null))\n },\n [actionsEntitled],\n )\n\n const handlePicked = useCallback(() => {\n const recipe = pickFor\n const picked = pickOptions.find((option) => option.id === pickedId)\n if (!recipe || !picked) return\n setPickFor(null)\n setDraft(draftFromAction(recipe.build({ picked }), null))\n }, [pickFor, pickOptions, pickedId])\n\n // Run log + test runs (AGL-266).\n const [runsFor, setRunsFor] = useState<any | null>(null)\n const handleTestRun = useCallback(\n async (action: any) => {\n try {\n /*\n * The console's own door, signed: a page's `events/dispatch` is a\n * tenant route this origin does not serve. The route reads the\n * trigger off the stored action and marks the run as a test, so the\n * body names only which action on which site.\n */\n const response = await authorizedFetch(\n user,\n `/api/${ACTION_TEST_RUN_API_ROUTE}`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, actionId: action.$id }),\n },\n )\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'Test run failed', {\n variant: 'warning',\n persist: false,\n })\n }\n const alerts = Array.isArray(payload?.alerts) ? payload.alerts : []\n enqueueSnackbar(\n alerts.length\n ? `Test ran — first alert: ${alerts[0].message}`\n : 'Test ran — server steps executed (see Runs)',\n { variant: 'success', persist: false },\n )\n } catch (error) {\n console.error(error)\n enqueueSnackbar('Test run failed', { variant: 'error' })\n }\n },\n [hostId, user, enqueueSnackbar],\n )\n\n const handleSave = useCallback(async () => {\n if (!draft) return\n const isCustom = draft.trigger.event === CUSTOM_EVENT_VALUE\n const candidate: HostAction = {\n name: draft.name.trim().slice(0, 60),\n trigger: {\n event: isCustom ? draft.customEvent.trim() : draft.trigger.event,\n ...(draft.trigger.filter?.trim()\n ? { filter: draft.trigger.filter.trim() }\n : {}),\n // Site-event config (AGL-256).\n ...(draft.trigger.selector?.trim()\n ? { selector: draft.trigger.selector.trim() }\n : {}),\n ...(Number(draft.trigger.threshold) > 0\n ? { threshold: Number(draft.trigger.threshold) }\n : {}),\n ...(draft.trigger.pathPattern?.trim()\n ? { pathPattern: draft.trigger.pathPattern.trim() }\n : {}),\n // Frequency caps (AGL-274).\n ...(draft.trigger.oncePerVisitor === true\n ? { oncePerVisitor: true }\n : {}),\n ...(draft.trigger.oncePerSession === true\n ? { oncePerSession: true }\n : {}),\n ...(Number(draft.trigger.cooldownMinutes) >= 1\n ? { cooldownMinutes: Number(draft.trigger.cooldownMinutes) }\n : {}),\n ...(draft.trigger.everyTime === true ? { everyTime: true } : {}),\n // Structured payload conditions (AGL-557; chained AGL-565):\n // rows keep their blank fields so validateHostAction surfaces\n // the miss. Saves always write the list shape — the legacy\n // single `condition` is only ever read, never written back.\n ...conditionsFromRows(draft.conditionRows, draft.conditionCombinator),\n },\n steps: draft.steps,\n enabled: draft.enabled !== false,\n // The stamp travels only when the draft knows one way or the other;\n // an older action's silence is kept (see interactionRecipeStamp).\n ...(draft.recipe !== undefined ? { recipe: draft.recipe } : {}),\n }\n const problem = validateHostAction(candidate)\n if (problem) {\n return void enqueueSnackbar(problem, {\n variant: 'warning',\n persist: false,\n })\n }\n try {\n const id = draft.id ?? createResourceUid()\n /**\n * Refuse an EDIT whose seed the server never confirmed (AGL-1358).\n *\n * The payload is the whole action. `merge: true` is here so the\n * frequency caps and conditions can be nulled explicitly, not to\n * protect untouched fields — there are none, they are all in the\n * payload. So a cached seed does not lose one edit, it reverts the\n * trigger and every step to whatever the cache last held, on an\n * automation that is running on a live site.\n *\n * Only the edit path. A NEW action is built from `EMPTY_*` defaults at\n * a fresh uid and can overwrite nothing; the first snapshot of any\n * listener is `fromCache: true`, so guarding a create would refuse a\n * save that was never unsafe.\n *\n * The guard WRAPS the write — the interaction builder's early return\n * is the shape you can keep while losing the protection.\n */\n /**\n * The action DOCUMENT is created by the server (AGL-2266).\n *\n * `hosts/{hostId}/actions` was in none of the host catch-all's exclusion\n * lists, so any editor could create one client-direct on any plan and\n * nothing counted them. /api/hosts/resources now owns the create and\n * holds `ACTIONS_MAX_PER_HOST` from a server read.\n *\n * Only the create moves, and it writes a SHELL. The merge-set below is\n * untouched and still carries the whole candidate — trigger, steps,\n * conditions, the explicit nulls AGL-274/557 depend on — so no field can\n * be lost to the route's allow-list, and for an existing action this\n * path does not run at all.\n */\n if (!draft.id) {\n try {\n await createResource({\n hostId,\n resource: 'action',\n id,\n data: { name: candidate.name ?? draft.name ?? 'Untitled action' },\n })\n } catch (error: any) {\n return void enqueueSnackbar(\n error?.message ?? 'Could not create the interaction',\n { variant: 'error' },\n )\n }\n }\n const verdict = await writeGuardedBySeed(\n {\n subject: 'action',\n unreadable: Boolean(draft.id) && actionsStatus === 'error',\n fromCache: Boolean(draft.id) && actionsFromCache,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'actions', id),\n {\n // The stored shape (AGL-2639), shared with the recipe-install\n // route: frequency caps overwrite explicitly (AGL-274) because\n // a merge-set keeps omitted keys, so switching one off must\n // write it out; conditions follow suit (AGL-557/565) — the\n // list + combinator write null when cleared, and the legacy\n // single `condition` is always nulled.\n ...siteInteractionDocument(candidate),\n updatedAt: Timestamp.now(),\n ...(draft.id ? {} : { createdAt: Timestamp.now() }),\n },\n { merge: true },\n )\n },\n )\n // A refusal keeps the editor open with everything that was typed.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setDraft(null)\n enqueueSnackbar('Action saved', { variant: 'success', persist: false })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n draft,\n firestore,\n createResource,\n hostId,\n enqueueSnackbar,\n actionsFromCache,\n actionsStatus,\n ])\n\n const handleDelete = useCallback(\n (action: any) => async () => {\n const confirmed = await confirm({\n title: 'Delete this action?',\n description: `\"${action.name}\" stops running on its trigger.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await updateDoc(doc(firestore, 'hosts', hostId, 'actions', action.$id), {\n deletedAt: Timestamp.now(),\n })\n },\n [confirm, firestore, hostId],\n )\n\n const handleToggle = useCallback(\n (action: any) => async (event: { target: { checked: boolean } }) => {\n const enabled = event.target.checked\n /*\n * A placeholder is a value nobody has supplied yet. Switched on, the\n * step holding it fails every run and a condition holding one never\n * matches, so turning such an automation on is confirmed, naming what\n * is still missing.\n */\n const missing = enabled ? interactionPlaceholders(action) : []\n if (missing.length) {\n const confirmed = await confirm({\n title: 'Switch on with placeholders?',\n description:\n `\"${action.name}\" still has ${missing.length === 1 ? 'a placeholder' : `${missing.length} placeholders`} ` +\n `to fill in: ${missing.slice(0, 3).map(describeInteractionPlaceholder).join('; ')}` +\n `${missing.length > 3 ? '; …' : ''}. Open it with Edit to fill ` +\n `${missing.length === 1 ? 'it' : 'them'} in first.`,\n confirmationText: 'Switch on anyway',\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n }\n await updateDoc(doc(firestore, 'hosts', hostId, 'actions', action.$id), {\n enabled,\n })\n },\n [confirm, firestore, hostId],\n )\n\n return (\n <CardDisplay\n header={'Actions'}\n help={pluginDocsHelp('actionsBuilder', { anchor: '#create-an-action' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'When a site event fires, run automations in order — trigger a ' +\n 'workflow, show the visitor an alert, chain a custom event, or ' +\n 'write to a dataset. Pro plans and up.'}\n </Typography>\n {visibleActions.map((action: any) => {\n const missing = interactionPlaceholders(action).length\n return (\n <Stack\n key={action.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Switch\n size=\"small\"\n checked={action.enabled !== false}\n onChange={handleToggle(action)}\n />\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {action.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {[\n `on ${hostEventLabel(action.trigger?.event)}`,\n (action.steps ?? [])\n .map(\n (step: any) =>\n HOST_ACTION_STEP_LABELS[\n step.type as HostActionStepType\n ] ?? step.type,\n )\n .filter(Boolean)\n .join(' → '),\n ]\n .filter(Boolean)\n .join(' · ')}\n </Typography>\n {missing ? (\n <Typography variant=\"caption\" color=\"warning.main\" noWrap>\n {missing === 1\n ? '1 placeholder to fill in'\n : `${missing} placeholders to fill in`}\n </Typography>\n ) : null}\n </Stack>\n <Button\n size=\"small\"\n onClick={() => setDraft(draftFromAction(action, action.$id))}\n >\n {'Edit'}\n </Button>\n {isSiteEventType(String(action.trigger?.event ?? '')) ? (\n // Test run (AGL-266): the server steps only, run now as a real\n // run through the console's test-run door.\n <Button size=\"small\" onClick={() => void handleTestRun(action)}>\n {'Test'}\n </Button>\n ) : null}\n <Button size=\"small\" onClick={() => setRunsFor(action)}>\n {'Runs'}\n </Button>\n <Button size=\"small\" color=\"error\" onClick={handleDelete(action)}>\n {'Delete'}\n </Button>\n </Stack>\n )\n })}\n {actions.length === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={visibleActions.length}\n // The actions the card HOLDS, which is what the reader is paging\n // through — not the collection, whose other half is the element\n // interactions counted below.\n count={actions.length}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n {actionsTruncated ? (\n <Alert severity=\"info\">\n {`Showing the first ${ACTION_CEILING} rows of this site’s ` +\n 'automations, ordered by id. There are more — both the list ' +\n 'above and the interaction count below describe only what was ' +\n 'read.'}\n </Alert>\n ) : null}\n <Stack direction=\"row\" spacing={1} sx={{ alignSelf: 'flex-start' }}>\n <Button size=\"small\" color=\"primary\" onClick={handleAdd}>\n {'Add action'}\n </Button>\n <Button\n size=\"small\"\n color=\"primary\"\n aria-haspopup=\"menu\"\n aria-controls={recipesAnchor ? 'host-action-recipes' : undefined}\n aria-expanded={recipesAnchor ? true : undefined}\n onClick={(event) => setRecipesAnchor(event.currentTarget)}\n >\n {'Recipes'}\n </Button>\n {/*\n Other ways to start an automation, from plugins (AGL-2919): the\n `hostAutomations` zone, drawn through the shell's own gated slot. A\n plugin page cannot mount that slot itself, so the shell hands it\n down, and a widget here passes the gates a console page's would.\n */}\n {ExtensionZone ? (\n <ExtensionZone\n slot={HOST_AUTOMATIONS_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n openAction={openAction}\n />\n ) : null}\n </Stack>\n <Menu\n id=\"host-action-recipes\"\n anchorEl={recipesAnchor}\n open={Boolean(recipesAnchor)}\n onClose={() => setRecipesAnchor(null)}\n >\n {interactionRecipes().map((recipe) => (\n <MenuItem key={recipe.id} onClick={() => handleRecipe(recipe)}>\n <ListItemText\n primary={recipe.title}\n secondary={recipe.description}\n slotProps={{ secondary: { sx: { whiteSpace: 'normal', maxWidth: 360 } } }}\n />\n </MenuItem>\n ))}\n </Menu>\n {/* Says where they went. A list that silently drops rows\n a reader saw last week is a list they stop trusting; this is the\n one sentence that makes the absence deliberate. */}\n {elementScoped.length ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {elementScoped.length === 1\n ? '1 interaction is set up on its own element — '\n : `${elementScoped.length} interactions are set up on their own elements — `}\n {'open the element in the besigner to edit it. Interactions ' +\n 'belong to the page they are on, so they publish and roll back ' +\n 'with it.'}\n </Typography>\n ) : null}\n </Stack>\n\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"sm\"\n fullWidth\n >\n <DialogTitle>{draft?.id ? 'Edit action' : 'Add action'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: 1 }}\n >\n {ExtensionZone && editorTarget ? (\n <ExtensionZone\n slot={AUTOMATION_EDITOR_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n target={editorTarget}\n openAction={openAction}\n />\n ) : null}\n {draft?.recipe ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Started from the “${\n interactionRecipe(draft.recipe)?.title ?? 'recipe'\n }” recipe — change anything, then save.`}\n </Typography>\n ) : null}\n {/*\n A short picker is worse than an empty one, because it looks\n complete: the target an author cannot find reads as deleted, and\n the step gets pointed somewhere else.\n */}\n {truncatedPickers.length > 0 ? (\n <Alert severity=\"info\" sx={{ mt: 1 }}>\n {`Offering the first ${EDITOR_OPTION_CEILING} rows, ordered by ` +\n `id, for: ${truncatedPickers.join(', ')}. This site has ` +\n 'more, so a step target may not be listed below.'}\n </Alert>\n ) : null}\n <TextField\n label=\"Name\"\n value={draft?.name ?? ''}\n onChange={(event) =>\n patch((previous) => ({ ...previous, name: event.target.value }))\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n select\n label=\"Trigger event\"\n value={draft?.trigger.event ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: { ...previous.trigger, event: event.target.value },\n }))\n }\n size=\"small\"\n sx={{ minWidth: 180 }}\n >\n {HOST_EVENT_TYPES.map((eventType) => (\n <MenuItem key={eventType} value={eventType}>\n {hostEventLabel(eventType)}\n </MenuItem>\n ))}\n {SITE_EVENT_TYPES.map((eventType) => (\n <MenuItem key={eventType} value={eventType}>\n {`${eventType} (on page)`}\n </MenuItem>\n ))}\n <MenuItem value={CUSTOM_EVENT_VALUE}>{'Custom event…'}</MenuItem>\n </TextField>\n {draft?.trigger.event === CUSTOM_EVENT_VALUE ? (\n <TextField\n label=\"Custom event name\"\n value={draft?.customEvent ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n customEvent: event.target.value,\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n ) : (\n <TextField\n label=\"Filter (optional)\"\n placeholder=\"subscribe\"\n // A comparison belongs in the conditions below: the filter's\n // evaluator is arithmetic, and `path == \"/pricing\"` throws on\n // every event, so it is refused here (AGL-3458). Otherwise,\n // what the expression — and the conditions — can name for\n // this event; nothing for an event whose payload is not\n // written down, rather than a guess.\n error={Boolean(triggerFilterProblem(draft?.trigger.filter))}\n helperText={\n triggerFilterProblem(draft?.trigger.filter) ??\n hostEventPayloadHint(draft?.trigger.event) ??\n undefined\n }\n value={draft?.trigger.filter ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: {\n ...previous.trigger,\n filter: event.target.value,\n },\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n )}\n </Stack>\n {/* Structured payload conditions (AGL-557): the no-code sibling\n of the filter — e.g. only when `subscribe` is not empty.\n Chainable with AND/OR (AGL-565), rows styled like steps. */}\n <TriggerConditionRows\n rows={draft?.conditionRows ?? []}\n combinator={draft?.conditionCombinator ?? 'and'}\n onRowsChange={(update) =>\n patch((previous) => ({\n ...previous,\n conditionRows: update(previous.conditionRows),\n }))\n }\n onCombinatorChange={(combinator) =>\n patch((previous) => ({\n ...previous,\n conditionCombinator: combinator,\n }))\n }\n // \"Form is …\", picked by id, where the event names the form (AGL-3458).\n {...(eventCarriesFormId ? { formOptions } : {})}\n />\n {isSiteEventType(draft?.trigger.event ?? '') ? (\n // Site-event config (AGL-256): what/where the trigger watches.\n <Stack direction=\"row\" spacing={1}>\n {(ELEMENT_SCOPED_SITE_EVENTS as readonly string[]).includes(\n draft?.trigger.event ?? '',\n ) ? (\n <ElementSelectorField\n label=\"Element\"\n hostId={hostId}\n // Open the page the trigger is limited to, when it names one.\n initialPath={\n draft?.trigger.pathPattern && !draft.trigger.pathPattern.includes('*')\n ? draft.trigger.pathPattern\n : undefined\n }\n value={draft?.trigger.selector ?? ''}\n onChange={(selector) =>\n patch((previous) => ({\n ...previous,\n trigger: { ...previous.trigger, selector },\n }))\n }\n />\n ) : null}\n {['scrollDepth', 'timeOnPage'].includes(\n draft?.trigger.event ?? '',\n ) ? (\n <TextField\n type=\"number\"\n label={\n draft?.trigger.event === 'scrollDepth'\n ? 'Scroll %'\n : 'Seconds'\n }\n value={draft?.trigger.threshold ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: {\n ...previous.trigger,\n threshold: Number(event.target.value),\n },\n }))\n }\n size=\"small\"\n sx={{ width: 120 }}\n />\n ) : null}\n <TextField\n label=\"Only on pages (optional)\"\n placeholder=\"/pricing or /blog/*\"\n value={draft?.trigger.pathPattern ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: {\n ...previous.trigger,\n pathPattern: event.target.value,\n },\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n {/* Frequency caps (AGL-274). */}\n <TextField\n select\n label=\"Frequency\"\n size=\"small\"\n sx={{ minWidth: 170 }}\n value={\n draft?.trigger.oncePerVisitor\n ? 'visitor'\n : draft?.trigger.oncePerSession\n ? 'session'\n : Number(draft?.trigger.cooldownMinutes) >= 1\n ? 'cooldown'\n : draft?.trigger.everyTime\n ? 'every'\n : ''\n }\n onChange={(event) => {\n const mode = event.target.value\n patch((previous) => ({\n ...previous,\n trigger: {\n ...previous.trigger,\n // Every occurrence (AGL-562): repeatable UI\n // choreography (menu/drawer toggles).\n everyTime: mode === 'every',\n oncePerVisitor: mode === 'visitor',\n oncePerSession: mode === 'session',\n cooldownMinutes:\n mode === 'cooldown'\n ? Number(previous.trigger.cooldownMinutes) >= 1\n ? Number(previous.trigger.cooldownMinutes)\n : 60\n : undefined,\n },\n }))\n }}\n >\n <MenuItem value=\"\">{'Every matching pageview'}</MenuItem>\n <MenuItem value=\"every\">\n {'Every occurrence (repeatable)'}\n </MenuItem>\n <MenuItem value=\"session\">{'Once per session'}</MenuItem>\n <MenuItem value=\"visitor\">{'Once per visitor'}</MenuItem>\n <MenuItem value=\"cooldown\">{'With a cooldown'}</MenuItem>\n </TextField>\n {Number(draft?.trigger.cooldownMinutes) >= 1 &&\n !draft?.trigger.oncePerVisitor &&\n !draft?.trigger.oncePerSession ? (\n <TextField\n type=\"number\"\n label=\"Cooldown (minutes)\"\n size=\"small\"\n sx={{ width: 150 }}\n value={draft?.trigger.cooldownMinutes ?? 60}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: {\n ...previous.trigger,\n cooldownMinutes: Number(event.target.value),\n },\n }))\n }\n />\n ) : null}\n </Stack>\n ) : null}\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Steps (run in order)'}\n </Typography>\n {(draft?.steps ?? []).map((step, index) => (\n <AutomationStepFields\n key={index}\n step={step}\n index={index}\n kind={step.type}\n kinds={ACTION_STEP_KINDS}\n stepForKind={(value) => defaultStep(value as HostActionStepType)}\n pickers={stepPickers}\n onSteps={(update) =>\n patch((previous) => ({\n ...previous,\n steps: update(previous.steps),\n }))\n }\n replyContext={{\n event: draft?.trigger.event,\n afterWait: stepRunsAfterWait(draft?.steps, index),\n }}\n siteHostId={hostId}\n />\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n disabled={(draft?.steps.length ?? 0) >= ACTION_MAX_STEPS}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n steps: [...previous.steps, defaultStep('siteAlert')],\n }))\n }\n >\n {'Add step'}\n </Button>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim()}\n onClick={handleSave}\n >\n {'Save action'}\n </Button>\n </DialogActions>\n </Dialog>\n <Dialog\n open={Boolean(pickFor)}\n onClose={() => setPickFor(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{pickFor?.title ?? ''}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: 1 }}\n >\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`${pickFor?.picks?.prompt ?? ''} The action opens ready to edit; ` +\n 'nothing is saved until you save it.'}\n </Typography>\n {pickTruncated ? (\n <Alert severity=\"info\">\n {`Offering the first ${EDITOR_OPTION_CEILING} ${pickFor?.picks?.plural ?? ''}, ` +\n `ordered by id. This site has more, so the ` +\n `${(pickFor?.picks?.label ?? '').toLowerCase()} you want may not be listed.`}\n </Alert>\n ) : null}\n {pickOptions.length ? (\n <TextField\n select\n label={pickFor?.picks?.label ?? ''}\n value={pickedId}\n onChange={(event) => setPickedId(event.target.value)}\n size=\"small\"\n sx={{ mt: 1 }}\n >\n {pickOptions.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {option.name}\n </MenuItem>\n ))}\n </TextField>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {pickFor?.picks?.none ?? ''}\n </Typography>\n )}\n </DialogContent>\n <DialogActions>\n <Button color=\"inherit\" onClick={() => setPickFor(null)}>\n {'Cancel'}\n </Button>\n <Button\n variant=\"contained\"\n disabled={!pickedId}\n onClick={handlePicked}\n >\n {'Use recipe'}\n </Button>\n </DialogActions>\n </Dialog>\n <Dialog\n open={Boolean(runsFor)}\n onClose={() => setRunsFor(null)}\n // md: the history's four columns fit without the table scrolling.\n maxWidth=\"md\"\n fullWidth\n >\n <DialogTitle>{`Runs — ${runsFor?.name ?? ''}`}</DialogTitle>\n <DialogContent>\n {runsFor ? (\n <HostRunHistoryCard\n hostId={hostId}\n orgId={org?.$id}\n targetId={runsFor.$id}\n targetType=\"action\"\n targetName={runsFor.name ?? ''}\n header=\"Recent runs\"\n />\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button color=\"inherit\" onClick={() => setRunsFor(null)}>\n {'Close'}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nHostActionsCard.displayName = 'HostActionsCard'\n\nexport default HostActionsCard\n"],"names":["ACTION_MAX_STEPS","checkEntitlement","createResourceUid","ELEMENT_SCOPED_SITE_EVENTS","HOST_EVENT_TYPES","hostEventLabel","HOST_EVENT_PAYLOAD_KEYS","hostEventPayloadHint","isSiteEventType","pluginDocsHelp","SITE_EVENT_TYPES","triggerFilterProblem","useConsoleWidgetSlot","interactionRecipe","interactionRecipes","interactionRecipeStamp","pluginRecordListQuery","pluginRecordsFromRows","AUTOMATION_EDITOR_ZONE","HOST_AUTOMATIONS_ZONE","OPEN_ACTION_PARAM","requestedActionId","CardDisplay","useConfirmationContext","ListPagination","TABLE_PAGE_SIZE_DEFAULT","useSnackbar","authorizedFetch","Timestamp","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","ListItemText","Menu","MenuItem","Stack","Switch","TextField","Typography","collection","doc","setDoc","updateDoc","useCallback","useEffect","useMemo","useRef","useState","ceilingedWindow","collectionCeiling","useFirestore","useFirestoreCollection","useHostResourceApi","useUser","writeGuardedBySeed","ACTION_TEST_RUN_API_ROUTE","AutomationStepFields","defaultStep","ElementSelectorField","conditionRowsFromTrigger","conditionsFromRows","EMPTY_CONDITION_ROW","TriggerConditionRows","HostRunHistoryCard","EDITOR_OPTION_CEILING","useAutomationStepPickers","siteInteractionDocument","HOST_ACTION_STEP_LABELS","stepRunsAfterWait","validateHostAction","describeInteractionPlaceholder","interactionPlaceholders","CUSTOM_EVENT_VALUE","ACTION_CEILING","ACTION_STEP_KINDS","Object","entries","map","value","label","draftFromAction","action","id","builtIn","includes","trigger","event","String","name","filter","selector","threshold","pathPattern","oncePerVisitor","oncePerSession","everyTime","Number","cooldownMinutes","steps","enabled","customEvent","conditionRows","conditionCombinator","combinator","recipe","LEAF_SELECTOR","HostActionsCard","props","runsFor","pickFor","hostId","org","firestore","createResource","data","user","enqueueSnackbar","confirm","ExtensionZone","actionDocs","status","actionsStatus","fromCache","actionsFromCache","idField","rows","readActions","truncated","actionsTruncated","draft","setDraft","editorOpened","setEditorOpened","pickers","stepPickers","truncatedPickers","liveActions","deletedAt","listedRef","current","openAction","actionId","find","row","$id","requested","setRequested","window","location","search","url","URL","href","searchParams","delete","history","replaceState","state","toString","length","elementScoped","test","actions","sort","a","b","localeCompare","page","setPage","pageSize","setPageSize","visibleActions","slice","patch","updater","previous","draftId","draftName","editorTarget","type","actionsEntitled","variant","persist","handleAdd","recipesAnchor","setRecipesAnchor","setPickFor","pickedId","setPickedId","pickKind","picks","kind","pickedKind","setPickedKind","pickRead","limit","pickRows","pickTruncated","pickOptions","record","facts","eventCarriesFormId","Boolean","formConditionOpened","setFormConditionOpened","formConditionRead","formOptions","handleRecipe","build","handlePicked","picked","option","setRunsFor","handleTestRun","response","method","headers","body","JSON","stringify","payload","json","catch","ok","error","alerts","Array","isArray","message","console","handleSave","isCustom","candidate","trim","undefined","problem","resource","verdict","subject","unreadable","updatedAt","now","createdAt","merge","allowDuplicate","handleDelete","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","handleToggle","target","checked","missing","join","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","size","onChange","flex","minWidth","noWrap","step","onClick","rowCount","count","onPageChange","onPageSizeChange","severity","alignSelf","aria-haspopup","aria-controls","aria-expanded","currentTarget","slot","orgId","anchorEl","open","onClose","primary","secondary","slotProps","whiteSpace","maxWidth","fullWidth","display","flexDirection","gap","pt","mt","autoFocus","select","eventType","placeholder","helperText","onRowsChange","update","onCombinatorChange","initialPath","width","mode","index","kinds","stepForKind","onSteps","replyContext","afterWait","siteHostId","disabled","prompt","plural","toLowerCase","none","targetId","targetType","targetName","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,gBAAgB,EAEhBC,gBAAgB,EAChBC,iBAAiB,EACjBC,0BAA0B,EAC1BC,gBAAgB,EAChBC,cAAc,EACdC,uBAAuB,EACvBC,oBAAoB,EAEpBC,eAAe,EACfC,cAAc,EACdC,gBAAgB,EAEhBC,oBAAoB,QACf,eAAc;AACrB,SAASC,oBAAoB,QAAQ,qDAAoD;AACzF,SAEEC,iBAAiB,EACjBC,kBAAkB,EAClBC,sBAAsB,QACjB,kDAAiD;AACxD,SACEC,qBAAqB,EACrBC,qBAAqB,QAChB,kDAAiD;AACxD,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,iBAAiB,EACjBC,iBAAiB,QAEZ,sBAAkB;AACzB,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAAS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AAG;AAE9B,eAAe5N,gBAAe"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/host-actions-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n ACTION_MAX_STEPS,\n type AglynOrgBilling,\n checkEntitlement,\n createResourceUid,\n ELEMENT_SCOPED_SITE_EVENTS,\n HOST_EVENT_TYPES,\n hostEventLabel,\n HOST_EVENT_PAYLOAD_KEYS,\n hostEventPayloadHint,\n type HostEventType,\n isSiteEventType,\n pluginDocsHelp,\n SITE_EVENT_TYPES,\n type TriggerCombinator,\n triggerFilterProblem,\n} from '@aglyn/aglyn'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport {\n type InteractionRecipe,\n interactionRecipe,\n interactionRecipes,\n interactionRecipeStamp,\n} from '@aglyn/aglyn/plugin-manager/interaction-recipes'\nimport {\n pluginRecordListQuery,\n pluginRecordsFromRows,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-lists'\nimport {\n AUTOMATION_EDITOR_ZONE,\n HOST_AUTOMATIONS_ZONE,\n OPEN_ACTION_PARAM,\n requestedActionId,\n type AutomationTarget,\n} from './workflow-zones'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n ListItemText,\n Menu,\n MenuItem,\n Stack,\n Switch,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport {\n ceilingedWindow,\n collectionCeiling,\n useFirestore,\n useFirestoreCollection,\n useHostResourceApi,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport { ACTION_TEST_RUN_API_ROUTE } from '../model/action-test-run'\nimport {\n AutomationStepFields,\n type AutomationStepKind,\n defaultStep,\n} from './automation-step-fields.component'\nimport { ElementSelectorField } from './element-selector-field.component'\nimport {\n conditionRowsFromTrigger,\n conditionsFromRows,\n type ConditionRowDraft,\n EMPTY_CONDITION_ROW,\n TriggerConditionRows,\n} from './automation-trigger-conditions.component'\nimport HostRunHistoryCard from './host-run-history-card.component'\nimport {\n EDITOR_OPTION_CEILING,\n useAutomationStepPickers,\n} from './use-automation-step-pickers'\nimport { siteInteractionDocument } from '@aglyn/aglyn/app-utils/site-interactions'\nimport {\n HOST_ACTION_STEP_LABELS,\n type HostAction,\n type HostActionStepType,\n stepRunsAfterWait,\n validateHostAction,\n} from '../model/host-actions'\nimport {\n describeInteractionPlaceholder,\n interactionPlaceholders,\n} from '@aglyn/aglyn/app-utils/draft-placeholders'\n\nconst CUSTOM_EVENT_VALUE = '__custom__'\n\n/**\n * How many action documents the card reads.\n *\n * A CEILING, not a page size — see the query, which explains why this one\n * collection cannot be sliced by the server without making the count beneath\n * the list a per-page number.\n *\n * `ACTIONS_MAX_PER_HOST` is 500, so the ceiling really can bite and the probe\n * beside it is what says when it has.\n */\nconst ACTION_CEILING = 100\n\ninterface ActionDraft extends HostAction {\n id: string | null\n /** Raw custom-event text when the trigger select is on \"custom\". */\n customEvent: string\n // Structured payload conditions (AGL-557), chainable with AND/OR\n // (AGL-565) — held as rows like the steps list; legacy\n // single-`condition` docs hydrate through normalizeTriggerConditions.\n conditionRows: ConditionRowDraft[]\n conditionCombinator: TriggerCombinator\n /**\n * The recipe this draft started from (AGL-2626), so the editor can say\n * so, and what Save writes back as the action's stamp (AGL-2639): null\n * for an action begun blank, and `undefined` for a stored action from\n * before the stamp existed — which Save leaves as it found it, so an\n * edit never turns \"unknown\" into \"no recipe\".\n */\n recipe: string | null | undefined\n}\n\n\n/** Every Actions step, as the builder's \"Do\" picker offers it. */\nconst ACTION_STEP_KINDS: AutomationStepKind[] = Object.entries(\n HOST_ACTION_STEP_LABELS,\n).map(([value, label]) => ({ value, label }))\n\n\n/**\n * A stored action — or one a recipe just built — as the editor holds it.\n *\n * One conversion for both doors, because they must agree: an action that\n * round-trips through Edit and one a recipe hands over are the same shape\n * to the editor, and a field the Edit path hydrated that the recipe path\n * forgot would be a recipe whose conditions vanished on open. Site events\n * are first-class (AGL-256/266): their selector/threshold/path config is\n * kept through an edit. Structured conditions (AGL-557; chained AGL-565)\n * become rows; a legacy single-condition doc normalizes to one row.\n */\nfunction draftFromAction(\n action: Record<string, any>,\n id: string | null,\n): ActionDraft {\n const builtIn =\n HOST_EVENT_TYPES.includes(action.trigger?.event) ||\n isSiteEventType(String(action.trigger?.event ?? ''))\n return {\n id,\n name: action.name ?? '',\n trigger: {\n event: builtIn ? action.trigger.event : CUSTOM_EVENT_VALUE,\n filter: action.trigger?.filter ?? '',\n selector: action.trigger?.selector ?? '',\n threshold: action.trigger?.threshold,\n pathPattern: action.trigger?.pathPattern ?? '',\n oncePerVisitor: action.trigger?.oncePerVisitor === true,\n oncePerSession: action.trigger?.oncePerSession === true,\n everyTime: action.trigger?.everyTime === true,\n ...(Number(action.trigger?.cooldownMinutes) >= 1\n ? { cooldownMinutes: Number(action.trigger?.cooldownMinutes) }\n : {}),\n },\n steps: action.steps ?? [],\n enabled: action.enabled !== false,\n customEvent: builtIn ? '' : (action.trigger?.event ?? ''),\n conditionRows: conditionRowsFromTrigger(action.trigger),\n conditionCombinator: action.trigger?.combinator === 'or' ? 'or' : 'and',\n // A recipe stamps what it builds, and a stored action carries what it\n // was saved with — one reader for both doors, unknown kept unknown.\n recipe: interactionRecipeStamp(action),\n }\n}\n\n/** A trigger bound to one element, which makes the row an interaction. */\nconst LEAF_SELECTOR = /^\\[data-aglyn=\"leaf:.+\"\\]$/\n\n/**\n * Actions builder (AGL-148): HubSpot-style enrollment — trigger event →\n * optional filter → ordered steps (run workflow, site alert, custom\n * event, dataset append). Runs server-side via runEventActions; paid\n * feature (`actions` flag, Pro+, `actionRunsPerMonth` metered).\n */\nexport function HostActionsCard(props: {\n hostId: string\n org?: Partial<AglynOrgBilling>\n}) {\n const { hostId, org } = props\n // Org-shared data root (AGL-237). Null until the org lookup settles\n // (AGL-1061), and for a host with no owning org — the pre-migration host\n // path is gone (AGL-1050), so the dataset and list pickers stay empty\n // instead of offering rows from a path nothing else reads.\n const firestore = useFirestore()\n // Action creation is server-owned since AGL-2266 (the cap); every other\n // action write on this surface stays client-direct.\n const createResource = useHostResourceApi()\n // The caller's token, for the test run's console door.\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n /**\n * The shell's zone renderer, for what other plugins add to automations\n * (AGL-2919); `null` outside the console shell, where there is no workspace\n * to gate on.\n */\n const ExtensionZone = useConsoleWidgetSlot()\n\n const {\n data: actionDocs,\n status: actionsStatus,\n /**\n * The action rows this card's editor is seeded from are unconfirmed by\n * the server (AGL-1358). Editing an action copies the whole stored row\n * into `draft` — name, trigger and every step — and writes all of it\n * back, so `merge: true` protects nothing and a cached seed reverts a\n * colleague's newer version of the steps nobody here touched.\n *\n * The same shape the interaction builder guards (AGL-1066); this is its\n * card twin, and it was the one that never got the guard.\n */\n fromCache: actionsFromCache,\n listen: actionsListen,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501) —\n * the same decision as the workflows card beside it.\n *\n * `limit(100)` alone is answered in DOCUMENT-ID order, so the window was a\n * pseudo-random hundred that the `localeCompare` below arranged\n * alphabetically, and nothing said the list was bounded.\n *\n * `collectionCeiling` does not change WHICH hundred — document-id order is\n * what the bare cap already returned. What it changes is that the order is\n * NAMED, so the obvious next edit is caught: ordering on `name` would HIDE\n * every action written without one rather than mis-sorting the list, and\n * `/api/hosts/resources` validates no field for presence while\n * `IMPORTABLE_FIELDS.actions` copies one only if the export carried it.\n *\n * The QUERY is not paged because this collection holds TWO audiences. A\n * row whose trigger names a leaf selector is an element interaction, which\n * belongs to its document and is reported below as a count rather than\n * listed; the rest are the site's actions. Both partitions are derived\n * from the rows in hand, so a server page would make \"3 interactions are\n * set up on their own elements\" mean \"3 on this page\" — a count that is a\n * window length, which is the defect this sweep keeps finding rather than\n * a shape it should add.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'actions'),\n ACTION_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readActions, truncated: actionsTruncated } =\n ceilingedWindow<any>(actionDocs, ACTION_CEILING)\n const [draft, setDraft] = useState<ActionDraft | null>(null)\n /**\n * The editor has been opened at least once in this session.\n *\n * A LATCH rather than `draft` itself, because the pickers below key their\n * listeners on it. Tracking the dialog would tear those subscriptions down\n * on Cancel and pay for them again on the next Edit, so a merchant working\n * through ten actions would buy the same six windows ten times — worse than\n * the mount-time read this replaces. Latched, a reader who never edits pays\n * nothing and a reader who edits pays once.\n */\n const [editorOpened, setEditorOpened] = useState(false)\n if (draft && !editorOpened) setEditorOpened(true)\n /*\n * The step editor's six option lists, read on the same latch as the\n * Workflows builder's — one hook, because the two editors offer one set of\n * steps and a second copy would be a second read cost to keep in agreement.\n */\n const { pickers: stepPickers, truncated: truncatedPickers } =\n useAutomationStepPickers(hostId, editorOpened)\n const liveActions = readActions.filter((action: any) => !action.deletedAt)\n /*\n * Opens a listed action in the editor, for a widget in the `hostAutomations`\n * zone — one that drafted an action and offers to open it. Read through a\n * ref so the callback keeps one identity while the list changes beneath it,\n * and answers `false` for an id the list has not read yet.\n */\n const listedRef = useRef<any[]>(liveActions)\n listedRef.current = liveActions\n const openAction = useCallback((actionId: string) => {\n const action = listedRef.current.find((row: any) => row.$id === actionId)\n if (!action) return false\n setDraft(draftFromAction(action, action.$id))\n return true\n }, [])\n /*\n * An action the address names (AGL-3603): the Workflows section drafts one\n * there and sends the reader here to open it. Opened once the list has read\n * it, then dropped from the address so a reload does not reopen it.\n */\n const [requested, setRequested] = useState<string | null>(() =>\n typeof window === 'undefined' ? null : requestedActionId(window.location.search),\n )\n useEffect(() => {\n if (!requested || !openAction(requested)) return\n setRequested(null)\n const url = new URL(window.location.href)\n url.searchParams.delete(OPEN_ACTION_PARAM)\n window.history.replaceState(window.history.state, '', url.toString())\n }, [requested, openAction, liveActions.length])\n /**\n * Element interactions are not listed here.\n *\n * An ACTION is something the SITE does — an order was placed, a form was\n * submitted. An INTERACTION is something an ELEMENT does, and it belongs to\n * the document that holds the element: it publishes and rolls back with it,\n * travels with it, and is deleted with it. This page is the site's\n * automation list, and a nav menu's hover timing sitting in it beside \"when\n * an order is placed\" was the tell that the two had been conflated.\n *\n * These rows are the ones written BEFORE the move, still bound by selector.\n * They keep running and stay editable — on their element, in the besigner,\n * which is now the only place they appear. Counted rather than hidden\n * outright, so the page can say where they went instead of appearing to\n * have lost them.\n */\n const elementScoped = liveActions.filter((action: any) =>\n LEAF_SELECTOR.test(String(action?.trigger?.selector ?? '')),\n )\n // Sorting is safe here in a way it is not on a paged list: these rows are\n // the whole collection below the ceiling, not a slice of one.\n const actions = liveActions\n .filter((action: any) => !elementScoped.includes(action))\n .sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n )\n // The page is a SLICE: the rows are already in hand, and both the element\n // interaction count and the alphabetical order need all of them.\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const visibleActions = useMemo(\n () => actions.slice(page * pageSize, page * pageSize + pageSize),\n [actions, page, pageSize],\n )\n\n const patch = useCallback(\n (updater: (previous: ActionDraft) => ActionDraft) =>\n setDraft((previous) => (previous ? updater(previous) : previous)),\n [],\n )\n\n /** The saved action the editor has open, as the `automationEditor` zone names it. */\n const draftId = draft?.id ?? null\n const draftName = draft?.name ?? ''\n const editorTarget = useMemo<AutomationTarget | null>(\n () => (draftId ? { type: 'action', id: draftId, name: draftName } : null),\n // The name the editor opened with: the zone reads the automation as it is\n // stored, so a rename being typed does not make it a different one.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [draftId],\n )\n\n /**\n * Whether this workspace may open the editor at all. One gate for the\n * blank action and the recipes: a recipe is an action, so the plan that\n * carries one carries the other, and the refusal reads the same.\n */\n const actionsEntitled = useCallback(() => {\n if (checkEntitlement(org, 'actions')) return true\n enqueueSnackbar(\n 'The actions builder requires a Pro plan — see Billing to upgrade',\n { variant: 'warning', persist: false },\n )\n return false\n }, [org, enqueueSnackbar])\n\n const handleAdd = useCallback(() => {\n if (!actionsEntitled()) return\n setDraft({\n id: null,\n name: '',\n trigger: { event: 'formSubmission', filter: '' },\n steps: [defaultStep('siteAlert')],\n enabled: true,\n customEvent: '',\n conditionRows: [EMPTY_CONDITION_ROW],\n conditionCombinator: 'and',\n recipe: null,\n })\n }, [actionsEntitled])\n\n /*\n * THE RECIPES (AGL-2626).\n *\n * A recipe opens the editor prefilled and writes nothing: the draft it\n * builds is the one Save would persist, and until then it is state in\n * this card and nowhere else. The recipes are the plugins' that write them\n * (`interaction-recipes`, AGL-3080) — the CRM's \"Welcome a new lead\" is the\n * CRM's — and this card offers whatever they registered. Most open at once;\n * one that picks a record first opens a picker, and the records are listed\n * through the list source the plugin that keeps them publishes, for this\n * site — the one host-scoped piece of the feature, held here rather than in\n * the recipe.\n */\n const [recipesAnchor, setRecipesAnchor] = useState<HTMLElement | null>(null)\n const [pickFor, setPickFor] = useState<InteractionRecipe | null>(null)\n const [pickedId, setPickedId] = useState('')\n /**\n * The picker has been opened at least once — the `editorOpened` latch's\n * twin, and for the same reason: the records are read for this picker only,\n * and a reader who never opens it pays nothing.\n */\n const pickKind = pickFor?.picks?.kind ?? null\n const [pickedKind, setPickedKind] = useState<string | null>(null)\n if (pickKind && pickKind !== pickedKind) setPickedKind(pickKind)\n const { data: pickRead } = useFirestoreCollection<any>(\n () =>\n pickedKind\n ? pluginRecordListQuery(pickedKind, firestore, {\n hostId,\n limit: EDITOR_OPTION_CEILING + 1,\n })\n : null,\n [firestore, hostId, pickedKind],\n { idField: '$id' },\n )\n const { rows: pickRows, truncated: pickTruncated } = ceilingedWindow<any>(\n pickRead,\n EDITOR_OPTION_CEILING,\n )\n // What the owner leaves out (an archived form collects nothing, so a recipe\n // keyed on it would never fire) is not offered. The facts the owner shares\n // ride along to the recipe, which may shape its draft by them (AGL-3458).\n const pickOptions = pluginRecordsFromRows(pickedKind ?? '', pickRows)\n .map((record) => ({ id: record.id, name: record.name, facts: record.facts }))\n .sort((a, b) => a.name.localeCompare(b.name))\n\n /*\n * The site's forms for the trigger's \"Form is\" condition (AGL-3458), for an\n * event that carries the form's id — through the same list source the\n * recipe picker reads, latched like it: read once the editor is open on\n * such an event, and never before.\n */\n const eventCarriesFormId = Boolean(\n draft && HOST_EVENT_PAYLOAD_KEYS[draft.trigger.event as HostEventType]?.includes('formId'),\n )\n const [formConditionOpened, setFormConditionOpened] = useState(false)\n if (eventCarriesFormId && !formConditionOpened) setFormConditionOpened(true)\n const { data: formConditionRead } = useFirestoreCollection<any>(\n () =>\n formConditionOpened\n ? pluginRecordListQuery('form', firestore, {\n hostId,\n limit: EDITOR_OPTION_CEILING + 1,\n })\n : null,\n [firestore, hostId, formConditionOpened],\n { idField: '$id' },\n )\n const formOptions = pluginRecordsFromRows(\n 'form',\n ceilingedWindow<any>(formConditionRead, EDITOR_OPTION_CEILING).rows,\n )\n .map((record) => ({ id: record.id, name: record.name }))\n .sort((a, b) => a.name.localeCompare(b.name))\n\n const handleRecipe = useCallback(\n (recipe: InteractionRecipe) => {\n setRecipesAnchor(null)\n if (!actionsEntitled()) return\n if (recipe.picks) {\n setPickedId('')\n setPickFor(recipe)\n return\n }\n setDraft(draftFromAction(recipe.build(), null))\n },\n [actionsEntitled],\n )\n\n const handlePicked = useCallback(() => {\n const recipe = pickFor\n const picked = pickOptions.find((option) => option.id === pickedId)\n if (!recipe || !picked) return\n setPickFor(null)\n setDraft(draftFromAction(recipe.build({ picked }), null))\n }, [pickFor, pickOptions, pickedId])\n\n // Run log + test runs (AGL-266).\n const [runsFor, setRunsFor] = useState<any | null>(null)\n const handleTestRun = useCallback(\n async (action: any) => {\n try {\n /*\n * The console's own door, signed: a page's `events/dispatch` is a\n * tenant route this origin does not serve. The route reads the\n * trigger off the stored action and marks the run as a test, so the\n * body names only which action on which site.\n */\n const response = await authorizedFetch(\n user,\n `/api/${ACTION_TEST_RUN_API_ROUTE}`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ hostId, actionId: action.$id }),\n },\n )\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n return void enqueueSnackbar(payload?.error ?? 'Test run failed', {\n variant: 'warning',\n persist: false,\n })\n }\n const alerts = Array.isArray(payload?.alerts) ? payload.alerts : []\n enqueueSnackbar(\n alerts.length\n ? `Test ran — first alert: ${alerts[0].message}`\n : 'Test ran — server steps executed (see Runs)',\n { variant: 'success', persist: false },\n )\n } catch (error) {\n console.error(error)\n enqueueSnackbar('Test run failed', { variant: 'error' })\n }\n },\n [hostId, user, enqueueSnackbar],\n )\n\n const handleSave = useCallback(async () => {\n if (!draft) return\n const isCustom = draft.trigger.event === CUSTOM_EVENT_VALUE\n const candidate: HostAction = {\n name: draft.name.trim().slice(0, 60),\n trigger: {\n event: isCustom ? draft.customEvent.trim() : draft.trigger.event,\n ...(draft.trigger.filter?.trim()\n ? { filter: draft.trigger.filter.trim() }\n : {}),\n // Site-event config (AGL-256).\n ...(draft.trigger.selector?.trim()\n ? { selector: draft.trigger.selector.trim() }\n : {}),\n ...(Number(draft.trigger.threshold) > 0\n ? { threshold: Number(draft.trigger.threshold) }\n : {}),\n ...(draft.trigger.pathPattern?.trim()\n ? { pathPattern: draft.trigger.pathPattern.trim() }\n : {}),\n // Frequency caps (AGL-274).\n ...(draft.trigger.oncePerVisitor === true\n ? { oncePerVisitor: true }\n : {}),\n ...(draft.trigger.oncePerSession === true\n ? { oncePerSession: true }\n : {}),\n ...(Number(draft.trigger.cooldownMinutes) >= 1\n ? { cooldownMinutes: Number(draft.trigger.cooldownMinutes) }\n : {}),\n ...(draft.trigger.everyTime === true ? { everyTime: true } : {}),\n // Structured payload conditions (AGL-557; chained AGL-565):\n // rows keep their blank fields so validateHostAction surfaces\n // the miss. Saves always write the list shape — the legacy\n // single `condition` is only ever read, never written back.\n ...conditionsFromRows(draft.conditionRows, draft.conditionCombinator),\n },\n steps: draft.steps,\n enabled: draft.enabled !== false,\n // The stamp travels only when the draft knows one way or the other;\n // an older action's silence is kept (see interactionRecipeStamp).\n ...(draft.recipe !== undefined ? { recipe: draft.recipe } : {}),\n }\n const problem = validateHostAction(candidate)\n if (problem) {\n return void enqueueSnackbar(problem, {\n variant: 'warning',\n persist: false,\n })\n }\n try {\n const id = draft.id ?? createResourceUid()\n /**\n * Refuse an EDIT whose seed the server never confirmed (AGL-1358).\n *\n * The payload is the whole action. `merge: true` is here so the\n * frequency caps and conditions can be nulled explicitly, not to\n * protect untouched fields — there are none, they are all in the\n * payload. So a cached seed does not lose one edit, it reverts the\n * trigger and every step to whatever the cache last held, on an\n * automation that is running on a live site.\n *\n * Only the edit path. A NEW action is built from `EMPTY_*` defaults at\n * a fresh uid and can overwrite nothing; the first snapshot of any\n * listener is `fromCache: true`, so guarding a create would refuse a\n * save that was never unsafe.\n *\n * The guard WRAPS the write — the interaction builder's early return\n * is the shape you can keep while losing the protection.\n */\n /**\n * The action DOCUMENT is created by the server (AGL-2266).\n *\n * `hosts/{hostId}/actions` was in none of the host catch-all's exclusion\n * lists, so any editor could create one client-direct on any plan and\n * nothing counted them. /api/hosts/resources now owns the create and\n * holds `ACTIONS_MAX_PER_HOST` from a server read.\n *\n * Only the create moves, and it writes a SHELL. The merge-set below is\n * untouched and still carries the whole candidate — trigger, steps,\n * conditions, the explicit nulls AGL-274/557 depend on — so no field can\n * be lost to the route's allow-list, and for an existing action this\n * path does not run at all.\n */\n if (!draft.id) {\n try {\n await createResource({\n hostId,\n resource: 'action',\n id,\n data: { name: candidate.name ?? draft.name ?? 'Untitled action' },\n })\n } catch (error: any) {\n return void enqueueSnackbar(\n error?.message ?? 'Could not create the interaction',\n { variant: 'error' },\n )\n }\n }\n const verdict = await writeGuardedBySeed(\n {\n subject: 'action',\n unreadable: Boolean(draft.id) && actionsStatus === 'error',\n fromCache: Boolean(draft.id) && actionsFromCache,\n listen: actionsListen,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'actions', id),\n {\n // The stored shape (AGL-2639), shared with the recipe-install\n // route: frequency caps overwrite explicitly (AGL-274) because\n // a merge-set keeps omitted keys, so switching one off must\n // write it out; conditions follow suit (AGL-557/565) — the\n // list + combinator write null when cleared, and the legacy\n // single `condition` is always nulled.\n ...siteInteractionDocument(candidate),\n updatedAt: Timestamp.now(),\n ...(draft.id ? {} : { createdAt: Timestamp.now() }),\n },\n { merge: true },\n )\n },\n )\n // A refusal keeps the editor open with everything that was typed.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n setDraft(null)\n enqueueSnackbar('Action saved', { variant: 'success', persist: false })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n draft,\n firestore,\n createResource,\n hostId,\n enqueueSnackbar,\n actionsFromCache,\n actionsListen,\n actionsStatus,\n ])\n\n const handleDelete = useCallback(\n (action: any) => async () => {\n const confirmed = await confirm({\n title: 'Delete this action?',\n description: `\"${action.name}\" stops running on its trigger.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await updateDoc(doc(firestore, 'hosts', hostId, 'actions', action.$id), {\n deletedAt: Timestamp.now(),\n })\n },\n [confirm, firestore, hostId],\n )\n\n const handleToggle = useCallback(\n (action: any) => async (event: { target: { checked: boolean } }) => {\n const enabled = event.target.checked\n /*\n * A placeholder is a value nobody has supplied yet. Switched on, the\n * step holding it fails every run and a condition holding one never\n * matches, so turning such an automation on is confirmed, naming what\n * is still missing.\n */\n const missing = enabled ? interactionPlaceholders(action) : []\n if (missing.length) {\n const confirmed = await confirm({\n title: 'Switch on with placeholders?',\n description:\n `\"${action.name}\" still has ${missing.length === 1 ? 'a placeholder' : `${missing.length} placeholders`} ` +\n `to fill in: ${missing.slice(0, 3).map(describeInteractionPlaceholder).join('; ')}` +\n `${missing.length > 3 ? '; …' : ''}. Open it with Edit to fill ` +\n `${missing.length === 1 ? 'it' : 'them'} in first.`,\n confirmationText: 'Switch on anyway',\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n }\n await updateDoc(doc(firestore, 'hosts', hostId, 'actions', action.$id), {\n enabled,\n })\n },\n [confirm, firestore, hostId],\n )\n\n return (\n <CardDisplay\n header={'Actions'}\n help={pluginDocsHelp('actionsBuilder', { anchor: '#create-an-action' })}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'When a site event fires, run automations in order — trigger a ' +\n 'workflow, show the visitor an alert, chain a custom event, or ' +\n 'write to a dataset. Pro plans and up.'}\n </Typography>\n {visibleActions.map((action: any) => {\n const missing = interactionPlaceholders(action).length\n return (\n <Stack\n key={action.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Switch\n size=\"small\"\n checked={action.enabled !== false}\n onChange={handleToggle(action)}\n />\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {action.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {[\n `on ${hostEventLabel(action.trigger?.event)}`,\n (action.steps ?? [])\n .map(\n (step: any) =>\n HOST_ACTION_STEP_LABELS[\n step.type as HostActionStepType\n ] ?? step.type,\n )\n .filter(Boolean)\n .join(' → '),\n ]\n .filter(Boolean)\n .join(' · ')}\n </Typography>\n {missing ? (\n <Typography variant=\"caption\" color=\"warning.main\" noWrap>\n {missing === 1\n ? '1 placeholder to fill in'\n : `${missing} placeholders to fill in`}\n </Typography>\n ) : null}\n </Stack>\n <Button\n size=\"small\"\n onClick={() => setDraft(draftFromAction(action, action.$id))}\n >\n {'Edit'}\n </Button>\n {isSiteEventType(String(action.trigger?.event ?? '')) ? (\n // Test run (AGL-266): the server steps only, run now as a real\n // run through the console's test-run door.\n <Button size=\"small\" onClick={() => void handleTestRun(action)}>\n {'Test'}\n </Button>\n ) : null}\n <Button size=\"small\" onClick={() => setRunsFor(action)}>\n {'Runs'}\n </Button>\n <Button size=\"small\" color=\"error\" onClick={handleDelete(action)}>\n {'Delete'}\n </Button>\n </Stack>\n )\n })}\n {actions.length === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={visibleActions.length}\n // The actions the card HOLDS, which is what the reader is paging\n // through — not the collection, whose other half is the element\n // interactions counted below.\n count={actions.length}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n {actionsTruncated ? (\n <Alert severity=\"info\">\n {`Showing the first ${ACTION_CEILING} rows of this site’s ` +\n 'automations, ordered by id. There are more — both the list ' +\n 'above and the interaction count below describe only what was ' +\n 'read.'}\n </Alert>\n ) : null}\n <Stack direction=\"row\" spacing={1} sx={{ alignSelf: 'flex-start' }}>\n <Button size=\"small\" color=\"primary\" onClick={handleAdd}>\n {'Add action'}\n </Button>\n <Button\n size=\"small\"\n color=\"primary\"\n aria-haspopup=\"menu\"\n aria-controls={recipesAnchor ? 'host-action-recipes' : undefined}\n aria-expanded={recipesAnchor ? true : undefined}\n onClick={(event) => setRecipesAnchor(event.currentTarget)}\n >\n {'Recipes'}\n </Button>\n {/*\n Other ways to start an automation, from plugins (AGL-2919): the\n `hostAutomations` zone, drawn through the shell's own gated slot. A\n plugin page cannot mount that slot itself, so the shell hands it\n down, and a widget here passes the gates a console page's would.\n */}\n {ExtensionZone ? (\n <ExtensionZone\n slot={HOST_AUTOMATIONS_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n openAction={openAction}\n />\n ) : null}\n </Stack>\n <Menu\n id=\"host-action-recipes\"\n anchorEl={recipesAnchor}\n open={Boolean(recipesAnchor)}\n onClose={() => setRecipesAnchor(null)}\n >\n {interactionRecipes().map((recipe) => (\n <MenuItem key={recipe.id} onClick={() => handleRecipe(recipe)}>\n <ListItemText\n primary={recipe.title}\n secondary={recipe.description}\n slotProps={{ secondary: { sx: { whiteSpace: 'normal', maxWidth: 360 } } }}\n />\n </MenuItem>\n ))}\n </Menu>\n {/* Says where they went. A list that silently drops rows\n a reader saw last week is a list they stop trusting; this is the\n one sentence that makes the absence deliberate. */}\n {elementScoped.length ? (\n <Typography variant=\"caption\" color=\"text.secondary\">\n {elementScoped.length === 1\n ? '1 interaction is set up on its own element — '\n : `${elementScoped.length} interactions are set up on their own elements — `}\n {'open the element in the besigner to edit it. Interactions ' +\n 'belong to the page they are on, so they publish and roll back ' +\n 'with it.'}\n </Typography>\n ) : null}\n </Stack>\n\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"sm\"\n fullWidth\n >\n <DialogTitle>{draft?.id ? 'Edit action' : 'Add action'}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: 1 }}\n >\n {ExtensionZone && editorTarget ? (\n <ExtensionZone\n slot={AUTOMATION_EDITOR_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n target={editorTarget}\n openAction={openAction}\n />\n ) : null}\n {draft?.recipe ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`Started from the “${\n interactionRecipe(draft.recipe)?.title ?? 'recipe'\n }” recipe — change anything, then save.`}\n </Typography>\n ) : null}\n {/*\n A short picker is worse than an empty one, because it looks\n complete: the target an author cannot find reads as deleted, and\n the step gets pointed somewhere else.\n */}\n {truncatedPickers.length > 0 ? (\n <Alert severity=\"info\" sx={{ mt: 1 }}>\n {`Offering the first ${EDITOR_OPTION_CEILING} rows, ordered by ` +\n `id, for: ${truncatedPickers.join(', ')}. This site has ` +\n 'more, so a step target may not be listed below.'}\n </Alert>\n ) : null}\n <TextField\n label=\"Name\"\n value={draft?.name ?? ''}\n onChange={(event) =>\n patch((previous) => ({ ...previous, name: event.target.value }))\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n <Stack direction=\"row\" spacing={1}>\n <TextField\n select\n label=\"Trigger event\"\n value={draft?.trigger.event ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: { ...previous.trigger, event: event.target.value },\n }))\n }\n size=\"small\"\n sx={{ minWidth: 180 }}\n >\n {HOST_EVENT_TYPES.map((eventType) => (\n <MenuItem key={eventType} value={eventType}>\n {hostEventLabel(eventType)}\n </MenuItem>\n ))}\n {SITE_EVENT_TYPES.map((eventType) => (\n <MenuItem key={eventType} value={eventType}>\n {`${eventType} (on page)`}\n </MenuItem>\n ))}\n <MenuItem value={CUSTOM_EVENT_VALUE}>{'Custom event…'}</MenuItem>\n </TextField>\n {draft?.trigger.event === CUSTOM_EVENT_VALUE ? (\n <TextField\n label=\"Custom event name\"\n value={draft?.customEvent ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n customEvent: event.target.value,\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n ) : (\n <TextField\n label=\"Filter (optional)\"\n placeholder=\"subscribe\"\n // A comparison belongs in the conditions below: the filter's\n // evaluator is arithmetic, and `path == \"/pricing\"` throws on\n // every event, so it is refused here (AGL-3458). Otherwise,\n // what the expression — and the conditions — can name for\n // this event; nothing for an event whose payload is not\n // written down, rather than a guess.\n error={Boolean(triggerFilterProblem(draft?.trigger.filter))}\n helperText={\n triggerFilterProblem(draft?.trigger.filter) ??\n hostEventPayloadHint(draft?.trigger.event) ??\n undefined\n }\n value={draft?.trigger.filter ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: {\n ...previous.trigger,\n filter: event.target.value,\n },\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n )}\n </Stack>\n {/* Structured payload conditions (AGL-557): the no-code sibling\n of the filter — e.g. only when `subscribe` is not empty.\n Chainable with AND/OR (AGL-565), rows styled like steps. */}\n <TriggerConditionRows\n rows={draft?.conditionRows ?? []}\n combinator={draft?.conditionCombinator ?? 'and'}\n onRowsChange={(update) =>\n patch((previous) => ({\n ...previous,\n conditionRows: update(previous.conditionRows),\n }))\n }\n onCombinatorChange={(combinator) =>\n patch((previous) => ({\n ...previous,\n conditionCombinator: combinator,\n }))\n }\n // \"Form is …\", picked by id, where the event names the form (AGL-3458).\n {...(eventCarriesFormId ? { formOptions } : {})}\n />\n {isSiteEventType(draft?.trigger.event ?? '') ? (\n // Site-event config (AGL-256): what/where the trigger watches.\n <Stack direction=\"row\" spacing={1}>\n {(ELEMENT_SCOPED_SITE_EVENTS as readonly string[]).includes(\n draft?.trigger.event ?? '',\n ) ? (\n <ElementSelectorField\n label=\"Element\"\n hostId={hostId}\n // Open the page the trigger is limited to, when it names one.\n initialPath={\n draft?.trigger.pathPattern && !draft.trigger.pathPattern.includes('*')\n ? draft.trigger.pathPattern\n : undefined\n }\n value={draft?.trigger.selector ?? ''}\n onChange={(selector) =>\n patch((previous) => ({\n ...previous,\n trigger: { ...previous.trigger, selector },\n }))\n }\n />\n ) : null}\n {['scrollDepth', 'timeOnPage'].includes(\n draft?.trigger.event ?? '',\n ) ? (\n <TextField\n type=\"number\"\n label={\n draft?.trigger.event === 'scrollDepth'\n ? 'Scroll %'\n : 'Seconds'\n }\n value={draft?.trigger.threshold ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: {\n ...previous.trigger,\n threshold: Number(event.target.value),\n },\n }))\n }\n size=\"small\"\n sx={{ width: 120 }}\n />\n ) : null}\n <TextField\n label=\"Only on pages (optional)\"\n placeholder=\"/pricing or /blog/*\"\n value={draft?.trigger.pathPattern ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: {\n ...previous.trigger,\n pathPattern: event.target.value,\n },\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n {/* Frequency caps (AGL-274). */}\n <TextField\n select\n label=\"Frequency\"\n size=\"small\"\n sx={{ minWidth: 170 }}\n value={\n draft?.trigger.oncePerVisitor\n ? 'visitor'\n : draft?.trigger.oncePerSession\n ? 'session'\n : Number(draft?.trigger.cooldownMinutes) >= 1\n ? 'cooldown'\n : draft?.trigger.everyTime\n ? 'every'\n : ''\n }\n onChange={(event) => {\n const mode = event.target.value\n patch((previous) => ({\n ...previous,\n trigger: {\n ...previous.trigger,\n // Every occurrence (AGL-562): repeatable UI\n // choreography (menu/drawer toggles).\n everyTime: mode === 'every',\n oncePerVisitor: mode === 'visitor',\n oncePerSession: mode === 'session',\n cooldownMinutes:\n mode === 'cooldown'\n ? Number(previous.trigger.cooldownMinutes) >= 1\n ? Number(previous.trigger.cooldownMinutes)\n : 60\n : undefined,\n },\n }))\n }}\n >\n <MenuItem value=\"\">{'Every matching pageview'}</MenuItem>\n <MenuItem value=\"every\">\n {'Every occurrence (repeatable)'}\n </MenuItem>\n <MenuItem value=\"session\">{'Once per session'}</MenuItem>\n <MenuItem value=\"visitor\">{'Once per visitor'}</MenuItem>\n <MenuItem value=\"cooldown\">{'With a cooldown'}</MenuItem>\n </TextField>\n {Number(draft?.trigger.cooldownMinutes) >= 1 &&\n !draft?.trigger.oncePerVisitor &&\n !draft?.trigger.oncePerSession ? (\n <TextField\n type=\"number\"\n label=\"Cooldown (minutes)\"\n size=\"small\"\n sx={{ width: 150 }}\n value={draft?.trigger.cooldownMinutes ?? 60}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: {\n ...previous.trigger,\n cooldownMinutes: Number(event.target.value),\n },\n }))\n }\n />\n ) : null}\n </Stack>\n ) : null}\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Steps (run in order)'}\n </Typography>\n {(draft?.steps ?? []).map((step, index) => (\n <AutomationStepFields\n key={index}\n step={step}\n index={index}\n kind={step.type}\n kinds={ACTION_STEP_KINDS}\n stepForKind={(value) => defaultStep(value as HostActionStepType)}\n pickers={stepPickers}\n onSteps={(update) =>\n patch((previous) => ({\n ...previous,\n steps: update(previous.steps),\n }))\n }\n replyContext={{\n event: draft?.trigger.event,\n afterWait: stepRunsAfterWait(draft?.steps, index),\n }}\n siteHostId={hostId}\n />\n ))}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n disabled={(draft?.steps.length ?? 0) >= ACTION_MAX_STEPS}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n steps: [...previous.steps, defaultStep('siteAlert')],\n }))\n }\n >\n {'Add step'}\n </Button>\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim()}\n onClick={handleSave}\n >\n {'Save action'}\n </Button>\n </DialogActions>\n </Dialog>\n <Dialog\n open={Boolean(pickFor)}\n onClose={() => setPickFor(null)}\n maxWidth=\"xs\"\n fullWidth\n >\n <DialogTitle>{pickFor?.title ?? ''}</DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: 1 }}\n >\n <Typography variant=\"body2\" color=\"text.secondary\">\n {`${pickFor?.picks?.prompt ?? ''} The action opens ready to edit; ` +\n 'nothing is saved until you save it.'}\n </Typography>\n {pickTruncated ? (\n <Alert severity=\"info\">\n {`Offering the first ${EDITOR_OPTION_CEILING} ${pickFor?.picks?.plural ?? ''}, ` +\n `ordered by id. This site has more, so the ` +\n `${(pickFor?.picks?.label ?? '').toLowerCase()} you want may not be listed.`}\n </Alert>\n ) : null}\n {pickOptions.length ? (\n <TextField\n select\n label={pickFor?.picks?.label ?? ''}\n value={pickedId}\n onChange={(event) => setPickedId(event.target.value)}\n size=\"small\"\n sx={{ mt: 1 }}\n >\n {pickOptions.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {option.name}\n </MenuItem>\n ))}\n </TextField>\n ) : (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {pickFor?.picks?.none ?? ''}\n </Typography>\n )}\n </DialogContent>\n <DialogActions>\n <Button color=\"inherit\" onClick={() => setPickFor(null)}>\n {'Cancel'}\n </Button>\n <Button\n variant=\"contained\"\n disabled={!pickedId}\n onClick={handlePicked}\n >\n {'Use recipe'}\n </Button>\n </DialogActions>\n </Dialog>\n <Dialog\n open={Boolean(runsFor)}\n onClose={() => setRunsFor(null)}\n // md: the history's four columns fit without the table scrolling.\n maxWidth=\"md\"\n fullWidth\n >\n <DialogTitle>{`Runs — ${runsFor?.name ?? ''}`}</DialogTitle>\n <DialogContent>\n {runsFor ? (\n <HostRunHistoryCard\n hostId={hostId}\n orgId={org?.$id}\n targetId={runsFor.$id}\n targetType=\"action\"\n targetName={runsFor.name ?? ''}\n header=\"Recent runs\"\n />\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button color=\"inherit\" onClick={() => setRunsFor(null)}>\n {'Close'}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nHostActionsCard.displayName = 'HostActionsCard'\n\nexport default HostActionsCard\n"],"names":["ACTION_MAX_STEPS","checkEntitlement","createResourceUid","ELEMENT_SCOPED_SITE_EVENTS","HOST_EVENT_TYPES","hostEventLabel","HOST_EVENT_PAYLOAD_KEYS","hostEventPayloadHint","isSiteEventType","pluginDocsHelp","SITE_EVENT_TYPES","triggerFilterProblem","useConsoleWidgetSlot","interactionRecipe","interactionRecipes","interactionRecipeStamp","pluginRecordListQuery","pluginRecordsFromRows","AUTOMATION_EDITOR_ZONE","HOST_AUTOMATIONS_ZONE","OPEN_ACTION_PARAM","requestedActionId","CardDisplay","useConfirmationContext","ListPagination","TABLE_PAGE_SIZE_DEFAULT","useSnackbar","authorizedFetch","Timestamp","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","ListItemText","Menu","MenuItem","Stack","Switch","TextField","Typography","collection","doc","setDoc","updateDoc","useCallback","useEffect","useMemo","useRef","useState","ceilingedWindow","collectionCeiling","useFirestore","useFirestoreCollection","useHostResourceApi","useUser","writeGuardedBySeed","ACTION_TEST_RUN_API_ROUTE","AutomationStepFields","defaultStep","ElementSelectorField","conditionRowsFromTrigger","conditionsFromRows","EMPTY_CONDITION_ROW","TriggerConditionRows","HostRunHistoryCard","EDITOR_OPTION_CEILING","useAutomationStepPickers","siteInteractionDocument","HOST_ACTION_STEP_LABELS","stepRunsAfterWait","validateHostAction","describeInteractionPlaceholder","interactionPlaceholders","CUSTOM_EVENT_VALUE","ACTION_CEILING","ACTION_STEP_KINDS","Object","entries","map","value","label","draftFromAction","action","id","builtIn","includes","trigger","event","String","name","filter","selector","threshold","pathPattern","oncePerVisitor","oncePerSession","everyTime","Number","cooldownMinutes","steps","enabled","customEvent","conditionRows","conditionCombinator","combinator","recipe","LEAF_SELECTOR","HostActionsCard","props","runsFor","pickFor","hostId","org","firestore","createResource","data","user","enqueueSnackbar","confirm","ExtensionZone","actionDocs","status","actionsStatus","fromCache","actionsFromCache","listen","actionsListen","idField","rows","readActions","truncated","actionsTruncated","draft","setDraft","editorOpened","setEditorOpened","pickers","stepPickers","truncatedPickers","liveActions","deletedAt","listedRef","current","openAction","actionId","find","row","$id","requested","setRequested","window","location","search","url","URL","href","searchParams","delete","history","replaceState","state","toString","length","elementScoped","test","actions","sort","a","b","localeCompare","page","setPage","pageSize","setPageSize","visibleActions","slice","patch","updater","previous","draftId","draftName","editorTarget","type","actionsEntitled","variant","persist","handleAdd","recipesAnchor","setRecipesAnchor","setPickFor","pickedId","setPickedId","pickKind","picks","kind","pickedKind","setPickedKind","pickRead","limit","pickRows","pickTruncated","pickOptions","record","facts","eventCarriesFormId","Boolean","formConditionOpened","setFormConditionOpened","formConditionRead","formOptions","handleRecipe","build","handlePicked","picked","option","setRunsFor","handleTestRun","response","method","headers","body","JSON","stringify","payload","json","catch","ok","error","alerts","Array","isArray","message","console","handleSave","isCustom","candidate","trim","undefined","problem","resource","verdict","subject","unreadable","updatedAt","now","createdAt","merge","allowDuplicate","handleDelete","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","handleToggle","target","checked","missing","join","header","help","anchor","contentGutterX","contentGutterY","spacing","direction","sx","alignItems","size","onChange","flex","minWidth","noWrap","step","onClick","rowCount","count","onPageChange","onPageSizeChange","severity","alignSelf","aria-haspopup","aria-controls","aria-expanded","currentTarget","slot","orgId","anchorEl","open","onClose","primary","secondary","slotProps","whiteSpace","maxWidth","fullWidth","display","flexDirection","gap","pt","mt","autoFocus","select","eventType","placeholder","helperText","onRowsChange","update","onCombinatorChange","initialPath","width","mode","index","kinds","stepForKind","onSteps","replyContext","afterWait","siteHostId","disabled","prompt","plural","toLowerCase","none","targetId","targetType","targetName","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SACEA,gBAAgB,EAEhBC,gBAAgB,EAChBC,iBAAiB,EACjBC,0BAA0B,EAC1BC,gBAAgB,EAChBC,cAAc,EACdC,uBAAuB,EACvBC,oBAAoB,EAEpBC,eAAe,EACfC,cAAc,EACdC,gBAAgB,EAEhBC,oBAAoB,QACf,eAAc;AACrB,SAASC,oBAAoB,QAAQ,qDAAoD;AACzF,SAEEC,iBAAiB,EACjBC,kBAAkB,EAClBC,sBAAsB,QACjB,kDAAiD;AACxD,SACEC,qBAAqB,EACrBC,qBAAqB,QAChB,kDAAiD;AACxD,SACEC,sBAAs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,KAAK,EAAEhL,uBAAAA,IAAKmC,GAAG;4BACfmL,UAAUzN,QAAQsC,GAAG;4BACrBoL,YAAW;4BACXC,UAAU,GAAE3N,gBAAAA,QAAQpB,IAAI,YAAZoB,gBAAgB;4BAC5BwJ,QAAO;6BAEP;;kCAEN,KAACvO;kCACC,cAAA,KAACF;4BAAOkO,OAAM;4BAAUsB,SAAS,IAAM7D,WAAW;sCAC/C;;;;;;;AAMb;AACA5G,gBAAgB8N,WAAW,GAAG;AAE9B,eAAe9N,gBAAe"}
@@ -124,7 +124,7 @@ import { stepRunsAfterWait } from "../model/host-actions.js";
124
124
  * card writes it, so a cached seed can re-arm an automation the author
125
125
  * disarmed — or disarm one running on a live site — and revert every
126
126
  * step of the pipeline with it.
127
- */ fromCache: workflowsFromCache } = useFirestoreCollection(/*
127
+ */ fromCache: workflowsFromCache, listen: workflowsListen } = useFirestoreCollection(/*
128
128
  * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501) —
129
129
  * the same decision as the logic plugin's two cards, for the same reasons.
130
130
  *
@@ -424,7 +424,8 @@ import { stepRunsAfterWait } from "../model/host-actions.js";
424
424
  */ const verdict = await writeGuardedBySeed({
425
425
  subject: 'workflow',
426
426
  unreadable: workflowsStatus === 'error',
427
- fromCache: workflowsFromCache
427
+ fromCache: workflowsFromCache,
428
+ listen: workflowsListen
428
429
  }, async ()=>{
429
430
  await setDoc(doc(firestore, 'hosts', hostId, 'workflows', draftId), _extends({}, fields, {
430
431
  updatedAt: Timestamp.now()
@@ -474,7 +475,8 @@ import { stepRunsAfterWait } from "../model/host-actions.js";
474
475
  createHostResource,
475
476
  enqueueSnackbar,
476
477
  workflowsStatus,
477
- workflowsFromCache
478
+ workflowsFromCache,
479
+ workflowsListen
478
480
  ]);
479
481
  const handleShowUsage = useCallback((workflow)=>async ()=>{
480
482
  setUsageLoading(workflow.$id);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/host-workflows-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n type AglynOrgBilling,\n checkEntitlement,\n checkQuota,\n HOST_EVENT_TYPES,\n hostEventLabel,\n hostEventPayloadHint,\n type HostFunction,\n type HostVariable,\n pluginDocsHelp,\n triggerFilterProblem,\n} from '@aglyn/aglyn'\n/*\n * The MODULE, not the barrel, for the two PURE helpers — every spec that\n * renders this card mocks `@aglyn/tenant-feature-instance` wholesale to stage\n * its Firestore hooks, and a query builder imported through that barrel\n * disappears under the mock. Neither of these is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport QuotaReadoutComponent from '@aglyn/shared-ui-jsx/components/quota-readout.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\nimport { getLiveCountFromServer } from '@aglyn/aglyn/app-utils/live-document-count.client'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport {\n useDuplicateResource,\n useFirestore,\n useFirestoreCollection,\n useHostResourceApi,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport {\n AutomationStepFields,\n type AutomationStepKind,\n defaultStep,\n} from './automation-step-fields.component'\nimport {\n type AutomationWorkflow,\n isWorkflowActionStep,\n validateWorkflowSteps,\n WORKFLOW_ACTION_STEP_TYPES,\n workflowFunctionCalls,\n type WorkflowStep,\n workflowStepTypeLabel,\n} from '../engine/workflow-steps'\nimport HostRunHistoryCard from './host-run-history-card.component'\nimport {\n EDITOR_OPTION_CEILING,\n useAutomationStepPickers,\n} from './use-automation-step-pickers'\nimport { listConsoleWidgets } from '@aglyn/aglyn'\nimport {\n fetchWhereUsed,\n summarizeDependents,\n type WhereUsedResult,\n} from '@aglyn/aglyn/app-utils/where-used'\nimport {\n AUTOMATION_EDITOR_ZONE,\n HOST_AUTOMATIONS_ZONE,\n openActionHref,\n WORKFLOW_USAGE_ZONE,\n type AutomationTarget,\n} from './workflow-zones'\nimport {\n type HostWorkflowStep,\n runWorkflow,\n WORKFLOW_MAX_STEPS,\n} from '../model/workflows'\nimport {\n type HostActionStep,\n type HostActionStepType,\n stepRunsAfterWait,\n} from '../model/host-actions'\n\n/**\n * How many workflows the card reads.\n *\n * A CEILING, not a page size — see the query, which explains why this list\n * cannot be paged by the server without making the duplicate-name check lie.\n */\nconst WORKFLOW_CEILING = 100\n\n/** The \"Do\" entry for the step kind a workflow has always had: a call. */\nconst FUNCTION_CALL_KIND = 'functionCall'\n\n/**\n * What a step may be (AGL-3105).\n *\n * The function call comes first because it is what a workflow was before the\n * two engines became one, and is still what a new step is. After it comes\n * every Actions step a SERVER event can run — the client-only interactions\n * are absent, because a workflow runs where there is no page to run them on.\n */\nconst STEP_KINDS: AutomationStepKind[] = [\n { value: FUNCTION_CALL_KIND, label: 'Call a function' },\n ...WORKFLOW_ACTION_STEP_TYPES.map((value) => ({\n value,\n label: workflowStepTypeLabel(value),\n })),\n]\n\nexport interface HostWorkflowsCardProps {\n hostId: string\n /** Resolved entitlement source for quota checks (AGL-395). */\n org?: Partial<AglynOrgBilling>\n /**\n * The Actions section's address (AGL-3603). A widget in the\n * `hostAutomations` zone drafts an ACTION, which lives there; opening it\n * goes to that section with the action named. Absent, the zone's\n * `openAction` answers `false` and the widget says where the draft went.\n */\n actionsHref?: string\n}\n\ninterface WorkflowDraft extends AutomationWorkflow {\n id: string | null\n}\n\n/**\n * Workflow builder v1 (AGL-101): pipelines of host-function calls — each\n * step's argument expressions see host variables and previous step results\n * (`step1`, or a custom result name). Runs through the pure `runWorkflow`\n * evaluator; test-run panel included. Plan-gated (`workflows` flag +\n * `workflowsPerHost` cap, AGL-99); site-event triggers are v2.\n */\nexport function HostWorkflowsCard(props: HostWorkflowsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const createHostResource = useHostResourceApi()\n const { enqueueSnackbar } = useSnackbar()\n // Duplicate (AGL-2936): the copy keeps every step and arrives disarmed —\n // its trigger is cleared — so nothing runs twice until somebody arms it.\n const duplicate = useDuplicateResource({\n hostId,\n onDuplicated: (_kind, copy) =>\n enqueueSnackbar(\n `Duplicated as “${copy.name}” — arm its trigger to run it`,\n {\n variant: 'success',\n },\n ),\n })\n const { confirm } = useConfirmationContext()\n const { org } = props\n /**\n * The shell's zone renderer, for what other plugins add to a saved workflow's\n * editor (AGL-2919); `null` outside the console shell.\n */\n const ExtensionZone = useConsoleWidgetSlot()\n const { actionsHref } = props\n /*\n * For the `hostAutomations` zone (AGL-3603): what a widget drafts is an\n * action, listed on the Actions section rather than this card, so opening\n * it goes there and asks that section's editor to open it.\n */\n const openAction = useCallback(\n (actionId: string) => {\n if (!actionsHref) return false\n window.location.assign(openActionHref(actionsHref, actionId))\n return true\n },\n [actionsHref],\n )\n const automationsZone = ExtensionZone ? (\n <ExtensionZone\n slot={HOST_AUTOMATIONS_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n openAction={openAction}\n />\n ) : null\n\n const {\n data: workflowDocs,\n status: workflowsStatus,\n /**\n * The rows this editor is seeded from are unconfirmed by the server\n * (AGL-1358). Editing destructures a whole stored workflow into `draft`\n * and writes `{...definition}` back, so `merge: true` protects nothing.\n * `trigger` is the field that makes this more than a lost edit: it is\n * `{event, filter}` or `null` for manual-only, and nothing else on this\n * card writes it, so a cached seed can re-arm an automation the author\n * disarmed — or disarm one running on a live site — and revert every\n * step of the pipeline with it.\n */\n fromCache: workflowsFromCache,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501) —\n * the same decision as the logic plugin's two cards, for the same reasons.\n *\n * `limit(100)` alone is answered in DOCUMENT-ID order, so the window is a\n * pseudo-random hundred that the `localeCompare` below arranges\n * alphabetically, and nothing said the list was bounded.\n *\n * `collectionCeiling` does not change WHICH hundred — document-id order is\n * what the bare cap already returned. What it changes is that the order is\n * NAMED, so the obvious next edit is caught: ordering on `name` would HIDE\n * every workflow written without one rather than mis-sorting the list, and\n * `/api/hosts/resources` validates no field for presence while\n * `IMPORTABLE_FIELDS.workflows` copies one only if the export carried it.\n *\n * The QUERY is not paged because `nameTaken` below tests the draft against\n * these rows: computed variables look their workflow up BY NAME\n * (AGL-185/AGL-261), so a duplicate silently rebinds a live binding, and a\n * uniqueness check over a ten-row page would let one through.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'workflows'),\n WORKFLOW_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readWorkflows, truncated: workflowsTruncated } =\n ceilingedWindow<any>(workflowDocs, WORKFLOW_CEILING)\n const [draft, setDraft] = useState<WorkflowDraft | null>(null)\n /**\n * The editor has been opened at least once in this session.\n *\n * A LATCH rather than `draft` itself, because the two reads below key their\n * listeners on it. Tracking the dialog would tear those subscriptions down\n * on Cancel and pay for them again on the next Edit, so a merchant working\n * through ten actions would buy the same two windows ten times — worse than\n * the mount-time read this replaces. Latched, a reader who never edits pays\n * nothing and a reader who edits pays once.\n */\n const [editorOpened, setEditorOpened] = useState(false)\n if (draft && !editorOpened) setEditorOpened(true)\n /*\n * THE EDITOR'S WORKING SET, read when the editor opens.\n *\n * Nothing outside the dialog reads either of these: the table renders a\n * workflow's stored step names, and `runWorkflow` is only reachable from the\n * test-run button inside the dialog. Mounting them unconditionally charges\n * every visitor to this page two windows to fill a select and seed a\n * scratchpad most of them never open.\n *\n * Ceilinged and ordered for the reason the workflows query above gives: a\n * bare `limit` is answered in document-id order, so the `localeCompare` on\n * the options below would arrange a pseudo-random hundred into a convincing\n * alphabet, and a function past the window could not be picked with nothing\n * saying why.\n */\n const { data: functionRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'functions'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n // Memoised so the window keeps one identity while the rows do — the option\n // list and the two lookup maps below are all built from it.\n const { rows: functionDocs, truncated: functionsTruncated } = useMemo(\n () => ceilingedWindow<any>(functionRead, EDITOR_OPTION_CEILING),\n [functionRead],\n )\n const { data: variableRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'variables'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n const { rows: variableDocs, truncated: variablesTruncated } = useMemo(\n () => ceilingedWindow<any>(variableRead, EDITOR_OPTION_CEILING),\n [variableRead],\n )\n /*\n * What an ACTIONS step can be pointed at, on the same latch (AGL-3105).\n *\n * The hook the Actions builder uses, because a workflow step may be any\n * server-side Actions step and the two editors therefore offer one set of\n * records. Read on the editor's first open, like the two windows above, so\n * a reader who never edits a workflow still pays nothing for them.\n */\n const { pickers: stepPickers, truncated: truncatedPickers } =\n useAutomationStepPickers(hostId, editorOpened)\n // Sorting is safe here in a way it is not on a paged list: these rows are\n // the whole collection below the ceiling, not a slice of one.\n const workflows = useMemo(\n () =>\n readWorkflows\n .filter((workflow: any) => !workflow.deletedAt)\n .sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n ),\n [readWorkflows],\n )\n // The page is a SLICE: the rows are already in hand and `nameTaken` needs\n // all of them.\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const visibleWorkflows = useMemo(\n () => workflows.slice(page * pageSize, page * pageSize + pageSize),\n [workflows, page, pageSize],\n )\n /**\n * The workflow HEAD-COUNT is a server aggregate, not the length of the\n * capped listener (AGL-1716, the AGL-1706 shape).\n *\n * The listener is `limit(100)` and `workflows.length` fed\n * `checkQuota(org, 'workflowsPerHost', …)`, whose bands are 0 / 3 / 25 /\n * 100 / 250 / 500. The window TIES Business's 100 and hides Scale's 250\n * and Advanced's 500, so on those plans the gate compared 100 against\n * hundreds and could never refuse — while `api/hosts/resources` counted\n * the collection and did. The card offered headroom that did not exist and\n * then failed the create.\n *\n * LIVE workflows, as that route counts them (AGL-3918): a deleted\n * workflow frees its slot, a disabled one keeps it. Every document less\n * the tombstones (`getLiveCountFromServer`). A create or a delete moves the\n * number, so both re-read it.\n */\n const [workflowCountEpoch, setWorkflowCountEpoch] = useState(0)\n const [serverWorkflowCount, setServerWorkflowCount] = useState<number | null>(\n null,\n )\n useEffect(() => {\n let active = true\n void getLiveCountFromServer(collection(firestore, 'hosts', hostId, 'workflows'))\n .then((count) => {\n if (active) setServerWorkflowCount(count)\n })\n .catch(() => {\n // Falls back to the loaded rows — a LOWER bound and the prior\n // behaviour, never 0, which `checkQuota` would answer as \"no usage\"\n // on a site that is over its band.\n })\n return () => {\n active = false\n }\n }, [firestore, hostId, workflowCountEpoch])\n const workflowCount = serverWorkflowCount ?? workflows.length\n // Double-keyed by doc id and name (AGL-261): id references are\n // rename-safe; legacy name references keep resolving.\n const functions = useMemo(() => {\n const map: Record<string, HostFunction> = {}\n for (const definition of functionDocs ?? []) {\n if (definition.deletedAt) continue\n if (definition.$id) map[definition.$id] = definition\n if (definition.name) map[definition.name] = definition\n }\n return map\n }, [functionDocs])\n const functionOptions = useMemo(\n () =>\n (functionDocs ?? [])\n .filter((definition: any) => !definition.deletedAt && definition.name)\n .map((definition: any) => ({\n id: definition.$id as string,\n name: definition.name as string,\n }))\n .sort((a, b) => a.name.localeCompare(b.name)),\n [functionDocs],\n )\n const variables = useMemo(() => {\n const map: Record<string, HostVariable> = {}\n for (const variable of variableDocs ?? []) {\n if (!variable.deletedAt && variable.name) map[variable.name] = variable\n }\n return map\n }, [variableDocs])\n\n // Where-used dialog (AGL-193).\n const [usage, setUsage] = useState<{\n name: string\n result: WhereUsedResult\n } | null>(null)\n const [usageLoading, setUsageLoading] = useState<string | null>(null)\n\n const [testResult, setTestResult] = useState<string | null>(null)\n const [runsFor, setRunsFor] = useState<any | null>(null)\n\n // Case-insensitive uniqueness (AGL-185): workflow names must stay\n // unambiguous for computed-variable lookups keyed by name.\n const nameTaken = Boolean(\n draft &&\n workflows.some(\n (definition: any) =>\n String(definition.name ?? '').toLowerCase() ===\n draft.name.trim().toLowerCase() && definition.$id !== draft.id,\n ),\n )\n\n const patch = useCallback(\n (updater: (previous: WorkflowDraft) => WorkflowDraft) =>\n setDraft((previous) => (previous ? updater(previous) : previous)),\n [],\n )\n\n /** The saved workflow the editor has open, as the `automationEditor` zone names it. */\n const draftId = draft?.id ?? null\n const draftName = draft?.name ?? ''\n const editorTarget = useMemo<AutomationTarget | null>(\n () => (draftId ? { type: 'workflow', id: draftId, name: draftName } : null),\n // The name the editor opened with: the zone reads the workflow as it is\n // stored, so a rename being typed does not make it a different one.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [draftId],\n )\n\n const handleAdd = useCallback(() => {\n // Feature + cap gate (AGL-99); dark-launch for plan-less workspaces.\n if (!checkEntitlement(org, 'workflows')) {\n return void enqueueSnackbar(\n 'Workflows require a Starter plan — see Billing to upgrade',\n { variant: 'warning', persist: false },\n )\n }\n // The site's workflows, not this page of them (AGL-1716).\n const quota = checkQuota(org, 'workflowsPerHost', workflowCount)\n if (!quota.allowed) {\n return void enqueueSnackbar(\n `Workflow limit reached (${quota.limit}) — upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setTestResult(null)\n setDraft({\n id: null,\n name: '',\n steps: [{ functionName: '', args: [], resultName: '' }],\n returnValue: '',\n trigger: null,\n })\n }, [org, workflowCount, enqueueSnackbar])\n\n /**\n * Every list the ceiling cut, named — the editor's two and the step\n * pickers' six, in one notice for the reason the Actions builder gives:\n * they are one read, and an author told the function list is short learns\n * nothing from being told again about datasets.\n */\n const shortLists = useMemo(\n () =>\n [\n functionsTruncated ? 'functions' : null,\n variablesTruncated ? 'variables' : null,\n ...truncatedPickers,\n ].filter((name): name is string => name !== null),\n [functionsTruncated, variablesTruncated, truncatedPickers],\n )\n\n /**\n * The first thing wrong with the steps, said the way the editors say it.\n *\n * The same check the engine makes of what it is handed: an Actions step is\n * held to the Actions validator, a call has to name a function, and a step\n * only a visitor's browser can run is refused. Said while the author is\n * still in the dialog rather than after a save that stores a step nothing\n * can run.\n */\n const stepProblem = useMemo(\n () =>\n draft\n ? // A filter the evaluator can never run saves fine and never fires\n // (AGL-3458), so it is refused with the steps.\n (triggerFilterProblem(draft.trigger?.filter, { remedy: 'action' }) ?? validateWorkflowSteps(draft.steps))\n : null,\n [draft],\n )\n\n const handleTestRun = useCallback(() => {\n if (!draft) return\n /*\n * The FUNCTION CALLS, evaluated. A test run is the pure evaluator, and\n * an Actions step is not something to evaluate — it sends, writes and\n * charges. Running one here would perform it against the live site from\n * a button labelled \"Test run\", so the calls are evaluated, each keeping\n * the result name it holds among all the steps, and the rest is left to\n * the run itself.\n */\n const run = runWorkflow(workflowFunctionCalls(draft), functions, variables)\n setTestResult(\n run.ok === false\n ? `Error: ${run.error}`\n : `Result: ${String(run.value)} (${Object.entries(run.results)\n .map(([key, value]) => `${key}=${value}`)\n .join(', ')})`,\n )\n }, [draft, functions, variables])\n\n const handleSave = useCallback(async () => {\n if (!draft || !draft.name.trim() || nameTaken) return\n // The steps are checked at the door, not after the write: a stored step\n // nothing can run is a run that fails on the site rather than here.\n if (stepProblem) {\n return void enqueueSnackbar(stepProblem, {\n variant: 'warning',\n persist: false,\n })\n }\n const { id: draftId, ...definition } = draft\n const fields = { ...definition, name: draft.name.trim().slice(0, 60) }\n try {\n if (draftId) {\n /**\n * Edit stays client-direct (no quota consumed) — and is refused when\n * its seed was never confirmed by the server (AGL-1358). `fields` is\n * the whole definition spread out of the listener row, `trigger` and\n * `steps` included, so `merge: true` has nothing left to protect.\n *\n * The guard WRAPS the write. An early return is a shape you can keep\n * while losing the protection; here the write is only reachable\n * through the verdict.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'workflow',\n unreadable: workflowsStatus === 'error',\n fromCache: workflowsFromCache,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'workflows', draftId),\n { ...fields, updatedAt: Timestamp.now() },\n { merge: true },\n )\n },\n )\n // Before `setDraft(null)`, so a refusal keeps the dialog open with\n // every step that was built and its test run still on screen.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n } else {\n // New workflow rides the quota-enforcing resources API (AGL-473) —\n // it also re-checks the `workflows` entitlement server-side.\n await createHostResource({ hostId, resource: 'workflow', data: fields })\n // A create moves the count; the one-shot aggregate below does not\n // refresh itself the way the listener refreshes the rows.\n setWorkflowCountEpoch((epoch) => epoch + 1)\n }\n setDraft(null)\n enqueueSnackbar('Workflow saved', { variant: 'success', persist: false })\n } catch (error: any) {\n console.error(error)\n enqueueSnackbar(error?.message ?? 'An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n draft,\n nameTaken,\n stepProblem,\n firestore,\n hostId,\n createHostResource,\n enqueueSnackbar,\n workflowsStatus,\n workflowsFromCache,\n ])\n\n const handleShowUsage = useCallback(\n (workflow: any) => async () => {\n setUsageLoading(workflow.$id)\n const result = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'workflow',\n id: workflow.$id,\n name: workflow.name,\n })\n setUsageLoading(null)\n // The rows and their deep links are drawn in a zone; with nothing\n // registered there the answer is still given, in words.\n if (listConsoleWidgets(WORKFLOW_USAGE_ZONE.id).length === 0) {\n enqueueSnackbar(\n result.total\n ? `\"${workflow.name}\" computes ${summarizeDependents(result)}`\n : `\"${workflow.name}\" is not referenced by anything published`,\n { variant: 'info', persist: false },\n )\n return\n }\n setUsage({ name: workflow.name, result })\n },\n [user, hostId, enqueueSnackbar],\n )\n\n const handleDelete = useCallback(\n (workflow: any) => async () => {\n // Dependents warning (AGL-187): computed variables backed by this\n // workflow keep their stored fallback value once it is gone.\n const scan = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'workflow',\n id: workflow.$id,\n name: workflow.name,\n })\n const confirmed = await confirm({\n title: 'Delete this workflow?',\n description: scan.total\n ? `\"${workflow.name}\" computes ${summarizeDependents(scan)} — ` +\n 'those variables will fall back to their stored values.'\n : `\"${workflow.name}\" will no longer be runnable.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await updateDoc(\n doc(firestore, 'hosts', hostId, 'workflows', workflow.$id),\n { deletedAt: Timestamp.now() },\n )\n // Deleting frees the slot (AGL-3918), so the head-count is re-read.\n setWorkflowCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar('Workflow deleted', {\n variant: 'success',\n persist: false,\n })\n },\n [user, confirm, firestore, hostId, enqueueSnackbar],\n )\n\n return (\n <CardDisplay\n header={'Workflows'}\n help={pluginDocsHelp('buildAWorkflow', {\n anchor: '#1-open-the-workflows-page',\n })}\n // Other ways to start an automation (AGL-3603), in the header while\n // the list has rows and in the empty state while it has none.\n actions={workflows.length === 0 ? undefined : automationsZone}\n contentGutterX\n contentGutterY\n >\n {duplicate.dialog}\n <Stack spacing={1}>\n {workflows.length === 0 ? (\n <Stack spacing={1} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Run steps in order when something happens on your site — a ' +\n 'form submission, a booking, a new member — or chain your ' +\n 'functions, each step feeding the next.'}\n </Typography>\n {automationsZone}\n </Stack>\n ) : (\n visibleWorkflows.map((workflow: any) => (\n <Stack\n key={workflow.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {workflow.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {[\n `${(workflow.steps ?? []).length} step${\n (workflow.steps ?? []).length === 1 ? '' : 's'\n }`,\n workflow.trigger?.event\n ? `on ${hostEventLabel(workflow.trigger.event)}`\n : '',\n // An Actions step calls no function, so it names none.\n (workflow.steps ?? [])\n .map((step: any) => step.functionName)\n .filter(Boolean)\n .join(' → '),\n ]\n .filter(Boolean)\n .join(' · ')}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n disabled={usageLoading === workflow.$id}\n onClick={handleShowUsage(workflow)}\n >\n {usageLoading === workflow.$id ? 'Scanning…' : 'Usage'}\n </Button>\n {/* Run history (wave v6): the event runner logs status +\n duration per run. */}\n <Button size=\"small\" onClick={() => setRunsFor(workflow)}>\n {'Runs'}\n </Button>\n <Button\n size=\"small\"\n onClick={() => {\n setTestResult(null)\n setDraft({\n id: workflow.$id,\n name: workflow.name ?? '',\n steps: workflow.steps ?? [],\n returnValue: workflow.returnValue ?? '',\n trigger: workflow.trigger ?? null,\n })\n }}\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n onClick={() =>\n duplicate.request('workflow', {\n id: workflow.$id,\n name: workflow.name ?? '',\n })\n }\n >\n {'Duplicate…'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDelete(workflow)}\n >\n {'Delete'}\n </Button>\n </Stack>\n ))\n )}\n {workflows.length === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={visibleWorkflows.length}\n // The workflows the card HOLDS. Not `workflowCount`, which is the\n // site's total including soft-deleted rows and answers the quota's\n // question rather than the reader's.\n count={workflows.length}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n {workflowsTruncated ? (\n <Alert severity=\"info\">\n {`Showing ${WORKFLOW_CEILING} workflows, ordered by id. This site ` +\n 'has more — the duplicate-name check below only covers the ' +\n 'ones listed here, so a name may already be taken by one that ' +\n 'is not.'}\n </Alert>\n ) : null}\n <Button\n size=\"small\"\n color=\"primary\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={handleAdd}\n >\n {'Add workflow'}\n </Button>\n {/* The cap, standing rather than only on refusal (AGL-2113).\n `workflowCount` is the server aggregate the gate uses, not\n `workflows.length` — the listener is `limit(100)` and its length\n saturates (AGL-1716). */}\n <QuotaReadoutComponent\n ready={org != null}\n used={workflowCount}\n limit={checkQuota(org, 'workflowsPerHost', workflowCount).limit}\n noun=\"workflow\"\n />\n </Stack>\n\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"sm\"\n fullWidth\n >\n <DialogTitle>\n {draft?.id ? 'Edit Workflow' : 'Add Workflow'}\n </DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: 1 }}\n >\n {ExtensionZone && editorTarget ? (\n <ExtensionZone\n slot={AUTOMATION_EDITOR_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n target={editorTarget}\n />\n ) : null}\n <TextField\n label=\"Name\"\n helperText={\n nameTaken\n ? 'A workflow with this name already exists'\n : 'Used to identify the workflow'\n }\n error={nameTaken}\n value={draft?.name ?? ''}\n onChange={(event) =>\n patch((previous) => ({ ...previous, name: event.target.value }))\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Steps'}\n </Typography>\n {/*\n The pickers and the test run speak only for what was read. A step\n calling a function past the ceiling still RUNS on the site — this\n editor simply cannot name it, and a test run resolves its\n expression against an incomplete variable set.\n */}\n {shortLists.length > 0 ? (\n <Alert severity=\"info\">\n {`Offering the first ${EDITOR_OPTION_CEILING} ` +\n `${shortLists.join(', ')} on this site, ordered by id. ` +\n 'There are more, so the pickers below are short and a test ' +\n 'run may not resolve every expression.'}\n </Alert>\n ) : null}\n {(draft?.steps ?? []).map((step, index) => {\n const call = isWorkflowActionStep(step)\n ? null\n : (step as HostWorkflowStep)\n const definition = call\n ? (functions[(call as any).functionId ?? ''] ??\n functions[call.functionName])\n : null\n return (\n <AutomationStepFields\n key={index}\n /*\n * The editor speaks the Actions vocabulary. A function call\n * has no Actions type, so it takes none of those fields and\n * renders its own through `fields` instead — which is what\n * keeps this one editor rather than two.\n */\n step={step as HostActionStep}\n index={index}\n kind={call ? FUNCTION_CALL_KIND : (step as HostActionStep).type}\n kinds={STEP_KINDS}\n stepForKind={(value) =>\n (value === FUNCTION_CALL_KIND\n ? { functionName: '', args: [], resultName: '' }\n : defaultStep(\n value as HostActionStepType,\n )) as HostActionStep\n }\n pickers={stepPickers}\n onSteps={(update) =>\n patch((previous) => ({\n ...previous,\n steps: update(\n previous.steps as HostActionStep[],\n ) as WorkflowStep[],\n }))\n }\n // A workflow with no trigger runs from another automation, so\n // its email step is a reply only on its own event.\n replyContext={{\n event: draft?.trigger?.event,\n afterWait: stepRunsAfterWait(draft?.steps as HostActionStep[], index),\n }}\n fields={\n call ? (\n <Stack\n useFlexGap\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', flex: 1, flexWrap: 'wrap' }}\n >\n <TextField\n label=\"Function\"\n // Stored by id (AGL-261); legacy steps carry only the\n // name and resolve through the double-keyed map.\n value={\n (call as any).functionId ??\n (functions[call.functionName] as any)?.$id ??\n ''\n }\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) =>\n index2 === index\n ? {\n ...s,\n functionId: event.target.value,\n functionName:\n functionOptions.find(\n (option) =>\n option.id === event.target.value,\n )?.name ??\n (s as HostWorkflowStep).functionName,\n }\n : s,\n ),\n }))\n }\n size=\"small\"\n select\n sx={{ minWidth: 160, flex: 1 }}\n >\n {functionOptions.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {option.name}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Result name\"\n placeholder={`step${index + 1}`}\n value={call.resultName ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) =>\n index2 === index\n ? {\n ...s,\n resultName: event.target.value.replace(\n /[^a-zA-Z0-9_]/g,\n '',\n ),\n }\n : s,\n ),\n }))\n }\n size=\"small\"\n sx={{ width: 140 }}\n />\n {(definition?.parameters ?? []).map(\n (parameter, parameterIndex) => (\n <TextField\n key={parameter.name}\n label={`${parameter.name} expression`}\n placeholder={\n parameterIndex === 0 && index > 0\n ? `step${index}`\n : 'a variable, number, or expression'\n }\n value={call.args?.[parameterIndex] ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) => {\n if (index2 !== index) return s\n const args = [\n ...((s as HostWorkflowStep).args ?? []),\n ]\n args[parameterIndex] = event.target.value\n return { ...s, args }\n }),\n }))\n }\n size=\"small\"\n sx={{ minWidth: 180, flex: 1 }}\n />\n ),\n )}\n </Stack>\n ) : undefined\n }\n />\n )\n })}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n disabled={(draft?.steps.length ?? 0) >= WORKFLOW_MAX_STEPS}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n steps: [\n ...previous.steps,\n { functionName: '', args: [], resultName: '' },\n ],\n }))\n }\n >\n {'Add step'}\n </Button>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Trigger'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Run on event\"\n value={draft?.trigger?.event ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: event.target.value\n ? {\n event: event.target.value as any,\n filter: previous.trigger?.filter ?? '',\n }\n : null,\n }))\n }\n size=\"small\"\n select\n sx={{ minWidth: 180 }}\n >\n <MenuItem value=\"\">{'Manual only'}</MenuItem>\n {HOST_EVENT_TYPES.map((eventType) => (\n <MenuItem key={eventType} value={eventType}>\n {hostEventLabel(eventType)}\n </MenuItem>\n ))}\n </TextField>\n {draft?.trigger ? (\n <TextField\n label=\"Filter (optional)\"\n placeholder=\"subscribe\"\n // The evaluator is arithmetic and has no comparison (AGL-3458):\n // `path == \"/pricing\"` throws on every event and never runs.\n error={Boolean(triggerFilterProblem(draft?.trigger?.filter, { remedy: 'action' }))}\n helperText={\n triggerFilterProblem(draft?.trigger?.filter, { remedy: 'action' }) ??\n [\n 'Runs only when this expression is truthy — a field name, or arithmetic. It cannot compare values.',\n hostEventPayloadHint(draft?.trigger?.event),\n ]\n .filter(Boolean)\n .join(' ')\n }\n value={draft?.trigger?.filter ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: previous.trigger\n ? { ...previous.trigger, filter: event.target.value }\n : previous.trigger,\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n ) : null}\n </Stack>\n <TextField\n label=\"Return value\"\n helperText=\"A step result name; defaults to the last step\"\n value={draft?.returnValue ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n returnValue: event.target.value,\n }))\n }\n size=\"small\"\n />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Button size=\"small\" color=\"primary\" onClick={handleTestRun}>\n {'Test run'}\n </Button>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Uses current variable values'}\n </Typography>\n </Stack>\n {testResult ? (\n <Alert\n severity={testResult.startsWith('Error') ? 'warning' : 'success'}\n >\n {testResult}\n </Alert>\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim() || nameTaken}\n onClick={handleSave}\n >\n {'Done'}\n </Button>\n </DialogActions>\n </Dialog>\n {ExtensionZone ? (\n <ExtensionZone\n slot={WORKFLOW_USAGE_ZONE.id}\n hostId={hostId}\n usage={usage}\n onClose={() => setUsage(null)}\n />\n ) : null}\n <Dialog\n open={Boolean(runsFor)}\n onClose={() => setRunsFor(null)}\n // md: the history's four columns fit without the table scrolling.\n maxWidth=\"md\"\n fullWidth\n >\n <DialogTitle>{`Runs — ${runsFor?.name ?? ''}`}</DialogTitle>\n <DialogContent>\n {runsFor ? (\n <HostRunHistoryCard\n hostId={hostId}\n orgId={org?.$id}\n targetId={runsFor.$id}\n targetType=\"workflow\"\n targetName={runsFor.name ?? ''}\n header=\"Recent runs\"\n />\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button color=\"inherit\" onClick={() => setRunsFor(null)}>\n {'Close'}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nHostWorkflowsCard.displayName = 'HostWorkflowsCard'\n\nexport default HostWorkflowsCard\n"],"names":["checkEntitlement","checkQuota","HOST_EVENT_TYPES","hostEventLabel","hostEventPayloadHint","pluginDocsHelp","triggerFilterProblem","ceilingedWindow","collectionCeiling","useConsoleWidgetSlot","CardDisplay","useConfirmationContext","ListPagination","TABLE_PAGE_SIZE_DEFAULT","QuotaReadoutComponent","useSnackbar","Timestamp","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Typography","collection","doc","setDoc","updateDoc","getLiveCountFromServer","useCallback","useEffect","useMemo","useState","useDuplicateResource","useFirestore","useFirestoreCollection","useHostResourceApi","useUser","writeGuardedBySeed","AutomationStepFields","defaultStep","isWorkflowActionStep","validateWorkflowSteps","WORKFLOW_ACTION_STEP_TYPES","workflowFunctionCalls","workflowStepTypeLabel","HostRunHistoryCard","EDITOR_OPTION_CEILING","useAutomationStepPickers","listConsoleWidgets","fetchWhereUsed","summarizeDependents","AUTOMATION_EDITOR_ZONE","HOST_AUTOMATIONS_ZONE","openActionHref","WORKFLOW_USAGE_ZONE","runWorkflow","WORKFLOW_MAX_STEPS","stepRunsAfterWait","WORKFLOW_CEILING","FUNCTION_CALL_KIND","STEP_KINDS","value","label","map","HostWorkflowsCard","props","runsFor","draft","hostId","firestore","data","user","createHostResource","enqueueSnackbar","duplicate","onDuplicated","_kind","copy","name","variant","confirm","org","ExtensionZone","actionsHref","openAction","actionId","window","location","assign","automationsZone","slot","id","orgId","$id","workflowDocs","status","workflowsStatus","fromCache","workflowsFromCache","idField","rows","readWorkflows","truncated","workflowsTruncated","setDraft","editorOpened","setEditorOpened","functionRead","functionDocs","functionsTruncated","variableRead","variableDocs","variablesTruncated","pickers","stepPickers","truncatedPickers","workflows","filter","workflow","deletedAt","sort","a","b","String","localeCompare","page","setPage","pageSize","setPageSize","visibleWorkflows","slice","workflowCountEpoch","setWorkflowCountEpoch","serverWorkflowCount","setServerWorkflowCount","active","then","count","catch","workflowCount","length","functions","definition","functionOptions","variables","variable","usage","setUsage","usageLoading","setUsageLoading","testResult","setTestResult","setRunsFor","nameTaken","Boolean","some","toLowerCase","trim","patch","updater","previous","draftId","draftName","editorTarget","type","handleAdd","persist","quota","allowed","limit","steps","functionName","args","resultName","returnValue","trigger","shortLists","stepProblem","remedy","handleTestRun","run","ok","error","Object","entries","results","key","join","handleSave","fields","verdict","subject","unreadable","updatedAt","now","merge","message","resource","epoch","console","allowDuplicate","handleShowUsage","result","kind","total","handleDelete","scan","confirmed","title","description","confirmationText","confirmationButtonProps","color","header","help","anchor","actions","undefined","contentGutterX","contentGutterY","dialog","spacing","sx","alignItems","direction","flex","minWidth","noWrap","event","step","size","disabled","onClick","request","rowCount","onPageChange","onPageSizeChange","severity","alignSelf","ready","used","noun","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","pt","target","helperText","onChange","autoFocus","mt","index","call","functionId","kinds","stepForKind","onSteps","update","replyContext","afterWait","useFlexGap","flexWrap","s","index2","find","option","select","placeholder","replace","width","parameters","parameter","parameterIndex","eventType","startsWith","targetId","targetType","targetName","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SAEEA,gBAAgB,EAChBC,UAAU,EACVC,gBAAgB,EAChBC,cAAc,EACdC,oBAAoB,EAGpBC,cAAc,EACdC,oBAAoB,QACf,eAAc;AACrB;;;;;CAKC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SAASC,oBAAoB,QAAQ,qDAAoD;AACzF,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,OAAOC,2BAA2B,0DAAyD;AAC3F,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,SAAS,QAAQ,+BAA8B;AACxD,SACEC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,GAAG,EACHC,MAAM,EACNC,SAAS,QACJ,qBAAoB;AAC3B,SAASC,sBAAsB,QAAQ,oDAAmD;AAC1F,SAASC,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACjE,SACEC,oBAAoB,EACpBC,YAAY,EACZC,sBAAsB,EACtBC,kBAAkB,EAClBC,OAAO,EACPC,kBAAkB,QACb,iCAAgC;AACvC,SACEC,oBAAoB,EAEpBC,WAAW,QACN,wCAAoC;AAC3C,SAEEC,oBAAoB,EACpBC,qBAAqB,EACrBC,0BAA0B,EAC1BC,qBAAqB,EAErBC,qBAAqB,QAChB,8BAA0B;AACjC,OAAOC,wBAAwB,uCAAmC;AAClE,SACEC,qBAAqB,EACrBC,wBAAwB,QACnB,m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ACdiL,SAAS,IAAM3F,WAAW;gBAC1B,kEAAkE;gBAClE4F,UAAS;gBACTC,SAAS;;kCAET,KAACnO;kCAAa,CAAC,OAAO,WAAEgD,2BAAAA,QAASY,IAAI,oBAAI,IAAI;;kCAC7C,KAAC7D;kCACEiD,wBACC,KAACrB;4BACCuB,QAAQA;4BACRwB,KAAK,EAAEX,uBAAAA,IAAKY,GAAG;4BACf0L,UAAUrN,QAAQ2B,GAAG;4BACrB2L,YAAW;4BACXC,UAAU,GAAEvN,gBAAAA,QAAQY,IAAI,YAAZZ,gBAAgB;4BAC5BmJ,QAAO;6BAEP;;kCAEN,KAACrM;kCACC,cAAA,KAACF;4BAAOsM,OAAM;4BAAUoB,SAAS,IAAMhF,WAAW;sCAC/C;;;;;;;AAMb;AACAxF,kBAAkB0N,WAAW,GAAG;AAEhC,eAAe1N,kBAAiB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/host-workflows-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n type AglynOrgBilling,\n checkEntitlement,\n checkQuota,\n HOST_EVENT_TYPES,\n hostEventLabel,\n hostEventPayloadHint,\n type HostFunction,\n type HostVariable,\n pluginDocsHelp,\n triggerFilterProblem,\n} from '@aglyn/aglyn'\n/*\n * The MODULE, not the barrel, for the two PURE helpers — every spec that\n * renders this card mocks `@aglyn/tenant-feature-instance` wholesale to stage\n * its Firestore hooks, and a query builder imported through that barrel\n * disappears under the mock. Neither of these is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport QuotaReadoutComponent from '@aglyn/shared-ui-jsx/components/quota-readout.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\nimport { getLiveCountFromServer } from '@aglyn/aglyn/app-utils/live-document-count.client'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport {\n useDuplicateResource,\n useFirestore,\n useFirestoreCollection,\n useHostResourceApi,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport {\n AutomationStepFields,\n type AutomationStepKind,\n defaultStep,\n} from './automation-step-fields.component'\nimport {\n type AutomationWorkflow,\n isWorkflowActionStep,\n validateWorkflowSteps,\n WORKFLOW_ACTION_STEP_TYPES,\n workflowFunctionCalls,\n type WorkflowStep,\n workflowStepTypeLabel,\n} from '../engine/workflow-steps'\nimport HostRunHistoryCard from './host-run-history-card.component'\nimport {\n EDITOR_OPTION_CEILING,\n useAutomationStepPickers,\n} from './use-automation-step-pickers'\nimport { listConsoleWidgets } from '@aglyn/aglyn'\nimport {\n fetchWhereUsed,\n summarizeDependents,\n type WhereUsedResult,\n} from '@aglyn/aglyn/app-utils/where-used'\nimport {\n AUTOMATION_EDITOR_ZONE,\n HOST_AUTOMATIONS_ZONE,\n openActionHref,\n WORKFLOW_USAGE_ZONE,\n type AutomationTarget,\n} from './workflow-zones'\nimport {\n type HostWorkflowStep,\n runWorkflow,\n WORKFLOW_MAX_STEPS,\n} from '../model/workflows'\nimport {\n type HostActionStep,\n type HostActionStepType,\n stepRunsAfterWait,\n} from '../model/host-actions'\n\n/**\n * How many workflows the card reads.\n *\n * A CEILING, not a page size — see the query, which explains why this list\n * cannot be paged by the server without making the duplicate-name check lie.\n */\nconst WORKFLOW_CEILING = 100\n\n/** The \"Do\" entry for the step kind a workflow has always had: a call. */\nconst FUNCTION_CALL_KIND = 'functionCall'\n\n/**\n * What a step may be (AGL-3105).\n *\n * The function call comes first because it is what a workflow was before the\n * two engines became one, and is still what a new step is. After it comes\n * every Actions step a SERVER event can run — the client-only interactions\n * are absent, because a workflow runs where there is no page to run them on.\n */\nconst STEP_KINDS: AutomationStepKind[] = [\n { value: FUNCTION_CALL_KIND, label: 'Call a function' },\n ...WORKFLOW_ACTION_STEP_TYPES.map((value) => ({\n value,\n label: workflowStepTypeLabel(value),\n })),\n]\n\nexport interface HostWorkflowsCardProps {\n hostId: string\n /** Resolved entitlement source for quota checks (AGL-395). */\n org?: Partial<AglynOrgBilling>\n /**\n * The Actions section's address (AGL-3603). A widget in the\n * `hostAutomations` zone drafts an ACTION, which lives there; opening it\n * goes to that section with the action named. Absent, the zone's\n * `openAction` answers `false` and the widget says where the draft went.\n */\n actionsHref?: string\n}\n\ninterface WorkflowDraft extends AutomationWorkflow {\n id: string | null\n}\n\n/**\n * Workflow builder v1 (AGL-101): pipelines of host-function calls — each\n * step's argument expressions see host variables and previous step results\n * (`step1`, or a custom result name). Runs through the pure `runWorkflow`\n * evaluator; test-run panel included. Plan-gated (`workflows` flag +\n * `workflowsPerHost` cap, AGL-99); site-event triggers are v2.\n */\nexport function HostWorkflowsCard(props: HostWorkflowsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const createHostResource = useHostResourceApi()\n const { enqueueSnackbar } = useSnackbar()\n // Duplicate (AGL-2936): the copy keeps every step and arrives disarmed —\n // its trigger is cleared — so nothing runs twice until somebody arms it.\n const duplicate = useDuplicateResource({\n hostId,\n onDuplicated: (_kind, copy) =>\n enqueueSnackbar(\n `Duplicated as “${copy.name}” — arm its trigger to run it`,\n {\n variant: 'success',\n },\n ),\n })\n const { confirm } = useConfirmationContext()\n const { org } = props\n /**\n * The shell's zone renderer, for what other plugins add to a saved workflow's\n * editor (AGL-2919); `null` outside the console shell.\n */\n const ExtensionZone = useConsoleWidgetSlot()\n const { actionsHref } = props\n /*\n * For the `hostAutomations` zone (AGL-3603): what a widget drafts is an\n * action, listed on the Actions section rather than this card, so opening\n * it goes there and asks that section's editor to open it.\n */\n const openAction = useCallback(\n (actionId: string) => {\n if (!actionsHref) return false\n window.location.assign(openActionHref(actionsHref, actionId))\n return true\n },\n [actionsHref],\n )\n const automationsZone = ExtensionZone ? (\n <ExtensionZone\n slot={HOST_AUTOMATIONS_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n openAction={openAction}\n />\n ) : null\n\n const {\n data: workflowDocs,\n status: workflowsStatus,\n /**\n * The rows this editor is seeded from are unconfirmed by the server\n * (AGL-1358). Editing destructures a whole stored workflow into `draft`\n * and writes `{...definition}` back, so `merge: true` protects nothing.\n * `trigger` is the field that makes this more than a lost edit: it is\n * `{event, filter}` or `null` for manual-only, and nothing else on this\n * card writes it, so a cached seed can re-arm an automation the author\n * disarmed — or disarm one running on a live site — and revert every\n * step of the pipeline with it.\n */\n fromCache: workflowsFromCache,\n listen: workflowsListen,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501) —\n * the same decision as the logic plugin's two cards, for the same reasons.\n *\n * `limit(100)` alone is answered in DOCUMENT-ID order, so the window is a\n * pseudo-random hundred that the `localeCompare` below arranges\n * alphabetically, and nothing said the list was bounded.\n *\n * `collectionCeiling` does not change WHICH hundred — document-id order is\n * what the bare cap already returned. What it changes is that the order is\n * NAMED, so the obvious next edit is caught: ordering on `name` would HIDE\n * every workflow written without one rather than mis-sorting the list, and\n * `/api/hosts/resources` validates no field for presence while\n * `IMPORTABLE_FIELDS.workflows` copies one only if the export carried it.\n *\n * The QUERY is not paged because `nameTaken` below tests the draft against\n * these rows: computed variables look their workflow up BY NAME\n * (AGL-185/AGL-261), so a duplicate silently rebinds a live binding, and a\n * uniqueness check over a ten-row page would let one through.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'workflows'),\n WORKFLOW_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readWorkflows, truncated: workflowsTruncated } =\n ceilingedWindow<any>(workflowDocs, WORKFLOW_CEILING)\n const [draft, setDraft] = useState<WorkflowDraft | null>(null)\n /**\n * The editor has been opened at least once in this session.\n *\n * A LATCH rather than `draft` itself, because the two reads below key their\n * listeners on it. Tracking the dialog would tear those subscriptions down\n * on Cancel and pay for them again on the next Edit, so a merchant working\n * through ten actions would buy the same two windows ten times — worse than\n * the mount-time read this replaces. Latched, a reader who never edits pays\n * nothing and a reader who edits pays once.\n */\n const [editorOpened, setEditorOpened] = useState(false)\n if (draft && !editorOpened) setEditorOpened(true)\n /*\n * THE EDITOR'S WORKING SET, read when the editor opens.\n *\n * Nothing outside the dialog reads either of these: the table renders a\n * workflow's stored step names, and `runWorkflow` is only reachable from the\n * test-run button inside the dialog. Mounting them unconditionally charges\n * every visitor to this page two windows to fill a select and seed a\n * scratchpad most of them never open.\n *\n * Ceilinged and ordered for the reason the workflows query above gives: a\n * bare `limit` is answered in document-id order, so the `localeCompare` on\n * the options below would arrange a pseudo-random hundred into a convincing\n * alphabet, and a function past the window could not be picked with nothing\n * saying why.\n */\n const { data: functionRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'functions'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n // Memoised so the window keeps one identity while the rows do — the option\n // list and the two lookup maps below are all built from it.\n const { rows: functionDocs, truncated: functionsTruncated } = useMemo(\n () => ceilingedWindow<any>(functionRead, EDITOR_OPTION_CEILING),\n [functionRead],\n )\n const { data: variableRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'variables'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n const { rows: variableDocs, truncated: variablesTruncated } = useMemo(\n () => ceilingedWindow<any>(variableRead, EDITOR_OPTION_CEILING),\n [variableRead],\n )\n /*\n * What an ACTIONS step can be pointed at, on the same latch (AGL-3105).\n *\n * The hook the Actions builder uses, because a workflow step may be any\n * server-side Actions step and the two editors therefore offer one set of\n * records. Read on the editor's first open, like the two windows above, so\n * a reader who never edits a workflow still pays nothing for them.\n */\n const { pickers: stepPickers, truncated: truncatedPickers } =\n useAutomationStepPickers(hostId, editorOpened)\n // Sorting is safe here in a way it is not on a paged list: these rows are\n // the whole collection below the ceiling, not a slice of one.\n const workflows = useMemo(\n () =>\n readWorkflows\n .filter((workflow: any) => !workflow.deletedAt)\n .sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n ),\n [readWorkflows],\n )\n // The page is a SLICE: the rows are already in hand and `nameTaken` needs\n // all of them.\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const visibleWorkflows = useMemo(\n () => workflows.slice(page * pageSize, page * pageSize + pageSize),\n [workflows, page, pageSize],\n )\n /**\n * The workflow HEAD-COUNT is a server aggregate, not the length of the\n * capped listener (AGL-1716, the AGL-1706 shape).\n *\n * The listener is `limit(100)` and `workflows.length` fed\n * `checkQuota(org, 'workflowsPerHost', …)`, whose bands are 0 / 3 / 25 /\n * 100 / 250 / 500. The window TIES Business's 100 and hides Scale's 250\n * and Advanced's 500, so on those plans the gate compared 100 against\n * hundreds and could never refuse — while `api/hosts/resources` counted\n * the collection and did. The card offered headroom that did not exist and\n * then failed the create.\n *\n * LIVE workflows, as that route counts them (AGL-3918): a deleted\n * workflow frees its slot, a disabled one keeps it. Every document less\n * the tombstones (`getLiveCountFromServer`). A create or a delete moves the\n * number, so both re-read it.\n */\n const [workflowCountEpoch, setWorkflowCountEpoch] = useState(0)\n const [serverWorkflowCount, setServerWorkflowCount] = useState<number | null>(\n null,\n )\n useEffect(() => {\n let active = true\n void getLiveCountFromServer(collection(firestore, 'hosts', hostId, 'workflows'))\n .then((count) => {\n if (active) setServerWorkflowCount(count)\n })\n .catch(() => {\n // Falls back to the loaded rows — a LOWER bound and the prior\n // behaviour, never 0, which `checkQuota` would answer as \"no usage\"\n // on a site that is over its band.\n })\n return () => {\n active = false\n }\n }, [firestore, hostId, workflowCountEpoch])\n const workflowCount = serverWorkflowCount ?? workflows.length\n // Double-keyed by doc id and name (AGL-261): id references are\n // rename-safe; legacy name references keep resolving.\n const functions = useMemo(() => {\n const map: Record<string, HostFunction> = {}\n for (const definition of functionDocs ?? []) {\n if (definition.deletedAt) continue\n if (definition.$id) map[definition.$id] = definition\n if (definition.name) map[definition.name] = definition\n }\n return map\n }, [functionDocs])\n const functionOptions = useMemo(\n () =>\n (functionDocs ?? [])\n .filter((definition: any) => !definition.deletedAt && definition.name)\n .map((definition: any) => ({\n id: definition.$id as string,\n name: definition.name as string,\n }))\n .sort((a, b) => a.name.localeCompare(b.name)),\n [functionDocs],\n )\n const variables = useMemo(() => {\n const map: Record<string, HostVariable> = {}\n for (const variable of variableDocs ?? []) {\n if (!variable.deletedAt && variable.name) map[variable.name] = variable\n }\n return map\n }, [variableDocs])\n\n // Where-used dialog (AGL-193).\n const [usage, setUsage] = useState<{\n name: string\n result: WhereUsedResult\n } | null>(null)\n const [usageLoading, setUsageLoading] = useState<string | null>(null)\n\n const [testResult, setTestResult] = useState<string | null>(null)\n const [runsFor, setRunsFor] = useState<any | null>(null)\n\n // Case-insensitive uniqueness (AGL-185): workflow names must stay\n // unambiguous for computed-variable lookups keyed by name.\n const nameTaken = Boolean(\n draft &&\n workflows.some(\n (definition: any) =>\n String(definition.name ?? '').toLowerCase() ===\n draft.name.trim().toLowerCase() && definition.$id !== draft.id,\n ),\n )\n\n const patch = useCallback(\n (updater: (previous: WorkflowDraft) => WorkflowDraft) =>\n setDraft((previous) => (previous ? updater(previous) : previous)),\n [],\n )\n\n /** The saved workflow the editor has open, as the `automationEditor` zone names it. */\n const draftId = draft?.id ?? null\n const draftName = draft?.name ?? ''\n const editorTarget = useMemo<AutomationTarget | null>(\n () => (draftId ? { type: 'workflow', id: draftId, name: draftName } : null),\n // The name the editor opened with: the zone reads the workflow as it is\n // stored, so a rename being typed does not make it a different one.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [draftId],\n )\n\n const handleAdd = useCallback(() => {\n // Feature + cap gate (AGL-99); dark-launch for plan-less workspaces.\n if (!checkEntitlement(org, 'workflows')) {\n return void enqueueSnackbar(\n 'Workflows require a Starter plan — see Billing to upgrade',\n { variant: 'warning', persist: false },\n )\n }\n // The site's workflows, not this page of them (AGL-1716).\n const quota = checkQuota(org, 'workflowsPerHost', workflowCount)\n if (!quota.allowed) {\n return void enqueueSnackbar(\n `Workflow limit reached (${quota.limit}) — upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setTestResult(null)\n setDraft({\n id: null,\n name: '',\n steps: [{ functionName: '', args: [], resultName: '' }],\n returnValue: '',\n trigger: null,\n })\n }, [org, workflowCount, enqueueSnackbar])\n\n /**\n * Every list the ceiling cut, named — the editor's two and the step\n * pickers' six, in one notice for the reason the Actions builder gives:\n * they are one read, and an author told the function list is short learns\n * nothing from being told again about datasets.\n */\n const shortLists = useMemo(\n () =>\n [\n functionsTruncated ? 'functions' : null,\n variablesTruncated ? 'variables' : null,\n ...truncatedPickers,\n ].filter((name): name is string => name !== null),\n [functionsTruncated, variablesTruncated, truncatedPickers],\n )\n\n /**\n * The first thing wrong with the steps, said the way the editors say it.\n *\n * The same check the engine makes of what it is handed: an Actions step is\n * held to the Actions validator, a call has to name a function, and a step\n * only a visitor's browser can run is refused. Said while the author is\n * still in the dialog rather than after a save that stores a step nothing\n * can run.\n */\n const stepProblem = useMemo(\n () =>\n draft\n ? // A filter the evaluator can never run saves fine and never fires\n // (AGL-3458), so it is refused with the steps.\n (triggerFilterProblem(draft.trigger?.filter, { remedy: 'action' }) ?? validateWorkflowSteps(draft.steps))\n : null,\n [draft],\n )\n\n const handleTestRun = useCallback(() => {\n if (!draft) return\n /*\n * The FUNCTION CALLS, evaluated. A test run is the pure evaluator, and\n * an Actions step is not something to evaluate — it sends, writes and\n * charges. Running one here would perform it against the live site from\n * a button labelled \"Test run\", so the calls are evaluated, each keeping\n * the result name it holds among all the steps, and the rest is left to\n * the run itself.\n */\n const run = runWorkflow(workflowFunctionCalls(draft), functions, variables)\n setTestResult(\n run.ok === false\n ? `Error: ${run.error}`\n : `Result: ${String(run.value)} (${Object.entries(run.results)\n .map(([key, value]) => `${key}=${value}`)\n .join(', ')})`,\n )\n }, [draft, functions, variables])\n\n const handleSave = useCallback(async () => {\n if (!draft || !draft.name.trim() || nameTaken) return\n // The steps are checked at the door, not after the write: a stored step\n // nothing can run is a run that fails on the site rather than here.\n if (stepProblem) {\n return void enqueueSnackbar(stepProblem, {\n variant: 'warning',\n persist: false,\n })\n }\n const { id: draftId, ...definition } = draft\n const fields = { ...definition, name: draft.name.trim().slice(0, 60) }\n try {\n if (draftId) {\n /**\n * Edit stays client-direct (no quota consumed) — and is refused when\n * its seed was never confirmed by the server (AGL-1358). `fields` is\n * the whole definition spread out of the listener row, `trigger` and\n * `steps` included, so `merge: true` has nothing left to protect.\n *\n * The guard WRAPS the write. An early return is a shape you can keep\n * while losing the protection; here the write is only reachable\n * through the verdict.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'workflow',\n unreadable: workflowsStatus === 'error',\n fromCache: workflowsFromCache,\n listen: workflowsListen,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'workflows', draftId),\n { ...fields, updatedAt: Timestamp.now() },\n { merge: true },\n )\n },\n )\n // Before `setDraft(null)`, so a refusal keeps the dialog open with\n // every step that was built and its test run still on screen.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n } else {\n // New workflow rides the quota-enforcing resources API (AGL-473) —\n // it also re-checks the `workflows` entitlement server-side.\n await createHostResource({ hostId, resource: 'workflow', data: fields })\n // A create moves the count; the one-shot aggregate below does not\n // refresh itself the way the listener refreshes the rows.\n setWorkflowCountEpoch((epoch) => epoch + 1)\n }\n setDraft(null)\n enqueueSnackbar('Workflow saved', { variant: 'success', persist: false })\n } catch (error: any) {\n console.error(error)\n enqueueSnackbar(error?.message ?? 'An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n draft,\n nameTaken,\n stepProblem,\n firestore,\n hostId,\n createHostResource,\n enqueueSnackbar,\n workflowsStatus,\n workflowsFromCache,\n workflowsListen,\n ])\n\n const handleShowUsage = useCallback(\n (workflow: any) => async () => {\n setUsageLoading(workflow.$id)\n const result = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'workflow',\n id: workflow.$id,\n name: workflow.name,\n })\n setUsageLoading(null)\n // The rows and their deep links are drawn in a zone; with nothing\n // registered there the answer is still given, in words.\n if (listConsoleWidgets(WORKFLOW_USAGE_ZONE.id).length === 0) {\n enqueueSnackbar(\n result.total\n ? `\"${workflow.name}\" computes ${summarizeDependents(result)}`\n : `\"${workflow.name}\" is not referenced by anything published`,\n { variant: 'info', persist: false },\n )\n return\n }\n setUsage({ name: workflow.name, result })\n },\n [user, hostId, enqueueSnackbar],\n )\n\n const handleDelete = useCallback(\n (workflow: any) => async () => {\n // Dependents warning (AGL-187): computed variables backed by this\n // workflow keep their stored fallback value once it is gone.\n const scan = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'workflow',\n id: workflow.$id,\n name: workflow.name,\n })\n const confirmed = await confirm({\n title: 'Delete this workflow?',\n description: scan.total\n ? `\"${workflow.name}\" computes ${summarizeDependents(scan)} — ` +\n 'those variables will fall back to their stored values.'\n : `\"${workflow.name}\" will no longer be runnable.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await updateDoc(\n doc(firestore, 'hosts', hostId, 'workflows', workflow.$id),\n { deletedAt: Timestamp.now() },\n )\n // Deleting frees the slot (AGL-3918), so the head-count is re-read.\n setWorkflowCountEpoch((epoch) => epoch + 1)\n enqueueSnackbar('Workflow deleted', {\n variant: 'success',\n persist: false,\n })\n },\n [user, confirm, firestore, hostId, enqueueSnackbar],\n )\n\n return (\n <CardDisplay\n header={'Workflows'}\n help={pluginDocsHelp('buildAWorkflow', {\n anchor: '#1-open-the-workflows-page',\n })}\n // Other ways to start an automation (AGL-3603), in the header while\n // the list has rows and in the empty state while it has none.\n actions={workflows.length === 0 ? undefined : automationsZone}\n contentGutterX\n contentGutterY\n >\n {duplicate.dialog}\n <Stack spacing={1}>\n {workflows.length === 0 ? (\n <Stack spacing={1} sx={{ alignItems: 'flex-start' }}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Run steps in order when something happens on your site — a ' +\n 'form submission, a booking, a new member — or chain your ' +\n 'functions, each step feeding the next.'}\n </Typography>\n {automationsZone}\n </Stack>\n ) : (\n visibleWorkflows.map((workflow: any) => (\n <Stack\n key={workflow.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {workflow.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {[\n `${(workflow.steps ?? []).length} step${\n (workflow.steps ?? []).length === 1 ? '' : 's'\n }`,\n workflow.trigger?.event\n ? `on ${hostEventLabel(workflow.trigger.event)}`\n : '',\n // An Actions step calls no function, so it names none.\n (workflow.steps ?? [])\n .map((step: any) => step.functionName)\n .filter(Boolean)\n .join(' → '),\n ]\n .filter(Boolean)\n .join(' · ')}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n disabled={usageLoading === workflow.$id}\n onClick={handleShowUsage(workflow)}\n >\n {usageLoading === workflow.$id ? 'Scanning…' : 'Usage'}\n </Button>\n {/* Run history (wave v6): the event runner logs status +\n duration per run. */}\n <Button size=\"small\" onClick={() => setRunsFor(workflow)}>\n {'Runs'}\n </Button>\n <Button\n size=\"small\"\n onClick={() => {\n setTestResult(null)\n setDraft({\n id: workflow.$id,\n name: workflow.name ?? '',\n steps: workflow.steps ?? [],\n returnValue: workflow.returnValue ?? '',\n trigger: workflow.trigger ?? null,\n })\n }}\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n onClick={() =>\n duplicate.request('workflow', {\n id: workflow.$id,\n name: workflow.name ?? '',\n })\n }\n >\n {'Duplicate…'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDelete(workflow)}\n >\n {'Delete'}\n </Button>\n </Stack>\n ))\n )}\n {workflows.length === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={visibleWorkflows.length}\n // The workflows the card HOLDS. Not `workflowCount`, which is the\n // site's total including soft-deleted rows and answers the quota's\n // question rather than the reader's.\n count={workflows.length}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n {workflowsTruncated ? (\n <Alert severity=\"info\">\n {`Showing ${WORKFLOW_CEILING} workflows, ordered by id. This site ` +\n 'has more — the duplicate-name check below only covers the ' +\n 'ones listed here, so a name may already be taken by one that ' +\n 'is not.'}\n </Alert>\n ) : null}\n <Button\n size=\"small\"\n color=\"primary\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={handleAdd}\n >\n {'Add workflow'}\n </Button>\n {/* The cap, standing rather than only on refusal (AGL-2113).\n `workflowCount` is the server aggregate the gate uses, not\n `workflows.length` — the listener is `limit(100)` and its length\n saturates (AGL-1716). */}\n <QuotaReadoutComponent\n ready={org != null}\n used={workflowCount}\n limit={checkQuota(org, 'workflowsPerHost', workflowCount).limit}\n noun=\"workflow\"\n />\n </Stack>\n\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"sm\"\n fullWidth\n >\n <DialogTitle>\n {draft?.id ? 'Edit Workflow' : 'Add Workflow'}\n </DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: 1 }}\n >\n {ExtensionZone && editorTarget ? (\n <ExtensionZone\n slot={AUTOMATION_EDITOR_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n target={editorTarget}\n />\n ) : null}\n <TextField\n label=\"Name\"\n helperText={\n nameTaken\n ? 'A workflow with this name already exists'\n : 'Used to identify the workflow'\n }\n error={nameTaken}\n value={draft?.name ?? ''}\n onChange={(event) =>\n patch((previous) => ({ ...previous, name: event.target.value }))\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Steps'}\n </Typography>\n {/*\n The pickers and the test run speak only for what was read. A step\n calling a function past the ceiling still RUNS on the site — this\n editor simply cannot name it, and a test run resolves its\n expression against an incomplete variable set.\n */}\n {shortLists.length > 0 ? (\n <Alert severity=\"info\">\n {`Offering the first ${EDITOR_OPTION_CEILING} ` +\n `${shortLists.join(', ')} on this site, ordered by id. ` +\n 'There are more, so the pickers below are short and a test ' +\n 'run may not resolve every expression.'}\n </Alert>\n ) : null}\n {(draft?.steps ?? []).map((step, index) => {\n const call = isWorkflowActionStep(step)\n ? null\n : (step as HostWorkflowStep)\n const definition = call\n ? (functions[(call as any).functionId ?? ''] ??\n functions[call.functionName])\n : null\n return (\n <AutomationStepFields\n key={index}\n /*\n * The editor speaks the Actions vocabulary. A function call\n * has no Actions type, so it takes none of those fields and\n * renders its own through `fields` instead — which is what\n * keeps this one editor rather than two.\n */\n step={step as HostActionStep}\n index={index}\n kind={call ? FUNCTION_CALL_KIND : (step as HostActionStep).type}\n kinds={STEP_KINDS}\n stepForKind={(value) =>\n (value === FUNCTION_CALL_KIND\n ? { functionName: '', args: [], resultName: '' }\n : defaultStep(\n value as HostActionStepType,\n )) as HostActionStep\n }\n pickers={stepPickers}\n onSteps={(update) =>\n patch((previous) => ({\n ...previous,\n steps: update(\n previous.steps as HostActionStep[],\n ) as WorkflowStep[],\n }))\n }\n // A workflow with no trigger runs from another automation, so\n // its email step is a reply only on its own event.\n replyContext={{\n event: draft?.trigger?.event,\n afterWait: stepRunsAfterWait(draft?.steps as HostActionStep[], index),\n }}\n fields={\n call ? (\n <Stack\n useFlexGap\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', flex: 1, flexWrap: 'wrap' }}\n >\n <TextField\n label=\"Function\"\n // Stored by id (AGL-261); legacy steps carry only the\n // name and resolve through the double-keyed map.\n value={\n (call as any).functionId ??\n (functions[call.functionName] as any)?.$id ??\n ''\n }\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) =>\n index2 === index\n ? {\n ...s,\n functionId: event.target.value,\n functionName:\n functionOptions.find(\n (option) =>\n option.id === event.target.value,\n )?.name ??\n (s as HostWorkflowStep).functionName,\n }\n : s,\n ),\n }))\n }\n size=\"small\"\n select\n sx={{ minWidth: 160, flex: 1 }}\n >\n {functionOptions.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {option.name}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Result name\"\n placeholder={`step${index + 1}`}\n value={call.resultName ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) =>\n index2 === index\n ? {\n ...s,\n resultName: event.target.value.replace(\n /[^a-zA-Z0-9_]/g,\n '',\n ),\n }\n : s,\n ),\n }))\n }\n size=\"small\"\n sx={{ width: 140 }}\n />\n {(definition?.parameters ?? []).map(\n (parameter, parameterIndex) => (\n <TextField\n key={parameter.name}\n label={`${parameter.name} expression`}\n placeholder={\n parameterIndex === 0 && index > 0\n ? `step${index}`\n : 'a variable, number, or expression'\n }\n value={call.args?.[parameterIndex] ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) => {\n if (index2 !== index) return s\n const args = [\n ...((s as HostWorkflowStep).args ?? []),\n ]\n args[parameterIndex] = event.target.value\n return { ...s, args }\n }),\n }))\n }\n size=\"small\"\n sx={{ minWidth: 180, flex: 1 }}\n />\n ),\n )}\n </Stack>\n ) : undefined\n }\n />\n )\n })}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n disabled={(draft?.steps.length ?? 0) >= WORKFLOW_MAX_STEPS}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n steps: [\n ...previous.steps,\n { functionName: '', args: [], resultName: '' },\n ],\n }))\n }\n >\n {'Add step'}\n </Button>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Trigger'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Run on event\"\n value={draft?.trigger?.event ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: event.target.value\n ? {\n event: event.target.value as any,\n filter: previous.trigger?.filter ?? '',\n }\n : null,\n }))\n }\n size=\"small\"\n select\n sx={{ minWidth: 180 }}\n >\n <MenuItem value=\"\">{'Manual only'}</MenuItem>\n {HOST_EVENT_TYPES.map((eventType) => (\n <MenuItem key={eventType} value={eventType}>\n {hostEventLabel(eventType)}\n </MenuItem>\n ))}\n </TextField>\n {draft?.trigger ? (\n <TextField\n label=\"Filter (optional)\"\n placeholder=\"subscribe\"\n // The evaluator is arithmetic and has no comparison (AGL-3458):\n // `path == \"/pricing\"` throws on every event and never runs.\n error={Boolean(triggerFilterProblem(draft?.trigger?.filter, { remedy: 'action' }))}\n helperText={\n triggerFilterProblem(draft?.trigger?.filter, { remedy: 'action' }) ??\n [\n 'Runs only when this expression is truthy — a field name, or arithmetic. It cannot compare values.',\n hostEventPayloadHint(draft?.trigger?.event),\n ]\n .filter(Boolean)\n .join(' ')\n }\n value={draft?.trigger?.filter ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: previous.trigger\n ? { ...previous.trigger, filter: event.target.value }\n : previous.trigger,\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n ) : null}\n </Stack>\n <TextField\n label=\"Return value\"\n helperText=\"A step result name; defaults to the last step\"\n value={draft?.returnValue ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n returnValue: event.target.value,\n }))\n }\n size=\"small\"\n />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Button size=\"small\" color=\"primary\" onClick={handleTestRun}>\n {'Test run'}\n </Button>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Uses current variable values'}\n </Typography>\n </Stack>\n {testResult ? (\n <Alert\n severity={testResult.startsWith('Error') ? 'warning' : 'success'}\n >\n {testResult}\n </Alert>\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim() || nameTaken}\n onClick={handleSave}\n >\n {'Done'}\n </Button>\n </DialogActions>\n </Dialog>\n {ExtensionZone ? (\n <ExtensionZone\n slot={WORKFLOW_USAGE_ZONE.id}\n hostId={hostId}\n usage={usage}\n onClose={() => setUsage(null)}\n />\n ) : null}\n <Dialog\n open={Boolean(runsFor)}\n onClose={() => setRunsFor(null)}\n // md: the history's four columns fit without the table scrolling.\n maxWidth=\"md\"\n fullWidth\n >\n <DialogTitle>{`Runs — ${runsFor?.name ?? ''}`}</DialogTitle>\n <DialogContent>\n {runsFor ? (\n <HostRunHistoryCard\n hostId={hostId}\n orgId={org?.$id}\n targetId={runsFor.$id}\n targetType=\"workflow\"\n targetName={runsFor.name ?? ''}\n header=\"Recent runs\"\n />\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button color=\"inherit\" onClick={() => setRunsFor(null)}>\n {'Close'}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nHostWorkflowsCard.displayName = 'HostWorkflowsCard'\n\nexport default HostWorkflowsCard\n"],"names":["checkEntitlement","checkQuota","HOST_EVENT_TYPES","hostEventLabel","hostEventPayloadHint","pluginDocsHelp","triggerFilterProblem","ceilingedWindow","collectionCeiling","useConsoleWidgetSlot","CardDisplay","useConfirmationContext","ListPagination","TABLE_PAGE_SIZE_DEFAULT","QuotaReadoutComponent","useSnackbar","Timestamp","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Typography","collection","doc","setDoc","updateDoc","getLiveCountFromServer","useCallback","useEffect","useMemo","useState","useDuplicateResource","useFirestore","useFirestoreCollection","useHostResourceApi","useUser","writeGuardedBySeed","AutomationStepFields","defaultStep","isWorkflowActionStep","validateWorkflowSteps","WORKFLOW_ACTION_STEP_TYPES","workflowFunctionCalls","workflowStepTypeLabel","HostRunHistoryCard","EDITOR_OPTION_CEILING","useAutomationStepPickers","listConsoleWidgets","fetchWhereUsed","summarizeDependents","AUTOMATION_EDITOR_ZONE","HOST_AUTOMATIONS_ZONE","openActionHref","WORKFLOW_USAGE_ZONE","runWorkflow","WORKFLOW_MAX_STEPS","stepRunsAfterWait","WORKFLOW_CEILING","FUNCTION_CALL_KIND","STEP_KINDS","value","label","map","HostWorkflowsCard","props","runsFor","draft","hostId","firestore","data","user","createHostResource","enqueueSnackbar","duplicate","onDuplicated","_kind","copy","name","variant","confirm","org","ExtensionZone","actionsHref","openAction","actionId","window","location","assign","automationsZone","slot","id","orgId","$id","workflowDocs","status","workflowsStatus","fromCache","workflowsFromCache","listen","workflowsListen","idField","rows","readWorkflows","truncated","workflowsTruncated","setDraft","editorOpened","setEditorOpened","functionRead","functionDocs","functionsTruncated","variableRead","variableDocs","variablesTruncated","pickers","stepPickers","truncatedPickers","workflows","filter","workflow","deletedAt","sort","a","b","String","localeCompare","page","setPage","pageSize","setPageSize","visibleWorkflows","slice","workflowCountEpoch","setWorkflowCountEpoch","serverWorkflowCount","setServerWorkflowCount","active","then","count","catch","workflowCount","length","functions","definition","functionOptions","variables","variable","usage","setUsage","usageLoading","setUsageLoading","testResult","setTestResult","setRunsFor","nameTaken","Boolean","some","toLowerCase","trim","patch","updater","previous","draftId","draftName","editorTarget","type","handleAdd","persist","quota","allowed","limit","steps","functionName","args","resultName","returnValue","trigger","shortLists","stepProblem","remedy","handleTestRun","run","ok","error","Object","entries","results","key","join","handleSave","fields","verdict","subject","unreadable","updatedAt","now","merge","message","resource","epoch","console","allowDuplicate","handleShowUsage","result","kind","total","handleDelete","scan","confirmed","title","description","confirmationText","confirmationButtonProps","color","header","help","anchor","actions","undefined","contentGutterX","contentGutterY","dialog","spacing","sx","alignItems","direction","flex","minWidth","noWrap","event","step","size","disabled","onClick","request","rowCount","onPageChange","onPageSizeChange","severity","alignSelf","ready","used","noun","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","pt","target","helperText","onChange","autoFocus","mt","index","call","functionId","kinds","stepForKind","onSteps","update","replyContext","afterWait","useFlexGap","flexWrap","s","index2","find","option","select","placeholder","replace","width","parameters","parameter","parameterIndex","eventType","startsWith","targetId","targetType","targetName","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SAEEA,gBAAgB,EAChBC,UAAU,EACVC,gBAAgB,EAChBC,cAAc,EACdC,oBAAoB,EAGpBC,cAAc,EACdC,oBAAoB,QACf,eAAc;AACrB;;;;;CAKC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SAASC,oBAAoB,QAAQ,qDAAoD;AACzF,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,OAAOC,2BAA2B,0DAAyD;AAC3F,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,SAAS,QAAQ,+BA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