@w6w/embed 0.2.21 → 0.2.22
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/dist/{ModelRoutesManager-1Ac5wcas.js → ModelRoutesManager-BUw_sm-M.js} +2 -2
- package/dist/ModelRoutesManager-BUw_sm-M.js.map +1 -0
- package/dist/{WorkflowEditor-Cgv3Pvsy.js → WorkflowEditor-LesBKjb2.js} +2 -2
- package/dist/{WorkflowEditor-Cgv3Pvsy.js.map → WorkflowEditor-LesBKjb2.js.map} +1 -1
- package/dist/{editor-tools-j3ThBY_4.js → editor-tools-DHyWiG21.js} +48 -39
- package/dist/{editor-tools-j3ThBY_4.js.map → editor-tools-DHyWiG21.js.map} +1 -1
- package/dist/editor.mjs +1 -1
- package/dist/editors.mjs +63 -56
- package/dist/editors.mjs.map +1 -1
- package/dist/forms.mjs +272 -269
- package/dist/forms.mjs.map +1 -1
- package/dist/lists.mjs +4 -4
- package/dist/lists.mjs.map +1 -1
- package/dist/rail.mjs +1 -1
- package/package.json +2 -2
- package/src/styles.css +30 -4
- package/dist/ModelRoutesManager-1Ac5wcas.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WorkflowEditor-Cgv3Pvsy.js","sources":["../src/chrome/ExecutionProfileHeader.tsx","../src/chrome/history-open-run.ts","../src/chrome/HistoryModal.tsx","../src/chrome/JsonToggle.tsx","../src/lib/workflow-version.ts","../src/editor/BindingBanner.tsx","../src/editor/EditorShell.tsx","../src/editor/PublishTooltip.tsx","../src/editor/SetupIncompleteBanner.tsx","../src/editor/StartingStateModal.tsx","../src/editor/definition.ts","../src/editor/json-apply.ts","../src/editor/step-problems-feed.ts","../src/editor/WorkflowEditor.tsx"],"sourcesContent":["import type { ReactNode } from \"react\";\n\n/**\n * `ExecutionProfileHeader` — the ONE editor header every execution profile's\n * editor mounts (T3.1.1, `building-blocks.md` §Profile building blocks\n * §Mirror).\n *\n * Extracted verbatim from `WorkflowsPage.tsx`'s full-bleed editor head, which\n * is the presentation of record: back control, title, actions. Two hosts use\n * it with two title CONFIGURATIONS, never two headers:\n * - `WorkflowsPage.tsx` — an inline-editable, controlled name input\n * (`editable: true`); back clears the `?edit=` search param; the action row\n * (run / stop / publish / JSON / settings) stays host-owned and arrives as\n * `actions`.\n * - `CallablePage.tsx`'s `CallableEditorChrome` — a Function/Endpoint\n * read-only heading (`editable: false`) with the `incomplete` badge passed\n * as `titleAdornment`, and the host's own JSON toggle then Save button as\n * `actions`.\n *\n * Presentation only: no query, mutation or navigation logic lives here — every\n * callback (`onBack`, `onChange`, `onBlur`) and every node in the action row is\n * the host's, mirroring the `ConnectionHeader.tsx` action-slot precedent.\n *\n * The rendered DOM of the Workflow editor's header is byte-for-byte what it\n * was before the extraction (`wf-fullbleed-head` / `wf-back-btn` /\n * `wf-title-input` / `wf-head-actions`, every `data-testid`, the `aria-label`\n * and the attribute order), which is what `styles.css`'s\n * `.wf-fullbleed-head input.wf-title-input` ancestor specificity and the\n * workflow header screenshot guard both depend on.\n */\n\n/** The editable title variant: the Workflow editor's inline-editable name. */\nexport interface EditableProfileTitle {\n /** The controlled value. */\n value: string;\n /** Called with the new text on every keystroke. */\n onChange: (next: string) => void;\n /** Called when the field loses focus — the Workflow host saves here. */\n onBlur: () => void;\n /** Shown while the value is empty; also the field's minimum sizing basis. */\n placeholder: string;\n /** The `maxLength` the input carries. */\n maxLength: number;\n /** The input's accessible name. */\n ariaLabel: string;\n}\n\n/** The read-only title variant: a Function/Endpoint editor's heading text. */\nexport interface ReadOnlyProfileTitle {\n value: string;\n}\n\n/** Which title the host mounts. The discriminant is `editable`. */\nexport type ExecutionProfileTitle =\n | ({ editable: true } & EditableProfileTitle)\n | ({ editable: false } & ReadOnlyProfileTitle);\n\n/**\n * The editable title field itself. Extracted so the input's own JSX — and the\n * `size` expression `src/lib/__tests__/workflow-title-size.test.ts` extracts\n * and RUNS — lives in one readable place. `size` is capped at the literal 80\n * (the same cap `maxLength` carries on the workflow host), independently of\n * `maxLength`: a name longer than 80 characters can only ever come from the\n * server, so `maxLength` alone would leave a pre-existing long name overflowing\n * its header.\n */\nfunction EditableTitle({ title }: { title: EditableProfileTitle }) {\n const { value, placeholder, maxLength, ariaLabel, onChange, onBlur } = title;\n return (\n <input\n className=\"wf-title-input\"\n value={value}\n placeholder={placeholder}\n maxLength={maxLength}\n size={Math.min(Math.max(value.length, placeholder.length), 80)}\n aria-label={ariaLabel}\n onChange={(e) => onChange(e.target.value)}\n onBlur={onBlur}\n />\n );\n}\n\nexport interface ExecutionProfileHeaderProps {\n /** The back control's click handler — host-owned (the Workflow host clears\n * `?edit=`; `CallableEditorChrome` navigates to the kind's listing). */\n onBack: () => void;\n /** The back control's visible text — host-owned copy (`\"← Workflows\"`,\n * `descriptor.editor.backLabel`). `null`: no back control is rendered. */\n backLabel: string | null;\n /** Editable (Workflow) or read-only (Function/Endpoint) title. */\n title: ExecutionProfileTitle;\n /** Rendered immediately after the title, including an editable workflow name. */\n titleAdornment?: ReactNode;\n /** The host's action row (buttons only; this component owns the wrapper). */\n actions: ReactNode;\n}\n\nexport function ExecutionProfileHeader({\n onBack,\n backLabel,\n title,\n titleAdornment,\n actions,\n}: ExecutionProfileHeaderProps) {\n return (\n <div className=\"wf-fullbleed-head\">\n {backLabel !== null && (\n <button\n type=\"button\"\n className=\"muted wf-back-btn\"\n data-testid=\"wf-editor-back\"\n onClick={onBack}\n >\n {backLabel}\n </button>\n )}\n {title.editable ? (\n <EditableTitle title={title} />\n ) : (\n <h2 className=\"exec-profile-title\">\n {title.value} {titleAdornment}\n </h2>\n )}\n <div className=\"wf-head-actions\" style={{ marginLeft: \"auto\" }}>\n {title.editable && titleAdornment}\n {actions}\n </div>\n </div>\n );\n}\n","import type { CallableKind, ExecutionSummary } from \"../repos/index.ts\";\n\n/**\n * The open-in-editor decision for a History view: only a workflow run has an editor to open, and\n * only when the host supplied `onOpenRun`. The handler closes the modal BEFORE handing the run id\n * to the host (the host's navigation then lands on an unobscured page).\n */\nexport function historyOpenRun(\n kind: CallableKind,\n onOpenRun: ((runId: string) => void) | undefined,\n onClose: () => void,\n): ((execution: ExecutionSummary) => void) | undefined {\n if (kind !== \"workflow\" || onOpenRun === undefined) return undefined;\n return (execution) => {\n onClose();\n onOpenRun(execution.id);\n };\n}\n","/**\n * `HistoryModal` (R-2 / T3.2.1) — the callable's own execution history,\n * opened as a full-page modal OVER the profile instead of away from it: the\n * route and the URL never change, so the editor underneath (unsaved edits,\n * canvas position, selected node) stays exactly as the author left it.\n * Mounted by `HistoryButton` in place of the navigation it used to do.\n *\n * `@w6w/ui`'s `Modal` at `size=\"full\"` (a near-fullscreen work surface,\n * `ui/src/components/Modal.tsx:12`) wraps `HistoryView`, scoped to this one\n * callable (`{ callable: id }`) with `showKind={false}` — a per-callable\n * view already knows its own kind. Filters are LOCAL state, starting empty\n * every time the modal opens, and are never written to the URL (HB10):\n * bookmarking a filtered view only makes sense for the standalone History\n * page, which still owns the URL-backed form.\n *\n * Closeable by ✕ (the `headerRight` button below), Esc (the real `Modal`'s\n * own `cancel` handling) or its backdrop click — all three funnel through\n * the same `onClose`, so the caller's \"focus returns to the History button\"\n * behaviour (`HistoryButton.tsx`) covers every dismissal path.\n *\n * \"Open in visual editor\" only ever applies to a workflow run, and every\n * execution this modal lists already belongs to THIS callable — its scope\n * is `{ callable: id }`, never project-wide — so there is no \"other\n * workflow\" branch to handle here (that one only exists on the project-wide\n * History page, which `HistoryPage.tsx` still owns). Closes the modal and\n * seeds `?run=` on the SAME route; `WorkflowsPage`'s own `[editId, runParam]`\n * effect (T2.4.2 HB7) is what opens the run overlay in place.\n */\nimport { type CallableKind, EMPTY_HISTORY_FILTERS, type HistoryFilters } from \"@w6w/embed/repos\";\nimport { IconButton, Modal } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport { HistoryView } from \"./HistoryView.tsx\";\nimport { historyOpenRun } from \"./history-open-run.ts\";\n\nexport interface HistoryModalProps {\n kind: CallableKind;\n id: string;\n onClose: () => void;\n /** Open a workflow run in the host's editor; absent ⇒ no open-in-editor affordance. */\n onOpenRun?: (runId: string) => void;\n}\n\nexport function HistoryModal(props: HistoryModalProps) {\n const { kind, id, onClose, onOpenRun } = props;\n const [filters, setFilters] = useState<HistoryFilters>(EMPTY_HISTORY_FILTERS);\n\n const onOpenInEditor = historyOpenRun(kind, onOpenRun, onClose);\n\n return (\n <Modal\n size=\"full\"\n title=\"History\"\n subtitle={id}\n onClose={onClose}\n headerRight={<IconButton icon=\"close\" label=\"Close\" onClick={onClose} />}\n >\n <div className=\"w6w-modal-body\">\n <HistoryView\n scope={{ callable: id }}\n showKind={false}\n filters={filters}\n onFiltersChange={setFilters}\n onOpenInEditor={onOpenInEditor}\n />\n </div>\n </Modal>\n );\n}\n","import { IconButton, JsonEditor } from \"@w6w/ui\";\nimport { useMemo, useState } from \"react\";\nimport { Modal } from \"./Modal.tsx\";\n\n/**\n * `apply`: the dialog edits its own copy of the text and hands it to the host only on Apply (the\n * workflow editor, whose canvas re-reads it). `disconnected`: the host owns the text and saves it.\n */\nexport type JsonToggleMode = \"apply\" | \"disconnected\";\n\n/** What `prepareApply` makes of the dialog's text: the text to apply, or why it can't be. */\nexport type JsonApplyCheck =\n | {\n ok: true;\n /** The text `onApply` receives — the edited text with any protected field put back. */\n text: string;\n /** Top-level fields whose loaded value was restored; listed under the editor. */\n restored: string[];\n }\n | { ok: false; error: string };\n\n/** The header icon button: `IconButton` with the set's `json` glyph — the\n * curly-brace icon, distinct from the `code` `</>` \"Call from code\" icon\n * beside it, so the two stop reading as the same button. The local\n * `JsonIcon` SVG this file used to carry is now `icon=\"json\"` in the shared\n * set. */\nexport function JsonToggleButton(props: { onClick: () => void }) {\n return <IconButton icon=\"json\" onClick={props.onClick} label=\"Edit raw JSON definition\" />;\n}\n\nexport interface JsonToggleProps {\n /** Parent-owned; render nothing when false. */\n open: boolean;\n onClose: () => void;\n /** Modal title. */\n title: string;\n mode: JsonToggleMode;\n /** disconnected: parent-owned text, the component keeps NO copy of it. apply: the text the\n * dialog starts from each time it opens. */\n value: string;\n /** disconnected only: every JsonEditor change. */\n onChange?: (text: string) => void;\n /** apply only: validates the dialog's text on every edit; Apply is enabled only on `ok`. */\n prepareApply?: (text: string) => JsonApplyCheck;\n /** apply only: the checked text, on Apply. */\n onApply?: (text: string) => void;\n /** Evaluated on `value` every render; non-null → shown in\n * <p className=\"muted small\" data-testid=\"json-toggle-reason\">. */\n guard?: (text: string) => string | null;\n /** disconnected only. */\n onSave?: () => void;\n /** disconnected only. */\n saving?: boolean;\n /** disconnected only; rendered as <div className=\"error\"> inside the dialog. */\n error?: string | null;\n /** JsonEditor aria-label. */\n editorLabel: string;\n}\n\n/**\n * The JSON⇄editor toggle's chrome — the header icon button's dialog, extracted from\n * `WorkflowsPage.tsx`'s raw-JSON modal (T2.1.1 D-2) and reused by the Function and Endpoint\n * editors in `mode=\"disconnected\"` (T2.1.2). Wraps `@w6w/ui`'s `JsonEditor` and studio's own\n * `Modal`. The editor fills the dialog and scrolls inside itself (`.modal-json`), so the title,\n * the description and the footer buttons stay in view on a long definition.\n */\nexport function JsonToggle(props: JsonToggleProps): JSX.Element | null {\n if (!props.open) return null;\n // Mounted per opening, so each one starts from the host's current text.\n return props.mode === \"apply\" ? (\n <ApplyJsonDialog {...props} />\n ) : (\n <DisconnectedJsonDialog {...props} />\n );\n}\n\nfunction JsonEditorFill(props: { value: string; onChange: (t: string) => void; label: string }) {\n return (\n <div className=\"json-toggle-editor\">\n <JsonEditor\n value={props.value}\n onChange={props.onChange}\n minHeight=\"120px\"\n aria-label={props.label}\n />\n </div>\n );\n}\n\n/**\n * Edits a copy: nothing reaches the host until Apply, which runs `prepareApply` (syntax, shape,\n * protected fields) and is disabled while that fails. The dialog stays open after Apply so the\n * restored-fields note is readable; closing with unapplied edits asks first.\n */\nfunction ApplyJsonDialog(props: JsonToggleProps): JSX.Element {\n const { onClose, title, value, prepareApply, onApply, editorLabel } = props;\n const [text, setText] = useState(value);\n // What the host holds now: the text at opening, then the last applied one.\n const [applied, setApplied] = useState(value);\n const [restored, setRestored] = useState<string[]>([]);\n const [confirming, setConfirming] = useState(false);\n const check = useMemo<JsonApplyCheck>(\n () => prepareApply?.(text) ?? { ok: true, text, restored: [] },\n [prepareApply, text],\n );\n const dirty = text !== applied;\n const requestClose = () => (dirty ? setConfirming(true) : onClose());\n const apply = () => {\n if (!check.ok || !dirty) return;\n onApply?.(check.text);\n setText(check.text);\n setApplied(check.text);\n setRestored(check.restored);\n setConfirming(false);\n };\n\n return (\n <Modal title={title} onClose={requestClose} wide className=\"modal-json\">\n <div className=\"modal-body\">\n <p className=\"muted small\">\n Edit the raw definition (<code>manifestVersion: \"2\"</code>). Apply updates the visual\n editor; Save stores it.\n </p>\n <JsonEditorFill\n value={text}\n onChange={(t) => {\n setText(t);\n setConfirming(false);\n }}\n label={editorLabel}\n />\n {!check.ok && (\n <p className=\"error small\" role=\"alert\" data-testid=\"json-toggle-error\">\n {check.error}\n </p>\n )}\n {restored.length > 0 && (\n <p className=\"muted small\" data-testid=\"json-toggle-restored\">\n Restored {restored.join(\", \")}: {restored.length > 1 ? \"these fields\" : \"this field\"}{\" \"}\n can't be changed in JSON.\n </p>\n )}\n </div>\n <div className=\"modal-actions\">\n {confirming ? (\n <>\n <span className=\"muted small json-toggle-confirm\">Discard unapplied changes?</span>\n <button type=\"button\" className=\"btn ghost\" onClick={() => setConfirming(false)}>\n Keep editing\n </button>\n <button\n type=\"button\"\n className=\"btn danger\"\n data-testid=\"json-toggle-discard\"\n onClick={onClose}\n >\n Discard\n </button>\n </>\n ) : (\n <>\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"json-toggle-close\"\n onClick={requestClose}\n >\n Close\n </button>\n <button\n type=\"button\"\n className=\"btn\"\n data-testid=\"json-toggle-apply\"\n disabled={!check.ok || !dirty}\n onClick={apply}\n >\n Apply\n </button>\n </>\n )}\n </div>\n </Modal>\n );\n}\n\n/**\n * The host owns the text (no copy here, so a reopened dialog never shows a stale snapshot) and\n * saves it itself; `guard` blocks Save with a reason.\n */\nfunction DisconnectedJsonDialog(props: JsonToggleProps): JSX.Element {\n const { onClose, title, value, onChange, guard, onSave, saving, error, editorLabel } = props;\n const guardReason = guard?.(value) ?? null;\n return (\n <Modal title={title} onClose={onClose} wide className=\"modal-json\">\n <div className=\"modal-body\">\n <p className=\"muted small\">Save replaces the stored definition.</p>\n <JsonEditorFill value={value} onChange={(t) => onChange?.(t)} label={editorLabel} />\n {guardReason && (\n <p className=\"muted small\" data-testid=\"json-toggle-reason\">\n {guardReason}\n </p>\n )}\n {error && <div className=\"error\">{error}</div>}\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={onClose}>\n Cancel\n </button>\n <button\n type=\"button\"\n className=\"btn\"\n data-testid=\"json-toggle-save\"\n disabled={guardReason != null || Boolean(saving)}\n onClick={onSave}\n >\n {saving ? \"Saving…\" : \"Save\"}\n </button>\n </div>\n </Modal>\n );\n}\n","/** Compare JSON definitions independent of object property order. Array order is meaningful. */\nexport function sameWorkflowDefinition(a: unknown, b: unknown): boolean {\n const canonical = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(canonical);\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, item]) => [key, canonical(item)]),\n );\n }\n return value;\n };\n // GET adds authoritative metadata absent from older snapshots. Status describes the\n // running publication, not the editable definition; empty tags and a null key are defaults.\n const definition = (value: unknown) => {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return value;\n const { status: _status, ...rest } = value as Record<string, unknown>;\n return { ...rest, key: rest.key ?? null, tags: rest.tags ?? [] };\n };\n return JSON.stringify(canonical(definition(a))) === JSON.stringify(canonical(definition(b)));\n}\n","import { createElement } from \"react\";\n\nexport interface BindingBannerProps {\n kind: \"workflow\" | \"function\" | \"endpoint\";\n problemCount: number;\n canEnable: boolean;\n onEnable: () => void;\n pending?: boolean;\n}\n\n/** The one \"disabled because a connection is gone\" banner all three editors render. */\nexport function BindingBanner(props: BindingBannerProps) {\n const { kind, problemCount, canEnable, onEnable, pending } = props;\n const text =\n problemCount > 0\n ? `This ${kind} is disabled and ${problemCount} ${problemCount === 1 ? \"step uses\" : \"steps use\"} a connection that no longer exists. Choose another connection, save, then Enable.`\n : \"Connections fixed. Enable to run again.\";\n return createElement(\n \"div\",\n { role: \"alert\", className: \"error\", \"data-testid\": \"binding-disabled-banner\" },\n createElement(\"span\", null, text),\n \" \",\n createElement(\n \"button\",\n {\n type: \"button\",\n \"data-testid\": \"binding-enable\",\n disabled: !canEnable || pending === true,\n onClick: onEnable,\n },\n \"Enable\",\n ),\n );\n}\n","/**\n * The editor frame shared by every callable editor: the rail environment, the project expression\n * scope, and (unless `rail={false}`) the workspace + `RightRail`. `WorkflowEditor` uses it; the\n * Function and Endpoint editors reuse it rather than re-inlining the providers.\n *\n * - `rail` omitted / `true`: its OWN nested `WorkspaceProvider` plus a `RightRail` — the editor's\n * rail, and the nested provider is what keeps a host's outer rail empty.\n * - `rail={false}`: no `RightRail`. Inside a `<CallableWorkspace>` the editor publishes into that\n * workspace; with none it mounts its own provider (no rail) so it can still publish and edit.\n */\nimport type { ReactNode } from \"react\";\nimport { type RailTool, RightRail } from \"../chrome/RightRail.tsx\";\nimport { WorkspaceProvider, useHasWorkspace } from \"../chrome/workspace.tsx\";\nimport { ProjectExpressionScope } from \"../rail/ExpressionScope.tsx\";\nimport { editorRailTools } from \"../rail/editor-tools.ts\";\nimport { RailEnvProvider, type RailNavigation } from \"../rail/rail-env.tsx\";\n\nexport interface EditorShellProps {\n /** Resolved project (`null` = none; tools refuse to save). */\n project: string | null;\n onNavigate: (to: RailNavigation) => void;\n /** Default `true`. `false`: render no rail; publish into the enclosing workspace if any. */\n rail?: boolean;\n /** Persisted-rail key; `null` = not yet persistable. */\n storageKey: string | null;\n /** Default {@link editorRailTools}. */\n tools?: readonly RailTool[];\n children: ReactNode;\n}\n\nexport function EditorShell({\n project,\n onNavigate,\n rail = true,\n storageKey,\n tools = editorRailTools,\n children,\n}: EditorShellProps): ReactNode {\n const enclosed = useHasWorkspace();\n const body = (\n <RailEnvProvider project={project} onNavigate={onNavigate}>\n <ProjectExpressionScope project={project}>\n {children}\n {rail && <RightRail tools={tools} storageKey={storageKey} />}\n </ProjectExpressionScope>\n </RailEnvProvider>\n );\n // Own provider when the rail is ours, or when there is no workspace to publish into.\n return rail || !enclosed ? <WorkspaceProvider>{body}</WorkspaceProvider> : body;\n}\n","import { type ReactNode, useId, useState } from \"react\";\n\n/** Immediate, keyboard-accessible publish help; no native title delay. */\nexport function PublishTooltip({\n message,\n disabled = false,\n children,\n}: {\n message: string;\n disabled?: boolean;\n children: (descriptionId: string) => ReactNode;\n}) {\n const id = useId();\n const [open, setOpen] = useState(false);\n return (\n <fieldset\n className=\"wf-publish-tooltip\"\n aria-label=\"Publish workflow\"\n aria-describedby={id}\n tabIndex={disabled ? 0 : undefined}\n onMouseEnter={() => setOpen(true)}\n onMouseLeave={() => setOpen(false)}\n onFocus={() => setOpen(true)}\n onBlur={(event) => {\n if (!event.currentTarget.contains(event.relatedTarget)) setOpen(false);\n }}\n onKeyDown={(event) => {\n if (event.key === \"Escape\") setOpen(false);\n }}\n >\n {children(id)}\n {open && (\n <span id={id} role=\"tooltip\" className=\"wf-publish-hint\">\n {message}\n </span>\n )}\n </fieldset>\n );\n}\n","import { createElement } from \"react\";\n\nexport interface SetupIncompleteBannerProps {\n /** Node id -> what is missing there (the detector's output). */\n problems: Record<string, string[]>;\n /** Node id -> display label; falls back to the id. */\n nodeLabel?: (nodeId: string) => string;\n}\n\n/** Non-blocking \"Setup incomplete\" banner; renders nothing when no node has a problem. */\nexport function SetupIncompleteBanner(props: SetupIncompleteBannerProps) {\n const { problems, nodeLabel } = props;\n const entries = Object.entries(problems).filter(([, items]) => items.length > 0);\n if (entries.length === 0) return null;\n const n = entries.length;\n return createElement(\n \"div\",\n { role: \"status\", className: \"error\", \"data-testid\": \"setup-incomplete-banner\" },\n createElement(\n \"span\",\n null,\n `Setup incomplete: ${n} ${n === 1 ? \"step needs\" : \"steps need\"} attention. The workflow can still run.`,\n ),\n createElement(\n \"ul\",\n { \"data-testid\": \"setup-incomplete-list\" },\n ...entries.map(([id, items]) =>\n createElement(\"li\", { key: id }, `${nodeLabel ? nodeLabel(id) : id}: ${items.join(\", \")}`),\n ),\n ),\n );\n}\n","import { validateInitialState } from \"@w6w/expr\";\nimport { ExpressionEditorModal, useExpressionOptions } from \"@w6w/ui\";\nimport { type StartingDataProblem, startingDataForSave } from \"../lib/index.ts\";\n\n/** What the starting state editor says about a draft it will not save. */\nconst STARTING_DATA_PROBLEM_TEXT: Record<StartingDataProblem, string> = {\n invalid_json: \"This isn't valid JSON yet, so it isn't saved. Fix it to save.\",\n not_object: 'Starting state must be a JSON object, like {\"region\": \"us\"}. Not saved.',\n too_large: \"Starting state is over the 64 KiB limit. Not saved.\",\n};\n\n/**\n * The one editor for a workflow's starting state (`Workflow.initialState`), opened from the\n * rail's State tool (`rail/StartingStateTool.tsx`) and from Settings → Starting data: the expression manager in its\n * starting-state mode. Its `{{ }}` references are resolved once when a run starts, before any\n * step, so the rail has no Previous steps or State section, and no Secrets (a secret never\n * enters state). A click inserts a reference or, with \"Value\", the source's current value. Save\n * goes through `startingDataForSave` and `validateInitialState` (the server's own check); `{}`\n * or empty drops the key.\n */\nexport function StartingStateModal(props: {\n initialState: Record<string, unknown> | undefined;\n onChange: (next: Record<string, unknown> | undefined) => void;\n onClose: () => void;\n}) {\n const options = useExpressionOptions();\n return (\n <ExpressionEditorModal\n mode=\"json-binding\"\n startingState\n title=\"Starting state\"\n fieldLabel=\"initialState\"\n value={undefined}\n options={options}\n jsonValue={props.initialState}\n jsonProblem={(text) => {\n const result = startingDataForSave(text);\n if (!result.ok) return STARTING_DATA_PROBLEM_TEXT[result.reason];\n // The rules the server refuses a save on: a secret reference, a root not readable at\n // run start (steps, state, a trigger), a forbidden key.\n const issue =\n result.value === undefined ? undefined : validateInitialState(result.value)[0];\n return issue ? `${issue.message} Not saved.` : null;\n }}\n onSaveJson={(next) => {\n const result = startingDataForSave(next === undefined ? \"\" : JSON.stringify(next));\n if (result.ok) props.onChange(result.value);\n }}\n onClose={props.onClose}\n />\n );\n}\n","import type { WorkflowStatus } from \"@w6w/sdk\";\nimport type { CallablePolicy, WorkflowSettings, WorkflowVariableRow } from \"../lib/index.ts\";\n\nexport type Parsed = Record<string, unknown> & {\n id?: string;\n name?: string;\n /** D-1: nullable, no backfill; `undefined` when the field is absent from\n * the text entirely — both mean \"no key\" to {@link workflowKeyEditAllowed}\n * (D-3). The rail's Key control (`SettingsTool.tsx`) is the only place\n * this is ever ASSIGNED; this page only ever reads it back. */\n key?: string | null;\n nodes?: unknown[];\n connections?: Record<string, { app: string; connection: string | null }>;\n /** Legacy name for `nodes`; read via `workflowNodes`. */\n steps?: unknown[];\n status?: WorkflowStatus;\n tags?: string[];\n /** Authoring presentation — rides in the definition, no column of its own. */\n settings?: WorkflowSettings;\n /** Declared public input schema (T1.1.5) — see `workflow-variables.ts`. */\n variables?: WorkflowVariableRow[];\n /**\n * The RUN-level error policy (core Workflow RFC — *Amendment — 2026-08-21:\n * the run-level error handler*). Authored from the right rail's Error\n * handling tool, which this page hands a writer to rather than letting it\n * save independently — see the `useWorkspace` call below.\n */\n retry?: CallablePolicy[\"retry\"];\n onError?: CallablePolicy[\"onError\"];\n reroute?: CallablePolicy[\"reroute\"];\n};\n\n/** Workflow ids: start alphanumeric, then word chars / dots / dashes. */\nexport const ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;\n\n/** Placeholder + minimum sizing basis for the inline title field. */\nexport const TITLE_PLACEHOLDER = \"Untitled workflow\";\n","import type { JsonApplyCheck } from \"../chrome/JsonToggle.tsx\";\nimport { ID_RE, type Parsed } from \"./definition.ts\";\n\n/**\n * The top-level fields the raw-JSON dialog may not change: `id` names the row the save writes to,\n * `key` is assigned only by the rail's Settings → Key control (`workflowKeyEditAllowed`), and\n * `manifestVersion` is the one value the server's `parseWorkflowDefinition` accepts. An edit that\n * alters or deletes one is not refused: Apply puts the loaded value back and says so.\n */\nexport const PROTECTED_WORKFLOW_FIELDS = [\"id\", \"key\", \"manifestVersion\"] as const;\n\n/**\n * The offset of the first character that makes `text` invalid JSON, or `null` when it is valid.\n * Engines disagree on whether `JSON.parse` reports a position at all (current V8 quotes a snippet\n * instead), so the dialog finds it itself with this small strict scanner.\n */\nexport function jsonErrorOffset(text: string): number | null {\n let i = 0;\n const ws = () => {\n while (i < text.length && \" \\t\\n\\r\".includes(text[i] as string)) i++;\n };\n const fail = (): never => {\n throw i;\n };\n const lit = (word: string) => {\n for (const ch of word) {\n if (text[i] !== ch) fail();\n i++;\n }\n };\n const str = () => {\n i++;\n while (text[i] !== '\"') {\n const ch = text[i];\n if (ch === undefined || ch < \" \") fail();\n if (ch === \"\\\\\") {\n i++;\n if (text[i] === \"u\") {\n for (let k = 0; k < 4; k++) {\n i++;\n if (!/[0-9a-fA-F]/.test(text[i] ?? \"\")) fail();\n }\n } else if (!'\"\\\\/bfnrt'.includes(text[i] ?? \"x\")) fail();\n }\n i++;\n }\n i++;\n };\n const NUM = /-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?/y;\n const num = () => {\n NUM.lastIndex = i;\n if (!NUM.test(text)) fail();\n i = NUM.lastIndex;\n };\n const value = (): void => {\n ws();\n const ch = text[i];\n if (ch === \"{\" || ch === \"[\") {\n const close = ch === \"{\" ? \"}\" : \"]\";\n i++;\n ws();\n if (text[i] === close) {\n i++;\n return;\n }\n for (;;) {\n if (close === \"}\") {\n ws();\n if (text[i] !== '\"') fail();\n str();\n ws();\n if (text[i] !== \":\") fail();\n i++;\n }\n value();\n ws();\n if (text[i] === \",\") i++;\n else if (text[i] === close) {\n i++;\n return;\n } else fail();\n }\n }\n if (ch === '\"') str();\n else if (ch === \"t\") lit(\"true\");\n else if (ch === \"f\") lit(\"false\");\n else if (ch === \"n\") lit(\"null\");\n else num();\n };\n try {\n value();\n ws();\n return i < text.length ? i : null;\n } catch (at) {\n return typeof at === \"number\" ? Math.min(at, text.length) : 0;\n }\n}\n\n/** `JSON.parse`'s message, prefixed with the 1-based line and column of the first bad character. */\nexport function jsonSyntaxError(text: string, e: unknown): string {\n const message = e instanceof Error ? e.message : String(e);\n const at = jsonErrorOffset(text);\n if (at === null) return message;\n const before = text.slice(0, at);\n const line = before.split(\"\\n\").length;\n const column = at - before.lastIndexOf(\"\\n\");\n return `Line ${line}, column ${column}: ${message}`;\n}\n\nconst isObj = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\n/**\n * The save-time shape rules the server applies (`parseWorkflowDefinition` + the step-id gate),\n * restated for the fields the canvas reads, plus the one the canvas needs on top: every edge names\n * a node that exists, or React Flow drops it silently and the next canvas edit deletes it.\n */\nexport function workflowShapeError(def: Record<string, unknown>): string | null {\n if (typeof def.name !== \"string\" || def.name.length === 0) return \"`name` is required.\";\n const nodes = def.nodes ?? def.steps;\n if (!Array.isArray(nodes)) return \"`nodes` must be an array.\";\n const ids = new Set<string>();\n for (let i = 0; i < nodes.length; i++) {\n const n: unknown = nodes[i];\n if (!isObj(n)) return `\\`nodes[${i}]\\` must be an object.`;\n if (typeof n.id !== \"string\" || n.id.length === 0) {\n return `\\`nodes[${i}].id\\` must be a non-empty string.`;\n }\n if (n.id.includes(\".\")) return `Node id \"${n.id}\" may not contain \".\".`;\n if (ids.has(n.id)) return `Node id \"${n.id}\" is used twice.`;\n ids.add(n.id);\n const p = n.position;\n if (p !== undefined && (!isObj(p) || !Number.isFinite(p.x) || !Number.isFinite(p.y))) {\n return `\\`nodes[${i}].position\\` must be { \"x\": number, \"y\": number }.`;\n }\n }\n if (def.edges !== undefined) {\n if (!Array.isArray(def.edges)) return \"`edges` must be an array.\";\n for (let i = 0; i < def.edges.length; i++) {\n const e: unknown = def.edges[i];\n if (!isObj(e)) return `\\`edges[${i}]\\` must be an object.`;\n for (const end of [\"from\", \"to\"] as const) {\n if (typeof e[end] !== \"string\" || !ids.has(e[end] as string)) {\n return `\\`edges[${i}].${end}\\` does not name an existing node.`;\n }\n }\n }\n }\n return null;\n}\n\n/**\n * Everything Apply checks, in order: the text parses, it is an object, the protected fields carry\n * the loaded values (restored when not), and the result has a shape the canvas and the save accept.\n * `ok` hands back the text to apply — re-serialized when a field was restored, verbatim otherwise.\n */\nexport function prepareWorkflowJsonApply(text: string, loaded: Parsed | null): JsonApplyCheck {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch (e) {\n return { ok: false, error: jsonSyntaxError(text, e) };\n }\n if (!isObj(value)) return { ok: false, error: \"The definition must be a JSON object.\" };\n const restored: string[] = [];\n let next: Record<string, unknown> = value;\n // Deleted ones go back in front, in this order, where the loaded document keeps them.\n const front: Record<string, unknown> = {};\n if (loaded) {\n for (const f of PROTECTED_WORKFLOW_FIELDS) {\n const had = Object.hasOwn(loaded, f);\n const has = Object.hasOwn(next, f);\n if (had === has && JSON.stringify(loaded[f]) === JSON.stringify(next[f])) continue;\n restored.push(f);\n if (!had) {\n const { [f]: _drop, ...rest } = next;\n next = rest;\n } else if (has) next = { ...next, [f]: loaded[f] };\n else front[f] = loaded[f];\n }\n next = { ...front, ...next };\n }\n if (typeof next.id === \"string\" && !ID_RE.test(next.id))\n return { ok: false, error: \"Invalid workflow id.\" };\n const shape = workflowShapeError(next);\n if (shape !== null) return { ok: false, error: shape };\n return { ok: true, text: restored.length > 0 ? JSON.stringify(next, null, 2) : text, restored };\n}\n","/**\n * Pure merge of the host's problem sources into the canvas's `stepProblems`:\n * connection problems (host lookup, `findBindingProblems`), loop problems\n * (`findLoopProblems`) and state problems (`findStateWriteProblems`), the last two\n * from `@w6w/ui/flow`. Type-only imports — the runtime helpers reach the host\n * through the editor's existing dynamic `import()`.\n */\nimport type { StepProblem, StepProblems } from \"@w6w/ui/flow\";\nimport type { BindingProblem } from \"../lib/binding-problems.ts\";\n\n/** Per step: its connection problem first, then its loop problems, then its state\n * problems, then its setup-incomplete problem; all kept, empty lists skipped. */\nexport function mergeStepProblems(\n bindingProblems: readonly BindingProblem[],\n loopProblems: StepProblems | undefined,\n stateProblems?: StepProblems,\n setupProblems?: StepProblems,\n): StepProblems {\n const out: StepProblems = {};\n for (const p of bindingProblems) {\n const conn: StepProblem = { code: p.code, connection: p.connection };\n out[p.siteId] = [...(Object.hasOwn(out, p.siteId) ? out[p.siteId] : []), conn];\n }\n for (const source of [loopProblems, stateProblems, setupProblems]) {\n for (const [id, list] of Object.entries(source ?? {})) {\n if (list.length > 0) out[id] = [...(Object.hasOwn(out, id) ? out[id] : []), ...list];\n }\n }\n return out;\n}\n","import { useQueries, useQueryClient } from \"@tanstack/react-query\";\nimport { ApiError } from \"@w6w/sdk\";\nimport {\n ExecutionLogPanel,\n IconButton,\n W6WUIProvider,\n isTestRequired,\n requiredParamsFilled,\n testInputSavesSettled,\n useW6WApi,\n} from \"@w6w/ui\";\nimport type { WorkflowConnectionResources } from \"@w6w/ui/flow\";\nimport type { InternalNodeDef, RunFromNodeRequest, StepProblems } from \"@w6w/ui/flow\";\nimport {\n type ReactNode,\n Suspense,\n lazy,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { ExecutionProfileHeader } from \"../chrome/ExecutionProfileHeader.tsx\";\nimport { HistoryModal } from \"../chrome/HistoryModal.tsx\";\nimport { JsonToggle, JsonToggleButton } from \"../chrome/JsonToggle.tsx\";\nimport { Modal } from \"../chrome/Modal.tsx\";\nimport { useWorkspace } from \"../chrome/workspace.tsx\";\nimport { useEmbedClient, useWorkflowDraft } from \"../draft/index.ts\";\nimport {\n type AppConnections,\n disabledBannerState,\n findBindingProblems,\n} from \"../lib/binding-problems.ts\";\nimport {\n type ActionParamLike,\n type CallablePolicy,\n type TriggerPreview,\n type TriggerPreviewFieldDef,\n type ValidityContext,\n type WorkflowLike,\n type WorkflowStepLike,\n definitionWithPolicy,\n invalidReason,\n policyFromDefinition,\n publishDisabledReason,\n publishProblems,\n readSettings,\n readStartingData,\n readVariables,\n triggerPreviews,\n variablesForSave,\n workflowKeyEditAllowed,\n writeSetting,\n} from \"../lib/index.ts\";\nimport { findSetupIncomplete } from \"../lib/setup-incomplete.ts\";\nimport { workflowNodes } from \"../lib/workflow-nodes.ts\";\nimport { sameWorkflowDefinition } from \"../lib/workflow-version.ts\";\nimport { useEditorProject, useEmbedProject } from \"../project-context.ts\";\nimport type { RailNavigation } from \"../rail/rail-env.tsx\";\nimport { connectionsForAppKey, listConnectionsForApp } from \"../repos/connections.ts\";\nimport {\n STEP_PASS_REFRESH_DELAYS_MS,\n classifyCancelError,\n headerRunEntry,\n isRunInFlight,\n listStepTests,\n listTestInputs,\n mapRunStateToLogSteps,\n resolveHeaderRunInput,\n runButtonLabel,\n runLevelErrors,\n runNodeMap,\n stepPassRefreshDue,\n stepTestsKey,\n useCancelRunMutation,\n useConstantsQuery,\n useDataStoresQuery,\n useLiveRunQuery,\n usePublishMutation,\n useRunFromNodeMutation,\n useRunStateWritesQuery,\n useSecretsQuery,\n useSetEnabledMutation,\n useStartRunMutation,\n useVarsQuery,\n useVersionsQuery,\n workflowStepTestsKey,\n} from \"../repos/index.ts\";\nimport { useRevertMutation, useVersionQuery } from \"../repos/versions.ts\";\nimport { EmbedThemeContext } from \"../theme-context.ts\";\nimport { BindingBanner } from \"./BindingBanner.tsx\";\nimport { EditorShell } from \"./EditorShell.tsx\";\nimport { PublishTooltip } from \"./PublishTooltip.tsx\";\nimport { SetupIncompleteBanner } from \"./SetupIncompleteBanner.tsx\";\nimport { StartingStateModal } from \"./StartingStateModal.tsx\";\nimport { ID_RE, type Parsed, TITLE_PLACEHOLDER } from \"./definition.ts\";\nimport { appActionsKey, useEditorApps } from \"./editor-apps.ts\";\nimport { prepareWorkflowJsonApply } from \"./json-apply.ts\";\nimport { mergeStepProblems } from \"./step-problems-feed.ts\";\nimport type {\n WorkflowEditorNavigation,\n WorkflowEditorProps,\n WorkflowEditorSlots,\n} from \"./types.ts\";\n\n// The visual editor is code-split — its @xyflow/react payload only loads when\n// the editor is actually open.\nconst WorkflowFlowEditor = lazy(() =>\n import(\"@w6w/ui/flow\").then((m) => ({ default: m.WorkflowFlowEditor })),\n);\n\nfunction EditorBody(props: {\n workflowId: string;\n project: string | null;\n /** The provider is still resolving `{use:\"default\"}`: no project YET, which is not an error. */\n projectPending: boolean;\n initialRunId?: string;\n onNavigate: (to: WorkflowEditorNavigation) => void;\n slots?: WorkflowEditorSlots;\n}) {\n const { workflowId, project, projectPending, initialRunId, onNavigate, slots } = props;\n const apiClient = useEmbedClient();\n const api = useW6WApi();\n // Page-level errors only (run, publish, create); the draft's own load/save errors come from\n // `useWorkflowDraft` (`draftError` below).\n const [error, setError] = useState<string | null>(null);\n const [showJson, setShowJson] = useState(false);\n // The canvas seeds its graph from `value` once per mount (it re-reads only on a workflow id\n // change), so a definition replaced from outside it — a JSON Apply, a reload from the server —\n // remounts it through this key. Without it the canvas kept showing the old graph and its next\n // edit wrote that old graph back over the applied JSON.\n const [canvasRevision, setCanvasRevision] = useState(0);\n const [showHistory, setShowHistory] = useState(false);\n const [showStartingState, setShowStartingState] = useState(false);\n const [reloading, setReloading] = useState(false);\n\n // D-3/P4: the key the SERVER most recently sent for the row the buffer is showing — what\n // `workflowKeyEditAllowed` compares the parsed text's own `key` against. `undefined` = nothing\n // loaded yet (refuses unconditionally). Captured whenever the buffer equals the server's copy\n // (load, 409 reload, and after a save), never while it holds unsaved edits. State, not a ref:\n // the guard below must change identity for the draft to re-evaluate it.\n const [loadedKey, setLoadedKey] = useState<string | null | undefined>(undefined);\n // Injected into the draft (the hook is headless — these are Studio's own rules).\n // `autoSave` and the publish-validity reason both depend on the parsed text, which the hook\n // itself produces, so they ride refs assigned after the call (one render of lag at most).\n const autoSaveRef = useRef(true);\n const publishReasonRef = useRef<(def: unknown) => string | null>(() => null);\n const saveGuard = useCallback(\n (def: unknown): string | null => {\n const d = def as Parsed;\n if (!ID_RE.test(typeof d.id === \"string\" ? d.id : \"\")) return \"Invalid workflow id.\";\n // D-3/P4: the rail's Key control is the only place a key is ever assigned — this JSON\n // editor must refuse to save a definition whose `key` differs from what was loaded. Folded\n // into the draft's save gate (never a separate `disabled` on the Save button): auto-save\n // reads the same gate, so a guard on the button alone would be bypassed by typing.\n return workflowKeyEditAllowed(loadedKey, d.key).reason;\n },\n [loadedKey],\n );\n // Load, buffer, save, auto-save, flush-on-hide/unmount and the 409 all live in the hook\n // (`../draft`). The project is `useEditorProject`'s answer (prop, else the provider's): with\n // none, the hook refuses to save (`saveBlockedReason`) rather than let the server pick the\n // account default.\n const draft = useWorkflowDraft({\n workflowId,\n project,\n autoSave: autoSaveRef.current,\n // The expression editor holds uncommitted parts in its own local state until its Save\n // button, so saving from under it would persist a workflow without the expression the user\n // is looking at. Read at fire time (opening it changes neither the buffer nor `canSave`).\n canAutoSave: () => !document.querySelector(\".w6w-exprmodal\"),\n saveGuard,\n publishBlockedReason: (def) => publishReasonRef.current(def),\n });\n const json = draft.json;\n const parsed = draft.parsed as Parsed | null;\n const canSave = draft.canSave;\n const dirty = draft.dirty;\n\n // Capture the server's key whenever the buffer equals the server's copy (never while it holds\n // unsaved edits), and forget it while a workflow is loading or failed to load.\n useEffect(() => {\n if (draft.loading || draft.loadError !== null) {\n setLoadedKey(undefined);\n return;\n }\n if (!draft.dirty && parsed) setLoadedKey((parsed.key as string | null | undefined) ?? null);\n }, [draft.loading, draft.loadError, draft.dirty, parsed]);\n\n // \"Keep editing\" dismisses the 409 modal; the draft stays stale (it refuses to save into the\n // conflict) until the author reloads.\n const [staleDismissed, setStaleDismissed] = useState(false);\n useEffect(() => {\n if (!draft.stale) setStaleDismissed(false);\n }, [draft.stale]);\n\n // The \"Saved.\" marker: a save finished without error since the last one began.\n const [saved, setSaved] = useState(false);\n const wasSaving = useRef(false);\n useEffect(() => {\n if (draft.saving) setSaved(false);\n else if (wasSaving.current && draft.error === null) setSaved(true);\n wasSaving.current = draft.saving;\n }, [draft.saving, draft.error]);\n\n // T2.1.1: the run this canvas is currently showing, if any. Reset inside\n // the `workflowId` load effect below, so a run from a previously open\n // workflow never bleeds into a different one's canvas.\n const [activeRunId, setActiveRunId] = useState<string | null>(null);\n\n // Names offered by each step field's expression picker (task 3.2). The vault\n // No project-scope memo here any more. The ƒx rail's vars, secrets,\n // documents, sample values and \"+ Add\"/seal callbacks are INHERITED from\n // `ProjectExpressionScope` (`App.tsx`); `WorkflowFlowEditor` and the settings\n // modal below both read them from context. What this page's editor\n // contributes on top — the upstream `steps` for one node, and the narrowed\n // `vars` rail for a variable's own default row — is added where it is known,\n // not restated here. See `ui/ExpressionScope.tsx`.\n\n // ── T2.1.1: Run/Stop in the visual editor — live poll, canvas feedback, ──\n // ── log panel, read-only lock. See building-blocks.md §G3/§G4/§G6/§5. ────\n const startRunMut = useStartRunMutation();\n const runFromNodeMut = useRunFromNodeMutation();\n const cancelRunMut = useCancelRunMutation();\n const runQuery = useLiveRunQuery(activeRunId);\n const runStatus = runQuery.data?.status;\n const runPollFailed = runQuery.isError;\n const runInFlight = isRunInFlight(runStatus, runPollFailed);\n // 26-10-04-01-fixes I-1: the run log's rows (each carrying its step's error)\n // and the run-level `error`/`stepErrors` the rows don't already show —\n // mapped once per render, shared by the panel's three props.\n // T5.1.1: a run record carries its per-node map under `nodes` (canonical) or\n // the legacy `steps` — `runNodeMap` prefers `nodes`.\n // State tree: the run's state-write log rides beside the run poll (same cadence, its own\n // query) and feeds each row's State block; a failed or absent log leaves the rows as they are.\n const stateWritesQuery = useRunStateWritesQuery(activeRunId, runStatus);\n const runLogSteps = mapRunStateToLogSteps(\n runNodeMap(runQuery.data),\n stateWritesQuery.data?.writes,\n );\n const runLogErrors = runLevelErrors(runQuery.data, runLogSteps);\n // Header Run fetches the trigger's saved fixture before starting the run;\n // the ref guards re-entry synchronously (a second click can land before the\n // re-render that disables the button), the state disables the button.\n const runStartingRef = useRef(false);\n const [runStarting, setRunStarting] = useState(false);\n\n // ── T2.4.2: `?run=<runId>` — the History page's \"Open in visual editor\" ──\n // A workflow run's History row links to `workflows/<id>?run=<runId>`, and\n // THIS editor is what that link opens. The run plumbing above already\n // renders a terminal run exactly like a live one (`useLiveRunQuery` stops\n // polling on a terminal status by itself), so seeding `activeRunId` from the\n // URL is the whole feature — nothing about the poll, the canvas, the\n // read-only lock or the log panel moves.\n //\n // Declared AFTER the `workflowId` load effect on purpose: that effect resets\n // `activeRunId` for the row it is opening, and effects run in declaration\n // order, so on a mount the URL's run wins. Keyed on `[workflowId, initialRunId]`\n // rather than on mount alone, so an in-app transition to `?run=…` while the\n // editor stays mounted (`history.pushState` + `popstate`) still opens the\n // panel.\n // T2.1.1: a run belongs to the row that started it — the draft's load (formerly this page's\n // `workflowId` effect) reset it; declared BEFORE the `?run=` seed below so the URL's run still wins.\n // biome-ignore lint/correctness/useExhaustiveDependencies: `workflowId` is the trigger, not a value read\n useEffect(() => {\n setActiveRunId(null);\n }, [workflowId]);\n // biome-ignore lint/correctness/useExhaustiveDependencies: `workflowId`'s own value is never read below — it exists solely to re-seed the URL's run when the OPEN WORKFLOW changes, not as a value this closure needs (same retrigger-dependency shape as `api/w6wApiFacade.tsx`).\n useEffect(() => {\n if (initialRunId) setActiveRunId(initialRunId);\n }, [workflowId, initialRunId]);\n\n // The run id alone is not enough: a stale or hand-edited `?run=` can name a\n // run belonging to a DIFFERENT workflow, and painting that run's steps on\n // this canvas would be a lie. `RunState` carries its own `workflowId`, so the\n // first answer that names another workflow drops the run instead of\n // rendering it.\n useEffect(() => {\n if (runQuery.data && runQuery.data.workflowId !== workflowId) setActiveRunId(null);\n }, [runQuery.data, workflowId]);\n\n /**\n * T2.1.5: run `action` only once the buffer is saved. `blocked` shows its reason in the banner;\n * `failed` is already surfaced by the draft itself (banner, or the 409 modal via `draft.stale`).\n */\n async function runAfterFlush(action: () => Promise<unknown>) {\n try {\n const r = await draft.flushThen(action);\n if (!r.ok && r.outcome.status === \"blocked\") setError(r.outcome.reason);\n } catch (e) {\n setError(e instanceof ApiError ? e.message : String(e));\n }\n }\n\n async function onRunClick() {\n if (!workflowId || runInFlight || runStartingRef.current) return;\n setError(null);\n runStartingRef.current = true;\n setRunStarting(true);\n try {\n // 26-10-04-01-fixes I-1 (pinned): the entry trigger's latest saved Test-tab\n // values become the run's `input`, verbatim; no fixture (or no trigger,\n // or a failed fetch) sends no `input` key, exactly as before. The entry is\n // the Manual trigger, else a webhook / schedule / app trigger — whose sample\n // payload is just as much what the author means to run with.\n const entry = flowHelpers\n ? headerRunEntry(steps, flowHelpers.isManualTrigger, flowHelpers.isEntryTrigger)\n : triggerPreviewList?.[0] && { id: triggerPreviewList[0].id, manual: true };\n // A payload edited a moment ago (the Test tab saves as it closes) lands before it is read.\n await testInputSavesSettled();\n const input = await resolveHeaderRunInput(\n entry?.id,\n (stepId) => listStepTests(apiClient, workflowId, stepId),\n () => listTestInputs(apiClient, workflowId),\n );\n // T2.1.5 (R-27): the stored row is what runs, so an unsaved edit is saved FIRST. A refused\n // flush (`blocked` reason / `failed` save) never starts the run.\n await runAfterFlush(() =>\n entry && !entry.manual\n ? // A webhook / schedule / app trigger entry runs FROM that trigger: the server takes\n // the payload as the event that fired it (its output and `trigger.event`), which a\n // plain run's `input` — the Manual trigger's slot — never reaches.\n runFromNodeMut\n .mutateAsync({\n id: workflowId,\n nodeId: entry.id,\n body: { stopAt: [], ...(input ? { input } : {}) },\n })\n .then((res) => setActiveRunId(res.runId))\n : startRunMut\n .mutateAsync({\n id: workflowId,\n variables: {},\n ...(input ? { input } : {}),\n })\n .then((res) => setActiveRunId(res.runId)),\n );\n } finally {\n runStartingRef.current = false;\n setRunStarting(false);\n }\n }\n\n /**\n * ▶ on a node (adhoc/run-pause): a real run that executes the node, continues downstream and\n * stops before every paused node. Saved first, like the header Run, because the stored row is\n * what runs; then shown exactly like a header run — live canvas + run log. A refusal (a blocked\n * save, an API error) rejects, and the editor shows it in the ▶ modal.\n */\n async function onRunFromNode(nodeId: string, req: RunFromNodeRequest) {\n if (!workflowId) return;\n setError(null);\n const r = await draft.flushThen(() =>\n runFromNodeMut.mutateAsync({\n id: workflowId,\n nodeId,\n body: {\n stopAt: req.stopAt,\n ...(req.state?.steps ? { nodes: req.state.steps } : {}),\n ...(req.input ? { input: req.input } : {}),\n },\n }),\n );\n if (!r.ok) {\n throw new Error(\n r.outcome.status === \"blocked\"\n ? r.outcome.reason\n : \"The workflow could not be saved, so it was not run.\",\n );\n }\n setActiveRunId(r.value.runId);\n }\n\n function onStopClick() {\n if (!activeRunId) return;\n cancelRunMut.mutate(activeRunId, {\n onError: (e) => {\n const code = e instanceof ApiError ? e.code : \"\";\n // A `409 run_not_cancelable` means the run already finished before the\n // cancel request landed — reconcile via the next poll, no error banner.\n if (classifyCancelError(code) === \"surface\") {\n setError(e instanceof ApiError ? e.message : String(e));\n }\n },\n });\n // T1.1.1 A1: ask the server to cancel, but reset the LOCAL run state now —\n // the cancel is cooperative (heartbeat-driven) and may land long after the\n // click, so waiting for a poll to observe a terminal status would leave the\n // canvas greyed out in front of the user who just pressed Stop. The request\n // above still goes out, and `onError` still classifies the 409.\n setActiveRunId(null);\n }\n\n /** Replace the editor's contents with the server's copy and re-arm the token. */\n async function reloadFromServer() {\n setReloading(true);\n try {\n await draft.reload();\n setCanvasRevision((r) => r + 1);\n setError(null);\n } finally {\n setReloading(false);\n }\n }\n\n // Page-level errors win; the draft's own load/save failure shows otherwise. A 409 is the\n // modal's business, not the banner's.\n const draftFailure = draft.stale ? null : (draft.error ?? draft.loadError);\n const bannerError =\n error ??\n (draftFailure === null\n ? null\n : draftFailure instanceof Error\n ? draftFailure.message\n : String(draftFailure));\n\n // Parse for the visual view + meta fields — the draft already parses (memoized) per edit.\n // T5.1.1: a definition declares its vertices under `nodes` (canonical) or the\n // legacy `steps` — either shape is drawable.\n const flowUsable =\n parsed !== null && (Array.isArray(parsed.nodes) || Array.isArray(parsed.steps));\n\n const displayName = (parsed?.displayName as string) ?? \"\";\n // Both flags are ON for a workflow that declares no `settings` — see readSettings.\n const settings = readSettings(parsed?.settings);\n // The starting state (`Workflow.initialState`): the rail State tool's dot and its editor.\n const startingState = readStartingData(parsed?.initialState);\n // The Variables tab's rows (T1.1.5) — declaring the workflow's public input\n // schema (HITL-5). `useMemo` because `varsRailFor` runs once per row on\n // every render otherwise.\n const variables = useMemo(() => readVariables(parsed?.variables), [parsed?.variables]);\n // Visible only once something has actually loaded AND the parsed text is\n // real JSON — never flashes \"Workflow not loaded yet\" on a fresh mount\n // before the initial fetch resolves.\n const keyEdit = workflowKeyEditAllowed(loadedKey, parsed?.key);\n const keyGuardReason =\n parsed !== null && loadedKey !== undefined && !keyEdit.allowed ? keyEdit.reason : null;\n\n // ── Publish-time validity gate (T4.2.1) ──────────────────────────────────\n // T5.1.1: `workflowNodes` reads `nodes` (canonical) or the legacy `steps`.\n const steps = useMemo<WorkflowStepLike[]>(\n () => workflowNodes<WorkflowStepLike>(parsed as WorkflowLike | null),\n [parsed],\n );\n\n // `INTERNAL_NODES`/`isInternalApp`/`internalNodeParams` resolve from the SAME\n // `import(\"@w6w/ui/flow\")` the canvas's `lazy()` above already triggers (a\n // module-cache hit, not a second bundle) — only needed while the editor is\n // open, same as the canvas itself. Defaults to \"nothing resolved yet\", which\n // fails `actionParamsByKey` closed (invalid) until it lands.\n const [flowHelpers, setFlowHelpers] = useState<{\n internalNodes: InternalNodeDef[];\n isInternalApp: (app: string) => boolean;\n internalNodeParams: (app: string, action: string) => ActionParamLike[];\n // \"Call from code\" trigger preview (T2.2.1) — `TRIGGER_APP`/`asFieldDefs`\n // resolve from the SAME import, no second dynamic import.\n isManualTrigger: (app: string) => boolean;\n // Any entry trigger (manual, webhook, schedule, app trigger) — the header Run's entry.\n isEntryTrigger: (uses: { app: string; trigger?: true }) => boolean;\n asFieldDefs: (fields: unknown) => TriggerPreviewFieldDef[];\n // Loop problems (T2.3.2) — pure detector from the SAME import; never a static value import.\n findLoopProblems: (wf: unknown) => StepProblems;\n // Parallel state-write problems (state tree) — same import, same rule.\n findStateWriteProblems: (wf: unknown) => StepProblems;\n } | null>(null);\n useEffect(() => {\n let canceled = false;\n import(\"@w6w/ui/flow\").then((m) => {\n if (canceled) return;\n setFlowHelpers({\n internalNodes: m.INTERNAL_NODES,\n isInternalApp: m.isInternalApp,\n internalNodeParams: m.internalNodeParams,\n isManualTrigger: (app) => app === m.TRIGGER_APP,\n isEntryTrigger: m.isTriggerStep,\n asFieldDefs: m.asFieldDefs,\n findLoopProblems: m.findLoopProblems as (wf: unknown) => StepProblems,\n findStateWriteProblems: m.findStateWriteProblems as (wf: unknown) => StepProblems,\n });\n });\n return () => {\n canceled = true;\n };\n }, []);\n\n // \"Call from code\" trigger preview (T2.2.1, HITL-2/HITL-4 pinned): the\n // modal's per-trigger field picker, derived from the SAME `steps` above —\n // no new fetch, no new query key.\n const triggerPreviewList = useMemo<TriggerPreview[] | undefined>(() => {\n if (!flowHelpers) return undefined;\n return triggerPreviews(\n { steps },\n {\n isManualTrigger: flowHelpers.isManualTrigger,\n asFieldDefs: flowHelpers.asFieldDefs,\n },\n );\n }, [flowHelpers, steps]);\n\n // Unique third-party (non-internal) app ids across the graph, batch-fetched\n // once each — mirrors the per-step fetch WorkflowFlowEditor already does\n // (WorkflowFlowEditor.tsx:~1432), hoisted to page level and de-duplicated.\n const thirdPartyAppIds = useMemo(() => {\n if (!flowHelpers) return [];\n const ids = new Set<string>();\n for (const s of steps) {\n const { app, action } = s.uses ?? {};\n if (app && action && !flowHelpers.isInternalApp(app)) ids.add(app);\n }\n return [...ids];\n }, [flowHelpers, steps]);\n // Registered apps, so the visual editor can render each action node with its\n // owning app's icon, display name, and version — bounded to the ids this\n // graph actually references (src/apps provider, T3.1.2).\n const { byId: fetchedAppsById } = useEditorApps(thirdPartyAppIds);\n const appsList = useMemo(() => [...fetchedAppsById.values()], [fetchedAppsById]);\n const appActionsQueries = useQueries({\n queries: thirdPartyAppIds.map((appId) => ({\n queryKey: appActionsKey(appId),\n queryFn: () => api.getAppActions(appId),\n })),\n });\n\n // Declared params for every step's target, internal (sync) or third-party\n // (fetched above) — keyed `${app}::${action}`, one entry per unique target.\n const actionParamsByKey = useMemo(() => {\n const out: Record<string, ActionParamLike[]> = {};\n if (!flowHelpers) return out;\n for (const s of steps) {\n const { app, action } = s.uses ?? {};\n if (!app || !action) continue;\n const key = `${app}::${action}`;\n if (key in out) continue;\n if (flowHelpers.isInternalApp(app)) {\n out[key] = flowHelpers.internalNodeParams(app, action);\n } else {\n const idx = thirdPartyAppIds.indexOf(app);\n const fetched = idx >= 0 ? appActionsQueries[idx]?.data : undefined;\n out[key] = fetched?.find((a) => a.key === action)?.params ?? [];\n }\n }\n return out;\n }, [flowHelpers, steps, thirdPartyAppIds, appActionsQueries]);\n\n const appsById = useMemo(() => {\n const out: Record<string, unknown> = {};\n for (const [id, a] of fetchedAppsById) out[id] = a;\n return out;\n }, [fetchedAppsById]);\n\n // Only a step whose app is BOTH a real fetched app AND opts into\n // testRequired needs a `listStepTests` fetch — an internal/trigger/control\n // step's app is never a key in `appsById`, so it is never gated.\n const testGatedSteps = useMemo(\n () =>\n steps.filter((s) => {\n const app = s.uses?.app;\n return !!app && app in appsById && isTestRequired(appsById[app]);\n }),\n [steps, appsById],\n );\n const stepTestsQueries = useQueries({\n queries: testGatedSteps.map((s) => ({\n queryKey: stepTestsKey(workflowId, s.id),\n queryFn: () => listStepTests(apiClient, workflowId, s.id),\n enabled: !!workflowId,\n })),\n });\n const testStatus = useMemo(() => {\n const out: Record<string, boolean> = {};\n testGatedSteps.forEach((s, i) => {\n out[s.id] = !!stepTestsQueries[i]?.data?.some((t) => t.lastRunStatus === \"succeeded\");\n });\n return out;\n }, [testGatedSteps, stepTestsQueries]);\n\n // T3.1.1: the Publish button's own published-state, gated the same shape\n // as `stepTestsQueries` above (`!!workflowId`) — never on mount\n // alone. Shares its cache entry with the Settings rail's own History\n // section (same `[\"versions\", \"workflow\", id]` key), so either surface's\n // Publish click refreshes both without a reload.\n const versionsQuery = useVersionsQuery(\"workflow\", workflowId, !!workflowId);\n const publishMut = usePublishMutation(\"workflow\");\n const publishedVersion = versionsQuery.data?.currentPublishedVersion ?? null;\n const publishedQuery = useVersionQuery(\"workflow\", workflowId, publishedVersion, !!workflowId);\n const matchesPublished =\n publishedQuery.data !== undefined &&\n parsed !== null &&\n sameWorkflowDefinition(parsed, publishedQuery.data.definition);\n const definitionStatus =\n versionsQuery.data === undefined\n ? undefined\n : publishedVersion === null\n ? \"unpublished\"\n : publishedQuery.data === undefined || draft.loading\n ? undefined\n : matchesPublished\n ? \"published\"\n : \"draft\";\n const [restoring, setRestoring] = useState(false);\n const revertMut = useRevertMutation(\"workflow\");\n\n async function restoreVersion(versionNumber: number) {\n setRestoring(true);\n setError(null);\n try {\n await draft.discardThen(() => revertMut.mutateAsync({ id: workflowId, versionNumber }));\n setCanvasRevision((r) => r + 1);\n setActiveRunId(null);\n } finally {\n setRestoring(false);\n }\n }\n\n // R5: steps bound to a connection id the account no longer has. Connections per third-party\n // app share the `connectionsForAppKey` cache entry; only a settled, successful list can\n // convict a binding (loading / error never paint a false problem).\n const qc = useQueryClient();\n // A finished run books each step that succeeded as its passing saved test (server\n // `step-passes.ts`), so re-read this workflow's step tests once per run as it turns terminal —\n // the publish gate's `testStatus` reads them and nothing else refetches them. Not cleaned up on\n // purpose: the latch stops a re-schedule, so a cleared later read would be lost for good.\n const stepPassesReadFor = useRef<string | null>(null);\n useEffect(() => {\n if (!workflowId || !activeRunId || stepPassesReadFor.current === activeRunId) return;\n if (!stepPassRefreshDue(runStatus, runQuery.data?.workflowId, workflowId)) return;\n stepPassesReadFor.current = activeRunId;\n for (const ms of STEP_PASS_REFRESH_DELAYS_MS) {\n setTimeout(\n () => void qc.invalidateQueries({ queryKey: workflowStepTestsKey(workflowId) }),\n ms,\n );\n }\n }, [workflowId, activeRunId, runStatus, runQuery.data?.workflowId, qc]);\n const connQueries = useQueries({\n queries: thirdPartyAppIds.map((appId) => ({\n queryKey: connectionsForAppKey(appId),\n queryFn: () => listConnectionsForApp(apiClient, appId),\n })),\n });\n const connByApp = useMemo(() => {\n const m = new Map<string, AppConnections>();\n thirdPartyAppIds.forEach((appId, i) => {\n const q = connQueries[i];\n if (!q) return;\n if (q.isError) m.set(appId, { state: \"error\" });\n else if (q.isSuccess && !q.isFetching)\n m.set(appId, { state: \"ready\", ids: new Set((q.data ?? []).map((c) => c.id)) });\n else m.set(appId, { state: \"loading\" });\n });\n return m;\n }, [thirdPartyAppIds, connQueries]);\n const bindingProblems = useMemo(\n () => findBindingProblems(steps, (app) => connByApp.get(app), parsed?.connections),\n [steps, connByApp, parsed?.connections],\n );\n // Setup-incomplete (non-blocking, derived from the saved workflow). A list that is loading or\n // errored is not ready, so its category is never flagged.\n const varsQ = useVarsQuery(project ?? undefined, project !== null);\n const secretsQ = useSecretsQuery();\n const constantsQ = useConstantsQuery();\n const storesQ = useDataStoresQuery(project ?? undefined);\n const setupResult = useMemo(() => {\n if (!parsed) return {};\n const list = (q: { isSuccess: boolean; data?: { name: string }[] }) => ({\n names: (q.data ?? []).map((x) => x.name),\n ready: q.isSuccess,\n });\n return findSetupIncomplete({\n workflow: parsed,\n lists: {\n vars: list(varsQ),\n secrets: list(secretsQ),\n constants: list(constantsQ),\n stores: list(storesQ),\n },\n });\n }, [parsed, varsQ, secretsQ, constantsQ, storesQ]);\n const setupProblems = useMemo(() => {\n const out: StepProblems = {};\n for (const [id, items] of Object.entries(setupResult))\n out[id] = [{ code: \"setup_incomplete\", items }];\n return out;\n }, [setupResult]);\n // Connection problems first, then loop problems, then state problems (never fed to the\n // disabled banner: that stays `bindingProblems`-only). Until `flowHelpers` lands this is\n // connection-only.\n const stepProblems = useMemo(\n () =>\n mergeStepProblems(\n bindingProblems,\n flowHelpers?.findLoopProblems(parsed),\n parsed ? flowHelpers?.findStateWriteProblems(parsed) : undefined,\n setupProblems,\n ),\n [bindingProblems, flowHelpers, parsed, setupProblems],\n );\n // A connection created through the step modal never touched this cache: refetch once per\n // (app, id) pair when the bound id is absent from a ready list. The latch stops any loop.\n const refetchedPairs = useRef(new Set<string>());\n useEffect(() => {\n for (const p of bindingProblems) {\n const pair = `${p.app}|${p.connection}`;\n if (refetchedPairs.current.has(pair)) continue;\n refetchedPairs.current.add(pair);\n qc.invalidateQueries({ queryKey: connectionsForAppKey(p.app) });\n }\n }, [bindingProblems, qc]);\n const hadProblemsRef = useRef({ id: workflowId, had: false });\n if (hadProblemsRef.current.id !== workflowId)\n hadProblemsRef.current = { id: workflowId, had: false };\n if (bindingProblems.length > 0) hadProblemsRef.current.had = true;\n const setEnabledMut = useSetEnabledMutation(\"workflow\");\n const bannerState = disabledBannerState({\n enabled: versionsQuery.data?.enabled,\n problemCount: bindingProblems.length,\n dirty: draft.dirty,\n hadProblems: hadProblemsRef.current.had,\n });\n\n const validityCtx = useMemo<ValidityContext>(\n () => ({\n actionParamsByKey,\n appsById,\n testStatus,\n requiredParamsFilled,\n isTestRequired,\n }),\n [actionParamsByKey, appsById, testStatus],\n );\n // Every reason Publish is disabled, so the button never greys out silently: the tooltip\n // carries the whole reason and the Why dialog makes it available without hovering. Fails closed\n // until the node catalog (`flowHelpers`) lands: before it, internal steps' params are unknown\n // and would read as \"all required params filled\".\n const publishBlockers = useMemo(\n () =>\n parsed !== null && flowHelpers !== null\n ? publishProblems(parsed as unknown as WorkflowLike, validityCtx)\n : [],\n [parsed, flowHelpers, validityCtx],\n );\n const [publishBusy, setPublishBusy] = useState(false);\n const publishInFlight = useRef(false);\n const publishValidationReason = publishDisabledReason({\n projectMissing: project === null,\n loading: !canSave,\n saveBlockedReason:\n draft.saveBlockedReason ??\n (canSave && parsed === null ? \"the workflow JSON does not parse.\" : null),\n catalogLoading: parsed !== null && flowHelpers === null,\n problems: publishBlockers,\n publishing: publishBusy || publishMut.isPending,\n });\n const publishBlockReason =\n publishValidationReason ??\n (versionsQuery.isPending || (publishedVersion !== null && publishedQuery.isPending)\n ? \"Checking the published version…\"\n : versionsQuery.isError || (publishedVersion !== null && publishedQuery.isError)\n ? \"Can't check the published version. Reload to try again.\"\n : matchesPublished\n ? \"Already published. Make a change before publishing again.\"\n : null);\n async function publishDraft() {\n if (!workflowId || publishBlockReason !== null || publishInFlight.current) return;\n publishInFlight.current = true;\n setPublishBusy(true);\n setError(null);\n try {\n await runAfterFlush(() => publishMut.mutateAsync(workflowId));\n } finally {\n publishInFlight.current = false;\n setPublishBusy(false);\n }\n }\n\n publishReasonRef.current = (def) =>\n def !== null && typeof def === \"object\"\n ? invalidReason(def as unknown as WorkflowLike, validityCtx)\n : null;\n autoSaveRef.current = settings.autoSave;\n\n // Stable per loaded definition, so the dialog re-checks only on its own edits.\n const prepareApply = useCallback(\n (text: string) => prepareWorkflowJsonApply(text, parsedRef.current),\n [],\n );\n\n /** Patch top-level workflow fields, keeping the JSON text as source of truth. */\n function patchMeta(patch: Partial<Parsed>) {\n if (!parsed) return;\n const next: Parsed = { ...parsed, ...patch };\n draft.setJson(JSON.stringify(next, null, 2));\n }\n\n /** Patch top-level fields and persist immediately (for publish/tags edits). */\n function saveMeta(patch: Partial<Parsed>) {\n if (!parsed) return;\n const next: Parsed = { ...parsed, ...patch };\n setError(null);\n void draft.commit(JSON.stringify(next, null, 2));\n }\n\n // The rail's `onPolicyChange` must be referentially stable (see the `useWorkspace` call\n // below) and therefore cannot close over `parsed`/`draft` directly: it reads the live\n // definition and the draft's `commit` through refs.\n const parsedRef = useRef(parsed);\n parsedRef.current = parsed;\n const commitRef = useRef(draft.commit);\n commitRef.current = draft.commit;\n const saveNowRef = useRef(draft.saveNow);\n saveNowRef.current = draft.saveNow;\n\n // Cmd/Ctrl+S saves while the visual editor is open (mirrors the project\n // switcher's keydown effect in components/Layout.tsx: one guarded document\n // listener, symmetric cleanup).\n useEffect(() => {\n const onKey = (e: KeyboardEvent) => {\n if (e.altKey || !(e.metaKey || e.ctrlKey) || e.key.toLowerCase() !== \"s\") return;\n // Suppress the browser's Save Page dialog on every match, including the\n // paths below that decline to save.\n e.preventDefault();\n // The expression editor holds uncommitted parts in its own local state\n // until its Save button, so saving from under it would persist a workflow\n // without the expression the user is looking at.\n if (document.querySelector(\".w6w-exprmodal\")) return;\n if (!canSave) return;\n saveNowRef.current();\n };\n document.addEventListener(\"keydown\", onKey);\n return () => {\n document.removeEventListener(\"keydown\", onKey);\n };\n }, [canSave]);\n\n // T2.1.2: publishes into the right rail's Code/Aliases tools — called on\n // EVERY render, into the `WorkspaceProvider` the outer `WorkflowEditor` mounts.\n //\n // The `policy`/`onPolicyChange` pair is the right rail's Error handling tool\n // (core Workflow RFC — *Amendment — 2026-08-21: the run-level error\n // handler*). The rail does NOT save a workflow itself: this page owns the\n // definition buffer and the draft saves it, so a second writer over the wire\n // would race the canvas and one side's edit would vanish. Handing the rail a\n // writer instead makes its Save fold into the very same JSON text.\n const wfPolicy = useMemo<CallablePolicy>(\n () => (parsed ? policyFromDefinition(parsed) : {}),\n [parsed],\n );\n // Referentially STABLE, as `workspace.tsx` requires: `useWorkspace` keys its\n // publish effect on `JSON.stringify(resource)`, which drops functions, so a\n // callback rebuilt per render would be stored once and then go stale. It\n // reads the current definition through `parsedRef` — always the live value,\n // never a captured one. Persists immediately, exactly like `saveMeta`'s\n // publish/tags edits.\n const onPolicyChange = useCallback((policy: CallablePolicy) => {\n const current = parsedRef.current;\n if (!current) return;\n const next = definitionWithPolicy(current, policy);\n setError(null);\n void commitRef.current(JSON.stringify(next, null, 2));\n }, []);\n\n // The rail State tool opens the starting state editor; stable for the same reason.\n const onOpenStartingState = useCallback(() => setShowStartingState(true), []);\n // The State panel's run link and the header History both open a run the same way; read through\n // a ref so the published callback stays stable.\n const openRunRef = useRef<(runId: string) => void>(() => {});\n openRunRef.current = (runId) => {\n setActiveRunId(runId);\n onNavigate({ type: \"run\", id: workflowId, runId });\n };\n const onOpenRun = useCallback((runId: string) => openRunRef.current(runId), []);\n\n const restoreVersionRef = useRef(restoreVersion);\n restoreVersionRef.current = restoreVersion;\n const onRestoreVersion = useCallback((n: number) => restoreVersionRef.current(n), []);\n const publishDraftRef = useRef(publishDraft);\n publishDraftRef.current = publishDraft;\n const onPublish = useCallback(() => publishDraftRef.current(), []);\n const authoringRef = useRef({ saveMeta, patchMeta });\n authoringRef.current = { saveMeta, patchMeta };\n const onAuthoringSettingChange = useCallback(\n (key: \"autoSave\" | \"savePosition\", value: boolean) => {\n authoringRef.current.saveMeta({\n settings: writeSetting(parsedRef.current?.settings, key, value),\n });\n },\n [],\n );\n const onVariablesChange = useCallback((next: Parameters<typeof variablesForSave>[0]) => {\n authoringRef.current.patchMeta({ variables: variablesForSave(next) });\n }, []);\n const [connectionResources, setConnectionResources] =\n useState<WorkflowConnectionResources | null>(null);\n const connectionResourcesRef = useRef(connectionResources);\n connectionResourcesRef.current = connectionResources;\n // Workspace publication compares data, so keep its callback valid across canvas remounts.\n const editConnectionResource = useCallback(\n (edit: Parameters<WorkflowConnectionResources[\"edit\"]>[0]) => {\n connectionResourcesRef.current?.edit(edit);\n },\n [],\n );\n const onOpenHistory = useCallback(() => setShowHistory(true), []);\n useWorkspace({\n kind: \"workflow\",\n id: workflowId,\n connectionResources:\n connectionResources?.workflowId === workflowId\n ? { ...connectionResources, edit: editConnectionResource }\n : undefined,\n label: displayName,\n key: parsed?.key ?? undefined,\n triggers: triggerPreviewList,\n onRestoreVersion,\n definitionStatus,\n onPublish,\n publishDisabled: publishBlockReason !== null,\n policy: wfPolicy,\n onPolicyChange,\n hasStartingState: startingState !== undefined && Object.keys(startingState).length > 0,\n startingState,\n onOpenStartingState,\n onOpenRun,\n authoringSettings: { autoSave: settings.autoSave, savePosition: settings.savePosition },\n onAuthoringSettingChange,\n variables,\n onVariablesChange,\n onOpenHistory,\n });\n\n return (\n <div className=\"wf-fullbleed\" style={{ height: \"100%\", minWidth: 0, flex: 1 }}>\n {/* T3.1.1: the header itself is `ExecutionProfileHeader` — the SAME\n component a Function/Endpoint editor mounts through\n `CallableEditorChrome`. Everything below is host business: the\n back control (A8, updated by T4.1.1: the editor is its own route\n now, so \"back\" navigates to the LISTING — the sibling params it was\n opened with are kept, since they are the author's), the controlled\n name field that persists on blur, and the action row. */}\n {slots?.header ?? (\n <ExecutionProfileHeader\n onBack={() => onNavigate({ type: \"list\" })}\n backLabel={slots?.backLabel === null ? null : (slots?.backLabel ?? \"← Workflows\")}\n title={{\n editable: true,\n value: displayName,\n placeholder: TITLE_PLACEHOLDER,\n maxLength: 80,\n ariaLabel: \"Workflow name\",\n onChange: (next) => patchMeta({ displayName: next }),\n onBlur: () => {\n if (canSave) draft.saveNow();\n },\n }}\n titleAdornment={\n definitionStatus && (\n <span\n className={`badge wf-definition-status ${definitionStatus}`}\n data-testid=\"wf-definition-status\"\n aria-live=\"polite\"\n title={\n definitionStatus === \"published\"\n ? \"This workflow matches the published version. Edits create a separate draft.\"\n : definitionStatus === \"draft\"\n ? \"You are editing a draft. The published version stays unchanged until you publish.\"\n : \"You are editing a draft. This workflow has not been published.\"\n }\n >\n {definitionStatus === \"published\" ? \"Live\" : \"Draft\"}\n </span>\n )\n }\n actions={\n <>\n <IconButton\n icon=\"play\"\n label={runButtonLabel(runStatus, runPollFailed)}\n data-testid=\"wf-run-start\"\n onClick={onRunClick}\n disabled={!workflowId || runInFlight || runStarting || startRunMut.isPending}\n />\n {runInFlight && (\n <IconButton\n icon=\"stop\"\n label=\"Stop this run\"\n data-testid=\"wf-run-stop\"\n onClick={onStopClick}\n disabled={cancelRunMut.isPending}\n />\n )}\n <PublishTooltip\n disabled={publishBlockReason !== null}\n message={\n publishBlockReason ??\n (publishedVersion !== null\n ? \"Republish this draft as a new live version\"\n : \"Publish this draft as a new live version\")\n }\n >\n {(descriptionId) => (\n <>\n <button\n type=\"button\"\n className=\"btn ghost wf-publish\"\n data-testid=\"wf-publish\"\n onClick={() => void publishDraft()}\n disabled={publishBlockReason !== null}\n aria-describedby={descriptionId}\n >\n {publishBusy || publishMut.isPending\n ? publishedVersion !== null\n ? \"Republishing…\"\n : \"Publishing…\"\n : publishedVersion !== null\n ? definitionStatus === \"draft\"\n ? \"Republish\"\n : \"Published\"\n : \"Publish\"}\n </button>\n </>\n )}\n </PublishTooltip>\n <JsonToggleButton onClick={() => setShowJson(true)} />\n {/* T2.1.2: \"Call from code\" moved to the right rail's Code tool —\n see the `useWorkspace` call above (this closes the prior\n project's HITL-1: the flow editor now publishes, since the\n gate is the editor's own mount, not the route wrapper that could\n never see this component's route param). */}\n {slots?.headerActions}\n </>\n }\n />\n )}\n <SetupIncompleteBanner problems={setupResult} />\n {bannerState.show && (\n <BindingBanner\n kind=\"workflow\"\n problemCount={bannerState.problemCount}\n canEnable={bannerState.canEnable}\n pending={setEnabledMut.isPending}\n onEnable={() => setEnabledMut.mutate({ id: workflowId, enabled: true })}\n />\n )}\n <div className=\"wf-fullbleed-canvas\">\n <div className=\"wf-run-area\">\n <div className=\"wf-run-canvas\">\n <Suspense fallback={<p className=\"muted\">Loading visual editor…</p>}>\n {flowUsable && parsed ? (\n <WorkflowFlowEditor\n onConnectionResourcesChange={setConnectionResources}\n key={canvasRevision}\n // The parsed cast is safe: onChange only receives shapes we produced.\n value={parsed as unknown as Parameters<typeof WorkflowFlowEditor>[0][\"value\"]}\n onChange={(next, meta) => {\n draft.setJson(JSON.stringify(next, null, 2));\n // T1.1.1 A2.1: an edit to the graph — a canvas edit or a\n // step-config commit from `StepEditModal`, both of which\n // arrive here — means the run this canvas was showing is\n // no longer the thing the author is looking at.\n // adhoc/run-paint: a pan/zoom (`viewportOnly`) is no edit —\n // the run paint stays until an edit or the next run.\n if (!meta?.viewportOnly) setActiveRunId(null);\n }}\n apps={appsList}\n project={project ?? undefined}\n height=\"100%\"\n // A4: locked while the run this canvas is showing is still\n // in flight, unlocked again on every terminal status AND\n // when the poll itself gives up or errors.\n readOnly={runInFlight}\n // adhoc/run-paint: no `fitViewKey` — running (or dismissing\n // the run log) never moves the author's camera.\n stepProblems={stepProblems}\n // A3: each intermediate RunState reaches the canvas as it\n // arrives — the cast crosses the same opaque-`steps`\n // boundary `getRunState`'s own callers already cross (the\n // SDK's console `RunState.steps` is `Record<string,\n // unknown>` on purpose; the server's real per-step shape\n // structurally satisfies `ui`'s narrower `RunState`).\n runState={\n runQuery.data as unknown as Parameters<typeof WorkflowFlowEditor>[0][\"runState\"]\n }\n // T1.1.1 A3: a step test starts → the run this canvas was\n // showing is no longer the thing under test, so drop it on\n // the click rather than waiting for the test's result.\n onTestRun={() => setActiveRunId(null)}\n // adhoc/run-pause: ▶ runs on from the node as a real run, shown in the\n // run log beside the canvas like a header Run.\n onRunFromNode={onRunFromNode}\n />\n ) : json === \"\" ? (\n <p className=\"muted\">Loading…</p>\n ) : (\n <p className=\"muted\">Fix the JSON to render the visual editor.</p>\n )}\n </Suspense>\n </div>\n {activeRunId && (\n <div className=\"wf-run-log\" data-testid=\"wf-run-log\">\n <ExecutionLogPanel\n steps={runLogSteps}\n runError={runLogErrors.runError}\n stepErrors={runLogErrors.stepErrors}\n // T1.1.1 A4: the one explicit \"I'm done looking at this run\"\n // control — same lever as Stop, so it must work in the empty\n // branch too (the panel renders its head there as well).\n onDismiss={() => setActiveRunId(null)}\n />\n </div>\n )}\n </div>\n </div>\n {project === null && !projectPending && (\n <div role=\"alert\" className=\"error\" data-testid=\"wf-project-required\">\n No project selected — pass a <code>project</code> prop (or set the provider's project) to\n edit and save this workflow.\n </div>\n )}\n <div className=\"wf-fullbleed-foot\">\n <div className=\"row\" style={{ flexWrap: \"wrap\", alignItems: \"center\" }}>\n {/* Auto-save does not remove this button (it is the escape hatch when\n `autoSave` is off, and the only legible signal of save state when it\n is on): it flushes the pending window now, and greys out once the\n canvas matches the server. */}\n <button\n type=\"button\"\n className=\"btn\"\n disabled={project === null || !canSave || !dirty}\n onClick={draft.saveNow}\n >\n {draft.saving ? \"Saving…\" : \"Save\"}\n </button>\n {saved && <span className=\"ok\">Saved.</span>}\n </div>\n {bannerError && <div className=\"error\">{bannerError}</div>}\n {keyGuardReason && (\n <div className=\"error\" data-testid=\"wf-key-guard\">\n {keyGuardReason}\n </div>\n )}\n </div>\n\n {restoring && (\n <Modal title=\"Restoring version…\" onClose={() => {}}>\n <div className=\"modal-body\">Replacing the draft…</div>\n </Modal>\n )}\n\n <JsonToggle\n open={showJson}\n onClose={() => setShowJson(false)}\n title={`JSON — ${(parsed?.displayName as string) || \"workflow\"}`}\n mode=\"apply\"\n value={json}\n prepareApply={prepareApply}\n onApply={(next) => {\n // The buffer takes the text (the workflow turns dirty; Save or auto-save stores it as\n // for any edit) and the canvas remounts on it.\n draft.setJson(next);\n setCanvasRevision((r) => r + 1);\n // T1.1.1 A2.2 (D-2): the raw-JSON surface is an edit surface\n // too, so it clears the shown run the same way the canvas does.\n setActiveRunId(null);\n }}\n editorLabel=\"Workflow definition JSON\"\n />\n\n {draft.stale && !staleDismissed && (\n <Modal title=\"This workflow changed on the server\" onClose={() => setStaleDismissed(true)}>\n <div className=\"modal-body\">\n <p className=\"muted small\">\n Someone else — another tab, another session — saved this workflow after you opened it.\n Your save was refused rather than applied, so their work is still intact.\n </p>\n <p className=\"muted small\">\n <strong>Reload from server</strong> replaces what is on this canvas with the saved\n copy; anything you changed here and have not saved is lost.{\" \"}\n <strong>Keep editing</strong> leaves your version exactly as it is — but every save\n will be refused the same way until you reload, so copy out anything you need first.\n </p>\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={() => setStaleDismissed(true)}>\n Keep editing\n </button>\n <button type=\"button\" className=\"btn\" disabled={reloading} onClick={reloadFromServer}>\n {reloading ? \"Reloading…\" : \"Reload from server\"}\n </button>\n </div>\n </Modal>\n )}\n\n {showHistory && (\n <HistoryModal\n kind=\"workflow\"\n id={workflowId}\n onClose={() => setShowHistory(false)}\n onOpenRun={onOpenRun}\n />\n )}\n\n {showStartingState && (\n <StartingStateModal\n initialState={startingState}\n onChange={(next) => patchMeta({ initialState: next })}\n onClose={() => setShowStartingState(false)}\n />\n )}\n </div>\n );\n}\n\nfunction StepTestApiProvider({\n children,\n callableHref,\n}: { children: ReactNode; callableHref?: WorkflowEditorProps[\"callableHref\"] }) {\n const api = useW6WApi();\n const qc = useQueryClient();\n const theme = useContext(EmbedThemeContext);\n const wrappedApi = useMemo(() => {\n const saveStepTest = (...args: Parameters<typeof api.saveStepTest>) =>\n api.saveStepTest(...args).finally(() => {\n void qc.invalidateQueries({ queryKey: stepTestsKey(args[0], args[1]) });\n });\n const recordStepTestRun = (...args: Parameters<typeof api.recordStepTestRun>) =>\n api.recordStepTestRun(...args).finally(() => {\n void qc.invalidateQueries({ queryKey: stepTestsKey(args[0], args[1]) });\n });\n return {\n ...api,\n saveStepTest,\n recordStepTestRun,\n callableHref: callableHref ?? api.callableHref,\n };\n }, [api, qc, callableHref]);\n return (\n <W6WUIProvider api={wrappedApi} theme={theme}>\n {children}\n </W6WUIProvider>\n );\n}\n\nconst NOOP = (): void => {};\n\n/**\n * The managed workflow editor. The outermost element is `.w6w-embed-root` (pinned for the embed\n * stylesheet); everything the editor renders — header, canvas, modals, rail — stays a descendant of\n * it, and nothing goes through a portal. It fills its host container (`height: 100%`), so the host\n * decides how tall the editor is.\n *\n * `useEditorProject(props.project)` is the ONLY project source: it feeds the draft, the expression\n * scope, the rail environment and the canvas. `null` (no project) refuses — see `EditorBody`.\n */\nexport function WorkflowEditor(props: WorkflowEditorProps): ReactNode {\n const { workflowId, initialRunId, onNavigate = NOOP, slots } = props;\n const project = useEditorProject(props.project);\n // Every load starts here when the host asks for the default project: saving still refuses until\n // it resolves, but the \"no project\" notice would only flash on the way, so it waits.\n const providerStatus = useEmbedProject().status;\n const projectPending = props.project === undefined && providerStatus === \"resolving\";\n const railNavigate = useCallback(\n (to: RailNavigation) => {\n if (to.type === \"list\") onNavigate({ type: \"list\" });\n else if (to.kind === \"workflow\") onNavigate({ type: \"workflow\", id: to.id });\n },\n [onNavigate],\n );\n return (\n <div\n className=\"w6w-embed-root\"\n style={{ display: \"flex\", width: \"100%\", height: \"100%\", minHeight: 0 }}\n >\n <EditorShell\n project={project}\n onNavigate={railNavigate}\n rail={props.rail}\n storageKey={project === null ? null : `w6w.rail.embed.${project}`}\n >\n <StepTestApiProvider callableHref={props.callableHref}>\n <EditorBody\n workflowId={workflowId}\n project={project}\n projectPending={projectPending}\n initialRunId={initialRunId}\n onNavigate={onNavigate}\n slots={slots}\n />\n </StepTestApiProvider>\n </EditorShell>\n </div>\n );\n}\n"],"names":["EditableTitle","title","value","placeholder","maxLength","ariaLabel","onChange","onBlur","jsx","e","ExecutionProfileHeader","onBack","backLabel","titleAdornment","actions","jsxs","historyOpenRun","kind","onOpenRun","onClose","execution","HistoryModal","props","id","filters","setFilters","useState","EMPTY_HISTORY_FILTERS","onOpenInEditor","Modal","IconButton","HistoryView","JsonToggleButton","JsonToggle","ApplyJsonDialog","DisconnectedJsonDialog","JsonEditorFill","JsonEditor","prepareApply","onApply","editorLabel","text","setText","applied","setApplied","restored","setRestored","confirming","setConfirming","check","useMemo","dirty","requestClose","apply","t","Fragment","guard","onSave","saving","error","guardReason","sameWorkflowDefinition","a","b","canonical","key","item","definition","_status","rest","BindingBanner","problemCount","canEnable","onEnable","pending","createElement","EditorShell","project","onNavigate","rail","storageKey","tools","editorRailTools","children","enclosed","useHasWorkspace","body","RailEnvProvider","ProjectExpressionScope","RightRail","WorkspaceProvider","PublishTooltip","message","disabled","useId","open","setOpen","event","SetupIncompleteBanner","problems","nodeLabel","entries","items","n","STARTING_DATA_PROBLEM_TEXT","StartingStateModal","options","useExpressionOptions","ExpressionEditorModal","result","startingDataForSave","issue","validateInitialState","next","ID_RE","TITLE_PLACEHOLDER","PROTECTED_WORKFLOW_FIELDS","jsonErrorOffset","i","ws","fail","lit","word","ch","str","k","NUM","num","close","at","jsonSyntaxError","before","line","column","isObj","v","workflowShapeError","def","nodes","ids","p","end","prepareWorkflowJsonApply","loaded","front","f","had","has","_drop","shape","mergeStepProblems","bindingProblems","loopProblems","stateProblems","setupProblems","out","conn","source","list","WorkflowFlowEditor","lazy","m","EditorBody","workflowId","projectPending","initialRunId","slots","apiClient","useEmbedClient","api","useW6WApi","setError","showJson","setShowJson","canvasRevision","setCanvasRevision","showHistory","setShowHistory","showStartingState","setShowStartingState","reloading","setReloading","loadedKey","setLoadedKey","autoSaveRef","useRef","publishReasonRef","saveGuard","useCallback","d","workflowKeyEditAllowed","draft","useWorkflowDraft","json","parsed","canSave","useEffect","staleDismissed","setStaleDismissed","saved","setSaved","wasSaving","activeRunId","setActiveRunId","startRunMut","useStartRunMutation","runFromNodeMut","useRunFromNodeMutation","cancelRunMut","useCancelRunMutation","runQuery","useLiveRunQuery","runStatus","_a","runPollFailed","runInFlight","isRunInFlight","stateWritesQuery","useRunStateWritesQuery","runLogSteps","mapRunStateToLogSteps","runNodeMap","_b","runLogErrors","runLevelErrors","runStartingRef","runStarting","setRunStarting","runAfterFlush","action","r","ApiError","onRunClick","entry","flowHelpers","headerRunEntry","steps","triggerPreviewList","testInputSavesSettled","input","resolveHeaderRunInput","stepId","listStepTests","listTestInputs","res","onRunFromNode","nodeId","req","onStopClick","code","classifyCancelError","reloadFromServer","draftFailure","bannerError","flowUsable","displayName","settings","readSettings","startingState","readStartingData","variables","readVariables","keyEdit","keyGuardReason","workflowNodes","setFlowHelpers","canceled","app","triggerPreviews","thirdPartyAppIds","s","fetchedAppsById","useEditorApps","appsList","appActionsQueries","useQueries","appId","appActionsKey","actionParamsByKey","idx","fetched","appsById","testGatedSteps","isTestRequired","stepTestsQueries","stepTestsKey","testStatus","versionsQuery","useVersionsQuery","publishMut","usePublishMutation","publishedVersion","_c","publishedQuery","useVersionQuery","matchesPublished","definitionStatus","restoring","setRestoring","revertMut","useRevertMutation","restoreVersion","versionNumber","qc","useQueryClient","stepPassesReadFor","stepPassRefreshDue","ms","STEP_PASS_REFRESH_DELAYS_MS","workflowStepTestsKey","_d","connQueries","connectionsForAppKey","listConnectionsForApp","connByApp","q","c","findBindingProblems","varsQ","useVarsQuery","secretsQ","useSecretsQuery","constantsQ","useConstantsQuery","storesQ","useDataStoresQuery","setupResult","x","findSetupIncomplete","stepProblems","refetchedPairs","pair","hadProblemsRef","setEnabledMut","useSetEnabledMutation","bannerState","disabledBannerState","_e","validityCtx","requiredParamsFilled","publishBlockers","publishProblems","publishBusy","setPublishBusy","publishInFlight","publishBlockReason","publishDisabledReason","publishDraft","invalidReason","parsedRef","patchMeta","patch","saveMeta","commitRef","saveNowRef","onKey","wfPolicy","policyFromDefinition","onPolicyChange","policy","current","definitionWithPolicy","onOpenStartingState","openRunRef","runId","restoreVersionRef","onRestoreVersion","publishDraftRef","onPublish","authoringRef","onAuthoringSettingChange","writeSetting","onVariablesChange","variablesForSave","connectionResources","setConnectionResources","connectionResourcesRef","editConnectionResource","edit","onOpenHistory","useWorkspace","runButtonLabel","descriptionId","Suspense","meta","ExecutionLogPanel","StepTestApiProvider","callableHref","theme","useContext","EmbedThemeContext","wrappedApi","args","W6WUIProvider","NOOP","WorkflowEditor","useEditorProject","providerStatus","useEmbedProject","railNavigate","to"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAkEA,SAASA,GAAc,EAAE,OAAAC,KAA0C;AACjE,QAAM,EAAE,OAAAC,GAAO,aAAAC,GAAa,WAAAC,GAAW,WAAAC,GAAW,UAAAC,GAAU,QAAAC,MAAWN;AACvE,SACE,gBAAAO;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAU;AAAA,MACV,OAAAN;AAAA,MACA,aAAAC;AAAA,MACA,WAAAC;AAAA,MACA,MAAM,KAAK,IAAI,KAAK,IAAIF,EAAM,QAAQC,EAAY,MAAM,GAAG,EAAE;AAAA,MAC7D,cAAYE;AAAA,MACZ,UAAU,CAACI,MAAMH,EAASG,EAAE,OAAO,KAAK;AAAA,MACxC,QAAAF;AAAA,IAAA;AAAA,EAAA;AAGN;AAiBO,SAASG,GAAuB;AAAA,EACrC,QAAAC;AAAA,EACA,WAAAC;AAAA,EACA,OAAAX;AAAA,EACA,gBAAAY;AAAA,EACA,SAAAC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AC7E;AAAA,IACA,CAAClU,CAAU;AAAA,EAAA;AAEb,SACE,gBAAAtE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAU;AAAA,MACV,OAAO,EAAE,SAAS,QAAQ,OAAO,QAAQ,QAAQ,QAAQ,WAAW,EAAA;AAAA,MAEpE,UAAA,gBAAAA;AAAA,QAACoE;AAAA,QAAA;AAAA,UACC,SAAAC;AAAA,UACA,YAAYkU;AAAA,UACZ,MAAMzX,EAAM;AAAA,UACZ,YAAYuD,MAAY,OAAO,OAAO,kBAAkBA,CAAO;AAAA,UAE/D,UAAA,gBAAArE,EAAC0X,IAAA,EAAoB,cAAc5W,EAAM,cACvC,UAAA,gBAAAd;AAAA,YAAC0J;AAAA,YAAA;AAAA,cACC,YAAAC;AAAA,cACA,SAAAtF;AAAA,cACA,gBAAAuF;AAAA,cACA,cAAAC;AAAA,cACA,YAAAvF;AAAA,cACA,OAAAwF;AAAA,YAAA;AAAA,UAAA,EACF,CACF;AAAA,QAAA;AAAA,MAAA;AAAA,IACF;AAAA,EAAA;AAGN;"}
|
|
1
|
+
{"version":3,"file":"WorkflowEditor-LesBKjb2.js","sources":["../src/chrome/ExecutionProfileHeader.tsx","../src/chrome/history-open-run.ts","../src/chrome/HistoryModal.tsx","../src/chrome/JsonToggle.tsx","../src/lib/workflow-version.ts","../src/editor/BindingBanner.tsx","../src/editor/EditorShell.tsx","../src/editor/PublishTooltip.tsx","../src/editor/SetupIncompleteBanner.tsx","../src/editor/StartingStateModal.tsx","../src/editor/definition.ts","../src/editor/json-apply.ts","../src/editor/step-problems-feed.ts","../src/editor/WorkflowEditor.tsx"],"sourcesContent":["import type { ReactNode } from \"react\";\n\n/**\n * `ExecutionProfileHeader` — the ONE editor header every execution profile's\n * editor mounts (T3.1.1, `building-blocks.md` §Profile building blocks\n * §Mirror).\n *\n * Extracted verbatim from `WorkflowsPage.tsx`'s full-bleed editor head, which\n * is the presentation of record: back control, title, actions. Two hosts use\n * it with two title CONFIGURATIONS, never two headers:\n * - `WorkflowsPage.tsx` — an inline-editable, controlled name input\n * (`editable: true`); back clears the `?edit=` search param; the action row\n * (run / stop / publish / JSON / settings) stays host-owned and arrives as\n * `actions`.\n * - `CallablePage.tsx`'s `CallableEditorChrome` — a Function/Endpoint\n * read-only heading (`editable: false`) with the `incomplete` badge passed\n * as `titleAdornment`, and the host's own JSON toggle then Save button as\n * `actions`.\n *\n * Presentation only: no query, mutation or navigation logic lives here — every\n * callback (`onBack`, `onChange`, `onBlur`) and every node in the action row is\n * the host's, mirroring the `ConnectionHeader.tsx` action-slot precedent.\n *\n * The rendered DOM of the Workflow editor's header is byte-for-byte what it\n * was before the extraction (`wf-fullbleed-head` / `wf-back-btn` /\n * `wf-title-input` / `wf-head-actions`, every `data-testid`, the `aria-label`\n * and the attribute order), which is what `styles.css`'s\n * `.wf-fullbleed-head input.wf-title-input` ancestor specificity and the\n * workflow header screenshot guard both depend on.\n */\n\n/** The editable title variant: the Workflow editor's inline-editable name. */\nexport interface EditableProfileTitle {\n /** The controlled value. */\n value: string;\n /** Called with the new text on every keystroke. */\n onChange: (next: string) => void;\n /** Called when the field loses focus — the Workflow host saves here. */\n onBlur: () => void;\n /** Shown while the value is empty; also the field's minimum sizing basis. */\n placeholder: string;\n /** The `maxLength` the input carries. */\n maxLength: number;\n /** The input's accessible name. */\n ariaLabel: string;\n}\n\n/** The read-only title variant: a Function/Endpoint editor's heading text. */\nexport interface ReadOnlyProfileTitle {\n value: string;\n}\n\n/** Which title the host mounts. The discriminant is `editable`. */\nexport type ExecutionProfileTitle =\n | ({ editable: true } & EditableProfileTitle)\n | ({ editable: false } & ReadOnlyProfileTitle);\n\n/**\n * The editable title field itself. Extracted so the input's own JSX — and the\n * `size` expression `src/lib/__tests__/workflow-title-size.test.ts` extracts\n * and RUNS — lives in one readable place. `size` is capped at the literal 80\n * (the same cap `maxLength` carries on the workflow host), independently of\n * `maxLength`: a name longer than 80 characters can only ever come from the\n * server, so `maxLength` alone would leave a pre-existing long name overflowing\n * its header.\n */\nfunction EditableTitle({ title }: { title: EditableProfileTitle }) {\n const { value, placeholder, maxLength, ariaLabel, onChange, onBlur } = title;\n return (\n <input\n className=\"wf-title-input\"\n value={value}\n placeholder={placeholder}\n maxLength={maxLength}\n size={Math.min(Math.max(value.length, placeholder.length), 80)}\n aria-label={ariaLabel}\n onChange={(e) => onChange(e.target.value)}\n onBlur={onBlur}\n />\n );\n}\n\nexport interface ExecutionProfileHeaderProps {\n /** The back control's click handler — host-owned (the Workflow host clears\n * `?edit=`; `CallableEditorChrome` navigates to the kind's listing). */\n onBack: () => void;\n /** The back control's visible text — host-owned copy (`\"← Workflows\"`,\n * `descriptor.editor.backLabel`). `null`: no back control is rendered. */\n backLabel: string | null;\n /** Editable (Workflow) or read-only (Function/Endpoint) title. */\n title: ExecutionProfileTitle;\n /** Rendered immediately after the title, including an editable workflow name. */\n titleAdornment?: ReactNode;\n /** The host's action row (buttons only; this component owns the wrapper). */\n actions: ReactNode;\n}\n\nexport function ExecutionProfileHeader({\n onBack,\n backLabel,\n title,\n titleAdornment,\n actions,\n}: ExecutionProfileHeaderProps) {\n return (\n <div className=\"wf-fullbleed-head\">\n {backLabel !== null && (\n <button\n type=\"button\"\n className=\"muted wf-back-btn\"\n data-testid=\"wf-editor-back\"\n onClick={onBack}\n >\n {backLabel}\n </button>\n )}\n {title.editable ? (\n <EditableTitle title={title} />\n ) : (\n <h2 className=\"exec-profile-title\">\n {title.value} {titleAdornment}\n </h2>\n )}\n <div className=\"wf-head-actions\" style={{ marginLeft: \"auto\" }}>\n {title.editable && titleAdornment}\n {actions}\n </div>\n </div>\n );\n}\n","import type { CallableKind, ExecutionSummary } from \"../repos/index.ts\";\n\n/**\n * The open-in-editor decision for a History view: only a workflow run has an editor to open, and\n * only when the host supplied `onOpenRun`. The handler closes the modal BEFORE handing the run id\n * to the host (the host's navigation then lands on an unobscured page).\n */\nexport function historyOpenRun(\n kind: CallableKind,\n onOpenRun: ((runId: string) => void) | undefined,\n onClose: () => void,\n): ((execution: ExecutionSummary) => void) | undefined {\n if (kind !== \"workflow\" || onOpenRun === undefined) return undefined;\n return (execution) => {\n onClose();\n onOpenRun(execution.id);\n };\n}\n","/**\n * `HistoryModal` (R-2 / T3.2.1) — the callable's own execution history,\n * opened as a full-page modal OVER the profile instead of away from it: the\n * route and the URL never change, so the editor underneath (unsaved edits,\n * canvas position, selected node) stays exactly as the author left it.\n * Mounted by `HistoryButton` in place of the navigation it used to do.\n *\n * `@w6w/ui`'s `Modal` at `size=\"full\"` (a near-fullscreen work surface,\n * `ui/src/components/Modal.tsx:12`) wraps `HistoryView`, scoped to this one\n * callable (`{ callable: id }`) with `showKind={false}` — a per-callable\n * view already knows its own kind. Filters are LOCAL state, starting empty\n * every time the modal opens, and are never written to the URL (HB10):\n * bookmarking a filtered view only makes sense for the standalone History\n * page, which still owns the URL-backed form.\n *\n * Closeable by ✕ (the `headerRight` button below), Esc (the real `Modal`'s\n * own `cancel` handling) or its backdrop click — all three funnel through\n * the same `onClose`, so the caller's \"focus returns to the History button\"\n * behaviour (`HistoryButton.tsx`) covers every dismissal path.\n *\n * \"Open in visual editor\" only ever applies to a workflow run, and every\n * execution this modal lists already belongs to THIS callable — its scope\n * is `{ callable: id }`, never project-wide — so there is no \"other\n * workflow\" branch to handle here (that one only exists on the project-wide\n * History page, which `HistoryPage.tsx` still owns). Closes the modal and\n * seeds `?run=` on the SAME route; `WorkflowsPage`'s own `[editId, runParam]`\n * effect (T2.4.2 HB7) is what opens the run overlay in place.\n */\nimport { type CallableKind, EMPTY_HISTORY_FILTERS, type HistoryFilters } from \"@w6w/embed/repos\";\nimport { IconButton, Modal } from \"@w6w/ui\";\nimport { useState } from \"react\";\nimport { HistoryView } from \"./HistoryView.tsx\";\nimport { historyOpenRun } from \"./history-open-run.ts\";\n\nexport interface HistoryModalProps {\n kind: CallableKind;\n id: string;\n onClose: () => void;\n /** Open a workflow run in the host's editor; absent ⇒ no open-in-editor affordance. */\n onOpenRun?: (runId: string) => void;\n}\n\nexport function HistoryModal(props: HistoryModalProps) {\n const { kind, id, onClose, onOpenRun } = props;\n const [filters, setFilters] = useState<HistoryFilters>(EMPTY_HISTORY_FILTERS);\n\n const onOpenInEditor = historyOpenRun(kind, onOpenRun, onClose);\n\n return (\n <Modal\n size=\"full\"\n title=\"History\"\n subtitle={id}\n onClose={onClose}\n headerRight={<IconButton icon=\"close\" label=\"Close\" onClick={onClose} />}\n >\n <div className=\"w6w-modal-body\">\n <HistoryView\n scope={{ callable: id }}\n showKind={false}\n filters={filters}\n onFiltersChange={setFilters}\n onOpenInEditor={onOpenInEditor}\n />\n </div>\n </Modal>\n );\n}\n","import { IconButton, JsonEditor } from \"@w6w/ui\";\nimport { useMemo, useState } from \"react\";\nimport { Modal } from \"./Modal.tsx\";\n\n/**\n * `apply`: the dialog edits its own copy of the text and hands it to the host only on Apply (the\n * workflow editor, whose canvas re-reads it). `disconnected`: the host owns the text and saves it.\n */\nexport type JsonToggleMode = \"apply\" | \"disconnected\";\n\n/** What `prepareApply` makes of the dialog's text: the text to apply, or why it can't be. */\nexport type JsonApplyCheck =\n | {\n ok: true;\n /** The text `onApply` receives — the edited text with any protected field put back. */\n text: string;\n /** Top-level fields whose loaded value was restored; listed under the editor. */\n restored: string[];\n }\n | { ok: false; error: string };\n\n/** The header icon button: `IconButton` with the set's `json` glyph — the\n * curly-brace icon, distinct from the `code` `</>` \"Call from code\" icon\n * beside it, so the two stop reading as the same button. The local\n * `JsonIcon` SVG this file used to carry is now `icon=\"json\"` in the shared\n * set. */\nexport function JsonToggleButton(props: { onClick: () => void }) {\n return <IconButton icon=\"json\" onClick={props.onClick} label=\"Edit raw JSON definition\" />;\n}\n\nexport interface JsonToggleProps {\n /** Parent-owned; render nothing when false. */\n open: boolean;\n onClose: () => void;\n /** Modal title. */\n title: string;\n mode: JsonToggleMode;\n /** disconnected: parent-owned text, the component keeps NO copy of it. apply: the text the\n * dialog starts from each time it opens. */\n value: string;\n /** disconnected only: every JsonEditor change. */\n onChange?: (text: string) => void;\n /** apply only: validates the dialog's text on every edit; Apply is enabled only on `ok`. */\n prepareApply?: (text: string) => JsonApplyCheck;\n /** apply only: the checked text, on Apply. */\n onApply?: (text: string) => void;\n /** Evaluated on `value` every render; non-null → shown in\n * <p className=\"muted small\" data-testid=\"json-toggle-reason\">. */\n guard?: (text: string) => string | null;\n /** disconnected only. */\n onSave?: () => void;\n /** disconnected only. */\n saving?: boolean;\n /** disconnected only; rendered as <div className=\"error\"> inside the dialog. */\n error?: string | null;\n /** JsonEditor aria-label. */\n editorLabel: string;\n}\n\n/**\n * The JSON⇄editor toggle's chrome — the header icon button's dialog, extracted from\n * `WorkflowsPage.tsx`'s raw-JSON modal (T2.1.1 D-2) and reused by the Function and Endpoint\n * editors in `mode=\"disconnected\"` (T2.1.2). Wraps `@w6w/ui`'s `JsonEditor` and studio's own\n * `Modal`. The editor fills the dialog and scrolls inside itself (`.modal-json`), so the title,\n * the description and the footer buttons stay in view on a long definition.\n */\nexport function JsonToggle(props: JsonToggleProps): JSX.Element | null {\n if (!props.open) return null;\n // Mounted per opening, so each one starts from the host's current text.\n return props.mode === \"apply\" ? (\n <ApplyJsonDialog {...props} />\n ) : (\n <DisconnectedJsonDialog {...props} />\n );\n}\n\nfunction JsonEditorFill(props: { value: string; onChange: (t: string) => void; label: string }) {\n return (\n <div className=\"json-toggle-editor\">\n <JsonEditor\n value={props.value}\n onChange={props.onChange}\n minHeight=\"120px\"\n aria-label={props.label}\n />\n </div>\n );\n}\n\n/**\n * Edits a copy: nothing reaches the host until Apply, which runs `prepareApply` (syntax, shape,\n * protected fields) and is disabled while that fails. The dialog stays open after Apply so the\n * restored-fields note is readable; closing with unapplied edits asks first.\n */\nfunction ApplyJsonDialog(props: JsonToggleProps): JSX.Element {\n const { onClose, title, value, prepareApply, onApply, editorLabel } = props;\n const [text, setText] = useState(value);\n // What the host holds now: the text at opening, then the last applied one.\n const [applied, setApplied] = useState(value);\n const [restored, setRestored] = useState<string[]>([]);\n const [confirming, setConfirming] = useState(false);\n const check = useMemo<JsonApplyCheck>(\n () => prepareApply?.(text) ?? { ok: true, text, restored: [] },\n [prepareApply, text],\n );\n const dirty = text !== applied;\n const requestClose = () => (dirty ? setConfirming(true) : onClose());\n const apply = () => {\n if (!check.ok || !dirty) return;\n onApply?.(check.text);\n setText(check.text);\n setApplied(check.text);\n setRestored(check.restored);\n setConfirming(false);\n };\n\n return (\n <Modal title={title} onClose={requestClose} wide className=\"modal-json\">\n <div className=\"modal-body\">\n <p className=\"muted small\">\n Edit the raw definition (<code>manifestVersion: \"2\"</code>). Apply updates the visual\n editor; Save stores it.\n </p>\n <JsonEditorFill\n value={text}\n onChange={(t) => {\n setText(t);\n setConfirming(false);\n }}\n label={editorLabel}\n />\n {!check.ok && (\n <p className=\"error small\" role=\"alert\" data-testid=\"json-toggle-error\">\n {check.error}\n </p>\n )}\n {restored.length > 0 && (\n <p className=\"muted small\" data-testid=\"json-toggle-restored\">\n Restored {restored.join(\", \")}: {restored.length > 1 ? \"these fields\" : \"this field\"}{\" \"}\n can't be changed in JSON.\n </p>\n )}\n </div>\n <div className=\"modal-actions\">\n {confirming ? (\n <>\n <span className=\"muted small json-toggle-confirm\">Discard unapplied changes?</span>\n <button type=\"button\" className=\"btn ghost\" onClick={() => setConfirming(false)}>\n Keep editing\n </button>\n <button\n type=\"button\"\n className=\"btn danger\"\n data-testid=\"json-toggle-discard\"\n onClick={onClose}\n >\n Discard\n </button>\n </>\n ) : (\n <>\n <button\n type=\"button\"\n className=\"btn ghost\"\n data-testid=\"json-toggle-close\"\n onClick={requestClose}\n >\n Close\n </button>\n <button\n type=\"button\"\n className=\"btn\"\n data-testid=\"json-toggle-apply\"\n disabled={!check.ok || !dirty}\n onClick={apply}\n >\n Apply\n </button>\n </>\n )}\n </div>\n </Modal>\n );\n}\n\n/**\n * The host owns the text (no copy here, so a reopened dialog never shows a stale snapshot) and\n * saves it itself; `guard` blocks Save with a reason.\n */\nfunction DisconnectedJsonDialog(props: JsonToggleProps): JSX.Element {\n const { onClose, title, value, onChange, guard, onSave, saving, error, editorLabel } = props;\n const guardReason = guard?.(value) ?? null;\n return (\n <Modal title={title} onClose={onClose} wide className=\"modal-json\">\n <div className=\"modal-body\">\n <p className=\"muted small\">Save replaces the stored definition.</p>\n <JsonEditorFill value={value} onChange={(t) => onChange?.(t)} label={editorLabel} />\n {guardReason && (\n <p className=\"muted small\" data-testid=\"json-toggle-reason\">\n {guardReason}\n </p>\n )}\n {error && <div className=\"error\">{error}</div>}\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={onClose}>\n Cancel\n </button>\n <button\n type=\"button\"\n className=\"btn\"\n data-testid=\"json-toggle-save\"\n disabled={guardReason != null || Boolean(saving)}\n onClick={onSave}\n >\n {saving ? \"Saving…\" : \"Save\"}\n </button>\n </div>\n </Modal>\n );\n}\n","/** Compare JSON definitions independent of object property order. Array order is meaningful. */\nexport function sameWorkflowDefinition(a: unknown, b: unknown): boolean {\n const canonical = (value: unknown): unknown => {\n if (Array.isArray(value)) return value.map(canonical);\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, item]) => [key, canonical(item)]),\n );\n }\n return value;\n };\n // GET adds authoritative metadata absent from older snapshots. Status describes the\n // running publication, not the editable definition; empty tags and a null key are defaults.\n const definition = (value: unknown) => {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) return value;\n const { status: _status, ...rest } = value as Record<string, unknown>;\n return { ...rest, key: rest.key ?? null, tags: rest.tags ?? [] };\n };\n return JSON.stringify(canonical(definition(a))) === JSON.stringify(canonical(definition(b)));\n}\n","import { createElement } from \"react\";\n\nexport interface BindingBannerProps {\n kind: \"workflow\" | \"function\" | \"endpoint\";\n problemCount: number;\n canEnable: boolean;\n onEnable: () => void;\n pending?: boolean;\n}\n\n/** The one \"disabled because a connection is gone\" banner all three editors render. */\nexport function BindingBanner(props: BindingBannerProps) {\n const { kind, problemCount, canEnable, onEnable, pending } = props;\n const text =\n problemCount > 0\n ? `This ${kind} is disabled and ${problemCount} ${problemCount === 1 ? \"step uses\" : \"steps use\"} a connection that no longer exists. Choose another connection, save, then Enable.`\n : \"Connections fixed. Enable to run again.\";\n return createElement(\n \"div\",\n { role: \"alert\", className: \"error\", \"data-testid\": \"binding-disabled-banner\" },\n createElement(\"span\", null, text),\n \" \",\n createElement(\n \"button\",\n {\n type: \"button\",\n \"data-testid\": \"binding-enable\",\n disabled: !canEnable || pending === true,\n onClick: onEnable,\n },\n \"Enable\",\n ),\n );\n}\n","/**\n * The editor frame shared by every callable editor: the rail environment, the project expression\n * scope, and (unless `rail={false}`) the workspace + `RightRail`. `WorkflowEditor` uses it; the\n * Function and Endpoint editors reuse it rather than re-inlining the providers.\n *\n * - `rail` omitted / `true`: its OWN nested `WorkspaceProvider` plus a `RightRail` — the editor's\n * rail, and the nested provider is what keeps a host's outer rail empty.\n * - `rail={false}`: no `RightRail`. Inside a `<CallableWorkspace>` the editor publishes into that\n * workspace; with none it mounts its own provider (no rail) so it can still publish and edit.\n */\nimport type { ReactNode } from \"react\";\nimport { type RailTool, RightRail } from \"../chrome/RightRail.tsx\";\nimport { WorkspaceProvider, useHasWorkspace } from \"../chrome/workspace.tsx\";\nimport { ProjectExpressionScope } from \"../rail/ExpressionScope.tsx\";\nimport { editorRailTools } from \"../rail/editor-tools.ts\";\nimport { RailEnvProvider, type RailNavigation } from \"../rail/rail-env.tsx\";\n\nexport interface EditorShellProps {\n /** Resolved project (`null` = none; tools refuse to save). */\n project: string | null;\n onNavigate: (to: RailNavigation) => void;\n /** Default `true`. `false`: render no rail; publish into the enclosing workspace if any. */\n rail?: boolean;\n /** Persisted-rail key; `null` = not yet persistable. */\n storageKey: string | null;\n /** Default {@link editorRailTools}. */\n tools?: readonly RailTool[];\n children: ReactNode;\n}\n\nexport function EditorShell({\n project,\n onNavigate,\n rail = true,\n storageKey,\n tools = editorRailTools,\n children,\n}: EditorShellProps): ReactNode {\n const enclosed = useHasWorkspace();\n const body = (\n <RailEnvProvider project={project} onNavigate={onNavigate}>\n <ProjectExpressionScope project={project}>\n {children}\n {rail && <RightRail tools={tools} storageKey={storageKey} />}\n </ProjectExpressionScope>\n </RailEnvProvider>\n );\n // Own provider when the rail is ours, or when there is no workspace to publish into.\n return rail || !enclosed ? <WorkspaceProvider>{body}</WorkspaceProvider> : body;\n}\n","import { type ReactNode, useId, useState } from \"react\";\n\n/** Immediate, keyboard-accessible publish help; no native title delay. */\nexport function PublishTooltip({\n message,\n disabled = false,\n children,\n}: {\n message: string;\n disabled?: boolean;\n children: (descriptionId: string) => ReactNode;\n}) {\n const id = useId();\n const [open, setOpen] = useState(false);\n return (\n <fieldset\n className=\"wf-publish-tooltip\"\n aria-label=\"Publish workflow\"\n aria-describedby={id}\n tabIndex={disabled ? 0 : undefined}\n onMouseEnter={() => setOpen(true)}\n onMouseLeave={() => setOpen(false)}\n onFocus={() => setOpen(true)}\n onBlur={(event) => {\n if (!event.currentTarget.contains(event.relatedTarget)) setOpen(false);\n }}\n onKeyDown={(event) => {\n if (event.key === \"Escape\") setOpen(false);\n }}\n >\n {children(id)}\n {open && (\n <span id={id} role=\"tooltip\" className=\"wf-publish-hint\">\n {message}\n </span>\n )}\n </fieldset>\n );\n}\n","import { createElement } from \"react\";\n\nexport interface SetupIncompleteBannerProps {\n /** Node id -> what is missing there (the detector's output). */\n problems: Record<string, string[]>;\n /** Node id -> display label; falls back to the id. */\n nodeLabel?: (nodeId: string) => string;\n}\n\n/** Non-blocking \"Setup incomplete\" banner; renders nothing when no node has a problem. */\nexport function SetupIncompleteBanner(props: SetupIncompleteBannerProps) {\n const { problems, nodeLabel } = props;\n const entries = Object.entries(problems).filter(([, items]) => items.length > 0);\n if (entries.length === 0) return null;\n const n = entries.length;\n return createElement(\n \"div\",\n { role: \"status\", className: \"error\", \"data-testid\": \"setup-incomplete-banner\" },\n createElement(\n \"span\",\n null,\n `Setup incomplete: ${n} ${n === 1 ? \"step needs\" : \"steps need\"} attention. The workflow can still run.`,\n ),\n createElement(\n \"ul\",\n { \"data-testid\": \"setup-incomplete-list\" },\n ...entries.map(([id, items]) =>\n createElement(\"li\", { key: id }, `${nodeLabel ? nodeLabel(id) : id}: ${items.join(\", \")}`),\n ),\n ),\n );\n}\n","import { validateInitialState } from \"@w6w/expr\";\nimport { ExpressionEditorModal, useExpressionOptions } from \"@w6w/ui\";\nimport { type StartingDataProblem, startingDataForSave } from \"../lib/index.ts\";\n\n/** What the starting state editor says about a draft it will not save. */\nconst STARTING_DATA_PROBLEM_TEXT: Record<StartingDataProblem, string> = {\n invalid_json: \"This isn't valid JSON yet, so it isn't saved. Fix it to save.\",\n not_object: 'Starting state must be a JSON object, like {\"region\": \"us\"}. Not saved.',\n too_large: \"Starting state is over the 64 KiB limit. Not saved.\",\n};\n\n/**\n * The one editor for a workflow's starting state (`Workflow.initialState`), opened from the\n * rail's State tool (`rail/StartingStateTool.tsx`) and from Settings → Starting data: the expression manager in its\n * starting-state mode. Its `{{ }}` references are resolved once when a run starts, before any\n * step, so the rail has no Previous steps or State section, and no Secrets (a secret never\n * enters state). A click inserts a reference or, with \"Value\", the source's current value. Save\n * goes through `startingDataForSave` and `validateInitialState` (the server's own check); `{}`\n * or empty drops the key.\n */\nexport function StartingStateModal(props: {\n initialState: Record<string, unknown> | undefined;\n onChange: (next: Record<string, unknown> | undefined) => void;\n onClose: () => void;\n}) {\n const options = useExpressionOptions();\n return (\n <ExpressionEditorModal\n mode=\"json-binding\"\n startingState\n title=\"Starting state\"\n fieldLabel=\"initialState\"\n value={undefined}\n options={options}\n jsonValue={props.initialState}\n jsonProblem={(text) => {\n const result = startingDataForSave(text);\n if (!result.ok) return STARTING_DATA_PROBLEM_TEXT[result.reason];\n // The rules the server refuses a save on: a secret reference, a root not readable at\n // run start (steps, state, a trigger), a forbidden key.\n const issue =\n result.value === undefined ? undefined : validateInitialState(result.value)[0];\n return issue ? `${issue.message} Not saved.` : null;\n }}\n onSaveJson={(next) => {\n const result = startingDataForSave(next === undefined ? \"\" : JSON.stringify(next));\n if (result.ok) props.onChange(result.value);\n }}\n onClose={props.onClose}\n />\n );\n}\n","import type { WorkflowStatus } from \"@w6w/sdk\";\nimport type { CallablePolicy, WorkflowSettings, WorkflowVariableRow } from \"../lib/index.ts\";\n\nexport type Parsed = Record<string, unknown> & {\n id?: string;\n name?: string;\n /** D-1: nullable, no backfill; `undefined` when the field is absent from\n * the text entirely — both mean \"no key\" to {@link workflowKeyEditAllowed}\n * (D-3). The rail's Key control (`SettingsTool.tsx`) is the only place\n * this is ever ASSIGNED; this page only ever reads it back. */\n key?: string | null;\n nodes?: unknown[];\n connections?: Record<string, { app: string; connection: string | null }>;\n /** Legacy name for `nodes`; read via `workflowNodes`. */\n steps?: unknown[];\n status?: WorkflowStatus;\n tags?: string[];\n /** Authoring presentation — rides in the definition, no column of its own. */\n settings?: WorkflowSettings;\n /** Declared public input schema (T1.1.5) — see `workflow-variables.ts`. */\n variables?: WorkflowVariableRow[];\n /**\n * The RUN-level error policy (core Workflow RFC — *Amendment — 2026-08-21:\n * the run-level error handler*). Authored from the right rail's Error\n * handling tool, which this page hands a writer to rather than letting it\n * save independently — see the `useWorkspace` call below.\n */\n retry?: CallablePolicy[\"retry\"];\n onError?: CallablePolicy[\"onError\"];\n reroute?: CallablePolicy[\"reroute\"];\n};\n\n/** Workflow ids: start alphanumeric, then word chars / dots / dashes. */\nexport const ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;\n\n/** Placeholder + minimum sizing basis for the inline title field. */\nexport const TITLE_PLACEHOLDER = \"Untitled workflow\";\n","import type { JsonApplyCheck } from \"../chrome/JsonToggle.tsx\";\nimport { ID_RE, type Parsed } from \"./definition.ts\";\n\n/**\n * The top-level fields the raw-JSON dialog may not change: `id` names the row the save writes to,\n * `key` is assigned only by the rail's Settings → Key control (`workflowKeyEditAllowed`), and\n * `manifestVersion` is the one value the server's `parseWorkflowDefinition` accepts. An edit that\n * alters or deletes one is not refused: Apply puts the loaded value back and says so.\n */\nexport const PROTECTED_WORKFLOW_FIELDS = [\"id\", \"key\", \"manifestVersion\"] as const;\n\n/**\n * The offset of the first character that makes `text` invalid JSON, or `null` when it is valid.\n * Engines disagree on whether `JSON.parse` reports a position at all (current V8 quotes a snippet\n * instead), so the dialog finds it itself with this small strict scanner.\n */\nexport function jsonErrorOffset(text: string): number | null {\n let i = 0;\n const ws = () => {\n while (i < text.length && \" \\t\\n\\r\".includes(text[i] as string)) i++;\n };\n const fail = (): never => {\n throw i;\n };\n const lit = (word: string) => {\n for (const ch of word) {\n if (text[i] !== ch) fail();\n i++;\n }\n };\n const str = () => {\n i++;\n while (text[i] !== '\"') {\n const ch = text[i];\n if (ch === undefined || ch < \" \") fail();\n if (ch === \"\\\\\") {\n i++;\n if (text[i] === \"u\") {\n for (let k = 0; k < 4; k++) {\n i++;\n if (!/[0-9a-fA-F]/.test(text[i] ?? \"\")) fail();\n }\n } else if (!'\"\\\\/bfnrt'.includes(text[i] ?? \"x\")) fail();\n }\n i++;\n }\n i++;\n };\n const NUM = /-?(0|[1-9]\\d*)(\\.\\d+)?([eE][+-]?\\d+)?/y;\n const num = () => {\n NUM.lastIndex = i;\n if (!NUM.test(text)) fail();\n i = NUM.lastIndex;\n };\n const value = (): void => {\n ws();\n const ch = text[i];\n if (ch === \"{\" || ch === \"[\") {\n const close = ch === \"{\" ? \"}\" : \"]\";\n i++;\n ws();\n if (text[i] === close) {\n i++;\n return;\n }\n for (;;) {\n if (close === \"}\") {\n ws();\n if (text[i] !== '\"') fail();\n str();\n ws();\n if (text[i] !== \":\") fail();\n i++;\n }\n value();\n ws();\n if (text[i] === \",\") i++;\n else if (text[i] === close) {\n i++;\n return;\n } else fail();\n }\n }\n if (ch === '\"') str();\n else if (ch === \"t\") lit(\"true\");\n else if (ch === \"f\") lit(\"false\");\n else if (ch === \"n\") lit(\"null\");\n else num();\n };\n try {\n value();\n ws();\n return i < text.length ? i : null;\n } catch (at) {\n return typeof at === \"number\" ? Math.min(at, text.length) : 0;\n }\n}\n\n/** `JSON.parse`'s message, prefixed with the 1-based line and column of the first bad character. */\nexport function jsonSyntaxError(text: string, e: unknown): string {\n const message = e instanceof Error ? e.message : String(e);\n const at = jsonErrorOffset(text);\n if (at === null) return message;\n const before = text.slice(0, at);\n const line = before.split(\"\\n\").length;\n const column = at - before.lastIndexOf(\"\\n\");\n return `Line ${line}, column ${column}: ${message}`;\n}\n\nconst isObj = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\n/**\n * The save-time shape rules the server applies (`parseWorkflowDefinition` + the step-id gate),\n * restated for the fields the canvas reads, plus the one the canvas needs on top: every edge names\n * a node that exists, or React Flow drops it silently and the next canvas edit deletes it.\n */\nexport function workflowShapeError(def: Record<string, unknown>): string | null {\n if (typeof def.name !== \"string\" || def.name.length === 0) return \"`name` is required.\";\n const nodes = def.nodes ?? def.steps;\n if (!Array.isArray(nodes)) return \"`nodes` must be an array.\";\n const ids = new Set<string>();\n for (let i = 0; i < nodes.length; i++) {\n const n: unknown = nodes[i];\n if (!isObj(n)) return `\\`nodes[${i}]\\` must be an object.`;\n if (typeof n.id !== \"string\" || n.id.length === 0) {\n return `\\`nodes[${i}].id\\` must be a non-empty string.`;\n }\n if (n.id.includes(\".\")) return `Node id \"${n.id}\" may not contain \".\".`;\n if (ids.has(n.id)) return `Node id \"${n.id}\" is used twice.`;\n ids.add(n.id);\n const p = n.position;\n if (p !== undefined && (!isObj(p) || !Number.isFinite(p.x) || !Number.isFinite(p.y))) {\n return `\\`nodes[${i}].position\\` must be { \"x\": number, \"y\": number }.`;\n }\n }\n if (def.edges !== undefined) {\n if (!Array.isArray(def.edges)) return \"`edges` must be an array.\";\n for (let i = 0; i < def.edges.length; i++) {\n const e: unknown = def.edges[i];\n if (!isObj(e)) return `\\`edges[${i}]\\` must be an object.`;\n for (const end of [\"from\", \"to\"] as const) {\n if (typeof e[end] !== \"string\" || !ids.has(e[end] as string)) {\n return `\\`edges[${i}].${end}\\` does not name an existing node.`;\n }\n }\n }\n }\n return null;\n}\n\n/**\n * Everything Apply checks, in order: the text parses, it is an object, the protected fields carry\n * the loaded values (restored when not), and the result has a shape the canvas and the save accept.\n * `ok` hands back the text to apply — re-serialized when a field was restored, verbatim otherwise.\n */\nexport function prepareWorkflowJsonApply(text: string, loaded: Parsed | null): JsonApplyCheck {\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch (e) {\n return { ok: false, error: jsonSyntaxError(text, e) };\n }\n if (!isObj(value)) return { ok: false, error: \"The definition must be a JSON object.\" };\n const restored: string[] = [];\n let next: Record<string, unknown> = value;\n // Deleted ones go back in front, in this order, where the loaded document keeps them.\n const front: Record<string, unknown> = {};\n if (loaded) {\n for (const f of PROTECTED_WORKFLOW_FIELDS) {\n const had = Object.hasOwn(loaded, f);\n const has = Object.hasOwn(next, f);\n if (had === has && JSON.stringify(loaded[f]) === JSON.stringify(next[f])) continue;\n restored.push(f);\n if (!had) {\n const { [f]: _drop, ...rest } = next;\n next = rest;\n } else if (has) next = { ...next, [f]: loaded[f] };\n else front[f] = loaded[f];\n }\n next = { ...front, ...next };\n }\n if (typeof next.id === \"string\" && !ID_RE.test(next.id))\n return { ok: false, error: \"Invalid workflow id.\" };\n const shape = workflowShapeError(next);\n if (shape !== null) return { ok: false, error: shape };\n return { ok: true, text: restored.length > 0 ? JSON.stringify(next, null, 2) : text, restored };\n}\n","/**\n * Pure merge of the host's problem sources into the canvas's `stepProblems`:\n * connection problems (host lookup, `findBindingProblems`), loop problems\n * (`findLoopProblems`) and state problems (`findStateWriteProblems`), the last two\n * from `@w6w/ui/flow`. Type-only imports — the runtime helpers reach the host\n * through the editor's existing dynamic `import()`.\n */\nimport type { StepProblem, StepProblems } from \"@w6w/ui/flow\";\nimport type { BindingProblem } from \"../lib/binding-problems.ts\";\n\n/** Per step: its connection problem first, then its loop problems, then its state\n * problems, then its setup-incomplete problem; all kept, empty lists skipped. */\nexport function mergeStepProblems(\n bindingProblems: readonly BindingProblem[],\n loopProblems: StepProblems | undefined,\n stateProblems?: StepProblems,\n setupProblems?: StepProblems,\n): StepProblems {\n const out: StepProblems = {};\n for (const p of bindingProblems) {\n const conn: StepProblem = { code: p.code, connection: p.connection };\n out[p.siteId] = [...(Object.hasOwn(out, p.siteId) ? out[p.siteId] : []), conn];\n }\n for (const source of [loopProblems, stateProblems, setupProblems]) {\n for (const [id, list] of Object.entries(source ?? {})) {\n if (list.length > 0) out[id] = [...(Object.hasOwn(out, id) ? out[id] : []), ...list];\n }\n }\n return out;\n}\n","import { useQueries, useQueryClient } from \"@tanstack/react-query\";\nimport { ApiError } from \"@w6w/sdk\";\nimport {\n ExecutionLogPanel,\n IconButton,\n W6WUIProvider,\n isTestRequired,\n requiredParamsFilled,\n testInputSavesSettled,\n useW6WApi,\n} from \"@w6w/ui\";\nimport type { WorkflowConnectionResources } from \"@w6w/ui/flow\";\nimport type { InternalNodeDef, RunFromNodeRequest, StepProblems } from \"@w6w/ui/flow\";\nimport {\n type ReactNode,\n Suspense,\n lazy,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { ExecutionProfileHeader } from \"../chrome/ExecutionProfileHeader.tsx\";\nimport { HistoryModal } from \"../chrome/HistoryModal.tsx\";\nimport { JsonToggle, JsonToggleButton } from \"../chrome/JsonToggle.tsx\";\nimport { Modal } from \"../chrome/Modal.tsx\";\nimport { useWorkspace } from \"../chrome/workspace.tsx\";\nimport { useEmbedClient, useWorkflowDraft } from \"../draft/index.ts\";\nimport {\n type AppConnections,\n disabledBannerState,\n findBindingProblems,\n} from \"../lib/binding-problems.ts\";\nimport {\n type ActionParamLike,\n type CallablePolicy,\n type TriggerPreview,\n type TriggerPreviewFieldDef,\n type ValidityContext,\n type WorkflowLike,\n type WorkflowStepLike,\n definitionWithPolicy,\n invalidReason,\n policyFromDefinition,\n publishDisabledReason,\n publishProblems,\n readSettings,\n readStartingData,\n readVariables,\n triggerPreviews,\n variablesForSave,\n workflowKeyEditAllowed,\n writeSetting,\n} from \"../lib/index.ts\";\nimport { findSetupIncomplete } from \"../lib/setup-incomplete.ts\";\nimport { workflowNodes } from \"../lib/workflow-nodes.ts\";\nimport { sameWorkflowDefinition } from \"../lib/workflow-version.ts\";\nimport { useEditorProject, useEmbedProject } from \"../project-context.ts\";\nimport type { RailNavigation } from \"../rail/rail-env.tsx\";\nimport { connectionsForAppKey, listConnectionsForApp } from \"../repos/connections.ts\";\nimport {\n STEP_PASS_REFRESH_DELAYS_MS,\n classifyCancelError,\n headerRunEntry,\n isRunInFlight,\n listStepTests,\n listTestInputs,\n mapRunStateToLogSteps,\n resolveHeaderRunInput,\n runButtonLabel,\n runLevelErrors,\n runNodeMap,\n stepPassRefreshDue,\n stepTestsKey,\n useCancelRunMutation,\n useConstantsQuery,\n useDataStoresQuery,\n useLiveRunQuery,\n usePublishMutation,\n useRunFromNodeMutation,\n useRunStateWritesQuery,\n useSecretsQuery,\n useSetEnabledMutation,\n useStartRunMutation,\n useVarsQuery,\n useVersionsQuery,\n workflowStepTestsKey,\n} from \"../repos/index.ts\";\nimport { useRevertMutation, useVersionQuery } from \"../repos/versions.ts\";\nimport { EmbedThemeContext } from \"../theme-context.ts\";\nimport { BindingBanner } from \"./BindingBanner.tsx\";\nimport { EditorShell } from \"./EditorShell.tsx\";\nimport { PublishTooltip } from \"./PublishTooltip.tsx\";\nimport { SetupIncompleteBanner } from \"./SetupIncompleteBanner.tsx\";\nimport { StartingStateModal } from \"./StartingStateModal.tsx\";\nimport { ID_RE, type Parsed, TITLE_PLACEHOLDER } from \"./definition.ts\";\nimport { appActionsKey, useEditorApps } from \"./editor-apps.ts\";\nimport { prepareWorkflowJsonApply } from \"./json-apply.ts\";\nimport { mergeStepProblems } from \"./step-problems-feed.ts\";\nimport type {\n WorkflowEditorNavigation,\n WorkflowEditorProps,\n WorkflowEditorSlots,\n} from \"./types.ts\";\n\n// The visual editor is code-split — its @xyflow/react payload only loads when\n// the editor is actually open.\nconst WorkflowFlowEditor = lazy(() =>\n import(\"@w6w/ui/flow\").then((m) => ({ default: m.WorkflowFlowEditor })),\n);\n\nfunction EditorBody(props: {\n workflowId: string;\n project: string | null;\n /** The provider is still resolving `{use:\"default\"}`: no project YET, which is not an error. */\n projectPending: boolean;\n initialRunId?: string;\n onNavigate: (to: WorkflowEditorNavigation) => void;\n slots?: WorkflowEditorSlots;\n}) {\n const { workflowId, project, projectPending, initialRunId, onNavigate, slots } = props;\n const apiClient = useEmbedClient();\n const api = useW6WApi();\n // Page-level errors only (run, publish, create); the draft's own load/save errors come from\n // `useWorkflowDraft` (`draftError` below).\n const [error, setError] = useState<string | null>(null);\n const [showJson, setShowJson] = useState(false);\n // The canvas seeds its graph from `value` once per mount (it re-reads only on a workflow id\n // change), so a definition replaced from outside it — a JSON Apply, a reload from the server —\n // remounts it through this key. Without it the canvas kept showing the old graph and its next\n // edit wrote that old graph back over the applied JSON.\n const [canvasRevision, setCanvasRevision] = useState(0);\n const [showHistory, setShowHistory] = useState(false);\n const [showStartingState, setShowStartingState] = useState(false);\n const [reloading, setReloading] = useState(false);\n\n // D-3/P4: the key the SERVER most recently sent for the row the buffer is showing — what\n // `workflowKeyEditAllowed` compares the parsed text's own `key` against. `undefined` = nothing\n // loaded yet (refuses unconditionally). Captured whenever the buffer equals the server's copy\n // (load, 409 reload, and after a save), never while it holds unsaved edits. State, not a ref:\n // the guard below must change identity for the draft to re-evaluate it.\n const [loadedKey, setLoadedKey] = useState<string | null | undefined>(undefined);\n // Injected into the draft (the hook is headless — these are Studio's own rules).\n // `autoSave` and the publish-validity reason both depend on the parsed text, which the hook\n // itself produces, so they ride refs assigned after the call (one render of lag at most).\n const autoSaveRef = useRef(true);\n const publishReasonRef = useRef<(def: unknown) => string | null>(() => null);\n const saveGuard = useCallback(\n (def: unknown): string | null => {\n const d = def as Parsed;\n if (!ID_RE.test(typeof d.id === \"string\" ? d.id : \"\")) return \"Invalid workflow id.\";\n // D-3/P4: the rail's Key control is the only place a key is ever assigned — this JSON\n // editor must refuse to save a definition whose `key` differs from what was loaded. Folded\n // into the draft's save gate (never a separate `disabled` on the Save button): auto-save\n // reads the same gate, so a guard on the button alone would be bypassed by typing.\n return workflowKeyEditAllowed(loadedKey, d.key).reason;\n },\n [loadedKey],\n );\n // Load, buffer, save, auto-save, flush-on-hide/unmount and the 409 all live in the hook\n // (`../draft`). The project is `useEditorProject`'s answer (prop, else the provider's): with\n // none, the hook refuses to save (`saveBlockedReason`) rather than let the server pick the\n // account default.\n const draft = useWorkflowDraft({\n workflowId,\n project,\n autoSave: autoSaveRef.current,\n // The expression editor holds uncommitted parts in its own local state until its Save\n // button, so saving from under it would persist a workflow without the expression the user\n // is looking at. Read at fire time (opening it changes neither the buffer nor `canSave`).\n canAutoSave: () => !document.querySelector(\".w6w-exprmodal\"),\n saveGuard,\n publishBlockedReason: (def) => publishReasonRef.current(def),\n });\n const json = draft.json;\n const parsed = draft.parsed as Parsed | null;\n const canSave = draft.canSave;\n const dirty = draft.dirty;\n\n // Capture the server's key whenever the buffer equals the server's copy (never while it holds\n // unsaved edits), and forget it while a workflow is loading or failed to load.\n useEffect(() => {\n if (draft.loading || draft.loadError !== null) {\n setLoadedKey(undefined);\n return;\n }\n if (!draft.dirty && parsed) setLoadedKey((parsed.key as string | null | undefined) ?? null);\n }, [draft.loading, draft.loadError, draft.dirty, parsed]);\n\n // \"Keep editing\" dismisses the 409 modal; the draft stays stale (it refuses to save into the\n // conflict) until the author reloads.\n const [staleDismissed, setStaleDismissed] = useState(false);\n useEffect(() => {\n if (!draft.stale) setStaleDismissed(false);\n }, [draft.stale]);\n\n // The \"Saved.\" marker: a save finished without error since the last one began.\n const [saved, setSaved] = useState(false);\n const wasSaving = useRef(false);\n useEffect(() => {\n if (draft.saving) setSaved(false);\n else if (wasSaving.current && draft.error === null) setSaved(true);\n wasSaving.current = draft.saving;\n }, [draft.saving, draft.error]);\n\n // T2.1.1: the run this canvas is currently showing, if any. Reset inside\n // the `workflowId` load effect below, so a run from a previously open\n // workflow never bleeds into a different one's canvas.\n const [activeRunId, setActiveRunId] = useState<string | null>(null);\n\n // Names offered by each step field's expression picker (task 3.2). The vault\n // No project-scope memo here any more. The ƒx rail's vars, secrets,\n // documents, sample values and \"+ Add\"/seal callbacks are INHERITED from\n // `ProjectExpressionScope` (`App.tsx`); `WorkflowFlowEditor` and the settings\n // modal below both read them from context. What this page's editor\n // contributes on top — the upstream `steps` for one node, and the narrowed\n // `vars` rail for a variable's own default row — is added where it is known,\n // not restated here. See `ui/ExpressionScope.tsx`.\n\n // ── T2.1.1: Run/Stop in the visual editor — live poll, canvas feedback, ──\n // ── log panel, read-only lock. See building-blocks.md §G3/§G4/§G6/§5. ────\n const startRunMut = useStartRunMutation();\n const runFromNodeMut = useRunFromNodeMutation();\n const cancelRunMut = useCancelRunMutation();\n const runQuery = useLiveRunQuery(activeRunId);\n const runStatus = runQuery.data?.status;\n const runPollFailed = runQuery.isError;\n const runInFlight = isRunInFlight(runStatus, runPollFailed);\n // 26-10-04-01-fixes I-1: the run log's rows (each carrying its step's error)\n // and the run-level `error`/`stepErrors` the rows don't already show —\n // mapped once per render, shared by the panel's three props.\n // T5.1.1: a run record carries its per-node map under `nodes` (canonical) or\n // the legacy `steps` — `runNodeMap` prefers `nodes`.\n // State tree: the run's state-write log rides beside the run poll (same cadence, its own\n // query) and feeds each row's State block; a failed or absent log leaves the rows as they are.\n const stateWritesQuery = useRunStateWritesQuery(activeRunId, runStatus);\n const runLogSteps = mapRunStateToLogSteps(\n runNodeMap(runQuery.data),\n stateWritesQuery.data?.writes,\n );\n const runLogErrors = runLevelErrors(runQuery.data, runLogSteps);\n // Header Run fetches the trigger's saved fixture before starting the run;\n // the ref guards re-entry synchronously (a second click can land before the\n // re-render that disables the button), the state disables the button.\n const runStartingRef = useRef(false);\n const [runStarting, setRunStarting] = useState(false);\n\n // ── T2.4.2: `?run=<runId>` — the History page's \"Open in visual editor\" ──\n // A workflow run's History row links to `workflows/<id>?run=<runId>`, and\n // THIS editor is what that link opens. The run plumbing above already\n // renders a terminal run exactly like a live one (`useLiveRunQuery` stops\n // polling on a terminal status by itself), so seeding `activeRunId` from the\n // URL is the whole feature — nothing about the poll, the canvas, the\n // read-only lock or the log panel moves.\n //\n // Declared AFTER the `workflowId` load effect on purpose: that effect resets\n // `activeRunId` for the row it is opening, and effects run in declaration\n // order, so on a mount the URL's run wins. Keyed on `[workflowId, initialRunId]`\n // rather than on mount alone, so an in-app transition to `?run=…` while the\n // editor stays mounted (`history.pushState` + `popstate`) still opens the\n // panel.\n // T2.1.1: a run belongs to the row that started it — the draft's load (formerly this page's\n // `workflowId` effect) reset it; declared BEFORE the `?run=` seed below so the URL's run still wins.\n // biome-ignore lint/correctness/useExhaustiveDependencies: `workflowId` is the trigger, not a value read\n useEffect(() => {\n setActiveRunId(null);\n }, [workflowId]);\n // biome-ignore lint/correctness/useExhaustiveDependencies: `workflowId`'s own value is never read below — it exists solely to re-seed the URL's run when the OPEN WORKFLOW changes, not as a value this closure needs (same retrigger-dependency shape as `api/w6wApiFacade.tsx`).\n useEffect(() => {\n if (initialRunId) setActiveRunId(initialRunId);\n }, [workflowId, initialRunId]);\n\n // The run id alone is not enough: a stale or hand-edited `?run=` can name a\n // run belonging to a DIFFERENT workflow, and painting that run's steps on\n // this canvas would be a lie. `RunState` carries its own `workflowId`, so the\n // first answer that names another workflow drops the run instead of\n // rendering it.\n useEffect(() => {\n if (runQuery.data && runQuery.data.workflowId !== workflowId) setActiveRunId(null);\n }, [runQuery.data, workflowId]);\n\n /**\n * T2.1.5: run `action` only once the buffer is saved. `blocked` shows its reason in the banner;\n * `failed` is already surfaced by the draft itself (banner, or the 409 modal via `draft.stale`).\n */\n async function runAfterFlush(action: () => Promise<unknown>) {\n try {\n const r = await draft.flushThen(action);\n if (!r.ok && r.outcome.status === \"blocked\") setError(r.outcome.reason);\n } catch (e) {\n setError(e instanceof ApiError ? e.message : String(e));\n }\n }\n\n async function onRunClick() {\n if (!workflowId || runInFlight || runStartingRef.current) return;\n setError(null);\n runStartingRef.current = true;\n setRunStarting(true);\n try {\n // 26-10-04-01-fixes I-1 (pinned): the entry trigger's latest saved Test-tab\n // values become the run's `input`, verbatim; no fixture (or no trigger,\n // or a failed fetch) sends no `input` key, exactly as before. The entry is\n // the Manual trigger, else a webhook / schedule / app trigger — whose sample\n // payload is just as much what the author means to run with.\n const entry = flowHelpers\n ? headerRunEntry(steps, flowHelpers.isManualTrigger, flowHelpers.isEntryTrigger)\n : triggerPreviewList?.[0] && { id: triggerPreviewList[0].id, manual: true };\n // A payload edited a moment ago (the Test tab saves as it closes) lands before it is read.\n await testInputSavesSettled();\n const input = await resolveHeaderRunInput(\n entry?.id,\n (stepId) => listStepTests(apiClient, workflowId, stepId),\n () => listTestInputs(apiClient, workflowId),\n );\n // T2.1.5 (R-27): the stored row is what runs, so an unsaved edit is saved FIRST. A refused\n // flush (`blocked` reason / `failed` save) never starts the run.\n await runAfterFlush(() =>\n entry && !entry.manual\n ? // A webhook / schedule / app trigger entry runs FROM that trigger: the server takes\n // the payload as the event that fired it (its output and `trigger.event`), which a\n // plain run's `input` — the Manual trigger's slot — never reaches.\n runFromNodeMut\n .mutateAsync({\n id: workflowId,\n nodeId: entry.id,\n body: { stopAt: [], ...(input ? { input } : {}) },\n })\n .then((res) => setActiveRunId(res.runId))\n : startRunMut\n .mutateAsync({\n id: workflowId,\n variables: {},\n ...(input ? { input } : {}),\n })\n .then((res) => setActiveRunId(res.runId)),\n );\n } finally {\n runStartingRef.current = false;\n setRunStarting(false);\n }\n }\n\n /**\n * ▶ on a node (adhoc/run-pause): a real run that executes the node, continues downstream and\n * stops before every paused node. Saved first, like the header Run, because the stored row is\n * what runs; then shown exactly like a header run — live canvas + run log. A refusal (a blocked\n * save, an API error) rejects, and the editor shows it in the ▶ modal.\n */\n async function onRunFromNode(nodeId: string, req: RunFromNodeRequest) {\n if (!workflowId) return;\n setError(null);\n const r = await draft.flushThen(() =>\n runFromNodeMut.mutateAsync({\n id: workflowId,\n nodeId,\n body: {\n stopAt: req.stopAt,\n ...(req.state?.steps ? { nodes: req.state.steps } : {}),\n ...(req.input ? { input: req.input } : {}),\n },\n }),\n );\n if (!r.ok) {\n throw new Error(\n r.outcome.status === \"blocked\"\n ? r.outcome.reason\n : \"The workflow could not be saved, so it was not run.\",\n );\n }\n setActiveRunId(r.value.runId);\n }\n\n function onStopClick() {\n if (!activeRunId) return;\n cancelRunMut.mutate(activeRunId, {\n onError: (e) => {\n const code = e instanceof ApiError ? e.code : \"\";\n // A `409 run_not_cancelable` means the run already finished before the\n // cancel request landed — reconcile via the next poll, no error banner.\n if (classifyCancelError(code) === \"surface\") {\n setError(e instanceof ApiError ? e.message : String(e));\n }\n },\n });\n // T1.1.1 A1: ask the server to cancel, but reset the LOCAL run state now —\n // the cancel is cooperative (heartbeat-driven) and may land long after the\n // click, so waiting for a poll to observe a terminal status would leave the\n // canvas greyed out in front of the user who just pressed Stop. The request\n // above still goes out, and `onError` still classifies the 409.\n setActiveRunId(null);\n }\n\n /** Replace the editor's contents with the server's copy and re-arm the token. */\n async function reloadFromServer() {\n setReloading(true);\n try {\n await draft.reload();\n setCanvasRevision((r) => r + 1);\n setError(null);\n } finally {\n setReloading(false);\n }\n }\n\n // Page-level errors win; the draft's own load/save failure shows otherwise. A 409 is the\n // modal's business, not the banner's.\n const draftFailure = draft.stale ? null : (draft.error ?? draft.loadError);\n const bannerError =\n error ??\n (draftFailure === null\n ? null\n : draftFailure instanceof Error\n ? draftFailure.message\n : String(draftFailure));\n\n // Parse for the visual view + meta fields — the draft already parses (memoized) per edit.\n // T5.1.1: a definition declares its vertices under `nodes` (canonical) or the\n // legacy `steps` — either shape is drawable.\n const flowUsable =\n parsed !== null && (Array.isArray(parsed.nodes) || Array.isArray(parsed.steps));\n\n const displayName = (parsed?.displayName as string) ?? \"\";\n // Both flags are ON for a workflow that declares no `settings` — see readSettings.\n const settings = readSettings(parsed?.settings);\n // The starting state (`Workflow.initialState`): the rail State tool's dot and its editor.\n const startingState = readStartingData(parsed?.initialState);\n // The Variables tab's rows (T1.1.5) — declaring the workflow's public input\n // schema (HITL-5). `useMemo` because `varsRailFor` runs once per row on\n // every render otherwise.\n const variables = useMemo(() => readVariables(parsed?.variables), [parsed?.variables]);\n // Visible only once something has actually loaded AND the parsed text is\n // real JSON — never flashes \"Workflow not loaded yet\" on a fresh mount\n // before the initial fetch resolves.\n const keyEdit = workflowKeyEditAllowed(loadedKey, parsed?.key);\n const keyGuardReason =\n parsed !== null && loadedKey !== undefined && !keyEdit.allowed ? keyEdit.reason : null;\n\n // ── Publish-time validity gate (T4.2.1) ──────────────────────────────────\n // T5.1.1: `workflowNodes` reads `nodes` (canonical) or the legacy `steps`.\n const steps = useMemo<WorkflowStepLike[]>(\n () => workflowNodes<WorkflowStepLike>(parsed as WorkflowLike | null),\n [parsed],\n );\n\n // `INTERNAL_NODES`/`isInternalApp`/`internalNodeParams` resolve from the SAME\n // `import(\"@w6w/ui/flow\")` the canvas's `lazy()` above already triggers (a\n // module-cache hit, not a second bundle) — only needed while the editor is\n // open, same as the canvas itself. Defaults to \"nothing resolved yet\", which\n // fails `actionParamsByKey` closed (invalid) until it lands.\n const [flowHelpers, setFlowHelpers] = useState<{\n internalNodes: InternalNodeDef[];\n isInternalApp: (app: string) => boolean;\n internalNodeParams: (app: string, action: string) => ActionParamLike[];\n // \"Call from code\" trigger preview (T2.2.1) — `TRIGGER_APP`/`asFieldDefs`\n // resolve from the SAME import, no second dynamic import.\n isManualTrigger: (app: string) => boolean;\n // Any entry trigger (manual, webhook, schedule, app trigger) — the header Run's entry.\n isEntryTrigger: (uses: { app: string; trigger?: true }) => boolean;\n asFieldDefs: (fields: unknown) => TriggerPreviewFieldDef[];\n // Loop problems (T2.3.2) — pure detector from the SAME import; never a static value import.\n findLoopProblems: (wf: unknown) => StepProblems;\n // Parallel state-write problems (state tree) — same import, same rule.\n findStateWriteProblems: (wf: unknown) => StepProblems;\n } | null>(null);\n useEffect(() => {\n let canceled = false;\n import(\"@w6w/ui/flow\").then((m) => {\n if (canceled) return;\n setFlowHelpers({\n internalNodes: m.INTERNAL_NODES,\n isInternalApp: m.isInternalApp,\n internalNodeParams: m.internalNodeParams,\n isManualTrigger: (app) => app === m.TRIGGER_APP,\n isEntryTrigger: m.isTriggerStep,\n asFieldDefs: m.asFieldDefs,\n findLoopProblems: m.findLoopProblems as (wf: unknown) => StepProblems,\n findStateWriteProblems: m.findStateWriteProblems as (wf: unknown) => StepProblems,\n });\n });\n return () => {\n canceled = true;\n };\n }, []);\n\n // \"Call from code\" trigger preview (T2.2.1, HITL-2/HITL-4 pinned): the\n // modal's per-trigger field picker, derived from the SAME `steps` above —\n // no new fetch, no new query key.\n const triggerPreviewList = useMemo<TriggerPreview[] | undefined>(() => {\n if (!flowHelpers) return undefined;\n return triggerPreviews(\n { steps },\n {\n isManualTrigger: flowHelpers.isManualTrigger,\n asFieldDefs: flowHelpers.asFieldDefs,\n },\n );\n }, [flowHelpers, steps]);\n\n // Unique third-party (non-internal) app ids across the graph, batch-fetched\n // once each — mirrors the per-step fetch WorkflowFlowEditor already does\n // (WorkflowFlowEditor.tsx:~1432), hoisted to page level and de-duplicated.\n const thirdPartyAppIds = useMemo(() => {\n if (!flowHelpers) return [];\n const ids = new Set<string>();\n for (const s of steps) {\n const { app, action } = s.uses ?? {};\n if (app && action && !flowHelpers.isInternalApp(app)) ids.add(app);\n }\n return [...ids];\n }, [flowHelpers, steps]);\n // Registered apps, so the visual editor can render each action node with its\n // owning app's icon, display name, and version — bounded to the ids this\n // graph actually references (src/apps provider, T3.1.2).\n const { byId: fetchedAppsById } = useEditorApps(thirdPartyAppIds);\n const appsList = useMemo(() => [...fetchedAppsById.values()], [fetchedAppsById]);\n const appActionsQueries = useQueries({\n queries: thirdPartyAppIds.map((appId) => ({\n queryKey: appActionsKey(appId),\n queryFn: () => api.getAppActions(appId),\n })),\n });\n\n // Declared params for every step's target, internal (sync) or third-party\n // (fetched above) — keyed `${app}::${action}`, one entry per unique target.\n const actionParamsByKey = useMemo(() => {\n const out: Record<string, ActionParamLike[]> = {};\n if (!flowHelpers) return out;\n for (const s of steps) {\n const { app, action } = s.uses ?? {};\n if (!app || !action) continue;\n const key = `${app}::${action}`;\n if (key in out) continue;\n if (flowHelpers.isInternalApp(app)) {\n out[key] = flowHelpers.internalNodeParams(app, action);\n } else {\n const idx = thirdPartyAppIds.indexOf(app);\n const fetched = idx >= 0 ? appActionsQueries[idx]?.data : undefined;\n out[key] = fetched?.find((a) => a.key === action)?.params ?? [];\n }\n }\n return out;\n }, [flowHelpers, steps, thirdPartyAppIds, appActionsQueries]);\n\n const appsById = useMemo(() => {\n const out: Record<string, unknown> = {};\n for (const [id, a] of fetchedAppsById) out[id] = a;\n return out;\n }, [fetchedAppsById]);\n\n // Only a step whose app is BOTH a real fetched app AND opts into\n // testRequired needs a `listStepTests` fetch — an internal/trigger/control\n // step's app is never a key in `appsById`, so it is never gated.\n const testGatedSteps = useMemo(\n () =>\n steps.filter((s) => {\n const app = s.uses?.app;\n return !!app && app in appsById && isTestRequired(appsById[app]);\n }),\n [steps, appsById],\n );\n const stepTestsQueries = useQueries({\n queries: testGatedSteps.map((s) => ({\n queryKey: stepTestsKey(workflowId, s.id),\n queryFn: () => listStepTests(apiClient, workflowId, s.id),\n enabled: !!workflowId,\n })),\n });\n const testStatus = useMemo(() => {\n const out: Record<string, boolean> = {};\n testGatedSteps.forEach((s, i) => {\n out[s.id] = !!stepTestsQueries[i]?.data?.some((t) => t.lastRunStatus === \"succeeded\");\n });\n return out;\n }, [testGatedSteps, stepTestsQueries]);\n\n // T3.1.1: the Publish button's own published-state, gated the same shape\n // as `stepTestsQueries` above (`!!workflowId`) — never on mount\n // alone. Shares its cache entry with the Settings rail's own History\n // section (same `[\"versions\", \"workflow\", id]` key), so either surface's\n // Publish click refreshes both without a reload.\n const versionsQuery = useVersionsQuery(\"workflow\", workflowId, !!workflowId);\n const publishMut = usePublishMutation(\"workflow\");\n const publishedVersion = versionsQuery.data?.currentPublishedVersion ?? null;\n const publishedQuery = useVersionQuery(\"workflow\", workflowId, publishedVersion, !!workflowId);\n const matchesPublished =\n publishedQuery.data !== undefined &&\n parsed !== null &&\n sameWorkflowDefinition(parsed, publishedQuery.data.definition);\n const definitionStatus =\n versionsQuery.data === undefined\n ? undefined\n : publishedVersion === null\n ? \"unpublished\"\n : publishedQuery.data === undefined || draft.loading\n ? undefined\n : matchesPublished\n ? \"published\"\n : \"draft\";\n const [restoring, setRestoring] = useState(false);\n const revertMut = useRevertMutation(\"workflow\");\n\n async function restoreVersion(versionNumber: number) {\n setRestoring(true);\n setError(null);\n try {\n await draft.discardThen(() => revertMut.mutateAsync({ id: workflowId, versionNumber }));\n setCanvasRevision((r) => r + 1);\n setActiveRunId(null);\n } finally {\n setRestoring(false);\n }\n }\n\n // R5: steps bound to a connection id the account no longer has. Connections per third-party\n // app share the `connectionsForAppKey` cache entry; only a settled, successful list can\n // convict a binding (loading / error never paint a false problem).\n const qc = useQueryClient();\n // A finished run books each step that succeeded as its passing saved test (server\n // `step-passes.ts`), so re-read this workflow's step tests once per run as it turns terminal —\n // the publish gate's `testStatus` reads them and nothing else refetches them. Not cleaned up on\n // purpose: the latch stops a re-schedule, so a cleared later read would be lost for good.\n const stepPassesReadFor = useRef<string | null>(null);\n useEffect(() => {\n if (!workflowId || !activeRunId || stepPassesReadFor.current === activeRunId) return;\n if (!stepPassRefreshDue(runStatus, runQuery.data?.workflowId, workflowId)) return;\n stepPassesReadFor.current = activeRunId;\n for (const ms of STEP_PASS_REFRESH_DELAYS_MS) {\n setTimeout(\n () => void qc.invalidateQueries({ queryKey: workflowStepTestsKey(workflowId) }),\n ms,\n );\n }\n }, [workflowId, activeRunId, runStatus, runQuery.data?.workflowId, qc]);\n const connQueries = useQueries({\n queries: thirdPartyAppIds.map((appId) => ({\n queryKey: connectionsForAppKey(appId),\n queryFn: () => listConnectionsForApp(apiClient, appId),\n })),\n });\n const connByApp = useMemo(() => {\n const m = new Map<string, AppConnections>();\n thirdPartyAppIds.forEach((appId, i) => {\n const q = connQueries[i];\n if (!q) return;\n if (q.isError) m.set(appId, { state: \"error\" });\n else if (q.isSuccess && !q.isFetching)\n m.set(appId, { state: \"ready\", ids: new Set((q.data ?? []).map((c) => c.id)) });\n else m.set(appId, { state: \"loading\" });\n });\n return m;\n }, [thirdPartyAppIds, connQueries]);\n const bindingProblems = useMemo(\n () => findBindingProblems(steps, (app) => connByApp.get(app), parsed?.connections),\n [steps, connByApp, parsed?.connections],\n );\n // Setup-incomplete (non-blocking, derived from the saved workflow). A list that is loading or\n // errored is not ready, so its category is never flagged.\n const varsQ = useVarsQuery(project ?? undefined, project !== null);\n const secretsQ = useSecretsQuery();\n const constantsQ = useConstantsQuery();\n const storesQ = useDataStoresQuery(project ?? undefined);\n const setupResult = useMemo(() => {\n if (!parsed) return {};\n const list = (q: { isSuccess: boolean; data?: { name: string }[] }) => ({\n names: (q.data ?? []).map((x) => x.name),\n ready: q.isSuccess,\n });\n return findSetupIncomplete({\n workflow: parsed,\n lists: {\n vars: list(varsQ),\n secrets: list(secretsQ),\n constants: list(constantsQ),\n stores: list(storesQ),\n },\n });\n }, [parsed, varsQ, secretsQ, constantsQ, storesQ]);\n const setupProblems = useMemo(() => {\n const out: StepProblems = {};\n for (const [id, items] of Object.entries(setupResult))\n out[id] = [{ code: \"setup_incomplete\", items }];\n return out;\n }, [setupResult]);\n // Connection problems first, then loop problems, then state problems (never fed to the\n // disabled banner: that stays `bindingProblems`-only). Until `flowHelpers` lands this is\n // connection-only.\n const stepProblems = useMemo(\n () =>\n mergeStepProblems(\n bindingProblems,\n flowHelpers?.findLoopProblems(parsed),\n parsed ? flowHelpers?.findStateWriteProblems(parsed) : undefined,\n setupProblems,\n ),\n [bindingProblems, flowHelpers, parsed, setupProblems],\n );\n // A connection created through the step modal never touched this cache: refetch once per\n // (app, id) pair when the bound id is absent from a ready list. The latch stops any loop.\n const refetchedPairs = useRef(new Set<string>());\n useEffect(() => {\n for (const p of bindingProblems) {\n const pair = `${p.app}|${p.connection}`;\n if (refetchedPairs.current.has(pair)) continue;\n refetchedPairs.current.add(pair);\n qc.invalidateQueries({ queryKey: connectionsForAppKey(p.app) });\n }\n }, [bindingProblems, qc]);\n const hadProblemsRef = useRef({ id: workflowId, had: false });\n if (hadProblemsRef.current.id !== workflowId)\n hadProblemsRef.current = { id: workflowId, had: false };\n if (bindingProblems.length > 0) hadProblemsRef.current.had = true;\n const setEnabledMut = useSetEnabledMutation(\"workflow\");\n const bannerState = disabledBannerState({\n enabled: versionsQuery.data?.enabled,\n problemCount: bindingProblems.length,\n dirty: draft.dirty,\n hadProblems: hadProblemsRef.current.had,\n });\n\n const validityCtx = useMemo<ValidityContext>(\n () => ({\n actionParamsByKey,\n appsById,\n testStatus,\n requiredParamsFilled,\n isTestRequired,\n }),\n [actionParamsByKey, appsById, testStatus],\n );\n // Every reason Publish is disabled, so the button never greys out silently: the tooltip\n // carries the whole reason and the Why dialog makes it available without hovering. Fails closed\n // until the node catalog (`flowHelpers`) lands: before it, internal steps' params are unknown\n // and would read as \"all required params filled\".\n const publishBlockers = useMemo(\n () =>\n parsed !== null && flowHelpers !== null\n ? publishProblems(parsed as unknown as WorkflowLike, validityCtx)\n : [],\n [parsed, flowHelpers, validityCtx],\n );\n const [publishBusy, setPublishBusy] = useState(false);\n const publishInFlight = useRef(false);\n const publishValidationReason = publishDisabledReason({\n projectMissing: project === null,\n loading: !canSave,\n saveBlockedReason:\n draft.saveBlockedReason ??\n (canSave && parsed === null ? \"the workflow JSON does not parse.\" : null),\n catalogLoading: parsed !== null && flowHelpers === null,\n problems: publishBlockers,\n publishing: publishBusy || publishMut.isPending,\n });\n const publishBlockReason =\n publishValidationReason ??\n (versionsQuery.isPending || (publishedVersion !== null && publishedQuery.isPending)\n ? \"Checking the published version…\"\n : versionsQuery.isError || (publishedVersion !== null && publishedQuery.isError)\n ? \"Can't check the published version. Reload to try again.\"\n : matchesPublished\n ? \"Already published. Make a change before publishing again.\"\n : null);\n async function publishDraft() {\n if (!workflowId || publishBlockReason !== null || publishInFlight.current) return;\n publishInFlight.current = true;\n setPublishBusy(true);\n setError(null);\n try {\n await runAfterFlush(() => publishMut.mutateAsync(workflowId));\n } finally {\n publishInFlight.current = false;\n setPublishBusy(false);\n }\n }\n\n publishReasonRef.current = (def) =>\n def !== null && typeof def === \"object\"\n ? invalidReason(def as unknown as WorkflowLike, validityCtx)\n : null;\n autoSaveRef.current = settings.autoSave;\n\n // Stable per loaded definition, so the dialog re-checks only on its own edits.\n const prepareApply = useCallback(\n (text: string) => prepareWorkflowJsonApply(text, parsedRef.current),\n [],\n );\n\n /** Patch top-level workflow fields, keeping the JSON text as source of truth. */\n function patchMeta(patch: Partial<Parsed>) {\n if (!parsed) return;\n const next: Parsed = { ...parsed, ...patch };\n draft.setJson(JSON.stringify(next, null, 2));\n }\n\n /** Patch top-level fields and persist immediately (for publish/tags edits). */\n function saveMeta(patch: Partial<Parsed>) {\n if (!parsed) return;\n const next: Parsed = { ...parsed, ...patch };\n setError(null);\n void draft.commit(JSON.stringify(next, null, 2));\n }\n\n // The rail's `onPolicyChange` must be referentially stable (see the `useWorkspace` call\n // below) and therefore cannot close over `parsed`/`draft` directly: it reads the live\n // definition and the draft's `commit` through refs.\n const parsedRef = useRef(parsed);\n parsedRef.current = parsed;\n const commitRef = useRef(draft.commit);\n commitRef.current = draft.commit;\n const saveNowRef = useRef(draft.saveNow);\n saveNowRef.current = draft.saveNow;\n\n // Cmd/Ctrl+S saves while the visual editor is open (mirrors the project\n // switcher's keydown effect in components/Layout.tsx: one guarded document\n // listener, symmetric cleanup).\n useEffect(() => {\n const onKey = (e: KeyboardEvent) => {\n if (e.altKey || !(e.metaKey || e.ctrlKey) || e.key.toLowerCase() !== \"s\") return;\n // Suppress the browser's Save Page dialog on every match, including the\n // paths below that decline to save.\n e.preventDefault();\n // The expression editor holds uncommitted parts in its own local state\n // until its Save button, so saving from under it would persist a workflow\n // without the expression the user is looking at.\n if (document.querySelector(\".w6w-exprmodal\")) return;\n if (!canSave) return;\n saveNowRef.current();\n };\n document.addEventListener(\"keydown\", onKey);\n return () => {\n document.removeEventListener(\"keydown\", onKey);\n };\n }, [canSave]);\n\n // T2.1.2: publishes into the right rail's Code/Aliases tools — called on\n // EVERY render, into the `WorkspaceProvider` the outer `WorkflowEditor` mounts.\n //\n // The `policy`/`onPolicyChange` pair is the right rail's Error handling tool\n // (core Workflow RFC — *Amendment — 2026-08-21: the run-level error\n // handler*). The rail does NOT save a workflow itself: this page owns the\n // definition buffer and the draft saves it, so a second writer over the wire\n // would race the canvas and one side's edit would vanish. Handing the rail a\n // writer instead makes its Save fold into the very same JSON text.\n const wfPolicy = useMemo<CallablePolicy>(\n () => (parsed ? policyFromDefinition(parsed) : {}),\n [parsed],\n );\n // Referentially STABLE, as `workspace.tsx` requires: `useWorkspace` keys its\n // publish effect on `JSON.stringify(resource)`, which drops functions, so a\n // callback rebuilt per render would be stored once and then go stale. It\n // reads the current definition through `parsedRef` — always the live value,\n // never a captured one. Persists immediately, exactly like `saveMeta`'s\n // publish/tags edits.\n const onPolicyChange = useCallback((policy: CallablePolicy) => {\n const current = parsedRef.current;\n if (!current) return;\n const next = definitionWithPolicy(current, policy);\n setError(null);\n void commitRef.current(JSON.stringify(next, null, 2));\n }, []);\n\n // The rail State tool opens the starting state editor; stable for the same reason.\n const onOpenStartingState = useCallback(() => setShowStartingState(true), []);\n // The State panel's run link and the header History both open a run the same way; read through\n // a ref so the published callback stays stable.\n const openRunRef = useRef<(runId: string) => void>(() => {});\n openRunRef.current = (runId) => {\n setActiveRunId(runId);\n onNavigate({ type: \"run\", id: workflowId, runId });\n };\n const onOpenRun = useCallback((runId: string) => openRunRef.current(runId), []);\n\n const restoreVersionRef = useRef(restoreVersion);\n restoreVersionRef.current = restoreVersion;\n const onRestoreVersion = useCallback((n: number) => restoreVersionRef.current(n), []);\n const publishDraftRef = useRef(publishDraft);\n publishDraftRef.current = publishDraft;\n const onPublish = useCallback(() => publishDraftRef.current(), []);\n const authoringRef = useRef({ saveMeta, patchMeta });\n authoringRef.current = { saveMeta, patchMeta };\n const onAuthoringSettingChange = useCallback(\n (key: \"autoSave\" | \"savePosition\", value: boolean) => {\n authoringRef.current.saveMeta({\n settings: writeSetting(parsedRef.current?.settings, key, value),\n });\n },\n [],\n );\n const onVariablesChange = useCallback((next: Parameters<typeof variablesForSave>[0]) => {\n authoringRef.current.patchMeta({ variables: variablesForSave(next) });\n }, []);\n const [connectionResources, setConnectionResources] =\n useState<WorkflowConnectionResources | null>(null);\n const connectionResourcesRef = useRef(connectionResources);\n connectionResourcesRef.current = connectionResources;\n // Workspace publication compares data, so keep its callback valid across canvas remounts.\n const editConnectionResource = useCallback(\n (edit: Parameters<WorkflowConnectionResources[\"edit\"]>[0]) => {\n connectionResourcesRef.current?.edit(edit);\n },\n [],\n );\n const onOpenHistory = useCallback(() => setShowHistory(true), []);\n useWorkspace({\n kind: \"workflow\",\n id: workflowId,\n connectionResources:\n connectionResources?.workflowId === workflowId\n ? { ...connectionResources, edit: editConnectionResource }\n : undefined,\n label: displayName,\n key: parsed?.key ?? undefined,\n triggers: triggerPreviewList,\n onRestoreVersion,\n definitionStatus,\n onPublish,\n publishDisabled: publishBlockReason !== null,\n policy: wfPolicy,\n onPolicyChange,\n hasStartingState: startingState !== undefined && Object.keys(startingState).length > 0,\n startingState,\n onOpenStartingState,\n onOpenRun,\n authoringSettings: { autoSave: settings.autoSave, savePosition: settings.savePosition },\n onAuthoringSettingChange,\n variables,\n onVariablesChange,\n onOpenHistory,\n });\n\n return (\n <div className=\"wf-fullbleed\" style={{ height: \"100%\", minWidth: 0, flex: 1 }}>\n {/* T3.1.1: the header itself is `ExecutionProfileHeader` — the SAME\n component a Function/Endpoint editor mounts through\n `CallableEditorChrome`. Everything below is host business: the\n back control (A8, updated by T4.1.1: the editor is its own route\n now, so \"back\" navigates to the LISTING — the sibling params it was\n opened with are kept, since they are the author's), the controlled\n name field that persists on blur, and the action row. */}\n {slots?.header ?? (\n <ExecutionProfileHeader\n onBack={() => onNavigate({ type: \"list\" })}\n backLabel={slots?.backLabel === null ? null : (slots?.backLabel ?? \"← Workflows\")}\n title={{\n editable: true,\n value: displayName,\n placeholder: TITLE_PLACEHOLDER,\n maxLength: 80,\n ariaLabel: \"Workflow name\",\n onChange: (next) => patchMeta({ displayName: next }),\n onBlur: () => {\n if (canSave) draft.saveNow();\n },\n }}\n titleAdornment={\n definitionStatus && (\n <span\n className={`badge wf-definition-status ${definitionStatus}`}\n data-testid=\"wf-definition-status\"\n aria-live=\"polite\"\n title={\n definitionStatus === \"published\"\n ? \"This workflow matches the published version. Edits create a separate draft.\"\n : definitionStatus === \"draft\"\n ? \"You are editing a draft. The published version stays unchanged until you publish.\"\n : \"You are editing a draft. This workflow has not been published.\"\n }\n >\n {definitionStatus === \"published\" ? \"Live\" : \"Draft\"}\n </span>\n )\n }\n actions={\n <>\n <IconButton\n icon=\"play\"\n label={runButtonLabel(runStatus, runPollFailed)}\n data-testid=\"wf-run-start\"\n onClick={onRunClick}\n disabled={!workflowId || runInFlight || runStarting || startRunMut.isPending}\n />\n {runInFlight && (\n <IconButton\n icon=\"stop\"\n label=\"Stop this run\"\n data-testid=\"wf-run-stop\"\n onClick={onStopClick}\n disabled={cancelRunMut.isPending}\n />\n )}\n <PublishTooltip\n disabled={publishBlockReason !== null}\n message={\n publishBlockReason ??\n (publishedVersion !== null\n ? \"Republish this draft as a new live version\"\n : \"Publish this draft as a new live version\")\n }\n >\n {(descriptionId) => (\n <>\n <button\n type=\"button\"\n className=\"btn ghost wf-publish\"\n data-testid=\"wf-publish\"\n onClick={() => void publishDraft()}\n disabled={publishBlockReason !== null}\n aria-describedby={descriptionId}\n >\n {publishBusy || publishMut.isPending\n ? publishedVersion !== null\n ? \"Republishing…\"\n : \"Publishing…\"\n : publishedVersion !== null\n ? definitionStatus === \"draft\"\n ? \"Republish\"\n : \"Published\"\n : \"Publish\"}\n </button>\n </>\n )}\n </PublishTooltip>\n <JsonToggleButton onClick={() => setShowJson(true)} />\n {/* T2.1.2: \"Call from code\" moved to the right rail's Code tool —\n see the `useWorkspace` call above (this closes the prior\n project's HITL-1: the flow editor now publishes, since the\n gate is the editor's own mount, not the route wrapper that could\n never see this component's route param). */}\n {slots?.headerActions}\n </>\n }\n />\n )}\n <SetupIncompleteBanner problems={setupResult} />\n {bannerState.show && (\n <BindingBanner\n kind=\"workflow\"\n problemCount={bannerState.problemCount}\n canEnable={bannerState.canEnable}\n pending={setEnabledMut.isPending}\n onEnable={() => setEnabledMut.mutate({ id: workflowId, enabled: true })}\n />\n )}\n <div className=\"wf-fullbleed-canvas\">\n <div className=\"wf-run-area\">\n <div className=\"wf-run-canvas\">\n <Suspense fallback={<p className=\"muted\">Loading visual editor…</p>}>\n {flowUsable && parsed ? (\n <WorkflowFlowEditor\n onConnectionResourcesChange={setConnectionResources}\n key={canvasRevision}\n // The parsed cast is safe: onChange only receives shapes we produced.\n value={parsed as unknown as Parameters<typeof WorkflowFlowEditor>[0][\"value\"]}\n onChange={(next, meta) => {\n draft.setJson(JSON.stringify(next, null, 2));\n // T1.1.1 A2.1: an edit to the graph — a canvas edit or a\n // step-config commit from `StepEditModal`, both of which\n // arrive here — means the run this canvas was showing is\n // no longer the thing the author is looking at.\n // adhoc/run-paint: a pan/zoom (`viewportOnly`) is no edit —\n // the run paint stays until an edit or the next run.\n if (!meta?.viewportOnly) setActiveRunId(null);\n }}\n apps={appsList}\n project={project ?? undefined}\n height=\"100%\"\n // A4: locked while the run this canvas is showing is still\n // in flight, unlocked again on every terminal status AND\n // when the poll itself gives up or errors.\n readOnly={runInFlight}\n // adhoc/run-paint: no `fitViewKey` — running (or dismissing\n // the run log) never moves the author's camera.\n stepProblems={stepProblems}\n // A3: each intermediate RunState reaches the canvas as it\n // arrives — the cast crosses the same opaque-`steps`\n // boundary `getRunState`'s own callers already cross (the\n // SDK's console `RunState.steps` is `Record<string,\n // unknown>` on purpose; the server's real per-step shape\n // structurally satisfies `ui`'s narrower `RunState`).\n runState={\n runQuery.data as unknown as Parameters<typeof WorkflowFlowEditor>[0][\"runState\"]\n }\n // T1.1.1 A3: a step test starts → the run this canvas was\n // showing is no longer the thing under test, so drop it on\n // the click rather than waiting for the test's result.\n onTestRun={() => setActiveRunId(null)}\n // adhoc/run-pause: ▶ runs on from the node as a real run, shown in the\n // run log beside the canvas like a header Run.\n onRunFromNode={onRunFromNode}\n />\n ) : json === \"\" ? (\n <p className=\"muted\">Loading…</p>\n ) : (\n <p className=\"muted\">Fix the JSON to render the visual editor.</p>\n )}\n </Suspense>\n </div>\n {activeRunId && (\n <div className=\"wf-run-log\" data-testid=\"wf-run-log\">\n <ExecutionLogPanel\n steps={runLogSteps}\n runError={runLogErrors.runError}\n stepErrors={runLogErrors.stepErrors}\n // T1.1.1 A4: the one explicit \"I'm done looking at this run\"\n // control — same lever as Stop, so it must work in the empty\n // branch too (the panel renders its head there as well).\n onDismiss={() => setActiveRunId(null)}\n />\n </div>\n )}\n </div>\n </div>\n {project === null && !projectPending && (\n <div role=\"alert\" className=\"error\" data-testid=\"wf-project-required\">\n No project selected — pass a <code>project</code> prop (or set the provider's project) to\n edit and save this workflow.\n </div>\n )}\n <div className=\"wf-fullbleed-foot\">\n <div className=\"row\" style={{ flexWrap: \"wrap\", alignItems: \"center\" }}>\n {/* Auto-save does not remove this button (it is the escape hatch when\n `autoSave` is off, and the only legible signal of save state when it\n is on): it flushes the pending window now, and greys out once the\n canvas matches the server. */}\n <button\n type=\"button\"\n className=\"btn\"\n disabled={project === null || !canSave || !dirty}\n onClick={draft.saveNow}\n >\n {draft.saving ? \"Saving…\" : \"Save\"}\n </button>\n {saved && <span className=\"ok\">Saved.</span>}\n </div>\n {bannerError && <div className=\"error\">{bannerError}</div>}\n {keyGuardReason && (\n <div className=\"error\" data-testid=\"wf-key-guard\">\n {keyGuardReason}\n </div>\n )}\n </div>\n\n {restoring && (\n <Modal title=\"Restoring version…\" onClose={() => {}}>\n <div className=\"modal-body\">Replacing the draft…</div>\n </Modal>\n )}\n\n <JsonToggle\n open={showJson}\n onClose={() => setShowJson(false)}\n title={`JSON — ${(parsed?.displayName as string) || \"workflow\"}`}\n mode=\"apply\"\n value={json}\n prepareApply={prepareApply}\n onApply={(next) => {\n // The buffer takes the text (the workflow turns dirty; Save or auto-save stores it as\n // for any edit) and the canvas remounts on it.\n draft.setJson(next);\n setCanvasRevision((r) => r + 1);\n // T1.1.1 A2.2 (D-2): the raw-JSON surface is an edit surface\n // too, so it clears the shown run the same way the canvas does.\n setActiveRunId(null);\n }}\n editorLabel=\"Workflow definition JSON\"\n />\n\n {draft.stale && !staleDismissed && (\n <Modal title=\"This workflow changed on the server\" onClose={() => setStaleDismissed(true)}>\n <div className=\"modal-body\">\n <p className=\"muted small\">\n Someone else — another tab, another session — saved this workflow after you opened it.\n Your save was refused rather than applied, so their work is still intact.\n </p>\n <p className=\"muted small\">\n <strong>Reload from server</strong> replaces what is on this canvas with the saved\n copy; anything you changed here and have not saved is lost.{\" \"}\n <strong>Keep editing</strong> leaves your version exactly as it is — but every save\n will be refused the same way until you reload, so copy out anything you need first.\n </p>\n </div>\n <div className=\"modal-actions\">\n <button type=\"button\" className=\"btn ghost\" onClick={() => setStaleDismissed(true)}>\n Keep editing\n </button>\n <button type=\"button\" className=\"btn\" disabled={reloading} onClick={reloadFromServer}>\n {reloading ? \"Reloading…\" : \"Reload from server\"}\n </button>\n </div>\n </Modal>\n )}\n\n {showHistory && (\n <HistoryModal\n kind=\"workflow\"\n id={workflowId}\n onClose={() => setShowHistory(false)}\n onOpenRun={onOpenRun}\n />\n )}\n\n {showStartingState && (\n <StartingStateModal\n initialState={startingState}\n onChange={(next) => patchMeta({ initialState: next })}\n onClose={() => setShowStartingState(false)}\n />\n )}\n </div>\n );\n}\n\nfunction StepTestApiProvider({\n children,\n callableHref,\n}: { children: ReactNode; callableHref?: WorkflowEditorProps[\"callableHref\"] }) {\n const api = useW6WApi();\n const qc = useQueryClient();\n const theme = useContext(EmbedThemeContext);\n const wrappedApi = useMemo(() => {\n const saveStepTest = (...args: Parameters<typeof api.saveStepTest>) =>\n api.saveStepTest(...args).finally(() => {\n void qc.invalidateQueries({ queryKey: stepTestsKey(args[0], args[1]) });\n });\n const recordStepTestRun = (...args: Parameters<typeof api.recordStepTestRun>) =>\n api.recordStepTestRun(...args).finally(() => {\n void qc.invalidateQueries({ queryKey: stepTestsKey(args[0], args[1]) });\n });\n return {\n ...api,\n saveStepTest,\n recordStepTestRun,\n callableHref: callableHref ?? api.callableHref,\n };\n }, [api, qc, callableHref]);\n return (\n <W6WUIProvider api={wrappedApi} theme={theme}>\n {children}\n </W6WUIProvider>\n );\n}\n\nconst NOOP = (): void => {};\n\n/**\n * The managed workflow editor. The outermost element is `.w6w-embed-root` (pinned for the embed\n * stylesheet); everything the editor renders — header, canvas, modals, rail — stays a descendant of\n * it, and nothing goes through a portal. It fills its host container (`height: 100%`), so the host\n * decides how tall the editor is.\n *\n * `useEditorProject(props.project)` is the ONLY project source: it feeds the draft, the expression\n * scope, the rail environment and the canvas. `null` (no project) refuses — see `EditorBody`.\n */\nexport function WorkflowEditor(props: WorkflowEditorProps): ReactNode {\n const { workflowId, initialRunId, onNavigate = NOOP, slots } = props;\n const project = useEditorProject(props.project);\n // Every load starts here when the host asks for the default project: saving still refuses until\n // it resolves, but the \"no project\" notice would only flash on the way, so it waits.\n const providerStatus = useEmbedProject().status;\n const projectPending = props.project === undefined && providerStatus === \"resolving\";\n const railNavigate = useCallback(\n (to: RailNavigation) => {\n if (to.type === \"list\") onNavigate({ type: \"list\" });\n else if (to.kind === \"workflow\") onNavigate({ type: \"workflow\", id: to.id });\n },\n [onNavigate],\n );\n return (\n <div\n className=\"w6w-embed-root\"\n style={{ display: \"flex\", width: \"100%\", height: \"100%\", minHeight: 0 }}\n >\n <EditorShell\n project={project}\n onNavigate={railNavigate}\n rail={props.rail}\n storageKey={project === null ? null : `w6w.rail.embed.${project}`}\n >\n <StepTestApiProvider callableHref={props.callableHref}>\n <EditorBody\n workflowId={workflowId}\n project={project}\n projectPending={projectPending}\n initialRunId={initialRunId}\n onNavigate={onNavigate}\n slots={slots}\n />\n </StepTestApiProvider>\n </EditorShell>\n </div>\n );\n}\n"],"names":["EditableTitle","title","value","placeholder","maxLength","ariaLabel","onChange","onBlur","jsx","e","ExecutionProfileHeader","onBack","backLabel","titleAdornment","actions","jsxs","historyOpenRun","kind","onOpenRun","onClose","execution","HistoryModal","props","id","filters","setFilters","useState","EMPTY_HISTORY_FILTERS","onOpenInEditor","Modal","IconButton","HistoryView","JsonToggleButton","JsonToggle","ApplyJsonDialog","DisconnectedJsonDialog","JsonEditorFill","JsonEditor","prepareApply","onApply","editorLabel","text","setText","applied","setApplied","restored","setRestored","confirming","setConfirming","check","useMemo","dirty","requestClose","apply","t","Fragment","guard","onSave","saving","error","guardReason","sameWorkflowDefinition","a","b","canonical","key","item","definition","_status","rest","BindingBanner","problemCount","canEnable","onEnable","pending","createElement","EditorShell","project","onNavigate","rail","storageKey","tools","editorRailTools","children","enclosed","useHasWorkspace","body","RailEnvProvider","ProjectExpressionScope","RightRail","WorkspaceProvider","PublishTooltip","message","disabled","useId","open","setOpen","event","SetupIncompleteBanner","problems","nodeLabel","entries","items","n","STARTING_DATA_PROBLEM_TEXT","StartingStateModal","options","useExpressionOptions","ExpressionEditorModal","result","startingDataForSave","issue","validateInitialState","next","ID_RE","TITLE_PLACEHOLDER","PROTECTED_WORKFLOW_FIELDS","jsonErrorOffset","i","ws","fail","lit","word","ch","str","k","NUM","num","close","at","jsonSyntaxError","before","line","column","isObj","v","workflowShapeError","def","nodes","ids","p","end","prepareWorkflowJsonApply","loaded","front","f","had","has","_drop","shape","mergeStepProblems","bindingProblems","loopProblems","stateProblems","setupProblems","out","conn","source","list","WorkflowFlowEditor","lazy","m","EditorBody","workflowId","projectPending","initialRunId","slots","apiClient","useEmbedClient","api","useW6WApi","setError","showJson","setShowJson","canvasRevision","setCanvasRevision","showHistory","setShowHistory","showStartingState","setShowStartingState","reloading","setReloading","loadedKey","setLoadedKey","autoSaveRef","useRef","publishReasonRef","saveGuard","useCallback","d","workflowKeyEditAllowed","draft","useWorkflowDraft","json","parsed","canSave","useEffect","staleDismissed","setStaleDismissed","saved","setSaved","wasSaving","activeRunId","setActiveRunId","startRunMut","useStartRunMutation","runFromNodeMut","useRunFromNodeMutation","cancelRunMut","useCancelRunMutation","runQuery","useLiveRunQuery","runStatus","_a","runPollFailed","runInFlight","isRunInFlight","stateWritesQuery","useRunStateWritesQuery","runLogSteps","mapRunStateToLogSteps","runNodeMap","_b","runLogErrors","runLevelErrors","runStartingRef","runStarting","setRunStarting","runAfterFlush","action","r","ApiError","onRunClick","entry","flowHelpers","headerRunEntry","steps","triggerPreviewList","testInputSavesSettled","input","resolveHeaderRunInput","stepId","listStepTests","listTestInputs","res","onRunFromNode","nodeId","req","onStopClick","code","classifyCancelError","reloadFromServer","draftFailure","bannerError","flowUsable","displayName","settings","readSettings","startingState","readStartingData","variables","readVariables","keyEdit","keyGuardReason","workflowNodes","setFlowHelpers","canceled","app","triggerPreviews","thirdPartyAppIds","s","fetchedAppsById","useEditorApps","appsList","appActionsQueries","useQueries","appId","appActionsKey","actionParamsByKey","idx","fetched","appsById","testGatedSteps","isTestRequired","stepTestsQueries","stepTestsKey","testStatus","versionsQuery","useVersionsQuery","publishMut","usePublishMutation","publishedVersion","_c","publishedQuery","useVersionQuery","matchesPublished","definitionStatus","restoring","setRestoring","revertMut","useRevertMutation","restoreVersion","versionNumber","qc","useQueryClient","stepPassesReadFor","stepPassRefreshDue","ms","STEP_PASS_REFRESH_DELAYS_MS","workflowStepTestsKey","_d","connQueries","connectionsForAppKey","listConnectionsForApp","connByApp","q","c","findBindingProblems","varsQ","useVarsQuery","secretsQ","useSecretsQuery","constantsQ","useConstantsQuery","storesQ","useDataStoresQuery","setupResult","x","findSetupIncomplete","stepProblems","refetchedPairs","pair","hadProblemsRef","setEnabledMut","useSetEnabledMutation","bannerState","disabledBannerState","_e","validityCtx","requiredParamsFilled","publishBlockers","publishProblems","publishBusy","setPublishBusy","publishInFlight","publishBlockReason","publishDisabledReason","publishDraft","invalidReason","parsedRef","patchMeta","patch","saveMeta","commitRef","saveNowRef","onKey","wfPolicy","policyFromDefinition","onPolicyChange","policy","current","definitionWithPolicy","onOpenStartingState","openRunRef","runId","restoreVersionRef","onRestoreVersion","publishDraftRef","onPublish","authoringRef","onAuthoringSettingChange","writeSetting","onVariablesChange","variablesForSave","connectionResources","setConnectionResources","connectionResourcesRef","editConnectionResource","edit","onOpenHistory","useWorkspace","runButtonLabel","descriptionId","Suspense","meta","ExecutionLogPanel","StepTestApiProvider","callableHref","theme","useContext","EmbedThemeContext","wrappedApi","args","W6WUIProvider","NOOP","WorkflowEditor","useEditorProject","providerStatus","useEmbedProject","railNavigate","to"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAkEA,SAASA,GAAc,EAAE,OAAAC,KAA0C;AACjE,QAAM,EAAE,OAAAC,GAAO,aAAAC,GAAa,WAAAC,GAAW,WAAAC,GAAW,UAAAC,GAAU,QAAAC,MAAWN;AACvE,SACE,gBAAAO;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAU;AAAA,MACV,OAAAN;AAAA,MACA,aAAAC;AAAA,MACA,WAAAC;AAAA,MACA,MAAM,KAAK,IAAI,KAAK,IAAIF,EAAM,QAAQC,EAAY,MAAM,GAAG,EAAE;AAAA,MAC7D,cAAYE;AAAA,MACZ,UAAU,CAACI,MAAMH,EAASG,EAAE,OAAO,KAAK;AAAA,MACxC,QAAAF;AAAA,IAAA;AAAA,EAAA;AAGN;AAiBO,SAASG,GAAuB;AAAA,EACrC,QAAAC;AAAA,EACA,WAAAC;AAAA,EACA,OAAAX;AAAA,EACA,gBAAAY;AAAA,EACA,SAAAC;AACF,GAAgC;AAC9B,SACE,gBAAAC,EAAC,OAAA,EAAI,WAAU,qBACZ,UAAA;AAAA,I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