@aglyn/plugins-workflows 1.0.0-beta.264 → 1.0.0-beta.268

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/plugins-workflows",
3
- "version": "1.0.0-beta.264",
3
+ "version": "1.0.0-beta.268",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,23 +25,23 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.0.0-beta.264",
29
- "@aglyn/shared-data-mdi": "1.0.0-beta.264",
30
- "@aglyn/shared-ui-jsx": "1.0.0-beta.264",
31
- "@aglyn/shared-ui-next": "1.0.0-beta.264",
32
- "@aglyn/shared-ui-snackstack": "1.0.0-beta.264",
33
- "@aglyn/shared-util-email": "1.0.0-beta.264",
34
- "@aglyn/shared-util-http": "1.0.0-beta.264",
35
- "@aglyn/shared-util-timestamp": "1.0.0-beta.264",
36
- "@aglyn/tenant-data-admin": "1.0.0-beta.264",
37
- "@aglyn/tenant-feature-instance": "1.0.0-beta.264",
38
- "@aglyn/tenant-runtime": "1.0.0-beta.264",
28
+ "@aglyn/aglyn": "1.0.0-beta.268",
29
+ "@aglyn/shared-data-mdi": "1.0.0-beta.268",
30
+ "@aglyn/shared-ui-jsx": "1.0.0-beta.268",
31
+ "@aglyn/shared-ui-next": "1.0.0-beta.268",
32
+ "@aglyn/shared-ui-snackstack": "1.0.0-beta.268",
33
+ "@aglyn/shared-util-email": "1.0.0-beta.268",
34
+ "@aglyn/shared-util-http": "1.0.0-beta.268",
35
+ "@aglyn/shared-util-timestamp": "1.0.0-beta.268",
36
+ "@aglyn/tenant-data-admin": "1.0.0-beta.268",
37
+ "@aglyn/tenant-feature-instance": "1.0.0-beta.268",
38
+ "@aglyn/tenant-runtime": "1.0.0-beta.268",
39
39
  "@swc/helpers": "0.5.23"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@mui/material": "^9.3.1",
43
43
  "@mui/x-data-grid": "^9.12.0",
44
- "firebase": "^12.18.0",
44
+ "firebase": "^13.0.0",
45
45
  "firebase-admin": "^14.3.0",
46
46
  "next": "^16.3.3",
47
47
  "react": "^19.2.8"
@@ -32,7 +32,8 @@ import QuotaReadoutComponent from "@aglyn/shared-ui-jsx/components/quota-readout
32
32
  import { useSnackbar } from "@aglyn/shared-ui-snackstack";
33
33
  import { Timestamp } from "@aglyn/shared-util-timestamp";
34
34
  import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography } from "@mui/material";
35
- import { collection, doc, getCountFromServer, setDoc, updateDoc } from "firebase/firestore";
35
+ import { collection, doc, setDoc, updateDoc } from "firebase/firestore";
36
+ import { getLiveCountFromServer } from "@aglyn/aglyn/app-utils/live-document-count.client";
36
37
  import { useCallback, useEffect, useMemo, useState } from "react";
37
38
  import { useDuplicateResource, useFirestore, useFirestoreCollection, useHostResourceApi, useUser, writeGuardedBySeed } from "@aglyn/tenant-feature-instance";
38
39
  import { AutomationStepFields, defaultStep } from "./automation-step-fields.component.js";
@@ -234,17 +235,16 @@ import { stepRunsAfterWait } from "../model/host-actions.js";
234
235
  * the collection and did. The card offered headroom that did not exist and
235
236
  * then failed the create.
236
237
  *
237
- * UNFILTERED, matching that route's plain `collection('workflows').count()`
238
- * — its `softDeletes` branch governs only the flat per-host webhook cap, so
239
- * soft-deleted workflows have always counted server-side while this card
240
- * excluded them. Only a create moves the number, so that is where it is
241
- * re-read.
238
+ * LIVE workflows, as that route counts them (AGL-3918): a deleted
239
+ * workflow frees its slot, a disabled one keeps it. Every document less
240
+ * the tombstones (`getLiveCountFromServer`). A create or a delete moves the
241
+ * number, so both re-read it.
242
242
  */ const [workflowCountEpoch, setWorkflowCountEpoch] = useState(0);
243
243
  const [serverWorkflowCount, setServerWorkflowCount] = useState(null);
244
244
  useEffect(()=>{
245
245
  let active = true;
246
- void getCountFromServer(collection(firestore, 'hosts', hostId, 'workflows')).then((snapshot)=>{
247
- if (active) setServerWorkflowCount(snapshot.data().count);
246
+ void getLiveCountFromServer(collection(firestore, 'hosts', hostId, 'workflows')).then((count)=>{
247
+ if (active) setServerWorkflowCount(count);
248
248
  }).catch(()=>{
249
249
  // Falls back to the loaded rows — a LOWER bound and the prior
250
250
  // behaviour, never 0, which `checkQuota` would answer as "no usage"
@@ -524,6 +524,8 @@ import { stepRunsAfterWait } from "../model/host-actions.js";
524
524
  await updateDoc(doc(firestore, 'hosts', hostId, 'workflows', workflow.$id), {
525
525
  deletedAt: Timestamp.now()
526
526
  });
527
+ // Deleting frees the slot (AGL-3918), so the head-count is re-read.
528
+ setWorkflowCountEpoch((epoch)=>epoch + 1);
527
529
  enqueueSnackbar('Workflow deleted', {
528
530
  variant: 'success',
529
531
  persist: false
@@ -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 getCountFromServer,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\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 * UNFILTERED, matching that route's plain `collection('workflows').count()`\n * — its `softDeletes` branch governs only the flat per-host webhook cap, so\n * soft-deleted workflows have always counted server-side while this card\n * excluded them. Only a create moves the number, so that is where it is\n * re-read.\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 getCountFromServer(collection(firestore, 'hosts', hostId, 'workflows'))\n .then((snapshot) => {\n if (active) setServerWorkflowCount(snapshot.data().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 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","getCountFromServer","setDoc","updateDoc","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","snapshot","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,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AQ;wCAAUsI,OAAM;kDACjC;;;;4BAGJ9D,2BACC,KAAC1I;gCACCiO,UAAUvF,WAAWgI,UAAU,CAAC,WAAW,YAAY;0CAEtDhI;iCAED;;;kCAEN,MAACvI;;0CACC,KAACF;gCAAO2N,SAAS,IAAMjI,SAAS;0CAAQ;;0CACxC,KAAC1F;gCACCiE,SAAQ;gCACRsI,OAAM;gCACNmB,UAAU,EAACrK,yBAAAA,MAAOW,IAAI,CAACgF,IAAI,OAAMJ;gCACjC+E,SAAS5C;0CAER;;;;;;YAIN3G,8BACC,KAACA;gBACCQ,MAAMpC,oBAAoBqC,EAAE;gBAC5BvB,QAAQA;gBACR+E,OAAOA;gBACPiG,SAAS,IAAMhG,SAAS;iBAExB;0BACJ,MAACrI;gBACCoO,MAAMxF,QAAQzF;gBACdkL,SAAS,IAAM3F,WAAW;gBAC1B,kEAAkE;gBAClE4F,UAAS;gBACTC,SAAS;;kCAET,KAACpO;kCAAa,CAAC,OAAO,WAAEgD,2BAAAA,QAASY,IAAI,oBAAI,IAAI;;kCAC7C,KAAC7D;kCACEiD,wBACC,KAACrB;4BACCuB,QAAQA;4BACRwB,KAAK,EAAEX,uBAAAA,IAAKY,GAAG;4BACf2L,UAAUtN,QAAQ2B,GAAG;4BACrB4L,YAAW;4BACXC,UAAU,GAAExN,gBAAAA,QAAQY,IAAI,YAAZZ,gBAAgB;4BAC5BoJ,QAAO;6BAEP;;kCAEN,KAACtM;kCACC,cAAA,KAACF;4BAAOuM,OAAM;4BAAUoB,SAAS,IAAMhF,WAAW;sCAC/C;;;;;;;AAMb;AACAzF,kBAAkB2N,WAAW,GAAG;AAEhC,eAAe3N,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 } = 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;;;;;;;;;;;;;;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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"}
@@ -16,8 +16,10 @@
16
16
  */ // The seam from its own module, not the plugin-manager barrel: both apps load
17
17
  // this at boot, and the barrel reaches the client contexts.
18
18
  import { registerInteractionStepChecks } from "@aglyn/aglyn/plugin-manager/interaction-step-checks";
19
+ import { registerPluginActivityActions } from "@aglyn/aglyn/plugin-manager/plugin-activity-actions";
19
20
  import { BUNDLE_ID } from "./constants/bundle-common.js";
20
21
  import { hostActionStepProblem, SERVER_ACTION_STEP_TYPES } from "./model/host-actions.js";
22
+ import { describeAutomationRunAction } from "./model/run-activity-words.js";
21
23
  /**
22
24
  * The automation editor's DECLARATIONS: what another surface reads of this
23
25
  * plugin before any of its own surfaces load, in both apps and in the
@@ -32,6 +34,16 @@ import { hostActionStepProblem, SERVER_ACTION_STEP_TYPES } from "./model/host-ac
32
34
  registerInteractionStepChecks(SERVER_ACTION_STEP_TYPES, hostActionStepProblem, {
33
35
  pluginId: BUNDLE_ID
34
36
  });
37
+ // The run lines the engine files in a site's activity read in words in every feed and the apps' activity rows (AGL-3892).
38
+ registerPluginActivityActions({
39
+ pluginId: BUNDLE_ID,
40
+ group: {
41
+ id: 'automation',
42
+ label: 'Automation'
43
+ },
44
+ actions: [],
45
+ describeAction: describeAutomationRunAction
46
+ });
35
47
  }
36
48
 
37
49
  //# sourceMappingURL=declarations.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/plugins/workflows/src/lib/declarations.ts"],"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\n// The seam from its own module, not the plugin-manager barrel: both apps load\n// this at boot, and the barrel reaches the client contexts.\nimport { registerInteractionStepChecks } from '@aglyn/aglyn/plugin-manager/interaction-step-checks'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { hostActionStepProblem, SERVER_ACTION_STEP_TYPES } from './model/host-actions'\n\n/**\n * The automation editor's DECLARATIONS: what another surface reads of this\n * plugin before any of its own surfaces load, in both apps and in the\n * console's browser.\n *\n * The checks of the server steps an automation holds (AGL-3080), so a plugin\n * that writes an automation it does not edit — a recipe installed into a\n * site, a drafted automation graded before it is handed over — refuses what\n * this editor would (`validateStoredInteraction`). Light by construction: the\n * checks are pure, and nothing here reaches Firestore or React.\n */\nexport function registerWorkflowsDeclarations(): void {\n registerInteractionStepChecks(SERVER_ACTION_STEP_TYPES, hostActionStepProblem, { pluginId: BUNDLE_ID })\n}\n"],"names":["registerInteractionStepChecks","BUNDLE_ID","hostActionStepProblem","SERVER_ACTION_STEP_TYPES","registerWorkflowsDeclarations","pluginId"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,4DAA4D;AAC5D,SAASA,6BAA6B,QAAQ,sDAAqD;AACnG,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,qBAAqB,EAAEC,wBAAwB,QAAQ,0BAAsB;AAEtF;;;;;;;;;;CAUC,GACD,OAAO,SAASC;IACdJ,8BAA8BG,0BAA0BD,uBAAuB;QAAEG,UAAUJ;IAAU;AACvG"}
1
+ {"version":3,"sources":["../../../../../../libs/plugins/workflows/src/lib/declarations.ts"],"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\n// The seam from its own module, not the plugin-manager barrel: both apps load\n// this at boot, and the barrel reaches the client contexts.\nimport { registerInteractionStepChecks } from '@aglyn/aglyn/plugin-manager/interaction-step-checks'\nimport { registerPluginActivityActions } from '@aglyn/aglyn/plugin-manager/plugin-activity-actions'\nimport { BUNDLE_ID } from './constants/bundle-common'\nimport { hostActionStepProblem, SERVER_ACTION_STEP_TYPES } from './model/host-actions'\nimport { describeAutomationRunAction } from './model/run-activity-words'\n\n/**\n * The automation editor's DECLARATIONS: what another surface reads of this\n * plugin before any of its own surfaces load, in both apps and in the\n * console's browser.\n *\n * The checks of the server steps an automation holds (AGL-3080), so a plugin\n * that writes an automation it does not edit — a recipe installed into a\n * site, a drafted automation graded before it is handed over — refuses what\n * this editor would (`validateStoredInteraction`). Light by construction: the\n * checks are pure, and nothing here reaches Firestore or React.\n */\nexport function registerWorkflowsDeclarations(): void {\n registerInteractionStepChecks(SERVER_ACTION_STEP_TYPES, hostActionStepProblem, { pluginId: BUNDLE_ID })\n // The run lines the engine files in a site's activity read in words in every feed and the apps' activity rows (AGL-3892).\n registerPluginActivityActions({\n pluginId: BUNDLE_ID,\n group: { id: 'automation', label: 'Automation' },\n actions: [],\n describeAction: describeAutomationRunAction,\n })\n}\n"],"names":["registerInteractionStepChecks","registerPluginActivityActions","BUNDLE_ID","hostActionStepProblem","SERVER_ACTION_STEP_TYPES","describeAutomationRunAction","registerWorkflowsDeclarations","pluginId","group","id","label","actions","describeAction"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,8EAA8E;AAC9E,4DAA4D;AAC5D,SAASA,6BAA6B,QAAQ,sDAAqD;AACnG,SAASC,6BAA6B,QAAQ,sDAAqD;AACnG,SAASC,SAAS,QAAQ,+BAA2B;AACrD,SAASC,qBAAqB,EAAEC,wBAAwB,QAAQ,0BAAsB;AACtF,SAASC,2BAA2B,QAAQ,gCAA4B;AAExE;;;;;;;;;;CAUC,GACD,OAAO,SAASC;IACdN,8BAA8BI,0BAA0BD,uBAAuB;QAAEI,UAAUL;IAAU;IACrG,0HAA0H;IAC1HD,8BAA8B;QAC5BM,UAAUL;QACVM,OAAO;YAAEC,IAAI;YAAcC,OAAO;QAAa;QAC/CC,SAAS,EAAE;QACXC,gBAAgBP;IAClB;AACF"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * What a person reads for a run line the engine files in a site's activity
19
+ * (AGL-3892). The engine writes prose, not a code, such as
20
+ * `Action ran on formSubmission`, `Workflow failed on booking: …` or
21
+ * `Action is waiting, on lead`, and the event inside it is a key. The feed shows the act and
22
+ * the event in words: `Automation ran: Form submitted`.
23
+ *
24
+ * `undefined` for any other action, so the activity seam leaves it alone.
25
+ */
26
+ export declare function describeAutomationRunAction(action: string): string | undefined;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ import { hostEventLabel } from "@aglyn/aglyn/app-utils/host-events";
17
+ /**
18
+ * What a person reads for a run line the engine files in a site's activity
19
+ * (AGL-3892). The engine writes prose, not a code, such as
20
+ * `Action ran on formSubmission`, `Workflow failed on booking: …` or
21
+ * `Action is waiting, on lead`, and the event inside it is a key. The feed shows the act and
22
+ * the event in words: `Automation ran: Form submitted`.
23
+ *
24
+ * `undefined` for any other action, so the activity seam leaves it alone.
25
+ */ export function describeAutomationRunAction(action) {
26
+ const match = /^(Action|Org automation|Workflow) (ran|skipped|failed|is waiting,) on ([A-Za-z][\w.:-]*?)(?:(?: with errors)?:\s.*| with errors:.*)?$/.exec(action.trim());
27
+ if (!match) return undefined;
28
+ const [, actor, verb, event] = match;
29
+ const failed = verb === 'failed' || / with errors:/.test(action);
30
+ const who = actor === 'Action' ? 'Automation' : actor;
31
+ const what = failed ? 'failed' : verb === 'skipped' ? 'skipped' : verb === 'is waiting,' ? 'is waiting' : 'ran';
32
+ return `${who} ${what}: ${eventWords(event)}`;
33
+ }
34
+ /** The event's label; a key no plugin labels (an inbound `webhook`) reads as a word, never as the key. */ function eventWords(event) {
35
+ const label = hostEventLabel(event);
36
+ if (label !== event) return label;
37
+ const words = event.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[._:-]+/g, ' ').toLowerCase();
38
+ return words.charAt(0).toUpperCase() + words.slice(1);
39
+ }
40
+
41
+ //# sourceMappingURL=run-activity-words.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/model/run-activity-words.ts"],"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\nimport { hostEventLabel } from '@aglyn/aglyn/app-utils/host-events'\n\n/**\n * What a person reads for a run line the engine files in a site's activity\n * (AGL-3892). The engine writes prose, not a code, such as\n * `Action ran on formSubmission`, `Workflow failed on booking: …` or\n * `Action is waiting, on lead`, and the event inside it is a key. The feed shows the act and\n * the event in words: `Automation ran: Form submitted`.\n *\n * `undefined` for any other action, so the activity seam leaves it alone.\n */\nexport function describeAutomationRunAction(action: string): string | undefined {\n const match =\n /^(Action|Org automation|Workflow) (ran|skipped|failed|is waiting,) on ([A-Za-z][\\w.:-]*?)(?:(?: with errors)?:\\s.*| with errors:.*)?$/.exec(\n action.trim(),\n )\n if (!match) return undefined\n const [, actor, verb, event] = match\n const failed = verb === 'failed' || / with errors:/.test(action)\n const who = actor === 'Action' ? 'Automation' : actor\n const what = failed\n ? 'failed'\n : verb === 'skipped'\n ? 'skipped'\n : verb === 'is waiting,'\n ? 'is waiting'\n : 'ran'\n return `${who} ${what}: ${eventWords(event)}`\n}\n\n/** The event's label; a key no plugin labels (an inbound `webhook`) reads as a word, never as the key. */\nfunction eventWords(event: string): string {\n const label = hostEventLabel(event)\n if (label !== event) return label\n const words = event.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[._:-]+/g, ' ').toLowerCase()\n return words.charAt(0).toUpperCase() + words.slice(1)\n}\n"],"names":["hostEventLabel","describeAutomationRunAction","action","match","exec","trim","undefined","actor","verb","event","failed","test","who","what","eventWords","label","words","replace","toLowerCase","charAt","toUpperCase","slice"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,cAAc,QAAQ,qCAAoC;AAEnE;;;;;;;;CAQC,GACD,OAAO,SAASC,4BAA4BC,MAAc;IACxD,MAAMC,QACJ,wIAAwIC,IAAI,CAC1IF,OAAOG,IAAI;IAEf,IAAI,CAACF,OAAO,OAAOG;IACnB,MAAM,GAAGC,OAAOC,MAAMC,MAAM,GAAGN;IAC/B,MAAMO,SAASF,SAAS,YAAY,gBAAgBG,IAAI,CAACT;IACzD,MAAMU,MAAML,UAAU,WAAW,eAAeA;IAChD,MAAMM,OAAOH,SACT,WACAF,SAAS,YACP,YACAA,SAAS,gBACP,eACA;IACR,OAAO,GAAGI,IAAI,CAAC,EAAEC,KAAK,EAAE,EAAEC,WAAWL,QAAQ;AAC/C;AAEA,wGAAwG,GACxG,SAASK,WAAWL,KAAa;IAC/B,MAAMM,QAAQf,eAAeS;IAC7B,IAAIM,UAAUN,OAAO,OAAOM;IAC5B,MAAMC,QAAQP,MAAMQ,OAAO,CAAC,sBAAsB,SAASA,OAAO,CAAC,YAAY,KAAKC,WAAW;IAC/F,OAAOF,MAAMG,MAAM,CAAC,GAAGC,WAAW,KAAKJ,MAAMK,KAAK,CAAC;AACrD"}