@w6w/ui 0.2.54 → 0.2.55
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/WorkflowConnectionsPanel.d.ts +5 -0
- package/dist/WorkflowFlowEditor.d.ts +3 -0
- package/dist/components/ConfirmModal.d.ts +3 -1
- package/dist/connection-app-meta-BEXlKBgV.cjs +22 -0
- package/dist/connection-app-meta-BEXlKBgV.cjs.map +1 -0
- package/dist/{node-samples-DkJL07EX.js → connection-app-meta-ZCPakGjD.js} +1685 -1565
- package/dist/connection-app-meta-ZCPakGjD.js.map +1 -0
- package/dist/flow.cjs +4 -4
- package/dist/flow.cjs.map +1 -1
- package/dist/flow.d.ts +2 -0
- package/dist/flow.mjs +2645 -2208
- package/dist/flow.mjs.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +365 -376
- package/dist/index.mjs.map +1 -1
- package/dist/workflow-connections.d.ts +49 -1
- package/package.json +1 -1
- package/src/styles/_connections.scss +64 -0
- package/src/styles/_flow.scss +6 -0
- package/src/styles.css +93 -0
- package/dist/node-samples-ChdyMBnJ.cjs +0 -22
- package/dist/node-samples-ChdyMBnJ.cjs.map +0 -1
- package/dist/node-samples-DkJL07EX.js.map +0 -1
package/dist/flow.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow.mjs","sources":["../src/CanvasContextMenu.tsx","../src/canvas-context-menu.ts","../src/canvas-types.ts","../src/canvas-utils.ts","../src/components/resolved-clip.ts","../src/components/ResolvedParams.tsx","../src/components/ScriptBindingsNotice.tsx","../src/flow-delete.ts","../src/flow-fanout.ts","../src/flow-history.ts","../src/flow-layout.ts","../src/flow-loop-colors.ts","../src/flow-node-flags.ts","../src/flow-problems.ts","../src/flow-state.ts","../src/run-visuals.ts","../src/state-shape.ts","../src/trigger-registration.ts","../src/use-app-action-defs.ts","../src/WorkflowFlowEditor.tsx"],"sourcesContent":["import { useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport type { CanvasMenuAction, CanvasMenuItem } from \"./canvas-context-menu.ts\";\n\n/**\n * The workflow canvas's right-click menu. Positioned in the editor's own box (`x`/`y` are\n * relative to it) so it inherits the editor's theme tokens, and drawn with the canvas\n * note menu's classes rather than a look of its own.\n *\n * Keyboard: focus lands on the first item; ↑/↓ (and Home/End) move, Enter or Space runs\n * the focused item, Esc or Tab closes. A greyed item stays focusable (`aria-disabled`, the\n * menu pattern's rule) but does nothing. It closes on any pointer-down outside it and on\n * a scroll anywhere; the editor closes it on a pan or zoom.\n */\nexport function CanvasContextMenu({\n x,\n y,\n items,\n onAction,\n onClose,\n}: {\n x: number;\n y: number;\n items: CanvasMenuItem[];\n onAction: (action: CanvasMenuAction) => void;\n /** `restoreFocus` is true when the menu closed from the keyboard (Esc / Tab). */\n onClose: (restoreFocus: boolean) => void;\n}) {\n const ref = useRef<HTMLDivElement>(null);\n const [pos, setPos] = useState({ left: x, top: y });\n\n // Keep the menu inside the editor box: flip left/up when it would overflow.\n useLayoutEffect(() => {\n const el = ref.current;\n const box = el?.offsetParent as HTMLElement | null;\n if (!el || !box) return;\n const w = el.offsetWidth;\n const h = el.offsetHeight;\n setPos({\n left: x + w > box.clientWidth ? Math.max(0, x - w) : x,\n top: y + h > box.clientHeight ? Math.max(0, y - h) : y,\n });\n }, [x, y]);\n\n useEffect(() => {\n ref.current\n ?.querySelector<HTMLButtonElement>(\"[role=menuitem]\")\n ?.focus({ preventScroll: true });\n }, []);\n\n useEffect(() => {\n const onDown = (e: PointerEvent) => {\n if (!ref.current?.contains(e.target as Node)) onClose(false);\n };\n const onScroll = (e: Event) => {\n if (!ref.current?.contains(e.target as Node)) onClose(false);\n };\n const onBlur = () => onClose(false);\n document.addEventListener(\"pointerdown\", onDown, true);\n document.addEventListener(\"scroll\", onScroll, true);\n document.addEventListener(\"wheel\", onScroll, { capture: true, passive: true });\n window.addEventListener(\"blur\", onBlur);\n window.addEventListener(\"resize\", onBlur);\n return () => {\n document.removeEventListener(\"pointerdown\", onDown, true);\n document.removeEventListener(\"scroll\", onScroll, true);\n document.removeEventListener(\"wheel\", onScroll, true);\n window.removeEventListener(\"blur\", onBlur);\n window.removeEventListener(\"resize\", onBlur);\n };\n }, [onClose]);\n\n const run = (item: CanvasMenuItem) => {\n if (item.disabled) return;\n onClose(false);\n onAction(item.action);\n };\n\n return (\n <div\n ref={ref}\n className=\"w6w-note-menu w6w-canvas-menu\"\n role=\"menu\"\n aria-label=\"Canvas actions\"\n data-testid=\"canvas-context-menu\"\n style={{ left: pos.left, top: pos.top }}\n onContextMenu={(e) => e.preventDefault()}\n onKeyDown={(e) => {\n // Nothing typed into the menu reaches the canvas: its Delete/Backspace handler\n // would otherwise act on the selection behind the menu.\n e.stopPropagation();\n const buttons = [\n ...(ref.current?.querySelectorAll<HTMLButtonElement>(\"[role=menuitem]\") ?? []),\n ];\n const at = buttons.indexOf(document.activeElement as HTMLButtonElement);\n const focus = (i: number) => buttons[(i + buttons.length) % buttons.length]?.focus();\n if (e.key === \"ArrowDown\") focus(at + 1);\n else if (e.key === \"ArrowUp\") focus(at < 0 ? -1 : at - 1);\n else if (e.key === \"Home\") focus(0);\n else if (e.key === \"End\") focus(-1);\n else if (e.key === \"Escape\" || e.key === \"Tab\") onClose(true);\n else if (e.key === \"Enter\" || e.key === \" \") {\n if (at >= 0) run(items[at]);\n } else return;\n e.preventDefault();\n }}\n >\n {items.map((item) => (\n <button\n key={item.action}\n type=\"button\"\n role=\"menuitem\"\n tabIndex={-1}\n aria-disabled={item.disabled || undefined}\n className={`w6w-note-menu-item${item.danger ? \" danger\" : \"\"}${item.separated ? \" separated\" : \"\"}`}\n data-action={item.action}\n onClick={() => run(item)}\n >\n {item.label}\n </button>\n ))}\n </div>\n );\n}\n","// The canvas right-click menu's pure half: which nodes a right-click acts on and which\n// items it offers. `CanvasContextMenu.tsx` renders it;\n// `WorkflowFlowEditor` owns the actions.\n\n/** A right-click's flow-space drop point plus the nodes its node actions apply to. */\nexport interface CanvasMenuTarget {\n /** Where an added node lands — the click converted to flow coordinates. */\n flow: { x: number; y: number };\n /** Node ids Duplicate / Delete act on. Empty on a bare-canvas right-click. */\n nodeIds: string[];\n}\n\nexport type CanvasMenuAction = \"duplicate\" | \"delete\" | \"add-node\" | \"add-trigger\";\n\nexport interface CanvasMenuItem {\n action: CanvasMenuAction;\n label: string;\n disabled: boolean;\n danger?: boolean;\n /** A divider is drawn above this item. */\n separated?: boolean;\n}\n\n/**\n * The nodes a right-click acts on. A node that is part of the current selection acts on\n * the whole selection; any other node acts on itself alone (and becomes the selection).\n * The bare canvas acts on whatever is selected.\n */\nexport function contextMenuTargets(selectedIds: readonly string[], nodeId?: string): string[] {\n if (nodeId === undefined) return [...selectedIds];\n return selectedIds.includes(nodeId) ? [...selectedIds] : [nodeId];\n}\n\n/** Duplicate + Delete when nodes are targeted, then Add node + Add trigger. All greyed when read-only. */\nexport function canvasMenuItems(nodeIds: readonly string[], readOnly: boolean): CanvasMenuItem[] {\n const items: CanvasMenuItem[] = [];\n const n = nodeIds.length;\n if (n > 0) {\n const suffix = n > 1 ? ` ${n} nodes` : \"\";\n items.push({ action: \"duplicate\", label: `Duplicate${suffix}`, disabled: readOnly });\n items.push({ action: \"delete\", label: `Delete${suffix}`, disabled: readOnly, danger: true });\n }\n items.push({ action: \"add-node\", label: \"Add node\", disabled: readOnly, separated: n > 0 });\n items.push({ action: \"add-trigger\", label: \"Add trigger\", disabled: readOnly });\n return items;\n}\n","/** Workflow canvas (notes + sections); hand-mirror of core's `Workflow.canvas`. */\nexport interface CanvasNote {\n id: string;\n color: string;\n position: { x: number; y: number };\n size: { width: number; height: number };\n content: string;\n}\n\nexport interface CanvasSection {\n id: string;\n title: string;\n color: string;\n position: { x: number; y: number };\n size: { width: number; height: number };\n /** Member node ids; a node belongs to at most one section. */\n nodes: string[];\n}\n\nexport interface FlowCanvas {\n notes?: CanvasNote[];\n sections?: CanvasSection[];\n}\n\nexport const MAX_NOTES = 200;\nexport const MAX_SECTIONS = 200;\nexport const MAX_NOTE_BYTES = 10240;\n","import { type FlowCanvas, MAX_NOTES, MAX_NOTE_BYTES, MAX_SECTIONS } from \"./canvas-types.ts\";\n\n/** Live geometry keyed by note/section id. */\nexport interface LiveGeometry {\n [id: string]: { position?: { x: number; y: number }; size?: { width: number; height: number } };\n}\n\n/** Round every stored number to an integer. */\nexport function roundGeometry<\n T extends { x: number; y: number } | { width: number; height: number },\n>(g: T): T {\n const out: Record<string, number> = {};\n for (const [k, v] of Object.entries(g)) out[k] = Math.round(v as number);\n return out as T;\n}\n\ntype Pos = { x: number; y: number };\ntype Size = { width: number; height: number };\n\nconst isFinitePos = (p?: Pos): p is Pos => !!p && Number.isFinite(p.x) && Number.isFinite(p.y);\nconst isFiniteSize = (z?: Size): z is Size =>\n !!z && Number.isFinite(z.width) && Number.isFinite(z.height);\n\nfunction mapItems<T extends { id: string; position: Pos; size: Size }>(\n items: T[] | undefined,\n live: LiveGeometry | undefined,\n useLive: boolean,\n): T[] | undefined {\n if (!items) return items;\n return items.map((it) => {\n const l = useLive ? live?.[it.id] : undefined;\n const position = isFinitePos(l?.position) ? l.position : it.position;\n const size = isFiniteSize(l?.size) ? l.size : it.size;\n return { ...it, position: roundGeometry(position), size: roundGeometry(size) };\n });\n}\n\n/**\n * Stamp live geometry onto the stored canvas, rounded to integers. When\n * `savePosition === false` the stored canvas is returned untouched (mirrors\n * `flowToWorkflow`'s `withPosition`): not written is not erased.\n */\nexport function withCanvasGeometry(\n canvas: FlowCanvas,\n savePosition: boolean,\n live?: LiveGeometry,\n): FlowCanvas {\n if (!savePosition) return canvas;\n const out: FlowCanvas = { ...canvas };\n if (canvas.notes) out.notes = mapItems(canvas.notes, live, true);\n if (canvas.sections) out.sections = mapItems(canvas.sections, live, true);\n return out;\n}\n\n/** Remove a deleted node id from every section. */\nexport function pruneSectionMembers(canvas: FlowCanvas, deletedNodeId: string): FlowCanvas {\n if (!canvas.sections) return canvas;\n return {\n ...canvas,\n sections: canvas.sections.map((s) => ({\n ...s,\n nodes: s.nodes.filter((n) => n !== deletedNodeId),\n })),\n };\n}\n\n/** Map a renamed node id in every section. */\nexport function renameSectionMember(canvas: FlowCanvas, from: string, to: string): FlowCanvas {\n if (!canvas.sections) return canvas;\n return {\n ...canvas,\n sections: canvas.sections.map((s) => ({\n ...s,\n nodes: s.nodes.map((n) => (n === from ? to : n)),\n })),\n };\n}\n\n/** Put `nodeIds` into `sectionId`, removing them from any other section (at most one each). */\nexport function assignMembership(\n canvas: FlowCanvas,\n sectionId: string,\n nodeIds: string[],\n): FlowCanvas {\n if (!canvas.sections) return canvas;\n const moving = new Set(nodeIds);\n return {\n ...canvas,\n sections: canvas.sections.map((s) => {\n const kept = s.nodes.filter((n) => !moving.has(n));\n return s.id === sectionId\n ? { ...s, nodes: [...new Set([...kept, ...nodeIds])] }\n : { ...s, nodes: kept };\n }),\n };\n}\n\n/** Ids of every section containing the node. */\nexport function sectionsContaining(canvas: FlowCanvas, nodeId: string): string[] {\n return (canvas.sections ?? []).filter((s) => s.nodes.includes(nodeId)).map((s) => s.id);\n}\n\n/** Truncate to at most `max` UTF-8 bytes without splitting a codepoint. */\nfunction truncateBytes(text: string, max: number): string {\n const enc = new TextEncoder();\n if (enc.encode(text).length <= max) return text;\n let out = \"\";\n let used = 0;\n for (const ch of text) {\n const n = enc.encode(ch).length;\n if (used + n > max) break;\n out += ch;\n used += n;\n }\n return out;\n}\n\n/** Enforce the caps: 200 notes, 200 sections, 10240 UTF-8 bytes per note content. */\nexport function clampCanvas(canvas: FlowCanvas): FlowCanvas {\n const out: FlowCanvas = { ...canvas };\n if (canvas.notes) {\n out.notes = canvas.notes\n .slice(0, MAX_NOTES)\n .map((n) => ({ ...n, content: truncateBytes(n.content, MAX_NOTE_BYTES) }));\n }\n if (canvas.sections) out.sections = canvas.sections.slice(0, MAX_SECTIONS);\n return out;\n}\n\n/**\n * The canvas to emit. Geometry is stamped (rounded) from the live canvas when `savePosition` is\n * on; when off, every item already in `stored` keeps its STORED position/size (live edits render\n * but are not written — mirrors node positions). Items new this session keep their live geometry.\n */\nexport function persistCanvas(\n canvas: FlowCanvas,\n stored: FlowCanvas | undefined,\n savePosition: boolean,\n): FlowCanvas {\n const live: LiveGeometry = {};\n for (const it of [...(canvas.notes ?? []), ...(canvas.sections ?? [])]) {\n live[it.id] = { position: it.position, size: it.size };\n }\n const pin = <T extends { id: string; position: Pos; size: Size }>(items?: T[], old?: T[]) =>\n items?.map((it) => {\n const s = old?.find((o) => o.id === it.id);\n return s ? { ...it, position: s.position, size: s.size } : it;\n });\n const base: FlowCanvas = savePosition\n ? canvas\n : {\n ...canvas,\n ...(canvas.notes ? { notes: pin(canvas.notes, stored?.notes) } : {}),\n ...(canvas.sections ? { sections: pin(canvas.sections, stored?.sections) } : {}),\n };\n return withCanvasGeometry(base, savePosition, live);\n}\n","/**\n * Clipping for ONE resolved value's display text (Test tab, read-only rows).\n *\n * A resolved row is a SUMMARY of what the run will be sent, not a viewer for\n * it. A value that resolves from a document (`documents.*.body`) or a rendered\n * template is routinely tens of kilobytes of HTML, and pasting all of it inline\n * pushed the rest of the params — and the run's own result — off the screen\n * (human report, 2026-09-01). So a long value is clipped here and offered\n * behind a toggle; the complete value is always one click away in the `<>`\n * code view above, which is COMPLETE over every visible param by construction\n * (`resolved-json.ts`, D-2) and so must never be clipped itself.\n *\n * Plain `.ts`, no React — same pure-module-beside-the-component precedent\n * `history-scale.ts` sets for `HistoryTimeline.tsx`, so the rule is testable\n * without a JSX transpile.\n */\n\n/**\n * Characters shown before a value is clipped. Sized to a few lines at the\n * row's font — enough to recognize WHICH value resolved (the opening of an\n * HTML document, a subject line, a URL) without becoming the page.\n */\nexport const RESOLVED_VALUE_CLIP = 220;\n\n/** A clip decision: the text to render, and whether anything was withheld. */\nexport interface ClippedValue {\n /** What to show when collapsed — never longer than {@link RESOLVED_VALUE_CLIP}. */\n text: string;\n /** True when `text` is shorter than the input, i.e. a toggle is warranted. */\n clipped: boolean;\n /** The full value's length, for the toggle's own label. */\n length: number;\n}\n\n/**\n * Clip `text` for the collapsed row. At or under the budget the input is\n * returned byte-identically and `clipped` is false — a short value must never\n * grow a toggle, an ellipsis, or a trailing-whitespace trim it didn't ask for.\n *\n * Over the budget, the cut is a plain `slice` at the boundary with trailing\n * whitespace trimmed (so an ellipsis never floats a space away from the text).\n * No word-boundary search: these values are markup and JSON as often as prose,\n * where \"the last space\" is not a meaningful place to stop.\n */\nexport function clipResolvedValue(text: string): ClippedValue {\n if (text.length <= RESOLVED_VALUE_CLIP) {\n return { text, clipped: false, length: text.length };\n }\n return {\n text: text.slice(0, RESOLVED_VALUE_CLIP).trimEnd(),\n clipped: true,\n length: text.length,\n };\n}\n","import { effectiveParam } from \"@w6w/expr\";\nimport { useMemo, useState } from \"react\";\nimport { JsonEditor } from \"../JsonEditor.tsx\";\nimport { dataVarRows, flattenParams, isParamVisible } from \"../ParamsForm.tsx\";\nimport { hasParamCustomization, previewCustomization } from \"../param-customization.ts\";\nimport type { StepStartState } from \"../provider.tsx\";\nimport {\n type ResolveScope,\n type ResolvedSegment,\n buildResolveScope,\n deepEqual,\n resolveParamValue,\n} from \"../resolve-params.ts\";\nimport { resolveParamJson, resolveVarsJson } from \"../resolved-json.ts\";\nimport type { ActionParam } from \"../types.ts\";\nimport { Copyable } from \"./Copyable.tsx\";\nimport { useExpressionOptions } from \"./ExpressionOptions.tsx\";\nimport { varLabel } from \"./expression-dom.ts\";\nimport { clipResolvedValue } from \"./resolved-clip.ts\";\n\nexport interface ResolvedParamsProps {\n /** The action's declared params — same list `ParamsForm` renders on Configure. */\n params: ActionParam[];\n /** What will actually be submitted: `{ ...step.with, ...override }` — `testValues`, not `step.with`. */\n values: Record<string, unknown>;\n /** The exact object the test invoke sends as `state` — `steps.*`/`trigger.*` resolve against this. */\n testStartState?: StepStartState;\n /**\n * `\"props\"` (default) renders the filtered row list; `\"code\"` renders the\n * COMPLETE resolved-values JSON (A4/A5/D-2) — every visible param, defaults\n * included. Driven by the host's own toggle state; this component never\n * mounts a toggle of its own (D-7 — `PropertyEntryForm` already owns one on\n * the trigger arm, and two side by side is a defect, not a feature).\n */\n view?: \"props\" | \"code\";\n /**\n * Param keys the host sends as SOURCE TEXT, never resolved (`@w6w/script`'s `code`, the\n * engine's `LITERAL_PARAMS`): shown verbatim, so a `{{ }}` in them never reads as a value.\n */\n literalKeys?: readonly string[];\n}\n\n/**\n * Read-only sibling of `ParamsForm`: for every configured param, shows the\n * value it resolves to against the current test scope instead of an editable\n * widget. Mounts no `contentEditable`, no `ƒx` button, no input, and never\n * calls an `onChange` — this is the Test tab's \"what will actually be sent\"\n * view, not a second place to edit params.\n *\n * Reuses `flattenParams`/`isParamVisible` from `ParamsForm.tsx` (same order +\n * visibility the Configure tab uses) rather than re-flattening sections, and\n * the static chip vocabulary (`varLabel`, `.w6w-expr-chip-*`) rather than\n * `expression-dom.ts`'s DOM-painting, which is for the editable field.\n */\nexport function ResolvedParams({\n params,\n values,\n testStartState,\n view = \"props\",\n literalKeys,\n}: ResolvedParamsProps) {\n const { sampleValues, nodeConfig, nodeMeta } = useExpressionOptions();\n const scope = useMemo(\n () => buildResolveScope(sampleValues, testStartState, nodeConfig, nodeMeta),\n [sampleValues, testStartState, nodeConfig, nodeMeta],\n );\n const flat = flattenParams(params);\n const effective = (key: string) =>\n values[key] !== undefined ? values[key] : flat.find((p) => p.key === key)?.default;\n // Sections are layout-only containers with no value of their own (their\n // children, already flattened, carry the values) — skip rendering a row for\n // the section param itself, exactly as `ParamsForm`'s own `renderOne` does.\n // This is the \"visible\" row set D-2's code view is complete OVER — before\n // A1's unchanged-value filter, so the code view still carries a param the\n // list hides.\n const visibleRows = flat\n .filter((p) => p.type !== \"section\" && isParamVisible(p, effective))\n .map((p) => effectiveParam(p, effective));\n\n if (hasParamCustomization(values)) {\n const custom = previewCustomization(values.$merge, scope, literalKeys);\n const object = custom !== null && typeof custom === \"object\" && !Array.isArray(custom);\n const base = buildResolvedJson(visibleRows, values, scope, literalKeys);\n for (const [key, value] of Object.entries(values)) {\n if (key !== \"$merge\")\n base[key] = literalKeys?.includes(key) ? value : previewCustomization(value, scope);\n }\n const merged = object ? { ...base, ...custom } : base;\n return (\n <div className=\"w6w-resolved-params\">\n <p className=\"w6w-muted w6w-small\">\n {object\n ? \"JSON customization applied after form values.\"\n : `JSON customization is not available as an object in this preview (${String(custom)}). Test the step to validate it.`}\n </p>\n {view === \"code\" ? (\n <JsonEditor\n value={JSON.stringify(merged, null, 2)}\n onChange={() => {}}\n readOnly\n minHeight=\"260px\"\n height=\"100%\"\n aria-label=\"Resolved test values (JSON)\"\n />\n ) : (\n <div className=\"w6w-resolved-table\">\n {Object.entries(merged).map(([key, value]) => (\n <ResolvedParamRow\n key={key}\n label={flat.find((p) => p.key === key)?.label ?? key}\n segments={[{ status: \"resolved\", value }]}\n />\n ))}\n </div>\n )}\n </div>\n );\n }\n\n if (view === \"code\") {\n // Derived fresh on every render from `values` — no draft state — so\n // editing the incoming-state override above updates this text live,\n // exactly as it already updates the row list (A5).\n const json = buildResolvedJson(visibleRows, values, scope, literalKeys);\n return (\n <div className=\"w6w-resolved-params\">\n <JsonEditor\n value={JSON.stringify(json, null, 2)}\n onChange={() => {}}\n readOnly\n minHeight=\"260px\"\n height=\"100%\"\n aria-label=\"Resolved test values (JSON)\"\n />\n </div>\n );\n }\n\n // A1/D-1: drop a row whose effective value is deep-equal to its declared\n // default — noise the human named explicitly (an unset `Sender Name \"\"`, an\n // explicitly-false `required` boolean, an empty `{}`/array). Uniform: no\n // `required` exemption, and a key EXPLICITLY present in `with` that happens\n // to equal the default is hidden too (equality, not presence — D-1).\n const rows = visibleRows.filter((p) => !deepEqual(effective(p.key), p.default));\n\n if (visibleRows.length === 0) {\n return (\n <div className=\"w6w-resolved-params\">\n <p className=\"w6w-muted w6w-small\">This action takes no parameters.</p>\n </div>\n );\n }\n\n if (rows.length === 0) {\n return (\n <div className=\"w6w-resolved-params\">\n <p className=\"w6w-muted w6w-small\">\n Every configured value matches its default — nothing to show here. Switch to JSON to see\n the full set.\n </p>\n </div>\n );\n }\n\n return (\n // `.w6w-resolved-table` is the ONE grid this whole row list shares — each\n // `.w6w-resolved-row` below is `display: contents` and contributes its\n // two children straight into these column tracks, so every row's key\n // column lines up with every other row's.\n <div className=\"w6w-resolved-params w6w-resolved-table\">\n {rows.map((param) =>\n param.type === \"vars\" ? (\n <ResolvedVarsRow key={param.key} param={param} value={values[param.key]} scope={scope} />\n ) : (\n <ResolvedParamRow\n key={param.key}\n label={param.label ?? param.key}\n segments={\n literalKeys?.includes(param.key)\n ? [{ status: \"resolved\", value: effective(param.key) }]\n : resolveParamValue(effective(param.key), scope)\n }\n />\n ),\n )}\n </div>\n );\n}\n\n/**\n * D-2: the code view is COMPLETE over `rows` (every visible param — see the\n * caller — defaults included, the row set BEFORE A1's filter), one key per\n * `param.key`, each folded through {@link resolveParamJson}/{@link\n * resolveVarsJson} (never the schema, never raw `step.with`, never the\n * `{type:\"expr\",…}` envelope — A6's pinned serialization).\n */\nfunction buildResolvedJson(\n rows: ActionParam[],\n values: Record<string, unknown>,\n scope: ResolveScope,\n literalKeys?: readonly string[],\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const param of rows) {\n if (literalKeys?.includes(param.key)) {\n out[param.key] = values[param.key] !== undefined ? values[param.key] : param.default;\n } else if (param.type === \"vars\") {\n const raw = values[param.key] ?? param.default ?? [];\n const vars = dataVarRows(raw);\n out[param.key] = vars ? resolveVarsJson(vars, scope) : resolveParamJson(raw, scope);\n } else {\n out[param.key] = resolveParamJson(\n values[param.key] !== undefined ? values[param.key] : param.default,\n scope,\n );\n }\n }\n return out;\n}\n\nfunction ResolvedParamRow({ label, segments }: { label: string; segments: ResolvedSegment[] }) {\n return (\n <div className=\"w6w-resolved-row\">\n <span className=\"w6w-resolved-label\">{label}</span>\n <div className=\"w6w-resolved-value\">\n <ResolvedSegments segments={segments} />\n </div>\n </div>\n );\n}\n\n/** A `vars`-typed param: one row per configured key, each resolved independently (A5). */\nfunction ResolvedVarsRow({\n param,\n value,\n scope,\n}: {\n param: ActionParam;\n value: unknown;\n scope: ResolveScope;\n}) {\n const raw = value ?? param.default ?? [];\n const rows = dataVarRows(raw);\n if (rows === null) {\n return (\n <ResolvedParamRow label={param.label ?? param.key} segments={resolveParamValue(raw, scope)} />\n );\n }\n return (\n <div className=\"w6w-resolved-row\">\n <span className=\"w6w-resolved-label\">{param.label ?? param.key}</span>\n {rows.length === 0 ? (\n <p className=\"w6w-muted w6w-small\">None configured.</p>\n ) : (\n <div className=\"w6w-stack\">\n {rows.map((row, i) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: rows have no stable id (mirrors ParamsForm's VarsField)\n <div className=\"w6w-resolved-value\" key={i}>\n <code>{row.key || \"(no key)\"}</code>\n {\" → \"}\n <ResolvedSegments segments={resolveParamValue(row.value, scope)} />\n </div>\n ))}\n </div>\n )}\n </div>\n );\n}\n\nfunction ResolvedSegments({ segments }: { segments: ResolvedSegment[] }) {\n return (\n <>\n {segments.map((seg, i) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: segments are a positional, immutable render of one value's parts\n <ResolvedSegmentView key={i} segment={seg} />\n ))}\n </>\n );\n}\n\n/** One part's worth of chrome: a static chip (for anything ref-shaped) plus its outcome. */\nfunction ResolvedSegmentView({ segment }: { segment: ResolvedSegment }) {\n switch (segment.status) {\n case \"resolved\":\n return segment.ref ? (\n <>\n <ExprChip kind=\"var\" refName={segment.ref} />\n <ResolvedValueText value={segment.value} />\n </>\n ) : (\n <ResolvedValueText value={segment.value} />\n );\n case \"unresolved\":\n // Never the ref/template text as if it were the value: the chip shows\n // only the short display LABEL (never the full ref string — the same\n // \"label ≠ ref\" precedent `expression-dom.ts` documents), and the\n // outcome is a dedicated, always-non-blank badge.\n return (\n <>\n <ExprChip kind=\"var\" refName={segment.ref} />\n <span className=\"w6w-param-unresolved\">unresolved</span>\n </>\n );\n case \"at-run\":\n // A node config key this client cannot see (the host fills it on the run): neutral.\n return (\n <>\n <ExprChip kind=\"var\" refName={segment.ref} />\n <span className=\"w6w-param-unevaluated\">resolved at run</span>\n </>\n );\n case \"not-evaluated\":\n return (\n <>\n <ExprChip kind=\"expr\" />\n <span className=\"w6w-param-unevaluated\">not evaluated</span>\n </>\n );\n case \"masked\":\n // The chip's 🔒 sigil already says \"masked\" — no separate badge needed,\n // and no ciphertext or plaintext is ever available to show here.\n return <ExprChip kind=\"secret\" refName={segment.ref} />;\n }\n}\n\n/**\n * One resolved value's text, clipped when it is long enough to take over the\n * row (`resolved-clip.ts`). A document body or a rendered template resolves to\n * tens of kilobytes of HTML, and a row that pastes all of it inline buries the\n * other params and the run's result below it (human report, 2026-09-01).\n *\n * Expanding does NOT restore the unbounded paste: the full text goes into its\n * own scrollable block (`.w6w-resolved-text-full`), so the row can never grow\n * past a few lines of the panel either way. A value inside the budget renders\n * exactly as it always did — one bare `<span>`, no toggle, no wrapper.\n */\nfunction ResolvedValueText({ value }: { value: unknown }) {\n const [expanded, setExpanded] = useState(false);\n const full = formatResolvedValue(value);\n const clip = clipResolvedValue(full);\n if (!clip.clipped) return <span>{full}</span>;\n return (\n <>\n {expanded ? (\n <Copyable value={full} label=\"Copy resolved value\" className=\"w6w-resolved-copy\">\n <pre className=\"w6w-resolved-text-full\">{full}</pre>\n </Copyable>\n ) : (\n <span>{clip.text}…</span>\n )}\n <button\n type=\"button\"\n className=\"w6w-resolved-more\"\n aria-expanded={expanded}\n onClick={() => setExpanded((e) => !e)}\n >\n {expanded ? \"Show less\" : `Show all (${clip.length.toLocaleString()} characters)`}\n </button>\n </>\n );\n}\n\nconst CHIP_SIGIL: Record<\"var\" | \"secret\" | \"expr\", string> = { var: \"◆\", secret: \"🔒\", expr: \"ƒ\" };\n\n/**\n * A read-only chip, visually consistent with `expression-dom.ts`'s\n * `makeChip` (same classes/sigils, same `varLabel` shortening) but built on a\n * plain `<span>` — no `contentEditable`, no remove button, no DOM painting.\n */\nfunction ExprChip({ kind, refName }: { kind: \"var\" | \"secret\" | \"expr\"; refName?: string }) {\n const label = kind === \"expr\" ? \"expr\" : varLabel(refName ?? \"\");\n return (\n <span className={`w6w-expr-chip w6w-expr-chip-${kind}`}>\n <span className=\"w6w-expr-chip-sigil\">{CHIP_SIGIL[kind]}</span>\n <span className=\"w6w-expr-chip-label\">{label}</span>\n </span>\n );\n}\n\n/**\n * A resolved value, formatted for display — never blank, even for the falsy\n * values `resolved` explicitly covers (`null`/`\"\"`/`false`/`0`): each renders\n * visibly distinct text so it never reads as \"nothing here\" the way an actual\n * blank would.\n */\nfunction formatResolvedValue(value: unknown): string {\n if (value === null) return \"null\";\n if (value === undefined) return \"(not set)\";\n if (value === \"\") return '\"\"';\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n","import { useEffect, useRef, useState } from \"react\";\nimport {\n type ScriptLanguage,\n convertCodeBindingsToReads,\n findCodeBindings,\n} from \"../script-bindings.ts\";\n\nfunction languageOf(values: Record<string, unknown>): ScriptLanguage {\n return values.language === \"python\" || values.language === \"typescript\"\n ? values.language\n : \"javascript\";\n}\n\nexport interface ScriptConversion {\n /** What the open-time conversion did, until Undo. */\n converted: number;\n undo: () => void;\n}\n\n/**\n * A Run script's `{{ }}` markers, converted when the step opens. The host never substitutes\n * inside code (see `script-bindings.ts`), so a marker there is literal text at run time. When\n * the step opens, each convertible marker is rewritten to the code read it names\n * (`$.get(root, ...keys)` in JavaScript/TypeScript); {@link ScriptBindingsNotice} says so,\n * with Undo. Runs once per mount of the step editor, so after Undo the code stays as it was\n * until the step is opened again. Read-only (or not a script), nothing is rewritten.\n */\nexport function useScriptConversion({\n enabled,\n values,\n onChange,\n}: {\n /** A writable `@w6w/script` step. */\n enabled: boolean;\n /** The step's `with`: `code`, `language`, `input`. */\n values: Record<string, unknown>;\n onChange: (next: Record<string, unknown>) => void;\n}): ScriptConversion | null {\n const [done, setDone] = useState<{\n original: string;\n converted: number;\n } | null>(null);\n const ran = useRef(false);\n const code = typeof values.code === \"string\" ? values.code : \"\";\n\n useEffect(() => {\n if (!enabled || ran.current) return;\n ran.current = true;\n const r = convertCodeBindingsToReads(code, languageOf(values));\n if (r.converted === 0) return;\n setDone({ original: code, converted: r.converted });\n onChange({ ...values, code: r.code });\n }, [enabled, code, values, onChange]);\n\n if (!done) return null;\n return {\n converted: done.converted,\n undo: () => {\n onChange({ ...values, code: done.original });\n setDone(null);\n },\n };\n}\n\n/**\n * The quiet line under a Run script's Configure tab: \"Converted 2 references to code reads ·\n * Undo\" after the open-time conversion, and, for any marker still in the code, that it stays\n * literal text. Renders nothing otherwise.\n */\nexport function ScriptBindingsNotice({\n values,\n conversion,\n readOnly,\n}: {\n /** The step's `with`: `code`, `language`. */\n values: Record<string, unknown>;\n conversion: ScriptConversion | null;\n readOnly?: boolean;\n}) {\n const code = typeof values.code === \"string\" ? values.code : \"\";\n const done = conversion;\n const left = findCodeBindings(code, languageOf(values)).length;\n if (!done && left === 0) return null;\n return (\n <output className=\"w6w-hint w6w-script-converted\">\n {done && (\n <>\n Converted {done.converted} reference{done.converted === 1 ? \"\" : \"s\"} to code reads\n {!readOnly && (\n <>\n {\" · \"}\n <button type=\"button\" className=\"w6w-script-converted-undo\" onClick={done.undo}>\n Undo\n </button>\n </>\n )}\n {left > 0 && \" · \"}\n </>\n )}\n {left > 0 && (\n <>\n {left} <code>{\"{{ }}\"}</code> left in the code stay\n {left === 1 ? \"s\" : \"\"} literal text — read {left === 1 ? \"it\" : \"them\"} from{\" \"}\n <code>state</code>, or bind under Custom input\n </>\n )}\n </output>\n );\n}\n","import type { Edge } from \"@xyflow/react\";\nimport type { FlowCanvas } from \"./canvas-types.ts\";\nimport { pruneSectionMembers } from \"./canvas-utils.ts\";\nimport { bridgeDeletedBodyStep, deleteStepMessage, isForeachStep, loopBody } from \"./flow-loop.ts\";\nimport type { StepNode } from \"./flow-utils.ts\";\n\nexport interface FlowDeleteSelection {\n nodeIds: string[];\n edgeIds: string[];\n}\n\n/** Capture the full selection, independently of the first item shown in the side panel. */\nexport function selectedFlowElements(nodes: StepNode[], edges: Edge[]): FlowDeleteSelection {\n return {\n nodeIds: nodes.filter((n) => n.selected).map((n) => n.id),\n edgeIds: edges.filter((e) => e.selected).map((e) => e.id),\n };\n}\n\n/** Apply the entire confirmed selection before the editor emits one change/history entry. */\nexport function deleteFlowSelection(\n selection: FlowDeleteSelection,\n nodes: StepNode[],\n edges: Edge[],\n canvas: FlowCanvas,\n) {\n const nodeIds = new Set(selection.nodeIds);\n const edgeIds = new Set(selection.edgeIds);\n const removed = nodes.filter((n) => nodeIds.has(n.id));\n // Detach an entire loop before removing any selected body members: otherwise removing\n // a branching body step first could hide surviving descendants from the loop traversal.\n const ordered = [\n ...removed.filter((n) => isForeachStep(n.data.step)),\n ...removed.filter((n) => !isForeachStep(n.data.step)),\n ];\n let nextNodes = nodes;\n let nextEdges = edges;\n let nextCanvas = canvas;\n for (const node of ordered) {\n nextEdges = bridgeDeletedBodyStep(node.id, nextNodes, nextEdges);\n nextNodes = nextNodes.filter((n) => n.id !== node.id);\n nextCanvas = pruneSectionMembers(nextCanvas, node.id);\n }\n return {\n nodes: nextNodes,\n edges: nextEdges.filter((e) => !edgeIds.has(e.id)),\n canvas: nextCanvas,\n };\n}\n\nexport function flowDeleteMessage(\n selection: FlowDeleteSelection,\n nodes: StepNode[],\n edges: Edge[],\n): string {\n const nodeIds = new Set(selection.nodeIds);\n const edgeIds = new Set(selection.edgeIds);\n // Incident edges are already covered by \"their connections\"; name separately selected edges.\n const extraEdges = edges.filter(\n (e) => edgeIds.has(e.id) && !nodeIds.has(e.source) && !nodeIds.has(e.target),\n );\n const messages: string[] = [];\n if (nodeIds.size === 1) {\n messages.push(deleteStepMessage(selection.nodeIds[0], nodes, edges));\n } else if (nodeIds.size > 1) {\n messages.push(\n `Delete nodes ${[...nodeIds].map((id) => `\"${id}\"`).join(\", \")}? Their connections are removed too.`,\n );\n const detached = new Set<string>();\n for (const id of nodeIds) {\n if (!isForeachStep(nodes.find((n) => n.id === id)?.data.step)) continue;\n for (const member of loopBody(id, nodes, edges)) {\n if (!nodeIds.has(member)) detached.add(member);\n }\n }\n if (detached.size) {\n messages.push(\n `Loop body steps ${[...detached].map((id) => `\"${id}\"`).join(\", \")} stay as standalone steps.`,\n );\n }\n }\n if (extraEdges.length) {\n messages.push(\n `Delete ${extraEdges.length === 1 ? \"connection\" : \"connections\"} ${extraEdges.map((e) => `\"${e.source} → ${e.target}\"`).join(\", \")}?`,\n );\n }\n return messages.join(\" \");\n}\n","// Pure fan-out decisions for the \"Run next nodes\" control and card badge.\nimport type { Edge } from \"@xyflow/react\";\nimport { edgeLane } from \"./flow-connect.ts\";\nimport type { FlowStep } from \"./flow-types.ts\";\n\nexport type FanOutMode = \"sequential\" | \"parallel\";\n\n/**\n * `count` is the largest number of outgoing edges the node has in any ONE lane\n * (success / error); fan-out only means something at `count >= 2`.\n */\nexport function fanOutState(\n stepId: string,\n edges: readonly Edge[],\n): { enabled: boolean; count: number } {\n const per = { success: 0, error: 0 };\n for (const e of edges) {\n if (e.source !== stepId) continue;\n const lane = edgeLane(e);\n // The each lane is a loop body, not fan-out: it never counts.\n if (lane !== \"each\") per[lane]++;\n }\n const count = Math.max(per.success, per.error);\n return { enabled: count >= 2, count };\n}\n\n/** Sequential is the default, so it is expressed by the key's ABSENCE. */\nexport function setFanOut(step: FlowStep, mode: FanOutMode): FlowStep {\n const { fanOut: _drop, ...rest } = step;\n return mode === \"parallel\" ? { ...rest, fanOut: \"parallel\" } : rest;\n}\n\n/** Card-badge wording: how many next nodes run, and in which mode. */\nexport function fanOutLabel(count: number, mode: FanOutMode): string {\n return `Runs these ${count} nodes in ${mode === \"parallel\" ? \"parallel\" : \"sequence\"}`;\n}\n","import type { Edge } from \"@xyflow/react\";\nimport type { FlowCanvas } from \"./canvas-types.ts\";\nimport type { FlowStep, FlowWorkflow } from \"./flow-types.ts\";\nimport { type StepNode, flowToWorkflow, workflowToFlow } from \"./flow-utils.ts\";\n\n/** Only authored graph data. Tests, samples, run paint, selection and viewport never enter history. */\nexport interface FlowEditSnapshot {\n nodes: FlowStep[];\n edges: NonNullable<FlowWorkflow[\"edges\"]>;\n connections: NonNullable<FlowWorkflow[\"connections\"]>;\n canvas: FlowCanvas;\n /** Keep the live layout even when saving positions is switched off. */\n positions: Record<string, { x: number; y: number }>;\n}\n\nexport function captureFlowEdit(\n base: FlowWorkflow,\n nodes: StepNode[],\n edges: Edge[],\n connections: FlowEditSnapshot[\"connections\"],\n canvas: FlowCanvas,\n): FlowEditSnapshot {\n const definition = flowToWorkflow({ ...base, connections }, nodes, edges);\n return {\n nodes: definition.nodes.map(({ with: params, ...step }) =>\n params && Object.keys(params).length ? { ...step, with: params } : step,\n ),\n edges: definition.edges ?? [],\n connections: definition.connections ?? {},\n canvas,\n positions: Object.fromEntries(nodes.map((n) => [n.id, n.position])),\n };\n}\n\nexport function restoreFlowEdit(base: FlowWorkflow, snapshot: FlowEditSnapshot) {\n const graph = workflowToFlow({ ...base, ...snapshot });\n return {\n ...graph,\n nodes: graph.nodes.map((n) => ({\n ...n,\n position: snapshot.positions[n.id] ?? n.position,\n })),\n };\n}\n\n/** Bounded, editor-session history. One text-field focus session is one undoable edit. */\nexport class FlowEditHistory {\n private past: string[] = [];\n private future: string[] = [];\n private present: string;\n private group: object | undefined;\n private readonly limit: number;\n\n constructor(initial: FlowEditSnapshot, limit = 100) {\n this.limit = limit;\n this.present = JSON.stringify(initial);\n }\n\n reset(initial: FlowEditSnapshot) {\n this.present = JSON.stringify(initial);\n this.past = [];\n this.future = [];\n this.group = undefined;\n }\n\n record(snapshot: FlowEditSnapshot, group?: object) {\n const next = JSON.stringify(snapshot);\n if (next === this.present) return;\n if (!group || group !== this.group) {\n this.past.push(this.present);\n if (this.past.length > this.limit) this.past.shift();\n }\n this.present = next;\n this.group = group;\n this.future = [];\n }\n\n undo(): FlowEditSnapshot | undefined {\n const previous = this.past.pop();\n if (previous === undefined) return;\n this.future.push(this.present);\n this.present = previous;\n this.group = undefined;\n return JSON.parse(previous);\n }\n\n redo(): FlowEditSnapshot | undefined {\n const next = this.future.pop();\n if (next === undefined) return;\n this.past.push(this.present);\n this.present = next;\n this.group = undefined;\n return JSON.parse(next);\n }\n}\n\n/** Leave native text undo and CodeMirror's own history alone. */\nexport function isFlowTextTarget(target: EventTarget | null): boolean {\n const element = target as HTMLElement | null;\n return Boolean(\n element?.isContentEditable ||\n element?.closest?.(\n 'input, textarea, select, [contenteditable=\"true\"], [contenteditable=\"\"], [role=\"textbox\"], .cm-editor',\n ),\n );\n}\n","import type { Edge } from \"@xyflow/react\";\nimport type { FlowCanvas } from \"./canvas-types.ts\";\nimport { type StepNode, relayoutNodes } from \"./flow-utils.ts\";\n\nconst GAP = 64;\nconst SECTION_PADDING = 24;\nconst SECTION_LABEL_HEIGHT = 32;\n\ntype Rect = { x: number; y: number; width: number; height: number };\n\nfunction nodeSize(node: StepNode) {\n return {\n width: node.measured?.width ?? node.width ?? 200,\n height: node.measured?.height ?? node.height ?? 64,\n };\n}\n\nfunction overlaps(a: Rect, b: Rect) {\n return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;\n}\n\n/** Expand columns and rows for the actual cards, including trigger metadata. */\nfunction spaceNodes(nodes: StepNode[]): StepNode[] {\n const offsets = (axis: \"x\" | \"y\", dimension: \"width\" | \"height\") => {\n const extents = new Map<number, number>();\n for (const node of nodes) {\n const at = node.position[axis];\n extents.set(at, Math.max(extents.get(at) ?? 0, nodeSize(node)[dimension]));\n }\n const placed = new Map<number, number>();\n let end = Number.NEGATIVE_INFINITY;\n for (const [at, extent] of [...extents].sort(([a], [b]) => a - b)) {\n const start = Math.max(at, end);\n placed.set(at, start);\n end = start + extent + GAP;\n }\n return placed;\n };\n const x = offsets(\"x\", \"width\");\n const y = offsets(\"y\", \"height\");\n return nodes.map((node) => ({\n ...node,\n position: {\n x: x.get(node.position.x) ?? node.position.x,\n y: y.get(node.position.y) ?? node.position.y,\n },\n }));\n}\n\n/**\n * Arrange paths and their section frames together. Membership is authored data:\n * fit each frame to its members, never infer new membership from moved geometry.\n * A section spanning non-members is moved with its members below the obstruction.\n * Notes and empty sections retain their authored geometry.\n */\nexport function relayoutFlow(\n nodes: StepNode[],\n edges: Edge[],\n canvas: FlowCanvas,\n): { nodes: StepNode[]; canvas: FlowCanvas } {\n const arranged = spaceNodes(relayoutNodes(nodes, edges));\n if (!canvas.sections?.length) return { nodes: arranged, canvas };\n const byId = new Map(arranged.map((node) => [node.id, node]));\n const occupied: Rect[] = (canvas.notes ?? []).map((note) => ({ ...note.position, ...note.size }));\n // Empty frames also occupy space, even if encountered after a populated one.\n for (const section of canvas.sections) {\n if (!section.nodes.some((id) => byId.has(id))) {\n occupied.push({\n ...section.position,\n ...section.size,\n y: section.position.y - SECTION_LABEL_HEIGHT,\n height: section.size.height + SECTION_LABEL_HEIGHT,\n });\n }\n }\n const sections = canvas.sections.map((section) => {\n const memberIds = new Set(section.nodes);\n const members = arranged.filter((node) => memberIds.has(node.id));\n if (!members.length) return section;\n const x = Math.min(...members.map((node) => node.position.x)) - SECTION_PADDING;\n const y = Math.min(...members.map((node) => node.position.y)) - SECTION_PADDING;\n const right = Math.max(...members.map((node) => node.position.x + nodeSize(node).width));\n const bottom = Math.max(...members.map((node) => node.position.y + nodeSize(node).height));\n const frame = {\n x,\n y,\n width: right + SECTION_PADDING - x,\n height: bottom + SECTION_PADDING - y,\n };\n const obstacles = [\n ...occupied,\n ...[...byId.values()]\n .filter((node) => !memberIds.has(node.id))\n .map((node) => ({ ...node.position, ...nodeSize(node) })),\n ].sort((a, b) => a.y - b.y);\n for (const obstacle of obstacles) {\n const withLabel = {\n ...frame,\n y: frame.y - SECTION_LABEL_HEIGHT,\n height: frame.height + SECTION_LABEL_HEIGHT,\n };\n if (overlaps(withLabel, obstacle)) {\n frame.y = obstacle.y + obstacle.height + SECTION_PADDING + SECTION_LABEL_HEIGHT;\n }\n }\n const dy = frame.y - y;\n for (const node of members) {\n byId.set(node.id, { ...node, position: { x: node.position.x, y: node.position.y + dy } });\n }\n occupied.push({\n ...frame,\n y: frame.y - SECTION_LABEL_HEIGHT,\n height: frame.height + SECTION_LABEL_HEIGHT,\n });\n return {\n ...section,\n position: { x: frame.x, y: frame.y },\n size: { width: frame.width, height: frame.height },\n };\n });\n return {\n nodes: arranged.map((node) => byId.get(node.id) ?? node),\n canvas: { ...canvas, sections },\n };\n}\n","/**\n * Loop colours: every For each on a canvas gets its own tone, shared by its Each item\n * port, its body edges and the dots on its body steps (never the body steps' own\n * background — a step inside a loop looks like any other). The palette lives in\n * `_tokens.scss` as `--w6w-loop-1` … `--w6w-loop-{LOOP_TONES}` (light + dark), and\n * deliberately holds no red, black or green, so a loop never reads as an error port\n * or a success/taken edge.\n *\n * A tone is DERIVED from the For each's id — hashed, then probed past tones another\n * loop already took — so it survives a reload and two loops in one workflow never share\n * one (until there are more loops than tones).\n */\nimport type { Edge } from \"@xyflow/react\";\nimport type { CSSProperties } from \"react\";\nimport { isForeachStep } from \"./flow-loop.ts\";\nimport { EACH_SOURCE_HANDLE } from \"./flow-types.ts\";\nimport type { StepNode } from \"./flow-utils.ts\";\n\n/** How many `--w6w-loop-N` tokens `_tokens.scss` defines. */\nexport const LOOP_TONES = 6;\n\n/** FNV-1a over the id's UTF-16 code units — small, stable, no dependency. */\nfunction hashId(id: string): number {\n let h = 0x811c9dc5;\n for (let i = 0; i < id.length; i++) {\n h ^= id.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return h >>> 0;\n}\n\n/**\n * Tone index (1-based) per For each id. Ids are visited in sorted order so the result\n * does not depend on node order; each takes its hashed tone, or the next free one.\n */\nexport function assignLoopTones(foreachIds: Iterable<string>): Map<string, number> {\n const out = new Map<string, number>();\n let taken = new Set<number>();\n for (const id of [...new Set(foreachIds)].sort()) {\n if (taken.size === LOOP_TONES) taken = new Set();\n let tone = hashId(id) % LOOP_TONES;\n while (taken.has(tone)) tone = (tone + 1) % LOOP_TONES;\n taken.add(tone);\n out.set(id, tone + 1);\n }\n return out;\n}\n\n/** The CSS colour for a tone index. */\nexport function loopToneVar(tone: number): string {\n return `var(--w6w-loop-${tone})`;\n}\n\n/** The loops enclosing `id`, outermost first, following each For each's own `loopOf`. */\nexport function enclosingLoops(\n id: string,\n loopOfById: ReadonlyMap<string, string | undefined>,\n): string[] {\n const chain: string[] = [];\n const seen = new Set<string>([id]);\n for (let cur = loopOfById.get(id); cur && !seen.has(cur); cur = loopOfById.get(cur)) {\n seen.add(cur);\n chain.unshift(cur);\n }\n return chain;\n}\n\n/**\n * Paint each-lane edges with the colour of the loop they belong to: the For each itself\n * for its Each item link, else the loop the edge's source step runs in. Sets the\n * `--w6w-loop-color` custom property the `.w6w-edge-each` rule reads, so run-state\n * classes still compose over it. Same array when nothing needs painting.\n */\nexport function paintLoopEdges(\n edges: Edge[],\n tones: ReadonlyMap<string, number>,\n loopOfById: ReadonlyMap<string, string | undefined>,\n): Edge[] {\n if (tones.size === 0) return edges;\n return edges.map((e) => {\n if (e.data?.when !== \"each\") return e;\n const owner = e.sourceHandle === EACH_SOURCE_HANDLE ? e.source : loopOfById.get(e.source);\n const tone = owner ? tones.get(owner) : undefined;\n if (tone === undefined) return e;\n return { ...e, style: { ...e.style, \"--w6w-loop-color\": loopToneVar(tone) } as Edge[\"style\"] };\n });\n}\n\n/**\n * The colour custom property a card's root carries: a For each's own tone, read by its\n * Each item port. A loop-body step gets none — it looks exactly like a step outside a\n * loop; its dots are what mark it.\n */\nexport function loopCardStyle(\n id: string,\n tones: ReadonlyMap<string, number>,\n): CSSProperties | undefined {\n const own = tones.get(id);\n return own === undefined\n ? undefined\n : ({ \"--w6w-loop-color\": loopToneVar(own) } as CSSProperties);\n}\n\n/** What the canvas paints loops from: each For each's tone, and each step's own loop. */\nexport type LoopPaint = {\n tones: ReadonlyMap<string, number>;\n loopOf: ReadonlyMap<string, string | undefined>;\n};\n\n/**\n * A string that changes only when a loop's membership does — the memo key for\n * {@link loopPaint}, so dragging a node does not hand every card a new context value.\n */\nexport function loopPaintKey(nodes: readonly StepNode[]): string {\n const rows: [string, 0 | 1, string?][] = [];\n for (const n of nodes) {\n const foreach = isForeachStep(n.data.step);\n if (foreach || n.data.loopOf) rows.push([n.id, foreach ? 1 : 0, n.data.loopOf]);\n }\n return JSON.stringify(rows);\n}\n\n/** Rebuild the {@link LoopPaint} a {@link loopPaintKey} describes. */\nexport function loopPaint(key: string): LoopPaint {\n const rows = JSON.parse(key) as [string, 0 | 1, string?][];\n return {\n tones: assignLoopTones(rows.filter((r) => r[1] === 1).map((r) => r[0])),\n loopOf: new Map(rows.map((r) => [r[0], r[2]])),\n };\n}\n","// Per-node run flags the node toolbar toggles: PAUSE and DISABLE.\n//\n// - `disabled` is a definition field the engine reads (`Node.disabled` in @w6w/workflow-types):\n// the node is skipped in EVERY run, published and triggered included, and its outgoing edges\n// are skipped, so a node that depends only on it does not run either.\n// - `ui.paused` is editor metadata the engine never reads. Only a test run started from a node's\n// ▶ honours it: the editor sends every paused id as that run's `stopAt`, and the run stops\n// BEFORE each one (it does not execute). A published or triggered run never sees it.\n//\n// Both are written as `true` or left out — never `false`, never an empty `ui: {}` — so toggling a\n// flag on and off again leaves a definition byte-identical to the one it started from.\nimport type { FlowStep } from \"./flow-types.ts\";\n\nexport const PAUSED_LABEL = \"Paused — test runs stop before this node\";\nexport const DISABLED_LABEL = \"Disabled — skipped in every run\";\n\nexport function isPausedStep(step: FlowStep): boolean {\n return step.ui?.paused === true;\n}\n\nexport function isDisabledStep(step: FlowStep): boolean {\n return step.disabled === true;\n}\n\n/** `step` with `ui.paused` set (on) or removed (off); an emptied `ui` is dropped. */\nexport function withPaused(step: FlowStep, on: boolean): FlowStep {\n const { ui, ...rest } = step;\n const { paused: _paused, ...otherUi } = ui ?? {};\n const nextUi = on ? { ...otherUi, paused: true as const } : otherUi;\n return Object.keys(nextUi).length > 0 ? { ...rest, ui: nextUi } : rest;\n}\n\n/** `step` with `disabled: true` (on) or without the key (off). */\nexport function withDisabled(step: FlowStep, on: boolean): FlowStep {\n const { disabled: _disabled, ...rest } = step;\n return on ? { ...rest, disabled: true } : rest;\n}\n\n/**\n * The `stopAt` of a run started from `startId`'s ▶: every paused node except the start itself\n * (pressing ▶ on a paused node runs it — the pause stops runs that ARRIVE at it).\n */\nexport function pausedStopAt(steps: readonly FlowStep[], startId: string): string[] {\n return steps.filter((s) => s.id !== startId && isPausedStep(s)).map((s) => s.id);\n}\n","import { effectiveStateConfig, statePathsOverlap, staticWritePaths } from \"@w6w/expr\";\nimport type { Edge } from \"@xyflow/react\";\n/**\n * Pure loop-problem detectors and their one-click fixes (D-A2). Host-called:\n * the embed host runs `findLoopProblems` on the definition it hands the canvas\n * and passes the result as `stepProblems`; the editor renders the fix buttons\n * and calls `applyStepProblemFix` only from a click.\n *\n * Grammar: strings go through `parseRootAnchoredTemplate` / `serializeTemplate`\n * and path markers through `isDollarPath` — never a regex over raw text. Body\n * membership comes from `definitionLoops` alone (the one place that knows the\n * legacy-chain rule). Not flagged in v1: JSONLogic `$expr` `var` refs and `expr`\n * parts such as `{{ a || \"x\" }}`.\n */\nimport { parseRootAnchoredTemplate, serializeTemplate } from \"./components/expression-template.ts\";\nimport {\n type LoopRefusalReason,\n controlOwnedIds,\n definitionLoops,\n effectiveEdges,\n isEachLink,\n isForeachStep,\n loopMembership,\n loopRefusal,\n} from \"./flow-loop.ts\";\nimport {\n CONTROL_APP,\n type CanvasLane,\n type FlowStep,\n type FlowWorkflowInput,\n laneForSourceHandle,\n} from \"./flow-types.ts\";\nimport { type StepNode, normalizeInput } from \"./flow-utils.ts\";\nimport { isDollarPath } from \"./resolve-params.ts\";\nimport type { StepProblem, StepProblems } from \"./step-problems.ts\";\n\nconst ROOTS = [\"nodes\", \"steps\"] as const;\n\n/**\n * THE matcher: is `ref` a reference to foreach `foreachId`'s output, and what\n * does it become inside the loop. `R.F.output` → `foreach.item`, `R.F.output.<rest>`\n * → `foreach.item.<rest>`, `R.F.output[<rest>` → `foreach.item[<rest>`. Segment\n * boundary only: `…outputs` and `for_each_10` never match.\n */\nexport function loopOutputRef(ref: string, foreachId: string): string | null {\n for (const root of ROOTS) {\n const prefix = `${root}.${foreachId}.output`;\n if (!ref.startsWith(prefix)) continue;\n const rest = ref.slice(prefix.length);\n if (rest === \"\" || rest[0] === \".\" || rest[0] === \"[\") return `foreach.item${rest}`;\n }\n return null;\n}\n\n/**\n * Walk `v` depth-first (key order, then index order), rewriting every matching ref\n * and pushing each distinct matched ref string onto `refs`. Returns the SAME\n * reference when nothing matched (structure-shared otherwise). Never mutates.\n */\nfunction rewrite(v: unknown, foreachId: string, refs: string[]): unknown {\n if (typeof v === \"string\") {\n if (!v.includes(\"{{\")) return v;\n const parts = parseRootAnchoredTemplate(v);\n let hit = false;\n const next = parts.map((p) => {\n if (p.kind !== \"var\" || p.ref === undefined) return p;\n const to = loopOutputRef(p.ref, foreachId);\n if (to === null) return p;\n hit = true;\n if (!refs.includes(p.ref)) refs.push(p.ref);\n return { ...p, ref: to };\n });\n return hit ? serializeTemplate(next) : v;\n }\n if (isDollarPath(v)) {\n const path = v.$;\n if (typeof path !== \"string\") return v;\n const to = loopOutputRef(path, foreachId);\n if (to === null) return v;\n if (!refs.includes(path)) refs.push(path);\n return { $: to };\n }\n if (Array.isArray(v)) {\n let changed = false;\n const out = v.map((el) => {\n const n = rewrite(el, foreachId, refs);\n if (n !== el) changed = true;\n return n;\n });\n return changed ? out : v;\n }\n if (typeof v === \"object\" && v !== null) {\n let changed = false;\n const out: Record<string, unknown> = {};\n for (const [k, el] of Object.entries(v)) {\n const n = rewrite(el, foreachId, refs);\n if (n !== el) changed = true;\n out[k] = n;\n }\n return changed ? out : v;\n }\n return v;\n}\n\n/** A whole-value ref: a string that parses to exactly one `var` part, or `{ \"$\": string }`. */\nfunction isWholeRef(v: unknown): boolean {\n if (typeof v === \"string\") {\n if (!v.includes(\"{{\")) return false;\n const parts = parseRootAnchoredTemplate(v);\n return parts.length === 1 && parts[0].kind === \"var\";\n }\n return isDollarPath(v) && typeof v.$ === \"string\";\n}\n\n/** `items` is a list of exactly one whole-value ref — it loops once over a list of one list. */\nfunction isWrappedItems(items: unknown): items is unknown[] {\n return Array.isArray(items) && items.length === 1 && isWholeRef(items[0]);\n}\n\n/**\n * The loop problems of a stored definition, keyed by step id. Never throws and\n * never mutates: any input `workflowToFlow` would reject gives `{}` (it runs in a\n * host memo with no error boundary).\n */\nexport function findLoopProblems(input: FlowWorkflowInput): StepProblems {\n try {\n const wf = normalizeInput(input);\n if (!Array.isArray(wf.nodes)) return {};\n const out: StepProblems = {};\n const add = (id: string, p: StepProblem) => {\n const list = Object.hasOwn(out, id) ? out[id] : [];\n list.push(p);\n out[id] = list;\n };\n const byId = new Map(wf.nodes.map((s) => [s.id, s]));\n for (const [fid, loop] of Object.entries(definitionLoops(wf))) {\n const f = byId.get(fid);\n if (f && isWrappedItems(f.with?.items)) {\n add(fid, {\n code: \"foreach_wrapped_items\",\n fix: { kind: \"unwrap_items\", label: \"Unwrap Items\" },\n });\n }\n if (\"invalid\" in loop) {\n add(fid, { code: \"loop_body_invalid\", reason: { ...loop.invalid } });\n continue;\n }\n for (const id of loop.body) {\n const step = byId.get(id);\n if (!step?.with) continue;\n const refs: string[] = [];\n rewrite(step.with, fid, refs);\n if (refs.length > 0) {\n add(id, {\n code: \"foreach_body_refs_output\",\n foreachId: fid,\n refs,\n fix: { kind: \"use_current_item\", foreachId: fid, label: \"Use Current item\" },\n });\n }\n }\n }\n return out;\n } catch {\n return {};\n }\n}\n\n/** One editor-side parallel-write warning — the engine's `StateWriteWarning`, this code only. */\nexport interface StateParallelWrite {\n code: \"state_parallel_write\";\n nodes: string[];\n path: string[];\n}\n\n/** The ids inside one `@w6w/control` `parallel` branch (strings at any array depth). */\nfunction branchIds(branch: unknown): Set<string> {\n const out = new Set<string>();\n const collect = (v: unknown) => {\n if (typeof v === \"string\") out.add(v);\n else if (Array.isArray(v)) for (const el of v) collect(el);\n };\n collect(branch);\n return out;\n}\n\n/**\n * The editor mirror of the engine's plan-time parallel-write warning (R16, plan\n * §2.3; proven equal on `core/packages/expr/tests/fixtures/state-write-conflicts.json`).\n * Two writers are concurrent iff they sit in different branches of one\n * `@w6w/control` `parallel`; else never when they share an anchor (outermost\n * owning control, else the step) or one anchor reaches the other; else iff one\n * `fanOut: \"parallel\"` step has two distinct outgoing edges in the SAME lane\n * whose targets reach the two anchors. Each overlapping pair of static write\n * paths gives one warning on the shorter path; deduped, sorted by the engine's\n * order (`code`, then `nodes`, then `path`). Never throws (→ `[]`), never mutates.\n */\nexport function stateWriteConflicts(input: FlowWorkflowInput): StateParallelWrite[] {\n try {\n const wf = normalizeInput(input);\n if (!Array.isArray(wf.nodes)) return [];\n const steps = wf.nodes.filter(\n (s): s is FlowStep => typeof s === \"object\" && s !== null && typeof s.id === \"string\",\n );\n const edges = effectiveEdges({ ...wf, nodes: steps }).filter(\n (e) => typeof e?.from === \"string\" && typeof e?.to === \"string\",\n );\n\n // Writers and their static paths, in node order.\n const writers: Array<{ id: string; paths: string[][] }> = [];\n for (const s of steps) {\n try {\n const paths = staticWritePaths(effectiveStateConfig(s.uses?.app, s.uses?.action, s.state));\n if (paths.length > 0) writers.push({ id: s.id, paths });\n } catch {\n // An unreadable `state` writes nothing statically; the save route reports it.\n }\n }\n if (writers.length < 2) return [];\n\n // Owner (direct owning control) and anchor (outermost owning control, else self).\n const owner = new Map<string, string>();\n for (const s of steps) {\n for (const id of controlOwnedIds(s)) if (!owner.has(id)) owner.set(id, s.id);\n }\n const chain = (id: string): string[] => {\n const out = [id];\n let cur = id;\n while (owner.has(cur)) {\n cur = owner.get(cur) as string;\n if (out.includes(cur)) break;\n out.push(cur);\n }\n return out;\n };\n const anchor = (id: string): string => {\n const c = chain(id);\n return c[c.length - 1];\n };\n\n // Reachability over every edge (all lanes, each-links included), non-reflexive.\n const succ = new Map<string, string[]>();\n for (const e of edges) {\n const list = succ.get(e.from) ?? [];\n list.push(e.to);\n succ.set(e.from, list);\n }\n const reachCache = new Map<string, Set<string>>();\n const reach = (from: string): Set<string> => {\n const hit = reachCache.get(from);\n if (hit) return hit;\n const seen = new Set<string>();\n const stack = [...(succ.get(from) ?? [])];\n while (stack.length > 0) {\n const n = stack.pop() as string;\n if (seen.has(n)) continue;\n seen.add(n);\n for (const m of succ.get(n) ?? []) stack.push(m);\n }\n reachCache.set(from, seen);\n return seen;\n };\n const reachesRefl = (from: string, to: string) => from === to || reach(from).has(to);\n\n // (i) `@w6w/control` parallel branches.\n const parallels = steps\n .filter((s) => s.uses?.app === CONTROL_APP && s.uses.action === \"parallel\")\n .map((s) => {\n const branches = s.with?.branches;\n return Array.isArray(branches) ? branches.map(branchIds) : [];\n });\n const branchOf = (branches: Set<string>[], id: string): number => {\n for (const c of chain(id)) {\n const i = branches.findIndex((b) => b.has(c));\n if (i >= 0) return i;\n }\n return -1;\n };\n\n // (iv) fan-out points: per parallel step, its same-lane outgoing edge groups.\n const fanGroups: string[][] = [];\n for (const s of steps) {\n if (s.fanOut !== \"parallel\") continue;\n const lanes = new Map<string, string[]>();\n for (const e of edges) {\n if (e.from !== s.id || isEachLink(e)) continue;\n const lane = e.when ?? \"success\";\n const list = lanes.get(lane) ?? [];\n list.push(e.to);\n lanes.set(lane, list);\n }\n for (const targets of lanes.values()) if (targets.length >= 2) fanGroups.push(targets);\n }\n\n const concurrent = (a: string, b: string): boolean => {\n for (const branches of parallels) {\n const ia = branchOf(branches, a);\n const ib = branchOf(branches, b);\n if (ia >= 0 && ib >= 0 && ia !== ib) return true;\n }\n const aa = anchor(a);\n const ab = anchor(b);\n if (aa === ab || reach(aa).has(ab) || reach(ab).has(aa)) return false;\n return fanGroups.some((targets) =>\n targets.some((ta, i) =>\n targets.some((tb, j) => i !== j && reachesRefl(ta, aa) && reachesRefl(tb, ab)),\n ),\n );\n };\n\n const seen = new Set<string>();\n const out: StateParallelWrite[] = [];\n for (let i = 0; i < writers.length; i++) {\n for (let j = i + 1; j < writers.length; j++) {\n const A = writers[i];\n const B = writers[j];\n if (A.id === B.id || !concurrent(A.id, B.id)) continue;\n for (const pa of A.paths) {\n for (const pb of B.paths) {\n if (!statePathsOverlap(pa, pb)) continue;\n const w: StateParallelWrite = {\n code: \"state_parallel_write\",\n nodes: [A.id, B.id].sort(),\n path: [...(pa.length <= pb.length ? pa : pb)],\n };\n const key = JSON.stringify([w.nodes, w.path]);\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(w);\n }\n }\n }\n }\n const cmp = (x: string, y: string) => (x < y ? -1 : x > y ? 1 : 0);\n return out.sort(\n (x, y) =>\n cmp(x.code, y.code) ||\n cmp(x.nodes.join(\",\"), y.nodes.join(\",\")) ||\n cmp(x.path.join(\".\"), y.path.join(\".\")),\n );\n } catch {\n return [];\n }\n}\n\n/**\n * `stateWriteConflicts` as canvas problems: each warning lands on both of its\n * steps, naming the other one (`with`). Never throws (→ `{}`), never mutates.\n */\nexport function findStateWriteProblems(input: FlowWorkflowInput): StepProblems {\n try {\n const out: StepProblems = {};\n for (const w of stateWriteConflicts(input)) {\n for (const n of w.nodes) {\n const list = Object.hasOwn(out, n) ? out[n] : [];\n list.push({ code: w.code, path: [...w.path], with: w.nodes.filter((x) => x !== n) });\n out[n] = list;\n }\n }\n return out;\n } catch {\n return {};\n }\n}\n\n/**\n * Apply a problem's fix to `step`, returning a new step. Re-scans the step it is\n * given (never trusts the problem's `refs` snapshot); the SAME reference comes\n * back for a problem with no fix or nothing left to fix. Never mutates.\n */\nexport function applyStepProblemFix(step: FlowStep, problem: StepProblem): FlowStep {\n if (problem.code === \"foreach_wrapped_items\") {\n const items = step.with?.items;\n if (!step.with || !isWrappedItems(items)) return step;\n return { ...step, with: { ...step.with, items: items[0] } };\n }\n if (problem.code === \"foreach_body_refs_output\") {\n if (!step.with) return step;\n const next = rewrite(step.with, problem.foreachId, []);\n if (next === step.with) return step;\n return { ...step, with: next as Record<string, unknown> };\n }\n return step;\n}\n\n/**\n * The lane of a drag, read from the handle the pointer went down on. xyflow's\n * `connectionState.fromHandle` resolves an id-less handle (the Done port) to the\n * node's FIRST handle (`out-each`), so it cannot tell Done from Each item;\n * `onConnectStart` reports the real `handleId` (null for Done). Falls back to\n * `fromHandle.id` when no matching start was recorded.\n */\nexport function dragLane(\n start: { nodeId: string | null; handleId: string | null; handleType: string | null } | null,\n fromNodeId: string,\n fromHandle: { id?: string | null; type?: string } | null | undefined,\n): CanvasLane {\n if (start && start.nodeId === fromNodeId && start.handleType === (fromHandle?.type ?? \"source\")) {\n return laneForSourceHandle(start.handleId);\n }\n return laneForSourceHandle(fromHandle?.id);\n}\n\n/**\n * The loop reason a source-handle drag dropped ON an existing node is refused for\n * (`null` when the loop rule has nothing to say). `onConnectEnd` shows it as the\n * node-anchored notice instead of opening the step builder. The lane is promoted the\n * way `planConnect` does: a success drag from a body node extends the body.\n */\nexport function connectDropRefusal(\n source: string,\n target: string,\n lane: \"success\" | \"error\" | \"each\",\n nodes: StepNode[],\n edges: Edge[],\n): LoopRefusalReason | null {\n const srcStep = nodes.find((n) => n.id === source)?.data.step;\n const inBody = loopMembership(nodes, edges)[source] !== undefined;\n const effLane = lane === \"success\" && inBody ? \"each\" : lane;\n if (effLane === \"each\" && !inBody && !isForeachStep(srcStep)) return null;\n return loopRefusal(source, target, effLane, nodes, edges);\n}\n","// Pure \"Write to state\" decisions for the step settings control (`Node.state`,\n// core/rfcs/workflow.md). JSX-free. Path, key and limit rules live in `@w6w/expr`\n// (`validateStateConfig`, `effectiveStateConfig`) — never re-implemented here.\nimport { type StateWriteConfig, effectiveStateConfig } from \"@w6w/expr\";\nimport { type FlowStep, isControlApp } from \"./flow-types.ts\";\n\nexport type StateMode = StateWriteConfig[\"mode\"];\n\n/** The five modes, in the order the control lists them. */\nexport const STATE_MODES: readonly StateMode[] = [\"off\", \"root\", \"key\", \"pick\", \"append\"];\n\nexport const STATE_MODE_LABELS: Record<StateMode, string> = {\n off: \"Off\",\n root: \"Merge at root\",\n key: \"Under a key\",\n pick: \"Pick fields\",\n append: \"Append\",\n};\n\ntype StepLike = Pick<FlowStep, \"id\" | \"uses\" | \"state\">;\n\n/** What the step writes, the default applied (R14: Set data merges at root, every other step is Off). */\nexport function stateWriteFor(step: StepLike): StateWriteConfig {\n return effectiveStateConfig(step.uses.app, step.uses.action, step.state);\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\n/**\n * The step with `config` as its state write. The default is the key's ABSENCE\n * (Off on an ordinary step, Merge at root on Set data), so writing the default\n * removes `state`. Never mutates; every other key passes through.\n */\nexport function setStateWrite<S extends StepLike>(step: S, config: StateWriteConfig): S {\n const { state: _drop, ...rest } = step;\n const fallback = effectiveStateConfig(step.uses.app, step.uses.action, undefined);\n return (deepEqual(config, fallback) ? rest : { ...rest, state: config }) as S;\n}\n\n/** The config written when the author picks `mode`: named after the step so it is valid at once. */\nexport function seedStateWrite(step: Pick<FlowStep, \"id\">, mode: StateMode): StateWriteConfig {\n switch (mode) {\n case \"key\":\n return { mode: \"key\", key: step.id };\n case \"pick\":\n return { mode: \"pick\", map: [{ from: \"\", to: step.id }] };\n case \"append\":\n return { mode: \"append\", path: step.id };\n case \"root\":\n return { mode: \"root\" };\n default:\n return { mode: \"off\" };\n }\n}\n\n/** The control shows for app steps and triggers; every control-flow step (If, For each, Parallel, Race) hides it. */\nexport function stateWriteVisible(step: Pick<FlowStep, \"uses\">): boolean {\n return !isControlApp(step.uses.app);\n}\n","/**\n * Pure derivation of a live run's canvas visuals (T1.1.1) — step node styling\n * and main-graph edge taken/skipped/untouched state. Plain functions of (run\n * state, step/edge identity) → visual state, with **no React import**, so\n * `node --test` exercises them directly (A7) the same way `flow-connect.ts`'s\n * connection rules do.\n *\n * `RunStatus`/`StepStatus`/`RunState`/`StepExecution` below are thin LOCAL\n * copies of the shapes `@w6w/workflow-types` declares\n * (`packages/w6w-workflow/packages/types/mod.ts`) — the same house idiom\n * `components/HealthStatusPill.tsx`'s `HealthPillState` uses, and the same\n * design note `flow-types.ts`'s own header already states for\n * `FlowWorkflow`/`FlowStep`: `packages/ui/package.json` has no dependency on\n * `@w6w/workflow-types` and must not gain one, so this module stays a\n * pure-presentation leaf with no transport/spec coupling. A caller who\n * already has the real `RunState`/`StepExecution` is structurally compatible\n * for free.\n */\nimport { type CanvasLane, FOREACH_DONE_ROUTE } from \"./flow-types.ts\";\n\n/** Mirrors `RunStatus` in `@w6w/workflow-types`. */\nexport type RunStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"canceled\";\n/** Mirrors `StepStatus` in `@w6w/workflow-types`. */\nexport type StepStatus = \"pending\" | \"running\" | \"succeeded\" | \"failed\" | \"skipped\";\n\n/** The slice of `StepExecution` this module reads. */\nexport interface StepExecution {\n status: StepStatus;\n /** Why a `skipped` step did not run; `\"not_on_path\"` = never part of this run (no paint). */\n skipReason?: string;\n output?: unknown;\n /** For each only (I3): per-iteration body-step records, keyed by body-step id. */\n iterations?: ReadonlyArray<{ nodes?: Record<string, { status: StepStatus }> }>;\n}\n\n/** The slice of `RunState` this module reads — steps keyed by step id, same\n * as the engine's own `RunState.steps`. */\nexport interface RunState {\n status: RunStatus;\n /** Canonical per-node records (D2). */\n nodes?: Record<string, StepExecution>;\n /** Legacy alias of `nodes`; read as `nodes ?? steps` (un-upgraded server). */\n steps?: Record<string, StepExecution>;\n}\n\nfunction execOf(runState: RunState, id: string): StepExecution | undefined {\n return (runState.nodes ?? runState.steps)?.[id];\n}\n\n/** A step on another path — not downstream of the fired trigger, or outside a run-from-node\n * scope. It was never part of this run, so it and its edges get no run paint at all. */\nfunction offPath(runState: RunState, id: string): boolean {\n const rec = execOf(runState, id);\n return rec?.status === \"skipped\" && rec.skipReason === \"not_on_path\";\n}\n\nconst RUN_ENDED: ReadonlySet<RunStatus> = new Set([\"succeeded\", \"failed\", \"canceled\"]);\n\n/**\n * A step node's rendered state — exactly the five {@link StepStatus} values\n * plus `\"no-run\"` (A2): `runState` omitted ⇒ `\"no-run\"` (this canvas isn't\n * showing any run). A step present in `runState.steps` renders its own\n * recorded status; a step the run hasn't reached yet has no entry there at\n * all (only steps that were actually started/skipped get a `StepExecution` —\n * see the engine's `recordSkipped`), so absence reads as `\"pending\"`.\n */\nexport type StepVisualState = \"no-run\" | StepStatus;\n\n/**\n * The rendered state for step `stepId` under `runState` — the StepStatus\n * half of A3's RunStatus × StepStatus mapping. Pure function of the run's own\n * step records; no additional data needed (`GET /runs/:id` already returns\n * everything this reads). A step whose record says `skipReason: \"not_on_path\"` (or whose\n * enclosing loop's does) was never part of the run: `\"no-run\"`, the unpainted look.\n */\nexport function stepVisualState(\n runState: RunState | undefined,\n stepId: string,\n loops: readonly string[] = [],\n): StepVisualState {\n // `loops`: the For each steps enclosing `stepId` — a body step of a loop on another path is\n // off the path too.\n if (!runState || [...loops, stepId].some((id) => offPath(runState, id))) return \"no-run\";\n const own = execOf(runState, stepId);\n if (own) return own.status;\n // A For each body node has no record of its own (D-R1): derive from the owning\n // loop's iterations — failed > running > succeeded > skipped, else pending.\n const seen = new Set<StepStatus>();\n for (const rec of Object.values(runState.nodes ?? runState.steps ?? {})) {\n if (!Array.isArray(rec?.iterations)) continue;\n for (const it of rec.iterations) {\n const s = it?.nodes?.[stepId]?.status;\n if (s) seen.add(s);\n }\n }\n for (const s of [\"failed\", \"running\", \"succeeded\", \"skipped\"] as const) {\n if (seen.has(s)) return s;\n }\n return \"pending\";\n}\n\n/** One node's non-persisted, run-aware look. Colour is never the only signal\n * (the house rule `HealthStatusPill`'s own doc comment states) — every\n * non-default state also differs from the default (`\"no-run\"`) in\n * `borderStyle`, `borderWidth`, or `opacity`. */\nexport interface StepNodeVisual {\n borderColor: string;\n borderStyle: \"solid\" | \"dashed\";\n borderWidth: number;\n opacity: number;\n}\n\nconst NO_RUN_VISUAL: StepNodeVisual = {\n borderColor: \"var(--w6w-border)\",\n borderStyle: \"solid\",\n borderWidth: 1,\n opacity: 1,\n};\n\n/**\n * The node visual for a step's {@link StepVisualState}, `runStatus`\n * (the owning run's OWN status) additionally distinguishing the `\"pending\"`\n * case — A3: a `canceled`/`failed` run's not-yet-reached steps render\n * dimmer/muted (they never will run) than a `queued`/`running` run's\n * not-yet-reached steps (they still might), even though both share the same\n * `StepVisualState`. Every token used is one of the five named in\n * `context.notes` (`--w6w-accent`/`--w6w-success`/`--w6w-danger`/\n * `--w6w-muted`/`--w6w-border`) — never a literal hex, never a different\n * token family.\n */\nexport function stepNodeVisual(state: StepVisualState, runStatus?: RunStatus): StepNodeVisual {\n const runEnded = runStatus !== undefined && RUN_ENDED.has(runStatus);\n switch (state) {\n case \"no-run\":\n return NO_RUN_VISUAL;\n case \"pending\":\n return runEnded\n ? { borderColor: \"var(--w6w-muted)\", borderStyle: \"dashed\", borderWidth: 1, opacity: 0.5 }\n : { borderColor: \"var(--w6w-border)\", borderStyle: \"dashed\", borderWidth: 1, opacity: 1 };\n case \"running\":\n return { borderColor: \"var(--w6w-accent)\", borderStyle: \"solid\", borderWidth: 2, opacity: 1 };\n case \"succeeded\":\n return {\n borderColor: \"var(--w6w-success)\",\n borderStyle: \"solid\",\n borderWidth: 2,\n opacity: 1,\n };\n case \"failed\":\n return { borderColor: \"var(--w6w-danger)\", borderStyle: \"solid\", borderWidth: 2, opacity: 1 };\n case \"skipped\":\n return {\n borderColor: \"var(--w6w-muted)\",\n borderStyle: \"dashed\",\n borderWidth: 1,\n opacity: 0.7,\n };\n default:\n return NO_RUN_VISUAL;\n }\n}\n\n// ── Edge inference (main-graph `when` edges only — no `if`/then-else\n// sub-block inference: the canvas has no rendering or authoring path for\n// that construct today, see FOLLOWUPS.md) ───────────────────────────────\n\n/** Whether a main-graph edge was taken, skipped, or left untouched by the\n * run (`undefined` — the source step hasn't been decided yet, or there is\n * no run). */\nexport type EdgeRunState = \"taken\" | \"skipped\";\n\n/**\n * Whether the edge `from --(when)--> …` was taken or skipped in `runState` —\n * computable from the run's step records alone (no engine data beyond what\n * `GET /runs/:id` already returns):\n * - `from` **succeeded**: its `\"success\"`/omitted-`when` edges are taken,\n * its `\"error\"` edges are skipped.\n * - `from` **failed**: a declared `\"error\"` edge is taken, every other\n * outgoing edge (the `\"success\"` lane) is skipped.\n * - `from` was itself **skipped** (reached only through a skipped edge —\n * the engine's own `recordSkipped`/`markOutgoingEdgesSkipped`): every\n * outgoing edge is skipped too, regardless of lane — a step that never\n * ran cannot have taken an exit.\n * - `from` is **running**, or has no record at all (not yet reached): the\n * edge's fate isn't decided yet ⇒ `undefined`.\n */\nexport function edgeRunState(\n runState: RunState | undefined,\n from: string,\n when: CanvasLane | undefined,\n route?: string,\n to?: string,\n): EdgeRunState | undefined {\n if (!runState || offPath(runState, from) || (to !== undefined && offPath(runState, to))) {\n return undefined;\n }\n const state = edgeStateFromSource(runState, from, when, route);\n // An edge into a step that was skipped was not taken, whatever its source did (a For each\n // whose body hit Stop workflow still succeeded, but nothing on Done ran).\n if (state === \"taken\" && to !== undefined && execOf(runState, to)?.status === \"skipped\") {\n return \"skipped\";\n }\n return state;\n}\n\nfunction edgeStateFromSource(\n runState: RunState,\n from: string,\n when: CanvasLane | undefined,\n route?: string,\n): EdgeRunState | undefined {\n const exec = execOf(runState, from);\n if (!exec) return undefined;\n // Each lane: a body edge's fate is not decidable from the parent's record (body\n // ids are never `RunState.nodes` keys) — only a skipped parent skips it.\n if (when === \"each\") return exec.status === \"skipped\" ? \"skipped\" : undefined;\n const lane = when ?? \"success\";\n const output = exec.output;\n // A For each's Done route is its plain success exit (a Router's routes carry `route`).\n const done =\n route === FOREACH_DONE_ROUTE && !(output && typeof output === \"object\" && \"route\" in output);\n if (route !== undefined && !done && exec.status === \"succeeded\") {\n // An If's routed edge (its False port, or an explicit \"true\") follows `matched`.\n if (output && typeof output === \"object\" && \"matched\" in output) {\n return (route === \"false\") !== (output.matched === true) ? \"taken\" : \"skipped\";\n }\n return output && typeof output === \"object\" && \"route\" in output && output.route === route\n ? \"taken\"\n : \"skipped\";\n }\n if (exec.status === \"succeeded\") return lane === \"success\" ? \"taken\" : \"skipped\";\n if (exec.status === \"failed\") return lane === \"error\" ? \"taken\" : \"skipped\";\n if (exec.status === \"skipped\") return \"skipped\";\n return undefined;\n}\n","/**\n * The workflow STATE a node can read, merged at design time: what the reference picker's\n * \"State\" section lists and what the ƒx previews resolve `state.<path>` against — no run needed.\n *\n * The shape at an anchor node = the starting data (`Workflow.initialState`), then the keys the\n * workflow's `variables` seed, then every WRITER (a node whose effective \"Write to state\" is not\n * Off) on a path that reaches the anchor, folded in the engine's order: Kahn's topological sort,\n * ties by declared node order, edges in declared order (`w6w-workflow` `plan.ts`). The writes\n * themselves come from `@w6w/expr`'s `computeStateWrites` / `foldState` — the SAME merge the\n * engine runs, never a second one here.\n *\n * A writer's output is what the editor already knows about it, in the editor's own tier order:\n * the last test output (fresh, else persisted), else the declared output (as a skeleton via\n * {@link shapeToSkeleton}), else the app's `sample`. Each field is flagged `all` when every entry\n * path into the anchor sets it (or the starting data / variables do), `some` otherwise — two\n * triggers converging on one node can each write different fields.\n *\n * Pure and JSX-free so `node --test` exercises it directly. Imports `step-preview-state.ts`\n * (for `ancestorIds`); that module never imports this one.\n */\nimport {\n type StateTree,\n type StateWriteOp,\n computeStateWrites,\n effectiveStateConfig,\n foldState,\n} from \"@w6w/expr\";\nimport type { Edge } from \"@xyflow/react\";\nimport type { ExpressionStateField } from \"./components/ExpressionOptions.tsx\";\nimport { TRIGGER_APP, internalNodeDef } from \"./flow-types.ts\";\nimport type { FlowWorkflow } from \"./flow-types.ts\";\nimport type { StepNode } from \"./flow-utils.ts\";\nimport { type NodeShape, shapeToSkeleton } from \"./node-samples.ts\";\nimport { inferOutputFields, valueAtPath } from \"./output-shape.ts\";\nimport { type StepShapeContext, ancestorIds } from \"./step-preview-state.ts\";\nimport { asFieldDefs, fieldsToParams } from \"./trigger-fields.ts\";\n\n/** The merged state at one anchor node. */\nexport interface StateShape {\n /** Every field path of the merged tree (depth/count capped like a step's output fields). */\n fields: ExpressionStateField[];\n /**\n * Preview values keyed by the ref the picker inserts (`state.<path>`), from REAL values only\n * (test outputs, the app's `sample`, starting data, variable defaults) — never a skeleton.\n */\n sampleValues: Record<string, unknown>;\n}\n\nexport interface StateShapeInput {\n /** The node whose incoming state this is (`null` → empty shape). */\n anchorId: string | null | undefined;\n nodes: StepNode[];\n edges: Edge[];\n initialState?: FlowWorkflow[\"initialState\"];\n variables?: FlowWorkflow[\"variables\"];\n /** The same shape context the picker's \"Previous steps\" projection reads. */\n shapes?: StepShapeContext;\n /** Each node's REAL output (fresh test, else persisted), for preview values. */\n previewOutputs?: Record<string, unknown>;\n}\n\nconst EMPTY: StateShape = { fields: [], sampleValues: {} };\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/**\n * The engine's run order over `nodes`/`edges`: Kahn's, the ready queue seeded in declared node\n * order, successors released in declared edge order. Nodes a cycle leaves out follow in declared\n * order (the engine refuses such a plan; the editor still has to show something).\n */\nexport function stateWriteOrder(nodes: StepNode[], edges: Edge[]): string[] {\n const ids = nodes.map((n) => n.id);\n const known = new Set(ids);\n const indegree = new Map(ids.map((id) => [id, 0]));\n const outgoing = new Map<string, string[]>(ids.map((id) => [id, []]));\n for (const e of edges) {\n if (!known.has(e.source) || !known.has(e.target)) continue;\n outgoing.get(e.source)?.push(e.target);\n indegree.set(e.target, (indegree.get(e.target) ?? 0) + 1);\n }\n const order: string[] = [];\n const ready = ids.filter((id) => indegree.get(id) === 0);\n while (ready.length > 0) {\n const id = ready.shift() as string;\n order.push(id);\n for (const to of outgoing.get(id) ?? []) {\n const d = (indegree.get(to) ?? 0) - 1;\n indegree.set(to, d);\n if (d === 0) ready.push(to);\n }\n }\n const placed = new Set(order);\n for (const id of ids) if (!placed.has(id)) order.push(id);\n return order;\n}\n\nconst DECLARED_TYPES = new Set([\"string\", \"number\", \"boolean\", \"object\", \"array\"]);\n\n/**\n * A declared `output` (`[{ key, type?, items? }]`, or a built-in node's `[{ key }]`) as a\n * {@link NodeShape}. An untyped leaf is a `string`: a `null` skeleton would DELETE the key when a\n * later writer merges into it (`foldState`'s null rule), losing a field the author can read.\n */\nfunction declaredShape(output: unknown): NodeShape | undefined {\n if (!Array.isArray(output)) return undefined;\n const root: NodeShape = { type: \"object\", fields: {} };\n let any = false;\n for (const f of output) {\n if (!isPlainObject(f) || typeof f.key !== \"string\" || f.key === \"\") continue;\n const segs = f.key.split(\".\");\n let cur = root as { type: \"object\"; fields: Record<string, NodeShape> };\n for (const seg of segs.slice(0, -1)) {\n const next = cur.fields[seg];\n if (next?.type !== \"object\") cur.fields[seg] = { type: \"object\", fields: {} };\n cur = cur.fields[seg] as typeof cur;\n }\n const t = typeof f.type === \"string\" && DECLARED_TYPES.has(f.type) ? f.type : \"string\";\n let leaf: NodeShape;\n if (t === \"array\") {\n const items = declaredShape(f.items);\n leaf = items ? { type: \"array\", items } : { type: \"array\" };\n } else if (t === \"object\") {\n leaf = declaredShape(f.fields ?? f.properties) ?? { type: \"object\", fields: {} };\n } else {\n leaf = { type: t as \"string\" | \"number\" | \"boolean\" };\n }\n cur.fields[segs[segs.length - 1]] = leaf;\n any = true;\n }\n return any ? root : undefined;\n}\n\n/**\n * What one writer outputs, for the SHAPE: its test output (fresh, else persisted), else its\n * declared output as a skeleton, else the app's `sample`. `undefined` when nothing is known.\n */\nfunction writerShapeOutput(node: StepNode, shapes: StepShapeContext): unknown {\n const step = node.data.step;\n const tested = shapes.testOutputs?.[step.id] ?? shapes.persistedOutputs?.[step.id];\n if (tested !== undefined && tested !== null) return tested;\n const { app, action } = step.uses;\n if (app === TRIGGER_APP && internalNodeDef(app, action)?.group === \"trigger\") {\n const keys = fieldsToParams(asFieldDefs(step.with?.fields)).map((p) => ({ key: p.key }));\n return shapeToSkeleton(declaredShape(keys));\n }\n const internal = internalNodeDef(app, action)?.output;\n if (internal && internal.length > 0) return shapeToSkeleton(declaredShape(internal));\n const def =\n step.uses.trigger === true ? shapes.triggerDef?.(app, action) : shapes.actionDef?.(app, action);\n const declared = declaredShape(def?.output);\n if (declared) return shapeToSkeleton(declared);\n return def?.sample;\n}\n\n/** What one writer outputs, for PREVIEW values: a real value only (never a skeleton). */\nfunction writerPreviewOutput(node: StepNode, input: StateShapeInput): unknown {\n const step = node.data.step;\n const real = input.previewOutputs?.[step.id];\n if (real !== undefined && real !== null) return real;\n const { app, action } = step.uses;\n const def =\n step.uses.trigger === true\n ? input.shapes?.triggerDef?.(app, action)\n : input.shapes?.actionDef?.(app, action);\n return def?.sample;\n}\n\n/** A starting placeholder for a variable with no default, by its declared type. */\nfunction variablePlaceholder(type: string | undefined): unknown {\n switch (type) {\n case \"number\":\n case \"integer\":\n return 0;\n case \"boolean\":\n return false;\n case \"object\":\n return {};\n case \"array\":\n return [];\n default:\n return \"\";\n }\n}\n\n/** The tree the run starts from: starting data, then the workflow's variables (later wins). */\nfunction seedTree(input: StateShapeInput, real: boolean): StateTree {\n const tree: StateTree = isPlainObject(input.initialState) ? { ...input.initialState } : {};\n for (const v of input.variables ?? []) {\n if (!v || typeof v.key !== \"string\" || v.key === \"\") continue;\n if (v.default !== undefined) tree[v.key] = v.default;\n else if (!real) tree[v.key] = variablePlaceholder(v.type);\n }\n return tree;\n}\n\n/** The field paths of `tree`, capped like a step's output fields (`inferOutputFields`). */\nfunction fieldKeys(tree: unknown): string[] {\n return (inferOutputFields(tree) ?? []).map((f) => f.key);\n}\n\n/**\n * The merged state shape a node reads — see the file header. Empty (no fields) when nothing on\n * any path into `anchorId` writes state and there is no starting data or variable.\n */\nexport function computeStateShape(input: StateShapeInput): StateShape {\n const { anchorId, nodes, edges } = input;\n if (!anchorId) return EMPTY;\n const shapes = input.shapes ?? {};\n const ancestors = ancestorIds(anchorId, edges);\n ancestors.delete(anchorId);\n const byId = new Map(nodes.map((n) => [n.id, n]));\n\n const shapeOps: StateWriteOp[] = [];\n const previewOps: StateWriteOp[] = [];\n /** field path → the writers whose own writes produce it */\n const writersOf = new Map<string, Set<string>>();\n for (const id of stateWriteOrder(nodes, edges)) {\n if (!ancestors.has(id)) continue;\n const node = byId.get(id);\n if (!node) continue;\n const { app, action } = node.data.step.uses;\n const config = effectiveStateConfig(app, action, node.data.step.state);\n if (config.mode === \"off\") continue;\n const out = writerShapeOutput(node, shapes);\n if (out !== undefined) {\n const { ops } = computeStateWrites(config, out);\n shapeOps.push(...ops);\n for (const key of fieldKeys(foldState({}, ops))) {\n const set = writersOf.get(key) ?? new Set<string>();\n set.add(id);\n writersOf.set(key, set);\n }\n }\n const real = writerPreviewOutput(node, input);\n if (real !== undefined) previewOps.push(...computeStateWrites(config, real).ops);\n }\n\n const seed = seedTree(input, false);\n const tree = foldState(seed, shapeOps);\n const keys = fieldKeys(tree);\n if (keys.length === 0) return EMPTY;\n const seeded = new Set(fieldKeys(seed));\n\n // Entry nodes: ancestors with no parent among the ancestors. A field is on ALL paths when no\n // entry reaches the anchor without passing one of its writers.\n const parents = new Map<string, string[]>();\n const children = new Map<string, string[]>();\n for (const e of edges) {\n if (!ancestors.has(e.source)) continue;\n if (!ancestors.has(e.target) && e.target !== anchorId) continue;\n parents.set(e.target, [...(parents.get(e.target) ?? []), e.source]);\n children.set(e.source, [...(children.get(e.source) ?? []), e.target]);\n }\n const entries = [...ancestors].filter((id) => !(parents.get(id) ?? []).length);\n const onAllPaths = (writers: Set<string>): boolean => {\n const seen = new Set<string>();\n const stack = entries.filter((id) => !writers.has(id));\n while (stack.length > 0) {\n const id = stack.pop() as string;\n if (id === anchorId) return false;\n if (seen.has(id)) continue;\n seen.add(id);\n for (const c of children.get(id) ?? []) if (!writers.has(c)) stack.push(c);\n }\n return true;\n };\n\n const preview = foldState(seedTree(input, true), previewOps);\n const fields: ExpressionStateField[] = [];\n const sampleValues: Record<string, unknown> = {};\n for (const key of keys) {\n const writers = writersOf.get(key) ?? new Set<string>();\n const all = seeded.has(key) || (writers.size > 0 && onAllPaths(writers));\n fields.push({ key, path: true, paths: all ? \"all\" : \"some\" });\n const v = valueAtPath(preview, key);\n if (v !== undefined) sampleValues[`state.${key}`] = v;\n }\n return { fields, sampleValues };\n}\n","// Pure display decision for a trigger node's bound Subscription\n// (rfcs/trigger-protocol.md §Lifecycle \"Subscription states\", §Observability).\n// No DOM and no React so the node test runner covers it directly.\nimport type { SubscriptionStatus, SubscriptionSummary } from \"./types.ts\";\n\nexport type RegistrationTone = \"ok\" | \"pending\" | \"danger\" | \"muted\";\n\nexport interface RegistrationDisplay {\n label: string;\n tone: RegistrationTone;\n /** `lastError.message`, only for a failed subscription that carries one. */\n error: string | null;\n /** Always set: a distinct \"never fired\" text when `lastFireAt` is null/absent/unparseable. */\n lastFire: string;\n /** True iff the subscription is `failed` AND the host can retry. */\n retryVisible: boolean;\n}\n\nconst LABELS: Record<SubscriptionStatus, { label: string; tone: RegistrationTone }> = {\n registered: { label: \"Registered\", tone: \"ok\" },\n pending: { label: \"Registering\", tone: \"pending\" },\n failed: { label: \"Registration failed\", tone: \"danger\" },\n paused: { label: \"Paused\", tone: \"muted\" },\n destroying: { label: \"Removing\", tone: \"muted\" },\n};\n\nexport const NEVER_FIRED = \"Never fired\";\n\n/** UTC, minute precision, so the text is stable across locales and test hosts. */\nexport function formatLastFire(iso: string | null | undefined): string {\n if (!iso) return NEVER_FIRED;\n const t = new Date(iso);\n if (Number.isNaN(t.getTime())) return NEVER_FIRED;\n return `Last fired ${t.toISOString().slice(0, 16).replace(\"T\", \" \")} UTC`;\n}\n\n/** Null when the summary has no known status (older server): the node shows no badge. */\nexport function registrationDisplay(\n sub: SubscriptionSummary | undefined,\n canRetry: boolean,\n): RegistrationDisplay | null {\n if (!sub?.status) return null;\n const known = LABELS[sub.status];\n if (!known) return null;\n const failed = sub.status === \"failed\";\n return {\n label: known.label,\n tone: known.tone,\n error: failed ? (sub.lastError?.message ?? null) : null,\n lastFire: formatLastFire(sub.lastFireAt),\n retryVisible: failed && canRetry,\n };\n}\n\n/** nodeId -> subscription for the node-bound ones (a null `nodeId` is workflow-level). */\nexport function subscriptionsByNode(\n subs: readonly SubscriptionSummary[],\n): Map<string, SubscriptionSummary> {\n const m = new Map<string, SubscriptionSummary>();\n for (const s of subs) if (s.nodeId) m.set(s.nodeId, s);\n return m;\n}\n\n/**\n * The app trigger nodes of a workflow value. Total over a value that has no `nodes` yet\n * (embed mounts pass a partial value): an absent list is no trigger nodes.\n */\nexport function appTriggerNodesOf<N extends { uses?: { trigger?: boolean } }>(\n nodes: readonly N[] | null | undefined,\n): N[] {\n return (nodes ?? []).filter((n) => n.uses?.trigger === true);\n}\n","/**\n * The action definitions of every app a workflow's steps use, so the editor\n * can read each upstream step's declared output shape (`output-shape.ts`)\n * without running it.\n *\n * Fetched once per app id (`getAppActions`, i.e. `GET /apps/:id`) and kept for\n * the editor's lifetime. Keyed on the sorted SET of app ids rather than\n * `nodes`' identity — `nodes` is rebuilt on every drag and keystroke. Internal\n * `@w6w/*` apps are skipped: their shapes are static (`internalNodeDef`).\n * Best-effort per app: a failed fetch contributes nothing and never breaks\n * the picker.\n */\nimport { useEffect, useRef, useState } from \"react\";\nimport { type PortsLookup, isInternalApp } from \"./flow-types.ts\";\nimport type { StepNode } from \"./flow-utils.ts\";\nimport type { W6WApi } from \"./provider.tsx\";\nimport type { ActionDef, TriggerSummary } from \"./types.ts\";\n\nexport function useAppActionDefs(api: W6WApi, nodes: StepNode[]): Record<string, ActionDef[]> {\n const [defs, setDefs] = useState<Record<string, ActionDef[]>>({});\n // Apps already requested (loaded or in flight), so a re-run fetches only new ones.\n const requested = useRef(new Set<string>());\n const appIdsKey = JSON.stringify(\n [...new Set(nodes.map((n) => n.data.step.uses.app))]\n .filter((app) => app && !isInternalApp(app))\n .sort(),\n );\n useEffect(() => {\n const missing = (JSON.parse(appIdsKey) as string[]).filter(\n (app) => !requested.current.has(app),\n );\n if (missing.length === 0) return;\n for (const app of missing) requested.current.add(app);\n // Never canceled: an app's actions don't depend on which run of this effect\n // asked for them, so a result landing after a re-key is still right, and\n // dropping it would leave that app unloaded (it is already `requested`).\n Promise.all(\n missing.map(async (app) => {\n try {\n return [app, await api.getAppActions(app)] as const;\n } catch {\n requested.current.delete(app); // let a later change retry it\n return null;\n }\n }),\n ).then((res) => {\n const loaded = res.filter((r): r is readonly [string, ActionDef[]] => r !== null);\n if (loaded.length === 0) return;\n setDefs((prev) => ({ ...prev, ...Object.fromEntries(loaded) }));\n });\n }, [api, appIdsKey]);\n return defs;\n}\n\n/**\n * The trigger definitions of every app a workflow's APP-TRIGGER nodes (`uses.trigger === true`)\n * use, so the editor can offer `trigger.event.<field>` from a trigger's declared `output` /\n * `sample` without a run. Same shape as {@link useAppActionDefs}: fetched once per app id\n * (`getAppTriggers`, optional on the api — absent means no claim), keyed on the sorted set of\n * app ids, best-effort, a failed fetch retried by a later change.\n */\nexport function useAppTriggerDefs(\n api: W6WApi,\n nodes: StepNode[],\n): Record<string, TriggerSummary[]> {\n const [defs, setDefs] = useState<Record<string, TriggerSummary[]>>({});\n const requested = useRef(new Set<string>());\n const appIdsKey = JSON.stringify(\n [\n ...new Set(\n nodes.filter((n) => n.data.step.uses.trigger === true).map((n) => n.data.step.uses.app),\n ),\n ]\n .filter((app) => app && !isInternalApp(app))\n .sort(),\n );\n useEffect(() => {\n const load = api.getAppTriggers;\n if (typeof load !== \"function\") return;\n const missing = (JSON.parse(appIdsKey) as string[]).filter(\n (app) => !requested.current.has(app),\n );\n if (missing.length === 0) return;\n for (const app of missing) requested.current.add(app);\n Promise.all(\n missing.map(async (app) => {\n try {\n return [app, await load.call(api, app)] as const;\n } catch {\n requested.current.delete(app);\n return null;\n }\n }),\n ).then((res) => {\n const loaded = res.filter((r): r is readonly [string, TriggerSummary[]] => r !== null);\n if (loaded.length === 0) return;\n setDefs((prev) => ({ ...prev, ...Object.fromEntries(loaded) }));\n });\n }, [api, appIdsKey]);\n return defs;\n}\n\n/** Build a `PortsLookup` over the fetched catalog defs (`useAppActionDefs`' result). */\nexport function portsLookupFromDefs(defs: Record<string, ActionDef[]>): PortsLookup {\n return (app, action) => defs[app]?.find((d) => d.key === action)?.ports;\n}\n","import { type StateWriteConfig, validateStateConfig } from \"@w6w/expr\";\nimport {\n Background,\n type Connection,\n // Rendered as a `<Controls>` CHILD, which the library appends after its three\n // built-ins — so the auto-layout button lands in the same stack and inherits\n // T3.1.1's `--xy-*` → `--w6w-*` bridge with no chrome of its own.\n ConnectionLineType,\n ControlButton,\n Controls,\n type Edge,\n MiniMap,\n type NodeProps,\n NodeToolbar,\n Panel,\n Position,\n ReactFlow,\n ReactFlowProvider,\n // Type-only now: `addEdge` itself is called inside `flow-connect.ts`; this file\n // only borrows its parameter type for the `onConnect` handler.\n type addEdge,\n useEdgesState,\n useNodeId,\n useNodesState,\n useReactFlow,\n useUpdateNodeInternals,\n} from \"@xyflow/react\";\nimport type { FinalConnectionState } from \"@xyflow/react\";\nimport { Handle } from \"@xyflow/react\";\nimport {\n type CSSProperties,\n type ReactNode,\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { AppPicker } from \"./AppPicker.tsx\";\nimport { CanvasContextMenu } from \"./CanvasContextMenu.tsx\";\nimport { CanvasLayer } from \"./CanvasLayer.tsx\";\nimport { ConditionEditor } from \"./ConditionEditor.tsx\";\nimport { JsonEditor } from \"./JsonEditor.tsx\";\nimport { NodeConfigForm } from \"./NodeConfigForm.tsx\";\nimport { ParamCustomization } from \"./ParamCustomization.tsx\";\nimport { ParamsForm } from \"./ParamsForm.tsx\";\nimport { PropertyEntryForm } from \"./PropertyEntryForm.tsx\";\nimport { RouterEditor } from \"./RouterEditor.tsx\";\nimport {\n AppTriggerTestNote,\n type BuiltStep,\n type ConfigView,\n ConfigViewToggle,\n StepBuilderModal,\n StepTestRun,\n type StepTestRunHandle,\n getTriggerDefs,\n requiredParamsFilled,\n} from \"./StepBuilderModal.tsx\";\nimport { StepNameEditor } from \"./StepNameEditor.tsx\";\nimport { StopEditor } from \"./StopEditor.tsx\";\nimport { TriggerFillForm } from \"./TriggerFillForm.tsx\";\nimport { WaitEditor } from \"./WaitEditor.tsx\";\nimport { pickWebhookSubscription } from \"./WebhookListenPanel.tsx\";\nimport {\n WorkflowConnectionPicker,\n WorkflowConnectionsContext,\n useWorkflowConnections,\n} from \"./WorkflowConnections.tsx\";\nimport {\n type CanvasMenuAction,\n type CanvasMenuTarget,\n canvasMenuItems,\n contextMenuTargets,\n} from \"./canvas-context-menu.ts\";\nimport type { FlowCanvas } from \"./canvas-types.ts\";\nimport {\n assignMembership,\n clampCanvas,\n persistCanvas,\n pruneSectionMembers,\n renameSectionMember,\n sectionsContaining,\n} from \"./canvas-utils.ts\";\nimport { AnchoredFlyout } from \"./components/AnchoredFlyout.tsx\";\nimport { AppIcon } from \"./components/AppIcon.tsx\";\nimport { Combobox } from \"./components/Combobox.tsx\";\nimport { ConfirmModal } from \"./components/ConfirmModal.tsx\";\nimport { Copyable } from \"./components/Copyable.tsx\";\nimport { DeleteButton } from \"./components/DeleteButton.tsx\";\nimport { EventbriteTriggerPicker } from \"./components/EventbriteTriggerPicker.tsx\";\nimport {\n type ExpressionLoopSource,\n type ExpressionOptions,\n ExpressionOptionsProvider,\n type ExpressionStepSource,\n excludeSelfStep,\n useExpressionOptions,\n} from \"./components/ExpressionOptions.tsx\";\nimport { Icon } from \"./components/Icon.tsx\";\nimport { IconButton } from \"./components/IconButton.tsx\";\nimport { InternalIcon } from \"./components/InternalIcon.tsx\";\nimport { Modal } from \"./components/Modal.tsx\";\nimport { ResolvedParams } from \"./components/ResolvedParams.tsx\";\nimport { ResultViewer } from \"./components/ResultViewer.tsx\";\nimport { ScriptBindingsNotice, useScriptConversion } from \"./components/ScriptBindingsNotice.tsx\";\nimport { eventbriteTriggerChoices } from \"./eventbrite-trigger-selection.ts\";\nimport {\n applyConnect,\n canConnect,\n connectConflict,\n connectRefusal,\n edgeLane,\n edgeWhenConflict,\n relaneRefusal,\n renameStepInEdges,\n setEdgeWhen,\n} from \"./flow-connect.ts\";\nimport {\n type FlowDeleteSelection,\n deleteFlowSelection,\n flowDeleteMessage,\n selectedFlowElements,\n} from \"./flow-delete.ts\";\n// The connection rules live in a JSX-free `.ts` module so `node --test` can run\n// them (see `flow-connect.ts`). This file is their only production caller.\nimport { fanOutLabel, fanOutState, setFanOut } from \"./flow-fanout.ts\";\nimport {\n FlowEditHistory,\n captureFlowEdit,\n isFlowTextTarget,\n restoreFlowEdit,\n} from \"./flow-history.ts\";\nimport { relayoutFlow } from \"./flow-layout.ts\";\nimport {\n type LoopPaint,\n enclosingLoops,\n loopCardStyle,\n loopPaint,\n loopPaintKey,\n loopToneVar,\n paintLoopEdges,\n} from \"./flow-loop-colors.ts\";\nimport { isForeachStep } from \"./flow-loop.ts\";\nimport { type LoopRefusalReason, loopRefusalMessage, stampLoopOf, stripBody } from \"./flow-loop.ts\";\nimport {\n DISABLED_LABEL,\n PAUSED_LABEL,\n isDisabledStep,\n isPausedStep,\n pausedStopAt,\n withDisabled,\n withPaused,\n} from \"./flow-node-flags.ts\";\nimport { applyStepProblemFix, connectDropRefusal, dragLane } from \"./flow-problems.ts\";\nimport {\n STATE_MODES,\n STATE_MODE_LABELS,\n type StateMode,\n seedStateWrite,\n setStateWrite,\n stateWriteFor,\n stateWriteVisible,\n} from \"./flow-state.ts\";\nimport {\n FOREACH_DONE_ROUTE,\n RACE_APP,\n RACE_DESCRIPTION,\n ROUTER_APP,\n ifPortLayout,\n isIfStep,\n routeFromHandle,\n routeHandle,\n routerPortLayout,\n routesForStep,\n} from \"./flow-types.ts\";\nimport {\n CALL_APP,\n CONTROL_APP,\n type CanvasLane,\n EACH_SOURCE_HANDLE,\n ERROR_SOURCE_HANDLE,\n type FlowStep,\n type FlowWorkflow,\n INTERNAL_NODES,\n type PortsLookup,\n SCRIPT_APP,\n WEBHOOK_APP,\n edgeVisuals,\n internalNodeDefaults,\n internalNodeIcon,\n internalNodeLabel,\n internalNodeParams,\n isControlApp,\n isInternalApp,\n isTriggerStep,\n laneForSourceHandle,\n nodePortsForStep,\n} from \"./flow-types.ts\";\nimport {\n type StepNode,\n findChainRoot,\n findChainTail,\n flowToWorkflow,\n idClashMessage,\n slugifyLabel,\n stepNameError,\n stepToJson,\n storedViewport,\n suggestStepId,\n withViewport,\n workflowToFlow,\n} from \"./flow-utils.ts\";\nimport {\n type NodeSample,\n indexNodeSamples,\n splitNodeOutputs,\n splitPreviewOutputs,\n} from \"./node-samples.ts\";\nimport { inferOutputFields, resolveOutputShape } from \"./output-shape.ts\";\nimport { hasParamCustomization } from \"./param-customization.ts\";\n// One implementation of the incoming-state pipeline, shared by every surface\n// that offers upstream seed chips (this file's step editor + ▶ Run collect\n// form, and StepBuilderModal's add-step Test tab) — see `step-preview-state.ts`'s\n// header comment for why this lives outside WorkflowFlowEditor.tsx.\nimport {\n type StepMeta,\n type StepStartState,\n type StepTest,\n WorkflowProjectProvider,\n useW6WApi,\n} from \"./provider.tsx\";\n// T1.1.1 — the pure run-visual derivation, no React import (`run-visuals.ts`'s\n// own header). This file is the one production caller that turns it into\n// pixels: a live-run repaint effect (in `Inner`) feeds the results into\n// `data`, and `StepNodeCard`/`ControlNodeCard` read them back off `data`.\nimport { type RunState, edgeRunState, stepNodeVisual, stepVisualState } from \"./run-visuals.ts\";\nimport { computeStateShape } from \"./state-shape.ts\";\nimport {\n type SeedSource,\n type StepShapeContext,\n declaredSamples,\n foreachTestFixture,\n foreachTestSample,\n loopItemText,\n nodeConfigSources,\n nodeConfigValues,\n nodeMetaSampleValues,\n nodeMetaValues,\n parseLoopSeed,\n resolveLoopItemsInState,\n startStateFromSeeds,\n stepBuilderLoop,\n stepBuilderUpstreamSteps,\n upstreamSampleValueSources,\n upstreamSampleValues,\n upstreamStateSources,\n} from \"./step-preview-state.ts\";\nimport {\n type StepProblem,\n type StepProblems,\n applyStepProblems,\n isConnectionBlocked,\n stepProblemTooltip,\n} from \"./step-problems.ts\";\nimport { useEffectiveTheme } from \"./theme.ts\";\nimport { asFieldDefs, fieldsToParams, seedValues } from \"./trigger-fields.ts\";\nimport {\n appTriggerNodesOf,\n registrationDisplay,\n subscriptionsByNode,\n} from \"./trigger-registration.ts\";\nimport type {\n ActionDef,\n ActionParam,\n AppSummary,\n ConnectionSummary,\n SubscriptionSummary,\n} from \"./types.ts\";\nimport { portsLookupFromDefs, useAppActionDefs, useAppTriggerDefs } from \"./use-app-action-defs.ts\";\nimport { useSeedSources } from \"./use-seed-sources.ts\";\nimport { LastUsedNote, useRememberedTestInput } from \"./use-test-input.tsx\";\nimport {\n type FlowConnections,\n centralizeConnections,\n connectionIdFor,\n defaultConnectionFor,\n selectNodeConnection,\n withConnectionRef,\n} from \"./workflow-connections.ts\";\n\n/**\n * What the \"Run on\" control does, shown on the lane panel (T1.1.1).\n *\n * An error edge is authored by DRAGGING from the step's error exit port (the\n * second, red-tinted source handle every step/control node renders below its\n * ordinary exit) — that's what stamps `sourceHandle`/`data.when` at creation\n * time (`onConnect` → `laneForSourceHandle`). This panel is not how an error\n * edge is first drawn; it is the RE-LANE affordance for an edge already drawn,\n * for when it was dragged from the wrong port. Each lane still holds one edge\n * out of an `out: 1` step, so switching an edge into a lane that's already\n * occupied re-points the incumbent (the deliberate single-slot UX).\n */\nconst LANE_HINT =\n \"Which outcome of the source node this edge carries. An error edge is drawn by dragging \" +\n \"from the node's error exit port; use this control to re-lane an edge already drawn. \" +\n \"An error edge overrides the node’s “On error” policy.\";\n\n/**\n * The step ids the refused edge id is minted from: the endpoints of the edge being\n * drawn/moved plus those of the edge already holding the id. {@link idClashMessage}\n * needs them to *determine* the cause instead of asserting one — the wording used to\n * blame a `:error` step id unconditionally, and a collision from an embedded `->`\n * therefore told the author to rename a step that did not exist (ADDENDUM Y).\n *\n * Both call sites look the sitting edge up by the id `connectConflict` /\n * `edgeWhenConflict` returned; a corrupt edge set with no such edge simply\n * contributes nothing, and the message falls back to naming no cause.\n */\nfunction clashInvolvedIds(\n edges: Edge[],\n conflictId: string,\n source: string | null | undefined,\n target: string | null | undefined,\n): (string | null | undefined)[] {\n const sitting = edges.find((e) => e.id === conflictId);\n return [source, target, sitting?.source, sitting?.target];\n}\n\n/** What kind of change an `onChange` reports — see `WorkflowFlowEditorProps.onChange`. */\nexport interface FlowChangeMeta {\n viewportOnly?: true;\n}\n\nexport interface WorkflowFlowEditorProps {\n /** The workflow being edited. The editor re-derives layout when this changes identity. */\n value: FlowWorkflow;\n /**\n * Fired whenever the user changes the graph — new nodes, edges, or step edits.\n *\n * `meta.viewportOnly` is `true` when the change is the author's pan/zoom being\n * written to `settings.viewport` and nothing else. A host that drops the shown\n * run on an edit (so the run paint stops describing a workflow that changed)\n * keeps it for these: moving the camera changes nothing that ran.\n */\n onChange: (next: FlowWorkflow, meta?: FlowChangeMeta) => void;\n /** Disable all interactions — pans/zooms are still enabled. */\n readOnly?: boolean;\n /** Height of the editor viewport. Defaults to 480px. */\n height?: string | number;\n /**\n * Registered apps, used to render each action node with its owning app's icon,\n * display name, and version. A step only carries `uses.app` (an id), so the\n * card joins that id against this list. Optional — unknown/absent apps degrade\n * to an initials tile with no version. Metadata is looked up at render time and\n * never stored on nodes, so it can't corrupt round-tripping back to a workflow.\n */\n apps?: AppSummary[];\n /**\n * EXTRA scope for each step field's expression picker, on top of whatever\n * this editor is already mounted under.\n *\n * Optional, and normally omitted: `ExpressionOptionsProvider` layers, so a\n * host that provides the project's vars/secrets/documents above this editor\n * (studio does, once, in its app shell) needs to pass nothing here. Use it\n * only to add or override something at this level.\n *\n * Names only — secret plaintext never reaches the client.\n */\n exprOptions?: ExpressionOptions;\n /**\n * The workflow's currently-selected project id. Threaded into ad-hoc\n * test-invokes so document expressions resolve against that project's docs\n * (not the scope's default/starter project). The host (studio) passes the\n * active project here; omitted → server default-project behavior. See T2.1.2 /\n * HITL-4(b): the invoke path's ambient scope is already project-aware.\n */\n project?: string;\n /**\n * The live run's per-step state, when the canvas is showing one (T1.1.1).\n * Omitted ⇒ the canvas renders exactly as it does today: every node in its\n * default look, every edge unstyled beyond its own `when` lane. This\n * editor does no fetching of its own — the host (`studio`) owns polling\n * `GET /runs/:id` and passes each successive result here, the same\n * \"host owns the query, editor is presentational\" split `apps`/`readOnly`\n * already establish for every other external data source.\n *\n * A structural subset of `RunState` in `@w6w/workflow-types` (mirrors this\n * file's own `FlowWorkflow`/`FlowStep` — see `flow-types.ts`'s header\n * note): `packages/ui` takes no dependency on the engine's types, so a\n * caller who already has the real `RunState` is compatible for free.\n *\n * Never persisted: {@link flowToWorkflow} never reads it — a run is not\n * part of the workflow that ran, and `data.stepStatus`/`data.runStatus`\n * (where this ends up on the canvas) are never among the fields it reads\n * back off a node.\n */\n runState?: RunState;\n /**\n * Host-detected per-step problems, keyed by step id — an app step whose bound\n * connection no longer exists gets an error ring + tooltip. Omitted ⇒ the\n * canvas renders exactly as today. The host owns detection; this editor never\n * infers a problem itself. Repaints live (same `value.id`) and is never\n * persisted: `flowToWorkflow` never reads `data.stepProblems`.\n */\n stepProblems?: StepProblems;\n /**\n * Fired the instant a step test starts — the ▶ collect form's Run button, or\n * `StepEditModal`'s footer Test button — before the invoke goes out, so a host\n * can drop whatever run its canvas was showing (T1.1.1) instead of leaving a\n * test to run underneath a stale run's highlighting.\n *\n * On the click, never on the result: only one of those two surfaces has a\n * completion to report at all, and the click is the one moment both share.\n */\n onTestRun?: () => void;\n /**\n * Re-frames the canvas when the host changes the space around it. When this\n * value changes after mount (compared with `Object.is`), the editor calls\n * `fitView({ duration: 300 })` once. It never fires on mount, and omitting it\n * or passing the same value again adds no fit.\n *\n * For a host whose page layout resizes the canvas without the graph changing,\n * e.g. a side panel docking beside it (pass the panel's open state). React Flow\n * keeps its pan/zoom transform when its pane narrows, so nodes near the edge\n * would otherwise end up behind the panel. The editor does not watch its own\n * size, so the host decides which layout changes deserve a re-frame.\n *\n * A fit replaces whatever camera is showing, including a saved viewport the\n * editor restored on open. The fit is not user-initiated, so it never emits\n * `onChange` and never overwrites the stored viewport.\n */\n fitViewKey?: string | number | boolean;\n /**\n * Run from a node: ▶ runs THAT node and then continues through every node downstream of it,\n * following the edges the way a real run does, and stops BEFORE each paused node\n * (`ui.paused`). The host enqueues it as a real run (`POST /workflows/:id/nodes/:nodeId/run`\n * with `continue: true`) and shows it like any run — `runState` + its run log.\n *\n * Called from the ▶ collect form's Run button with:\n * - `stopAt` — every paused node except the start node itself;\n * - `state` — the upstream outputs the form seeded (saved step tests / the last run), the same\n * start state a single-node run is given;\n * - `input` — the filled values, only when the start node is a trigger.\n *\n * Omitted ⇒ ▶ test-runs the single node exactly as before (and flow-control nodes have no ▶).\n * A rejected promise is shown in the run modal.\n */\n onRunFromNode?: (nodeId: string, req: RunFromNodeRequest) => Promise<void> | void;\n}\n\n/** What {@link WorkflowFlowEditorProps.onRunFromNode} is called with. */\nexport interface RunFromNodeRequest {\n /** Paused node ids the run must stop before (never the start node). */\n stopAt: string[];\n /** Upstream outputs seeded from saved step tests / the last run; absent when none. */\n state?: StepStartState;\n /** The trigger's filled values — present only when the start node is a trigger. */\n input?: Record<string, unknown>;\n}\n\n/**\n * App metadata by id, shared with the node cards so `StepNodeCard` can show the\n * app's icon/name/version without threading it through each node's `data`.\n */\nconst PortsLookupCtx = createContext<PortsLookup | undefined>(undefined);\n/** Per-step max outgoing edges in one lane (`fanOutState().count`); drives the card badge. */\nconst FanOutCountsCtx = createContext<ReadonlyMap<string, number>>(new Map());\n/** Each For each's tone and each step's loop, for the Each item port and the loop dots. */\nconst LoopPaintCtx = createContext<LoopPaint>({ tones: new Map(), loopOf: new Map() });\n\n/** The inline refusal when a source is already at its finite `out` cap (no eviction). */\nfunction outCapMessage(cap: number): string {\n return `Can’t draw that edge: this node allows at most ${cap} outgoing edge${cap === 1 ? \"\" : \"s\"} per lane.`;\n}\n\nconst AppsCtx = createContext<Map<string, AppSummary>>(new Map());\n\n/** The workflow's node-bound Subscriptions, read once per editor (not per card). */\ninterface TriggerRegistrationValue {\n byNode: ReadonlyMap<string, SubscriptionSummary>;\n /** The whole list — a webhook node's `nodes.<id>.meta.config.url` comes from it. */\n subs: readonly SubscriptionSummary[];\n /** Present only when the host can retry; re-reads the list after the retry. */\n retry?: (subscriptionId: string) => Promise<void>;\n}\nconst TriggerRegistrationCtx = createContext<TriggerRegistrationValue>({\n byNode: new Map(),\n subs: [],\n});\n\n/** `AppsCtx` plus the trigger-registration context (one provider, no extra nesting level). */\nfunction CardDataProvider({\n apps,\n registration,\n children,\n}: {\n apps: Map<string, AppSummary>;\n registration: TriggerRegistrationValue;\n children: ReactNode;\n}) {\n return (\n <AppsCtx.Provider value={apps}>\n <TriggerRegistrationCtx.Provider value={registration}>\n {children}\n </TriggerRegistrationCtx.Provider>\n </AppsCtx.Provider>\n );\n}\n\n/** Which view the step edit modal opens in: the tabbed form, raw JSON, or node settings. */\ntype EditView = \"props\" | \"json\" | \"settings\";\n\n/** Per-node control handlers, provided to the node cards via context. */\ninterface StepControls {\n /** Open the edit modal on the form view. */\n onEdit: (id: string) => void;\n /** Open the edit modal straight on the JSON view. */\n onEditJson: (id: string) => void;\n /** Test-run a single step and show its result. */\n onRun: (id: string) => void;\n onDuplicate: (id: string) => void;\n onDelete: (id: string) => void;\n /** Toggle `ui.paused` — test runs started from ▶ stop before a paused node. */\n onTogglePause: (id: string) => void;\n /** Toggle `disabled` — a disabled node is skipped in every run. */\n onToggleDisable: (id: string) => void;\n /** True when ▶ runs on from the node (`onRunFromNode`), so flow-control nodes get a ▶ too. */\n runsFromNode: boolean;\n /**\n * Open the step builder for a new step wired to this port — a plain click on the\n * port. Same path as dropping a dragged connection on empty canvas.\n */\n onAddFromPort: (id: string, handleType: \"source\" | \"target\", handleId?: string) => void;\n readOnly?: boolean;\n}\nconst StepControlsCtx = createContext<StepControls | null>(null);\n\n/**\n * Visual workflow editor. Renders a Workflow's DAG as a React Flow graph:\n *\n * - Auto-layouted on load (topological columns + sibling rows).\n * - Nodes render differently for action steps vs. control steps\n * (`uses.app === \"@w6w/control\"`).\n * - `+ Node` opens a guided builder (pick app → connection → action → params,\n * or a flow control). Drag nodes to reposition; connect handles to add edges.\n * - Selecting a node reveals a toolbar above it: Edit / Duplicate / Delete.\n * - Edit opens a modal with a Form ⇄ JSON toggle for that step.\n * - Every meaningful change fires `onChange` with an updated Workflow.\n * - Ctrl/Cmd+Z undoes graph edits; Ctrl/Cmd+Shift+Z (or Ctrl+Y) redoes them.\n * History is local to the open workflow and excludes tests, samples and viewport changes.\n */\nexport function WorkflowFlowEditor(props: WorkflowFlowEditorProps) {\n return (\n <ReactFlowProvider>\n <Inner {...props} />\n </ReactFlowProvider>\n );\n}\n\n/**\n * Live state of a single-step test run, shown in **one** modal that walks three\n * phases against this one state slot: `collect` (fill the step's properties),\n * `running`, then `done` / `error`. ▶ opens `collect` — it no longer invokes on\n * click, so a trigger's declared fields are filled before the run instead of the\n * run coming back `{}`.\n */\ninterface StepRunState {\n stepId: string;\n status: \"collect\" | \"running\" | \"done\" | \"error\";\n value?: unknown;\n /** Which app/version/action/connection the run used; absent when the host sent none. */\n meta?: StepMeta;\n error?: string;\n errorCode?: string;\n /** console.* output captured from a script node run, if any. */\n logs?: string[];\n}\n\nfunction nextCanvasId(prefix: string, taken: string[]) {\n let i = taken.length + 1;\n while (taken.includes(`${prefix}-${i}`)) i++;\n return `${prefix}-${i}`;\n}\nfunction nodeRect(n: StepNode) {\n return {\n x: n.position.x,\n y: n.position.y,\n w: n.measured?.width ?? n.width ?? 200,\n h: n.measured?.height ?? n.height ?? 64,\n };\n}\n\nfunction Inner({\n value,\n onChange,\n readOnly,\n height = 480,\n apps,\n exprOptions,\n project,\n runState,\n stepProblems,\n onTestRun,\n fitViewKey,\n onRunFromNode,\n}: WorkflowFlowEditorProps) {\n const api = useW6WApi();\n const appsById = useMemo(() => new Map((apps ?? []).map((a) => [a.id, a])), [apps]);\n const triggerRegistration = useTriggerRegistration(value);\n const [runResult, setRunResult] = useState<StepRunState | null>(null);\n // Re-hydrate nodes+edges only when the workflow id changes identity. Local\n // edits (drag, connect, delete) go through the useNodesState / useEdgesState\n // handles so React Flow's own state stays authoritative during interaction.\n // biome-ignore lint/correctness/useExhaustiveDependencies: re-derive layout only on workflow identity change\n const initialWorkflow = useMemo(() => centralizeConnections(value), [value.id]);\n const initial = useMemo(() => workflowToFlow(initialWorkflow), [initialWorkflow]);\n const [connections, setConnectionsState] = useState<FlowConnections>(\n initialWorkflow.connections ?? {},\n );\n const connectionsRef = useRef(connections);\n const setConnections = useCallback((next: FlowConnections) => {\n connectionsRef.current = next;\n setConnectionsState(next);\n }, []);\n const prepareStep = useCallback(\n (step: FlowStep) => {\n const next = centralizeConnections({ nodes: [step], connections: connectionsRef.current });\n if (next.connections !== connectionsRef.current) setConnections(next.connections);\n return next.nodes[0];\n },\n [setConnections],\n );\n // The camera to open at, read at mount for the same reason `initial` is: React\n // Flow consumes `defaultViewport` in a mount-only effect (ZoomPane's `XYPanZoom`\n // init), so a fresh object per render would be inert but misleading — and this\n // is what makes a save round-trip not yank the view back.\n // biome-ignore lint/correctness/useExhaustiveDependencies: read at mount only, like `initial`\n const savedViewport = useMemo(() => storedViewport(value), [value.id]);\n // Gates BOTH position writers below (the drag and the pan/zoom). ⚠️ Omitted ⇒\n // **true** (core rfcs/workflow.md · authoring-presentation amendment), so it is\n // read as `!== false` — never `?? false` and never `=== true`. Derived from\n // `value`, deliberately NOT a prop: the flag is a field of the workflow the\n // editor already receives, and a prop would be a second source of truth that\n // can disagree with the persisted document.\n const savePosition = value.settings?.savePosition !== false;\n const [nodes, setNodes, onNodesChange] = useNodesState<StepNode>(initial.nodes);\n // Catalog ports reach resolution through this lookup, never by stamping\n // `step.ports` (which would persist into every saved workflow).\n const actionDefs = useAppActionDefs(api, nodes);\n const triggerDefs = useAppTriggerDefs(api, nodes);\n const portsLookup = useMemo(() => portsLookupFromDefs(actionDefs), [actionDefs]);\n const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>(initial.edges);\n const [selectedId, setSelectedId] = useState<string | null>(null);\n // Notes + sections: live canvas state (geometry renders live; persistCanvas decides what is\n // written). Re-seeded only on workflow identity change, like nodes/edges.\n // biome-ignore lint/correctness/useExhaustiveDependencies: re-seed on workflow identity change only\n const initialCanvas = useMemo<FlowCanvas>(() => value.canvas ?? {}, [value.id]);\n const [canvas, setCanvas] = useState<FlowCanvas>(initialCanvas);\n const [editHistory] = useState(\n () =>\n new FlowEditHistory(\n captureFlowEdit(initialWorkflow, initial.nodes, initial.edges, connections, initialCanvas),\n ),\n );\n const textEditGroup = useRef<object>();\n const [restoreVersion, setRestoreVersion] = useState(0);\n // The draw-section tool, and the rectangle being dragged (client px) while it is armed.\n const [drawingSection, setDrawingSection] = useState(false);\n const [sectionDraft, setSectionDraft] = useState<{\n sx: number;\n sy: number;\n ex: number;\n ey: number;\n } | null>(null);\n const [pendingCanvasDelete, setPendingCanvasDelete] = useState<{\n kind: \"note\" | \"section\";\n id: string;\n } | null>(null);\n const [selectedEdgeId, setSelectedEdgeId] = useState<string | null>(null);\n const [builderOpen, setBuilderOpen] = useState(false);\n const builderEditGroup = useRef<object>({});\n useEffect(() => {\n // The progressive add form creates and configures one node as one undoable action.\n if (!builderOpen) builderEditGroup.current = {};\n }, [builderOpen]);\n const [editingId, setEditingId] = useState<string | null>(null);\n const [editView, setEditView] = useState<EditView>(\"props\");\n // The open right-click menu: where it sits in the editor box and what it acts on.\n // `edgeIds`: selected edges ride along with a selection-wide Delete, as with the Delete key.\n const [contextMenu, setContextMenu] = useState<\n (CanvasMenuTarget & { x: number; y: number; edgeIds: string[] }) | null\n >(null);\n // Where the step picker drops its node and which tab it opens on, when the right-click\n // menu opened it. Cleared whenever the picker closes, so \"+ Node\" keeps its cascade.\n const [builderPlace, setBuilderPlace] = useState<{\n position: { x: number; y: number };\n tab?: \"triggers\";\n } | null>(null);\n // Snapshot the entire selection awaiting confirmation; later selection changes cannot alter it.\n const [pendingDelete, setPendingDelete] = useState<FlowDeleteSelection | null>(null);\n // Set right after `setNodes(next)` in `performRelayout`, cleared by the\n // `[nodes, fitView]` effect below, which then calls `fitView()`. A ref (not\n // state) because it drives no render of its own — it only needs to survive\n // from the relayout click to the next commit of `nodes`.\n const relayoutPendingFitRef = useRef(false);\n // Carries the flow container so the capture-phase dblclick listener below\n // can be attached/removed on it directly — see that effect for why a native\n // listener is required instead of React Flow's own node-double-click prop.\n const flowContainerRef = useRef<HTMLElement>(null);\n // When a connection drag is released on empty canvas, we open the builder to\n // create a new node and auto-wire it to the handle it was dragged from.\n const [pendingConnect, setPendingConnect] = useState<{\n nodeId: string;\n handleType: \"source\" | \"target\";\n position: { x: number; y: number };\n /**\n * The lane the drag originated from, derived via {@link laneForSourceHandle}\n * at CAPTURE time in `onConnectEnd` (T1.1.1) — a target-handle drag reports a\n * handle id that is never `ERROR_SOURCE_HANDLE`, so this naturally reads\n * \"success\" for that gesture without a separate branch.\n */\n lane: CanvasLane;\n route?: string;\n } | null>(null);\n const { screenToFlowPosition, fitView } = useReactFlow();\n // React Flow's `colorMode` defaults to \"light\", so without this its chrome\n // (controls, minimap mask, handles, edge strokes, background dots) stays in the\n // light palette on a dark canvas. Read the mode from the house hook — the same\n // `data-theme` signal `styles.css` and AppIcon/CodeEditor/JsonEditor already\n // follow — rather than adding a prop the host would have to keep in sync.\n const colorMode = useEffectiveTheme();\n\n // If the caller swaps in a different workflow, reset local graph state.\n useEffect(() => {\n setNodes(initial.nodes);\n setEdges(initial.edges);\n setSelectedId(null);\n setSelectedEdgeId(null);\n setPendingDelete(null);\n setEditingId(null);\n setContextMenu(null);\n setCanvas(initialCanvas);\n setConnections(initialWorkflow.connections ?? {});\n editHistory.reset(\n captureFlowEdit(\n initialWorkflow,\n initial.nodes,\n initial.edges,\n initialWorkflow.connections ?? {},\n initialCanvas,\n ),\n );\n textEditGroup.current = undefined;\n }, [initial, initialCanvas, initialWorkflow, setNodes, setEdges, setConnections, editHistory]);\n\n // These two stamps are declared AFTER the workflow-swap reset above on purpose: effects run in\n // declaration order, so the reset (which reseeds nodes from `initial`, with neither stamp) would\n // otherwise overwrite a first-render `runState`/`stepProblems`. `initial` is a dep so they\n // re-stamp after a swap too.\n // T1.1.1 — live run-state repaint. `initial` above deliberately re-derives\n // nodes/edges ONLY on workflow identity change (Trap 1 — its own lint\n // suppression comment a few lines up says so), so a poll tick that\n // changes `runState` while `value.id` stays put would be invisible to the\n // cards if it went through `workflowToFlow` — that memo simply never fires\n // again. This effect instead patches the already-authoritative React Flow\n // state directly, the same mechanism a drag/connect/delete already uses to\n // update `nodes`/`edges` without re-deriving `initial`.\n //\n // Only new `data` keys are stamped — `stepStatus`/`runStatus` on nodes, a\n // run-aware `className`/`label` on edges. `data.step` and `data.when` (the\n // fields `flowToWorkflow` reads back to build the persisted document) are\n // never touched here, so nothing run-related can round-trip into a saved\n // workflow (A6).\n //\n // Functional `setNodes`/`setEdges` updaters read the PREVIOUS state\n // directly, so `nodes`/`edges` need not be dependencies — keeping this\n // effect keyed on `runState` is what keeps a plain drag or edit from repainting.\n // Workflow swaps and undo/redo also re-stamp the restored graph from the current run.\n // biome-ignore lint/correctness/useExhaustiveDependencies: `initial` and `restoreVersion` re-stamp a restored graph\n useEffect(() => {\n setNodes((nds) => {\n // A loop body step has no record of its own; one whose For each is on another path stays\n // unpainted with it (computed here, not read off `data.loopOf`, which may not be stamped yet).\n const loopOf = new Map(stampLoopOf(nds, edges).map((n) => [n.id, n.data.loopOf]));\n return nds.map((n) => {\n const stepStatus = stepVisualState(runState, n.id, enclosingLoops(n.id, loopOf));\n if (n.data.stepStatus === stepStatus && n.data.runStatus === runState?.status) return n;\n return { ...n, data: { ...n.data, stepStatus, runStatus: runState?.status } };\n });\n });\n setEdges((eds) =>\n eds.map((e) => {\n const lane = edgeLane(e);\n const run = edgeRunState(\n runState,\n e.source,\n lane,\n typeof e.data?.route === \"string\" ? e.data.route : undefined,\n e.target,\n );\n const visuals = edgeVisuals(lane, run);\n if (e.className === visuals.className && e.label === visuals.label) return e;\n return { ...e, className: visuals.className, label: visuals.label };\n }),\n );\n }, [runState, initial, restoreVersion, setNodes, setEdges]);\n // Host-supplied step problems — same live-repaint mechanism as runState above:\n // stamps/clears `data.stepProblems` only, never `data.step`.\n // biome-ignore lint/correctness/useExhaustiveDependencies: `initial` and `restoreVersion` re-stamp a restored graph\n useEffect(() => {\n setNodes((nds) => applyStepProblems(nds, stepProblems));\n }, [stepProblems, initial, restoreVersion, setNodes]);\n\n // Stamp the `canvas` key onto an outgoing workflow. Omitted entirely when there is nothing to\n // keep (no notes, no sections), so a workflow that never used the feature round-trips unchanged.\n const withCanvas = useCallback(\n (wf: FlowWorkflow, c: FlowCanvas): FlowWorkflow => {\n const { canvas: _drop, ...rest } = wf;\n if (!c.notes?.length && !c.sections?.length) return rest as FlowWorkflow;\n return { ...rest, canvas: persistCanvas(c, value.canvas, savePosition) };\n },\n [value.canvas, savePosition],\n );\n\n const emitChange = useCallback(\n (nextNodes: StepNode[], nextEdges: Edge[], canvasOverride?: FlowCanvas) => {\n editHistory.record(\n captureFlowEdit(\n value,\n nextNodes,\n nextEdges,\n connectionsRef.current,\n canvasOverride ?? canvas,\n ),\n builderOpen ? builderEditGroup.current : textEditGroup.current,\n );\n onChange(\n withCanvas(\n flowToWorkflow({ ...value, connections: connectionsRef.current }, nextNodes, nextEdges),\n canvasOverride ?? canvas,\n ),\n );\n },\n [value, onChange, canvas, withCanvas, editHistory, builderOpen],\n );\n\n // Live gate while dragging a connection — React Flow marks the drop invalid\n // (and won't fire onConnect) when this returns false.\n const isValidConnection = useCallback(\n (c: Connection | Edge) =>\n canConnect(c.source, c.target, nodes, edges, portsLookup, routeFromHandle(c.sourceHandle)),\n [nodes, edges, portsLookup],\n );\n\n // The typed reason a loop-breaking connection was refused, anchored to the node it\n // was drawn from (D-A6, D-B2). Its own channel — never the edge-lane panel, which\n // needs a selected edge. Cleared on the next successful connect and when the\n // selected node changes (guarded by `loopNoticeSelRef`: React Flow re-invokes\n // `onSelectionChange` after every render, so an unguarded clear would wipe the\n // notice before it paints).\n const [loopNotice, setLoopNotice] = useState<{\n nodeId: string;\n reason: LoopRefusalReason;\n } | null>(null);\n const loopNoticeSelRef = useRef<string | null>(null);\n // The handle a drag started on (see `dragLane`): xyflow's end-state handle is wrong for Done.\n const connectStartRef = useRef<{\n nodeId: string | null;\n handleId: string | null;\n handleType: string | null;\n } | null>(null);\n\n // Mark each loop-body step with its For each (`data.loopOf`) from the each-lane\n // edges. Its own effect, never folded into the runState / stepProblems ones, and\n // never touching `canvas` — the stamp is canvas-only and `flowToWorkflow` ignores it.\n useEffect(() => {\n setNodes((nds) => stampLoopOf(nds, edges));\n }, [edges, setNodes]);\n\n const onConnect = useCallback(\n (params: Parameters<typeof addEdge>[0]) => {\n if (readOnly) return;\n // The lane rides on the handle the wire was dragged from (T1.1.1) — the\n // one canonicalisation point, so a handle-to-handle drag and the\n // drag-to-empty-canvas gesture in `onConnectEnd` cannot disagree on what\n // counts as the error port. applyConnect only ever adds an edge: an input\n // takes any number, an exit at its finite cap refuses.\n const next = applyConnect(\n params.source,\n params.target,\n nodes,\n edges,\n laneForSourceHandle(params.sourceHandle),\n portsLookup,\n routeFromHandle(params.sourceHandle),\n );\n if (!next) {\n // FAIL LOUDLY when the refusal is one the drag could not have shown. Every\n // ordinary rule already ran in `isValidConnection` (React Flow marks the\n // drop invalid and never fires this handler), so the only refusal that\n // reaches here is a duplicate minted id — and that one is *invisible*:\n // React Flow's id-keyed store would have held ONE wire for two edges, which\n // reads as the editor losing the author's work.\n //\n // No new channel: `connectConflict` names the edge already holding the id,\n // and the refusal renders in the edge-lane panel's `role=\"alert\"` slot. The\n // clashing edge is SELECTED — in React Flow's own store, not just our mirror\n // state, so `onSelectionChange` (re-invoked on any re-render) confirms it\n // instead of wiping it before paint — which both reveals that panel and\n // highlights the wire the author has to rename.\n // A finite `out` cap is refused, never evicted: name the cap inline, on an\n // edge already leaving this source in this lane (the panel needs one selected).\n const lane = laneForSourceHandle(params.sourceHandle);\n const refusal = connectRefusal(\n params.source,\n params.target,\n nodes,\n edges,\n lane,\n portsLookup,\n routeFromHandle(params.sourceHandle),\n );\n if (refusal && refusal.refused === \"loop\") {\n setLoopNotice({ nodeId: params.source, reason: refusal.reason });\n return;\n }\n if (refusal) {\n const holder = edges.find((e) => e.source === params.source && edgeLane(e) === lane);\n if (holder) {\n setEdges(edges.map((e) => ({ ...e, selected: e.id === holder.id })));\n setSelectedEdgeId(holder.id);\n setLaneError({ edgeId: holder.id, message: outCapMessage(refusal.cap) });\n }\n return;\n }\n const conflict = connectConflict(\n params.source,\n params.target,\n nodes,\n edges,\n laneForSourceHandle(params.sourceHandle),\n );\n if (!conflict) return;\n setEdges(edges.map((e) => ({ ...e, selected: e.id === conflict })));\n setSelectedEdgeId(conflict);\n setLaneError({\n edgeId: conflict,\n message: idClashMessage(\n \"Can’t draw that edge\",\n conflict,\n clashInvolvedIds(edges, conflict, params.source, params.target),\n ),\n });\n return;\n }\n setLaneError(null);\n setLoopNotice(null);\n setEdges(next);\n emitChange(nodes, next);\n },\n [edges, nodes, setEdges, emitChange, readOnly, portsLookup],\n );\n\n // A connection dropped on empty canvas (no valid target) means \"add a new node\n // here and connect to it\" — open the builder and remember where it came from.\n const onConnectEnd = useCallback(\n (event: MouseEvent | TouchEvent, connectionState: FinalConnectionState) => {\n if (readOnly) return;\n // A valid drop onto a handle is already handled by onConnect.\n if (connectionState.isValid) return;\n const fromNode = connectionState.fromNode;\n if (!fromNode) return;\n const handleType = connectionState.fromHandle?.type === \"target\" ? \"target\" : \"source\";\n // A drop ON an existing node that the editor rejected is a refusal, never \"add a\n // new node here\": when the loop rule names why (e.g. the Done handle onto the\n // loop's own first step), show that reason anchored to the source and stop.\n const toNode = connectionState.toNode;\n if (toNode && handleType === \"source\") {\n const reason = connectDropRefusal(\n fromNode.id,\n toNode.id,\n dragLane(connectStartRef.current, fromNode.id, connectionState.fromHandle),\n nodes,\n edges,\n );\n if (reason) {\n setLoopNotice({ nodeId: fromNode.id, reason });\n return;\n }\n }\n // Only spawn if the origin handle can participate at all — a source handle\n // needs an exit port, a target handle an entry port. (A full single-slot\n // port is fine: the auto-wire below replaces its existing edge.)\n const originStep = nodes.find((n) => n.id === fromNode.id)?.data.step;\n if (originStep) {\n const p = nodePortsForStep(originStep, portsLookup);\n if ((handleType === \"source\" ? p.out : p.in) < 1) return;\n }\n const point = \"changedTouches\" in event ? event.changedTouches[0] : event;\n const position = screenToFlowPosition({ x: point.clientX, y: point.clientY });\n // The lane is derived HERE, not re-derived at `addBuiltStep` time\n // (T1.1.1): the dragged handle is only available on `connectionState`,\n // which does not survive past this callback — the step builder opens in\n // between. A target-handle drag reports a handle id that is never\n // `ERROR_SOURCE_HANDLE`, so this naturally reads \"success\" for that\n // gesture with no separate branch.\n setPendingConnect({\n nodeId: fromNode.id,\n handleType,\n position,\n lane: dragLane(connectStartRef.current, fromNode.id, connectionState.fromHandle),\n route: routeFromHandle(connectionState.fromHandle?.id),\n });\n setBuilderOpen(true);\n },\n [readOnly, screenToFlowPosition, nodes, edges, portsLookup],\n );\n\n // A plain click on a port: the same \"new step wired to this port\" as a drag\n // dropped on empty canvas, with no drop point — the new step is placed one\n // step-width out from the port's side of the node instead.\n const addFromPort = useCallback(\n (nodeId: string, handleType: \"source\" | \"target\", handleId?: string) => {\n if (readOnly) return;\n const n = nodes.find((x) => x.id === nodeId);\n if (!n) return;\n const r = nodeRect(n);\n const lane = laneForSourceHandle(handleId);\n const gap = 120;\n const position =\n handleType === \"target\"\n ? { x: r.x - r.w - gap, y: r.y }\n : lane === \"error\"\n ? { x: r.x, y: r.y + r.h + gap }\n : lane === \"each\"\n ? { x: r.x + r.w + gap, y: r.y - r.h - gap / 2 }\n : { x: r.x + r.w + gap, y: r.y };\n setPendingConnect({ nodeId, handleType, position, lane, route: routeFromHandle(handleId) });\n setBuilderOpen(true);\n },\n [readOnly, nodes],\n );\n\n // The node trash button requests one deletion; the canvas keydown handler requests\n // the full selection. Both use the same pending state and confirmation modal.\n // `performDeleteSelection` is invoked solely from the ConfirmModal's onConfirm.\n const deleteStep = useCallback(\n (id: string) => {\n if (readOnly) return;\n setPendingDelete({ nodeIds: [id], edgeIds: [] });\n },\n [readOnly],\n );\n\n const performDeleteSelection = useCallback(\n (selection: FlowDeleteSelection) => {\n if (readOnly) return;\n const next = deleteFlowSelection(selection, nodes, edges, canvas);\n setNodes(next.nodes);\n setEdges(next.edges);\n setCanvas(next.canvas);\n if (!next.nodes.some((n) => n.id === selectedId)) setSelectedId(null);\n if (!next.nodes.some((n) => n.id === editingId)) setEditingId(null);\n if (!next.edges.some((e) => e.id === selectedEdgeId)) setSelectedEdgeId(null);\n emitChange(next.nodes, next.edges, next.canvas);\n },\n [\n nodes,\n edges,\n canvas,\n setNodes,\n setEdges,\n emitChange,\n readOnly,\n selectedId,\n editingId,\n selectedEdgeId,\n ],\n );\n // ── Auto-layout (the fourth control button) ─────────────────────────────────\n //\n // Arrange the current paths and their section frames as one undoable edit.\n const performRelayout = useCallback(() => {\n if (readOnly) return;\n const next = relayoutFlow(nodes, edges, canvas);\n setNodes(next.nodes);\n setCanvas(next.canvas);\n relayoutPendingFitRef.current = true;\n emitChange(next.nodes, edges, next.canvas);\n }, [nodes, edges, canvas, setNodes, emitChange, readOnly]);\n\n // No confirmation (D-T2b): re-flowing is instant, deliberately with no\n // replacement gate — the intake is explicit this click should never warn. See\n // `.ai/conventions.md`'s \"No browser dialogs\" for the house pattern this is a\n // recorded exception to, not an oversight.\n const requestRelayout = useCallback(() => {\n if (readOnly) return;\n performRelayout();\n }, [readOnly, performRelayout]);\n\n // Frame the re-flowed graph once React Flow's own node-sync effect (a child of\n // this component) has committed the new positions — that child-before-parent\n // effect ordering is what makes `fitView()` here read POST-relayout bounds\n // instead of the stale pre-relayout ones. Keyed on `[nodes, fitView]` so it\n // re-checks the ref on every nodes commit, not just relayout's — `nodes`\n // itself is unread in the body, only its commit timing matters, so the\n // exhaustive-deps rule can't see why it's there.\n // biome-ignore lint/correctness/useExhaustiveDependencies: `nodes` drives ordering, not the body\n useEffect(() => {\n if (!relayoutPendingFitRef.current) return;\n relayoutPendingFitRef.current = false;\n void fitView({ duration: 300 });\n }, [nodes, fitView]);\n\n // `fitViewKey`: one fit per change of the host's key, never on mount. The ref\n // starts at the mount value, so the first run (and StrictMode's re-run) sees\n // no change; a new `fitView` identity alone fails the same check.\n const lastFitViewKeyRef = useRef(fitViewKey);\n useEffect(() => {\n if (Object.is(lastFitViewKeyRef.current, fitViewKey)) return;\n lastFitViewKeyRef.current = fitViewKey;\n void fitView({ duration: 300 });\n }, [fitViewKey, fitView]);\n\n // ── The edge-level lane control (`Run on: Success / Error`) ─────────────────\n // Reuses the selection state that already exists; nothing new is tracked but the\n // refusal message, which renders INLINE in the panel. Never a browser dialog —\n // same rule as the delete confirm above (.ai/conventions.md · No browser dialogs).\n // Scoped to the edge it is about, NOT cleared from `onSelectionChange`: React\n // Flow re-invokes that callback after any re-render (it is an inline lambda, so\n // it re-subscribes), which clears the message before it is ever painted — a\n // refusal that renders for zero frames is the same as failing silently.\n const [laneError, setLaneError] = useState<{ edgeId: string; message: string } | null>(null);\n const selectedEdge = useMemo(\n () => edges.find((e) => e.id === selectedEdgeId) ?? null,\n [edges, selectedEdgeId],\n );\n\n const setEdgeLane = useCallback(\n (when: \"success\" | \"error\") => {\n if (readOnly || !selectedEdgeId) return;\n const me = edges.find((e) => e.id === selectedEdgeId);\n if (!me) return;\n // Choosing the lane it is already on is a no-op — don't emit a change (which\n // would mark the host's workflow dirty for nothing). `setEdgeWhen` is\n // separately safe for this, so neither layer relies on the other.\n if (edgeLane(me) === when) return;\n const conflict = edgeWhenConflict(edges, selectedEdgeId, when, nodes);\n const refusal = relaneRefusal(edges, selectedEdgeId, when, nodes, portsLookup);\n const next =\n conflict || refusal ? null : setEdgeWhen(edges, selectedEdgeId, when, nodes, portsLookup);\n if (!next) {\n if (refusal) {\n setLaneError({ edgeId: selectedEdgeId, message: outCapMessage(refusal.cap) });\n return;\n }\n // FAIL LOUDLY. The alternative is minting a duplicate edge id, which React\n // Flow's id-keyed store silently collapses — one wire disappearing from the\n // canvas with no error, indistinguishable from the editor losing the work.\n setLaneError({\n edgeId: selectedEdgeId,\n message: conflict\n ? idClashMessage(\n \"Can’t switch this edge\",\n conflict,\n clashInvolvedIds(edges, conflict, me.source, me.target),\n )\n : \"This edge can’t be switched right now.\",\n });\n return;\n }\n setLaneError(null);\n setEdges(next);\n // The id encodes the lane, so re-laning re-mints it — move the selection (and\n // therefore this panel) onto the same wire under its new id.\n const relaned = next.find(\n (e) => e.source === me.source && e.target === me.target && edgeLane(e) === when,\n );\n setSelectedEdgeId(relaned?.id ?? null);\n emitChange(nodes, next);\n },\n [edges, nodes, setEdges, emitChange, readOnly, selectedEdgeId, portsLookup],\n );\n\n const deleteEdge = useCallback(\n (id: string) => {\n if (readOnly) return;\n const nextEdges = edges.filter((e) => e.id !== id);\n if (nextEdges.length === edges.length) return;\n setEdges(nextEdges);\n if (selectedEdgeId === id) setSelectedEdgeId(null);\n emitChange(nodes, nextEdges);\n },\n [nodes, edges, setEdges, emitChange, readOnly, selectedEdgeId],\n );\n\n // Each copy lands offset from its source and is selected; edges are not copied (the\n // node toolbar's Duplicate, applied to every id at once).\n const duplicateSteps = useCallback(\n (ids: readonly string[]) => {\n if (readOnly) return;\n const sources = ids\n .map((id) => nodes.find((n) => n.id === id))\n .filter((n): n is StepNode => n !== undefined);\n if (sources.length === 0) return;\n const taken = nodes.map((n) => n.id);\n const copies = sources.map((src): StepNode => {\n const newId = suggestStepId(taken, `${src.data.step.id}_copy`);\n taken.push(newId);\n const cloned: FlowStep = { ...stripBody(structuredClone(src.data.step)), id: newId };\n return {\n id: newId,\n type: src.type,\n position: { x: src.position.x + 40, y: src.position.y + 60 },\n data: { step: cloned, isInternal: src.data.isInternal },\n ...(sources.length > 1 ? { selected: true } : {}),\n };\n });\n const nextNodes = [\n ...(sources.length > 1\n ? nodes.map((n) => (n.selected ? { ...n, selected: false } : n))\n : nodes),\n ...copies,\n ];\n setNodes(nextNodes);\n setSelectedId(copies[0].id);\n emitChange(nextNodes, edges);\n },\n [nodes, edges, setNodes, emitChange, readOnly],\n );\n const duplicateStep = useCallback((id: string) => duplicateSteps([id]), [duplicateSteps]);\n\n const addBuiltStep = useCallback(\n (built: BuiltStep): string | undefined => {\n if (readOnly) return undefined;\n const isInternal = isInternalApp(built.uses.app);\n // Derived from the action itself (\"data_1\", \"render_template_1\"), not\n // a generic \"gate_1\"/\"step_1\" — human override, 2026-08-30: a reader\n // who never renames a step can still orient by its id.\n // `internalNodeLabel` falls back to the bare `action` key for a\n // non-internal (registry) app, since only internal nodes carry a\n // `label` this lookup can find.\n const taken = nodes.map((n) => n.id);\n // A name chosen in the add flow wins when it is valid; otherwise mint one.\n const id =\n built.id && !stepNameError(built.id, taken)\n ? built.id\n : suggestStepId(\n taken,\n slugifyLabel(internalNodeLabel(built.uses.app, built.uses.action)),\n );\n const step: FlowStep = prepareStep({\n id,\n uses: built.uses,\n ...(built.with && Object.keys(built.with).length > 0 ? { with: built.with } : {}),\n });\n const newNode: StepNode = {\n id,\n type: isInternal ? \"control\" : \"step\",\n // Drop point when spawned from a dragged connection or the right-click menu;\n // else a light cascade.\n position: pendingConnect?.position ??\n builderPlace?.position ?? { x: 80, y: 80 + nodes.length * 24 },\n data: { step, isInternal },\n };\n const nextNodes = [...nodes, newNode];\n\n // Auto-wire the edge back to the handle the drag started from. Dragging a\n // source handle points the edge at the new node; a target handle reverses it.\n // Gated per the port rules (applyConnect) against the new node; it only adds.\n let nextEdges = edges;\n // A loop-breaking auto-wire is never silent (D-B2): the step is added\n // unconnected only together with the typed notice, anchored to the source node.\n let loopRefused: { nodeId: string; reason: LoopRefusalReason } | null = null;\n const noteLoopRefusal = (\n source: string,\n target: string,\n lane: CanvasLane,\n anchor: string,\n ) => {\n const r = connectRefusal(source, target, nextNodes, edges, lane, portsLookup);\n if (r && r.refused === \"loop\") loopRefused = { nodeId: anchor, reason: r.reason };\n };\n if (pendingConnect) {\n const [source, target] =\n pendingConnect.handleType === \"target\"\n ? [id, pendingConnect.nodeId]\n : [pendingConnect.nodeId, id];\n // The lane captured at drag-release time (T1.1.1) — a step spawned by\n // dragging the error port onto empty canvas is wired error, one spawned\n // from the ordinary exit is wired success.\n const wired = applyConnect(\n source,\n target,\n nextNodes,\n edges,\n pendingConnect.lane,\n portsLookup,\n pendingConnect.route,\n );\n if (!wired) noteLoopRefusal(source, target, pendingConnect.lane, pendingConnect.nodeId);\n nextEdges = wired ?? edges;\n } else {\n // \"+ Node\" (no drag) — human override, 2026-08-30. A trigger\n // auto-wires to the CURRENT chain root, but ONLY when no trigger\n // exists yet anywhere in the graph; a second trigger is left\n // floating on purpose (nothing to sensibly guess — the author\n // decides if and where it feeds in). A non-trigger step prefers\n // wiring an existing UNCONNECTED trigger forward (the likely intent\n // right after adding one) over extending the current tail.\n const existingTrigger = nodes.find((n) => isTriggerStep(n.data.step.uses));\n if (isTriggerStep(built.uses)) {\n if (!existingTrigger) {\n const root = findChainRoot(nodes, edges);\n if (root) {\n const wired = applyConnect(id, root.id, nextNodes, edges, \"success\", portsLookup);\n if (!wired) noteLoopRefusal(id, root.id, \"success\", root.id);\n nextEdges = wired ?? edges;\n }\n }\n } else {\n const unconnectedTrigger =\n existingTrigger && !edges.some((e) => e.source === existingTrigger.id)\n ? existingTrigger\n : undefined;\n const from = unconnectedTrigger ?? findChainTail(nodes, edges);\n if (from) {\n const wired = applyConnect(from.id, id, nextNodes, edges, \"success\", portsLookup);\n if (!wired) noteLoopRefusal(from.id, id, \"success\", from.id);\n nextEdges = wired ?? edges;\n }\n }\n }\n\n setNodes(nextNodes);\n if (nextEdges !== edges) setEdges(nextEdges);\n setLoopNotice(loopRefused);\n setSelectedId(id);\n // Progressive commit (T4.1.1): the builder stays open past this first\n // commit to keep taking edits via `onDraftChange`, so closing is\n // exclusively `onClose`'s job now (wired at the render site below).\n emitChange(nextNodes, nextEdges);\n return id;\n },\n [\n nodes,\n edges,\n setNodes,\n setEdges,\n emitChange,\n readOnly,\n pendingConnect,\n builderPlace,\n portsLookup,\n prepareStep,\n ],\n );\n\n // Apply an edit to a step, rewiring edges if its id changed.\n const updateStep = useCallback(\n (prevId: string, draft: FlowStep) => {\n let next = draft;\n const previous = nodes.find((n) => n.id === prevId)?.data.step;\n // The progressive add form still emits inline account IDs. Reuse its private\n // binding on later field edits, and detach once if it was sharing a binding.\n if (\n draft.uses.connection &&\n !draft.uses.connectionRef &&\n previous?.uses.connectionRef &&\n previous.uses.app === draft.uses.app\n ) {\n const selected = selectNodeConnection(\n withConnectionRef(draft, previous.uses.connectionRef),\n draft.uses.connection,\n nodes.map((n) => n.data.step),\n connectionsRef.current,\n );\n setConnections(selected.connections);\n next = selected.step;\n } else next = prepareStep(draft);\n const idChanged = next.id !== prevId;\n if (idChanged && nodes.some((n) => n.id === next.id)) return; // reject dup id\n const nextNodes = nodes.map((n) =>\n n.id === prevId\n ? {\n ...n,\n id: next.id,\n data: { step: next, isInternal: isInternalApp(next.uses.app) },\n }\n : n,\n );\n if (idChanged) {\n // Re-point the endpoints AND re-mint each id in the edge's own lane. This\n // used to rebuild every id unqualified, dropping an error edge's `:error`\n // suffix so a same-target success+error pair collapsed into one edge in\n // React Flow's id-keyed store. The lane-aware rewrite lives in\n // `flow-connect.ts` and mints ids through the one shared `flowEdgeId`\n // helper — never a second copy of the template.\n const nextEdges = renameStepInEdges(edges, prevId, next.id);\n const nextCanvas = renameSectionMember(canvas, prevId, next.id);\n setNodes(nextNodes);\n setEdges(nextEdges);\n setCanvas(nextCanvas);\n if (selectedId === prevId) setSelectedId(next.id);\n if (editingId === prevId) setEditingId(next.id);\n emitChange(nextNodes, nextEdges, nextCanvas);\n return;\n }\n setNodes(nextNodes);\n const routeIds = new Set(routesForStep(next).map((r) => r.id));\n const nextEdges = edges.filter(\n (e) =>\n e.source !== next.id || e.data?.route === undefined || routeIds.has(String(e.data.route)),\n );\n if (nextEdges.length !== edges.length) setEdges(nextEdges);\n emitChange(nextNodes, nextEdges);\n },\n [\n nodes,\n edges,\n canvas,\n setNodes,\n setEdges,\n selectedId,\n editingId,\n emitChange,\n prepareStep,\n setConnections,\n ],\n );\n\n // ── Notes & sections ────────────────────────────────────────────────────────\n const onCanvasChange = useCallback(\n (next: FlowCanvas) => {\n if (readOnly) return;\n setCanvas(next);\n emitChange(nodes, edges, next);\n },\n [readOnly, nodes, edges, emitChange],\n );\n\n const addNote = useCallback(() => {\n if (readOnly) return;\n const box = flowContainerRef.current?.getBoundingClientRect();\n const at = box\n ? screenToFlowPosition({ x: box.left + box.width / 2, y: box.top + box.height / 2 })\n : { x: 0, y: 0 };\n const notes = canvas.notes ?? [];\n const note = {\n id: nextCanvasId(\n \"note\",\n notes.map((n) => n.id),\n ),\n color: \"#facc15\",\n position: { x: Math.round(at.x - 100), y: Math.round(at.y - 60) },\n size: { width: 200, height: 120 },\n content: \"\",\n };\n onCanvasChange(clampCanvas({ ...canvas, notes: [...notes, note] }));\n }, [readOnly, canvas, screenToFlowPosition, onCanvasChange]);\n\n // \"Draw section\" tool: the author drags a rectangle anywhere on the canvas (corners in flow\n // units). The frame owns the nodes whose centre falls inside it — the same rule a node drag\n // uses — so dragging the section carries them. A click without a drag drops a default frame.\n const addSectionAt = useCallback(\n (a: { x: number; y: number }, b: { x: number; y: number } | null) => {\n if (readOnly) return;\n const x0 = b ? Math.min(a.x, b.x) : a.x;\n const y0 = b ? Math.min(a.y, b.y) : a.y;\n const w = b ? Math.abs(b.x - a.x) : 360;\n const h = b ? Math.abs(b.y - a.y) : 240;\n const members = nodes\n .filter((n) => {\n const r = nodeRect(n);\n const cx = r.x + r.w / 2;\n const cy = r.y + r.h / 2;\n return cx >= x0 && cx <= x0 + w && cy >= y0 && cy <= y0 + h;\n })\n .map((n) => n.id);\n const sections = canvas.sections ?? [];\n const id = nextCanvasId(\n \"section\",\n sections.map((x) => x.id),\n );\n const section = {\n id,\n title: \"Section\",\n color: \"#6366f1\",\n position: { x: Math.round(x0), y: Math.round(y0) },\n size: { width: Math.round(w), height: Math.round(h) },\n nodes: [] as string[],\n };\n const withNew = { ...canvas, sections: [...sections, section] };\n onCanvasChange(clampCanvas(assignMembership(withNew, id, members)));\n },\n [readOnly, nodes, canvas, onCanvasChange],\n );\n\n // Esc leaves the draw-section tool without drawing.\n useEffect(() => {\n if (!drawingSection) return;\n const onKey = (e: KeyboardEvent) => {\n if (e.key !== \"Escape\") return;\n setDrawingSection(false);\n setSectionDraft(null);\n };\n window.addEventListener(\"keydown\", onKey);\n return () => window.removeEventListener(\"keydown\", onKey);\n }, [drawingSection]);\n\n // Dropping a section moves its members by the same delta: ONE emission, on drop.\n const onSectionDrop = useCallback(\n (id: string, d: { dx: number; dy: number }) => {\n if (readOnly) return;\n const sec = canvas.sections?.find((x) => x.id === id);\n if (!sec) return;\n const members = new Set(sec.nodes);\n const nextNodes = nodes.map((n) =>\n members.has(n.id)\n ? { ...n, position: { x: n.position.x + d.dx, y: n.position.y + d.dy } }\n : n,\n );\n const nextCanvas: FlowCanvas = {\n ...canvas,\n sections: (canvas.sections ?? []).map((x) =>\n x.id === id ? { ...x, position: { x: x.position.x + d.dx, y: x.position.y + d.dy } } : x,\n ),\n };\n setNodes(nextNodes);\n setCanvas(nextCanvas);\n emitChange(nextNodes, edges, nextCanvas);\n },\n [readOnly, canvas, nodes, edges, setNodes, emitChange],\n );\n\n const performCanvasDelete = useCallback(\n (kind: \"note\" | \"section\", id: string) => {\n if (readOnly) return;\n // Deleting a section deletes the frame, never its nodes.\n const next: FlowCanvas =\n kind === \"note\"\n ? { ...canvas, notes: (canvas.notes ?? []).filter((n) => n.id !== id) }\n : { ...canvas, sections: (canvas.sections ?? []).filter((x) => x.id !== id) };\n onCanvasChange(next);\n },\n [readOnly, canvas, onCanvasChange],\n );\n\n // After a node drag: membership follows the node CENTRE (inside a section ⇒ joins it,\n // leaving any other; outside every section ⇒ leaves). Returns the canvas to emit.\n const membershipAfterDrag = (dragged: StepNode[]): FlowCanvas => {\n let next = canvas;\n for (const d of dragged) {\n const r = nodeRect(d);\n const cx = r.x + r.w / 2;\n const cy = r.y + r.h / 2;\n const target = (next.sections ?? []).find(\n (sec) =>\n cx >= sec.position.x &&\n cx <= sec.position.x + sec.size.width &&\n cy >= sec.position.y &&\n cy <= sec.position.y + sec.size.height,\n );\n const current = sectionsContaining(next, d.id);\n if (target) {\n if (current.length !== 1 || current[0] !== target.id) {\n next = assignMembership(next, target.id, [d.id]);\n }\n } else if (current.length > 0) {\n next = pruneSectionMembers(next, d.id);\n }\n }\n return next;\n };\n\n // Remember the values a Run was made with, then record the run AGAINST that\n // fixture — the same two-call sequence the Test path uses (`StepTestRun` in\n // StepBuilderModal), so a Run and a Test write the same kind of `step_tests`\n // row for the same step and each surface pre-fills from whichever ran last.\n //\n // The `stepTestId` is the load-bearing half: `recordStepTestRun` only updates\n // the fixture's `last_run_*` columns when it is present, and this call used to\n // post without one — so a canvas run was logged but never written back onto\n // the fixture. Best-effort throughout: a persist failure is logged and never\n // surfaces as a failed run.\n //\n // The two calls fail INDEPENDENTLY, and deliberately so: remembering the\n // values and recording that the run happened are different obligations, and\n // only the first can fail on its own (`POST …/tests` 404s on an unknown\n // workflow, `POST …/test-runs` does not). Folding both into one `try` would\n // make a fixture-save failure swallow the run's `step_test_runs` row *and* the\n // `run_log` ledger row the server writes per POST — i.e. silently lose run\n // history over a persistence hiccup. So a failed save degrades to\n // `stepTestId: null`: a run recorded with no fixture attached, which is\n // exactly what the route already accepts (step-test-runs.ts).\n const persistStepRun = useCallback(\n (\n stepId: string,\n fixture: { input: Record<string, unknown>; with: Record<string, unknown> },\n outcome: { status: string; output?: unknown; error?: unknown; meta?: StepMeta },\n ) => {\n void (async () => {\n const saved = await api.saveStepTest(value.id, stepId, fixture).catch((err) => {\n console.error(\"step run fixture save failed\", err);\n return null;\n });\n await api.recordStepTestRun(value.id, stepId, {\n stepTestId: saved?.id ?? null,\n status: outcome.status,\n input: fixture.input,\n output: outcome.output,\n error: outcome.error,\n ...(outcome.meta ? { meta: outcome.meta } : {}),\n });\n })().catch((err) => {\n console.error(\"step run persist failed\", err);\n });\n },\n [api, value.id],\n );\n\n // Test-running one step is two-phase, mirroring delete's request/perform split:\n // `runStep` (the ▶ control) only *opens* the collect phase, and\n // `performRunStep` — reached solely from the collect form's Run button — does\n // the invoke with the values the user just filled in. Control steps aren't\n // invocable. Signature is unchanged: `onRun` is still `(id: string) => void`.\n const runStep = useCallback(\n (id: string) => {\n const node = nodes.find((n) => n.id === id);\n // Flow-control nodes can't run standalone; app + compute/trigger nodes can. A run that\n // continues downstream is a real run, so it can start at a flow-control node too.\n if (!node || (!onRunFromNode && isControlApp(node.data.step.uses.app))) return;\n setRunResult({ stepId: id, status: \"collect\" });\n },\n [nodes, onRunFromNode],\n );\n\n // ▶ with a host that runs on from the node: the collect form's values become a real run that\n // continues downstream and stops before every paused node. The host owns the request and the\n // run it shows, so the modal closes once the run has started; a refusal stays in the modal.\n const performRunFromNode = useCallback(\n async (id: string, values: Record<string, unknown>, state?: StepStartState) => {\n if (!onRunFromNode) return;\n const node = nodes.find((n) => n.id === id);\n if (!node) return;\n const isTrigger = isTriggerStep(node.data.step.uses);\n const req: RunFromNodeRequest = {\n stopAt: pausedStopAt(\n nodes.map((n) => n.data.step),\n id,\n ),\n ...(state ? { state } : {}),\n ...(isTrigger ? { input: values } : {}),\n };\n setRunResult({ stepId: id, status: \"running\" });\n try {\n await onRunFromNode(id, req);\n setRunResult(null);\n } catch (e) {\n const err = e as { message?: string; code?: string };\n setRunResult({\n stepId: id,\n status: \"error\",\n error: err.message ?? String(e),\n errorCode: err.code,\n });\n }\n },\n [nodes, onRunFromNode],\n );\n\n // Pause / disable: flip one flag on one step, keeping the node's run/problem stamps.\n const patchStep = useCallback(\n (id: string, fn: (step: FlowStep) => FlowStep) => {\n if (readOnly) return;\n const nextNodes = nodes.map((n) =>\n n.id === id ? { ...n, data: { ...n.data, step: fn(n.data.step) } } : n,\n );\n setNodes(nextNodes);\n emitChange(nextNodes, edges);\n },\n [nodes, edges, setNodes, emitChange, readOnly],\n );\n const togglePause = useCallback(\n (id: string) => patchStep(id, (s) => withPaused(s, !isPausedStep(s))),\n [patchStep],\n );\n const toggleDisable = useCallback(\n (id: string) => patchStep(id, (s) => withDisabled(s, !isDisabledStep(s))),\n [patchStep],\n );\n\n // Invoke one step through the invoke API with the properties collected in the\n // modal's collect phase, and (for action steps) its stored connection.\n //\n // `state` is the run's START STATE — what the upstream steps last produced —\n // and it is NOT params: it goes out as the invoke body's own `state` field so\n // the server can resolve `{{ steps.<id>.output.<field> }}` in the step's\n // `with`. Sending it as params would do nothing: the runtime copies only\n // DECLARED params and drops the rest (`core/runtime/src/resolve.ts`).\n const performRunStep = useCallback(\n async (id: string, values: Record<string, unknown>, state?: StepStartState) => {\n // T1.1.1: a step test starts NOW, so the host drops the run it was\n // showing before the invoke goes out — the canvas returns to editable on\n // the user's action, not on this test's eventual result.\n onTestRun?.();\n const node = nodes.find((n) => n.id === id);\n if (!node) return;\n const step = node.data.step;\n const isTrigger = isTriggerStep(step.uses);\n // A trigger's filled fields ARE the run's starting state: the handler\n // returns `params.input` verbatim, so anything else comes back `{}`. Every\n // other step is ALREADY CONFIGURED — `values` is the incoming state the\n // collect form asked for, merged over the step's STORED `with`, which is\n // exactly the payload the Test tab sends (`testValues`). The stored `with`\n // is read, never written: a run does not rewrite the step's configuration.\n const payload = isTrigger ? { input: values } : { ...(step.with ?? {}), ...values };\n // The fixture saved alongside the run, in the same two slots the Test tab\n // writes: `input` is the run's incoming state — for a trigger its filled\n // values *are* it, for every other step it is what the incoming-state box\n // held — and `with` is the full set of params the call was made with.\n const fixture = isTrigger\n ? { input: values, with: values }\n : { input: values, with: payload };\n setRunResult({ stepId: id, status: \"running\" });\n try {\n const result = await api.invokeAction(step.uses.app, step.uses.action, payload, {\n connectionId: connectionIdFor(step, connectionsRef.current),\n // Scope document expressions to the workflow's selected project (T2.1.2).\n project,\n // Omitted when nothing upstream has a saved output, so a run with no\n // seed sends exactly the request it sent before.\n ...(state ? { state } : {}),\n // So `{{ nodes.<id>.config.* }}` resolves as on a run.\n workflowId: value.id,\n });\n // Script nodes may return captured console output alongside the value.\n const logs = (result as { logs?: string[] }).logs;\n const meta = result.meta;\n setRunResult({\n stepId: id,\n status: \"done\",\n value: result.value,\n logs,\n ...(meta ? { meta } : {}),\n });\n // Remember the values and log the run against the fixture they were\n // saved as (best-effort — never fail the run over it).\n persistStepRun(id, fixture, {\n status: \"succeeded\",\n output: result.value,\n ...(meta ? { meta } : {}),\n });\n } catch (e) {\n // The api client wraps network/parse failures with context; duck-type the\n // code so the modal can show it next to the message.\n const err = e as { message?: string; code?: string };\n setRunResult({\n stepId: id,\n status: \"error\",\n error: err.message ?? String(e),\n errorCode: err.code,\n });\n // A failed run still remembers what was entered — the operator's next\n // attempt starts from the values that failed, not from blank.\n persistStepRun(id, fixture, { status: \"failed\", error: err.message ?? String(e) });\n }\n },\n [nodes, api, persistStepRun, project, onTestRun, value.id],\n );\n\n const controls = useMemo<StepControls>(\n () => ({\n onEdit: (id) => {\n setEditView(\"props\");\n setEditingId(id);\n },\n onEditJson: (id) => {\n setEditView(\"json\");\n setEditingId(id);\n },\n onRun: runStep,\n onDuplicate: duplicateStep,\n onDelete: deleteStep,\n onTogglePause: togglePause,\n onToggleDisable: toggleDisable,\n runsFromNode: !!onRunFromNode,\n onAddFromPort: addFromPort,\n readOnly,\n }),\n [\n runStep,\n duplicateStep,\n deleteStep,\n togglePause,\n toggleDisable,\n onRunFromNode,\n addFromPort,\n readOnly,\n ],\n );\n\n // Opens the step editor on a canvas node double-click — deliberately NOT\n // React Flow's own node-double-click prop on `<ReactFlow>` below. That prop\n // fires from React's root container, an ANCESTOR of `.react-flow__pane` under\n // React 18's event delegation, so it always loses the race to the pane's own\n // native `dblclick.zoom` listener and can't stop it. A capture-phase listener\n // on this container fires first instead.\n //\n // The guard matters specifically in `readOnly`: `nodesDraggable={!readOnly}`\n // below drops `nopan` from the node wrapper's class list for a non-draggable\n // node, and for THIS scenario — a non-wheel double-click with no active\n // selection or connection in progress — `@xyflow/system`'s zoom filter's\n // remaining check is `.nopan` — so without this listener winning the race,\n // a viewer's double-click silently zooms the canvas instead of opening the\n // modal.\n useEffect(() => {\n const div = flowContainerRef.current;\n if (!div) return;\n const handler = (e: MouseEvent) => {\n const card = (e.target as HTMLElement).closest(\".react-flow__node\");\n if (!card) return; // not over a node — let the pane's own dblclick-zoom run\n const id = card.getAttribute(\"data-id\");\n if (!id) return;\n // CAPTURE phase (registered below) is what makes this run before the\n // pane's bubble-phase `dblclick.zoom` listener; stopping it here is what\n // actually suppresses the zoom.\n e.stopPropagation();\n // Same transition the node toolbar's pencil button performs — no new\n // plumbing, `controls` already carries `onEdit`.\n controls.onEdit(id);\n };\n div.addEventListener(\"dblclick\", handler, true);\n return () => div.removeEventListener(\"dblclick\", handler, true);\n }, [controls]);\n\n const editingNode = nodes.find((n) => n.id === editingId);\n const editingStep = editingNode?.data.step ?? null;\n // The step the run modal is open on, resolved live so the collect phase reads\n // the current `with` (a trigger's declared `fields`) rather than a snapshot.\n const runningStep = runResult\n ? (nodes.find((n) => n.id === runResult.stepId)?.data.step ?? null)\n : null;\n // Phase 1 of the run modal: collect the run's incoming state, nothing invoked\n // yet. The collect form offers the same upstream seed chips the Test tab does,\n // so it needs the RUNNING step's graph ancestors — the step editor's own\n // `upstreamState` below is computed for `editingId`, a different step.\n const collecting = runResult?.status === \"collect\" && !!runningStep;\n\n const fanOutCounts = useMemo(() => {\n const m = new Map<string, number>();\n for (const n of nodes) m.set(n.id, fanOutState(n.id, edges).count);\n return m;\n }, [nodes, edges]);\n\n // Loop colours: keyed on loop membership only, so a drag keeps the same context value.\n const loopKey = loopPaintKey(nodes);\n const paint = useMemo(() => loopPaint(loopKey), [loopKey]);\n const paintedEdges = useMemo(\n () => paintLoopEdges(edges, paint.tones, paint.loopOf),\n [edges, paint],\n );\n\n const nodeTypes = useMemo(\n () => ({\n step: StepNodeCard,\n control: ControlNodeCard,\n }),\n [],\n );\n\n // The workflow state in scope for the step being edited: its upstream steps'\n // outputs (`steps.<id>.output`) and, if a trigger precedes it, `trigger.event`.\n //\n // Each upstream step also carries its pickable output FIELDS when a shape is\n // known (`output-shape.ts`): an app action's declared `output`, else its\n // `sample`, else that step's last test run — so a later step can reference\n // `steps.<id>.output.<field>` without running anything first.\n const [stepTestOutputs, setStepTestOutputs] = useState<Record<string, unknown>>({});\n const [stepTestMetas, setStepTestMetas] = useState<Record<string, StepMeta>>({});\n // A For each's own saved Test (its item sample), by step id — read only as the loop's\n // item-shape fallback (`loopSourceFor`), never as that step's output.\n const [stepLoopSamples, setStepLoopSamples] = useState<Record<string, unknown[]>>({});\n // When each of those saved tests last ran — a persisted node sample strictly newer than it wins.\n const [stepTestRunAt, setStepTestRunAt] = useState<Record<string, string | null | undefined>>({});\n // The workflow's PERSISTED node samples (`node-samples.ts`): each node's last output shape from\n // any Test / node run / run, written server-side. Loaded per workflow (and again whenever a step\n // editor or the builder opens, alongside the saved tests below), so upstream keys survive a\n // reload, a reopen or another browser. A host without `loadNodeSamples` keeps `[]` — as before.\n // While the add-step builder is open, the step being drafted (declared here, before its first read).\n const [draftStepId, setDraftStepId] = useState<string | null>(null);\n const [nodeSamples, setNodeSamples] = useState<NodeSample[]>([]);\n const nodeSampleOpenKey = editingId ?? draftStepId ?? \"\";\n useEffect(() => {\n // Read the key so the effect re-runs when a step editor / the builder opens.\n void nodeSampleOpenKey;\n const load = api.loadNodeSamples;\n if (typeof load !== \"function\" || !value.id) {\n setNodeSamples([]);\n return;\n }\n let canceled = false;\n // Best-effort: a failed load keeps whatever was loaded before and never breaks the editor.\n load(value.id).then(\n (rows) => {\n if (!canceled) setNodeSamples(Array.isArray(rows) ? rows : []);\n },\n () => {},\n );\n return () => {\n canceled = true;\n };\n }, [api, value.id, nodeSampleOpenKey]);\n const persistedSamples = useMemo(() => indexNodeSamples(nodeSamples), [nodeSamples]);\n // Fresh (saved-test) and persisted outputs stay SEPARATE tiers, for SHAPES (skeletons included):\n // a persisted sample is offered only where it wins (no saved test, or strictly newer).\n const shapeTiers = useMemo(\n () => splitNodeOutputs(stepTestOutputs, persistedSamples, stepTestRunAt),\n [stepTestOutputs, persistedSamples, stepTestRunAt],\n );\n // …and for the Result PREVIEWS (real values only, never a skeleton).\n const previewTiers = useMemo(\n () => splitPreviewOutputs(stepTestOutputs, persistedSamples, stepTestRunAt),\n [stepTestOutputs, persistedSamples, stepTestRunAt],\n );\n const stepShapes = useMemo<StepShapeContext>(\n () => ({\n actionDef: (app, action) => actionDefs[app]?.find((a) => a.key === action),\n triggerDef: (app, trigger) => triggerDefs[app]?.find((t) => t.key === trigger),\n testOutputs: shapeTiers.fresh,\n persistedOutputs: shapeTiers.persisted,\n loopSamples: stepLoopSamples,\n }),\n [actionDefs, triggerDefs, shapeTiers, stepLoopSamples],\n );\n // The ▶ Run modal's projection, kept WHOLE: ONE call yields both the seed chips' ancestors\n // (`.steps`) and the `loop` the Current item / Index seed comes from (never a second membership\n // derivation). It passes `stepShapes` so the loop's sample item resolves.\n const runUpstreamSteps = useMemo(\n () =>\n runResult ? upstreamStateSources(runResult.stepId, nodes, edges, stepShapes) : undefined,\n [runResult, nodes, edges, stepShapes],\n );\n const runSteps = useMemo(() => runUpstreamSteps?.steps ?? [], [runUpstreamSteps]);\n // While the add-step builder is open `editingId` is null: a wired draft anchors the rail on\n // `draftStepId`, but a floating one makes `upstreamStateSources` offer EVERY node — including\n // the step being drafted (progressively committed as a node). Exclude it from its own sources.\n const upstreamState = useMemo(() => {\n const st = upstreamStateSources(editingId, nodes, edges, stepShapes, draftStepId);\n return { ...st, steps: excludeSelfStep(st.steps, editingId ?? draftStepId) };\n }, [editingId, draftStepId, nodes, edges, stepShapes]);\n // The merged workflow STATE the edited step reads (starting data, variables, upstream\n // writers in run order) — the picker's \"State\" section and its `state.<path>` previews.\n const stateShape = useMemo(\n () =>\n computeStateShape({\n anchorId: editingId ?? draftStepId,\n nodes,\n edges,\n initialState: value.initialState,\n variables: value.variables,\n shapes: stepShapes,\n previewOutputs: { ...previewTiers.persisted, ...previewTiers.fresh },\n }),\n [\n editingId,\n draftStepId,\n nodes,\n edges,\n value.initialState,\n value.variables,\n stepShapes,\n previewTiers,\n ],\n );\n // A stable identity for *which* steps are upstream. The memo above rebuilds on\n // every node drag and every field edit; this string changes only when the SET\n // does, so the fetch below doesn't re-run on each keystroke.\n // Includes the saved tests the projection reads beyond `steps` (an after-loop For each's last body step).\n const upstreamIdsKey = JSON.stringify([\n ...upstreamState.steps.map((s) => s.id),\n ...(upstreamState.extraSampleIds ?? []),\n ]);\n\n // Design-time sample values for the expression editor's Result pane: what each\n // upstream step's LAST TEST RUN actually captured, flattened onto the very refs\n // the picker inserts (`steps.<id>.output` and `steps.<id>.output.<field>`). Read\n // from the saved fixtures (`StepTest.lastRunOutput`), so it survives a reload.\n //\n // ⚠️ EDITOR-SIDE ONLY, like `upstreamStateSources` above: this is a PREVIEW of\n // values a past test produced. It is not what a full run resolves — nothing here\n // is sent to the engine.\n useEffect(() => {\n const ids = JSON.parse(upstreamIdsKey) as string[];\n if ((!editingId && !draftStepId) || ids.length === 0) {\n setStepTestOutputs({});\n setStepTestMetas({});\n setStepLoopSamples({});\n setStepTestRunAt({});\n return;\n }\n let canceled = false;\n // Best-effort, per step: a failed or empty list contributes no entry and never\n // breaks the picker — the same shape as the step editor's seed effect.\n Promise.all(\n ids.map(async (id) => {\n try {\n const tests = await api.listStepTests(value.id, id);\n // `listStepTests` is oldest-first, so the LAST entry is the most recent\n // fixture — the \"latest\" convention this file already uses twice.\n const latest = tests.length ? tests[tests.length - 1] : null;\n return latest\n ? {\n id,\n output: latest.lastRunOutput,\n runAt: latest.lastRunAt,\n meta: latest.lastRunMeta,\n loopSample: foreachTestSample(latest),\n }\n : null;\n } catch {\n return null;\n }\n }),\n ).then((res) => {\n // LOAD-BEARING, and its failure mode is silent: without this guard a slow\n // list that resolves after the editor was closed and reopened overwrites\n // the fresh samples with the ones it read before — the pane then previews a\n // POPULATED, STALE value, which is worse than showing none. Pinned by\n // `artifacts/T5.1.3-r2-checks.sh` §X (mutant M11).\n if (canceled) return;\n const next: Record<string, unknown> = {};\n const nextMetas: Record<string, StepMeta> = {};\n const nextLoopSamples: Record<string, unknown[]> = {};\n const nextRunAt: Record<string, string | null | undefined> = {};\n for (const r of res) {\n if (r?.meta) nextMetas[r.id] = r.meta;\n if (r?.loopSample) nextLoopSamples[r.id] = r.loopSample;\n if (!r || r.output === undefined || r.output === null) continue;\n next[r.id] = r.output;\n nextRunAt[r.id] = r.runAt;\n }\n setStepTestOutputs(next);\n setStepTestRunAt(nextRunAt);\n setStepTestMetas(nextMetas);\n setStepLoopSamples(nextLoopSamples);\n });\n return () => {\n canceled = true;\n };\n }, [api, value.id, editingId, draftStepId, upstreamIdsKey]);\n // The last test output, flattened onto the very refs the picker inserts: the\n // whole output, and each offered field path (nested ones included). Values\n // pass through unstringified — the modal's `effectiveSamples` stringifies.\n const declared = useMemo(() => declaredSamples(nodes, stepShapes), [nodes, stepShapes]);\n const sampleTiers = useMemo(\n () => ({ persisted: previewTiers.persisted, samples: declared.samples, event: declared.event }),\n [previewTiers.persisted, declared],\n );\n const stepSampleValues = useMemo(\n () =>\n upstreamSampleValues(\n upstreamState.steps,\n previewTiers.fresh,\n stepTestMetas,\n upstreamState.loop,\n sampleTiers,\n ),\n [upstreamState.steps, upstreamState.loop, previewTiers.fresh, stepTestMetas, sampleTiers],\n );\n const stepValueSources = useMemo(\n () =>\n upstreamSampleValueSources(\n upstreamState.steps,\n previewTiers.fresh,\n stepTestMetas,\n upstreamState.loop,\n sampleTiers,\n ),\n [upstreamState.steps, upstreamState.loop, previewTiers.fresh, stepTestMetas, sampleTiers],\n );\n\n // …merged with the host-supplied vars/secrets/sealSecret so the expression\n // editor's left panel shows every source at once.\n //\n // `ExpressionOptionsProvider` below LAYERS over whatever this editor is\n // mounted under, so the project's vars/secrets/documents arrive on their own\n // and need not be restated here — the `exprOptions` PROP is now only for a\n // host that wants to override or add something at this level.\n //\n // `sampleValues` is the one key that must UNION rather than replace, and that\n // is why the inherited scope is read explicitly: three disjoint ref\n // namespaces contribute to it (`var.*`/`documents.*` from the app shell,\n // anything the prop adds, and `steps.*` computed here), and layering alone\n // would let the object built below shadow the inherited one wholesale.\n const inheritedExprOptions = useExpressionOptions();\n // Every node's `nodes.<id>.config` keys — offered whether or not the node is upstream.\n const nodeConfigs = useMemo(() => nodeConfigSources(nodes), [nodes]);\n // …and their values, so the Test tab previews a config ref instead of calling it unresolved.\n const nodeConfig = useMemo(\n () => nodeConfigValues(nodes, triggerRegistration.subs),\n [nodes, triggerRegistration.subs],\n );\n // …and every node's static metadata (`nodes.<id>.meta.app|version|action|connectionId`, a\n // webhook's subscription), readable without a run. `version` is the one the canvas labels.\n const nodeMeta = useMemo(\n () => nodeMetaValues(nodes, triggerRegistration.subs, appsById, connections),\n [nodes, triggerRegistration.subs, appsById, connections],\n );\n const mergedExprOptions = useMemo<ExpressionOptions>(\n () => ({\n ...(exprOptions ?? {}),\n steps: upstreamState.steps,\n hasTrigger: upstreamState.hasTrigger,\n eventOutputs: upstreamState.eventOutputs,\n eventOutputsFrom: upstreamState.eventOutputsFrom,\n loop: upstreamState.loop,\n stateShape: { fields: stateShape.fields },\n nodeConfigs: nodeConfigs,\n nodeConfig,\n nodeMeta,\n valueSources: stepValueSources,\n sampleValues: {\n ...(inheritedExprOptions.sampleValues ?? {}),\n ...(exprOptions?.sampleValues ?? {}),\n // Static meta under a test's reported meta, which wins.\n ...nodeMetaSampleValues(nodeMeta),\n ...stepSampleValues,\n ...stateShape.sampleValues,\n },\n }),\n [\n exprOptions,\n inheritedExprOptions.sampleValues,\n upstreamState,\n stateShape,\n stepSampleValues,\n stepValueSources,\n nodeConfigs,\n nodeConfig,\n nodeMeta,\n ],\n );\n\n const restoreEdit = (direction: \"undo\" | \"redo\") => {\n if (readOnly) return;\n const snapshot = editHistory[direction]();\n if (!snapshot) return;\n const graph = restoreFlowEdit(value, snapshot);\n setNodes(graph.nodes.map((n) => ({ ...n, selected: n.id === selectedId })));\n setEdges(graph.edges.map((e) => ({ ...e, selected: e.id === selectedEdgeId })));\n setCanvas(snapshot.canvas);\n setConnections(snapshot.connections);\n if (!graph.nodes.some((n) => n.id === selectedId)) setSelectedId(null);\n if (!graph.edges.some((e) => e.id === selectedEdgeId)) setSelectedEdgeId(null);\n const keepEditor = graph.nodes.some((n) => n.id === editingId);\n if (!keepEditor) setEditingId(null);\n setBuilderOpen(false);\n setDraftStepId(null);\n setPendingConnect(null);\n setPendingDelete(null);\n setPendingCanvasDelete(null);\n setBuilderPlace(null);\n setContextMenu(null);\n setLoopNotice(null);\n setLaneError(null);\n textEditGroup.current = undefined;\n // Repaint from CURRENT run/problem data, and refresh authored fields in an open modal.\n // Test results, cached samples and in-flight tests are deliberately left alone.\n setRestoreVersion((v) => v + 1);\n onChange(\n withCanvas(\n flowToWorkflow(\n { ...value, nodes: snapshot.nodes, connections: snapshot.connections },\n graph.nodes,\n graph.edges,\n ),\n snapshot.canvas,\n ),\n );\n if (!keepEditor && !runResult) flowContainerRef.current?.focus({ preventScroll: true });\n };\n const restoreEditRef = useRef(restoreEdit);\n restoreEditRef.current = restoreEdit;\n useEffect(() => {\n const editor = flowContainerRef.current;\n if (!editor) return;\n let active = editor.contains(document.activeElement);\n const trackActive = (event: Event) => {\n // Removing a focused flyout button returns focus to body. Keep its editor active\n // until the author actually focuses or clicks somewhere else.\n if (event.type === \"focusin\" && event.target === document.body) return;\n active = editor.contains(event.target as Node);\n };\n const onKey = (event: KeyboardEvent) => {\n if (readOnly || event.defaultPrevented || isFlowTextTarget(event.target)) return;\n if (!editor.contains(event.target as Node) && !(active && event.target === document.body))\n return;\n const key = event.key.toLowerCase();\n if (!(event.ctrlKey || event.metaKey) || event.altKey) return;\n if (key !== \"z\" && !(key === \"y\" && !event.shiftKey)) return;\n event.preventDefault();\n restoreEditRef.current(key === \"y\" || event.shiftKey ? \"redo\" : \"undo\");\n };\n document.addEventListener(\"pointerdown\", trackActive);\n document.addEventListener(\"focusin\", trackActive);\n document.addEventListener(\"keydown\", onKey);\n return () => {\n document.removeEventListener(\"pointerdown\", trackActive);\n document.removeEventListener(\"focusin\", trackActive);\n document.removeEventListener(\"keydown\", onKey);\n };\n }, [readOnly]);\n\n // ── Right-click menu ────────────────────────────────────────────────────────\n //\n // The native browser menu is suppressed only where this one opens: the pane, a node,\n // an edge and the selection box. A right-click inside a text field keeps the native\n // menu (copy/paste). Read-only still opens it, with every item greyed.\n const openContextMenu = useCallback(\n (\n event: {\n clientX: number;\n clientY: number;\n target: EventTarget | null;\n preventDefault(): void;\n },\n nodeId?: string,\n ) => {\n if (isFlowTextTarget(event.target)) return;\n const box = flowContainerRef.current?.getBoundingClientRect();\n if (!box) return;\n event.preventDefault();\n const selection = selectedFlowElements(nodes, edges);\n const selected = selection.nodeIds;\n const nodeIds = contextMenuTargets(selected, nodeId);\n const alone = nodeId !== undefined && !selected.includes(nodeId);\n // A node outside the selection becomes the selection, so the menu's target shows.\n if (alone) {\n setNodes(\n nodes.map((n) =>\n n.selected !== (n.id === nodeId) ? { ...n, selected: n.id === nodeId } : n,\n ),\n );\n }\n setContextMenu({\n x: event.clientX - box.left,\n y: event.clientY - box.top,\n flow: screenToFlowPosition({ x: event.clientX, y: event.clientY }),\n nodeIds,\n edgeIds: alone ? [] : selection.edgeIds,\n });\n },\n [nodes, edges, setNodes, screenToFlowPosition],\n );\n const closeContextMenu = useCallback((restoreFocus: boolean) => {\n setContextMenu(null);\n if (restoreFocus) flowContainerRef.current?.focus({ preventScroll: true });\n }, []);\n const onContextMenuAction = (action: CanvasMenuAction) => {\n const menu = contextMenu;\n if (!menu || readOnly) return;\n if (action === \"duplicate\") duplicateSteps(menu.nodeIds);\n // The same pending selection + confirm as the Delete key and the node trash button.\n else if (action === \"delete\")\n setPendingDelete({ nodeIds: menu.nodeIds, edgeIds: menu.edgeIds });\n else {\n setPendingConnect(null);\n setBuilderPlace({\n position: menu.flow,\n ...(action === \"add-trigger\" ? { tab: \"triggers\" as const } : {}),\n });\n setBuilderOpen(true);\n }\n };\n\n const editor = (\n <StepControlsCtx.Provider value={controls}>\n <PortsLookupCtx.Provider value={portsLookup}>\n <FanOutCountsCtx.Provider value={fanOutCounts}>\n <LoopPaintCtx.Provider value={paint}>\n <CardDataProvider apps={appsById} registration={triggerRegistration}>\n <WorkflowProjectProvider project={project} workflowId={value.id}>\n <ExpressionOptionsProvider value={mergedExprOptions}>\n <section\n ref={flowContainerRef}\n className=\"w6w-flow\"\n tabIndex={-1}\n aria-label=\"Workflow editor\"\n style={{ width: \"100%\", height, position: \"relative\" }}\n onFocusCapture={(e) => {\n textEditGroup.current = isFlowTextTarget(e.target) ? {} : undefined;\n }}\n onBlurCapture={() => {\n textEditGroup.current = undefined;\n }}\n onKeyDown={(e) => {\n if (e.defaultPrevented) return;\n if (e.key !== \"Backspace\" && e.key !== \"Delete\") return;\n // Only delete selected elements when the key is aimed at the\n // canvas — never while a modal is open or the user is editing a field.\n // The modal <dialog> is a DOM descendant here, so its keystrokes\n // bubble up; without this guard, backspacing a typo deletes a node.\n if (readOnly || editingId || builderOpen || pendingDelete) return;\n const t = e.target as HTMLElement;\n if (\n t.isContentEditable ||\n t.tagName === \"INPUT\" ||\n t.tagName === \"TEXTAREA\" ||\n t.tagName === \"SELECT\" ||\n t.closest(\"dialog, .w6w-modal\") !== null\n ) {\n return;\n }\n const selection = selectedFlowElements(nodes, edges);\n if (!selection.nodeIds.length && !selection.edgeIds.length) return;\n e.preventDefault();\n if (!selection.nodeIds.length && selection.edgeIds.length === 1) {\n deleteEdge(selection.edgeIds[0]);\n } else {\n setPendingDelete(selection);\n }\n }}\n >\n <ReactFlow\n nodes={nodes}\n edges={paintedEdges}\n minZoom={0.05}\n // Straight segments with right-angle corners, not the library's\n // default bezier curve — reads clearer on a wide, branchy graph\n // than a sweeping curve does. One place: no edge object sets its\n // own `type`, so this alone governs every edge on the canvas.\n // `connectionLineType` matches it for the in-progress drag line,\n // so the preview doesn't curve while the settled edge won't.\n defaultEdgeOptions={{ type: \"smoothstep\" }}\n connectionLineType={ConnectionLineType.SmoothStep}\n onNodesChange={onNodesChange}\n onEdgesChange={onEdgesChange}\n onConnect={onConnect}\n onConnectStart={(_e, p) => {\n connectStartRef.current = p;\n }}\n onConnectEnd={onConnectEnd}\n onPaneClick={() => setLoopNotice(null)}\n onPaneContextMenu={(e) => openContextMenu(e)}\n onNodeContextMenu={(e, node) => openContextMenu(e, node.id)}\n onEdgeContextMenu={(e) => openContextMenu(e)}\n onSelectionContextMenu={(e) => openContextMenu(e)}\n // A pan or zoom moves the canvas out from under the menu's drop point.\n onMoveStart={() => setContextMenu(null)}\n isValidConnection={isValidConnection}\n // A finished drag is what makes a new coordinate stick: until this\n // existed, dragging went only through `onNodesChange` and never\n // marked the workflow changed, so the position was lost on reload.\n // `flowToWorkflow` (inside `emitChange`) does the conversion and the\n // rounding — nothing is converted here.\n //\n // Drag STOP, never `onNodeDrag`: the per-frame variant fires on every\n // animation frame of the gesture, and the host's auto-save is a\n // trailing debounce over emitted changes, so a per-frame emit is a\n // write storm by construction.\n //\n // No `readOnly` term is needed: `nodesDraggable={!readOnly}` below\n // means React Flow never starts the drag, so this cannot fire at all\n // in a read-only editor. Measured, not assumed — the probe's readOnly\n // fixture asserts the node does not move (F4-V1).\n onNodeDragStop={(_e, _n, dragged) => {\n const nextCanvas = membershipAfterDrag(dragged as StepNode[]);\n const membershipChanged = nextCanvas !== canvas;\n if (membershipChanged) setCanvas(nextCanvas);\n if (!savePosition && !membershipChanged) {\n editHistory.record(\n captureFlowEdit(\n value,\n nodes,\n edges,\n connectionsRef.current,\n nextCanvas,\n ),\n );\n return;\n }\n emitChange(nodes, edges, nextCanvas);\n }}\n onMoveEnd={(event, viewport) => {\n // FIRST statement, and load-bearing. React Flow passes\n // `event === null` when the move was NOT user-initiated\n // (@xyflow/react 12.11.1, `types/component-props.d.ts` on\n // `onMoveEnd`: \"If the movement is not user-initiated, the event\n // parameter will be `null`.\"). The `fitView` on open is exactly\n // such a move — without this guard every open would emit a change,\n // and with the host's auto-save every page load would be a write.\n if (!event) return;\n // `readOnly` is checked here and NOT delegated, because — unlike a\n // drag — panning and zooming stay enabled in a read-only editor (see\n // the prop's docstring), so this handler really does fire and a\n // viewer must not write to what they are only looking at.\n if (readOnly) return;\n // `savePosition` is deliberately NOT re-checked here: `withViewport`\n // is the single place that reads the flag for this path and returns\n // its argument unchanged when it is off, so a duplicate term would be\n // unobservable — measured as a surviving mutant (T3.3.2-mutants.sh\n // C5) and removed rather than shipped as an unpinnable branch.\n //\n // Emit ONLY when `withViewport` hands back a different reference:\n // it returns `value`'s base unchanged when the rounded viewport\n // already equals the stored one, so a pan that lands back where it\n // started emits nothing. Rate is bounded by the gesture, not the\n // frame — `onMoveEnd` is d3-zoom's terminal event, and\n // `@xyflow/system` additionally coalesces scroll-driven pans behind\n // a 150ms trailing timer of its own (no timer belongs here).\n const base = flowToWorkflow(value, nodes, edges);\n const next = withViewport(base, viewport);\n // `viewportOnly`: a camera move must not cost the host its run\n // paint (adhoc/run-paint) — only the definition changing does.\n if (next !== base) onChange(next, { viewportOnly: true });\n }}\n onSelectionChange={({ nodes: sel, edges: edgeSel }) => {\n // ⚠️ Only primitives are stored from this handler: React Flow re-invokes\n // it (inline) after every re-render of this component, so storing a\n // fresh array here defeats React's `Object.is` bail-out and loops —\n // a silent CPU burn in a page, a frozen main thread under Storybook.\n setSelectedId(sel[0]?.id ?? null);\n setSelectedEdgeId(edgeSel[0]?.id ?? null);\n if (loopNoticeSelRef.current !== (sel[0]?.id ?? null)) {\n loopNoticeSelRef.current = sel[0]?.id ?? null;\n setLoopNotice(null);\n }\n // Deliberately NOT clearing `laneError` here — see its declaration.\n }}\n nodeTypes={nodeTypes}\n nodesDraggable={!readOnly}\n nodesConnectable={!readOnly}\n // A click on a port adds a step from it (PortHandle) — not the library's\n // click-a-port-then-click-another connect mode, which shows nothing\n // after the first click and reads as a dead port.\n connectOnClick={false}\n elementsSelectable\n // Reopen at the camera the author left, when the workflow stores one;\n // otherwise fit the graph exactly as before. The two props are spread\n // in so only ONE of them is ever passed: they are mutually exclusive\n // by the library's own rule — \"If a default viewport is provided but\n // `fitView` is enabled, the default viewport will be ignored\"\n // (`types/component-props.d.ts` on `defaultViewport`) — and a stray\n // `fitView` would silently discard the restored view.\n {...(savedViewport ? { defaultViewport: savedViewport } : { fitView: true })}\n // Deletion is owned solely by the guarded onKeyDown handler above\n // (canvas-only, with a confirm). Disable React Flow's built-in\n // Backspace/Delete so it can't silently remove a node — e.g. while a\n // modal is open or the user is editing a field.\n deleteKeyCode={null}\n colorMode={colorMode}\n proOptions={{ hideAttribution: true }}\n >\n <Background gap={16} />\n {/* `showInteractive={false}` still suppresses the lock button; the\n child is appended AFTER the three built-ins (zoom in / zoom out /\n fit view), so auto-layout reads as the fourth control in the same\n stack — \"beside the zoom controls\", not a floating panel. It\n carries NO colour, background or border of its own: the\n `--xy-controls-button-*` → `--w6w-*` bridge in `styles.css` sets\n inherited custom properties on the `.w6w-flow` wrapper, so any\n control button added later is themed for free (measured in both\n stylesheet orders — T3.1.1's evaluation built this exact shape). */}\n <Controls showInteractive={false}>\n {!readOnly && (\n <ControlButton\n onClick={requestRelayout}\n title=\"Auto-layout — re-flow the graph into columns\"\n aria-label=\"Auto-layout the graph\"\n >\n {/* `icons.tsx`'s `layout` — the three-box hierarchy. It must NOT be a\n `fill=\"none\" stroke=…` glyph: the library styles a control button's\n svg as `svg { width: 100%; max-width: 12px; max-height: 12px;\n fill: currentColor }` (`@xyflow/react/dist/style.css`), so a stroked\n root would render as nothing at all in here — hence `layout`'s bare\n root (see its entry). */}\n <Icon name=\"layout\" />\n </ControlButton>\n )}\n </Controls>\n <MiniMap pannable zoomable style={{ background: \"var(--w6w-panel-2)\" }} />\n {!readOnly && (\n <Panel position=\"top-left\" className=\"w6w-flow-tools\">\n <button\n type=\"button\"\n className=\"w6w-btn\"\n onClick={() => setBuilderOpen(true)}\n >\n + Node\n </button>\n <IconButton\n label=\"Add note\"\n icon=\"sticky-note\"\n className=\"w6w-flow-tool\"\n data-testid=\"add-note\"\n onClick={addNote}\n />\n <IconButton\n label=\"Draw section\"\n title=\"Draw section — drag a frame on the canvas (Esc cancels)\"\n icon=\"frame\"\n className={`w6w-flow-tool${drawingSection ? \" active\" : \"\"}`}\n aria-pressed={drawingSection}\n data-testid=\"draw-section\"\n onClick={() => {\n setDrawingSection(!drawingSection);\n setSectionDraft(null);\n }}\n />\n </Panel>\n )}\n {/* The draw-section surface: above the graph (z 4, after the renderer)\n and below the panels (z 5), so the tool button stays clickable. */}\n {!readOnly && drawingSection && (\n <div\n className=\"w6w-section-draw nopan nodrag nowheel\"\n data-testid=\"section-draw-surface\"\n onPointerDown={(e) => {\n if (e.button !== 0) return;\n e.currentTarget.setPointerCapture(e.pointerId);\n const { clientX: x, clientY: y } = e;\n setSectionDraft({ sx: x, sy: y, ex: x, ey: y });\n }}\n onPointerMove={(e) => {\n const { clientX: x, clientY: y } = e;\n setSectionDraft((d) => d && { ...d, ex: x, ey: y });\n }}\n onPointerUp={() => {\n const d = sectionDraft;\n setSectionDraft(null);\n setDrawingSection(false);\n if (!d) return;\n const a = screenToFlowPosition({ x: d.sx, y: d.sy });\n const dragged = Math.abs(d.ex - d.sx) > 6 || Math.abs(d.ey - d.sy) > 6;\n addSectionAt(\n a,\n dragged ? screenToFlowPosition({ x: d.ex, y: d.ey }) : null,\n );\n }}\n >\n {sectionDraft &&\n (() => {\n const box = flowContainerRef.current?.getBoundingClientRect();\n const ox = box?.left ?? 0;\n const oy = box?.top ?? 0;\n return (\n <div\n className=\"w6w-section-draw-rect\"\n style={{\n left: Math.min(sectionDraft.sx, sectionDraft.ex) - ox,\n top: Math.min(sectionDraft.sy, sectionDraft.ey) - oy,\n width: Math.abs(sectionDraft.ex - sectionDraft.sx),\n height: Math.abs(sectionDraft.ey - sectionDraft.sy),\n }}\n />\n );\n })()}\n </div>\n )}\n {/* Which outcome the selected edge carries (core rfcs/workflow.md ·\n `Edge.when`). Revealed only when exactly ONE edge is selected —\n `selectedEdgeId` is already `edgeSel[0]`, so selecting a node or\n nothing hides it. top-left is `+ Node`, Controls are bottom-left,\n the MiniMap bottom-right. D-T1-7 SUPERSEDED (T1.1.1): id'd source\n handles now exist (the error exit port), so a fresh edge's lane IS\n chosen by which handle it was dragged from — this panel keeps its\n job as the RE-LANE affordance for an edge already drawn on the\n wrong port, not the only way to author an error edge. */}\n {!readOnly &&\n selectedEdge &&\n edgeLane(selectedEdge) !== \"each\" &&\n nodes.find((n) => n.id === selectedEdge.source)?.data.step.uses.app !==\n ROUTER_APP && (\n <Panel position=\"top-right\">\n <div className=\"w6w-edge-lane\">\n <span className=\"w6w-muted w6w-small\">Run on</span>\n {([\"success\", \"error\"] as const).map((lane) => (\n <button\n key={lane}\n type=\"button\"\n className={`w6w-btn w6w-btn-sm w6w-btn-ghost${\n edgeLane(selectedEdge) === lane ? \" active\" : \"\"\n }`}\n aria-pressed={edgeLane(selectedEdge) === lane}\n title={LANE_HINT}\n onClick={() => setEdgeLane(lane)}\n >\n {lane === \"success\" ? \"Success\" : \"Error\"}\n </button>\n ))}\n {laneError?.edgeId === selectedEdge.id && (\n <span className=\"w6w-edge-lane-err w6w-small\" role=\"alert\">\n {laneError.message}\n </span>\n )}\n </div>\n </Panel>\n )}\n {loopNotice && (\n <NodeToolbar\n nodeId={loopNotice.nodeId}\n position={Position.Bottom}\n isVisible\n >\n <div className=\"w6w-loop-notice w6w-small\" role=\"alert\">\n {loopRefusalMessage(loopNotice.reason)}\n </div>\n </NodeToolbar>\n )}\n <CanvasLayer\n canvas={canvas}\n readOnly={readOnly}\n savePosition={savePosition}\n onChange={onCanvasChange}\n onSectionDrop={onSectionDrop}\n onRequestDelete={(kind, id) =>\n !readOnly && setPendingCanvasDelete({ kind, id })\n }\n />\n </ReactFlow>\n {pendingCanvasDelete && (\n <ConfirmModal\n title={\n pendingCanvasDelete.kind === \"note\" ? \"Delete note\" : \"Delete section\"\n }\n message={\n pendingCanvasDelete.kind === \"note\"\n ? \"Delete this note?\"\n : \"Delete this section? Its nodes are kept.\"\n }\n confirmLabel=\"Delete\"\n onConfirm={() => {\n performCanvasDelete(pendingCanvasDelete.kind, pendingCanvasDelete.id);\n setPendingCanvasDelete(null);\n }}\n onClose={() => setPendingCanvasDelete(null)}\n />\n )}\n\n {builderOpen && (\n <StepBuilderModal\n initialTab={builderPlace?.tab}\n onClose={() => {\n setBuilderOpen(false);\n setPendingConnect(null);\n setBuilderPlace(null);\n setDraftStepId(null);\n }}\n onAdd={(built) => {\n const id = addBuiltStep(built);\n if (id) setDraftStepId(id);\n return id;\n }}\n // Progressive commit (T4.1.1): once `addBuiltStep` has minted\n // the step's id, every subsequent field change updates that\n // same node instead of waiting for a final \"Add node\" click.\n onDraftChange={(id, next) => updateStep(id, { id, ...next })}\n // The graph's node ids, so a name typed in the add flow is checked\n // for uniqueness the way a rename is.\n stepIds={nodes.map((n) => n.id)}\n // A picked app trigger lands in the node's own step editor,\n // on its config, the way any node opens.\n onOpenStep={(id) => {\n setBuilderOpen(false);\n setPendingConnect(null);\n setBuilderPlace(null);\n setDraftStepId(null);\n setEditView(\"props\");\n setEditingId(id);\n }}\n workflowId={value.id}\n // The new step's known upstream ancestors, from the handle a\n // connection drag was released from (T1.1.1) — so the builder's\n // own Test tab can seed `{{ steps.<id>.output.<field> }}` the\n // same way the step editor's Test tab already does.\n upstreamSteps={stepBuilderUpstreamSteps(pendingConnect, nodes, edges)}\n loop={stepBuilderLoop(pendingConnect, nodes, edges, stepShapes)}\n />\n )}\n\n {editingStep && editingId && (\n // No `key` on purpose: renaming a step updates `editingId`, and a keyed\n // remount would drop focus mid-keystroke. The modal seeds its own state\n // once and unmounts (editingId → null) between edits of different nodes.\n <StepEditModal\n workflowId={value.id}\n step={editingStep}\n restoreVersion={restoreVersion}\n // Graph ancestors of the editing step, from `upstreamStateSources`\n // (via `mergedExprOptions`) — the incoming-state picker seeds from\n // each ancestor's latest saved step-test rather than re-walking the graph.\n upstreamSteps={mergedExprOptions.steps ?? []}\n loop={mergedExprOptions.loop}\n readOnly={readOnly}\n fanOutCount={fanOutCounts.get(editingId) ?? 0}\n stateOutputFields={resolveOutputShape(\n stepShapes.actionDef?.(editingStep.uses.app, editingStep.uses.action),\n stepShapes.testOutputs?.[editingId],\n stepShapes.persistedOutputs?.[editingId],\n )?.fields.map((f) => f.key)}\n initialView={editView}\n stepProblems={editingNode?.data.stepProblems}\n otherStepIds={nodes.filter((n) => n.id !== editingId).map((n) => n.id)}\n onChange={(next) => updateStep(editingId, next)}\n onClose={() => setEditingId(null)}\n onTestRun={onTestRun}\n />\n )}\n\n {runResult && (\n <Modal\n title={`${collecting ? \"Run node\" : \"Test run\"}: ${runResult.stepId}`}\n onClose={() => setRunResult(null)}\n >\n {collecting && runningStep && (\n <StepRunCollect\n // Keyed on the step so switching nodes re-seeds the form.\n key={runResult.stepId}\n workflowId={value.id}\n step={runningStep}\n upstreamSteps={runSteps}\n loop={runUpstreamSteps?.loop}\n continues={\n onRunFromNode\n ? {\n stopAt: pausedStopAt(\n nodes.map((n) => n.data.step),\n runResult.stepId,\n ),\n }\n : undefined\n }\n onCancel={() => setRunResult(null)}\n onRun={(values, state) =>\n onRunFromNode\n ? performRunFromNode(runResult.stepId, values, state)\n : performRunStep(runResult.stepId, values, state)\n }\n />\n )}\n {/* The collect phase renders its own actions (Run + Cancel),\n gated on the required fields being filled. The status/result/log\n blocks scroll inside the body; Close stays pinned below it. */}\n {!collecting && (\n <>\n <div className=\"w6w-modal-body\">\n {runResult.status === \"running\" && (\n <p className=\"w6w-muted w6w-small\">Running…</p>\n )}\n {runResult.status === \"error\" && (\n <div className=\"w6w-result w6w-error\">\n {runResult.errorCode && (\n <div\n className=\"w6w-small\"\n style={{ opacity: 0.75, marginBottom: 4 }}\n >\n <code>{runResult.errorCode}</code>\n </div>\n )}\n {runResult.error || \"The node failed with no error message.\"}\n </div>\n )}\n {runResult.status === \"done\" && (\n <div>\n <div className=\"w6w-muted w6w-small\" style={{ marginBottom: 6 }}>\n Result\n </div>\n <ResultViewer value={runResult.value} maxHeight={360} />\n {runResult.meta && (\n <>\n <div\n className=\"w6w-muted w6w-small\"\n style={{ margin: \"10px 0 6px\" }}\n >\n Metadata\n </div>\n <ResultViewer value={runResult.meta} maxHeight={360} />\n </>\n )}\n </div>\n )}\n {runResult.logs && runResult.logs.length > 0 && (\n <div>\n <div\n className=\"w6w-muted w6w-small\"\n style={{ margin: \"10px 0 6px\" }}\n >\n Console output\n </div>\n <pre\n className=\"w6w-result\"\n style={{\n whiteSpace: \"pre-wrap\",\n maxHeight: 200,\n overflow: \"auto\",\n margin: 0,\n }}\n >\n {runResult.logs.join(\"\\n\")}\n </pre>\n </div>\n )}\n </div>\n <div className=\"w6w-modal-actions\">\n <button\n type=\"button\"\n className=\"w6w-btn\"\n onClick={() => setRunResult(null)}\n >\n Close\n </button>\n </div>\n </>\n )}\n </Modal>\n )}\n\n {pendingDelete !== null && (\n <ConfirmModal\n title={\n pendingDelete.nodeIds.length === 1\n ? \"Delete node\"\n : pendingDelete.nodeIds.length > 1\n ? `Delete ${pendingDelete.nodeIds.length} nodes`\n : `Delete ${pendingDelete.edgeIds.length} connections`\n }\n message={flowDeleteMessage(pendingDelete, nodes, edges)}\n confirmLabel=\"Delete\"\n onConfirm={() => {\n performDeleteSelection(pendingDelete);\n setPendingDelete(null);\n }}\n onClose={() => setPendingDelete(null)}\n />\n )}\n\n {contextMenu && (\n <CanvasContextMenu\n x={contextMenu.x}\n y={contextMenu.y}\n items={canvasMenuItems(contextMenu.nodeIds, !!readOnly)}\n onAction={onContextMenuAction}\n onClose={closeContextMenu}\n />\n )}\n </section>\n </ExpressionOptionsProvider>\n </WorkflowProjectProvider>\n </CardDataProvider>\n </LoopPaintCtx.Provider>\n </FanOutCountsCtx.Provider>\n </PortsLookupCtx.Provider>\n </StepControlsCtx.Provider>\n );\n return (\n <WorkflowConnectionsContext.Provider\n value={{ nodes: nodes.map((n) => n.data.step), connections, setConnections, readOnly }}\n >\n {editor}\n </WorkflowConnectionsContext.Provider>\n );\n}\n\n/** `@w6w/script`'s params the host passes through as source text, never resolved (engine `LITERAL_PARAMS`). */\nconst SCRIPT_LITERAL_KEYS = [\"code\"];\n\n/**\n * Parse the incoming-state box into the object it stands for. Anything that is\n * not a JSON **object** — unparseable, an array, a scalar, `null` — is not a\n * state at all and reads as `null`, which the callers turn into \"merge nothing\"\n * (Test) or \"don't run\" (▶ Run, a real execution).\n */\nfunction parseStateOverride(text: string): Record<string, unknown> | null {\n try {\n const v = JSON.parse(text);\n return v && typeof v === \"object\" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n}\n\n/**\n * A For each Test's override box: the usual JSON object (its `items` key replaces the\n * binding), or — what a pasted sample usually is — a bare array, taken as `items` itself.\n */\nfunction parseForeachOverride(text: string): Record<string, unknown> | null {\n try {\n const v = JSON.parse(text);\n if (Array.isArray(v)) return { items: v };\n } catch {\n return null;\n }\n return parseStateOverride(text);\n}\n\ntype ForeachSave = \"idle\" | \"saving\" | \"saved\" | \"failed\";\n\n/**\n * A For each's Test result: what its Items resolve to against the incoming state — the count\n * and the first item. Nothing inside the loop runs; the footer's Test saves the sample\n * (`foreachTestFixture`) so the body steps' picker offers the item's keys.\n */\nfunction ForeachTestResult({ items, save }: { items: unknown[] | undefined; save: ForeachSave }) {\n if (!items) {\n return (\n <output className=\"w6w-small\" style={{ display: \"block\" }}>\n <strong>Items</strong> doesn't resolve to a list yet: no step before this one has a saved\n test that produces it. Test an earlier step, or paste a sample list under{\" \"}\n <strong>Override the incoming state</strong> below.\n </output>\n );\n }\n const first = items[0];\n const keys = first !== undefined ? (inferOutputFields(first) ?? []).map((o) => o.key) : [];\n return (\n <div className=\"w6w-testout\">\n <div className=\"w6w-testout-label\">\n {items.length} {items.length === 1 ? \"item\" : \"items\"}\n </div>\n {items.length === 0 ? (\n <p className=\"w6w-muted w6w-small\">The list is empty, so there is no item to sample.</p>\n ) : (\n <>\n <div className=\"w6w-testout-label\">First item</div>\n <ResultViewer value={first} maxHeight={220} />\n </>\n )}\n {save === \"saved\" && (\n <output className=\"w6w-small\" style={{ display: \"block\" }}>\n Saved as this loop's sample.\n {keys.length > 0 && (\n <>\n {\" \"}\n Steps on <strong>Each item</strong> now offer <strong>Current item</strong> ›{\" \"}\n {keys.map((k, i) => (\n <span key={k}>\n {i > 0 && \", \"}\n <code>{k}</code>\n </span>\n ))}\n .\n </>\n )}\n </output>\n )}\n {save === \"failed\" && (\n <p className=\"w6w-small\" role=\"alert\">\n Couldn't save the sample. Try Test again.\n </p>\n )}\n </div>\n );\n}\n\n/**\n * The loop seed a test of a For each BODY step is sent as `state.foreach`: the sample item\n * (editable JSON) and the index (default 0). While \"Current item\" is untouched it FOLLOWS the\n * loop's `itemSample` (which can arrive after mount); once edited, the edit wins.\n */\nfunction useLoopSeed(loop: ExpressionLoopSource | undefined) {\n const [editedItem, setEditedItem] = useState<string | null>(null);\n const [indexText, setIndexText] = useState(\"0\");\n const itemText = editedItem ?? loopItemText(loop);\n const parsed = loop ? parseLoopSeed(itemText, indexText) : undefined;\n return { active: !!loop, itemText, indexText, setItemText: setEditedItem, setIndexText, parsed };\n}\ntype LoopSeed = ReturnType<typeof useLoopSeed>;\n\n/** The seed `startStateFromSeeds` takes: absent off a loop and while the control is invalid. */\nfunction loopSeedValue(seed: LoopSeed): { item?: unknown; index?: number } | undefined {\n return seed.parsed?.ok ? seed.parsed.value : undefined;\n}\n\n/** Why a loop seed refuses the run (`null` when it is fine, or there is no loop). */\nfunction loopSeedError(seed: LoopSeed): string | null {\n return seed.parsed && !seed.parsed.ok ? seed.parsed.error : null;\n}\n\n/** Sibling of {@link IncomingStateField}: the Current item / Index a loop-body test runs with. */\nfunction LoopSeedField({ seed, readOnly }: { seed: LoopSeed; readOnly?: boolean }) {\n if (!seed.active) return null;\n const error = loopSeedError(seed);\n return (\n <div className=\"w6w-field w6w-loop-seed\">\n <span>Current item</span>\n <textarea\n rows={3}\n value={seed.itemText}\n readOnly={readOnly}\n spellCheck={false}\n aria-label=\"Current item\"\n onChange={(e) => seed.setItemText(e.target.value)}\n />\n <span>Index</span>\n <input\n type=\"text\"\n inputMode=\"numeric\"\n value={seed.indexText}\n readOnly={readOnly}\n aria-label=\"Index\"\n onChange={(e) => seed.setIndexText(e.target.value)}\n />\n <span className=\"w6w-hint\">\n This step runs once per item of the For each. Test it as one iteration — starting from the\n sample item, or edit it.\n </span>\n {error && (\n <span className=\"w6w-hint\" role=\"alert\">\n {error}\n </span>\n )}\n </div>\n );\n}\n\n/**\n * The **incoming state** control — the one implementation behind both the step\n * editor's Test tab and the canvas ▶ Run collect form for a non-trigger step.\n * What varies between two runs of an already-configured step is the data\n * arriving at it, not its parameters, so this is what both surfaces collect.\n *\n * The raw JSON box is an **override** and is titled as one: it sits behind a\n * closed disclosure so neither surface opens on a JSON textarea, while the\n * upstream seed chips stay in plain sight above it. The disclosure opens by\n * itself whenever an override actually exists — seeded from a chip, remembered\n * from the last run, or typed — so an active override is never hidden.\n *\n * ⚠️ This component says nothing about what a **production** run resolves; it\n * collects what the test/run call is given.\n */\nfunction IncomingStateField({\n text,\n onChange,\n seeds,\n readOnly,\n expand,\n hint,\n}: {\n /** Raw JSON text of the override. `{}` (the default) means \"no override\". */\n text: string;\n onChange: (next: string) => void;\n seeds: SeedSource[];\n readOnly?: boolean;\n /** Opens the override disclosure (a caller with nothing to show without one). */\n expand?: boolean;\n /** Replaces the default hint under the override box. */\n hint?: ReactNode;\n}) {\n const parsed = parseStateOverride(text);\n const keyCount = parsed ? Object.keys(parsed).length : 0;\n const hasOverride = keyCount > 0;\n const [open, setOpen] = useState(hasOverride);\n // An override usually arrives AFTER this field has mounted — the Test tab's\n // remembered-state effect (`StepEditModal`) sets the text a network hop later\n // — and `useState`'s argument is a MOUNT-TIME value that never re-derives. Do\n // not collapse this back into the initial value: with `listStepTests` delayed\n // 900 ms, that left a remembered override IN EFFECT behind a CLOSED\n // disclosure (measured in T6.1.1's evaluation; ▶ Run escaped it only because\n // it withholds the whole form until its fixture has loaded). Only the\n // \"nothing → something\" transition reopens it, so a disclosure the operator\n // closed themselves stays closed while they keep typing in it.\n useEffect(() => {\n if (hasOverride || expand) setOpen(true);\n }, [hasOverride, expand]);\n // Seeding from an ancestor uses the output its last run captured; only a\n // fixture that never ran falls back to its own captured incoming state.\n const seedFrom = (test: StepTest) => {\n onChange(JSON.stringify(test.lastRunOutput ?? test.input ?? {}, null, 2));\n setOpen(true);\n };\n return (\n <div className=\"w6w-field w6w-incoming-state\">\n <span>Incoming state</span>\n {seeds.length > 0 && (\n <div className=\"w6w-seed-picker\">\n <div className=\"w6w-seed-chips\">\n {seeds.map((s) => (\n <button\n key={s.stepId}\n type=\"button\"\n className=\"w6w-chip w6w-seed-chip\"\n title={`Use ${s.label}'s saved test as the incoming state`}\n disabled={readOnly}\n onClick={() => seedFrom(s.test)}\n >\n <code>{s.label}</code>\n {s.test.lastRunStatus ? (\n <span className=\"w6w-muted w6w-small\">\n {\" · \"}\n {s.test.lastRunStatus}\n </span>\n ) : null}\n </button>\n ))}\n </div>\n </div>\n )}\n <details\n className=\"w6w-state-override\"\n open={open}\n onToggle={(e) => setOpen(e.currentTarget.open)}\n >\n <summary>\n Override the incoming state\n {keyCount > 0 ? ` · ${keyCount} key${keyCount === 1 ? \"\" : \"s\"} set` : \"\"}\n </summary>\n <textarea\n rows={3}\n value={text}\n readOnly={readOnly}\n spellCheck={false}\n aria-label=\"Incoming state override (JSON)\"\n onChange={(e) => onChange(e.target.value)}\n />\n <span className=\"w6w-hint\">\n {hint ?? (\n <>\n JSON whose keys replace this step's parameters by name, for this test only — so a\n script's data goes under <code>input</code>: <code>{'{\"input\": {…}}'}</code>. Upstream\n outputs already reach <code>{\"{{ nodes.<id>.output }}\"}</code> bindings from their\n saved tests. Reach for this to test against a state the flow cannot currently produce\n — a field no upstream step returns yet, or a case you can't reproduce by running the\n flow.\n </>\n )}\n </span>\n </details>\n </div>\n );\n}\n\n/**\n * Phase 1 of the canvas ▶ run: **collect the run's incoming state**, then hand\n * it to the host to invoke. Rendered inside the run modal, which is the chrome.\n *\n * Two shapes, because the two kinds of step start from different things:\n * - a **trigger** has no incoming state — it *is* the start — so it projects\n * its configured `fields` *definitions* into params (`fieldsToParams`), seeds\n * from their declared defaults (`seedValues`) and renders them through\n * {@link PropertyEntryForm} (chrome-less by contract, so it is mounted bare\n * here). The filled values become the run's starting state (`{ input }`), and\n * the step's **last saved values** come back pre-filled on top (T4.1.3).\n * - **everything else** is already configured, and what changes between two\n * runs is the data arriving at it. So it collects exactly what the Test tab\n * collects — {@link IncomingStateField}, the same component — and runs the\n * step with its **stored** `with` underneath. The configuration is not\n * re-collected here and is never rewritten by a run (R-I-1: the ▶ modal used\n * to render the Configure form).\n *\n * The trigger check comes first on purpose: a trigger *is* an internal node, and\n * its internal schema is the `fields` **editor**, not the fields themselves.\n *\n * `params` is fetched on **both** paths — a trigger renders them, and a\n * non-trigger needs them for the same required-params gate the Test tab applies\n * to `{...step.with, ...state}`. An app action fetches its action definition\n * exactly as `StepEditModal` does, showing \"Loading parameters…\" until it lands.\n */\nfunction StepRunCollect({\n workflowId,\n step,\n upstreamSteps,\n loop,\n onRun,\n onCancel,\n continues,\n}: {\n /** Fixture key, with `step.id` — where the remembered values are read from. */\n workflowId: string;\n step: FlowStep;\n /** Graph ancestors of this step; their saved tests are offered as seeds. */\n upstreamSteps: ExpressionStepSource[];\n /** The enclosing For each when this step is in its body (from the same projection call). */\n loop?: ExpressionLoopSource;\n /**\n * Fired when the user presses Run — with the trigger's filled values, or (for\n * every other step) the incoming-state override alone, plus the start state\n * seeded from the upstream steps' saved outputs (so the step's own\n * `{{ steps.<id>.output.<field> }}` references resolve). The two are\n * different things and stay separate: `values` are params, `state` is scope.\n */\n onRun: (values: Record<string, unknown>, state?: StepStartState) => void;\n onCancel: () => void;\n /** Present when Run continues downstream (`onRunFromNode`): the paused ids it stops before. */\n continues?: { stopAt: string[] };\n}) {\n const api = useW6WApi();\n const isTrigger = isTriggerStep(step.uses);\n const isInternal = isInternalApp(step.uses.app);\n const defs = useMemo(\n () => (isTrigger ? asFieldDefs(step.with?.fields) : []),\n [isTrigger, step.with],\n );\n\n // Known synchronously for triggers and internal nodes; `null` means \"an app\n // action, still to be fetched\" so only that path shows a loading line.\n const localParams = useMemo<ActionParam[] | null>(() => {\n if (isTrigger) return fieldsToParams(defs);\n if (isInternal) return internalNodeParams(step.uses.app, step.uses.action);\n return null;\n }, [isTrigger, isInternal, defs, step.uses.app, step.uses.action]);\n const [fetched, setFetched] = useState<ActionParam[] | null>(null);\n const params = localParams ?? fetched;\n\n // Mirrors StepEditModal's \"refetch actions + params\" effect rather than\n // inventing a second fetch pattern.\n useEffect(() => {\n if (localParams) return;\n if (!step.uses.app || !step.uses.action) {\n setFetched([]);\n return;\n }\n let canceled = false;\n setFetched(null);\n api\n .getAppActions(step.uses.app)\n .then((acts) => {\n if (canceled) return;\n setFetched(acts.find((a) => a.key === step.uses.action)?.params ?? []);\n })\n .catch(() => !canceled && setFetched([]));\n return () => {\n canceled = true;\n };\n }, [api, localParams, step.uses.app, step.uses.action]);\n\n // THE TRIGGER PATH's value bag, seeded once from its declared defaults.\n const [values, setValues] = useState<Record<string, unknown>>(() =>\n isTrigger ? seedValues(asFieldDefs(step.with?.fields)) : {},\n );\n // EVERY OTHER STEP's collect surface: the incoming-state override, as raw\n // JSON text — the same thing the Test tab collects, in the same component.\n const [stateText, setStateText] = useState(\"{}\");\n const seeds = useSeedSources(workflowId, upstreamSteps, !isTrigger);\n // The same fixtures the chips offer, projected into the run's start state —\n // one source, so what the chips SAY is upstream is what the run is GIVEN.\n const loopSeed = useLoopSeed(loop);\n const startState = startStateFromSeeds(seeds, loopSeedValue(loopSeed));\n\n // …then layered with what was entered the last time this step was tested or\n // run. `listStepTests` is oldest-first, so the LAST entry is the most recent\n // fixture — the same convention the step editor's upstream-seed effect uses.\n // Which slot is remembered follows what the surface collects: a trigger's\n // filled fields live in the fixture's `with`, an ordinary step's incoming\n // state in its `input` (that is what the Test tab writes there too).\n // An `ExprValue` (`{type:\"expr\",…}`) round-trips untouched: `FxField` derives\n // expression mode from the value, so it comes back as a chip, not as text.\n //\n // The REMEMBERED test input (`node_test_inputs`, server-side, written by every\n // Run / Test of this node) wins over the fixture: it is what was last typed on\n // ANY surface, including this one. A row that is `{}` was cleared — the form\n // stays on its declared defaults and the fixture is not consulted.\n const remembered = useRememberedTestInput(workflowId, step.id);\n const [seeded, setSeeded] = useState(false);\n const [prefilled, setPrefilled] = useState(false);\n // biome-ignore lint/correctness/useExhaustiveDependencies: seeds ONCE, when the remembered read settles — a later save must not re-seed\n useEffect(() => {\n if (!remembered.loaded) return;\n let canceled = false;\n const apply = (input: Record<string, unknown> | undefined, fromMemory: boolean) => {\n if (input && Object.keys(input).length > 0) {\n if (isTrigger) setValues((v) => ({ ...v, ...input }));\n else setStateText(JSON.stringify(input, null, 2));\n if (fromMemory) setPrefilled(true);\n }\n setSeeded(true);\n };\n if (remembered.input !== undefined) {\n apply(remembered.input, true);\n return;\n }\n api\n .listStepTests(workflowId, step.id)\n .then((tests) => {\n if (canceled) return;\n const latest = tests.length ? tests[tests.length - 1] : null;\n apply(isTrigger ? latest?.with : latest?.input, false);\n })\n // Never block or break the form: no fixture (or a failed list) just leaves\n // the declared defaults in place, silently.\n .catch(() => {\n if (!canceled) setSeeded(true);\n });\n return () => {\n canceled = true;\n };\n }, [api, workflowId, step.id, isTrigger, remembered.loaded]);\n const [formKey, setFormKey] = useState(0);\n const clearRemembered = () => {\n remembered.clear();\n setPrefilled(false);\n if (isTrigger) setValues(seedValues(defs));\n else setStateText(\"{}\");\n setFormKey((k) => k + 1);\n };\n\n // A raw-JSON draft that is not a values map (unparseable, or an array/scalar/\n // `null`) never reaches `values` — the entry form holds it back and says so\n // here. Run is a REAL execution, so it must not silently run the *previous*\n // payload while the operator is looking at a different one. The same applies\n // to the incoming-state box, which is parsed by the same rule.\n const [draftValid, setDraftValid] = useState(true);\n const state = parseStateOverride(stateText);\n const validDraft = isTrigger ? draftValid : state !== null;\n // What the run will actually be given. A non-trigger runs on its STORED\n // configuration with the incoming state merged over it — byte-for-byte what\n // the Test tab sends — so the required-params gate is applied to that, not to\n // the override alone. Never a second required-check.\n const effective = isTrigger ? values : { ...(step.with ?? {}), ...(state ?? {}) };\n const loopError = isTrigger ? null : loopSeedError(loopSeed);\n const canRun =\n !!params && seeded && validDraft && !loopError && requiredParamsFilled(params, effective);\n\n return (\n // `.w6w-stepconfig` frame + body + pinned footer (D-3): this component is a\n // direct <Modal> child, so the frame's `height:100%` resolves against the\n // dialog and only the form scrolls. The `.w6w-stack` keeps its own spacing.\n <div className=\"w6w-stepconfig\">\n <div className=\"w6w-modal-body\">\n <div className=\"w6w-stack\">\n {continues && (\n <p className=\"w6w-muted w6w-small\" data-testid=\"run-from-node-hint\">\n Runs this node, then continues through every node after it\n {continues.stopAt.length > 0 ? (\n <>\n {\" \"}\n and stops before{\" \"}\n {continues.stopAt.length === 1 ? \"the paused node\" : \"paused nodes\"}{\" \"}\n {continues.stopAt.map((id, i) => (\n <span key={id}>\n {i > 0 ? \", \" : \"\"}\n <code>{id}</code>\n </span>\n ))}\n </>\n ) : null}\n . Disabled nodes are skipped.\n </p>\n )}\n {prefilled && params !== null && seeded && <LastUsedNote onClear={clearRemembered} />}\n {params === null || !seeded ? (\n <p className=\"w6w-muted w6w-small\">\n {params === null ? \"Loading parameters…\" : \"Loading saved values…\"}\n </p>\n ) : isTrigger ? (\n <>\n <PropertyEntryForm\n // Remounted on Clear, so a raw-JSON draft is re-derived from the defaults too.\n key={formKey}\n params={params}\n values={values}\n onChange={setValues}\n onValidityChange={setDraftValid}\n />\n {params.length === 0 && (\n <span className=\"w6w-hint\">\n This trigger declares no fields — provide a sample payload to run with. It becomes\n the trigger's output state (<code>input</code>).\n </span>\n )}\n </>\n ) : (\n <>\n <p className=\"w6w-muted w6w-small\">\n Runs <code>{step.uses.action}</code> with the configuration saved on this node —\n only the incoming state changes per run. Edit the node to change how it is\n configured.\n </p>\n <LoopSeedField seed={loopSeed} />\n <IncomingStateField text={stateText} onChange={setStateText} seeds={seeds} />\n </>\n )}\n </div>\n </div>\n <div className=\"w6w-modal-actions\">\n <button type=\"button\" className=\"w6w-btn w6w-btn-ghost\" onClick={onCancel}>\n Cancel\n </button>\n {!canRun && params !== null && seeded && (\n <span className=\"w6w-muted w6w-small\">\n {loopError\n ? `${loopError} Fix it to run.`\n : !validDraft\n ? isTrigger\n ? \"The payload must be a JSON object to run.\"\n : \"The incoming state must be a JSON object to run.\"\n : isTrigger\n ? \"Fill the required fields to test.\"\n : \"This step is missing required configuration — set it on the Configure tab.\"}\n </span>\n )}\n <button\n type=\"button\"\n className=\"w6w-btn\"\n disabled={!canRun}\n // A trigger IS the start state, so it seeds nothing from upstream —\n // its filled fields go out as params (`{ input }`) exactly as before.\n onClick={() => {\n // Remembered server-side BEFORE the run, so reopening this modal (or\n // the Test tab, or the header Run) comes back prefilled whatever the\n // run's outcome. Secret literals are dropped; bindings are kept.\n remembered.save(isTrigger ? values : (state ?? {}), params ?? []);\n onRun(isTrigger ? values : (state ?? {}), isTrigger ? undefined : startState);\n }}\n >\n ▶ Run\n </button>\n </div>\n </div>\n );\n}\n\n// ── Node renderers ────────────────────────────────────────────────────────\n\n/**\n * A single connection handle, drawn to distinguish a single port from a\n * **multiple**-connection (fan-in / fan-out) port: a lone port keeps React\n * Flow's default dot, while `multiple` (cardinality > 1) renders a taller,\n * segmented bar so a node that accepts several inbound edges reads differently\n * from a single-in node (see core rfcs/node-types.md · Ports & cardinality).\n *\n * `variant === \"error\"` (T1.1.1) renders the second, visually subordinate\n * source handle every step/control node's error exit uses — `id` is what\n * lets React Flow (and `laneForSourceHandle`) tell it apart from the node's\n * ordinary, unnamed exit. The ONE shared handle component for both — no\n * second handle component and no raw inline `<Handle>` at either node card's\n * call site (`building-blocks.md`'s anti-duplication callout).\n */\n/** `@w6w/control` · `foreach` — the only card that renders the Each item handle. */\nfunction isForeachCard(step: FlowStep): boolean {\n return step.uses.app === CONTROL_APP && step.uses.action === \"foreach\";\n}\n\n/**\n * The loop dots above a body step's top-right corner: one per enclosing For each,\n * outermost first, each in that loop's colour and named on hover.\n */\nfunction LoopDots({ id }: { id: string }) {\n const { tones, loopOf } = useContext(LoopPaintCtx);\n const chain = enclosingLoops(id, loopOf);\n if (chain.length === 0) return null;\n return (\n <span className=\"w6w-loop-dots\">\n {chain.map((loop) => (\n <span\n key={loop}\n className=\"w6w-loop-dot\"\n role=\"img\"\n aria-label={`In loop · ${loop}`}\n title={`In loop · ${loop}`}\n style={{ background: loopToneVar(tones.get(loop) ?? 1) }}\n />\n ))}\n </span>\n );\n}\n\n/** A card's loop colour: only a For each carries one, for its Each item port. */\nfunction useLoopStyle(id: string): CSSProperties | undefined {\n return loopCardStyle(id, useContext(LoopPaintCtx).tones);\n}\n\nfunction PortHandle({\n type,\n position,\n multiple,\n id,\n variant,\n top,\n routeLabel,\n}: {\n type: \"source\" | \"target\";\n position: Position;\n multiple: boolean;\n id?: string;\n variant?: \"error\" | \"each\";\n top?: string;\n routeLabel?: string;\n}) {\n const nodeId = useNodeId();\n const ctrl = useContext(StepControlsCtx);\n const canAdd = !!nodeId && !!ctrl && !ctrl.readOnly;\n const add = () => {\n if (canAdd && nodeId) ctrl.onAddFromPort(nodeId, type, id);\n };\n const what =\n variant === \"error\"\n ? \"a step that handles this step's failure\"\n : variant === \"each\"\n ? \"the first step of this loop's body\"\n : type === \"target\"\n ? \"a step before this one\"\n : \"the next step\";\n return (\n <Handle\n type={type}\n position={position}\n id={id}\n className={\n variant === \"error\"\n ? \"w6w-handle-error\"\n : variant === \"each\"\n ? \"w6w-handle-each\"\n : multiple\n ? \"w6w-handle-multi\"\n : undefined\n }\n style={{\n ...(multiple ? { height: 22, borderRadius: 3, width: 8 } : {}),\n ...(top ? { top } : {}),\n }}\n // A click (no drag) adds a step from this port; a drag still draws a connection.\n onClick={canAdd ? add : undefined}\n title={\n routeLabel\n ? `${routeLabel} — drag or click to connect`\n : canAdd\n ? `Drag to empty canvas (or click) to add ${what} · drag to a port to connect`\n : variant === \"error\"\n ? \"On error — drag to route this step's failure separately\"\n : variant === \"each\"\n ? \"Each item — drag to the first step to repeat for every item\"\n : multiple\n ? type === \"target\"\n ? \"Accepts multiple incoming connections\"\n : \"Multiple outgoing connections\"\n : undefined\n }\n />\n );\n}\n\n/**\n * The node's hover toolbar: the run controls — ▶ run, ⏸ pause, ⃠ disable — then a divider, then\n * the edit controls (edit, copy, delete).\n */\nfunction NodeControls({ id, step, runnable }: { id: string; step: FlowStep; runnable?: boolean }) {\n const ctrl = useContext(StepControlsCtx);\n if (!ctrl || ctrl.readOnly) return null;\n // A run that continues downstream is a real run, so any node — flow control too — can start it.\n const canRun = runnable || ctrl.runsFromNode;\n const runLabel = ctrl.runsFromNode\n ? \"Run from this node — continues through the nodes after it\"\n : \"Test-run this node\";\n const paused = isPausedStep(step);\n const disabled = isDisabledStep(step);\n return (\n <NodeToolbar position={Position.Top} className=\"w6w-node-toolbar\">\n {canRun && (\n <button\n type=\"button\"\n className=\"w6w-node-toolbar-btn\"\n title={runLabel}\n aria-label={runLabel}\n onClick={() => ctrl.onRun(id)}\n >\n <Icon name=\"run\" size={15} />\n </button>\n )}\n <button\n type=\"button\"\n className=\"w6w-node-toolbar-btn\"\n data-testid=\"node-pause-toggle\"\n aria-pressed={paused}\n title={\n paused\n ? \"Resume — test runs go through this node\"\n : \"Pause — test runs stop before this node\"\n }\n aria-label={paused ? \"Unpause node\" : \"Pause node\"}\n onClick={() => ctrl.onTogglePause(id)}\n >\n <Icon name=\"pause\" size={15} />\n </button>\n <button\n type=\"button\"\n className=\"w6w-node-toolbar-btn\"\n data-testid=\"node-disable-toggle\"\n aria-pressed={disabled}\n title={disabled ? \"Enable — this node runs again\" : \"Disable — skip this node in every run\"}\n aria-label={disabled ? \"Enable node\" : \"Disable node\"}\n onClick={() => ctrl.onToggleDisable(id)}\n >\n <Icon name=\"ban\" size={15} />\n </button>\n <span className=\"w6w-node-toolbar-divider\" aria-hidden=\"true\" />\n <button\n type=\"button\"\n className=\"w6w-node-toolbar-btn\"\n title=\"Edit\"\n aria-label=\"Edit node\"\n onClick={() => ctrl.onEdit(id)}\n >\n <Icon name=\"edit\" size={15} />\n </button>\n <button\n type=\"button\"\n className=\"w6w-node-toolbar-btn\"\n title=\"Duplicate\"\n aria-label=\"Duplicate node\"\n onClick={() => ctrl.onDuplicate(id)}\n >\n <Icon name=\"copy\" size={15} />\n </button>\n <button\n type=\"button\"\n className=\"w6w-node-toolbar-btn danger\"\n title=\"Delete\"\n aria-label=\"Delete node\"\n onClick={() => ctrl.onDelete(id)}\n >\n <Icon name=\"trash\" size={15} />\n </button>\n </NodeToolbar>\n );\n}\n\n/** Card badge: a text glyph per mode (not colour), only with 2+ outgoing edges in a lane. */\nfunction FanOutBadge({ step, count }: { step: FlowStep; count: number }) {\n if (count < 2) return null;\n const parallel = step.fanOut === \"parallel\";\n const label = fanOutLabel(count, parallel ? \"parallel\" : \"sequential\");\n return (\n <div className=\"w6w-fanout-badge\" role=\"img\" aria-label={label} title={label}>\n <span aria-hidden=\"true\">{parallel ? \"⇉\" : \"→\"}</span> {count}\n </div>\n );\n}\n\n/** Persistent flags under a card — visible without hovering: ⏸ paused, ⃠ disabled. */\nfunction NodeFlagBadges({ step }: { step: FlowStep }) {\n const paused = isPausedStep(step);\n const disabled = isDisabledStep(step);\n if (!paused && !disabled) return null;\n return (\n <div>\n {disabled && (\n <span\n className=\"w6w-node-flag w6w-node-flag-disabled\"\n data-testid=\"step-disabled-badge\"\n role=\"img\"\n aria-label={DISABLED_LABEL}\n title={DISABLED_LABEL}\n >\n <Icon name=\"ban\" size={11} /> Disabled\n </span>\n )}\n {paused && (\n <span\n className=\"w6w-node-flag w6w-node-flag-paused\"\n data-testid=\"step-paused-badge\"\n role=\"img\"\n aria-label={PAUSED_LABEL}\n title={PAUSED_LABEL}\n >\n <Icon name=\"pause\" size={11} /> Paused\n </span>\n )}\n </div>\n );\n}\n\n/** `data-step-problem` (codes, space-joined) + `title` (tooltips, newline-joined); absent with no problems. */\nfunction problemAttrs(problems: StepProblem[] | undefined) {\n if (!problems || problems.length === 0) return {};\n return {\n \"data-step-problem\": problems.map((p) => p.code).join(\" \"),\n title: problems.map(stepProblemTooltip).join(\"\\n\"),\n };\n}\n\nfunction ProblemBadge({ problems }: { problems: StepProblem[] | undefined }) {\n if (!problems || problems.length === 0) return null;\n const tip = problems.map(stepProblemTooltip).join(\"\\n\");\n return (\n <span\n data-step-problem-badge=\"\"\n role=\"img\"\n aria-label={tip}\n title={tip}\n style={{\n position: \"absolute\",\n top: -9,\n right: -9,\n width: 18,\n height: 18,\n borderRadius: \"50%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n background: \"var(--w6w-danger)\",\n color: \"#fff\",\n }}\n >\n <Icon name=\"warning\" size={12} />\n </span>\n );\n}\n\n/**\n * The display title of an app trigger node's trigger (`api.getAppTriggers`),\n * falling back to its key until/unless the catalog answers. Read-only: the\n * editor never subscribes anything (the server derives that on publish).\n */\nfunction useAppTriggerTitle(step: FlowStep): string {\n const api = useW6WApi();\n const key = step.uses.action;\n const [title, setTitle] = useState<string | null>(null);\n const enabled = step.uses.trigger === true;\n const app = step.uses.app;\n useEffect(() => {\n if (!enabled || !api.getAppTriggers) return;\n let canceled = false;\n api\n .getAppTriggers(app)\n .then((ts) => !canceled && setTitle(ts.find((t) => t.key === key)?.title ?? null))\n .catch(() => {});\n return () => {\n canceled = true;\n };\n }, [api, app, key, enabled]);\n return title || key;\n}\n\n/**\n * ONE `listSubscriptionsForWorkflow` read per mounted workflow, shared with every\n * trigger card through context. Re-read when the workflow's trigger nodes change\n * (a publish rewrites them) and after a Retry. Absent API member => empty map.\n */\nfunction useTriggerRegistration(value: FlowWorkflow): TriggerRegistrationValue {\n const api = useW6WApi();\n const list = api.listSubscriptionsForWorkflow;\n const retrySub = api.retrySubscriptionRegistration;\n const workflowId = value.id;\n // App triggers, plus `@w6w/webhook` nodes: their URL is `nodes.<id>.meta.config.url`.\n const triggers = [\n ...appTriggerNodesOf(value.nodes),\n ...(value.nodes ?? []).filter((n) => n.uses?.app === WEBHOOK_APP && n.uses.trigger !== true),\n ];\n const hasTrigger = triggers.length > 0;\n const triggerSig = triggers\n .map(\n (n) =>\n `${n.id}:${n.uses.app}:${n.uses.action}:${connectionIdFor(n, value.connections) ?? \"\"}`,\n )\n .join(\"|\");\n const [subs, setSubs] = useState<readonly SubscriptionSummary[]>([]);\n const byNode = useMemo(() => subscriptionsByNode(subs), [subs]);\n const [tick, setTick] = useState(0);\n // biome-ignore lint/correctness/useExhaustiveDependencies: triggerSig/tick are refetch keys\n useEffect(() => {\n if (!list || !hasTrigger) {\n setSubs([]);\n return;\n }\n let canceled = false;\n list\n .call(api, workflowId)\n .then((next) => !canceled && setSubs(next))\n .catch(() => {});\n return () => {\n canceled = true;\n };\n }, [api, list, workflowId, hasTrigger, triggerSig, tick]);\n const retry = useMemo(\n () =>\n retrySub\n ? async (subscriptionId: string) => {\n try {\n await retrySub.call(api, subscriptionId);\n } finally {\n setTick((t) => t + 1);\n }\n }\n : undefined,\n [api, retrySub],\n );\n return useMemo(() => ({ byNode, subs, retry }), [byNode, subs, retry]);\n}\n\n/** Registration state, last error, last fire and Retry for a trigger node's bound subscription. */\nfunction TriggerRegistrationBadge({ nodeId }: { nodeId: string }) {\n const { byNode, retry } = useContext(TriggerRegistrationCtx);\n const [busy, setBusy] = useState(false);\n const sub = byNode.get(nodeId);\n const d = registrationDisplay(sub, retry !== undefined);\n if (!sub || !d) return null;\n return (\n <div\n className=\"w6w-small\"\n data-trigger-registration={sub.status}\n data-tone={d.tone}\n style={{ marginTop: 3, paddingLeft: 2 }}\n >\n <span style={d.tone === \"danger\" ? { color: \"var(--w6w-danger)\" } : undefined}>\n {d.label}\n </span>\n <span className=\"w6w-muted\"> · {d.lastFire}</span>\n {d.error && (\n <div role=\"alert\" style={{ color: \"var(--w6w-danger)\" }}>\n {d.error}\n </div>\n )}\n {d.retryVisible && retry && (\n <button\n type=\"button\"\n className=\"nodrag\"\n disabled={busy}\n onClick={() => {\n setBusy(true);\n retry(sub.id)\n .catch(() => {})\n .finally(() => setBusy(false));\n }}\n >\n Retry\n </button>\n )}\n </div>\n );\n}\n\nfunction StepNodeCard({ id, data, selected }: NodeProps<StepNode>) {\n const step = data.step;\n const apps = useContext(AppsCtx);\n const app = apps.get(step.uses.app);\n // The human app name (fall back to the raw id when the app isn't in the list).\n const appName = app?.displayName || step.uses.app || \"—\";\n // An app trigger node (`uses.trigger`): entry card — no inbound port, no error\n // exit — labelled \"<App> · <trigger title>\".\n const isTrigger = isTriggerStep(step.uses);\n const triggerTitle = useAppTriggerTitle(step);\n const cardName = step.uses.trigger ? `${appName} · ${triggerTitle}` : appName;\n // Per-step ports (T2.3.1): a persisted `ports.in > 1` renders a multi-input handle.\n const ports = nodePortsForStep(step, useContext(PortsLookupCtx));\n // T1.1.1 — run-execution visual, RunStatus × StepStatus (A3). `data.stepStatus`\n // is stamped by `Inner`'s live-run repaint effect, never by `workflowToFlow`.\n const visual = stepNodeVisual(data.stepStatus ?? \"no-run\", data.runStatus);\n const fanBadge = <FanOutBadge step={step} count={useContext(FanOutCountsCtx).get(id) ?? 0} />;\n const loopStyle = useLoopStyle(id);\n return (\n <div\n className={\n [data.loopOf ? \"w6w-node-in-loop\" : \"\", isDisabledStep(step) ? \"w6w-node-disabled\" : \"\"]\n .filter(Boolean)\n .join(\" \") || undefined\n }\n data-loop-of={data.loopOf}\n style={loopStyle}\n data-disabled={isDisabledStep(step) || undefined}\n data-paused={isPausedStep(step) || undefined}\n >\n <NodeControls id={id} step={step} runnable />\n <div\n // An app trigger gets the same half-pill entry chrome as a built-in trigger.\n className={isTrigger ? \"w6w-node-trigger\" : undefined}\n data-node-kind={isTrigger ? \"trigger\" : undefined}\n data-run-status={data.stepStatus ?? \"no-run\"}\n {...problemAttrs(data.stepProblems)}\n style={{\n // `relative` so the Handles center on the CARD, not the whole node\n // (which also spans the meta line below) — keeps ports vertically centered.\n position: \"relative\",\n // Missing-connection ring; the border stays the run-status visual.\n ...(data.stepProblems ? { boxShadow: \"0 0 0 2px var(--w6w-danger)\" } : {}),\n // Selection always wins the BORDER COLOUR (unchanged from before\n // T1.1.1 — the ternary this extends); width/style/opacity keep\n // reflecting the run status underneath so a selected running/failed\n // step is still distinguishable from a selected idle one.\n border: `${visual.borderWidth}px ${visual.borderStyle} ${\n selected ? \"var(--w6w-accent)\" : visual.borderColor\n }`,\n // A disabled node reads greyed out whatever its run status (`.w6w-node-disabled`).\n opacity: isDisabledStep(step) ? 0.45 : selected ? 1 : visual.opacity,\n background: \"var(--w6w-panel)\",\n color: \"var(--w6w-text)\",\n // The trigger half-pill's radius + padding live in `.w6w-node-trigger`.\n ...(isTrigger ? {} : { borderRadius: 4, padding: \"8px 12px\" }),\n minWidth: 180,\n fontSize: 13,\n display: \"flex\",\n alignItems: \"center\",\n gap: 10,\n }}\n >\n <ProblemBadge problems={data.stepProblems} />\n {ports.in > 0 && (\n <PortHandle type=\"target\" position={Position.Left} multiple={ports.in > 1} />\n )}\n <AppIcon\n src={app?.iconSvg}\n srcDark={app?.iconSvgDark}\n brandColor={app?.brandColor}\n name={appName}\n size={28}\n />\n <div style={{ minWidth: 0 }}>\n <div style={{ fontWeight: 600 }}>{cardName}</div>\n <div className=\"w6w-muted w6w-small\" style={{ marginTop: 2 }}>\n <code>{step.uses.action || \"—\"}</code>\n </div>\n </div>\n {ports.out > 0 && (\n <>\n <PortHandle type=\"source\" position={Position.Right} multiple={ports.out > 1} />\n {!isTrigger && (\n <PortHandle\n type=\"source\"\n position={Position.Bottom}\n multiple={false}\n id={ERROR_SOURCE_HANDLE}\n variant=\"error\"\n />\n )}\n </>\n )}\n </div>\n {fanBadge}\n <NodeFlagBadges step={step} />\n {isTrigger && step.uses.trigger === true && <TriggerRegistrationBadge nodeId={id} />}\n {data.loopOf && <LoopDots id={id} />}\n {/* Meta line under the card: the step id and (when known) the app version. */}\n <div\n className=\"w6w-muted\"\n style={{ marginTop: 3, fontSize: 10, opacity: 0.75, paddingLeft: 2 }}\n >\n {step.id}\n {app?.version ? ` - v${app.version}` : \"\"}\n </div>\n {/* The step's own Notes (settings → gear icon), shown here so a reader\n can associate it with the step without opening it — human override,\n 2026-08-30. Full text in `title=` for a hover, one visual line on\n the canvas itself; `.w6w-node-notes` (styles.css) truncates. */}\n {step.notes && (\n <div className=\"w6w-muted w6w-node-notes\" title={step.notes}>\n {step.notes}\n </div>\n )}\n </div>\n );\n}\n\nfunction ControlNodeCard({ id, data, selected }: NodeProps<StepNode>) {\n const step = data.step;\n const routes = routesForStep(step);\n const isRouter = step.uses.app === ROUTER_APP;\n // An If lays its True/False ports out like a Router's routes (ifPortLayout).\n const isIf = isIfStep(step);\n const routerPorts = routes.length ? routerPortLayout(routes) : isIf ? ifPortLayout() : undefined;\n const routeKey = JSON.stringify(routes.map((r) => r.id));\n const updateNodeInternals = useUpdateNodeInternals();\n // biome-ignore lint/correctness/useExhaustiveDependencies: route identities and order change handle positions.\n useEffect(() => {\n updateNodeInternals(id);\n }, [id, routeKey, updateNodeInternals]);\n const label = internalNodeLabel(step.uses.app, step.uses.action);\n const icon = internalNodeIcon(step.uses.app, step.uses.action);\n // Per-step ports (T2.3.1): triggers have no entry (0 in, 1 out); a fan-in node\n // (e.g. aggregate, or `ports.in > 1`) renders a multi-input handle.\n const ports = nodePortsForStep(step, useContext(PortsLookupCtx));\n // A trigger is the run's ENTRY, not a step that acts: it emits the start\n // payload and has no vendor call to fail, so there is no failure of its own\n // to route — no error exit port (human report, 2026-09-01). Triggers on the\n // canvas may be internal nodes or an app trigger node (uses.trigger, D-5);\n // an app trigger renders in StepNodeCard, which guards it separately.\n const isTrigger = isTriggerStep(step.uses);\n const isForeach = isForeachCard(step);\n // T1.1.1 — same run-execution visual StepNodeCard derives; see its comment.\n const visual = stepNodeVisual(data.stepStatus ?? \"no-run\", data.runStatus);\n const fanBadge = <FanOutBadge step={step} count={useContext(FanOutCountsCtx).get(id) ?? 0} />;\n const loopStyle = useLoopStyle(id);\n return (\n <div\n className={\n [\n isForeach ? \"w6w-node-foreach\" : \"\",\n data.loopOf ? \"w6w-node-in-loop\" : \"\",\n isDisabledStep(step) ? \"w6w-node-disabled\" : \"\",\n ]\n .filter(Boolean)\n .join(\" \") || undefined\n }\n data-loop-of={data.loopOf}\n style={loopStyle}\n data-disabled={isDisabledStep(step) || undefined}\n data-paused={isPausedStep(step) || undefined}\n >\n {/* Compute/trigger nodes can be test-run; flow-control nodes only start a run that continues. */}\n <NodeControls id={id} step={step} runnable={!isControlApp(step.uses.app)} />\n <div\n className={isTrigger ? \"w6w-node-trigger\" : isRouter ? \"w6w-node-router\" : undefined}\n data-node-kind={isTrigger ? \"trigger\" : undefined}\n data-run-status={data.stepStatus ?? \"no-run\"}\n {...problemAttrs(data.stepProblems)}\n style={{\n // `relative` so the Handles center on the CARD, not the whole node\n // (which also spans the meta line below) — keeps ports vertically centered.\n position: \"relative\",\n ...(data.stepProblems ? { boxShadow: \"0 0 0 2px var(--w6w-danger)\" } : {}),\n border: `${visual.borderWidth}px ${visual.borderStyle} ${\n selected ? \"var(--w6w-accent)\" : visual.borderColor\n }`,\n // A disabled node reads greyed out whatever its run status (`.w6w-node-disabled`).\n opacity: isDisabledStep(step) ? 0.45 : selected ? 1 : visual.opacity,\n background: \"var(--w6w-panel-2)\",\n color: \"var(--w6w-text)\",\n // A trigger's half-pill radius + padding live in `.w6w-node-trigger`\n // (styles/_flow.scss): an inline value here would beat the class.\n ...(isTrigger ? {} : { borderRadius: 4, padding: \"6px 14px 6px 8px\" }),\n minWidth: 140,\n // Past three route ports the Router grows a fixed step per port\n // (routerPortLayout); border-box so that height is the whole card's.\n ...(routerPorts?.minHeight\n ? { minHeight: routerPorts.minHeight, boxSizing: \"border-box\" as const }\n : {}),\n fontSize: 13,\n display: \"flex\",\n alignItems: \"center\",\n gap: 10,\n }}\n >\n <ProblemBadge problems={data.stepProblems} />\n {ports.in > 0 && (\n <PortHandle type=\"target\" position={Position.Left} multiple={ports.in > 1} />\n )}\n {icon && <InternalIcon icon={icon} />}\n <div style={{ minWidth: 0, textAlign: \"left\" }}>\n <div style={{ fontWeight: 600 }}>{label}</div>\n <div className=\"w6w-muted w6w-small\" style={{ marginTop: 2 }}>\n <code>{step.uses.action || \"—\"}</code>\n </div>\n </div>\n {isForeach && (\n <div className=\"w6w-foreach-ports w6w-small\" aria-hidden=\"true\">\n <span>Each item</span>\n <span>Done</span>\n </div>\n )}\n {/* Route labels inside the card, each beside its right-edge handle, the\n way For each labels Each item / Done. One row per port over the full\n card height, so a row's centre is its handle's `top`. */}\n {!!routerPorts?.right.length && (\n <div\n className=\"w6w-router-ports w6w-small\"\n style={{ gridTemplateRows: `repeat(${routerPorts.right.length}, 1fr)` }}\n aria-hidden=\"true\"\n >\n {routerPorts.right.map((port) => (\n <span key={port.id} title={port.label}>\n {port.label}\n </span>\n ))}\n </div>\n )}\n {ports.out > 0 && (\n <>\n {isForeach && (\n <PortHandle\n type=\"source\"\n position={Position.Right}\n multiple={false}\n id={EACH_SOURCE_HANDLE}\n variant=\"each\"\n />\n )}\n {routerPorts ? (\n <>\n {routerPorts.right.map((port) => (\n <PortHandle\n key={port.id}\n type=\"source\"\n position={Position.Right}\n multiple={false}\n id={port.handleId}\n top={port.top}\n routeLabel={port.label}\n />\n ))}\n {routerPorts.bottom && (\n <>\n <PortHandle\n type=\"source\"\n position={Position.Bottom}\n multiple={false}\n id={routerPorts.bottom.handleId}\n routeLabel={routerPorts.bottom.label}\n />\n <span className=\"w6w-router-fallback-label w6w-small\" aria-hidden=\"true\">\n {routerPorts.bottom.label}\n </span>\n </>\n )}\n </>\n ) : (\n // A For each's Done port is named: React Flow anchors a handle-less edge\n // to the FIRST source handle, which here is Each item.\n <PortHandle\n type=\"source\"\n position={Position.Right}\n multiple={ports.out > 1}\n id={isForeach ? routeHandle(FOREACH_DONE_ROUTE) : undefined}\n />\n )}\n {!isTrigger && !isRouter && !isIf && step.uses.app !== RACE_APP && (\n <PortHandle\n type=\"source\"\n position={Position.Bottom}\n multiple={false}\n id={ERROR_SOURCE_HANDLE}\n variant=\"error\"\n />\n )}\n </>\n )}\n </div>\n {fanBadge}\n <NodeFlagBadges step={step} />\n {data.loopOf && <LoopDots id={id} />}\n {data.legacyLoop && (\n <div className=\"w6w-loop-legacy-note w6w-small\">\n This loop was converted from an older definition. Its steps after For each now run once\n per item; check the order, then save.\n </div>\n )}\n {/* Meta line under the card: the step id (internal nodes carry no version). */}\n <div\n className=\"w6w-muted\"\n style={{ marginTop: 3, fontSize: 10, opacity: 0.75, paddingLeft: 2 }}\n >\n {step.id}\n </div>\n {/* The step's own Notes — see StepNodeCard's own copy for the rationale. */}\n {step.notes && (\n <div className=\"w6w-muted w6w-node-notes\" title={step.notes}>\n {step.notes}\n </div>\n )}\n </div>\n );\n}\n\n// ── Step edit modal (Form ⇄ JSON) ─────────────────────────────────────────\n\n/**\n * The state the Test tab PREVIEWS its resolved params against: the seeded `testStartState`\n * (what the test will actually send) with, for each upstream `nodes.<id>.output` and the\n * `trigger.event` that the seeds do not carry, the value the editor already previews in the ƒx\n * Result (`sampleValues`: a persisted test's kept value or the app's declared `sample`). A seeded\n * output always wins. Only the PREVIEW reads this; the invoke is still sent `testStartState`.\n */\nexport function previewStartState(\n state: StepStartState | undefined,\n sampleValues: Record<string, unknown> | undefined,\n): StepStartState | undefined {\n if (!sampleValues) return state;\n const steps: NonNullable<StepStartState[\"steps\"]> = { ...(state?.steps ?? {}) };\n let added = false;\n for (const [ref, value] of Object.entries(sampleValues)) {\n const m = /^nodes\\.([^.]+)\\.output$/.exec(ref);\n if (!m || steps[m[1]]?.output !== undefined) continue;\n steps[m[1]] = { ...(steps[m[1]] ?? {}), output: value };\n added = true;\n }\n const event = sampleValues[\"trigger.event\"];\n const addEvent = event !== undefined && state?.trigger?.event === undefined;\n if (!added && !addEvent) return state;\n return {\n ...(state ?? {}),\n ...(added ? { steps } : {}),\n ...(addEvent ? { trigger: { ...(state?.trigger ?? {}), event } } : {}),\n };\n}\n\nexport function StepEditModal(props: StepEditModalProps) {\n // One editor for every node. An app trigger node rides the action editor:\n // Setup (app, account, trigger) · Configure (its params) · Test.\n return <ActionStepEditModal {...props} />;\n}\n\ninterface StepEditModalProps {\n workflowId: string;\n step: FlowStep;\n /** Refresh authored fields after undo/redo without remounting the Test tab. */\n restoreVersion?: number;\n /** Graph ancestors of this step (from `upstreamStateSources`); the incoming-state picker seeds from their saved tests. */\n upstreamSteps: ExpressionStepSource[];\n /** The enclosing For each when this step is in its body: seeds `state.foreach` on Test. */\n loop?: ExpressionLoopSource;\n onChange: (next: FlowStep) => void;\n onClose: () => void;\n readOnly?: boolean;\n initialView?: EditView;\n /** Most outgoing edges this node has in one lane; \"Run next nodes\" needs >= 2. */\n fanOutCount?: number;\n /** This step's own output field keys, offered by \"Write to state\" › Pick fields (free text still accepted). */\n stateOutputFields?: string[];\n /** Fired the instant the footer Test button is clicked, before the test runs (T1.1.1). */\n onTestRun?: () => void;\n /** Host-supplied problems for this step; a dangling connection locks Configure/Test, a fixable one gets a button. */\n stepProblems?: StepProblem[];\n /** The graph's other node ids — a rename onto one of them is refused with a message. */\n otherStepIds?: string[];\n}\n\nfunction ActionStepEditModal({\n workflowId,\n step: initialStep,\n restoreVersion,\n upstreamSteps,\n loop,\n onChange,\n onClose,\n readOnly,\n initialView = \"props\",\n fanOutCount = 0,\n stateOutputFields,\n onTestRun,\n stepProblems,\n otherStepIds,\n}: StepEditModalProps) {\n const api = useW6WApi();\n const apps = useContext(AppsCtx);\n const [step, setStep] = useState<FlowStep>(initialStep);\n const connectionScope = useWorkflowConnections();\n const connectionId = connectionIdFor(step, connectionScope?.connections);\n const effectiveStep = { ...step, uses: { ...step.uses, connection: connectionId } };\n // Checked against the LOCAL step so choosing another connection unblocks at once.\n const unresolvedConnection = step.uses.connectionRef !== undefined && !connectionId;\n const blocked = unresolvedConnection || isConnectionBlocked(effectiveStep, stepProblems);\n const connectionProblem = stepProblems?.find(\n (p): p is Extract<StepProblem, { code: \"unknown_connection\" }> =>\n p.code === \"unknown_connection\" && p.connection === connectionId,\n );\n const fixable = (stepProblems ?? []).filter((p) => \"fix\" in p);\n // Same shape as the add modal: Setup/Configure/Test tabs with the Configure\n // tab showing form (props) / full-step JSON (code) / params JSON\n // (params-code) / node settings (config).\n const [tab, setTab] = useState<\"setup\" | \"configure\" | \"test\">(blocked ? \"setup\" : \"configure\");\n const [configView, setConfigView] = useState<ConfigView>(\n initialView === \"json\" ? \"code\" : initialView === \"settings\" ? \"config\" : \"props\",\n );\n // The Test tab's own props/JSON toggle state (A4/D-7) — deliberately NOT\n // `configView`, which ranges over `\"params-code\"`/`\"config\"` too, neither of\n // which is in the Test tab's narrowed `[\"props\",\"code\"]` set. Always starts\n // on the row list.\n const [testView, setTestView] = useState<\"props\" | \"code\">(\"props\");\n // Draft text backing the \"code\" (full-step, read-only) view.\n const [codeText, setCodeText] = useState(() => stepToJson(initialStep));\n // Draft text backing the \"params-code\" (params-only, writable) view.\n const [testState, setTestState] = useState(\"{}\");\n // Drives the footer \"Test\" button, which triggers the body's <StepTestRun> so\n // the run + persist logic isn't duplicated across two affordances.\n const testRunRef = useRef<StepTestRunHandle>(null);\n const [testBusy, setTestBusy] = useState(false);\n const lastRestoreVersion = useRef(restoreVersion);\n useEffect(() => {\n if (lastRestoreVersion.current === restoreVersion) return;\n lastRestoreVersion.current = restoreVersion;\n setStep(initialStep);\n setCodeText(stepToJson(initialStep));\n }, [restoreVersion, initialStep]);\n\n const [params, setParams] = useState<ActionParam[] | null>(null);\n const [actions, setActions] = useState<ActionDef[] | null>(null);\n const [conns, setConns] = useState<ConnectionSummary[] | null>(null);\n const [connsFailed, setConnsFailed] = useState(false);\n const isInternal = isInternalApp(step.uses.app);\n // An app trigger node (`uses.trigger`): its \"actions\" are the app's triggers.\n const isAppTrigger = step.uses.trigger === true;\n\n // Refetch actions + params whenever the app/action identity changes. P-3:\n // this must refetch on an APP change alone (action `\"\"` included) — an\n // early return here on a missing action left `actions` holding the\n // PREVIOUS app's list, stale-ing the Action <select> after Change (D-1).\n useEffect(() => {\n if (isInternal) {\n setParams(internalNodeParams(step.uses.app, step.uses.action));\n const grouped = INTERNAL_NODES.filter(\n (node) => node.app === step.uses.app && node.groupActions && !node.hidden,\n );\n setActions(\n grouped.length\n ? grouped.map((node) => ({\n key: node.action,\n title: node.label,\n params: node.params,\n }))\n : null,\n );\n return;\n }\n if (!step.uses.app) {\n setActions(null);\n setParams([]);\n return;\n }\n let canceled = false;\n setParams(null);\n (isAppTrigger ? getTriggerDefs(api, step.uses.app) : api.getAppActions(step.uses.app))\n .then((acts) => {\n if (canceled) return;\n setActions(acts);\n setParams(\n step.uses.action ? (acts.find((a) => a.key === step.uses.action)?.params ?? []) : [],\n );\n })\n .catch(() => !canceled && setParams([]));\n return () => {\n canceled = true;\n };\n }, [api, step.uses.app, step.uses.action, isInternal, isAppTrigger]);\n\n const appSelectionRequest = useRef(0);\n useEffect(\n () => () => {\n appSelectionRequest.current++;\n },\n [],\n );\n\n const refetchConns = useCallback(() => {\n if (isInternal || !step.uses.app) return;\n api\n .listConnectionsForApp(step.uses.app)\n .then((c) => {\n setConns(c);\n setConnsFailed(false);\n })\n .catch(() => setConnsFailed(true));\n }, [api, step.uses.app, isInternal]);\n\n useEffect(() => {\n if (isInternal || !step.uses.app) return;\n let canceled = false;\n setConns(null);\n setConnsFailed(false);\n api\n .listConnectionsForApp(step.uses.app)\n .then((c) => {\n if (canceled) return;\n setConns(c);\n setConnsFailed(false);\n })\n .catch(() => !canceled && setConnsFailed(true));\n return () => {\n canceled = true;\n };\n }, [api, step.uses.app, isInternal]);\n\n const commit = useCallback(\n (next: FlowStep) => {\n setStep(next);\n onChange(next);\n },\n [onChange],\n );\n\n // A script's `{{ }}` markers become code reads when the step opens (quiet note + Undo).\n const scriptConversion = useScriptConversion({\n enabled: step.uses.app === SCRIPT_APP && !readOnly,\n values: step.with ?? {},\n onChange: (w) => commit({ ...step, with: w }),\n });\n\n const changeConfigView = (v: ConfigView) => {\n if (v === \"code\") setCodeText(stepToJson(step));\n setConfigView(v);\n };\n // Inline step rename (pencil next to the name); `updateStep` fixes up edges. A refused\n // name is reported inline (the host also drops a duplicate id, silently).\n const rename = (id: string) => {\n const err = stepNameError(id, otherStepIds ?? []);\n if (!err) commit({ ...step, id });\n return err;\n };\n\n const testable = !!step.uses.app && !!step.uses.action && !isControlApp(step.uses.app);\n // A For each's Test resolves its Items (nothing runs) and saves the sample.\n const isForeach = isForeachStep(step);\n // A manual/webhook trigger's Test tab fills its configured `fields` into\n // `{ input }` (via TriggerFillForm) rather than running the raw config.\n const isTrigger = isTriggerStep(step.uses);\n // A4/D-7: the tabs-bar toggle is enabled and narrowed to props/code ONLY on\n // this arm — the non-trigger, testable Test tab, the one that mounts\n // `<ResolvedParams>`. The trigger arm keeps the dim four (`PropertyEntryForm`\n // renders its own toggle inside `TriggerFillForm`'s body); Setup/Configure\n // are unchanged.\n const isTestPropsCode = tab === \"test\" && testable && !isTrigger;\n\n // The editing step's graph ancestors that carry a saved step-test, offered as\n // one-click seeds for the incoming state. The SAME hook the canvas ▶ Run\n // collect form uses — one implementation, so the two surfaces cannot drift.\n const seedSources = useSeedSources(\n workflowId,\n upstreamSteps,\n (testable && !isTrigger) || isForeach,\n );\n // …and the start state the test is SENT with, from those same fixtures. This\n // is what makes `{{ steps.<id>.output.<field> }}` in this step's `with`\n // resolve to what that step last produced instead of to \"\".\n const loopSeed = useLoopSeed(testable && !isTrigger ? loop : undefined);\n const testStartState = startStateFromSeeds(seedSources, loopSeedValue(loopSeed));\n const previewState = previewStartState(testStartState, useExpressionOptions().sampleValues);\n\n // The incoming state this step was last tested or run with comes back (T4.1.3\n // on this surface's own noun): the fixture's `input` slot is where both\n // surfaces write it. Applied only while the box is still untouched, so a slow\n // list can never overwrite what the operator is typing.\n //\n // The remembered test input (`node_test_inputs`, written by every Run / Test\n // of this node on any surface) wins over the fixture; a `{}` row was cleared.\n // A For each keeps its fixture-only seeding (its Test saves a sample instead).\n const rememberedTest = useRememberedTestInput(\n (testable && !isTrigger) || isForeach ? workflowId : undefined,\n step.id,\n );\n const [testPrefilled, setTestPrefilled] = useState(false);\n // biome-ignore lint/correctness/useExhaustiveDependencies: seeds ONCE, when the remembered read settles — a later save must not re-seed\n useEffect(() => {\n if ((!testable || isTrigger) && !isForeach) return;\n if (!rememberedTest.loaded) return;\n if (!isForeach && rememberedTest.input !== undefined) {\n const input = rememberedTest.input;\n if (Object.keys(input).length === 0) return;\n const next = JSON.stringify(input, null, 2);\n setTestState((cur) => (cur.trim() === \"{}\" ? next : cur));\n setTestPrefilled(true);\n return;\n }\n let canceled = false;\n api\n .listStepTests(workflowId, step.id)\n .then((tests) => {\n if (canceled) return;\n const latest = tests.length ? tests[tests.length - 1] : null;\n if (!latest?.input || Object.keys(latest.input).length === 0) return;\n const next = JSON.stringify(latest.input, null, 2);\n setTestState((cur) => (cur.trim() === \"{}\" ? next : cur));\n })\n // Best-effort, exactly like the seed effect: no fixture (or a failed list)\n // just leaves the box empty.\n .catch(() => {});\n return () => {\n canceled = true;\n };\n }, [api, workflowId, step.id, testable, isTrigger, isForeach, rememberedTest.loaded]);\n\n // The incoming-state override, and the payload it produces. The step's STORED\n // configuration is what runs; the override is merged over it. A box that is\n // not a JSON object overrides nothing (see `parseStateOverride`).\n const testOverride = isForeach ? parseForeachOverride(testState) : parseStateOverride(testState);\n const testValues = { ...(step.with ?? {}), ...(testOverride ?? {}) };\n // The resolved incoming state saved alongside the fixture — the slot the ▶ Run\n // collect form reads back, and what the upstream seed chips write into.\n const testInput = testOverride ?? {};\n const canTest = !!params && !loopSeedError(loopSeed) && requiredParamsFilled(params, testValues);\n // A For each's Test: its Items against the same start state, and the save of the sample.\n const foreachItems = isForeach\n ? resolveLoopItemsInState(testValues.items, testStartState)\n : undefined;\n const [foreachSave, setForeachSave] = useState<ForeachSave>(\"idle\");\n const changeTestState = (next: string) => {\n setTestState(next);\n setForeachSave(\"idle\");\n };\n const saveForeachTest = async () => {\n if (!foreachItems) return;\n setForeachSave(\"saving\");\n try {\n await api.saveStepTest(workflowId, step.id, foreachTestFixture(foreachItems, testInput));\n setForeachSave(\"saved\");\n } catch {\n setForeachSave(\"failed\");\n }\n };\n\n // Header icon mirrors the canvas node: the app's icon for app steps, the\n // internal glyph for triggers/actions/control nodes (same as the node cards).\n const app = apps.get(step.uses.app);\n const internalIcon = isInternal ? internalNodeIcon(step.uses.app, step.uses.action) : null;\n const titleIcon = isInternal ? (\n internalIcon ? (\n <InternalIcon icon={internalIcon} />\n ) : null\n ) : (\n <AppIcon\n src={app?.iconSvg}\n srcDark={app?.iconSvgDark}\n brandColor={app?.brandColor}\n name={app?.displayName}\n />\n );\n\n return (\n <Modal\n ariaLabel=\"Edit step\"\n titleIcon={titleIcon}\n title={<StepNameEditor value={step.id} onCommit={rename} readOnly={readOnly} />}\n onClose={onClose}\n size=\"wide\"\n >\n <div className=\"w6w-stepconfig\">\n <div className=\"w6w-tabsbar\">\n <div className=\"w6w-subtabs\">\n {([\"setup\", \"configure\", \"test\"] as const)\n .filter((t) => step.uses.app !== RACE_APP || t !== \"test\")\n .map((t) => (\n <button\n key={t}\n type=\"button\"\n className={`w6w-subtab${tab === t ? \" active\" : \"\"}`}\n disabled={blocked && t !== \"setup\"}\n onClick={() => setTab(t)}\n >\n {t === \"setup\" ? \"Setup\" : t === \"configure\" ? \"Configure\" : \"Test\"}\n </button>\n ))}\n </div>\n {isTestPropsCode ? (\n <ConfigViewToggle\n view={testView}\n views={[\"props\", \"code\"]}\n onChange={(v) => setTestView(v as \"props\" | \"code\")}\n />\n ) : (\n <ConfigViewToggle\n view={configView}\n customized={hasParamCustomization(step.with ?? {})}\n onChange={changeConfigView}\n disabled={tab !== \"configure\"}\n />\n )}\n </div>\n\n {blocked && connectionProblem && (\n <div role=\"alert\" className=\"w6w-field-error\">\n Connection {connectionProblem.connection} no longer exists — choose another to continue.\n </div>\n )}\n {fixable.length > 0 && (\n <div className=\"w6w-stepproblem-fixes\" style={{ display: \"grid\", gap: 6 }}>\n {fixable.map((p) => (\n <div\n key={p.code}\n className=\"w6w-small\"\n style={{ display: \"flex\", gap: 8, alignItems: \"center\" }}\n >\n <span>{stepProblemTooltip(p)}</span>\n <button\n type=\"button\"\n className=\"w6w-btn\"\n data-fix-code={p.code}\n disabled={readOnly}\n onClick={() => {\n const next = applyStepProblemFix(step, p);\n commit(next);\n setCodeText(stepToJson(next));\n }}\n >\n {\"fix\" in p ? p.fix.label : \"\"}\n </button>\n </div>\n ))}\n </div>\n )}\n <div className=\"w6w-stepconfig-body\">\n {tab === \"setup\" && (\n <SetupTab\n step={step}\n app={app}\n actions={actions}\n conns={conns}\n connsFailed={connsFailed}\n isInternal={isInternal}\n actionLabel={isAppTrigger ? \"Trigger\" : \"Action\"}\n readOnly={readOnly}\n onChangeAction={(action) => {\n const values = isInternal ? internalNodeDefaults(step.uses.app, action) : {};\n if (isInternal) {\n for (const param of internalNodeParams(step.uses.app, action)) {\n if (param.key in (step.with ?? {})) values[param.key] = step.with?.[param.key];\n }\n }\n commit({ ...step, uses: { ...step.uses, action }, with: values });\n }}\n onChangeTriggerEvents={(action, events) =>\n commit({\n ...step,\n uses: { ...step.uses, action },\n with: { ...step.with, actions: events },\n })\n }\n onChangeConnection={(connection) => {\n // Standalone step editors have no workflow map to write to.\n if (!connectionScope) {\n const { connectionRef: _ref, ...uses } = step.uses;\n commit({ ...step, uses: { ...uses, connection } });\n return;\n }\n const selected = selectNodeConnection(\n step,\n connection,\n connectionScope?.nodes ?? [step],\n connectionScope?.connections ?? {},\n );\n connectionScope?.setConnections(selected.connections);\n commit(selected.step);\n }}\n onChangeConnectionRef={(ref) => commit(withConnectionRef(step, ref))}\n onConnectionCreated={refetchConns}\n onChangeApp={(appId) => {\n const request = ++appSelectionRequest.current;\n if (appId === step.uses.app) {\n commit(step);\n return;\n }\n // Commit the new app and its default account together, so one undo restores both.\n const next: FlowStep = {\n ...step,\n uses: {\n app: appId,\n action: \"\",\n ...(isAppTrigger ? { trigger: true as const } : {}),\n },\n with: {},\n };\n void (isInternalApp(appId) ? Promise.resolve([]) : api.listConnectionsForApp(appId))\n .catch(() => [])\n .then((choices) => {\n if (request !== appSelectionRequest.current) return;\n const selected = defaultConnectionFor(\n next,\n choices,\n connectionScope?.nodes ?? [],\n connectionScope?.connections ?? {},\n );\n commit({ ...next, uses: { ...next.uses, ...selected } });\n });\n }}\n />\n )}\n\n {tab === \"configure\" && (\n <>\n {step.uses.app === WEBHOOK_APP &&\n api.listSubscriptionsForWorkflow &&\n api.createSubscription && (\n <WebhookUrlPanel workflowId={workflowId} step={step} readOnly={readOnly} />\n )}\n {params === null ? (\n <p className=\"w6w-muted w6w-small\">Loading parameters…</p>\n ) : configView === \"props\" ? (\n step.uses.app === RACE_APP ? (\n <p className=\"w6w-muted w6w-small\">{RACE_DESCRIPTION}</p>\n ) : step.uses.action === \"wait\" && isControlApp(step.uses.app) ? (\n <WaitEditor\n values={step.with ?? {}}\n readOnly={readOnly}\n onChange={(w) => commit({ ...step, with: w })}\n />\n ) : step.uses.action === \"if\" && isControlApp(step.uses.app) ? (\n <ConditionEditor\n values={step.with ?? {}}\n readOnly={readOnly}\n onChange={(w) => commit({ ...step, with: w })}\n />\n ) : step.uses.app === \"@w6w/stop\" ? (\n <StopEditor\n values={step.with ?? {}}\n readOnly={readOnly}\n onChange={(w) => commit({ ...step, with: w })}\n />\n ) : step.uses.app === ROUTER_APP ? (\n <RouterEditor\n values={step.with ?? {}}\n readOnly={readOnly}\n onChange={(w) => commit({ ...step, with: w })}\n />\n ) : (\n <>\n {step.uses.app === SCRIPT_APP && (\n <ScriptBindingsNotice\n values={step.with ?? {}}\n conversion={scriptConversion}\n readOnly={readOnly}\n />\n )}\n <ParamsForm\n params={params}\n values={step.with ?? {}}\n readOnly={readOnly}\n onChange={(w) => commit({ ...step, with: w })}\n dynamic={\n isInternal || !step.uses.action\n ? undefined\n : {\n appId: step.uses.app,\n actionKey: step.uses.action,\n connectionId: blocked ? undefined : connectionId,\n appName: app?.displayName,\n }\n }\n />\n </>\n )\n ) : configView === \"code\" ? (\n // Full step, read-only (D-3) — `stepToJson` is the ONE serializer,\n // shared with the two other code-view hosts.\n <JsonEditor\n value={codeText}\n onChange={() => {}}\n readOnly\n minHeight=\"260px\"\n height=\"100%\"\n aria-label={`Node ${step.id} JSON`}\n copyable\n />\n ) : configView === \"params-code\" ? (\n <ParamCustomization\n values={step.with ?? {}}\n onChange={(w) => commit({ ...step, with: w })}\n readOnly={readOnly}\n />\n ) : (\n <div className=\"w6w-stack\">\n <NodeConfigForm\n config={{ retry: step.retry, onError: step.onError, notes: step.notes }}\n onChange={(c) => commit({ ...step, ...c })}\n readOnly={readOnly}\n // A trigger has no failure of its own to retry or police —\n // same reason its card renders no error exit port.\n failureHandling={!isTrigger}\n // A `@w6w/call`/`@w6w/control` step runs no retry loop of\n // its own (core rfcs/workflow.md \"Retries come first\"; D-3).\n retryControls={!isControlApp(step.uses.app) && step.uses.app !== CALL_APP}\n />\n {SHOW_STEP_PORTS && (\n <StepPortsControl step={step} readOnly={readOnly} onChange={commit} />\n )}\n <StepFanOutControl\n step={step}\n count={fanOutCount}\n readOnly={readOnly}\n onChange={commit}\n />\n {stateWriteVisible(step) && (\n <StepStateControl\n step={step}\n inLoop={loop !== undefined}\n outputFields={stateOutputFields}\n readOnly={readOnly}\n onChange={commit}\n />\n )}\n </div>\n )}\n </>\n )}\n\n {tab === \"test\" && (\n <div className=\"w6w-stack\">\n {testable ? (\n isAppTrigger ? (\n <AppTriggerTestNote\n title={\n actions?.find((a) => a.key === step.uses.action)?.title ?? step.uses.action\n }\n app={app?.displayName ?? step.uses.app}\n />\n ) : isTrigger ? (\n <TriggerFillForm\n app={step.uses.app}\n action={step.uses.action}\n fields={step.with?.fields}\n // Same fixture key the non-trigger Test path passes to\n // <StepTestRun> below, so the values entered here are\n // remembered and come back on the canvas ▶ Run form.\n persist={{ workflowId, stepId: step.id, input: testInput }}\n // A webhook trigger's primary test is a REAL request: listen for one.\n listen={\n step.uses.app === WEBHOOK_APP &&\n api.listSubscriptionsForWorkflow &&\n api.startWebhookListen\n ? { stepWith: step.with, readOnly }\n : undefined\n }\n />\n ) : (\n <>\n <p className=\"w6w-muted w6w-small\">\n Tests <code>{step.uses.action}</code> with the configuration saved on this\n step — only the incoming state changes per run.\n </p>\n <LoopSeedField seed={loopSeed} readOnly={readOnly} />\n {testPrefilled && !readOnly && (\n <LastUsedNote\n onClear={() => {\n rememberedTest.clear();\n setTestPrefilled(false);\n setTestState(\"{}\");\n }}\n />\n )}\n <IncomingStateField\n text={testState}\n onChange={setTestState}\n seeds={seedSources}\n readOnly={readOnly}\n />\n {/* What will actually be submitted, resolved against the\n incoming state above — `testValues` (post-override),\n never `step.with` alone, so overriding the incoming\n state visibly updates these rows. */}\n {params === null ? (\n <p className=\"w6w-muted w6w-small\">Loading parameters…</p>\n ) : (\n <ResolvedParams\n params={params}\n values={testValues}\n testStartState={previewState}\n view={testView}\n literalKeys={step.uses.app === SCRIPT_APP ? SCRIPT_LITERAL_KEYS : undefined}\n />\n )}\n <StepTestRun\n ref={testRunRef}\n app={step.uses.app}\n action={step.uses.action}\n connectionId={connectionId}\n values={testValues}\n state={testStartState}\n canRun={canTest}\n hideRunButton\n persist={{ workflowId, stepId: step.id, input: testInput }}\n onBusyChange={setTestBusy}\n />\n </>\n )\n ) : isForeach ? (\n <>\n <p className=\"w6w-muted w6w-small\">\n Resolves <strong>Items</strong> against the incoming state — nothing inside the\n loop runs. <strong>Test</strong> saves the first item as this loop's sample, so\n the steps on its <strong>Each item</strong> output can pick its keys. To run the\n loop's work, test a step on <strong>Each item</strong>: it runs once, on one\n item.\n </p>\n <IncomingStateField\n text={testState}\n onChange={changeTestState}\n seeds={seedSources}\n readOnly={readOnly}\n expand={!foreachItems}\n hint={\n <>\n Paste a sample list — <code>{'[{\"id\": 1, \"name\": \"…\"}]'}</code> — or{\" \"}\n <code>{'{\"items\": […]}'}</code>. It replaces what <strong>Items</strong>{\" \"}\n resolves to, for this test only.\n </>\n }\n />\n <ForeachTestResult items={foreachItems} save={foreachSave} />\n </>\n ) : (\n <p className=\"w6w-muted w6w-small\">\n Flow-control nodes can't be tested on their own.\n </p>\n )}\n </div>\n )}\n </div>\n\n <div className=\"w6w-modal-actions w6w-stepconfig-footer\">\n {step.uses.app === RACE_APP && tab === \"configure\" ? (\n <button type=\"button\" className=\"w6w-btn\" onClick={onClose}>\n Done\n </button>\n ) : tab !== \"test\" ? (\n <button\n type=\"button\"\n className=\"w6w-btn\"\n disabled={blocked}\n onClick={() => setTab(tab === \"setup\" ? \"configure\" : \"test\")}\n >\n Next →\n </button>\n ) : (\n <>\n <button type=\"button\" className=\"w6w-btn w6w-btn-ghost\" onClick={onClose}>\n Done\n </button>\n {testable && !isTrigger && (\n // Runs the step and persists the outcome (records a run + saves\n // the fixture) via the body's <StepTestRun>, so a step test is\n // saved and re-runnable. `readOnly` viewers can't write tests.\n <button\n type=\"button\"\n className=\"w6w-btn\"\n disabled={readOnly || !canTest || testBusy}\n onClick={() => {\n // T1.1.1: before the run, so the host clears whatever run\n // the canvas was showing on the click itself.\n onTestRun?.();\n testRunRef.current?.run();\n }}\n >\n {testBusy ? \"Testing…\" : \"Test\"}\n </button>\n )}\n {isForeach && (\n <button\n type=\"button\"\n className=\"w6w-btn\"\n disabled={readOnly || !foreachItems?.length || foreachSave === \"saving\"}\n onClick={() => void saveForeachTest()}\n >\n {foreachSave === \"saving\" ? \"Testing…\" : \"Test\"}\n </button>\n )}\n </>\n )}\n </div>\n </div>\n </Modal>\n );\n}\n\n/** Default in-cardinality applied when a step is opted into multiple inbound edges. */\nconst MULTI_IN_DEFAULT = 10;\n\n/** Hidden for now (26-08-30-00-fixes item 3). Flip to `true` to restore; nothing else changes. */\nconst SHOW_STEP_PORTS = false;\n\n/**\n * Opt a step into accepting **multiple** incoming edges by setting `step.ports.in`\n * (see core rfcs/node-types.md · Ports & cardinality). Unchecking reverts to the\n * node's default (drops the persisted `ports` so an untouched step stays `1/1`).\n * Hidden for entry nodes (triggers) that declare no inbound port.\n */\nfunction StepPortsControl({\n step,\n readOnly,\n onChange,\n}: {\n step: FlowStep;\n readOnly?: boolean;\n onChange: (next: FlowStep) => void;\n}) {\n const ports = nodePortsForStep(step, useContext(PortsLookupCtx));\n // Nothing flows into a node with no entry port (e.g. a trigger).\n if (ports.in < 1) return null;\n const multiple = ports.in > 1;\n return (\n <label className=\"w6w-field\" style={{ flexDirection: \"row\", alignItems: \"center\", gap: 8 }}>\n <input\n type=\"checkbox\"\n checked={multiple}\n disabled={readOnly}\n onChange={(e) => {\n if (e.target.checked) {\n onChange({ ...step, ports: { in: MULTI_IN_DEFAULT, out: ports.out } });\n } else {\n const { ports: _drop, ...rest } = step;\n onChange(rest);\n }\n }}\n />\n <span>Accept multiple incoming connections</span>\n </label>\n );\n}\n\n/** \"Run next nodes: In sequence / In parallel\" — only meaningful with 2+ outgoing edges in a lane. */\nfunction StepFanOutControl({\n step,\n count,\n readOnly,\n onChange,\n}: {\n step: FlowStep;\n count: number;\n readOnly?: boolean;\n onChange: (next: FlowStep) => void;\n}) {\n const enabled = count >= 2;\n const mode = step.fanOut === \"parallel\" ? \"parallel\" : \"sequential\";\n return (\n <label className=\"w6w-field\">\n <span>Run next nodes</span>\n <select\n aria-label=\"Run next nodes\"\n value={mode}\n disabled={readOnly || !enabled}\n onChange={(e) => onChange(setFanOut(step, e.target.value as \"sequential\" | \"parallel\"))}\n >\n <option value=\"sequential\">In sequence</option>\n <option value=\"parallel\">In parallel</option>\n </select>\n {!enabled && (\n <span className=\"w6w-muted w6w-small\">\n Connect two or more steps after this one to choose how they run.\n </span>\n )}\n </label>\n );\n}\n\n/** Column headers over the \"Write to state\" mapping rows: which side is the step, which is state. */\nfunction StateMapHead({ to }: { to: string }) {\n return (\n <div className=\"w6w-state-map-row w6w-state-map-head\" aria-hidden=\"true\">\n <span>From this step output</span>\n <span />\n <span>{to}</span>\n </div>\n );\n}\n\nfunction StateMapArrow() {\n return (\n <span className=\"w6w-state-map-arrow\" aria-hidden=\"true\">\n →\n </span>\n );\n}\n\n/**\n * A path in this step's output: picks from the fields `resolveOutputShape` found\n * (declared output, the last test or a saved sample) and takes free text for\n * anything else. Blank means the whole output.\n */\nfunction StateOutputPathInput({\n label,\n fields,\n value,\n readOnly,\n onChange,\n}: {\n label: string;\n fields?: string[];\n value: string;\n readOnly?: boolean;\n onChange: (next: string) => void;\n}) {\n const options = useMemo(() => (fields ?? []).map((k) => ({ value: k, label: k })), [fields]);\n return (\n <Combobox\n mode=\"combobox\"\n forceSelection={false}\n aria-label={label}\n placeholder=\"Whole output, or e.g. order\"\n options={options}\n value={value}\n disabled={readOnly}\n emptyText={\n options.length > 0\n ? \"No matching field — keep typing a path\"\n : \"Test this step to list its output fields, or type a path\"\n }\n onChange={onChange}\n />\n );\n}\n\n/**\n * \"Write to state\" — where this step's output lands in the run's state tree\n * (`Node.state`). Off is the key's absence (Merge at root on Set data, R14);\n * every rule about paths and keys comes from `@w6w/expr` `validateStateConfig`.\n */\nfunction StepStateControl({\n step,\n inLoop,\n outputFields,\n readOnly,\n onChange,\n}: {\n step: FlowStep;\n inLoop: boolean;\n outputFields?: string[];\n readOnly?: boolean;\n onChange: (next: FlowStep) => void;\n}) {\n const config = stateWriteFor(step);\n const issues = validateStateConfig(config);\n const commitConfig = (next: StateWriteConfig) => onChange(setStateWrite(step, next));\n const rows = config.mode === \"pick\" && Array.isArray(config.map) ? config.map : [];\n const setRow = (i: number, patch: Partial<{ from: string; to: string }>) =>\n commitConfig({\n mode: \"pick\",\n map: rows.map((r, j) => (j === i ? { ...r, ...patch } : r)),\n });\n const setAppend = (patch: { path?: string; from?: string }) => {\n if (config.mode !== \"append\") return;\n const path = patch.path ?? config.path;\n const from = \"from\" in patch ? patch.from : config.from;\n commitConfig({ mode: \"append\", path, ...(from ? { from } : {}) });\n };\n return (\n <div className=\"w6w-field w6w-stack\">\n <label className=\"w6w-field\">\n <span>Write to state</span>\n <select\n aria-label=\"Write to state\"\n value={config.mode}\n disabled={readOnly}\n onChange={(e) => commitConfig(seedStateWrite(step, e.target.value as StateMode))}\n >\n {STATE_MODES.map((m) => (\n <option key={m} value={m}>\n {STATE_MODE_LABELS[m]}\n </option>\n ))}\n </select>\n </label>\n {config.mode === \"key\" && (\n <label className=\"w6w-field\">\n <span>To state key</span>\n <input\n type=\"text\"\n aria-label=\"State key\"\n placeholder=\"e.g. order\"\n value={config.key}\n disabled={readOnly}\n onChange={(e) => commitConfig({ mode: \"key\", key: e.target.value })}\n />\n <span className=\"w6w-hint\">\n Copies the whole step output into <code>state.<key></code>. A dotted key such as{\" \"}\n <code>order.id</code> nests.\n </span>\n </label>\n )}\n {config.mode === \"pick\" && (\n <div className=\"w6w-stack\">\n <StateMapHead to=\"To state key\" />\n {rows.length === 0 && (\n <p className=\"w6w-muted w6w-small\">No fields yet — add one below.</p>\n )}\n {rows.map((row, i) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: rows are positional; their order is the write order\n <div key={i} className=\"w6w-datavar-row w6w-state-map-row\">\n <StateOutputPathInput\n label=\"From output field\"\n fields={outputFields}\n value={row.from}\n readOnly={readOnly}\n onChange={(from) => setRow(i, { from })}\n />\n <StateMapArrow />\n <input\n type=\"text\"\n aria-label=\"To state path\"\n placeholder=\"e.g. order\"\n value={row.to}\n disabled={readOnly}\n onChange={(e) => setRow(i, { to: e.target.value })}\n />\n {!readOnly && (\n <DeleteButton\n label=\"Remove field\"\n onClick={() =>\n commitConfig({ mode: \"pick\", map: rows.filter((_, j) => j !== i) })\n }\n />\n )}\n </div>\n ))}\n {!readOnly && (\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-ghost w6w-state-map-add\"\n aria-label=\"Add field\"\n onClick={() => commitConfig({ mode: \"pick\", map: [...rows, { from: \"\", to: \"\" }] })}\n >\n + Add field\n </button>\n )}\n <span className=\"w6w-hint\">\n Copies <code>output.<path></code> into <code>state.<key></code>. Leave the\n left side blank to copy the whole output.\n </span>\n </div>\n )}\n {config.mode === \"append\" && (\n <div className=\"w6w-stack\">\n <StateMapHead to=\"Append to state list\" />\n <div className=\"w6w-datavar-row w6w-state-map-row\">\n <StateOutputPathInput\n label=\"Output field to append\"\n fields={outputFields}\n value={config.from ?? \"\"}\n readOnly={readOnly}\n onChange={(from) => setAppend({ from })}\n />\n <StateMapArrow />\n <input\n type=\"text\"\n aria-label=\"Append to state path\"\n placeholder=\"e.g. orders\"\n value={config.path}\n disabled={readOnly}\n onChange={(e) => setAppend({ path: e.target.value })}\n />\n </div>\n <span className=\"w6w-hint\">\n Appends <code>output.<path></code> to the list at <code>state.<key></code>.\n Leave the left side blank to append the whole output.\n </span>\n </div>\n )}\n {issues.length > 0 && (\n <div role=\"alert\" className=\"w6w-state-write-issues w6w-small\">\n {issues.map((issue) => (\n <div key={`${issue.code}:${issue.message}`}>{issue.message}</div>\n ))}\n </div>\n )}\n {config.mode !== \"off\" && (\n <span className=\"w6w-muted w6w-small\">\n Writing <code>null</code> deletes the key, and secrets are stored masked.\n </span>\n )}\n {inLoop && (\n <span className=\"w6w-muted w6w-small\">\n This step is inside a For each, so it writes once per item — Append collects one entry per\n item.\n </span>\n )}\n </div>\n );\n}\n\n/**\n * \"Webhook URL\" panel (I-2) — rendered only for a `WEBHOOK_APP` step, above\n * the ParamsForm/JsonEditor arms. Get-or-create against the Subscription\n * mechanism (rfcs/trigger.md), per DECISIONS.md HITL-1 + plan.md D-5:\n * - on open, lists this workflow's Subscriptions ONCE and takes the first\n * `appId === WEBHOOK_APP` entry — never re-derived client-side\n * (gap-analysis-I2 §1's `SubscriptionsPage.tsx:24-28` correctness bug is\n * deliberately not reproduced here; the server's own `webhookUrl` is the\n * only source).\n * - if one exists, its URL renders through `Copyable` exactly as\n * `TenantSettingsPage.tsx:219-227` (full URL, readOnly, aria-label) — no\n * create call.\n * - if none exists, a labelled button creates one with the step's own\n * current `with` as the Subscription's `params`, then renders the result.\n * `sub_…` ids are server-minted, so this never re-fires on its own — only\n * an explicit click creates, and only once a subscription is confirmed\n * absent.\n */\nfunction WebhookUrlPanel({\n workflowId,\n step,\n readOnly,\n}: {\n workflowId: string;\n step: FlowStep;\n readOnly?: boolean;\n}) {\n const api = useW6WApi();\n // `undefined` while the initial list is in flight; `null` once resolved\n // with no existing webhook subscription for this workflow.\n const [sub, setSub] = useState<SubscriptionSummary | null | undefined>(undefined);\n const [error, setError] = useState<string | null>(null);\n const [creating, setCreating] = useState(false);\n\n // Deliberately keyed on [api, workflowId, step.id] only — NOT on `step` (its `with`\n // changes on every keystroke in the panel below). Re-running this on a\n // `with` edit would defeat the \"never re-creates\" guarantee this panel\n // exists to provide; the list is a one-shot get, not a live subscription.\n useEffect(() => {\n const list = api.listSubscriptionsForWorkflow;\n if (!list) return;\n let canceled = false;\n list(workflowId)\n .then((subs) => {\n if (!canceled) setSub(pickWebhookSubscription(subs, step.id));\n })\n .catch((e) => !canceled && setError((e as Error).message));\n return () => {\n canceled = true;\n };\n }, [api, workflowId, step.id]);\n\n const create = () => {\n const createSubscription = api.createSubscription;\n if (!createSubscription) return;\n setError(null);\n setCreating(true);\n createSubscription(WEBHOOK_APP, step.uses.action, {\n workflowId,\n connectionId: null,\n params: step.with ?? {},\n })\n .then((created) => {\n setCreating(false);\n setSub(created);\n })\n .catch((e) => {\n setCreating(false);\n setError(e instanceof Error ? e.message : String(e));\n });\n };\n\n return (\n <div className=\"w6w-stack\">\n <p className=\"w6w-muted w6w-small\">\n <strong>Webhook URL</strong> — the address a third party posts to.\n </p>\n {error && <div className=\"w6w-result w6w-error\">{error}</div>}\n {sub?.webhookUrl ? (\n <Copyable value={sub.webhookUrl} readOnly>\n <input type=\"text\" readOnly value={sub.webhookUrl} aria-label=\"Webhook URL\" />\n </Copyable>\n ) : sub === undefined ? (\n <p className=\"w6w-muted w6w-small\">Loading…</p>\n ) : (\n !readOnly && (\n <button type=\"button\" className=\"w6w-btn\" disabled={creating} onClick={create}>\n {creating ? \"Creating…\" : \"Create webhook URL\"}\n </button>\n )\n )}\n </div>\n );\n}\n\n/**\n * The Setup tab — an App button and a Connection button, spaced apart, then\n * the step's action (a dropdown for app steps). Two independent pickers\n * (2026-08-30, superseding D-1's single combined field — see intake for the\n * exact spec): App opens a searchable app picker; Connection opens a plain\n * list of connections FOR THE CURRENT APP plus \"+ New connection\" — no\n * search, per the ask (\"just list the connections for the same app\"). Both\n * render as an anchored flyout, not inline content that pushes the rest\n * of the tab down.\n */\nfunction SetupTab({\n step,\n app,\n actions,\n conns,\n connsFailed,\n isInternal,\n actionLabel = \"Action\",\n readOnly,\n onChangeAction,\n onChangeTriggerEvents,\n onChangeConnection,\n onChangeConnectionRef,\n onChangeApp,\n onConnectionCreated,\n}: {\n step: FlowStep;\n app: AppSummary | undefined;\n actions: ActionDef[] | null;\n conns: ConnectionSummary[] | null;\n /** The connections fetch rejected — a distinct state, never \"missing\". */\n connsFailed: boolean;\n isInternal: boolean;\n /** The picked thing's name: \"Action\", or \"Trigger\" on an app trigger node. */\n actionLabel?: string;\n readOnly?: boolean;\n onChangeAction: (action: string) => void;\n onChangeTriggerEvents: (action: string, events: string[]) => void;\n onChangeConnection: (connection: string | undefined) => void;\n onChangeConnectionRef: (ref: string) => void;\n /** Fires with whatever app is picked, same or different — the caller owns\n * the same-app-is-a-no-op / different-app-clears-action-and-with decision\n * (it already owns the equivalent decision for `onChangeAction`). */\n onChangeApp: (appId: string) => void;\n /** Fires after a new connection is created via the inline \"+ New\n * connection\" flow, so the caller can refetch its (app-scoped) connection\n * list — `conns` here is a prop, this component owns no fetch of its own. */\n onConnectionCreated: () => void;\n}) {\n const eventChoices = step.uses.trigger\n ? eventbriteTriggerChoices(step.uses.app, actions, step.uses.action, step.with ?? {})\n : null;\n // Which flyout (if either) is open. Local, ephemeral UI state: the tab\n // unmounts on tab-switch, so it always starts closed. `AppPicker` fetches\n // and searches its own catalog; the connection picker below just maps\n // `conns` (already app-scoped by the caller) — neither needs its own fetch.\n const [mode, setMode] = useState<\"app\" | \"conn\" | null>(null);\n const rowRef = useRef<HTMLDivElement>(null);\n const scope = useWorkflowConnections();\n const connectionId = connectionIdFor(step, scope?.connections);\n\n return (\n <div className=\"w6w-stack\">\n {step.uses.connectionRef && !connectionId && (\n <p role=\"alert\" className=\"w6w-field-error\">\n The shared connection is missing or unbound. Choose an account.\n </p>\n )}\n <div className=\"w6w-field\">\n <span>App</span>\n {/* One field, two buttons — `[App] <-- spacer --> [Connection]`\n (2026-08-30). Always rendered, never swapped out for the picker:\n each button IS the flyout's anchor, and stays clickable the whole\n time its own flyout is open (click again to close — the toggle\n is the only way back out short of picking something or clicking\n away, since there is no third \"cancel\" control). */}\n <div className=\"w6w-app-conn-row\" ref={rowRef}>\n <button\n type=\"button\"\n className=\"w6w-app-conn-btn\"\n aria-label=\"App\"\n aria-expanded={mode === \"app\"}\n disabled={readOnly}\n onClick={() => setMode((m) => (m === \"app\" ? null : \"app\"))}\n >\n {!isInternal && app && (\n <AppIcon\n src={app.iconSvg}\n srcDark={app.iconSvgDark}\n brandColor={app.brandColor}\n name={app.displayName}\n size={20}\n />\n )}\n <span className=\"w6w-conn-label-name\">\n {isInternal ? step.uses.app : (app?.displayName ?? step.uses.app)}\n </span>\n </button>\n {!isInternal && (\n <WorkflowConnectionPicker\n step={step}\n conns={conns}\n failed={connsFailed}\n readOnly={readOnly}\n open={mode === \"conn\"}\n onOpenChange={(open) => setMode(open ? \"conn\" : null)}\n anchorRef={rowRef}\n onChangeConnection={onChangeConnection}\n onChangeConnectionRef={onChangeConnectionRef}\n onConnectionCreated={onConnectionCreated}\n />\n )}\n </div>\n\n {mode === \"app\" && (\n <AnchoredFlyout anchorRef={rowRef} onClose={() => setMode(null)}>\n <AppPicker\n onSelectApp={(a) => {\n const sameAppReselected = a.id === step.uses.app;\n onChangeApp(a.id);\n // Same app: nothing else changed (action/config untouched, per\n // the ask) — go straight to the connection picker so they can\n // still pick a different connection. Different app: the caller\n // already wiped action/connection/with; close, exactly\n // \"start over\" on the fresh (connection-less) app.\n setMode(sameAppReselected ? \"conn\" : null);\n }}\n />\n </AnchoredFlyout>\n )}\n </div>\n\n {isInternal && !actions?.length ? (\n <div className=\"w6w-field\">\n <span>Action</span>\n <div className=\"w6w-muted w6w-small\">\n <code>{step.uses.action}</code>\n </div>\n </div>\n ) : eventChoices ? (\n <EventbriteTriggerPicker\n choices={eventChoices}\n readOnly={readOnly}\n onChange={(events) => onChangeTriggerEvents(eventChoices.triggerKey, events)}\n />\n ) : (\n // biome-ignore lint/a11y/noLabelWithoutControl: Combobox renders its own <select>/<input> INSIDE this label, so the field text labels the control at runtime; the rule cannot see through the component boundary.\n <label className=\"w6w-field\">\n <span>{actionLabel}</span>\n {/* While the action manifest is still loading there is nothing to pick\n from: the current action renders as the single option, so the field\n keeps showing the step's action instead of going empty. */}\n <Combobox\n value={step.uses.action}\n disabled={readOnly || actions === null}\n onChange={onChangeAction}\n options={\n actions === null\n ? [{ value: step.uses.action, label: step.uses.action }]\n : actions.map((a) => ({ value: a.key, label: a.title ?? a.key }))\n }\n />\n </label>\n )}\n </div>\n );\n}\n"],"names":["CanvasContextMenu","x","y","items","onAction","onClose","ref","useRef","pos","setPos","useState","useLayoutEffect","el","box","h","useEffect","_b","_a","onDown","e","onScroll","onBlur","run","item","jsx","buttons","at","focus","i","contextMenuTargets","selectedIds","nodeId","canvasMenuItems","nodeIds","readOnly","n","suffix","MAX_NOTES","MAX_SECTIONS","MAX_NOTE_BYTES","roundGeometry","g","out","k","v","isFinitePos","p","isFiniteSize","z","mapItems","live","useLive","it","l","position","size","withCanvasGeometry","canvas","savePosition","pruneSectionMembers","deletedNodeId","s","renameSectionMember","from","to","assignMembership","sectionId","moving","kept","sectionsContaining","truncateBytes","text","max","enc","used","ch","clampCanvas","persistCanvas","stored","pin","old","o","base","RESOLVED_VALUE_CLIP","clipResolvedValue","ResolvedParams","params","values","testStartState","view","literalKeys","sampleValues","nodeConfig","nodeMeta","useExpressionOptions","scope","useMemo","buildResolveScope","flat","flattenParams","effective","key","visibleRows","isParamVisible","effectiveParam","hasParamCustomization","custom","previewCustomization","object","buildResolvedJson","value","merged","jsxs","JsonEditor","ResolvedParamRow","json","rows","deepEqual","param","ResolvedVarsRow","resolveParamValue","raw","vars","dataVarRows","resolveVarsJson","resolveParamJson","label","segments","ResolvedSegments","row","Fragment","seg","ResolvedSegmentView","segment","ExprChip","ResolvedValueText","expanded","setExpanded","full","formatResolvedValue","clip","Copyable","CHIP_SIGIL","kind","refName","varLabel","languageOf","useScriptConversion","enabled","onChange","done","setDone","ran","code","r","convertCodeBindingsToReads","ScriptBindingsNotice","conversion","left","findCodeBindings","selectedFlowElements","nodes","edges","deleteFlowSelection","selection","edgeIds","removed","ordered","isForeachStep","nextNodes","nextEdges","nextCanvas","node","bridgeDeletedBodyStep","flowDeleteMessage","extraEdges","messages","deleteStepMessage","id","detached","member","loopBody","fanOutState","stepId","per","lane","edgeLane","count","setFanOut","step","mode","_drop","rest","fanOutLabel","captureFlowEdit","connections","definition","flowToWorkflow","restoreFlowEdit","snapshot","graph","workflowToFlow","FlowEditHistory","initial","limit","__publicField","group","next","previous","isFlowTextTarget","target","element","GAP","SECTION_PADDING","SECTION_LABEL_HEIGHT","nodeSize","overlaps","a","b","spaceNodes","offsets","axis","dimension","extents","placed","end","extent","start","relayoutFlow","arranged","relayoutNodes","byId","occupied","note","section","sections","memberIds","members","right","bottom","frame","obstacles","obstacle","withLabel","dy","LOOP_TONES","hashId","assignLoopTones","foreachIds","taken","tone","loopToneVar","enclosingLoops","loopOfById","chain","seen","cur","paintLoopEdges","tones","owner","EACH_SOURCE_HANDLE","loopCardStyle","own","loopPaintKey","foreach","loopPaint","PAUSED_LABEL","DISABLED_LABEL","isPausedStep","isDisabledStep","withPaused","on","ui","_paused","otherUi","nextUi","withDisabled","_disabled","pausedStopAt","steps","startId","ROOTS","loopOutputRef","foreachId","root","prefix","rewrite","refs","parts","parseRootAnchoredTemplate","hit","serializeTemplate","isDollarPath","path","changed","isWholeRef","isWrappedItems","findLoopProblems","input","wf","normalizeInput","add","list","fid","loop","definitionLoops","f","branchIds","branch","collect","stateWriteConflicts","effectiveEdges","writers","paths","staticWritePaths","effectiveStateConfig","controlOwnedIds","anchor","c","succ","reachCache","reach","stack","m","reachesRefl","parallels","CONTROL_APP","branches","branchOf","fanGroups","lanes","isEachLink","targets","concurrent","ia","ib","aa","ab","ta","tb","j","A","B","pa","pb","statePathsOverlap","w","cmp","findStateWriteProblems","applyStepProblemFix","problem","dragLane","fromNodeId","fromHandle","laneForSourceHandle","connectDropRefusal","source","srcStep","inBody","loopMembership","effLane","loopRefusal","STATE_MODES","STATE_MODE_LABELS","stateWriteFor","setStateWrite","config","fallback","seedStateWrite","stateWriteVisible","isControlApp","execOf","runState","offPath","rec","RUN_ENDED","stepVisualState","loops","NO_RUN_VISUAL","stepNodeVisual","state","runStatus","runEnded","edgeRunState","when","route","edgeStateFromSource","exec","output","FOREACH_DONE_ROUTE","EMPTY","isPlainObject","stateWriteOrder","ids","known","indegree","outgoing","order","ready","d","DECLARED_TYPES","declaredShape","any","segs","t","leaf","writerShapeOutput","shapes","tested","app","action","TRIGGER_APP","_c","internalNodeDef","keys","fieldsToParams","asFieldDefs","_d","shapeToSkeleton","internal","_e","def","_f","_g","declared","writerPreviewOutput","real","variablePlaceholder","type","seedTree","tree","fieldKeys","inferOutputFields","computeStateShape","anchorId","ancestors","ancestorIds","shapeOps","previewOps","writersOf","ops","computeStateWrites","foldState","set","seed","seeded","parents","children","entries","onAllPaths","preview","fields","all","valueAtPath","LABELS","NEVER_FIRED","formatLastFire","iso","registrationDisplay","sub","canRetry","failed","subscriptionsByNode","subs","appTriggerNodesOf","useAppActionDefs","api","defs","setDefs","requested","appIdsKey","isInternalApp","missing","res","loaded","prev","useAppTriggerDefs","load","portsLookupFromDefs","LANE_HINT","clashInvolvedIds","conflictId","sitting","PortsLookupCtx","createContext","FanOutCountsCtx","LoopPaintCtx","outCapMessage","cap","AppsCtx","TriggerRegistrationCtx","CardDataProvider","apps","registration","StepControlsCtx","WorkflowFlowEditor","props","ReactFlowProvider","Inner","nextCanvasId","nodeRect","height","exprOptions","project","stepProblems","onTestRun","fitViewKey","onRunFromNode","useW6WApi","appsById","triggerRegistration","useTriggerRegistration","runResult","setRunResult","initialWorkflow","centralizeConnections","setConnectionsState","connectionsRef","setConnections","useCallback","prepareStep","savedViewport","storedViewport","setNodes","onNodesChange","useNodesState","actionDefs","triggerDefs","portsLookup","setEdges","onEdgesChange","useEdgesState","selectedId","setSelectedId","initialCanvas","setCanvas","editHistory","textEditGroup","restoreVersion","setRestoreVersion","drawingSection","setDrawingSection","sectionDraft","setSectionDraft","pendingCanvasDelete","setPendingCanvasDelete","selectedEdgeId","setSelectedEdgeId","builderOpen","setBuilderOpen","builderEditGroup","editingId","setEditingId","editView","setEditView","contextMenu","setContextMenu","builderPlace","setBuilderPlace","pendingDelete","setPendingDelete","relayoutPendingFitRef","flowContainerRef","pendingConnect","setPendingConnect","screenToFlowPosition","fitView","useReactFlow","colorMode","useEffectiveTheme","nds","loopOf","stampLoopOf","stepStatus","eds","visuals","edgeVisuals","applyStepProblems","withCanvas","emitChange","canvasOverride","isValidConnection","canConnect","routeFromHandle","loopNotice","setLoopNotice","loopNoticeSelRef","connectStartRef","onConnect","applyConnect","refusal","connectRefusal","holder","setLaneError","conflict","connectConflict","idClashMessage","onConnectEnd","event","connectionState","fromNode","handleType","toNode","reason","originStep","nodePortsForStep","point","addFromPort","handleId","gap","deleteStep","performDeleteSelection","performRelayout","requestRelayout","lastFitViewKeyRef","laneError","selectedEdge","setEdgeLane","me","edgeWhenConflict","relaneRefusal","setEdgeWhen","relaned","deleteEdge","duplicateSteps","sources","copies","src","newId","suggestStepId","cloned","stripBody","duplicateStep","addBuiltStep","built","isInternal","stepNameError","slugifyLabel","internalNodeLabel","newNode","loopRefused","noteLoopRefusal","wired","existingTrigger","isTriggerStep","findChainRoot","findChainTail","updateStep","prevId","draft","selected","selectNodeConnection","withConnectionRef","idChanged","renameStepInEdges","routeIds","routesForStep","onCanvasChange","addNote","notes","addSectionAt","x0","y0","cx","cy","withNew","onKey","onSectionDrop","sec","performCanvasDelete","membershipAfterDrag","dragged","current","persistStepRun","fixture","outcome","saved","err","runStep","performRunFromNode","isTrigger","req","patchStep","fn","togglePause","toggleDisable","performRunStep","payload","result","connectionIdFor","logs","meta","controls","div","handler","card","editingNode","editingStep","runningStep","collecting","fanOutCounts","loopKey","paint","paintedEdges","nodeTypes","StepNodeCard","ControlNodeCard","stepTestOutputs","setStepTestOutputs","stepTestMetas","setStepTestMetas","stepLoopSamples","setStepLoopSamples","stepTestRunAt","setStepTestRunAt","draftStepId","setDraftStepId","nodeSamples","setNodeSamples","nodeSampleOpenKey","canceled","persistedSamples","indexNodeSamples","shapeTiers","splitNodeOutputs","previewTiers","splitPreviewOutputs","stepShapes","trigger","runUpstreamSteps","upstreamStateSources","runSteps","upstreamState","st","excludeSelfStep","stateShape","upstreamIdsKey","tests","latest","foreachTestSample","nextMetas","nextLoopSamples","nextRunAt","declaredSamples","sampleTiers","stepSampleValues","upstreamSampleValues","stepValueSources","upstreamSampleValueSources","inheritedExprOptions","nodeConfigs","nodeConfigSources","nodeConfigValues","nodeMetaValues","mergedExprOptions","nodeMetaSampleValues","restoreEdit","direction","keepEditor","restoreEditRef","editor","active","trackActive","openContextMenu","alone","closeContextMenu","restoreFocus","onContextMenuAction","menu","WorkflowProjectProvider","ExpressionOptionsProvider","ReactFlow","ConnectionLineType","_n","membershipChanged","viewport","withViewport","sel","edgeSel","Background","Controls","ControlButton","Icon","MiniMap","Panel","IconButton","ox","oy","ROUTER_APP","NodeToolbar","Position","loopRefusalMessage","CanvasLayer","ConfirmModal","StepBuilderModal","stepBuilderUpstreamSteps","stepBuilderLoop","StepEditModal","resolveOutputShape","Modal","StepRunCollect","ResultViewer","WorkflowConnectionsContext","SCRIPT_LITERAL_KEYS","parseStateOverride","parseForeachOverride","ForeachTestResult","save","first","useLoopSeed","editedItem","setEditedItem","indexText","setIndexText","itemText","loopItemText","parsed","parseLoopSeed","loopSeedValue","loopSeedError","LoopSeedField","error","IncomingStateField","seeds","expand","hint","keyCount","hasOverride","open","setOpen","seedFrom","test","workflowId","upstreamSteps","onRun","onCancel","continues","localParams","internalNodeParams","fetched","setFetched","acts","setValues","seedValues","stateText","setStateText","useSeedSources","loopSeed","startState","startStateFromSeeds","remembered","useRememberedTestInput","setSeeded","prefilled","setPrefilled","apply","fromMemory","formKey","setFormKey","clearRemembered","draftValid","setDraftValid","validDraft","loopError","canRun","requiredParamsFilled","LastUsedNote","PropertyEntryForm","isForeachCard","LoopDots","useContext","useLoopStyle","PortHandle","multiple","variant","top","routeLabel","useNodeId","ctrl","canAdd","what","Handle","NodeControls","runnable","runLabel","paused","disabled","FanOutBadge","parallel","NodeFlagBadges","problemAttrs","problems","stepProblemTooltip","ProblemBadge","tip","useAppTriggerTitle","title","setTitle","ts","retrySub","triggers","WEBHOOK_APP","hasTrigger","triggerSig","setSubs","byNode","tick","setTick","retry","subscriptionId","TriggerRegistrationBadge","busy","setBusy","data","appName","triggerTitle","cardName","ports","visual","fanBadge","loopStyle","AppIcon","ERROR_SOURCE_HANDLE","routes","isRouter","isIf","isIfStep","routerPorts","routerPortLayout","ifPortLayout","routeKey","updateNodeInternals","useUpdateNodeInternals","icon","internalNodeIcon","isForeach","InternalIcon","port","routeHandle","RACE_APP","previewStartState","added","addEvent","ActionStepEditModal","initialStep","initialView","fanOutCount","stateOutputFields","otherStepIds","setStep","connectionScope","useWorkflowConnections","connectionId","effectiveStep","blocked","isConnectionBlocked","connectionProblem","fixable","tab","setTab","configView","setConfigView","testView","setTestView","codeText","setCodeText","stepToJson","testState","setTestState","testRunRef","testBusy","setTestBusy","lastRestoreVersion","setParams","actions","setActions","conns","setConns","connsFailed","setConnsFailed","isAppTrigger","grouped","INTERNAL_NODES","getTriggerDefs","appSelectionRequest","refetchConns","commit","scriptConversion","SCRIPT_APP","changeConfigView","rename","testable","isTestPropsCode","seedSources","previewState","rememberedTest","testPrefilled","setTestPrefilled","testOverride","testValues","testInput","canTest","foreachItems","resolveLoopItemsInState","foreachSave","setForeachSave","changeTestState","saveForeachTest","foreachTestFixture","internalIcon","titleIcon","StepNameEditor","ConfigViewToggle","SetupTab","internalNodeDefaults","events","connection","_ref","uses","appId","request","choices","defaultConnectionFor","WebhookUrlPanel","RACE_DESCRIPTION","WaitEditor","ConditionEditor","StopEditor","RouterEditor","ParamsForm","ParamCustomization","NodeConfigForm","CALL_APP","SHOW_STEP_PORTS","StepFanOutControl","StepStateControl","AppTriggerTestNote","TriggerFillForm","StepTestRun","StateMapHead","StateMapArrow","StateOutputPathInput","options","Combobox","inLoop","outputFields","issues","validateStateConfig","commitConfig","setRow","patch","setAppend","DeleteButton","_","issue","setSub","setError","creating","setCreating","pickWebhookSubscription","create","createSubscription","created","actionLabel","onChangeAction","onChangeTriggerEvents","onChangeConnection","onChangeConnectionRef","onChangeApp","onConnectionCreated","eventChoices","eventbriteTriggerChoices","setMode","rowRef","WorkflowConnectionPicker","AnchoredFlyout","AppPicker","sameAppReselected","EventbriteTriggerPicker"],"mappings":";;;;;;;;;;;AAaO,SAASA,GAAkB;AAAA,EAChC,GAAAC;AAAA,EACA,GAAAC;AAAA,EACA,OAAAC;AAAA,EACA,UAAAC;AAAA,EACA,SAAAC;AACF,GAOG;AACD,QAAMC,IAAMC,GAAuB,IAAI,GACjC,CAACC,GAAKC,CAAM,IAAIC,EAAS,EAAE,MAAMT,GAAG,KAAKC,GAAG;AAGlD,EAAAS,GAAgB,MAAM;AACpB,UAAMC,IAAKN,EAAI,SACTO,IAAMD,KAAA,gBAAAA,EAAI;AAChB,QAAI,CAACA,KAAM,CAACC,EAAK;AACjB,UAAM,IAAID,EAAG,aACPE,IAAIF,EAAG;AACb,IAAAH,EAAO;AAAA,MACL,MAAMR,IAAI,IAAIY,EAAI,cAAc,KAAK,IAAI,GAAGZ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canvas-context-menu.ts","../src/canvas-types.ts","../src/canvas-utils.ts","../src/components/resolved-clip.ts","../src/components/ResolvedParams.tsx","../src/components/ScriptBindingsNotice.tsx","../src/flow-delete.ts","../src/flow-fanout.ts","../src/flow-history.ts","../src/flow-layout.ts","../src/flow-loop-colors.ts","../src/flow-node-flags.ts","../src/flow-problems.ts","../src/flow-state.ts","../src/run-visuals.ts","../src/state-shape.ts","../src/trigger-registration.ts","../src/use-app-action-defs.ts","../src/WorkflowFlowEditor.tsx","../src/WorkflowConnectionsPanel.tsx"],"sourcesContent":["import { useEffect, useLayoutEffect, useRef, useState } from \"react\";\nimport type { CanvasMenuAction, CanvasMenuItem } from \"./canvas-context-menu.ts\";\n\n/**\n * The workflow canvas's right-click menu. Positioned in the editor's own box (`x`/`y` are\n * relative to it) so it inherits the editor's theme tokens, and drawn with the canvas\n * note menu's classes rather than a look of its own.\n *\n * Keyboard: focus lands on the first item; ↑/↓ (and Home/End) move, Enter or Space runs\n * the focused item, Esc or Tab closes. A greyed item stays focusable (`aria-disabled`, the\n * menu pattern's rule) but does nothing. It closes on any pointer-down outside it and on\n * a scroll anywhere; the editor closes it on a pan or zoom.\n */\nexport function CanvasContextMenu({\n x,\n y,\n items,\n onAction,\n onClose,\n}: {\n x: number;\n y: number;\n items: CanvasMenuItem[];\n onAction: (action: CanvasMenuAction) => void;\n /** `restoreFocus` is true when the menu closed from the keyboard (Esc / Tab). */\n onClose: (restoreFocus: boolean) => void;\n}) {\n const ref = useRef<HTMLDivElement>(null);\n const [pos, setPos] = useState({ left: x, top: y });\n\n // Keep the menu inside the editor box: flip left/up when it would overflow.\n useLayoutEffect(() => {\n const el = ref.current;\n const box = el?.offsetParent as HTMLElement | null;\n if (!el || !box) return;\n const w = el.offsetWidth;\n const h = el.offsetHeight;\n setPos({\n left: x + w > box.clientWidth ? Math.max(0, x - w) : x,\n top: y + h > box.clientHeight ? Math.max(0, y - h) : y,\n });\n }, [x, y]);\n\n useEffect(() => {\n ref.current\n ?.querySelector<HTMLButtonElement>(\"[role=menuitem]\")\n ?.focus({ preventScroll: true });\n }, []);\n\n useEffect(() => {\n const onDown = (e: PointerEvent) => {\n if (!ref.current?.contains(e.target as Node)) onClose(false);\n };\n const onScroll = (e: Event) => {\n if (!ref.current?.contains(e.target as Node)) onClose(false);\n };\n const onBlur = () => onClose(false);\n document.addEventListener(\"pointerdown\", onDown, true);\n document.addEventListener(\"scroll\", onScroll, true);\n document.addEventListener(\"wheel\", onScroll, { capture: true, passive: true });\n window.addEventListener(\"blur\", onBlur);\n window.addEventListener(\"resize\", onBlur);\n return () => {\n document.removeEventListener(\"pointerdown\", onDown, true);\n document.removeEventListener(\"scroll\", onScroll, true);\n document.removeEventListener(\"wheel\", onScroll, true);\n window.removeEventListener(\"blur\", onBlur);\n window.removeEventListener(\"resize\", onBlur);\n };\n }, [onClose]);\n\n const run = (item: CanvasMenuItem) => {\n if (item.disabled) return;\n onClose(false);\n onAction(item.action);\n };\n\n return (\n <div\n ref={ref}\n className=\"w6w-note-menu w6w-canvas-menu\"\n role=\"menu\"\n aria-label=\"Canvas actions\"\n data-testid=\"canvas-context-menu\"\n style={{ left: pos.left, top: pos.top }}\n onContextMenu={(e) => e.preventDefault()}\n onKeyDown={(e) => {\n // Nothing typed into the menu reaches the canvas: its Delete/Backspace handler\n // would otherwise act on the selection behind the menu.\n e.stopPropagation();\n const buttons = [\n ...(ref.current?.querySelectorAll<HTMLButtonElement>(\"[role=menuitem]\") ?? []),\n ];\n const at = buttons.indexOf(document.activeElement as HTMLButtonElement);\n const focus = (i: number) => buttons[(i + buttons.length) % buttons.length]?.focus();\n if (e.key === \"ArrowDown\") focus(at + 1);\n else if (e.key === \"ArrowUp\") focus(at < 0 ? -1 : at - 1);\n else if (e.key === \"Home\") focus(0);\n else if (e.key === \"End\") focus(-1);\n else if (e.key === \"Escape\" || e.key === \"Tab\") onClose(true);\n else if (e.key === \"Enter\" || e.key === \" \") {\n if (at >= 0) run(items[at]);\n } else return;\n e.preventDefault();\n }}\n >\n {items.map((item) => (\n <button\n key={item.action}\n type=\"button\"\n role=\"menuitem\"\n tabIndex={-1}\n aria-disabled={item.disabled || undefined}\n className={`w6w-note-menu-item${item.danger ? \" danger\" : \"\"}${item.separated ? \" separated\" : \"\"}`}\n data-action={item.action}\n onClick={() => run(item)}\n >\n {item.label}\n </button>\n ))}\n </div>\n );\n}\n","// The canvas right-click menu's pure half: which nodes a right-click acts on and which\n// items it offers. `CanvasContextMenu.tsx` renders it;\n// `WorkflowFlowEditor` owns the actions.\n\n/** A right-click's flow-space drop point plus the nodes its node actions apply to. */\nexport interface CanvasMenuTarget {\n /** Where an added node lands — the click converted to flow coordinates. */\n flow: { x: number; y: number };\n /** Node ids Duplicate / Delete act on. Empty on a bare-canvas right-click. */\n nodeIds: string[];\n}\n\nexport type CanvasMenuAction = \"duplicate\" | \"delete\" | \"add-node\" | \"add-trigger\";\n\nexport interface CanvasMenuItem {\n action: CanvasMenuAction;\n label: string;\n disabled: boolean;\n danger?: boolean;\n /** A divider is drawn above this item. */\n separated?: boolean;\n}\n\n/**\n * The nodes a right-click acts on. A node that is part of the current selection acts on\n * the whole selection; any other node acts on itself alone (and becomes the selection).\n * The bare canvas acts on whatever is selected.\n */\nexport function contextMenuTargets(selectedIds: readonly string[], nodeId?: string): string[] {\n if (nodeId === undefined) return [...selectedIds];\n return selectedIds.includes(nodeId) ? [...selectedIds] : [nodeId];\n}\n\n/** Duplicate + Delete when nodes are targeted, then Add node + Add trigger. All greyed when read-only. */\nexport function canvasMenuItems(nodeIds: readonly string[], readOnly: boolean): CanvasMenuItem[] {\n const items: CanvasMenuItem[] = [];\n const n = nodeIds.length;\n if (n > 0) {\n const suffix = n > 1 ? ` ${n} nodes` : \"\";\n items.push({ action: \"duplicate\", label: `Duplicate${suffix}`, disabled: readOnly });\n items.push({ action: \"delete\", label: `Delete${suffix}`, disabled: readOnly, danger: true });\n }\n items.push({ action: \"add-node\", label: \"Add node\", disabled: readOnly, separated: n > 0 });\n items.push({ action: \"add-trigger\", label: \"Add trigger\", disabled: readOnly });\n return items;\n}\n","/** Workflow canvas (notes + sections); hand-mirror of core's `Workflow.canvas`. */\nexport interface CanvasNote {\n id: string;\n color: string;\n position: { x: number; y: number };\n size: { width: number; height: number };\n content: string;\n}\n\nexport interface CanvasSection {\n id: string;\n title: string;\n color: string;\n position: { x: number; y: number };\n size: { width: number; height: number };\n /** Member node ids; a node belongs to at most one section. */\n nodes: string[];\n}\n\nexport interface FlowCanvas {\n notes?: CanvasNote[];\n sections?: CanvasSection[];\n}\n\nexport const MAX_NOTES = 200;\nexport const MAX_SECTIONS = 200;\nexport const MAX_NOTE_BYTES = 10240;\n","import { type FlowCanvas, MAX_NOTES, MAX_NOTE_BYTES, MAX_SECTIONS } from \"./canvas-types.ts\";\n\n/** Live geometry keyed by note/section id. */\nexport interface LiveGeometry {\n [id: string]: { position?: { x: number; y: number }; size?: { width: number; height: number } };\n}\n\n/** Round every stored number to an integer. */\nexport function roundGeometry<\n T extends { x: number; y: number } | { width: number; height: number },\n>(g: T): T {\n const out: Record<string, number> = {};\n for (const [k, v] of Object.entries(g)) out[k] = Math.round(v as number);\n return out as T;\n}\n\ntype Pos = { x: number; y: number };\ntype Size = { width: number; height: number };\n\nconst isFinitePos = (p?: Pos): p is Pos => !!p && Number.isFinite(p.x) && Number.isFinite(p.y);\nconst isFiniteSize = (z?: Size): z is Size =>\n !!z && Number.isFinite(z.width) && Number.isFinite(z.height);\n\nfunction mapItems<T extends { id: string; position: Pos; size: Size }>(\n items: T[] | undefined,\n live: LiveGeometry | undefined,\n useLive: boolean,\n): T[] | undefined {\n if (!items) return items;\n return items.map((it) => {\n const l = useLive ? live?.[it.id] : undefined;\n const position = isFinitePos(l?.position) ? l.position : it.position;\n const size = isFiniteSize(l?.size) ? l.size : it.size;\n return { ...it, position: roundGeometry(position), size: roundGeometry(size) };\n });\n}\n\n/**\n * Stamp live geometry onto the stored canvas, rounded to integers. When\n * `savePosition === false` the stored canvas is returned untouched (mirrors\n * `flowToWorkflow`'s `withPosition`): not written is not erased.\n */\nexport function withCanvasGeometry(\n canvas: FlowCanvas,\n savePosition: boolean,\n live?: LiveGeometry,\n): FlowCanvas {\n if (!savePosition) return canvas;\n const out: FlowCanvas = { ...canvas };\n if (canvas.notes) out.notes = mapItems(canvas.notes, live, true);\n if (canvas.sections) out.sections = mapItems(canvas.sections, live, true);\n return out;\n}\n\n/** Remove a deleted node id from every section. */\nexport function pruneSectionMembers(canvas: FlowCanvas, deletedNodeId: string): FlowCanvas {\n if (!canvas.sections) return canvas;\n return {\n ...canvas,\n sections: canvas.sections.map((s) => ({\n ...s,\n nodes: s.nodes.filter((n) => n !== deletedNodeId),\n })),\n };\n}\n\n/** Map a renamed node id in every section. */\nexport function renameSectionMember(canvas: FlowCanvas, from: string, to: string): FlowCanvas {\n if (!canvas.sections) return canvas;\n return {\n ...canvas,\n sections: canvas.sections.map((s) => ({\n ...s,\n nodes: s.nodes.map((n) => (n === from ? to : n)),\n })),\n };\n}\n\n/** Put `nodeIds` into `sectionId`, removing them from any other section (at most one each). */\nexport function assignMembership(\n canvas: FlowCanvas,\n sectionId: string,\n nodeIds: string[],\n): FlowCanvas {\n if (!canvas.sections) return canvas;\n const moving = new Set(nodeIds);\n return {\n ...canvas,\n sections: canvas.sections.map((s) => {\n const kept = s.nodes.filter((n) => !moving.has(n));\n return s.id === sectionId\n ? { ...s, nodes: [...new Set([...kept, ...nodeIds])] }\n : { ...s, nodes: kept };\n }),\n };\n}\n\n/** Ids of every section containing the node. */\nexport function sectionsContaining(canvas: FlowCanvas, nodeId: string): string[] {\n return (canvas.sections ?? []).filter((s) => s.nodes.includes(nodeId)).map((s) => s.id);\n}\n\n/** Truncate to at most `max` UTF-8 bytes without splitting a codepoint. */\nfunction truncateBytes(text: string, max: number): string {\n const enc = new TextEncoder();\n if (enc.encode(text).length <= max) return text;\n let out = \"\";\n let used = 0;\n for (const ch of text) {\n const n = enc.encode(ch).length;\n if (used + n > max) break;\n out += ch;\n used += n;\n }\n return out;\n}\n\n/** Enforce the caps: 200 notes, 200 sections, 10240 UTF-8 bytes per note content. */\nexport function clampCanvas(canvas: FlowCanvas): FlowCanvas {\n const out: FlowCanvas = { ...canvas };\n if (canvas.notes) {\n out.notes = canvas.notes\n .slice(0, MAX_NOTES)\n .map((n) => ({ ...n, content: truncateBytes(n.content, MAX_NOTE_BYTES) }));\n }\n if (canvas.sections) out.sections = canvas.sections.slice(0, MAX_SECTIONS);\n return out;\n}\n\n/**\n * The canvas to emit. Geometry is stamped (rounded) from the live canvas when `savePosition` is\n * on; when off, every item already in `stored` keeps its STORED position/size (live edits render\n * but are not written — mirrors node positions). Items new this session keep their live geometry.\n */\nexport function persistCanvas(\n canvas: FlowCanvas,\n stored: FlowCanvas | undefined,\n savePosition: boolean,\n): FlowCanvas {\n const live: LiveGeometry = {};\n for (const it of [...(canvas.notes ?? []), ...(canvas.sections ?? [])]) {\n live[it.id] = { position: it.position, size: it.size };\n }\n const pin = <T extends { id: string; position: Pos; size: Size }>(items?: T[], old?: T[]) =>\n items?.map((it) => {\n const s = old?.find((o) => o.id === it.id);\n return s ? { ...it, position: s.position, size: s.size } : it;\n });\n const base: FlowCanvas = savePosition\n ? canvas\n : {\n ...canvas,\n ...(canvas.notes ? { notes: pin(canvas.notes, stored?.notes) } : {}),\n ...(canvas.sections ? { sections: pin(canvas.sections, stored?.sections) } : {}),\n };\n return withCanvasGeometry(base, savePosition, live);\n}\n","/**\n * Clipping for ONE resolved value's display text (Test tab, read-only rows).\n *\n * A resolved row is a SUMMARY of what the run will be sent, not a viewer for\n * it. A value that resolves from a document (`documents.*.body`) or a rendered\n * template is routinely tens of kilobytes of HTML, and pasting all of it inline\n * pushed the rest of the params — and the run's own result — off the screen\n * (human report, 2026-09-01). So a long value is clipped here and offered\n * behind a toggle; the complete value is always one click away in the `<>`\n * code view above, which is COMPLETE over every visible param by construction\n * (`resolved-json.ts`, D-2) and so must never be clipped itself.\n *\n * Plain `.ts`, no React — same pure-module-beside-the-component precedent\n * `history-scale.ts` sets for `HistoryTimeline.tsx`, so the rule is testable\n * without a JSX transpile.\n */\n\n/**\n * Characters shown before a value is clipped. Sized to a few lines at the\n * row's font — enough to recognize WHICH value resolved (the opening of an\n * HTML document, a subject line, a URL) without becoming the page.\n */\nexport const RESOLVED_VALUE_CLIP = 220;\n\n/** A clip decision: the text to render, and whether anything was withheld. */\nexport interface ClippedValue {\n /** What to show when collapsed — never longer than {@link RESOLVED_VALUE_CLIP}. */\n text: string;\n /** True when `text` is shorter than the input, i.e. a toggle is warranted. */\n clipped: boolean;\n /** The full value's length, for the toggle's own label. */\n length: number;\n}\n\n/**\n * Clip `text` for the collapsed row. At or under the budget the input is\n * returned byte-identically and `clipped` is false — a short value must never\n * grow a toggle, an ellipsis, or a trailing-whitespace trim it didn't ask for.\n *\n * Over the budget, the cut is a plain `slice` at the boundary with trailing\n * whitespace trimmed (so an ellipsis never floats a space away from the text).\n * No word-boundary search: these values are markup and JSON as often as prose,\n * where \"the last space\" is not a meaningful place to stop.\n */\nexport function clipResolvedValue(text: string): ClippedValue {\n if (text.length <= RESOLVED_VALUE_CLIP) {\n return { text, clipped: false, length: text.length };\n }\n return {\n text: text.slice(0, RESOLVED_VALUE_CLIP).trimEnd(),\n clipped: true,\n length: text.length,\n };\n}\n","import { effectiveParam } from \"@w6w/expr\";\nimport { useMemo, useState } from \"react\";\nimport { JsonEditor } from \"../JsonEditor.tsx\";\nimport { dataVarRows, flattenParams, isParamVisible } from \"../ParamsForm.tsx\";\nimport { hasParamCustomization, previewCustomization } from \"../param-customization.ts\";\nimport type { StepStartState } from \"../provider.tsx\";\nimport {\n type ResolveScope,\n type ResolvedSegment,\n buildResolveScope,\n deepEqual,\n resolveParamValue,\n} from \"../resolve-params.ts\";\nimport { resolveParamJson, resolveVarsJson } from \"../resolved-json.ts\";\nimport type { ActionParam } from \"../types.ts\";\nimport { Copyable } from \"./Copyable.tsx\";\nimport { useExpressionOptions } from \"./ExpressionOptions.tsx\";\nimport { varLabel } from \"./expression-dom.ts\";\nimport { clipResolvedValue } from \"./resolved-clip.ts\";\n\nexport interface ResolvedParamsProps {\n /** The action's declared params — same list `ParamsForm` renders on Configure. */\n params: ActionParam[];\n /** What will actually be submitted: `{ ...step.with, ...override }` — `testValues`, not `step.with`. */\n values: Record<string, unknown>;\n /** The exact object the test invoke sends as `state` — `steps.*`/`trigger.*` resolve against this. */\n testStartState?: StepStartState;\n /**\n * `\"props\"` (default) renders the filtered row list; `\"code\"` renders the\n * COMPLETE resolved-values JSON (A4/A5/D-2) — every visible param, defaults\n * included. Driven by the host's own toggle state; this component never\n * mounts a toggle of its own (D-7 — `PropertyEntryForm` already owns one on\n * the trigger arm, and two side by side is a defect, not a feature).\n */\n view?: \"props\" | \"code\";\n /**\n * Param keys the host sends as SOURCE TEXT, never resolved (`@w6w/script`'s `code`, the\n * engine's `LITERAL_PARAMS`): shown verbatim, so a `{{ }}` in them never reads as a value.\n */\n literalKeys?: readonly string[];\n}\n\n/**\n * Read-only sibling of `ParamsForm`: for every configured param, shows the\n * value it resolves to against the current test scope instead of an editable\n * widget. Mounts no `contentEditable`, no `ƒx` button, no input, and never\n * calls an `onChange` — this is the Test tab's \"what will actually be sent\"\n * view, not a second place to edit params.\n *\n * Reuses `flattenParams`/`isParamVisible` from `ParamsForm.tsx` (same order +\n * visibility the Configure tab uses) rather than re-flattening sections, and\n * the static chip vocabulary (`varLabel`, `.w6w-expr-chip-*`) rather than\n * `expression-dom.ts`'s DOM-painting, which is for the editable field.\n */\nexport function ResolvedParams({\n params,\n values,\n testStartState,\n view = \"props\",\n literalKeys,\n}: ResolvedParamsProps) {\n const { sampleValues, nodeConfig, nodeMeta } = useExpressionOptions();\n const scope = useMemo(\n () => buildResolveScope(sampleValues, testStartState, nodeConfig, nodeMeta),\n [sampleValues, testStartState, nodeConfig, nodeMeta],\n );\n const flat = flattenParams(params);\n const effective = (key: string) =>\n values[key] !== undefined ? values[key] : flat.find((p) => p.key === key)?.default;\n // Sections are layout-only containers with no value of their own (their\n // children, already flattened, carry the values) — skip rendering a row for\n // the section param itself, exactly as `ParamsForm`'s own `renderOne` does.\n // This is the \"visible\" row set D-2's code view is complete OVER — before\n // A1's unchanged-value filter, so the code view still carries a param the\n // list hides.\n const visibleRows = flat\n .filter((p) => p.type !== \"section\" && isParamVisible(p, effective))\n .map((p) => effectiveParam(p, effective));\n\n if (hasParamCustomization(values)) {\n const custom = previewCustomization(values.$merge, scope, literalKeys);\n const object = custom !== null && typeof custom === \"object\" && !Array.isArray(custom);\n const base = buildResolvedJson(visibleRows, values, scope, literalKeys);\n for (const [key, value] of Object.entries(values)) {\n if (key !== \"$merge\")\n base[key] = literalKeys?.includes(key) ? value : previewCustomization(value, scope);\n }\n const merged = object ? { ...base, ...custom } : base;\n return (\n <div className=\"w6w-resolved-params\">\n <p className=\"w6w-muted w6w-small\">\n {object\n ? \"JSON customization applied after form values.\"\n : `JSON customization is not available as an object in this preview (${String(custom)}). Test the step to validate it.`}\n </p>\n {view === \"code\" ? (\n <JsonEditor\n value={JSON.stringify(merged, null, 2)}\n onChange={() => {}}\n readOnly\n minHeight=\"260px\"\n height=\"100%\"\n aria-label=\"Resolved test values (JSON)\"\n />\n ) : (\n <div className=\"w6w-resolved-table\">\n {Object.entries(merged).map(([key, value]) => (\n <ResolvedParamRow\n key={key}\n label={flat.find((p) => p.key === key)?.label ?? key}\n segments={[{ status: \"resolved\", value }]}\n />\n ))}\n </div>\n )}\n </div>\n );\n }\n\n if (view === \"code\") {\n // Derived fresh on every render from `values` — no draft state — so\n // editing the incoming-state override above updates this text live,\n // exactly as it already updates the row list (A5).\n const json = buildResolvedJson(visibleRows, values, scope, literalKeys);\n return (\n <div className=\"w6w-resolved-params\">\n <JsonEditor\n value={JSON.stringify(json, null, 2)}\n onChange={() => {}}\n readOnly\n minHeight=\"260px\"\n height=\"100%\"\n aria-label=\"Resolved test values (JSON)\"\n />\n </div>\n );\n }\n\n // A1/D-1: drop a row whose effective value is deep-equal to its declared\n // default — noise the human named explicitly (an unset `Sender Name \"\"`, an\n // explicitly-false `required` boolean, an empty `{}`/array). Uniform: no\n // `required` exemption, and a key EXPLICITLY present in `with` that happens\n // to equal the default is hidden too (equality, not presence — D-1).\n const rows = visibleRows.filter((p) => !deepEqual(effective(p.key), p.default));\n\n if (visibleRows.length === 0) {\n return (\n <div className=\"w6w-resolved-params\">\n <p className=\"w6w-muted w6w-small\">This action takes no parameters.</p>\n </div>\n );\n }\n\n if (rows.length === 0) {\n return (\n <div className=\"w6w-resolved-params\">\n <p className=\"w6w-muted w6w-small\">\n Every configured value matches its default — nothing to show here. Switch to JSON to see\n the full set.\n </p>\n </div>\n );\n }\n\n return (\n // `.w6w-resolved-table` is the ONE grid this whole row list shares — each\n // `.w6w-resolved-row` below is `display: contents` and contributes its\n // two children straight into these column tracks, so every row's key\n // column lines up with every other row's.\n <div className=\"w6w-resolved-params w6w-resolved-table\">\n {rows.map((param) =>\n param.type === \"vars\" ? (\n <ResolvedVarsRow key={param.key} param={param} value={values[param.key]} scope={scope} />\n ) : (\n <ResolvedParamRow\n key={param.key}\n label={param.label ?? param.key}\n segments={\n literalKeys?.includes(param.key)\n ? [{ status: \"resolved\", value: effective(param.key) }]\n : resolveParamValue(effective(param.key), scope)\n }\n />\n ),\n )}\n </div>\n );\n}\n\n/**\n * D-2: the code view is COMPLETE over `rows` (every visible param — see the\n * caller — defaults included, the row set BEFORE A1's filter), one key per\n * `param.key`, each folded through {@link resolveParamJson}/{@link\n * resolveVarsJson} (never the schema, never raw `step.with`, never the\n * `{type:\"expr\",…}` envelope — A6's pinned serialization).\n */\nfunction buildResolvedJson(\n rows: ActionParam[],\n values: Record<string, unknown>,\n scope: ResolveScope,\n literalKeys?: readonly string[],\n): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const param of rows) {\n if (literalKeys?.includes(param.key)) {\n out[param.key] = values[param.key] !== undefined ? values[param.key] : param.default;\n } else if (param.type === \"vars\") {\n const raw = values[param.key] ?? param.default ?? [];\n const vars = dataVarRows(raw);\n out[param.key] = vars ? resolveVarsJson(vars, scope) : resolveParamJson(raw, scope);\n } else {\n out[param.key] = resolveParamJson(\n values[param.key] !== undefined ? values[param.key] : param.default,\n scope,\n );\n }\n }\n return out;\n}\n\nfunction ResolvedParamRow({ label, segments }: { label: string; segments: ResolvedSegment[] }) {\n return (\n <div className=\"w6w-resolved-row\">\n <span className=\"w6w-resolved-label\">{label}</span>\n <div className=\"w6w-resolved-value\">\n <ResolvedSegments segments={segments} />\n </div>\n </div>\n );\n}\n\n/** A `vars`-typed param: one row per configured key, each resolved independently (A5). */\nfunction ResolvedVarsRow({\n param,\n value,\n scope,\n}: {\n param: ActionParam;\n value: unknown;\n scope: ResolveScope;\n}) {\n const raw = value ?? param.default ?? [];\n const rows = dataVarRows(raw);\n if (rows === null) {\n return (\n <ResolvedParamRow label={param.label ?? param.key} segments={resolveParamValue(raw, scope)} />\n );\n }\n return (\n <div className=\"w6w-resolved-row\">\n <span className=\"w6w-resolved-label\">{param.label ?? param.key}</span>\n {rows.length === 0 ? (\n <p className=\"w6w-muted w6w-small\">None configured.</p>\n ) : (\n <div className=\"w6w-stack\">\n {rows.map((row, i) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: rows have no stable id (mirrors ParamsForm's VarsField)\n <div className=\"w6w-resolved-value\" key={i}>\n <code>{row.key || \"(no key)\"}</code>\n {\" → \"}\n <ResolvedSegments segments={resolveParamValue(row.value, scope)} />\n </div>\n ))}\n </div>\n )}\n </div>\n );\n}\n\nfunction ResolvedSegments({ segments }: { segments: ResolvedSegment[] }) {\n return (\n <>\n {segments.map((seg, i) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: segments are a positional, immutable render of one value's parts\n <ResolvedSegmentView key={i} segment={seg} />\n ))}\n </>\n );\n}\n\n/** One part's worth of chrome: a static chip (for anything ref-shaped) plus its outcome. */\nfunction ResolvedSegmentView({ segment }: { segment: ResolvedSegment }) {\n switch (segment.status) {\n case \"resolved\":\n return segment.ref ? (\n <>\n <ExprChip kind=\"var\" refName={segment.ref} />\n <ResolvedValueText value={segment.value} />\n </>\n ) : (\n <ResolvedValueText value={segment.value} />\n );\n case \"unresolved\":\n // Never the ref/template text as if it were the value: the chip shows\n // only the short display LABEL (never the full ref string — the same\n // \"label ≠ ref\" precedent `expression-dom.ts` documents), and the\n // outcome is a dedicated, always-non-blank badge.\n return (\n <>\n <ExprChip kind=\"var\" refName={segment.ref} />\n <span className=\"w6w-param-unresolved\">unresolved</span>\n </>\n );\n case \"at-run\":\n // A node config key this client cannot see (the host fills it on the run): neutral.\n return (\n <>\n <ExprChip kind=\"var\" refName={segment.ref} />\n <span className=\"w6w-param-unevaluated\">resolved at run</span>\n </>\n );\n case \"not-evaluated\":\n return (\n <>\n <ExprChip kind=\"expr\" />\n <span className=\"w6w-param-unevaluated\">not evaluated</span>\n </>\n );\n case \"masked\":\n // The chip's 🔒 sigil already says \"masked\" — no separate badge needed,\n // and no ciphertext or plaintext is ever available to show here.\n return <ExprChip kind=\"secret\" refName={segment.ref} />;\n }\n}\n\n/**\n * One resolved value's text, clipped when it is long enough to take over the\n * row (`resolved-clip.ts`). A document body or a rendered template resolves to\n * tens of kilobytes of HTML, and a row that pastes all of it inline buries the\n * other params and the run's result below it (human report, 2026-09-01).\n *\n * Expanding does NOT restore the unbounded paste: the full text goes into its\n * own scrollable block (`.w6w-resolved-text-full`), so the row can never grow\n * past a few lines of the panel either way. A value inside the budget renders\n * exactly as it always did — one bare `<span>`, no toggle, no wrapper.\n */\nfunction ResolvedValueText({ value }: { value: unknown }) {\n const [expanded, setExpanded] = useState(false);\n const full = formatResolvedValue(value);\n const clip = clipResolvedValue(full);\n if (!clip.clipped) return <span>{full}</span>;\n return (\n <>\n {expanded ? (\n <Copyable value={full} label=\"Copy resolved value\" className=\"w6w-resolved-copy\">\n <pre className=\"w6w-resolved-text-full\">{full}</pre>\n </Copyable>\n ) : (\n <span>{clip.text}…</span>\n )}\n <button\n type=\"button\"\n className=\"w6w-resolved-more\"\n aria-expanded={expanded}\n onClick={() => setExpanded((e) => !e)}\n >\n {expanded ? \"Show less\" : `Show all (${clip.length.toLocaleString()} characters)`}\n </button>\n </>\n );\n}\n\nconst CHIP_SIGIL: Record<\"var\" | \"secret\" | \"expr\", string> = { var: \"◆\", secret: \"🔒\", expr: \"ƒ\" };\n\n/**\n * A read-only chip, visually consistent with `expression-dom.ts`'s\n * `makeChip` (same classes/sigils, same `varLabel` shortening) but built on a\n * plain `<span>` — no `contentEditable`, no remove button, no DOM painting.\n */\nfunction ExprChip({ kind, refName }: { kind: \"var\" | \"secret\" | \"expr\"; refName?: string }) {\n const label = kind === \"expr\" ? \"expr\" : varLabel(refName ?? \"\");\n return (\n <span className={`w6w-expr-chip w6w-expr-chip-${kind}`}>\n <span className=\"w6w-expr-chip-sigil\">{CHIP_SIGIL[kind]}</span>\n <span className=\"w6w-expr-chip-label\">{label}</span>\n </span>\n );\n}\n\n/**\n * A resolved value, formatted for display — never blank, even for the falsy\n * values `resolved` explicitly covers (`null`/`\"\"`/`false`/`0`): each renders\n * visibly distinct text so it never reads as \"nothing here\" the way an actual\n * blank would.\n */\nfunction formatResolvedValue(value: unknown): string {\n if (value === null) return \"null\";\n if (value === undefined) return \"(not set)\";\n if (value === \"\") return '\"\"';\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n","import { useEffect, useRef, useState } from \"react\";\nimport {\n type ScriptLanguage,\n convertCodeBindingsToReads,\n findCodeBindings,\n} from \"../script-bindings.ts\";\n\nfunction languageOf(values: Record<string, unknown>): ScriptLanguage {\n return values.language === \"python\" || values.language === \"typescript\"\n ? values.language\n : \"javascript\";\n}\n\nexport interface ScriptConversion {\n /** What the open-time conversion did, until Undo. */\n converted: number;\n undo: () => void;\n}\n\n/**\n * A Run script's `{{ }}` markers, converted when the step opens. The host never substitutes\n * inside code (see `script-bindings.ts`), so a marker there is literal text at run time. When\n * the step opens, each convertible marker is rewritten to the code read it names\n * (`$.get(root, ...keys)` in JavaScript/TypeScript); {@link ScriptBindingsNotice} says so,\n * with Undo. Runs once per mount of the step editor, so after Undo the code stays as it was\n * until the step is opened again. Read-only (or not a script), nothing is rewritten.\n */\nexport function useScriptConversion({\n enabled,\n values,\n onChange,\n}: {\n /** A writable `@w6w/script` step. */\n enabled: boolean;\n /** The step's `with`: `code`, `language`, `input`. */\n values: Record<string, unknown>;\n onChange: (next: Record<string, unknown>) => void;\n}): ScriptConversion | null {\n const [done, setDone] = useState<{\n original: string;\n converted: number;\n } | null>(null);\n const ran = useRef(false);\n const code = typeof values.code === \"string\" ? values.code : \"\";\n\n useEffect(() => {\n if (!enabled || ran.current) return;\n ran.current = true;\n const r = convertCodeBindingsToReads(code, languageOf(values));\n if (r.converted === 0) return;\n setDone({ original: code, converted: r.converted });\n onChange({ ...values, code: r.code });\n }, [enabled, code, values, onChange]);\n\n if (!done) return null;\n return {\n converted: done.converted,\n undo: () => {\n onChange({ ...values, code: done.original });\n setDone(null);\n },\n };\n}\n\n/**\n * The quiet line under a Run script's Configure tab: \"Converted 2 references to code reads ·\n * Undo\" after the open-time conversion, and, for any marker still in the code, that it stays\n * literal text. Renders nothing otherwise.\n */\nexport function ScriptBindingsNotice({\n values,\n conversion,\n readOnly,\n}: {\n /** The step's `with`: `code`, `language`. */\n values: Record<string, unknown>;\n conversion: ScriptConversion | null;\n readOnly?: boolean;\n}) {\n const code = typeof values.code === \"string\" ? values.code : \"\";\n const done = conversion;\n const left = findCodeBindings(code, languageOf(values)).length;\n if (!done && left === 0) return null;\n return (\n <output className=\"w6w-hint w6w-script-converted\">\n {done && (\n <>\n Converted {done.converted} reference{done.converted === 1 ? \"\" : \"s\"} to code reads\n {!readOnly && (\n <>\n {\" · \"}\n <button type=\"button\" className=\"w6w-script-converted-undo\" onClick={done.undo}>\n Undo\n </button>\n </>\n )}\n {left > 0 && \" · \"}\n </>\n )}\n {left > 0 && (\n <>\n {left} <code>{\"{{ }}\"}</code> left in the code stay\n {left === 1 ? \"s\" : \"\"} literal text — read {left === 1 ? \"it\" : \"them\"} from{\" \"}\n <code>state</code>, or bind under Custom input\n </>\n )}\n </output>\n );\n}\n","import type { Edge } from \"@xyflow/react\";\nimport type { FlowCanvas } from \"./canvas-types.ts\";\nimport { pruneSectionMembers } from \"./canvas-utils.ts\";\nimport { bridgeDeletedBodyStep, deleteStepMessage, isForeachStep, loopBody } from \"./flow-loop.ts\";\nimport type { StepNode } from \"./flow-utils.ts\";\n\nexport interface FlowDeleteSelection {\n nodeIds: string[];\n edgeIds: string[];\n}\n\n/** Capture the full selection, independently of the first item shown in the side panel. */\nexport function selectedFlowElements(nodes: StepNode[], edges: Edge[]): FlowDeleteSelection {\n return {\n nodeIds: nodes.filter((n) => n.selected).map((n) => n.id),\n edgeIds: edges.filter((e) => e.selected).map((e) => e.id),\n };\n}\n\n/** Apply the entire confirmed selection before the editor emits one change/history entry. */\nexport function deleteFlowSelection(\n selection: FlowDeleteSelection,\n nodes: StepNode[],\n edges: Edge[],\n canvas: FlowCanvas,\n) {\n const nodeIds = new Set(selection.nodeIds);\n const edgeIds = new Set(selection.edgeIds);\n const removed = nodes.filter((n) => nodeIds.has(n.id));\n // Detach an entire loop before removing any selected body members: otherwise removing\n // a branching body step first could hide surviving descendants from the loop traversal.\n const ordered = [\n ...removed.filter((n) => isForeachStep(n.data.step)),\n ...removed.filter((n) => !isForeachStep(n.data.step)),\n ];\n let nextNodes = nodes;\n let nextEdges = edges;\n let nextCanvas = canvas;\n for (const node of ordered) {\n nextEdges = bridgeDeletedBodyStep(node.id, nextNodes, nextEdges);\n nextNodes = nextNodes.filter((n) => n.id !== node.id);\n nextCanvas = pruneSectionMembers(nextCanvas, node.id);\n }\n return {\n nodes: nextNodes,\n edges: nextEdges.filter((e) => !edgeIds.has(e.id)),\n canvas: nextCanvas,\n };\n}\n\nexport function flowDeleteMessage(\n selection: FlowDeleteSelection,\n nodes: StepNode[],\n edges: Edge[],\n): string {\n const nodeIds = new Set(selection.nodeIds);\n const edgeIds = new Set(selection.edgeIds);\n // Incident edges are already covered by \"their connections\"; name separately selected edges.\n const extraEdges = edges.filter(\n (e) => edgeIds.has(e.id) && !nodeIds.has(e.source) && !nodeIds.has(e.target),\n );\n const messages: string[] = [];\n if (nodeIds.size === 1) {\n messages.push(deleteStepMessage(selection.nodeIds[0], nodes, edges));\n } else if (nodeIds.size > 1) {\n messages.push(\n `Delete nodes ${[...nodeIds].map((id) => `\"${id}\"`).join(\", \")}? Their connections are removed too.`,\n );\n const detached = new Set<string>();\n for (const id of nodeIds) {\n if (!isForeachStep(nodes.find((n) => n.id === id)?.data.step)) continue;\n for (const member of loopBody(id, nodes, edges)) {\n if (!nodeIds.has(member)) detached.add(member);\n }\n }\n if (detached.size) {\n messages.push(\n `Loop body steps ${[...detached].map((id) => `\"${id}\"`).join(\", \")} stay as standalone steps.`,\n );\n }\n }\n if (extraEdges.length) {\n messages.push(\n `Delete ${extraEdges.length === 1 ? \"connection\" : \"connections\"} ${extraEdges.map((e) => `\"${e.source} → ${e.target}\"`).join(\", \")}?`,\n );\n }\n return messages.join(\" \");\n}\n","// Pure fan-out decisions for the \"Run next nodes\" control and card badge.\nimport type { Edge } from \"@xyflow/react\";\nimport { edgeLane } from \"./flow-connect.ts\";\nimport type { FlowStep } from \"./flow-types.ts\";\n\nexport type FanOutMode = \"sequential\" | \"parallel\";\n\n/**\n * `count` is the largest number of outgoing edges the node has in any ONE lane\n * (success / error); fan-out only means something at `count >= 2`.\n */\nexport function fanOutState(\n stepId: string,\n edges: readonly Edge[],\n): { enabled: boolean; count: number } {\n const per = { success: 0, error: 0 };\n for (const e of edges) {\n if (e.source !== stepId) continue;\n const lane = edgeLane(e);\n // The each lane is a loop body, not fan-out: it never counts.\n if (lane !== \"each\") per[lane]++;\n }\n const count = Math.max(per.success, per.error);\n return { enabled: count >= 2, count };\n}\n\n/** Sequential is the default, so it is expressed by the key's ABSENCE. */\nexport function setFanOut(step: FlowStep, mode: FanOutMode): FlowStep {\n const { fanOut: _drop, ...rest } = step;\n return mode === \"parallel\" ? { ...rest, fanOut: \"parallel\" } : rest;\n}\n\n/** Card-badge wording: how many next nodes run, and in which mode. */\nexport function fanOutLabel(count: number, mode: FanOutMode): string {\n return `Runs these ${count} nodes in ${mode === \"parallel\" ? \"parallel\" : \"sequence\"}`;\n}\n","import type { Edge } from \"@xyflow/react\";\nimport type { FlowCanvas } from \"./canvas-types.ts\";\nimport type { FlowStep, FlowWorkflow } from \"./flow-types.ts\";\nimport { type StepNode, flowToWorkflow, workflowToFlow } from \"./flow-utils.ts\";\n\n/** Only authored graph data. Tests, samples, run paint, selection and viewport never enter history. */\nexport interface FlowEditSnapshot {\n nodes: FlowStep[];\n edges: NonNullable<FlowWorkflow[\"edges\"]>;\n connections: NonNullable<FlowWorkflow[\"connections\"]>;\n canvas: FlowCanvas;\n /** Keep the live layout even when saving positions is switched off. */\n positions: Record<string, { x: number; y: number }>;\n}\n\nexport function captureFlowEdit(\n base: FlowWorkflow,\n nodes: StepNode[],\n edges: Edge[],\n connections: FlowEditSnapshot[\"connections\"],\n canvas: FlowCanvas,\n): FlowEditSnapshot {\n const definition = flowToWorkflow({ ...base, connections }, nodes, edges);\n return {\n nodes: definition.nodes.map(({ with: params, ...step }) =>\n params && Object.keys(params).length ? { ...step, with: params } : step,\n ),\n edges: definition.edges ?? [],\n connections: definition.connections ?? {},\n canvas,\n positions: Object.fromEntries(nodes.map((n) => [n.id, n.position])),\n };\n}\n\nexport function restoreFlowEdit(base: FlowWorkflow, snapshot: FlowEditSnapshot) {\n const graph = workflowToFlow({ ...base, ...snapshot });\n return {\n ...graph,\n nodes: graph.nodes.map((n) => ({\n ...n,\n position: snapshot.positions[n.id] ?? n.position,\n })),\n };\n}\n\n/** Bounded, editor-session history. One text-field focus session is one undoable edit. */\nexport class FlowEditHistory {\n private past: string[] = [];\n private future: string[] = [];\n private present: string;\n private group: object | undefined;\n private readonly limit: number;\n\n constructor(initial: FlowEditSnapshot, limit = 100) {\n this.limit = limit;\n this.present = JSON.stringify(initial);\n }\n\n reset(initial: FlowEditSnapshot) {\n this.present = JSON.stringify(initial);\n this.past = [];\n this.future = [];\n this.group = undefined;\n }\n\n record(snapshot: FlowEditSnapshot, group?: object) {\n const next = JSON.stringify(snapshot);\n if (next === this.present) return;\n if (!group || group !== this.group) {\n this.past.push(this.present);\n if (this.past.length > this.limit) this.past.shift();\n }\n this.present = next;\n this.group = group;\n this.future = [];\n }\n\n undo(): FlowEditSnapshot | undefined {\n const previous = this.past.pop();\n if (previous === undefined) return;\n this.future.push(this.present);\n this.present = previous;\n this.group = undefined;\n return JSON.parse(previous);\n }\n\n redo(): FlowEditSnapshot | undefined {\n const next = this.future.pop();\n if (next === undefined) return;\n this.past.push(this.present);\n this.present = next;\n this.group = undefined;\n return JSON.parse(next);\n }\n}\n\n/** Leave native text undo and CodeMirror's own history alone. */\nexport function isFlowTextTarget(target: EventTarget | null): boolean {\n const element = target as HTMLElement | null;\n return Boolean(\n element?.isContentEditable ||\n element?.closest?.(\n 'input, textarea, select, [contenteditable=\"true\"], [contenteditable=\"\"], [role=\"textbox\"], .cm-editor',\n ),\n );\n}\n","import type { Edge } from \"@xyflow/react\";\nimport type { FlowCanvas } from \"./canvas-types.ts\";\nimport { type StepNode, relayoutNodes } from \"./flow-utils.ts\";\n\nconst GAP = 64;\nconst SECTION_PADDING = 24;\nconst SECTION_LABEL_HEIGHT = 32;\n\ntype Rect = { x: number; y: number; width: number; height: number };\n\nfunction nodeSize(node: StepNode) {\n return {\n width: node.measured?.width ?? node.width ?? 200,\n height: node.measured?.height ?? node.height ?? 64,\n };\n}\n\nfunction overlaps(a: Rect, b: Rect) {\n return a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y;\n}\n\n/** Expand columns and rows for the actual cards, including trigger metadata. */\nfunction spaceNodes(nodes: StepNode[]): StepNode[] {\n const offsets = (axis: \"x\" | \"y\", dimension: \"width\" | \"height\") => {\n const extents = new Map<number, number>();\n for (const node of nodes) {\n const at = node.position[axis];\n extents.set(at, Math.max(extents.get(at) ?? 0, nodeSize(node)[dimension]));\n }\n const placed = new Map<number, number>();\n let end = Number.NEGATIVE_INFINITY;\n for (const [at, extent] of [...extents].sort(([a], [b]) => a - b)) {\n const start = Math.max(at, end);\n placed.set(at, start);\n end = start + extent + GAP;\n }\n return placed;\n };\n const x = offsets(\"x\", \"width\");\n const y = offsets(\"y\", \"height\");\n return nodes.map((node) => ({\n ...node,\n position: {\n x: x.get(node.position.x) ?? node.position.x,\n y: y.get(node.position.y) ?? node.position.y,\n },\n }));\n}\n\n/**\n * Arrange paths and their section frames together. Membership is authored data:\n * fit each frame to its members, never infer new membership from moved geometry.\n * A section spanning non-members is moved with its members below the obstruction.\n * Notes and empty sections retain their authored geometry.\n */\nexport function relayoutFlow(\n nodes: StepNode[],\n edges: Edge[],\n canvas: FlowCanvas,\n): { nodes: StepNode[]; canvas: FlowCanvas } {\n const arranged = spaceNodes(relayoutNodes(nodes, edges));\n if (!canvas.sections?.length) return { nodes: arranged, canvas };\n const byId = new Map(arranged.map((node) => [node.id, node]));\n const occupied: Rect[] = (canvas.notes ?? []).map((note) => ({ ...note.position, ...note.size }));\n // Empty frames also occupy space, even if encountered after a populated one.\n for (const section of canvas.sections) {\n if (!section.nodes.some((id) => byId.has(id))) {\n occupied.push({\n ...section.position,\n ...section.size,\n y: section.position.y - SECTION_LABEL_HEIGHT,\n height: section.size.height + SECTION_LABEL_HEIGHT,\n });\n }\n }\n const sections = canvas.sections.map((section) => {\n const memberIds = new Set(section.nodes);\n const members = arranged.filter((node) => memberIds.has(node.id));\n if (!members.length) return section;\n const x = Math.min(...members.map((node) => node.position.x)) - SECTION_PADDING;\n const y = Math.min(...members.map((node) => node.position.y)) - SECTION_PADDING;\n const right = Math.max(...members.map((node) => node.position.x + nodeSize(node).width));\n const bottom = Math.max(...members.map((node) => node.position.y + nodeSize(node).height));\n const frame = {\n x,\n y,\n width: right + SECTION_PADDING - x,\n height: bottom + SECTION_PADDING - y,\n };\n const obstacles = [\n ...occupied,\n ...[...byId.values()]\n .filter((node) => !memberIds.has(node.id))\n .map((node) => ({ ...node.position, ...nodeSize(node) })),\n ].sort((a, b) => a.y - b.y);\n for (const obstacle of obstacles) {\n const withLabel = {\n ...frame,\n y: frame.y - SECTION_LABEL_HEIGHT,\n height: frame.height + SECTION_LABEL_HEIGHT,\n };\n if (overlaps(withLabel, obstacle)) {\n frame.y = obstacle.y + obstacle.height + SECTION_PADDING + SECTION_LABEL_HEIGHT;\n }\n }\n const dy = frame.y - y;\n for (const node of members) {\n byId.set(node.id, { ...node, position: { x: node.position.x, y: node.position.y + dy } });\n }\n occupied.push({\n ...frame,\n y: frame.y - SECTION_LABEL_HEIGHT,\n height: frame.height + SECTION_LABEL_HEIGHT,\n });\n return {\n ...section,\n position: { x: frame.x, y: frame.y },\n size: { width: frame.width, height: frame.height },\n };\n });\n return {\n nodes: arranged.map((node) => byId.get(node.id) ?? node),\n canvas: { ...canvas, sections },\n };\n}\n","/**\n * Loop colours: every For each on a canvas gets its own tone, shared by its Each item\n * port, its body edges and the dots on its body steps (never the body steps' own\n * background — a step inside a loop looks like any other). The palette lives in\n * `_tokens.scss` as `--w6w-loop-1` … `--w6w-loop-{LOOP_TONES}` (light + dark), and\n * deliberately holds no red, black or green, so a loop never reads as an error port\n * or a success/taken edge.\n *\n * A tone is DERIVED from the For each's id — hashed, then probed past tones another\n * loop already took — so it survives a reload and two loops in one workflow never share\n * one (until there are more loops than tones).\n */\nimport type { Edge } from \"@xyflow/react\";\nimport type { CSSProperties } from \"react\";\nimport { isForeachStep } from \"./flow-loop.ts\";\nimport { EACH_SOURCE_HANDLE } from \"./flow-types.ts\";\nimport type { StepNode } from \"./flow-utils.ts\";\n\n/** How many `--w6w-loop-N` tokens `_tokens.scss` defines. */\nexport const LOOP_TONES = 6;\n\n/** FNV-1a over the id's UTF-16 code units — small, stable, no dependency. */\nfunction hashId(id: string): number {\n let h = 0x811c9dc5;\n for (let i = 0; i < id.length; i++) {\n h ^= id.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return h >>> 0;\n}\n\n/**\n * Tone index (1-based) per For each id. Ids are visited in sorted order so the result\n * does not depend on node order; each takes its hashed tone, or the next free one.\n */\nexport function assignLoopTones(foreachIds: Iterable<string>): Map<string, number> {\n const out = new Map<string, number>();\n let taken = new Set<number>();\n for (const id of [...new Set(foreachIds)].sort()) {\n if (taken.size === LOOP_TONES) taken = new Set();\n let tone = hashId(id) % LOOP_TONES;\n while (taken.has(tone)) tone = (tone + 1) % LOOP_TONES;\n taken.add(tone);\n out.set(id, tone + 1);\n }\n return out;\n}\n\n/** The CSS colour for a tone index. */\nexport function loopToneVar(tone: number): string {\n return `var(--w6w-loop-${tone})`;\n}\n\n/** The loops enclosing `id`, outermost first, following each For each's own `loopOf`. */\nexport function enclosingLoops(\n id: string,\n loopOfById: ReadonlyMap<string, string | undefined>,\n): string[] {\n const chain: string[] = [];\n const seen = new Set<string>([id]);\n for (let cur = loopOfById.get(id); cur && !seen.has(cur); cur = loopOfById.get(cur)) {\n seen.add(cur);\n chain.unshift(cur);\n }\n return chain;\n}\n\n/**\n * Paint each-lane edges with the colour of the loop they belong to: the For each itself\n * for its Each item link, else the loop the edge's source step runs in. Sets the\n * `--w6w-loop-color` custom property the `.w6w-edge-each` rule reads, so run-state\n * classes still compose over it. Same array when nothing needs painting.\n */\nexport function paintLoopEdges(\n edges: Edge[],\n tones: ReadonlyMap<string, number>,\n loopOfById: ReadonlyMap<string, string | undefined>,\n): Edge[] {\n if (tones.size === 0) return edges;\n return edges.map((e) => {\n if (e.data?.when !== \"each\") return e;\n const owner = e.sourceHandle === EACH_SOURCE_HANDLE ? e.source : loopOfById.get(e.source);\n const tone = owner ? tones.get(owner) : undefined;\n if (tone === undefined) return e;\n return { ...e, style: { ...e.style, \"--w6w-loop-color\": loopToneVar(tone) } as Edge[\"style\"] };\n });\n}\n\n/**\n * The colour custom property a card's root carries: a For each's own tone, read by its\n * Each item port. A loop-body step gets none — it looks exactly like a step outside a\n * loop; its dots are what mark it.\n */\nexport function loopCardStyle(\n id: string,\n tones: ReadonlyMap<string, number>,\n): CSSProperties | undefined {\n const own = tones.get(id);\n return own === undefined\n ? undefined\n : ({ \"--w6w-loop-color\": loopToneVar(own) } as CSSProperties);\n}\n\n/** What the canvas paints loops from: each For each's tone, and each step's own loop. */\nexport type LoopPaint = {\n tones: ReadonlyMap<string, number>;\n loopOf: ReadonlyMap<string, string | undefined>;\n};\n\n/**\n * A string that changes only when a loop's membership does — the memo key for\n * {@link loopPaint}, so dragging a node does not hand every card a new context value.\n */\nexport function loopPaintKey(nodes: readonly StepNode[]): string {\n const rows: [string, 0 | 1, string?][] = [];\n for (const n of nodes) {\n const foreach = isForeachStep(n.data.step);\n if (foreach || n.data.loopOf) rows.push([n.id, foreach ? 1 : 0, n.data.loopOf]);\n }\n return JSON.stringify(rows);\n}\n\n/** Rebuild the {@link LoopPaint} a {@link loopPaintKey} describes. */\nexport function loopPaint(key: string): LoopPaint {\n const rows = JSON.parse(key) as [string, 0 | 1, string?][];\n return {\n tones: assignLoopTones(rows.filter((r) => r[1] === 1).map((r) => r[0])),\n loopOf: new Map(rows.map((r) => [r[0], r[2]])),\n };\n}\n","// Per-node run flags the node toolbar toggles: PAUSE and DISABLE.\n//\n// - `disabled` is a definition field the engine reads (`Node.disabled` in @w6w/workflow-types):\n// the node is skipped in EVERY run, published and triggered included, and its outgoing edges\n// are skipped, so a node that depends only on it does not run either.\n// - `ui.paused` is editor metadata the engine never reads. Only a test run started from a node's\n// ▶ honours it: the editor sends every paused id as that run's `stopAt`, and the run stops\n// BEFORE each one (it does not execute). A published or triggered run never sees it.\n//\n// Both are written as `true` or left out — never `false`, never an empty `ui: {}` — so toggling a\n// flag on and off again leaves a definition byte-identical to the one it started from.\nimport type { FlowStep } from \"./flow-types.ts\";\n\nexport const PAUSED_LABEL = \"Paused — test runs stop before this node\";\nexport const DISABLED_LABEL = \"Disabled — skipped in every run\";\n\nexport function isPausedStep(step: FlowStep): boolean {\n return step.ui?.paused === true;\n}\n\nexport function isDisabledStep(step: FlowStep): boolean {\n return step.disabled === true;\n}\n\n/** `step` with `ui.paused` set (on) or removed (off); an emptied `ui` is dropped. */\nexport function withPaused(step: FlowStep, on: boolean): FlowStep {\n const { ui, ...rest } = step;\n const { paused: _paused, ...otherUi } = ui ?? {};\n const nextUi = on ? { ...otherUi, paused: true as const } : otherUi;\n return Object.keys(nextUi).length > 0 ? { ...rest, ui: nextUi } : rest;\n}\n\n/** `step` with `disabled: true` (on) or without the key (off). */\nexport function withDisabled(step: FlowStep, on: boolean): FlowStep {\n const { disabled: _disabled, ...rest } = step;\n return on ? { ...rest, disabled: true } : rest;\n}\n\n/**\n * The `stopAt` of a run started from `startId`'s ▶: every paused node except the start itself\n * (pressing ▶ on a paused node runs it — the pause stops runs that ARRIVE at it).\n */\nexport function pausedStopAt(steps: readonly FlowStep[], startId: string): string[] {\n return steps.filter((s) => s.id !== startId && isPausedStep(s)).map((s) => s.id);\n}\n","import { effectiveStateConfig, statePathsOverlap, staticWritePaths } from \"@w6w/expr\";\nimport type { Edge } from \"@xyflow/react\";\n/**\n * Pure loop-problem detectors and their one-click fixes (D-A2). Host-called:\n * the embed host runs `findLoopProblems` on the definition it hands the canvas\n * and passes the result as `stepProblems`; the editor renders the fix buttons\n * and calls `applyStepProblemFix` only from a click.\n *\n * Grammar: strings go through `parseRootAnchoredTemplate` / `serializeTemplate`\n * and path markers through `isDollarPath` — never a regex over raw text. Body\n * membership comes from `definitionLoops` alone (the one place that knows the\n * legacy-chain rule). Not flagged in v1: JSONLogic `$expr` `var` refs and `expr`\n * parts such as `{{ a || \"x\" }}`.\n */\nimport { parseRootAnchoredTemplate, serializeTemplate } from \"./components/expression-template.ts\";\nimport {\n type LoopRefusalReason,\n controlOwnedIds,\n definitionLoops,\n effectiveEdges,\n isEachLink,\n isForeachStep,\n loopMembership,\n loopRefusal,\n} from \"./flow-loop.ts\";\nimport {\n CONTROL_APP,\n type CanvasLane,\n type FlowStep,\n type FlowWorkflowInput,\n laneForSourceHandle,\n} from \"./flow-types.ts\";\nimport { type StepNode, normalizeInput } from \"./flow-utils.ts\";\nimport { isDollarPath } from \"./resolve-params.ts\";\nimport type { StepProblem, StepProblems } from \"./step-problems.ts\";\n\nconst ROOTS = [\"nodes\", \"steps\"] as const;\n\n/**\n * THE matcher: is `ref` a reference to foreach `foreachId`'s output, and what\n * does it become inside the loop. `R.F.output` → `foreach.item`, `R.F.output.<rest>`\n * → `foreach.item.<rest>`, `R.F.output[<rest>` → `foreach.item[<rest>`. Segment\n * boundary only: `…outputs` and `for_each_10` never match.\n */\nexport function loopOutputRef(ref: string, foreachId: string): string | null {\n for (const root of ROOTS) {\n const prefix = `${root}.${foreachId}.output`;\n if (!ref.startsWith(prefix)) continue;\n const rest = ref.slice(prefix.length);\n if (rest === \"\" || rest[0] === \".\" || rest[0] === \"[\") return `foreach.item${rest}`;\n }\n return null;\n}\n\n/**\n * Walk `v` depth-first (key order, then index order), rewriting every matching ref\n * and pushing each distinct matched ref string onto `refs`. Returns the SAME\n * reference when nothing matched (structure-shared otherwise). Never mutates.\n */\nfunction rewrite(v: unknown, foreachId: string, refs: string[]): unknown {\n if (typeof v === \"string\") {\n if (!v.includes(\"{{\")) return v;\n const parts = parseRootAnchoredTemplate(v);\n let hit = false;\n const next = parts.map((p) => {\n if (p.kind !== \"var\" || p.ref === undefined) return p;\n const to = loopOutputRef(p.ref, foreachId);\n if (to === null) return p;\n hit = true;\n if (!refs.includes(p.ref)) refs.push(p.ref);\n return { ...p, ref: to };\n });\n return hit ? serializeTemplate(next) : v;\n }\n if (isDollarPath(v)) {\n const path = v.$;\n if (typeof path !== \"string\") return v;\n const to = loopOutputRef(path, foreachId);\n if (to === null) return v;\n if (!refs.includes(path)) refs.push(path);\n return { $: to };\n }\n if (Array.isArray(v)) {\n let changed = false;\n const out = v.map((el) => {\n const n = rewrite(el, foreachId, refs);\n if (n !== el) changed = true;\n return n;\n });\n return changed ? out : v;\n }\n if (typeof v === \"object\" && v !== null) {\n let changed = false;\n const out: Record<string, unknown> = {};\n for (const [k, el] of Object.entries(v)) {\n const n = rewrite(el, foreachId, refs);\n if (n !== el) changed = true;\n out[k] = n;\n }\n return changed ? out : v;\n }\n return v;\n}\n\n/** A whole-value ref: a string that parses to exactly one `var` part, or `{ \"$\": string }`. */\nfunction isWholeRef(v: unknown): boolean {\n if (typeof v === \"string\") {\n if (!v.includes(\"{{\")) return false;\n const parts = parseRootAnchoredTemplate(v);\n return parts.length === 1 && parts[0].kind === \"var\";\n }\n return isDollarPath(v) && typeof v.$ === \"string\";\n}\n\n/** `items` is a list of exactly one whole-value ref — it loops once over a list of one list. */\nfunction isWrappedItems(items: unknown): items is unknown[] {\n return Array.isArray(items) && items.length === 1 && isWholeRef(items[0]);\n}\n\n/**\n * The loop problems of a stored definition, keyed by step id. Never throws and\n * never mutates: any input `workflowToFlow` would reject gives `{}` (it runs in a\n * host memo with no error boundary).\n */\nexport function findLoopProblems(input: FlowWorkflowInput): StepProblems {\n try {\n const wf = normalizeInput(input);\n if (!Array.isArray(wf.nodes)) return {};\n const out: StepProblems = {};\n const add = (id: string, p: StepProblem) => {\n const list = Object.hasOwn(out, id) ? out[id] : [];\n list.push(p);\n out[id] = list;\n };\n const byId = new Map(wf.nodes.map((s) => [s.id, s]));\n for (const [fid, loop] of Object.entries(definitionLoops(wf))) {\n const f = byId.get(fid);\n if (f && isWrappedItems(f.with?.items)) {\n add(fid, {\n code: \"foreach_wrapped_items\",\n fix: { kind: \"unwrap_items\", label: \"Unwrap Items\" },\n });\n }\n if (\"invalid\" in loop) {\n add(fid, { code: \"loop_body_invalid\", reason: { ...loop.invalid } });\n continue;\n }\n for (const id of loop.body) {\n const step = byId.get(id);\n if (!step?.with) continue;\n const refs: string[] = [];\n rewrite(step.with, fid, refs);\n if (refs.length > 0) {\n add(id, {\n code: \"foreach_body_refs_output\",\n foreachId: fid,\n refs,\n fix: { kind: \"use_current_item\", foreachId: fid, label: \"Use Current item\" },\n });\n }\n }\n }\n return out;\n } catch {\n return {};\n }\n}\n\n/** One editor-side parallel-write warning — the engine's `StateWriteWarning`, this code only. */\nexport interface StateParallelWrite {\n code: \"state_parallel_write\";\n nodes: string[];\n path: string[];\n}\n\n/** The ids inside one `@w6w/control` `parallel` branch (strings at any array depth). */\nfunction branchIds(branch: unknown): Set<string> {\n const out = new Set<string>();\n const collect = (v: unknown) => {\n if (typeof v === \"string\") out.add(v);\n else if (Array.isArray(v)) for (const el of v) collect(el);\n };\n collect(branch);\n return out;\n}\n\n/**\n * The editor mirror of the engine's plan-time parallel-write warning (R16, plan\n * §2.3; proven equal on `core/packages/expr/tests/fixtures/state-write-conflicts.json`).\n * Two writers are concurrent iff they sit in different branches of one\n * `@w6w/control` `parallel`; else never when they share an anchor (outermost\n * owning control, else the step) or one anchor reaches the other; else iff one\n * `fanOut: \"parallel\"` step has two distinct outgoing edges in the SAME lane\n * whose targets reach the two anchors. Each overlapping pair of static write\n * paths gives one warning on the shorter path; deduped, sorted by the engine's\n * order (`code`, then `nodes`, then `path`). Never throws (→ `[]`), never mutates.\n */\nexport function stateWriteConflicts(input: FlowWorkflowInput): StateParallelWrite[] {\n try {\n const wf = normalizeInput(input);\n if (!Array.isArray(wf.nodes)) return [];\n const steps = wf.nodes.filter(\n (s): s is FlowStep => typeof s === \"object\" && s !== null && typeof s.id === \"string\",\n );\n const edges = effectiveEdges({ ...wf, nodes: steps }).filter(\n (e) => typeof e?.from === \"string\" && typeof e?.to === \"string\",\n );\n\n // Writers and their static paths, in node order.\n const writers: Array<{ id: string; paths: string[][] }> = [];\n for (const s of steps) {\n try {\n const paths = staticWritePaths(effectiveStateConfig(s.uses?.app, s.uses?.action, s.state));\n if (paths.length > 0) writers.push({ id: s.id, paths });\n } catch {\n // An unreadable `state` writes nothing statically; the save route reports it.\n }\n }\n if (writers.length < 2) return [];\n\n // Owner (direct owning control) and anchor (outermost owning control, else self).\n const owner = new Map<string, string>();\n for (const s of steps) {\n for (const id of controlOwnedIds(s)) if (!owner.has(id)) owner.set(id, s.id);\n }\n const chain = (id: string): string[] => {\n const out = [id];\n let cur = id;\n while (owner.has(cur)) {\n cur = owner.get(cur) as string;\n if (out.includes(cur)) break;\n out.push(cur);\n }\n return out;\n };\n const anchor = (id: string): string => {\n const c = chain(id);\n return c[c.length - 1];\n };\n\n // Reachability over every edge (all lanes, each-links included), non-reflexive.\n const succ = new Map<string, string[]>();\n for (const e of edges) {\n const list = succ.get(e.from) ?? [];\n list.push(e.to);\n succ.set(e.from, list);\n }\n const reachCache = new Map<string, Set<string>>();\n const reach = (from: string): Set<string> => {\n const hit = reachCache.get(from);\n if (hit) return hit;\n const seen = new Set<string>();\n const stack = [...(succ.get(from) ?? [])];\n while (stack.length > 0) {\n const n = stack.pop() as string;\n if (seen.has(n)) continue;\n seen.add(n);\n for (const m of succ.get(n) ?? []) stack.push(m);\n }\n reachCache.set(from, seen);\n return seen;\n };\n const reachesRefl = (from: string, to: string) => from === to || reach(from).has(to);\n\n // (i) `@w6w/control` parallel branches.\n const parallels = steps\n .filter((s) => s.uses?.app === CONTROL_APP && s.uses.action === \"parallel\")\n .map((s) => {\n const branches = s.with?.branches;\n return Array.isArray(branches) ? branches.map(branchIds) : [];\n });\n const branchOf = (branches: Set<string>[], id: string): number => {\n for (const c of chain(id)) {\n const i = branches.findIndex((b) => b.has(c));\n if (i >= 0) return i;\n }\n return -1;\n };\n\n // (iv) fan-out points: per parallel step, its same-lane outgoing edge groups.\n const fanGroups: string[][] = [];\n for (const s of steps) {\n if (s.fanOut !== \"parallel\") continue;\n const lanes = new Map<string, string[]>();\n for (const e of edges) {\n if (e.from !== s.id || isEachLink(e)) continue;\n const lane = e.when ?? \"success\";\n const list = lanes.get(lane) ?? [];\n list.push(e.to);\n lanes.set(lane, list);\n }\n for (const targets of lanes.values()) if (targets.length >= 2) fanGroups.push(targets);\n }\n\n const concurrent = (a: string, b: string): boolean => {\n for (const branches of parallels) {\n const ia = branchOf(branches, a);\n const ib = branchOf(branches, b);\n if (ia >= 0 && ib >= 0 && ia !== ib) return true;\n }\n const aa = anchor(a);\n const ab = anchor(b);\n if (aa === ab || reach(aa).has(ab) || reach(ab).has(aa)) return false;\n return fanGroups.some((targets) =>\n targets.some((ta, i) =>\n targets.some((tb, j) => i !== j && reachesRefl(ta, aa) && reachesRefl(tb, ab)),\n ),\n );\n };\n\n const seen = new Set<string>();\n const out: StateParallelWrite[] = [];\n for (let i = 0; i < writers.length; i++) {\n for (let j = i + 1; j < writers.length; j++) {\n const A = writers[i];\n const B = writers[j];\n if (A.id === B.id || !concurrent(A.id, B.id)) continue;\n for (const pa of A.paths) {\n for (const pb of B.paths) {\n if (!statePathsOverlap(pa, pb)) continue;\n const w: StateParallelWrite = {\n code: \"state_parallel_write\",\n nodes: [A.id, B.id].sort(),\n path: [...(pa.length <= pb.length ? pa : pb)],\n };\n const key = JSON.stringify([w.nodes, w.path]);\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(w);\n }\n }\n }\n }\n const cmp = (x: string, y: string) => (x < y ? -1 : x > y ? 1 : 0);\n return out.sort(\n (x, y) =>\n cmp(x.code, y.code) ||\n cmp(x.nodes.join(\",\"), y.nodes.join(\",\")) ||\n cmp(x.path.join(\".\"), y.path.join(\".\")),\n );\n } catch {\n return [];\n }\n}\n\n/**\n * `stateWriteConflicts` as canvas problems: each warning lands on both of its\n * steps, naming the other one (`with`). Never throws (→ `{}`), never mutates.\n */\nexport function findStateWriteProblems(input: FlowWorkflowInput): StepProblems {\n try {\n const out: StepProblems = {};\n for (const w of stateWriteConflicts(input)) {\n for (const n of w.nodes) {\n const list = Object.hasOwn(out, n) ? out[n] : [];\n list.push({ code: w.code, path: [...w.path], with: w.nodes.filter((x) => x !== n) });\n out[n] = list;\n }\n }\n return out;\n } catch {\n return {};\n }\n}\n\n/**\n * Apply a problem's fix to `step`, returning a new step. Re-scans the step it is\n * given (never trusts the problem's `refs` snapshot); the SAME reference comes\n * back for a problem with no fix or nothing left to fix. Never mutates.\n */\nexport function applyStepProblemFix(step: FlowStep, problem: StepProblem): FlowStep {\n if (problem.code === \"foreach_wrapped_items\") {\n const items = step.with?.items;\n if (!step.with || !isWrappedItems(items)) return step;\n return { ...step, with: { ...step.with, items: items[0] } };\n }\n if (problem.code === \"foreach_body_refs_output\") {\n if (!step.with) return step;\n const next = rewrite(step.with, problem.foreachId, []);\n if (next === step.with) return step;\n return { ...step, with: next as Record<string, unknown> };\n }\n return step;\n}\n\n/**\n * The lane of a drag, read from the handle the pointer went down on. xyflow's\n * `connectionState.fromHandle` resolves an id-less handle (the Done port) to the\n * node's FIRST handle (`out-each`), so it cannot tell Done from Each item;\n * `onConnectStart` reports the real `handleId` (null for Done). Falls back to\n * `fromHandle.id` when no matching start was recorded.\n */\nexport function dragLane(\n start: { nodeId: string | null; handleId: string | null; handleType: string | null } | null,\n fromNodeId: string,\n fromHandle: { id?: string | null; type?: string } | null | undefined,\n): CanvasLane {\n if (start && start.nodeId === fromNodeId && start.handleType === (fromHandle?.type ?? \"source\")) {\n return laneForSourceHandle(start.handleId);\n }\n return laneForSourceHandle(fromHandle?.id);\n}\n\n/**\n * The loop reason a source-handle drag dropped ON an existing node is refused for\n * (`null` when the loop rule has nothing to say). `onConnectEnd` shows it as the\n * node-anchored notice instead of opening the step builder. The lane is promoted the\n * way `planConnect` does: a success drag from a body node extends the body.\n */\nexport function connectDropRefusal(\n source: string,\n target: string,\n lane: \"success\" | \"error\" | \"each\",\n nodes: StepNode[],\n edges: Edge[],\n): LoopRefusalReason | null {\n const srcStep = nodes.find((n) => n.id === source)?.data.step;\n const inBody = loopMembership(nodes, edges)[source] !== undefined;\n const effLane = lane === \"success\" && inBody ? \"each\" : lane;\n if (effLane === \"each\" && !inBody && !isForeachStep(srcStep)) return null;\n return loopRefusal(source, target, effLane, nodes, edges);\n}\n","// Pure \"Write to state\" decisions for the step settings control (`Node.state`,\n// core/rfcs/workflow.md). JSX-free. Path, key and limit rules live in `@w6w/expr`\n// (`validateStateConfig`, `effectiveStateConfig`) — never re-implemented here.\nimport { type StateWriteConfig, effectiveStateConfig } from \"@w6w/expr\";\nimport { type FlowStep, isControlApp } from \"./flow-types.ts\";\n\nexport type StateMode = StateWriteConfig[\"mode\"];\n\n/** The five modes, in the order the control lists them. */\nexport const STATE_MODES: readonly StateMode[] = [\"off\", \"root\", \"key\", \"pick\", \"append\"];\n\nexport const STATE_MODE_LABELS: Record<StateMode, string> = {\n off: \"Off\",\n root: \"Merge at root\",\n key: \"Under a key\",\n pick: \"Pick fields\",\n append: \"Append\",\n};\n\ntype StepLike = Pick<FlowStep, \"id\" | \"uses\" | \"state\">;\n\n/** What the step writes, the default applied (R14: Set data merges at root, every other step is Off). */\nexport function stateWriteFor(step: StepLike): StateWriteConfig {\n return effectiveStateConfig(step.uses.app, step.uses.action, step.state);\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\n/**\n * The step with `config` as its state write. The default is the key's ABSENCE\n * (Off on an ordinary step, Merge at root on Set data), so writing the default\n * removes `state`. Never mutates; every other key passes through.\n */\nexport function setStateWrite<S extends StepLike>(step: S, config: StateWriteConfig): S {\n const { state: _drop, ...rest } = step;\n const fallback = effectiveStateConfig(step.uses.app, step.uses.action, undefined);\n return (deepEqual(config, fallback) ? rest : { ...rest, state: config }) as S;\n}\n\n/** The config written when the author picks `mode`: named after the step so it is valid at once. */\nexport function seedStateWrite(step: Pick<FlowStep, \"id\">, mode: StateMode): StateWriteConfig {\n switch (mode) {\n case \"key\":\n return { mode: \"key\", key: step.id };\n case \"pick\":\n return { mode: \"pick\", map: [{ from: \"\", to: step.id }] };\n case \"append\":\n return { mode: \"append\", path: step.id };\n case \"root\":\n return { mode: \"root\" };\n default:\n return { mode: \"off\" };\n }\n}\n\n/** The control shows for app steps and triggers; every control-flow step (If, For each, Parallel, Race) hides it. */\nexport function stateWriteVisible(step: Pick<FlowStep, \"uses\">): boolean {\n return !isControlApp(step.uses.app);\n}\n","/**\n * Pure derivation of a live run's canvas visuals (T1.1.1) — step node styling\n * and main-graph edge taken/skipped/untouched state. Plain functions of (run\n * state, step/edge identity) → visual state, with **no React import**, so\n * `node --test` exercises them directly (A7) the same way `flow-connect.ts`'s\n * connection rules do.\n *\n * `RunStatus`/`StepStatus`/`RunState`/`StepExecution` below are thin LOCAL\n * copies of the shapes `@w6w/workflow-types` declares\n * (`packages/w6w-workflow/packages/types/mod.ts`) — the same house idiom\n * `components/HealthStatusPill.tsx`'s `HealthPillState` uses, and the same\n * design note `flow-types.ts`'s own header already states for\n * `FlowWorkflow`/`FlowStep`: `packages/ui/package.json` has no dependency on\n * `@w6w/workflow-types` and must not gain one, so this module stays a\n * pure-presentation leaf with no transport/spec coupling. A caller who\n * already has the real `RunState`/`StepExecution` is structurally compatible\n * for free.\n */\nimport { type CanvasLane, FOREACH_DONE_ROUTE } from \"./flow-types.ts\";\n\n/** Mirrors `RunStatus` in `@w6w/workflow-types`. */\nexport type RunStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"canceled\";\n/** Mirrors `StepStatus` in `@w6w/workflow-types`. */\nexport type StepStatus = \"pending\" | \"running\" | \"succeeded\" | \"failed\" | \"skipped\";\n\n/** The slice of `StepExecution` this module reads. */\nexport interface StepExecution {\n status: StepStatus;\n /** Why a `skipped` step did not run; `\"not_on_path\"` = never part of this run (no paint). */\n skipReason?: string;\n output?: unknown;\n /** For each only (I3): per-iteration body-step records, keyed by body-step id. */\n iterations?: ReadonlyArray<{ nodes?: Record<string, { status: StepStatus }> }>;\n}\n\n/** The slice of `RunState` this module reads — steps keyed by step id, same\n * as the engine's own `RunState.steps`. */\nexport interface RunState {\n status: RunStatus;\n /** Canonical per-node records (D2). */\n nodes?: Record<string, StepExecution>;\n /** Legacy alias of `nodes`; read as `nodes ?? steps` (un-upgraded server). */\n steps?: Record<string, StepExecution>;\n}\n\nfunction execOf(runState: RunState, id: string): StepExecution | undefined {\n return (runState.nodes ?? runState.steps)?.[id];\n}\n\n/** A step on another path — not downstream of the fired trigger, or outside a run-from-node\n * scope. It was never part of this run, so it and its edges get no run paint at all. */\nfunction offPath(runState: RunState, id: string): boolean {\n const rec = execOf(runState, id);\n return rec?.status === \"skipped\" && rec.skipReason === \"not_on_path\";\n}\n\nconst RUN_ENDED: ReadonlySet<RunStatus> = new Set([\"succeeded\", \"failed\", \"canceled\"]);\n\n/**\n * A step node's rendered state — exactly the five {@link StepStatus} values\n * plus `\"no-run\"` (A2): `runState` omitted ⇒ `\"no-run\"` (this canvas isn't\n * showing any run). A step present in `runState.steps` renders its own\n * recorded status; a step the run hasn't reached yet has no entry there at\n * all (only steps that were actually started/skipped get a `StepExecution` —\n * see the engine's `recordSkipped`), so absence reads as `\"pending\"`.\n */\nexport type StepVisualState = \"no-run\" | StepStatus;\n\n/**\n * The rendered state for step `stepId` under `runState` — the StepStatus\n * half of A3's RunStatus × StepStatus mapping. Pure function of the run's own\n * step records; no additional data needed (`GET /runs/:id` already returns\n * everything this reads). A step whose record says `skipReason: \"not_on_path\"` (or whose\n * enclosing loop's does) was never part of the run: `\"no-run\"`, the unpainted look.\n */\nexport function stepVisualState(\n runState: RunState | undefined,\n stepId: string,\n loops: readonly string[] = [],\n): StepVisualState {\n // `loops`: the For each steps enclosing `stepId` — a body step of a loop on another path is\n // off the path too.\n if (!runState || [...loops, stepId].some((id) => offPath(runState, id))) return \"no-run\";\n const own = execOf(runState, stepId);\n if (own) return own.status;\n // A For each body node has no record of its own (D-R1): derive from the owning\n // loop's iterations — failed > running > succeeded > skipped, else pending.\n const seen = new Set<StepStatus>();\n for (const rec of Object.values(runState.nodes ?? runState.steps ?? {})) {\n if (!Array.isArray(rec?.iterations)) continue;\n for (const it of rec.iterations) {\n const s = it?.nodes?.[stepId]?.status;\n if (s) seen.add(s);\n }\n }\n for (const s of [\"failed\", \"running\", \"succeeded\", \"skipped\"] as const) {\n if (seen.has(s)) return s;\n }\n return \"pending\";\n}\n\n/** One node's non-persisted, run-aware look. Colour is never the only signal\n * (the house rule `HealthStatusPill`'s own doc comment states) — every\n * non-default state also differs from the default (`\"no-run\"`) in\n * `borderStyle`, `borderWidth`, or `opacity`. */\nexport interface StepNodeVisual {\n borderColor: string;\n borderStyle: \"solid\" | \"dashed\";\n borderWidth: number;\n opacity: number;\n}\n\nconst NO_RUN_VISUAL: StepNodeVisual = {\n borderColor: \"var(--w6w-border)\",\n borderStyle: \"solid\",\n borderWidth: 1,\n opacity: 1,\n};\n\n/**\n * The node visual for a step's {@link StepVisualState}, `runStatus`\n * (the owning run's OWN status) additionally distinguishing the `\"pending\"`\n * case — A3: a `canceled`/`failed` run's not-yet-reached steps render\n * dimmer/muted (they never will run) than a `queued`/`running` run's\n * not-yet-reached steps (they still might), even though both share the same\n * `StepVisualState`. Every token used is one of the five named in\n * `context.notes` (`--w6w-accent`/`--w6w-success`/`--w6w-danger`/\n * `--w6w-muted`/`--w6w-border`) — never a literal hex, never a different\n * token family.\n */\nexport function stepNodeVisual(state: StepVisualState, runStatus?: RunStatus): StepNodeVisual {\n const runEnded = runStatus !== undefined && RUN_ENDED.has(runStatus);\n switch (state) {\n case \"no-run\":\n return NO_RUN_VISUAL;\n case \"pending\":\n return runEnded\n ? { borderColor: \"var(--w6w-muted)\", borderStyle: \"dashed\", borderWidth: 1, opacity: 0.5 }\n : { borderColor: \"var(--w6w-border)\", borderStyle: \"dashed\", borderWidth: 1, opacity: 1 };\n case \"running\":\n return { borderColor: \"var(--w6w-accent)\", borderStyle: \"solid\", borderWidth: 2, opacity: 1 };\n case \"succeeded\":\n return {\n borderColor: \"var(--w6w-success)\",\n borderStyle: \"solid\",\n borderWidth: 2,\n opacity: 1,\n };\n case \"failed\":\n return { borderColor: \"var(--w6w-danger)\", borderStyle: \"solid\", borderWidth: 2, opacity: 1 };\n case \"skipped\":\n return {\n borderColor: \"var(--w6w-muted)\",\n borderStyle: \"dashed\",\n borderWidth: 1,\n opacity: 0.7,\n };\n default:\n return NO_RUN_VISUAL;\n }\n}\n\n// ── Edge inference (main-graph `when` edges only — no `if`/then-else\n// sub-block inference: the canvas has no rendering or authoring path for\n// that construct today, see FOLLOWUPS.md) ───────────────────────────────\n\n/** Whether a main-graph edge was taken, skipped, or left untouched by the\n * run (`undefined` — the source step hasn't been decided yet, or there is\n * no run). */\nexport type EdgeRunState = \"taken\" | \"skipped\";\n\n/**\n * Whether the edge `from --(when)--> …` was taken or skipped in `runState` —\n * computable from the run's step records alone (no engine data beyond what\n * `GET /runs/:id` already returns):\n * - `from` **succeeded**: its `\"success\"`/omitted-`when` edges are taken,\n * its `\"error\"` edges are skipped.\n * - `from` **failed**: a declared `\"error\"` edge is taken, every other\n * outgoing edge (the `\"success\"` lane) is skipped.\n * - `from` was itself **skipped** (reached only through a skipped edge —\n * the engine's own `recordSkipped`/`markOutgoingEdgesSkipped`): every\n * outgoing edge is skipped too, regardless of lane — a step that never\n * ran cannot have taken an exit.\n * - `from` is **running**, or has no record at all (not yet reached): the\n * edge's fate isn't decided yet ⇒ `undefined`.\n */\nexport function edgeRunState(\n runState: RunState | undefined,\n from: string,\n when: CanvasLane | undefined,\n route?: string,\n to?: string,\n): EdgeRunState | undefined {\n if (!runState || offPath(runState, from) || (to !== undefined && offPath(runState, to))) {\n return undefined;\n }\n const state = edgeStateFromSource(runState, from, when, route);\n // An edge into a step that was skipped was not taken, whatever its source did (a For each\n // whose body hit Stop workflow still succeeded, but nothing on Done ran).\n if (state === \"taken\" && to !== undefined && execOf(runState, to)?.status === \"skipped\") {\n return \"skipped\";\n }\n return state;\n}\n\nfunction edgeStateFromSource(\n runState: RunState,\n from: string,\n when: CanvasLane | undefined,\n route?: string,\n): EdgeRunState | undefined {\n const exec = execOf(runState, from);\n if (!exec) return undefined;\n // Each lane: a body edge's fate is not decidable from the parent's record (body\n // ids are never `RunState.nodes` keys) — only a skipped parent skips it.\n if (when === \"each\") return exec.status === \"skipped\" ? \"skipped\" : undefined;\n const lane = when ?? \"success\";\n const output = exec.output;\n // A For each's Done route is its plain success exit (a Router's routes carry `route`).\n const done =\n route === FOREACH_DONE_ROUTE && !(output && typeof output === \"object\" && \"route\" in output);\n if (route !== undefined && !done && exec.status === \"succeeded\") {\n // An If's routed edge (its False port, or an explicit \"true\") follows `matched`.\n if (output && typeof output === \"object\" && \"matched\" in output) {\n return (route === \"false\") !== (output.matched === true) ? \"taken\" : \"skipped\";\n }\n return output && typeof output === \"object\" && \"route\" in output && output.route === route\n ? \"taken\"\n : \"skipped\";\n }\n if (exec.status === \"succeeded\") return lane === \"success\" ? \"taken\" : \"skipped\";\n if (exec.status === \"failed\") return lane === \"error\" ? \"taken\" : \"skipped\";\n if (exec.status === \"skipped\") return \"skipped\";\n return undefined;\n}\n","/**\n * The workflow STATE a node can read, merged at design time: what the reference picker's\n * \"State\" section lists and what the ƒx previews resolve `state.<path>` against — no run needed.\n *\n * The shape at an anchor node = the starting data (`Workflow.initialState`), then the keys the\n * workflow's `variables` seed, then every WRITER (a node whose effective \"Write to state\" is not\n * Off) on a path that reaches the anchor, folded in the engine's order: Kahn's topological sort,\n * ties by declared node order, edges in declared order (`w6w-workflow` `plan.ts`). The writes\n * themselves come from `@w6w/expr`'s `computeStateWrites` / `foldState` — the SAME merge the\n * engine runs, never a second one here.\n *\n * A writer's output is what the editor already knows about it, in the editor's own tier order:\n * the last test output (fresh, else persisted), else the declared output (as a skeleton via\n * {@link shapeToSkeleton}), else the app's `sample`. Each field is flagged `all` when every entry\n * path into the anchor sets it (or the starting data / variables do), `some` otherwise — two\n * triggers converging on one node can each write different fields.\n *\n * Pure and JSX-free so `node --test` exercises it directly. Imports `step-preview-state.ts`\n * (for `ancestorIds`); that module never imports this one.\n */\nimport {\n type StateTree,\n type StateWriteOp,\n computeStateWrites,\n effectiveStateConfig,\n foldState,\n} from \"@w6w/expr\";\nimport type { Edge } from \"@xyflow/react\";\nimport type { ExpressionStateField } from \"./components/ExpressionOptions.tsx\";\nimport { TRIGGER_APP, internalNodeDef } from \"./flow-types.ts\";\nimport type { FlowWorkflow } from \"./flow-types.ts\";\nimport type { StepNode } from \"./flow-utils.ts\";\nimport { type NodeShape, shapeToSkeleton } from \"./node-samples.ts\";\nimport { inferOutputFields, valueAtPath } from \"./output-shape.ts\";\nimport { type StepShapeContext, ancestorIds } from \"./step-preview-state.ts\";\nimport { asFieldDefs, fieldsToParams } from \"./trigger-fields.ts\";\n\n/** The merged state at one anchor node. */\nexport interface StateShape {\n /** Every field path of the merged tree (depth/count capped like a step's output fields). */\n fields: ExpressionStateField[];\n /**\n * Preview values keyed by the ref the picker inserts (`state.<path>`), from REAL values only\n * (test outputs, the app's `sample`, starting data, variable defaults) — never a skeleton.\n */\n sampleValues: Record<string, unknown>;\n}\n\nexport interface StateShapeInput {\n /** The node whose incoming state this is (`null` → empty shape). */\n anchorId: string | null | undefined;\n nodes: StepNode[];\n edges: Edge[];\n initialState?: FlowWorkflow[\"initialState\"];\n variables?: FlowWorkflow[\"variables\"];\n /** The same shape context the picker's \"Previous steps\" projection reads. */\n shapes?: StepShapeContext;\n /** Each node's REAL output (fresh test, else persisted), for preview values. */\n previewOutputs?: Record<string, unknown>;\n}\n\nconst EMPTY: StateShape = { fields: [], sampleValues: {} };\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/**\n * The engine's run order over `nodes`/`edges`: Kahn's, the ready queue seeded in declared node\n * order, successors released in declared edge order. Nodes a cycle leaves out follow in declared\n * order (the engine refuses such a plan; the editor still has to show something).\n */\nexport function stateWriteOrder(nodes: StepNode[], edges: Edge[]): string[] {\n const ids = nodes.map((n) => n.id);\n const known = new Set(ids);\n const indegree = new Map(ids.map((id) => [id, 0]));\n const outgoing = new Map<string, string[]>(ids.map((id) => [id, []]));\n for (const e of edges) {\n if (!known.has(e.source) || !known.has(e.target)) continue;\n outgoing.get(e.source)?.push(e.target);\n indegree.set(e.target, (indegree.get(e.target) ?? 0) + 1);\n }\n const order: string[] = [];\n const ready = ids.filter((id) => indegree.get(id) === 0);\n while (ready.length > 0) {\n const id = ready.shift() as string;\n order.push(id);\n for (const to of outgoing.get(id) ?? []) {\n const d = (indegree.get(to) ?? 0) - 1;\n indegree.set(to, d);\n if (d === 0) ready.push(to);\n }\n }\n const placed = new Set(order);\n for (const id of ids) if (!placed.has(id)) order.push(id);\n return order;\n}\n\nconst DECLARED_TYPES = new Set([\"string\", \"number\", \"boolean\", \"object\", \"array\"]);\n\n/**\n * A declared `output` (`[{ key, type?, items? }]`, or a built-in node's `[{ key }]`) as a\n * {@link NodeShape}. An untyped leaf is a `string`: a `null` skeleton would DELETE the key when a\n * later writer merges into it (`foldState`'s null rule), losing a field the author can read.\n */\nfunction declaredShape(output: unknown): NodeShape | undefined {\n if (!Array.isArray(output)) return undefined;\n const root: NodeShape = { type: \"object\", fields: {} };\n let any = false;\n for (const f of output) {\n if (!isPlainObject(f) || typeof f.key !== \"string\" || f.key === \"\") continue;\n const segs = f.key.split(\".\");\n let cur = root as { type: \"object\"; fields: Record<string, NodeShape> };\n for (const seg of segs.slice(0, -1)) {\n const next = cur.fields[seg];\n if (next?.type !== \"object\") cur.fields[seg] = { type: \"object\", fields: {} };\n cur = cur.fields[seg] as typeof cur;\n }\n const t = typeof f.type === \"string\" && DECLARED_TYPES.has(f.type) ? f.type : \"string\";\n let leaf: NodeShape;\n if (t === \"array\") {\n const items = declaredShape(f.items);\n leaf = items ? { type: \"array\", items } : { type: \"array\" };\n } else if (t === \"object\") {\n leaf = declaredShape(f.fields ?? f.properties) ?? { type: \"object\", fields: {} };\n } else {\n leaf = { type: t as \"string\" | \"number\" | \"boolean\" };\n }\n cur.fields[segs[segs.length - 1]] = leaf;\n any = true;\n }\n return any ? root : undefined;\n}\n\n/**\n * What one writer outputs, for the SHAPE: its test output (fresh, else persisted), else its\n * declared output as a skeleton, else the app's `sample`. `undefined` when nothing is known.\n */\nfunction writerShapeOutput(node: StepNode, shapes: StepShapeContext): unknown {\n const step = node.data.step;\n const tested = shapes.testOutputs?.[step.id] ?? shapes.persistedOutputs?.[step.id];\n if (tested !== undefined && tested !== null) return tested;\n const { app, action } = step.uses;\n if (app === TRIGGER_APP && internalNodeDef(app, action)?.group === \"trigger\") {\n const keys = fieldsToParams(asFieldDefs(step.with?.fields)).map((p) => ({ key: p.key }));\n return shapeToSkeleton(declaredShape(keys));\n }\n const internal = internalNodeDef(app, action)?.output;\n if (internal && internal.length > 0) return shapeToSkeleton(declaredShape(internal));\n const def =\n step.uses.trigger === true ? shapes.triggerDef?.(app, action) : shapes.actionDef?.(app, action);\n const declared = declaredShape(def?.output);\n if (declared) return shapeToSkeleton(declared);\n return def?.sample;\n}\n\n/** What one writer outputs, for PREVIEW values: a real value only (never a skeleton). */\nfunction writerPreviewOutput(node: StepNode, input: StateShapeInput): unknown {\n const step = node.data.step;\n const real = input.previewOutputs?.[step.id];\n if (real !== undefined && real !== null) return real;\n const { app, action } = step.uses;\n const def =\n step.uses.trigger === true\n ? input.shapes?.triggerDef?.(app, action)\n : input.shapes?.actionDef?.(app, action);\n return def?.sample;\n}\n\n/** A starting placeholder for a variable with no default, by its declared type. */\nfunction variablePlaceholder(type: string | undefined): unknown {\n switch (type) {\n case \"number\":\n case \"integer\":\n return 0;\n case \"boolean\":\n return false;\n case \"object\":\n return {};\n case \"array\":\n return [];\n default:\n return \"\";\n }\n}\n\n/** The tree the run starts from: starting data, then the workflow's variables (later wins). */\nfunction seedTree(input: StateShapeInput, real: boolean): StateTree {\n const tree: StateTree = isPlainObject(input.initialState) ? { ...input.initialState } : {};\n for (const v of input.variables ?? []) {\n if (!v || typeof v.key !== \"string\" || v.key === \"\") continue;\n if (v.default !== undefined) tree[v.key] = v.default;\n else if (!real) tree[v.key] = variablePlaceholder(v.type);\n }\n return tree;\n}\n\n/** The field paths of `tree`, capped like a step's output fields (`inferOutputFields`). */\nfunction fieldKeys(tree: unknown): string[] {\n return (inferOutputFields(tree) ?? []).map((f) => f.key);\n}\n\n/**\n * The merged state shape a node reads — see the file header. Empty (no fields) when nothing on\n * any path into `anchorId` writes state and there is no starting data or variable.\n */\nexport function computeStateShape(input: StateShapeInput): StateShape {\n const { anchorId, nodes, edges } = input;\n if (!anchorId) return EMPTY;\n const shapes = input.shapes ?? {};\n const ancestors = ancestorIds(anchorId, edges);\n ancestors.delete(anchorId);\n const byId = new Map(nodes.map((n) => [n.id, n]));\n\n const shapeOps: StateWriteOp[] = [];\n const previewOps: StateWriteOp[] = [];\n /** field path → the writers whose own writes produce it */\n const writersOf = new Map<string, Set<string>>();\n for (const id of stateWriteOrder(nodes, edges)) {\n if (!ancestors.has(id)) continue;\n const node = byId.get(id);\n if (!node) continue;\n const { app, action } = node.data.step.uses;\n const config = effectiveStateConfig(app, action, node.data.step.state);\n if (config.mode === \"off\") continue;\n const out = writerShapeOutput(node, shapes);\n if (out !== undefined) {\n const { ops } = computeStateWrites(config, out);\n shapeOps.push(...ops);\n for (const key of fieldKeys(foldState({}, ops))) {\n const set = writersOf.get(key) ?? new Set<string>();\n set.add(id);\n writersOf.set(key, set);\n }\n }\n const real = writerPreviewOutput(node, input);\n if (real !== undefined) previewOps.push(...computeStateWrites(config, real).ops);\n }\n\n const seed = seedTree(input, false);\n const tree = foldState(seed, shapeOps);\n const keys = fieldKeys(tree);\n if (keys.length === 0) return EMPTY;\n const seeded = new Set(fieldKeys(seed));\n\n // Entry nodes: ancestors with no parent among the ancestors. A field is on ALL paths when no\n // entry reaches the anchor without passing one of its writers.\n const parents = new Map<string, string[]>();\n const children = new Map<string, string[]>();\n for (const e of edges) {\n if (!ancestors.has(e.source)) continue;\n if (!ancestors.has(e.target) && e.target !== anchorId) continue;\n parents.set(e.target, [...(parents.get(e.target) ?? []), e.source]);\n children.set(e.source, [...(children.get(e.source) ?? []), e.target]);\n }\n const entries = [...ancestors].filter((id) => !(parents.get(id) ?? []).length);\n const onAllPaths = (writers: Set<string>): boolean => {\n const seen = new Set<string>();\n const stack = entries.filter((id) => !writers.has(id));\n while (stack.length > 0) {\n const id = stack.pop() as string;\n if (id === anchorId) return false;\n if (seen.has(id)) continue;\n seen.add(id);\n for (const c of children.get(id) ?? []) if (!writers.has(c)) stack.push(c);\n }\n return true;\n };\n\n const preview = foldState(seedTree(input, true), previewOps);\n const fields: ExpressionStateField[] = [];\n const sampleValues: Record<string, unknown> = {};\n for (const key of keys) {\n const writers = writersOf.get(key) ?? new Set<string>();\n const all = seeded.has(key) || (writers.size > 0 && onAllPaths(writers));\n fields.push({ key, path: true, paths: all ? \"all\" : \"some\" });\n const v = valueAtPath(preview, key);\n if (v !== undefined) sampleValues[`state.${key}`] = v;\n }\n return { fields, sampleValues };\n}\n","// Pure display decision for a trigger node's bound Subscription\n// (rfcs/trigger-protocol.md §Lifecycle \"Subscription states\", §Observability).\n// No DOM and no React so the node test runner covers it directly.\nimport type { SubscriptionStatus, SubscriptionSummary } from \"./types.ts\";\n\nexport type RegistrationTone = \"ok\" | \"pending\" | \"danger\" | \"muted\";\n\nexport interface RegistrationDisplay {\n label: string;\n tone: RegistrationTone;\n /** `lastError.message`, only for a failed subscription that carries one. */\n error: string | null;\n /** Always set: a distinct \"never fired\" text when `lastFireAt` is null/absent/unparseable. */\n lastFire: string;\n /** True iff the subscription is `failed` AND the host can retry. */\n retryVisible: boolean;\n}\n\nconst LABELS: Record<SubscriptionStatus, { label: string; tone: RegistrationTone }> = {\n registered: { label: \"Registered\", tone: \"ok\" },\n pending: { label: \"Registering\", tone: \"pending\" },\n failed: { label: \"Registration failed\", tone: \"danger\" },\n paused: { label: \"Paused\", tone: \"muted\" },\n destroying: { label: \"Removing\", tone: \"muted\" },\n};\n\nexport const NEVER_FIRED = \"Never fired\";\n\n/** UTC, minute precision, so the text is stable across locales and test hosts. */\nexport function formatLastFire(iso: string | null | undefined): string {\n if (!iso) return NEVER_FIRED;\n const t = new Date(iso);\n if (Number.isNaN(t.getTime())) return NEVER_FIRED;\n return `Last fired ${t.toISOString().slice(0, 16).replace(\"T\", \" \")} UTC`;\n}\n\n/** Null when the summary has no known status (older server): the node shows no badge. */\nexport function registrationDisplay(\n sub: SubscriptionSummary | undefined,\n canRetry: boolean,\n): RegistrationDisplay | null {\n if (!sub?.status) return null;\n const known = LABELS[sub.status];\n if (!known) return null;\n const failed = sub.status === \"failed\";\n return {\n label: known.label,\n tone: known.tone,\n error: failed ? (sub.lastError?.message ?? null) : null,\n lastFire: formatLastFire(sub.lastFireAt),\n retryVisible: failed && canRetry,\n };\n}\n\n/** nodeId -> subscription for the node-bound ones (a null `nodeId` is workflow-level). */\nexport function subscriptionsByNode(\n subs: readonly SubscriptionSummary[],\n): Map<string, SubscriptionSummary> {\n const m = new Map<string, SubscriptionSummary>();\n for (const s of subs) if (s.nodeId) m.set(s.nodeId, s);\n return m;\n}\n\n/**\n * The app trigger nodes of a workflow value. Total over a value that has no `nodes` yet\n * (embed mounts pass a partial value): an absent list is no trigger nodes.\n */\nexport function appTriggerNodesOf<N extends { uses?: { trigger?: boolean } }>(\n nodes: readonly N[] | null | undefined,\n): N[] {\n return (nodes ?? []).filter((n) => n.uses?.trigger === true);\n}\n","/**\n * The action definitions of every app a workflow's steps use, so the editor\n * can read each upstream step's declared output shape (`output-shape.ts`)\n * without running it.\n *\n * Fetched once per app id (`getAppActions`, i.e. `GET /apps/:id`) and kept for\n * the editor's lifetime. Keyed on the sorted SET of app ids rather than\n * `nodes`' identity — `nodes` is rebuilt on every drag and keystroke. Internal\n * `@w6w/*` apps are skipped: their shapes are static (`internalNodeDef`).\n * Best-effort per app: a failed fetch contributes nothing and never breaks\n * the picker.\n */\nimport { useEffect, useRef, useState } from \"react\";\nimport { type PortsLookup, isInternalApp } from \"./flow-types.ts\";\nimport type { StepNode } from \"./flow-utils.ts\";\nimport type { W6WApi } from \"./provider.tsx\";\nimport type { ActionDef, TriggerSummary } from \"./types.ts\";\n\nexport function useAppActionDefs(api: W6WApi, nodes: StepNode[]): Record<string, ActionDef[]> {\n const [defs, setDefs] = useState<Record<string, ActionDef[]>>({});\n // Apps already requested (loaded or in flight), so a re-run fetches only new ones.\n const requested = useRef(new Set<string>());\n const appIdsKey = JSON.stringify(\n [...new Set(nodes.map((n) => n.data.step.uses.app))]\n .filter((app) => app && !isInternalApp(app))\n .sort(),\n );\n useEffect(() => {\n const missing = (JSON.parse(appIdsKey) as string[]).filter(\n (app) => !requested.current.has(app),\n );\n if (missing.length === 0) return;\n for (const app of missing) requested.current.add(app);\n // Never canceled: an app's actions don't depend on which run of this effect\n // asked for them, so a result landing after a re-key is still right, and\n // dropping it would leave that app unloaded (it is already `requested`).\n Promise.all(\n missing.map(async (app) => {\n try {\n return [app, await api.getAppActions(app)] as const;\n } catch {\n requested.current.delete(app); // let a later change retry it\n return null;\n }\n }),\n ).then((res) => {\n const loaded = res.filter((r): r is readonly [string, ActionDef[]] => r !== null);\n if (loaded.length === 0) return;\n setDefs((prev) => ({ ...prev, ...Object.fromEntries(loaded) }));\n });\n }, [api, appIdsKey]);\n return defs;\n}\n\n/**\n * The trigger definitions of every app a workflow's APP-TRIGGER nodes (`uses.trigger === true`)\n * use, so the editor can offer `trigger.event.<field>` from a trigger's declared `output` /\n * `sample` without a run. Same shape as {@link useAppActionDefs}: fetched once per app id\n * (`getAppTriggers`, optional on the api — absent means no claim), keyed on the sorted set of\n * app ids, best-effort, a failed fetch retried by a later change.\n */\nexport function useAppTriggerDefs(\n api: W6WApi,\n nodes: StepNode[],\n): Record<string, TriggerSummary[]> {\n const [defs, setDefs] = useState<Record<string, TriggerSummary[]>>({});\n const requested = useRef(new Set<string>());\n const appIdsKey = JSON.stringify(\n [\n ...new Set(\n nodes.filter((n) => n.data.step.uses.trigger === true).map((n) => n.data.step.uses.app),\n ),\n ]\n .filter((app) => app && !isInternalApp(app))\n .sort(),\n );\n useEffect(() => {\n const load = api.getAppTriggers;\n if (typeof load !== \"function\") return;\n const missing = (JSON.parse(appIdsKey) as string[]).filter(\n (app) => !requested.current.has(app),\n );\n if (missing.length === 0) return;\n for (const app of missing) requested.current.add(app);\n Promise.all(\n missing.map(async (app) => {\n try {\n return [app, await load.call(api, app)] as const;\n } catch {\n requested.current.delete(app);\n return null;\n }\n }),\n ).then((res) => {\n const loaded = res.filter((r): r is readonly [string, TriggerSummary[]] => r !== null);\n if (loaded.length === 0) return;\n setDefs((prev) => ({ ...prev, ...Object.fromEntries(loaded) }));\n });\n }, [api, appIdsKey]);\n return defs;\n}\n\n/** Build a `PortsLookup` over the fetched catalog defs (`useAppActionDefs`' result). */\nexport function portsLookupFromDefs(defs: Record<string, ActionDef[]>): PortsLookup {\n return (app, action) => defs[app]?.find((d) => d.key === action)?.ports;\n}\n","import { type StateWriteConfig, validateStateConfig } from \"@w6w/expr\";\nimport {\n Background,\n type Connection,\n // Rendered as a `<Controls>` CHILD, which the library appends after its three\n // built-ins — so the auto-layout button lands in the same stack and inherits\n // T3.1.1's `--xy-*` → `--w6w-*` bridge with no chrome of its own.\n ConnectionLineType,\n ControlButton,\n Controls,\n type Edge,\n MiniMap,\n type NodeProps,\n NodeToolbar,\n Panel,\n Position,\n ReactFlow,\n ReactFlowProvider,\n // Type-only now: `addEdge` itself is called inside `flow-connect.ts`; this file\n // only borrows its parameter type for the `onConnect` handler.\n type addEdge,\n useEdgesState,\n useNodeId,\n useNodesState,\n useReactFlow,\n useUpdateNodeInternals,\n} from \"@xyflow/react\";\nimport type { FinalConnectionState } from \"@xyflow/react\";\nimport { Handle } from \"@xyflow/react\";\nimport {\n type CSSProperties,\n type ReactNode,\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport { AppPicker } from \"./AppPicker.tsx\";\nimport { CanvasContextMenu } from \"./CanvasContextMenu.tsx\";\nimport { CanvasLayer } from \"./CanvasLayer.tsx\";\nimport { ConditionEditor } from \"./ConditionEditor.tsx\";\nimport { JsonEditor } from \"./JsonEditor.tsx\";\nimport { NodeConfigForm } from \"./NodeConfigForm.tsx\";\nimport { ParamCustomization } from \"./ParamCustomization.tsx\";\nimport { ParamsForm } from \"./ParamsForm.tsx\";\nimport { PropertyEntryForm } from \"./PropertyEntryForm.tsx\";\nimport { RouterEditor } from \"./RouterEditor.tsx\";\nimport {\n AppTriggerTestNote,\n type BuiltStep,\n type ConfigView,\n ConfigViewToggle,\n StepBuilderModal,\n StepTestRun,\n type StepTestRunHandle,\n getTriggerDefs,\n requiredParamsFilled,\n} from \"./StepBuilderModal.tsx\";\nimport { StepNameEditor } from \"./StepNameEditor.tsx\";\nimport { StopEditor } from \"./StopEditor.tsx\";\nimport { TriggerFillForm } from \"./TriggerFillForm.tsx\";\nimport { WaitEditor } from \"./WaitEditor.tsx\";\nimport { pickWebhookSubscription } from \"./WebhookListenPanel.tsx\";\nimport {\n WorkflowConnectionPicker,\n WorkflowConnectionsContext,\n useWorkflowConnections,\n} from \"./WorkflowConnections.tsx\";\nimport {\n type CanvasMenuAction,\n type CanvasMenuTarget,\n canvasMenuItems,\n contextMenuTargets,\n} from \"./canvas-context-menu.ts\";\nimport type { FlowCanvas } from \"./canvas-types.ts\";\nimport {\n assignMembership,\n clampCanvas,\n persistCanvas,\n pruneSectionMembers,\n renameSectionMember,\n sectionsContaining,\n} from \"./canvas-utils.ts\";\nimport { AnchoredFlyout } from \"./components/AnchoredFlyout.tsx\";\nimport { AppIcon } from \"./components/AppIcon.tsx\";\nimport { Combobox } from \"./components/Combobox.tsx\";\nimport { ConfirmModal } from \"./components/ConfirmModal.tsx\";\nimport { Copyable } from \"./components/Copyable.tsx\";\nimport { DeleteButton } from \"./components/DeleteButton.tsx\";\nimport { EventbriteTriggerPicker } from \"./components/EventbriteTriggerPicker.tsx\";\nimport {\n type ExpressionLoopSource,\n type ExpressionOptions,\n ExpressionOptionsProvider,\n type ExpressionStepSource,\n excludeSelfStep,\n useExpressionOptions,\n} from \"./components/ExpressionOptions.tsx\";\nimport { Icon } from \"./components/Icon.tsx\";\nimport { IconButton } from \"./components/IconButton.tsx\";\nimport { InternalIcon } from \"./components/InternalIcon.tsx\";\nimport { Modal } from \"./components/Modal.tsx\";\nimport { ResolvedParams } from \"./components/ResolvedParams.tsx\";\nimport { ResultViewer } from \"./components/ResultViewer.tsx\";\nimport { ScriptBindingsNotice, useScriptConversion } from \"./components/ScriptBindingsNotice.tsx\";\nimport { eventbriteTriggerChoices } from \"./eventbrite-trigger-selection.ts\";\nimport {\n applyConnect,\n canConnect,\n connectConflict,\n connectRefusal,\n edgeLane,\n edgeWhenConflict,\n relaneRefusal,\n renameStepInEdges,\n setEdgeWhen,\n} from \"./flow-connect.ts\";\nimport {\n type FlowDeleteSelection,\n deleteFlowSelection,\n flowDeleteMessage,\n selectedFlowElements,\n} from \"./flow-delete.ts\";\n// The connection rules live in a JSX-free `.ts` module so `node --test` can run\n// them (see `flow-connect.ts`). This file is their only production caller.\nimport { fanOutLabel, fanOutState, setFanOut } from \"./flow-fanout.ts\";\nimport {\n FlowEditHistory,\n captureFlowEdit,\n isFlowTextTarget,\n restoreFlowEdit,\n} from \"./flow-history.ts\";\nimport { relayoutFlow } from \"./flow-layout.ts\";\nimport {\n type LoopPaint,\n enclosingLoops,\n loopCardStyle,\n loopPaint,\n loopPaintKey,\n loopToneVar,\n paintLoopEdges,\n} from \"./flow-loop-colors.ts\";\nimport { isForeachStep } from \"./flow-loop.ts\";\nimport { type LoopRefusalReason, loopRefusalMessage, stampLoopOf, stripBody } from \"./flow-loop.ts\";\nimport {\n DISABLED_LABEL,\n PAUSED_LABEL,\n isDisabledStep,\n isPausedStep,\n pausedStopAt,\n withDisabled,\n withPaused,\n} from \"./flow-node-flags.ts\";\nimport { applyStepProblemFix, connectDropRefusal, dragLane } from \"./flow-problems.ts\";\nimport {\n STATE_MODES,\n STATE_MODE_LABELS,\n type StateMode,\n seedStateWrite,\n setStateWrite,\n stateWriteFor,\n stateWriteVisible,\n} from \"./flow-state.ts\";\nimport {\n FOREACH_DONE_ROUTE,\n RACE_APP,\n RACE_DESCRIPTION,\n ROUTER_APP,\n ifPortLayout,\n isIfStep,\n routeFromHandle,\n routeHandle,\n routerPortLayout,\n routesForStep,\n} from \"./flow-types.ts\";\nimport {\n CALL_APP,\n CONTROL_APP,\n type CanvasLane,\n EACH_SOURCE_HANDLE,\n ERROR_SOURCE_HANDLE,\n type FlowStep,\n type FlowWorkflow,\n INTERNAL_NODES,\n type PortsLookup,\n SCRIPT_APP,\n WEBHOOK_APP,\n edgeVisuals,\n internalNodeDefaults,\n internalNodeIcon,\n internalNodeLabel,\n internalNodeParams,\n isControlApp,\n isInternalApp,\n isTriggerStep,\n laneForSourceHandle,\n nodePortsForStep,\n} from \"./flow-types.ts\";\nimport {\n type StepNode,\n findChainRoot,\n findChainTail,\n flowToWorkflow,\n idClashMessage,\n slugifyLabel,\n stepNameError,\n stepToJson,\n storedViewport,\n suggestStepId,\n withViewport,\n workflowToFlow,\n} from \"./flow-utils.ts\";\nimport {\n type NodeSample,\n indexNodeSamples,\n splitNodeOutputs,\n splitPreviewOutputs,\n} from \"./node-samples.ts\";\nimport { inferOutputFields, resolveOutputShape } from \"./output-shape.ts\";\nimport { hasParamCustomization } from \"./param-customization.ts\";\n// One implementation of the incoming-state pipeline, shared by every surface\n// that offers upstream seed chips (this file's step editor + ▶ Run collect\n// form, and StepBuilderModal's add-step Test tab) — see `step-preview-state.ts`'s\n// header comment for why this lives outside WorkflowFlowEditor.tsx.\nimport {\n type StepMeta,\n type StepStartState,\n type StepTest,\n WorkflowProjectProvider,\n useW6WApi,\n} from \"./provider.tsx\";\n// T1.1.1 — the pure run-visual derivation, no React import (`run-visuals.ts`'s\n// own header). This file is the one production caller that turns it into\n// pixels: a live-run repaint effect (in `Inner`) feeds the results into\n// `data`, and `StepNodeCard`/`ControlNodeCard` read them back off `data`.\nimport { type RunState, edgeRunState, stepNodeVisual, stepVisualState } from \"./run-visuals.ts\";\nimport { computeStateShape } from \"./state-shape.ts\";\nimport {\n type SeedSource,\n type StepShapeContext,\n declaredSamples,\n foreachTestFixture,\n foreachTestSample,\n loopItemText,\n nodeConfigSources,\n nodeConfigValues,\n nodeMetaSampleValues,\n nodeMetaValues,\n parseLoopSeed,\n resolveLoopItemsInState,\n startStateFromSeeds,\n stepBuilderLoop,\n stepBuilderUpstreamSteps,\n upstreamSampleValueSources,\n upstreamSampleValues,\n upstreamStateSources,\n} from \"./step-preview-state.ts\";\nimport {\n type StepProblem,\n type StepProblems,\n applyStepProblems,\n isConnectionBlocked,\n stepProblemTooltip,\n} from \"./step-problems.ts\";\nimport { useEffectiveTheme } from \"./theme.ts\";\nimport { asFieldDefs, fieldsToParams, seedValues } from \"./trigger-fields.ts\";\nimport {\n appTriggerNodesOf,\n registrationDisplay,\n subscriptionsByNode,\n} from \"./trigger-registration.ts\";\nimport type {\n ActionDef,\n ActionParam,\n AppSummary,\n ConnectionSummary,\n SubscriptionSummary,\n} from \"./types.ts\";\nimport { portsLookupFromDefs, useAppActionDefs, useAppTriggerDefs } from \"./use-app-action-defs.ts\";\nimport { useSeedSources } from \"./use-seed-sources.ts\";\nimport { LastUsedNote, useRememberedTestInput } from \"./use-test-input.tsx\";\nimport {\n type ConnectionResourceEdit,\n type FlowConnections,\n type WorkflowConnectionResources,\n centralizeConnections,\n connectionIdFor,\n defaultConnectionFor,\n editConnectionResources,\n selectNodeConnection,\n withConnectionRef,\n} from \"./workflow-connections.ts\";\n\n/**\n * What the \"Run on\" control does, shown on the lane panel (T1.1.1).\n *\n * An error edge is authored by DRAGGING from the step's error exit port (the\n * second, red-tinted source handle every step/control node renders below its\n * ordinary exit) — that's what stamps `sourceHandle`/`data.when` at creation\n * time (`onConnect` → `laneForSourceHandle`). This panel is not how an error\n * edge is first drawn; it is the RE-LANE affordance for an edge already drawn,\n * for when it was dragged from the wrong port. Each lane still holds one edge\n * out of an `out: 1` step, so switching an edge into a lane that's already\n * occupied re-points the incumbent (the deliberate single-slot UX).\n */\nconst LANE_HINT =\n \"Which outcome of the source node this edge carries. An error edge is drawn by dragging \" +\n \"from the node's error exit port; use this control to re-lane an edge already drawn. \" +\n \"An error edge overrides the node’s “On error” policy.\";\n\n/**\n * The step ids the refused edge id is minted from: the endpoints of the edge being\n * drawn/moved plus those of the edge already holding the id. {@link idClashMessage}\n * needs them to *determine* the cause instead of asserting one — the wording used to\n * blame a `:error` step id unconditionally, and a collision from an embedded `->`\n * therefore told the author to rename a step that did not exist (ADDENDUM Y).\n *\n * Both call sites look the sitting edge up by the id `connectConflict` /\n * `edgeWhenConflict` returned; a corrupt edge set with no such edge simply\n * contributes nothing, and the message falls back to naming no cause.\n */\nfunction clashInvolvedIds(\n edges: Edge[],\n conflictId: string,\n source: string | null | undefined,\n target: string | null | undefined,\n): (string | null | undefined)[] {\n const sitting = edges.find((e) => e.id === conflictId);\n return [source, target, sitting?.source, sitting?.target];\n}\n\n/** What kind of change an `onChange` reports — see `WorkflowFlowEditorProps.onChange`. */\nexport interface FlowChangeMeta {\n viewportOnly?: true;\n}\n\nexport interface WorkflowFlowEditorProps {\n /** Publishes the live connection manager to a host-owned rail. Edits share canvas undo/save. */\n onConnectionResourcesChange?: (resources: WorkflowConnectionResources | null) => void;\n /** The workflow being edited. The editor re-derives layout when this changes identity. */\n value: FlowWorkflow;\n /**\n * Fired whenever the user changes the graph — new nodes, edges, or step edits.\n *\n * `meta.viewportOnly` is `true` when the change is the author's pan/zoom being\n * written to `settings.viewport` and nothing else. A host that drops the shown\n * run on an edit (so the run paint stops describing a workflow that changed)\n * keeps it for these: moving the camera changes nothing that ran.\n */\n onChange: (next: FlowWorkflow, meta?: FlowChangeMeta) => void;\n /** Disable all interactions — pans/zooms are still enabled. */\n readOnly?: boolean;\n /** Height of the editor viewport. Defaults to 480px. */\n height?: string | number;\n /**\n * Registered apps, used to render each action node with its owning app's icon,\n * display name, and version. A step only carries `uses.app` (an id), so the\n * card joins that id against this list. Optional — unknown/absent apps degrade\n * to an initials tile with no version. Metadata is looked up at render time and\n * never stored on nodes, so it can't corrupt round-tripping back to a workflow.\n */\n apps?: AppSummary[];\n /**\n * EXTRA scope for each step field's expression picker, on top of whatever\n * this editor is already mounted under.\n *\n * Optional, and normally omitted: `ExpressionOptionsProvider` layers, so a\n * host that provides the project's vars/secrets/documents above this editor\n * (studio does, once, in its app shell) needs to pass nothing here. Use it\n * only to add or override something at this level.\n *\n * Names only — secret plaintext never reaches the client.\n */\n exprOptions?: ExpressionOptions;\n /**\n * The workflow's currently-selected project id. Threaded into ad-hoc\n * test-invokes so document expressions resolve against that project's docs\n * (not the scope's default/starter project). The host (studio) passes the\n * active project here; omitted → server default-project behavior. See T2.1.2 /\n * HITL-4(b): the invoke path's ambient scope is already project-aware.\n */\n project?: string;\n /**\n * The live run's per-step state, when the canvas is showing one (T1.1.1).\n * Omitted ⇒ the canvas renders exactly as it does today: every node in its\n * default look, every edge unstyled beyond its own `when` lane. This\n * editor does no fetching of its own — the host (`studio`) owns polling\n * `GET /runs/:id` and passes each successive result here, the same\n * \"host owns the query, editor is presentational\" split `apps`/`readOnly`\n * already establish for every other external data source.\n *\n * A structural subset of `RunState` in `@w6w/workflow-types` (mirrors this\n * file's own `FlowWorkflow`/`FlowStep` — see `flow-types.ts`'s header\n * note): `packages/ui` takes no dependency on the engine's types, so a\n * caller who already has the real `RunState` is compatible for free.\n *\n * Never persisted: {@link flowToWorkflow} never reads it — a run is not\n * part of the workflow that ran, and `data.stepStatus`/`data.runStatus`\n * (where this ends up on the canvas) are never among the fields it reads\n * back off a node.\n */\n runState?: RunState;\n /**\n * Host-detected per-step problems, keyed by step id — an app step whose bound\n * connection no longer exists gets an error ring + tooltip. Omitted ⇒ the\n * canvas renders exactly as today. The host owns detection; this editor never\n * infers a problem itself. Repaints live (same `value.id`) and is never\n * persisted: `flowToWorkflow` never reads `data.stepProblems`.\n */\n stepProblems?: StepProblems;\n /**\n * Fired the instant a step test starts — the ▶ collect form's Run button, or\n * `StepEditModal`'s footer Test button — before the invoke goes out, so a host\n * can drop whatever run its canvas was showing (T1.1.1) instead of leaving a\n * test to run underneath a stale run's highlighting.\n *\n * On the click, never on the result: only one of those two surfaces has a\n * completion to report at all, and the click is the one moment both share.\n */\n onTestRun?: () => void;\n /**\n * Re-frames the canvas when the host changes the space around it. When this\n * value changes after mount (compared with `Object.is`), the editor calls\n * `fitView({ duration: 300 })` once. It never fires on mount, and omitting it\n * or passing the same value again adds no fit.\n *\n * For a host whose page layout resizes the canvas without the graph changing,\n * e.g. a side panel docking beside it (pass the panel's open state). React Flow\n * keeps its pan/zoom transform when its pane narrows, so nodes near the edge\n * would otherwise end up behind the panel. The editor does not watch its own\n * size, so the host decides which layout changes deserve a re-frame.\n *\n * A fit replaces whatever camera is showing, including a saved viewport the\n * editor restored on open. The fit is not user-initiated, so it never emits\n * `onChange` and never overwrites the stored viewport.\n */\n fitViewKey?: string | number | boolean;\n /**\n * Run from a node: ▶ runs THAT node and then continues through every node downstream of it,\n * following the edges the way a real run does, and stops BEFORE each paused node\n * (`ui.paused`). The host enqueues it as a real run (`POST /workflows/:id/nodes/:nodeId/run`\n * with `continue: true`) and shows it like any run — `runState` + its run log.\n *\n * Called from the ▶ collect form's Run button with:\n * - `stopAt` — every paused node except the start node itself;\n * - `state` — the upstream outputs the form seeded (saved step tests / the last run), the same\n * start state a single-node run is given;\n * - `input` — the filled values, only when the start node is a trigger.\n *\n * Omitted ⇒ ▶ test-runs the single node exactly as before (and flow-control nodes have no ▶).\n * A rejected promise is shown in the run modal.\n */\n onRunFromNode?: (nodeId: string, req: RunFromNodeRequest) => Promise<void> | void;\n}\n\n/** What {@link WorkflowFlowEditorProps.onRunFromNode} is called with. */\nexport interface RunFromNodeRequest {\n /** Paused node ids the run must stop before (never the start node). */\n stopAt: string[];\n /** Upstream outputs seeded from saved step tests / the last run; absent when none. */\n state?: StepStartState;\n /** The trigger's filled values — present only when the start node is a trigger. */\n input?: Record<string, unknown>;\n}\n\n/**\n * App metadata by id, shared with the node cards so `StepNodeCard` can show the\n * app's icon/name/version without threading it through each node's `data`.\n */\nconst PortsLookupCtx = createContext<PortsLookup | undefined>(undefined);\n/** Per-step max outgoing edges in one lane (`fanOutState().count`); drives the card badge. */\nconst FanOutCountsCtx = createContext<ReadonlyMap<string, number>>(new Map());\n/** Each For each's tone and each step's loop, for the Each item port and the loop dots. */\nconst LoopPaintCtx = createContext<LoopPaint>({ tones: new Map(), loopOf: new Map() });\n\n/** The inline refusal when a source is already at its finite `out` cap (no eviction). */\nfunction outCapMessage(cap: number): string {\n return `Can’t draw that edge: this node allows at most ${cap} outgoing edge${cap === 1 ? \"\" : \"s\"} per lane.`;\n}\n\nconst AppsCtx = createContext<Map<string, AppSummary>>(new Map());\n\n/** The workflow's node-bound Subscriptions, read once per editor (not per card). */\ninterface TriggerRegistrationValue {\n byNode: ReadonlyMap<string, SubscriptionSummary>;\n /** The whole list — a webhook node's `nodes.<id>.meta.config.url` comes from it. */\n subs: readonly SubscriptionSummary[];\n /** Present only when the host can retry; re-reads the list after the retry. */\n retry?: (subscriptionId: string) => Promise<void>;\n}\nconst TriggerRegistrationCtx = createContext<TriggerRegistrationValue>({\n byNode: new Map(),\n subs: [],\n});\n\n/** `AppsCtx` plus the trigger-registration context (one provider, no extra nesting level). */\nfunction CardDataProvider({\n apps,\n registration,\n children,\n}: {\n apps: Map<string, AppSummary>;\n registration: TriggerRegistrationValue;\n children: ReactNode;\n}) {\n return (\n <AppsCtx.Provider value={apps}>\n <TriggerRegistrationCtx.Provider value={registration}>\n {children}\n </TriggerRegistrationCtx.Provider>\n </AppsCtx.Provider>\n );\n}\n\n/** Which view the step edit modal opens in: the tabbed form, raw JSON, or node settings. */\ntype EditView = \"props\" | \"json\" | \"settings\";\n\n/** Per-node control handlers, provided to the node cards via context. */\ninterface StepControls {\n /** Open the edit modal on the form view. */\n onEdit: (id: string) => void;\n /** Open the edit modal straight on the JSON view. */\n onEditJson: (id: string) => void;\n /** Test-run a single step and show its result. */\n onRun: (id: string) => void;\n onDuplicate: (id: string) => void;\n onDelete: (id: string) => void;\n /** Toggle `ui.paused` — test runs started from ▶ stop before a paused node. */\n onTogglePause: (id: string) => void;\n /** Toggle `disabled` — a disabled node is skipped in every run. */\n onToggleDisable: (id: string) => void;\n /** True when ▶ runs on from the node (`onRunFromNode`), so flow-control nodes get a ▶ too. */\n runsFromNode: boolean;\n /**\n * Open the step builder for a new step wired to this port — a plain click on the\n * port. Same path as dropping a dragged connection on empty canvas.\n */\n onAddFromPort: (id: string, handleType: \"source\" | \"target\", handleId?: string) => void;\n readOnly?: boolean;\n}\nconst StepControlsCtx = createContext<StepControls | null>(null);\n\n/**\n * Visual workflow editor. Renders a Workflow's DAG as a React Flow graph:\n *\n * - Auto-layouted on load (topological columns + sibling rows).\n * - Nodes render differently for action steps vs. control steps\n * (`uses.app === \"@w6w/control\"`).\n * - `+ Node` opens a guided builder (pick app → connection → action → params,\n * or a flow control). Drag nodes to reposition; connect handles to add edges.\n * - Selecting a node reveals a toolbar above it: Edit / Duplicate / Delete.\n * - Edit opens a modal with a Form ⇄ JSON toggle for that step.\n * - Every meaningful change fires `onChange` with an updated Workflow.\n * - Ctrl/Cmd+Z undoes graph edits; Ctrl/Cmd+Shift+Z (or Ctrl+Y) redoes them.\n * History is local to the open workflow and excludes tests, samples and viewport changes.\n */\nexport function WorkflowFlowEditor(props: WorkflowFlowEditorProps) {\n return (\n <ReactFlowProvider>\n <Inner {...props} />\n </ReactFlowProvider>\n );\n}\n\n/**\n * Live state of a single-step test run, shown in **one** modal that walks three\n * phases against this one state slot: `collect` (fill the step's properties),\n * `running`, then `done` / `error`. ▶ opens `collect` — it no longer invokes on\n * click, so a trigger's declared fields are filled before the run instead of the\n * run coming back `{}`.\n */\ninterface StepRunState {\n stepId: string;\n status: \"collect\" | \"running\" | \"done\" | \"error\";\n value?: unknown;\n /** Which app/version/action/connection the run used; absent when the host sent none. */\n meta?: StepMeta;\n error?: string;\n errorCode?: string;\n /** console.* output captured from a script node run, if any. */\n logs?: string[];\n}\n\nfunction nextCanvasId(prefix: string, taken: string[]) {\n let i = taken.length + 1;\n while (taken.includes(`${prefix}-${i}`)) i++;\n return `${prefix}-${i}`;\n}\nfunction nodeRect(n: StepNode) {\n return {\n x: n.position.x,\n y: n.position.y,\n w: n.measured?.width ?? n.width ?? 200,\n h: n.measured?.height ?? n.height ?? 64,\n };\n}\n\nfunction Inner({\n onConnectionResourcesChange,\n value,\n onChange,\n readOnly,\n height = 480,\n apps,\n exprOptions,\n project,\n runState,\n stepProblems,\n onTestRun,\n fitViewKey,\n onRunFromNode,\n}: WorkflowFlowEditorProps) {\n const api = useW6WApi();\n const appsById = useMemo(() => new Map((apps ?? []).map((a) => [a.id, a])), [apps]);\n const triggerRegistration = useTriggerRegistration(value);\n const [runResult, setRunResult] = useState<StepRunState | null>(null);\n // Re-hydrate nodes+edges only when the workflow id changes identity. Local\n // edits (drag, connect, delete) go through the useNodesState / useEdgesState\n // handles so React Flow's own state stays authoritative during interaction.\n // biome-ignore lint/correctness/useExhaustiveDependencies: re-derive layout only on workflow identity change\n const initialWorkflow = useMemo(() => centralizeConnections(value), [value.id]);\n const initial = useMemo(() => workflowToFlow(initialWorkflow), [initialWorkflow]);\n const [connections, setConnectionsState] = useState<FlowConnections>(\n initialWorkflow.connections ?? {},\n );\n const connectionsRef = useRef(connections);\n const setConnections = useCallback((next: FlowConnections) => {\n connectionsRef.current = next;\n setConnectionsState(next);\n }, []);\n const prepareStep = useCallback(\n (step: FlowStep) => {\n const next = centralizeConnections({ nodes: [step], connections: connectionsRef.current });\n if (next.connections !== connectionsRef.current) setConnections(next.connections);\n return next.nodes[0];\n },\n [setConnections],\n );\n // The camera to open at, read at mount for the same reason `initial` is: React\n // Flow consumes `defaultViewport` in a mount-only effect (ZoomPane's `XYPanZoom`\n // init), so a fresh object per render would be inert but misleading — and this\n // is what makes a save round-trip not yank the view back.\n // biome-ignore lint/correctness/useExhaustiveDependencies: read at mount only, like `initial`\n const savedViewport = useMemo(() => storedViewport(value), [value.id]);\n // Gates BOTH position writers below (the drag and the pan/zoom). ⚠️ Omitted ⇒\n // **true** (core rfcs/workflow.md · authoring-presentation amendment), so it is\n // read as `!== false` — never `?? false` and never `=== true`. Derived from\n // `value`, deliberately NOT a prop: the flag is a field of the workflow the\n // editor already receives, and a prop would be a second source of truth that\n // can disagree with the persisted document.\n const savePosition = value.settings?.savePosition !== false;\n const [nodes, setNodes, onNodesChange] = useNodesState<StepNode>(initial.nodes);\n // Catalog ports reach resolution through this lookup, never by stamping\n // `step.ports` (which would persist into every saved workflow).\n const actionDefs = useAppActionDefs(api, nodes);\n const triggerDefs = useAppTriggerDefs(api, nodes);\n const portsLookup = useMemo(() => portsLookupFromDefs(actionDefs), [actionDefs]);\n const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>(initial.edges);\n const [selectedId, setSelectedId] = useState<string | null>(null);\n // Notes + sections: live canvas state (geometry renders live; persistCanvas decides what is\n // written). Re-seeded only on workflow identity change, like nodes/edges.\n // biome-ignore lint/correctness/useExhaustiveDependencies: re-seed on workflow identity change only\n const initialCanvas = useMemo<FlowCanvas>(() => value.canvas ?? {}, [value.id]);\n const [canvas, setCanvas] = useState<FlowCanvas>(initialCanvas);\n const [editHistory] = useState(\n () =>\n new FlowEditHistory(\n captureFlowEdit(initialWorkflow, initial.nodes, initial.edges, connections, initialCanvas),\n ),\n );\n const textEditGroup = useRef<object>();\n const [restoreVersion, setRestoreVersion] = useState(0);\n // The draw-section tool, and the rectangle being dragged (client px) while it is armed.\n const [drawingSection, setDrawingSection] = useState(false);\n const [sectionDraft, setSectionDraft] = useState<{\n sx: number;\n sy: number;\n ex: number;\n ey: number;\n } | null>(null);\n const [pendingCanvasDelete, setPendingCanvasDelete] = useState<{\n kind: \"note\" | \"section\";\n id: string;\n } | null>(null);\n const [selectedEdgeId, setSelectedEdgeId] = useState<string | null>(null);\n const [builderOpen, setBuilderOpen] = useState(false);\n const builderEditGroup = useRef<object>({});\n useEffect(() => {\n // The progressive add form creates and configures one node as one undoable action.\n if (!builderOpen) builderEditGroup.current = {};\n }, [builderOpen]);\n const [editingId, setEditingId] = useState<string | null>(null);\n const [editView, setEditView] = useState<EditView>(\"props\");\n // The open right-click menu: where it sits in the editor box and what it acts on.\n // `edgeIds`: selected edges ride along with a selection-wide Delete, as with the Delete key.\n const [contextMenu, setContextMenu] = useState<\n (CanvasMenuTarget & { x: number; y: number; edgeIds: string[] }) | null\n >(null);\n // Where the step picker drops its node and which tab it opens on, when the right-click\n // menu opened it. Cleared whenever the picker closes, so \"+ Node\" keeps its cascade.\n const [builderPlace, setBuilderPlace] = useState<{\n position: { x: number; y: number };\n tab?: \"triggers\";\n } | null>(null);\n // Snapshot the entire selection awaiting confirmation; later selection changes cannot alter it.\n const [pendingDelete, setPendingDelete] = useState<FlowDeleteSelection | null>(null);\n // Set right after `setNodes(next)` in `performRelayout`, cleared by the\n // `[nodes, fitView]` effect below, which then calls `fitView()`. A ref (not\n // state) because it drives no render of its own — it only needs to survive\n // from the relayout click to the next commit of `nodes`.\n const relayoutPendingFitRef = useRef(false);\n // Carries the flow container so the capture-phase dblclick listener below\n // can be attached/removed on it directly — see that effect for why a native\n // listener is required instead of React Flow's own node-double-click prop.\n const flowContainerRef = useRef<HTMLElement>(null);\n // When a connection drag is released on empty canvas, we open the builder to\n // create a new node and auto-wire it to the handle it was dragged from.\n const [pendingConnect, setPendingConnect] = useState<{\n nodeId: string;\n handleType: \"source\" | \"target\";\n position: { x: number; y: number };\n /**\n * The lane the drag originated from, derived via {@link laneForSourceHandle}\n * at CAPTURE time in `onConnectEnd` (T1.1.1) — a target-handle drag reports a\n * handle id that is never `ERROR_SOURCE_HANDLE`, so this naturally reads\n * \"success\" for that gesture without a separate branch.\n */\n lane: CanvasLane;\n route?: string;\n } | null>(null);\n const { screenToFlowPosition, fitView } = useReactFlow();\n // React Flow's `colorMode` defaults to \"light\", so without this its chrome\n // (controls, minimap mask, handles, edge strokes, background dots) stays in the\n // light palette on a dark canvas. Read the mode from the house hook — the same\n // `data-theme` signal `styles.css` and AppIcon/CodeEditor/JsonEditor already\n // follow — rather than adding a prop the host would have to keep in sync.\n const colorMode = useEffectiveTheme();\n\n // If the caller swaps in a different workflow, reset local graph state.\n useEffect(() => {\n setNodes(initial.nodes);\n setEdges(initial.edges);\n setSelectedId(null);\n setSelectedEdgeId(null);\n setPendingDelete(null);\n setEditingId(null);\n setContextMenu(null);\n setCanvas(initialCanvas);\n setConnections(initialWorkflow.connections ?? {});\n editHistory.reset(\n captureFlowEdit(\n initialWorkflow,\n initial.nodes,\n initial.edges,\n initialWorkflow.connections ?? {},\n initialCanvas,\n ),\n );\n textEditGroup.current = undefined;\n }, [initial, initialCanvas, initialWorkflow, setNodes, setEdges, setConnections, editHistory]);\n\n // These two stamps are declared AFTER the workflow-swap reset above on purpose: effects run in\n // declaration order, so the reset (which reseeds nodes from `initial`, with neither stamp) would\n // otherwise overwrite a first-render `runState`/`stepProblems`. `initial` is a dep so they\n // re-stamp after a swap too.\n // T1.1.1 — live run-state repaint. `initial` above deliberately re-derives\n // nodes/edges ONLY on workflow identity change (Trap 1 — its own lint\n // suppression comment a few lines up says so), so a poll tick that\n // changes `runState` while `value.id` stays put would be invisible to the\n // cards if it went through `workflowToFlow` — that memo simply never fires\n // again. This effect instead patches the already-authoritative React Flow\n // state directly, the same mechanism a drag/connect/delete already uses to\n // update `nodes`/`edges` without re-deriving `initial`.\n //\n // Only new `data` keys are stamped — `stepStatus`/`runStatus` on nodes, a\n // run-aware `className`/`label` on edges. `data.step` and `data.when` (the\n // fields `flowToWorkflow` reads back to build the persisted document) are\n // never touched here, so nothing run-related can round-trip into a saved\n // workflow (A6).\n //\n // Functional `setNodes`/`setEdges` updaters read the PREVIOUS state\n // directly, so `nodes`/`edges` need not be dependencies — keeping this\n // effect keyed on `runState` is what keeps a plain drag or edit from repainting.\n // Workflow swaps and undo/redo also re-stamp the restored graph from the current run.\n // biome-ignore lint/correctness/useExhaustiveDependencies: `initial` and `restoreVersion` re-stamp a restored graph\n useEffect(() => {\n setNodes((nds) => {\n // A loop body step has no record of its own; one whose For each is on another path stays\n // unpainted with it (computed here, not read off `data.loopOf`, which may not be stamped yet).\n const loopOf = new Map(stampLoopOf(nds, edges).map((n) => [n.id, n.data.loopOf]));\n return nds.map((n) => {\n const stepStatus = stepVisualState(runState, n.id, enclosingLoops(n.id, loopOf));\n if (n.data.stepStatus === stepStatus && n.data.runStatus === runState?.status) return n;\n return { ...n, data: { ...n.data, stepStatus, runStatus: runState?.status } };\n });\n });\n setEdges((eds) =>\n eds.map((e) => {\n const lane = edgeLane(e);\n const run = edgeRunState(\n runState,\n e.source,\n lane,\n typeof e.data?.route === \"string\" ? e.data.route : undefined,\n e.target,\n );\n const visuals = edgeVisuals(lane, run);\n if (e.className === visuals.className && e.label === visuals.label) return e;\n return { ...e, className: visuals.className, label: visuals.label };\n }),\n );\n }, [runState, initial, restoreVersion, setNodes, setEdges]);\n // Host-supplied step problems — same live-repaint mechanism as runState above:\n // stamps/clears `data.stepProblems` only, never `data.step`.\n // biome-ignore lint/correctness/useExhaustiveDependencies: `initial` and `restoreVersion` re-stamp a restored graph\n useEffect(() => {\n setNodes((nds) => applyStepProblems(nds, stepProblems));\n }, [stepProblems, initial, restoreVersion, setNodes]);\n\n // Stamp the `canvas` key onto an outgoing workflow. Omitted entirely when there is nothing to\n // keep (no notes, no sections), so a workflow that never used the feature round-trips unchanged.\n const withCanvas = useCallback(\n (wf: FlowWorkflow, c: FlowCanvas): FlowWorkflow => {\n const { canvas: _drop, ...rest } = wf;\n if (!c.notes?.length && !c.sections?.length) return rest as FlowWorkflow;\n return { ...rest, canvas: persistCanvas(c, value.canvas, savePosition) };\n },\n [value.canvas, savePosition],\n );\n\n const emitChange = useCallback(\n (nextNodes: StepNode[], nextEdges: Edge[], canvasOverride?: FlowCanvas) => {\n editHistory.record(\n captureFlowEdit(\n value,\n nextNodes,\n nextEdges,\n connectionsRef.current,\n canvasOverride ?? canvas,\n ),\n builderOpen ? builderEditGroup.current : textEditGroup.current,\n );\n onChange(\n withCanvas(\n flowToWorkflow({ ...value, connections: connectionsRef.current }, nextNodes, nextEdges),\n canvasOverride ?? canvas,\n ),\n );\n },\n [value, onChange, canvas, withCanvas, editHistory, builderOpen],\n );\n\n const connectionResourceEditRef = useRef<(edit: ConnectionResourceEdit) => void>(() => {});\n connectionResourceEditRef.current = (edit) => {\n if (readOnly) return;\n const next = editConnectionResources(\n nodes.map((n) => n.data.step),\n connectionsRef.current,\n edit,\n );\n const nextNodes = nodes.map((n, i) => ({ ...n, data: { ...n.data, step: next.nodes[i] } }));\n setConnections(next.connections);\n setNodes(nextNodes);\n emitChange(nextNodes, edges);\n };\n const editResource = useCallback(\n (edit: ConnectionResourceEdit) => connectionResourceEditRef.current(edit),\n [],\n );\n const focusResourceNode = useCallback(\n (nodeId: string) => {\n setSelectedId(nodeId);\n setSelectedEdgeId(null);\n setNodes((current) => current.map((node) => ({ ...node, selected: node.id === nodeId })));\n setEdges((current) => current.map((edge) => ({ ...edge, selected: false })));\n void fitView({ nodes: [{ id: nodeId }], duration: 300, maxZoom: 1 });\n },\n [setNodes, setEdges, fitView],\n );\n const [highlightedResourceNode, highlightResourceNode] = useState<string | null>(null);\n const displayedNodes = useMemo(\n () =>\n highlightedResourceNode\n ? nodes.map((node) =>\n node.id === highlightedResourceNode\n ? { ...node, className: `${node.className ?? \"\"} w6w-connection-highlight`.trim() }\n : node,\n )\n : nodes,\n [nodes, highlightedResourceNode],\n );\n const resourceNodes = nodes.map((n) => ({ id: n.data.step.id, uses: n.data.step.uses }));\n const resourceKey = JSON.stringify(resourceNodes);\n const resourceAppsKey = JSON.stringify([...appsById]);\n // biome-ignore lint/correctness/useExhaustiveDependencies: graph geometry and run paint do not change the resource inventory.\n useEffect(() => {\n onConnectionResourcesChange?.({\n workflowId: value.id,\n nodes: resourceNodes,\n apps: appsById,\n connections,\n readOnly,\n edit: editResource,\n focusNode: focusResourceNode,\n highlightNode: highlightResourceNode,\n });\n }, [\n onConnectionResourcesChange,\n value.id,\n resourceKey,\n resourceAppsKey,\n connections,\n readOnly,\n editResource,\n focusResourceNode,\n ]);\n useEffect(() => () => onConnectionResourcesChange?.(null), [onConnectionResourcesChange]);\n\n // Live gate while dragging a connection — React Flow marks the drop invalid\n // (and won't fire onConnect) when this returns false.\n const isValidConnection = useCallback(\n (c: Connection | Edge) =>\n canConnect(c.source, c.target, nodes, edges, portsLookup, routeFromHandle(c.sourceHandle)),\n [nodes, edges, portsLookup],\n );\n\n // The typed reason a loop-breaking connection was refused, anchored to the node it\n // was drawn from (D-A6, D-B2). Its own channel — never the edge-lane panel, which\n // needs a selected edge. Cleared on the next successful connect and when the\n // selected node changes (guarded by `loopNoticeSelRef`: React Flow re-invokes\n // `onSelectionChange` after every render, so an unguarded clear would wipe the\n // notice before it paints).\n const [loopNotice, setLoopNotice] = useState<{\n nodeId: string;\n reason: LoopRefusalReason;\n } | null>(null);\n const loopNoticeSelRef = useRef<string | null>(null);\n // The handle a drag started on (see `dragLane`): xyflow's end-state handle is wrong for Done.\n const connectStartRef = useRef<{\n nodeId: string | null;\n handleId: string | null;\n handleType: string | null;\n } | null>(null);\n\n // Mark each loop-body step with its For each (`data.loopOf`) from the each-lane\n // edges. Its own effect, never folded into the runState / stepProblems ones, and\n // never touching `canvas` — the stamp is canvas-only and `flowToWorkflow` ignores it.\n useEffect(() => {\n setNodes((nds) => stampLoopOf(nds, edges));\n }, [edges, setNodes]);\n\n const onConnect = useCallback(\n (params: Parameters<typeof addEdge>[0]) => {\n if (readOnly) return;\n // The lane rides on the handle the wire was dragged from (T1.1.1) — the\n // one canonicalisation point, so a handle-to-handle drag and the\n // drag-to-empty-canvas gesture in `onConnectEnd` cannot disagree on what\n // counts as the error port. applyConnect only ever adds an edge: an input\n // takes any number, an exit at its finite cap refuses.\n const next = applyConnect(\n params.source,\n params.target,\n nodes,\n edges,\n laneForSourceHandle(params.sourceHandle),\n portsLookup,\n routeFromHandle(params.sourceHandle),\n );\n if (!next) {\n // FAIL LOUDLY when the refusal is one the drag could not have shown. Every\n // ordinary rule already ran in `isValidConnection` (React Flow marks the\n // drop invalid and never fires this handler), so the only refusal that\n // reaches here is a duplicate minted id — and that one is *invisible*:\n // React Flow's id-keyed store would have held ONE wire for two edges, which\n // reads as the editor losing the author's work.\n //\n // No new channel: `connectConflict` names the edge already holding the id,\n // and the refusal renders in the edge-lane panel's `role=\"alert\"` slot. The\n // clashing edge is SELECTED — in React Flow's own store, not just our mirror\n // state, so `onSelectionChange` (re-invoked on any re-render) confirms it\n // instead of wiping it before paint — which both reveals that panel and\n // highlights the wire the author has to rename.\n // A finite `out` cap is refused, never evicted: name the cap inline, on an\n // edge already leaving this source in this lane (the panel needs one selected).\n const lane = laneForSourceHandle(params.sourceHandle);\n const refusal = connectRefusal(\n params.source,\n params.target,\n nodes,\n edges,\n lane,\n portsLookup,\n routeFromHandle(params.sourceHandle),\n );\n if (refusal && refusal.refused === \"loop\") {\n setLoopNotice({ nodeId: params.source, reason: refusal.reason });\n return;\n }\n if (refusal) {\n const holder = edges.find((e) => e.source === params.source && edgeLane(e) === lane);\n if (holder) {\n setEdges(edges.map((e) => ({ ...e, selected: e.id === holder.id })));\n setSelectedEdgeId(holder.id);\n setLaneError({ edgeId: holder.id, message: outCapMessage(refusal.cap) });\n }\n return;\n }\n const conflict = connectConflict(\n params.source,\n params.target,\n nodes,\n edges,\n laneForSourceHandle(params.sourceHandle),\n );\n if (!conflict) return;\n setEdges(edges.map((e) => ({ ...e, selected: e.id === conflict })));\n setSelectedEdgeId(conflict);\n setLaneError({\n edgeId: conflict,\n message: idClashMessage(\n \"Can’t draw that edge\",\n conflict,\n clashInvolvedIds(edges, conflict, params.source, params.target),\n ),\n });\n return;\n }\n setLaneError(null);\n setLoopNotice(null);\n setEdges(next);\n emitChange(nodes, next);\n },\n [edges, nodes, setEdges, emitChange, readOnly, portsLookup],\n );\n\n // A connection dropped on empty canvas (no valid target) means \"add a new node\n // here and connect to it\" — open the builder and remember where it came from.\n const onConnectEnd = useCallback(\n (event: MouseEvent | TouchEvent, connectionState: FinalConnectionState) => {\n if (readOnly) return;\n // A valid drop onto a handle is already handled by onConnect.\n if (connectionState.isValid) return;\n const fromNode = connectionState.fromNode;\n if (!fromNode) return;\n const handleType = connectionState.fromHandle?.type === \"target\" ? \"target\" : \"source\";\n // A drop ON an existing node that the editor rejected is a refusal, never \"add a\n // new node here\": when the loop rule names why (e.g. the Done handle onto the\n // loop's own first step), show that reason anchored to the source and stop.\n const toNode = connectionState.toNode;\n if (toNode && handleType === \"source\") {\n const reason = connectDropRefusal(\n fromNode.id,\n toNode.id,\n dragLane(connectStartRef.current, fromNode.id, connectionState.fromHandle),\n nodes,\n edges,\n );\n if (reason) {\n setLoopNotice({ nodeId: fromNode.id, reason });\n return;\n }\n }\n // Only spawn if the origin handle can participate at all — a source handle\n // needs an exit port, a target handle an entry port. (A full single-slot\n // port is fine: the auto-wire below replaces its existing edge.)\n const originStep = nodes.find((n) => n.id === fromNode.id)?.data.step;\n if (originStep) {\n const p = nodePortsForStep(originStep, portsLookup);\n if ((handleType === \"source\" ? p.out : p.in) < 1) return;\n }\n const point = \"changedTouches\" in event ? event.changedTouches[0] : event;\n const position = screenToFlowPosition({ x: point.clientX, y: point.clientY });\n // The lane is derived HERE, not re-derived at `addBuiltStep` time\n // (T1.1.1): the dragged handle is only available on `connectionState`,\n // which does not survive past this callback — the step builder opens in\n // between. A target-handle drag reports a handle id that is never\n // `ERROR_SOURCE_HANDLE`, so this naturally reads \"success\" for that\n // gesture with no separate branch.\n setPendingConnect({\n nodeId: fromNode.id,\n handleType,\n position,\n lane: dragLane(connectStartRef.current, fromNode.id, connectionState.fromHandle),\n route: routeFromHandle(connectionState.fromHandle?.id),\n });\n setBuilderOpen(true);\n },\n [readOnly, screenToFlowPosition, nodes, edges, portsLookup],\n );\n\n // A plain click on a port: the same \"new step wired to this port\" as a drag\n // dropped on empty canvas, with no drop point — the new step is placed one\n // step-width out from the port's side of the node instead.\n const addFromPort = useCallback(\n (nodeId: string, handleType: \"source\" | \"target\", handleId?: string) => {\n if (readOnly) return;\n const n = nodes.find((x) => x.id === nodeId);\n if (!n) return;\n const r = nodeRect(n);\n const lane = laneForSourceHandle(handleId);\n const gap = 120;\n const position =\n handleType === \"target\"\n ? { x: r.x - r.w - gap, y: r.y }\n : lane === \"error\"\n ? { x: r.x, y: r.y + r.h + gap }\n : lane === \"each\"\n ? { x: r.x + r.w + gap, y: r.y - r.h - gap / 2 }\n : { x: r.x + r.w + gap, y: r.y };\n setPendingConnect({ nodeId, handleType, position, lane, route: routeFromHandle(handleId) });\n setBuilderOpen(true);\n },\n [readOnly, nodes],\n );\n\n // The node trash button requests one deletion; the canvas keydown handler requests\n // the full selection. Both use the same pending state and confirmation modal.\n // `performDeleteSelection` is invoked solely from the ConfirmModal's onConfirm.\n const deleteStep = useCallback(\n (id: string) => {\n if (readOnly) return;\n setPendingDelete({ nodeIds: [id], edgeIds: [] });\n },\n [readOnly],\n );\n\n const performDeleteSelection = useCallback(\n (selection: FlowDeleteSelection) => {\n if (readOnly) return;\n const next = deleteFlowSelection(selection, nodes, edges, canvas);\n setNodes(next.nodes);\n setEdges(next.edges);\n setCanvas(next.canvas);\n if (!next.nodes.some((n) => n.id === selectedId)) setSelectedId(null);\n if (!next.nodes.some((n) => n.id === editingId)) setEditingId(null);\n if (!next.edges.some((e) => e.id === selectedEdgeId)) setSelectedEdgeId(null);\n emitChange(next.nodes, next.edges, next.canvas);\n },\n [\n nodes,\n edges,\n canvas,\n setNodes,\n setEdges,\n emitChange,\n readOnly,\n selectedId,\n editingId,\n selectedEdgeId,\n ],\n );\n // ── Auto-layout (the fourth control button) ─────────────────────────────────\n //\n // Arrange the current paths and their section frames as one undoable edit.\n const performRelayout = useCallback(() => {\n if (readOnly) return;\n const next = relayoutFlow(nodes, edges, canvas);\n setNodes(next.nodes);\n setCanvas(next.canvas);\n relayoutPendingFitRef.current = true;\n emitChange(next.nodes, edges, next.canvas);\n }, [nodes, edges, canvas, setNodes, emitChange, readOnly]);\n\n // No confirmation (D-T2b): re-flowing is instant, deliberately with no\n // replacement gate — the intake is explicit this click should never warn. See\n // `.ai/conventions.md`'s \"No browser dialogs\" for the house pattern this is a\n // recorded exception to, not an oversight.\n const requestRelayout = useCallback(() => {\n if (readOnly) return;\n performRelayout();\n }, [readOnly, performRelayout]);\n\n // Frame the re-flowed graph once React Flow's own node-sync effect (a child of\n // this component) has committed the new positions — that child-before-parent\n // effect ordering is what makes `fitView()` here read POST-relayout bounds\n // instead of the stale pre-relayout ones. Keyed on `[nodes, fitView]` so it\n // re-checks the ref on every nodes commit, not just relayout's — `nodes`\n // itself is unread in the body, only its commit timing matters, so the\n // exhaustive-deps rule can't see why it's there.\n // biome-ignore lint/correctness/useExhaustiveDependencies: `nodes` drives ordering, not the body\n useEffect(() => {\n if (!relayoutPendingFitRef.current) return;\n relayoutPendingFitRef.current = false;\n void fitView({ duration: 300 });\n }, [nodes, fitView]);\n\n // `fitViewKey`: one fit per change of the host's key, never on mount. The ref\n // starts at the mount value, so the first run (and StrictMode's re-run) sees\n // no change; a new `fitView` identity alone fails the same check.\n const lastFitViewKeyRef = useRef(fitViewKey);\n useEffect(() => {\n if (Object.is(lastFitViewKeyRef.current, fitViewKey)) return;\n lastFitViewKeyRef.current = fitViewKey;\n void fitView({ duration: 300 });\n }, [fitViewKey, fitView]);\n\n // ── The edge-level lane control (`Run on: Success / Error`) ─────────────────\n // Reuses the selection state that already exists; nothing new is tracked but the\n // refusal message, which renders INLINE in the panel. Never a browser dialog —\n // same rule as the delete confirm above (.ai/conventions.md · No browser dialogs).\n // Scoped to the edge it is about, NOT cleared from `onSelectionChange`: React\n // Flow re-invokes that callback after any re-render (it is an inline lambda, so\n // it re-subscribes), which clears the message before it is ever painted — a\n // refusal that renders for zero frames is the same as failing silently.\n const [laneError, setLaneError] = useState<{ edgeId: string; message: string } | null>(null);\n const selectedEdge = useMemo(\n () => edges.find((e) => e.id === selectedEdgeId) ?? null,\n [edges, selectedEdgeId],\n );\n\n const setEdgeLane = useCallback(\n (when: \"success\" | \"error\") => {\n if (readOnly || !selectedEdgeId) return;\n const me = edges.find((e) => e.id === selectedEdgeId);\n if (!me) return;\n // Choosing the lane it is already on is a no-op — don't emit a change (which\n // would mark the host's workflow dirty for nothing). `setEdgeWhen` is\n // separately safe for this, so neither layer relies on the other.\n if (edgeLane(me) === when) return;\n const conflict = edgeWhenConflict(edges, selectedEdgeId, when, nodes);\n const refusal = relaneRefusal(edges, selectedEdgeId, when, nodes, portsLookup);\n const next =\n conflict || refusal ? null : setEdgeWhen(edges, selectedEdgeId, when, nodes, portsLookup);\n if (!next) {\n if (refusal) {\n setLaneError({ edgeId: selectedEdgeId, message: outCapMessage(refusal.cap) });\n return;\n }\n // FAIL LOUDLY. The alternative is minting a duplicate edge id, which React\n // Flow's id-keyed store silently collapses — one wire disappearing from the\n // canvas with no error, indistinguishable from the editor losing the work.\n setLaneError({\n edgeId: selectedEdgeId,\n message: conflict\n ? idClashMessage(\n \"Can’t switch this edge\",\n conflict,\n clashInvolvedIds(edges, conflict, me.source, me.target),\n )\n : \"This edge can’t be switched right now.\",\n });\n return;\n }\n setLaneError(null);\n setEdges(next);\n // The id encodes the lane, so re-laning re-mints it — move the selection (and\n // therefore this panel) onto the same wire under its new id.\n const relaned = next.find(\n (e) => e.source === me.source && e.target === me.target && edgeLane(e) === when,\n );\n setSelectedEdgeId(relaned?.id ?? null);\n emitChange(nodes, next);\n },\n [edges, nodes, setEdges, emitChange, readOnly, selectedEdgeId, portsLookup],\n );\n\n const deleteEdge = useCallback(\n (id: string) => {\n if (readOnly) return;\n const nextEdges = edges.filter((e) => e.id !== id);\n if (nextEdges.length === edges.length) return;\n setEdges(nextEdges);\n if (selectedEdgeId === id) setSelectedEdgeId(null);\n emitChange(nodes, nextEdges);\n },\n [nodes, edges, setEdges, emitChange, readOnly, selectedEdgeId],\n );\n\n // Each copy lands offset from its source and is selected; edges are not copied (the\n // node toolbar's Duplicate, applied to every id at once).\n const duplicateSteps = useCallback(\n (ids: readonly string[]) => {\n if (readOnly) return;\n const sources = ids\n .map((id) => nodes.find((n) => n.id === id))\n .filter((n): n is StepNode => n !== undefined);\n if (sources.length === 0) return;\n const taken = nodes.map((n) => n.id);\n const copies = sources.map((src): StepNode => {\n const newId = suggestStepId(taken, `${src.data.step.id}_copy`);\n taken.push(newId);\n const cloned: FlowStep = { ...stripBody(structuredClone(src.data.step)), id: newId };\n return {\n id: newId,\n type: src.type,\n position: { x: src.position.x + 40, y: src.position.y + 60 },\n data: { step: cloned, isInternal: src.data.isInternal },\n ...(sources.length > 1 ? { selected: true } : {}),\n };\n });\n const nextNodes = [\n ...(sources.length > 1\n ? nodes.map((n) => (n.selected ? { ...n, selected: false } : n))\n : nodes),\n ...copies,\n ];\n setNodes(nextNodes);\n setSelectedId(copies[0].id);\n emitChange(nextNodes, edges);\n },\n [nodes, edges, setNodes, emitChange, readOnly],\n );\n const duplicateStep = useCallback((id: string) => duplicateSteps([id]), [duplicateSteps]);\n\n const addBuiltStep = useCallback(\n (built: BuiltStep): string | undefined => {\n if (readOnly) return undefined;\n const isInternal = isInternalApp(built.uses.app);\n // Derived from the action itself (\"data_1\", \"render_template_1\"), not\n // a generic \"gate_1\"/\"step_1\" — human override, 2026-08-30: a reader\n // who never renames a step can still orient by its id.\n // `internalNodeLabel` falls back to the bare `action` key for a\n // non-internal (registry) app, since only internal nodes carry a\n // `label` this lookup can find.\n const taken = nodes.map((n) => n.id);\n // A name chosen in the add flow wins when it is valid; otherwise mint one.\n const id =\n built.id && !stepNameError(built.id, taken)\n ? built.id\n : suggestStepId(\n taken,\n slugifyLabel(internalNodeLabel(built.uses.app, built.uses.action)),\n );\n const step: FlowStep = prepareStep({\n id,\n uses: built.uses,\n ...(built.with && Object.keys(built.with).length > 0 ? { with: built.with } : {}),\n });\n const newNode: StepNode = {\n id,\n type: isInternal ? \"control\" : \"step\",\n // Drop point when spawned from a dragged connection or the right-click menu;\n // else a light cascade.\n position: pendingConnect?.position ??\n builderPlace?.position ?? { x: 80, y: 80 + nodes.length * 24 },\n data: { step, isInternal },\n };\n const nextNodes = [...nodes, newNode];\n\n // Auto-wire the edge back to the handle the drag started from. Dragging a\n // source handle points the edge at the new node; a target handle reverses it.\n // Gated per the port rules (applyConnect) against the new node; it only adds.\n let nextEdges = edges;\n // A loop-breaking auto-wire is never silent (D-B2): the step is added\n // unconnected only together with the typed notice, anchored to the source node.\n let loopRefused: { nodeId: string; reason: LoopRefusalReason } | null = null;\n const noteLoopRefusal = (\n source: string,\n target: string,\n lane: CanvasLane,\n anchor: string,\n ) => {\n const r = connectRefusal(source, target, nextNodes, edges, lane, portsLookup);\n if (r && r.refused === \"loop\") loopRefused = { nodeId: anchor, reason: r.reason };\n };\n if (pendingConnect) {\n const [source, target] =\n pendingConnect.handleType === \"target\"\n ? [id, pendingConnect.nodeId]\n : [pendingConnect.nodeId, id];\n // The lane captured at drag-release time (T1.1.1) — a step spawned by\n // dragging the error port onto empty canvas is wired error, one spawned\n // from the ordinary exit is wired success.\n const wired = applyConnect(\n source,\n target,\n nextNodes,\n edges,\n pendingConnect.lane,\n portsLookup,\n pendingConnect.route,\n );\n if (!wired) noteLoopRefusal(source, target, pendingConnect.lane, pendingConnect.nodeId);\n nextEdges = wired ?? edges;\n } else {\n // \"+ Node\" (no drag) — human override, 2026-08-30. A trigger\n // auto-wires to the CURRENT chain root, but ONLY when no trigger\n // exists yet anywhere in the graph; a second trigger is left\n // floating on purpose (nothing to sensibly guess — the author\n // decides if and where it feeds in). A non-trigger step prefers\n // wiring an existing UNCONNECTED trigger forward (the likely intent\n // right after adding one) over extending the current tail.\n const existingTrigger = nodes.find((n) => isTriggerStep(n.data.step.uses));\n if (isTriggerStep(built.uses)) {\n if (!existingTrigger) {\n const root = findChainRoot(nodes, edges);\n if (root) {\n const wired = applyConnect(id, root.id, nextNodes, edges, \"success\", portsLookup);\n if (!wired) noteLoopRefusal(id, root.id, \"success\", root.id);\n nextEdges = wired ?? edges;\n }\n }\n } else {\n const unconnectedTrigger =\n existingTrigger && !edges.some((e) => e.source === existingTrigger.id)\n ? existingTrigger\n : undefined;\n const from = unconnectedTrigger ?? findChainTail(nodes, edges);\n if (from) {\n const wired = applyConnect(from.id, id, nextNodes, edges, \"success\", portsLookup);\n if (!wired) noteLoopRefusal(from.id, id, \"success\", from.id);\n nextEdges = wired ?? edges;\n }\n }\n }\n\n setNodes(nextNodes);\n if (nextEdges !== edges) setEdges(nextEdges);\n setLoopNotice(loopRefused);\n setSelectedId(id);\n // Progressive commit (T4.1.1): the builder stays open past this first\n // commit to keep taking edits via `onDraftChange`, so closing is\n // exclusively `onClose`'s job now (wired at the render site below).\n emitChange(nextNodes, nextEdges);\n return id;\n },\n [\n nodes,\n edges,\n setNodes,\n setEdges,\n emitChange,\n readOnly,\n pendingConnect,\n builderPlace,\n portsLookup,\n prepareStep,\n ],\n );\n\n // Apply an edit to a step, rewiring edges if its id changed.\n const updateStep = useCallback(\n (prevId: string, draft: FlowStep) => {\n let next = draft;\n const previous = nodes.find((n) => n.id === prevId)?.data.step;\n // The progressive add form still emits inline account IDs. Reuse its private\n // binding on later field edits, and detach once if it was sharing a binding.\n if (\n draft.uses.connection &&\n !draft.uses.connectionRef &&\n previous?.uses.connectionRef &&\n previous.uses.app === draft.uses.app\n ) {\n const selected = selectNodeConnection(\n withConnectionRef(draft, previous.uses.connectionRef),\n draft.uses.connection,\n nodes.map((n) => n.data.step),\n connectionsRef.current,\n );\n setConnections(selected.connections);\n next = selected.step;\n } else next = prepareStep(draft);\n const idChanged = next.id !== prevId;\n if (idChanged && nodes.some((n) => n.id === next.id)) return; // reject dup id\n const nextNodes = nodes.map((n) =>\n n.id === prevId\n ? {\n ...n,\n id: next.id,\n data: { step: next, isInternal: isInternalApp(next.uses.app) },\n }\n : n,\n );\n if (idChanged) {\n // Re-point the endpoints AND re-mint each id in the edge's own lane. This\n // used to rebuild every id unqualified, dropping an error edge's `:error`\n // suffix so a same-target success+error pair collapsed into one edge in\n // React Flow's id-keyed store. The lane-aware rewrite lives in\n // `flow-connect.ts` and mints ids through the one shared `flowEdgeId`\n // helper — never a second copy of the template.\n const nextEdges = renameStepInEdges(edges, prevId, next.id);\n const nextCanvas = renameSectionMember(canvas, prevId, next.id);\n setNodes(nextNodes);\n setEdges(nextEdges);\n setCanvas(nextCanvas);\n if (selectedId === prevId) setSelectedId(next.id);\n if (editingId === prevId) setEditingId(next.id);\n emitChange(nextNodes, nextEdges, nextCanvas);\n return;\n }\n setNodes(nextNodes);\n const routeIds = new Set(routesForStep(next).map((r) => r.id));\n const nextEdges = edges.filter(\n (e) =>\n e.source !== next.id || e.data?.route === undefined || routeIds.has(String(e.data.route)),\n );\n if (nextEdges.length !== edges.length) setEdges(nextEdges);\n emitChange(nextNodes, nextEdges);\n },\n [\n nodes,\n edges,\n canvas,\n setNodes,\n setEdges,\n selectedId,\n editingId,\n emitChange,\n prepareStep,\n setConnections,\n ],\n );\n\n // ── Notes & sections ────────────────────────────────────────────────────────\n const onCanvasChange = useCallback(\n (next: FlowCanvas) => {\n if (readOnly) return;\n setCanvas(next);\n emitChange(nodes, edges, next);\n },\n [readOnly, nodes, edges, emitChange],\n );\n\n const addNote = useCallback(() => {\n if (readOnly) return;\n const box = flowContainerRef.current?.getBoundingClientRect();\n const at = box\n ? screenToFlowPosition({ x: box.left + box.width / 2, y: box.top + box.height / 2 })\n : { x: 0, y: 0 };\n const notes = canvas.notes ?? [];\n const note = {\n id: nextCanvasId(\n \"note\",\n notes.map((n) => n.id),\n ),\n color: \"#facc15\",\n position: { x: Math.round(at.x - 100), y: Math.round(at.y - 60) },\n size: { width: 200, height: 120 },\n content: \"\",\n };\n onCanvasChange(clampCanvas({ ...canvas, notes: [...notes, note] }));\n }, [readOnly, canvas, screenToFlowPosition, onCanvasChange]);\n\n // \"Draw section\" tool: the author drags a rectangle anywhere on the canvas (corners in flow\n // units). The frame owns the nodes whose centre falls inside it — the same rule a node drag\n // uses — so dragging the section carries them. A click without a drag drops a default frame.\n const addSectionAt = useCallback(\n (a: { x: number; y: number }, b: { x: number; y: number } | null) => {\n if (readOnly) return;\n const x0 = b ? Math.min(a.x, b.x) : a.x;\n const y0 = b ? Math.min(a.y, b.y) : a.y;\n const w = b ? Math.abs(b.x - a.x) : 360;\n const h = b ? Math.abs(b.y - a.y) : 240;\n const members = nodes\n .filter((n) => {\n const r = nodeRect(n);\n const cx = r.x + r.w / 2;\n const cy = r.y + r.h / 2;\n return cx >= x0 && cx <= x0 + w && cy >= y0 && cy <= y0 + h;\n })\n .map((n) => n.id);\n const sections = canvas.sections ?? [];\n const id = nextCanvasId(\n \"section\",\n sections.map((x) => x.id),\n );\n const section = {\n id,\n title: \"Section\",\n color: \"#6366f1\",\n position: { x: Math.round(x0), y: Math.round(y0) },\n size: { width: Math.round(w), height: Math.round(h) },\n nodes: [] as string[],\n };\n const withNew = { ...canvas, sections: [...sections, section] };\n onCanvasChange(clampCanvas(assignMembership(withNew, id, members)));\n },\n [readOnly, nodes, canvas, onCanvasChange],\n );\n\n // Esc leaves the draw-section tool without drawing.\n useEffect(() => {\n if (!drawingSection) return;\n const onKey = (e: KeyboardEvent) => {\n if (e.key !== \"Escape\") return;\n setDrawingSection(false);\n setSectionDraft(null);\n };\n window.addEventListener(\"keydown\", onKey);\n return () => window.removeEventListener(\"keydown\", onKey);\n }, [drawingSection]);\n\n // Dropping a section moves its members by the same delta: ONE emission, on drop.\n const onSectionDrop = useCallback(\n (id: string, d: { dx: number; dy: number }) => {\n if (readOnly) return;\n const sec = canvas.sections?.find((x) => x.id === id);\n if (!sec) return;\n const members = new Set(sec.nodes);\n const nextNodes = nodes.map((n) =>\n members.has(n.id)\n ? { ...n, position: { x: n.position.x + d.dx, y: n.position.y + d.dy } }\n : n,\n );\n const nextCanvas: FlowCanvas = {\n ...canvas,\n sections: (canvas.sections ?? []).map((x) =>\n x.id === id ? { ...x, position: { x: x.position.x + d.dx, y: x.position.y + d.dy } } : x,\n ),\n };\n setNodes(nextNodes);\n setCanvas(nextCanvas);\n emitChange(nextNodes, edges, nextCanvas);\n },\n [readOnly, canvas, nodes, edges, setNodes, emitChange],\n );\n\n const performCanvasDelete = useCallback(\n (kind: \"note\" | \"section\", id: string) => {\n if (readOnly) return;\n // Deleting a section deletes the frame, never its nodes.\n const next: FlowCanvas =\n kind === \"note\"\n ? { ...canvas, notes: (canvas.notes ?? []).filter((n) => n.id !== id) }\n : { ...canvas, sections: (canvas.sections ?? []).filter((x) => x.id !== id) };\n onCanvasChange(next);\n },\n [readOnly, canvas, onCanvasChange],\n );\n\n // After a node drag: membership follows the node CENTRE (inside a section ⇒ joins it,\n // leaving any other; outside every section ⇒ leaves). Returns the canvas to emit.\n const membershipAfterDrag = (dragged: StepNode[]): FlowCanvas => {\n let next = canvas;\n for (const d of dragged) {\n const r = nodeRect(d);\n const cx = r.x + r.w / 2;\n const cy = r.y + r.h / 2;\n const target = (next.sections ?? []).find(\n (sec) =>\n cx >= sec.position.x &&\n cx <= sec.position.x + sec.size.width &&\n cy >= sec.position.y &&\n cy <= sec.position.y + sec.size.height,\n );\n const current = sectionsContaining(next, d.id);\n if (target) {\n if (current.length !== 1 || current[0] !== target.id) {\n next = assignMembership(next, target.id, [d.id]);\n }\n } else if (current.length > 0) {\n next = pruneSectionMembers(next, d.id);\n }\n }\n return next;\n };\n\n // Remember the values a Run was made with, then record the run AGAINST that\n // fixture — the same two-call sequence the Test path uses (`StepTestRun` in\n // StepBuilderModal), so a Run and a Test write the same kind of `step_tests`\n // row for the same step and each surface pre-fills from whichever ran last.\n //\n // The `stepTestId` is the load-bearing half: `recordStepTestRun` only updates\n // the fixture's `last_run_*` columns when it is present, and this call used to\n // post without one — so a canvas run was logged but never written back onto\n // the fixture. Best-effort throughout: a persist failure is logged and never\n // surfaces as a failed run.\n //\n // The two calls fail INDEPENDENTLY, and deliberately so: remembering the\n // values and recording that the run happened are different obligations, and\n // only the first can fail on its own (`POST …/tests` 404s on an unknown\n // workflow, `POST …/test-runs` does not). Folding both into one `try` would\n // make a fixture-save failure swallow the run's `step_test_runs` row *and* the\n // `run_log` ledger row the server writes per POST — i.e. silently lose run\n // history over a persistence hiccup. So a failed save degrades to\n // `stepTestId: null`: a run recorded with no fixture attached, which is\n // exactly what the route already accepts (step-test-runs.ts).\n const persistStepRun = useCallback(\n (\n stepId: string,\n fixture: { input: Record<string, unknown>; with: Record<string, unknown> },\n outcome: { status: string; output?: unknown; error?: unknown; meta?: StepMeta },\n ) => {\n void (async () => {\n const saved = await api.saveStepTest(value.id, stepId, fixture).catch((err) => {\n console.error(\"step run fixture save failed\", err);\n return null;\n });\n await api.recordStepTestRun(value.id, stepId, {\n stepTestId: saved?.id ?? null,\n status: outcome.status,\n input: fixture.input,\n output: outcome.output,\n error: outcome.error,\n ...(outcome.meta ? { meta: outcome.meta } : {}),\n });\n })().catch((err) => {\n console.error(\"step run persist failed\", err);\n });\n },\n [api, value.id],\n );\n\n // Test-running one step is two-phase, mirroring delete's request/perform split:\n // `runStep` (the ▶ control) only *opens* the collect phase, and\n // `performRunStep` — reached solely from the collect form's Run button — does\n // the invoke with the values the user just filled in. Control steps aren't\n // invocable. Signature is unchanged: `onRun` is still `(id: string) => void`.\n const runStep = useCallback(\n (id: string) => {\n const node = nodes.find((n) => n.id === id);\n // Flow-control nodes can't run standalone; app + compute/trigger nodes can. A run that\n // continues downstream is a real run, so it can start at a flow-control node too.\n if (!node || (!onRunFromNode && isControlApp(node.data.step.uses.app))) return;\n setRunResult({ stepId: id, status: \"collect\" });\n },\n [nodes, onRunFromNode],\n );\n\n // ▶ with a host that runs on from the node: the collect form's values become a real run that\n // continues downstream and stops before every paused node. The host owns the request and the\n // run it shows, so the modal closes once the run has started; a refusal stays in the modal.\n const performRunFromNode = useCallback(\n async (id: string, values: Record<string, unknown>, state?: StepStartState) => {\n if (!onRunFromNode) return;\n const node = nodes.find((n) => n.id === id);\n if (!node) return;\n const isTrigger = isTriggerStep(node.data.step.uses);\n const req: RunFromNodeRequest = {\n stopAt: pausedStopAt(\n nodes.map((n) => n.data.step),\n id,\n ),\n ...(state ? { state } : {}),\n ...(isTrigger ? { input: values } : {}),\n };\n setRunResult({ stepId: id, status: \"running\" });\n try {\n await onRunFromNode(id, req);\n setRunResult(null);\n } catch (e) {\n const err = e as { message?: string; code?: string };\n setRunResult({\n stepId: id,\n status: \"error\",\n error: err.message ?? String(e),\n errorCode: err.code,\n });\n }\n },\n [nodes, onRunFromNode],\n );\n\n // Pause / disable: flip one flag on one step, keeping the node's run/problem stamps.\n const patchStep = useCallback(\n (id: string, fn: (step: FlowStep) => FlowStep) => {\n if (readOnly) return;\n const nextNodes = nodes.map((n) =>\n n.id === id ? { ...n, data: { ...n.data, step: fn(n.data.step) } } : n,\n );\n setNodes(nextNodes);\n emitChange(nextNodes, edges);\n },\n [nodes, edges, setNodes, emitChange, readOnly],\n );\n const togglePause = useCallback(\n (id: string) => patchStep(id, (s) => withPaused(s, !isPausedStep(s))),\n [patchStep],\n );\n const toggleDisable = useCallback(\n (id: string) => patchStep(id, (s) => withDisabled(s, !isDisabledStep(s))),\n [patchStep],\n );\n\n // Invoke one step through the invoke API with the properties collected in the\n // modal's collect phase, and (for action steps) its stored connection.\n //\n // `state` is the run's START STATE — what the upstream steps last produced —\n // and it is NOT params: it goes out as the invoke body's own `state` field so\n // the server can resolve `{{ steps.<id>.output.<field> }}` in the step's\n // `with`. Sending it as params would do nothing: the runtime copies only\n // DECLARED params and drops the rest (`core/runtime/src/resolve.ts`).\n const performRunStep = useCallback(\n async (id: string, values: Record<string, unknown>, state?: StepStartState) => {\n // T1.1.1: a step test starts NOW, so the host drops the run it was\n // showing before the invoke goes out — the canvas returns to editable on\n // the user's action, not on this test's eventual result.\n onTestRun?.();\n const node = nodes.find((n) => n.id === id);\n if (!node) return;\n const step = node.data.step;\n const isTrigger = isTriggerStep(step.uses);\n // A trigger's filled fields ARE the run's starting state: the handler\n // returns `params.input` verbatim, so anything else comes back `{}`. Every\n // other step is ALREADY CONFIGURED — `values` is the incoming state the\n // collect form asked for, merged over the step's STORED `with`, which is\n // exactly the payload the Test tab sends (`testValues`). The stored `with`\n // is read, never written: a run does not rewrite the step's configuration.\n const payload = isTrigger ? { input: values } : { ...(step.with ?? {}), ...values };\n // The fixture saved alongside the run, in the same two slots the Test tab\n // writes: `input` is the run's incoming state — for a trigger its filled\n // values *are* it, for every other step it is what the incoming-state box\n // held — and `with` is the full set of params the call was made with.\n const fixture = isTrigger\n ? { input: values, with: values }\n : { input: values, with: payload };\n setRunResult({ stepId: id, status: \"running\" });\n try {\n const result = await api.invokeAction(step.uses.app, step.uses.action, payload, {\n connectionId: connectionIdFor(step, connectionsRef.current),\n // Scope document expressions to the workflow's selected project (T2.1.2).\n project,\n // Omitted when nothing upstream has a saved output, so a run with no\n // seed sends exactly the request it sent before.\n ...(state ? { state } : {}),\n // So `{{ nodes.<id>.config.* }}` resolves as on a run.\n workflowId: value.id,\n });\n // Script nodes may return captured console output alongside the value.\n const logs = (result as { logs?: string[] }).logs;\n const meta = result.meta;\n setRunResult({\n stepId: id,\n status: \"done\",\n value: result.value,\n logs,\n ...(meta ? { meta } : {}),\n });\n // Remember the values and log the run against the fixture they were\n // saved as (best-effort — never fail the run over it).\n persistStepRun(id, fixture, {\n status: \"succeeded\",\n output: result.value,\n ...(meta ? { meta } : {}),\n });\n } catch (e) {\n // The api client wraps network/parse failures with context; duck-type the\n // code so the modal can show it next to the message.\n const err = e as { message?: string; code?: string };\n setRunResult({\n stepId: id,\n status: \"error\",\n error: err.message ?? String(e),\n errorCode: err.code,\n });\n // A failed run still remembers what was entered — the operator's next\n // attempt starts from the values that failed, not from blank.\n persistStepRun(id, fixture, { status: \"failed\", error: err.message ?? String(e) });\n }\n },\n [nodes, api, persistStepRun, project, onTestRun, value.id],\n );\n\n const controls = useMemo<StepControls>(\n () => ({\n onEdit: (id) => {\n setEditView(\"props\");\n setEditingId(id);\n },\n onEditJson: (id) => {\n setEditView(\"json\");\n setEditingId(id);\n },\n onRun: runStep,\n onDuplicate: duplicateStep,\n onDelete: deleteStep,\n onTogglePause: togglePause,\n onToggleDisable: toggleDisable,\n runsFromNode: !!onRunFromNode,\n onAddFromPort: addFromPort,\n readOnly,\n }),\n [\n runStep,\n duplicateStep,\n deleteStep,\n togglePause,\n toggleDisable,\n onRunFromNode,\n addFromPort,\n readOnly,\n ],\n );\n\n // Opens the step editor on a canvas node double-click — deliberately NOT\n // React Flow's own node-double-click prop on `<ReactFlow>` below. That prop\n // fires from React's root container, an ANCESTOR of `.react-flow__pane` under\n // React 18's event delegation, so it always loses the race to the pane's own\n // native `dblclick.zoom` listener and can't stop it. A capture-phase listener\n // on this container fires first instead.\n //\n // The guard matters specifically in `readOnly`: `nodesDraggable={!readOnly}`\n // below drops `nopan` from the node wrapper's class list for a non-draggable\n // node, and for THIS scenario — a non-wheel double-click with no active\n // selection or connection in progress — `@xyflow/system`'s zoom filter's\n // remaining check is `.nopan` — so without this listener winning the race,\n // a viewer's double-click silently zooms the canvas instead of opening the\n // modal.\n useEffect(() => {\n const div = flowContainerRef.current;\n if (!div) return;\n const handler = (e: MouseEvent) => {\n const card = (e.target as HTMLElement).closest(\".react-flow__node\");\n if (!card) return; // not over a node — let the pane's own dblclick-zoom run\n const id = card.getAttribute(\"data-id\");\n if (!id) return;\n // CAPTURE phase (registered below) is what makes this run before the\n // pane's bubble-phase `dblclick.zoom` listener; stopping it here is what\n // actually suppresses the zoom.\n e.stopPropagation();\n // Same transition the node toolbar's pencil button performs — no new\n // plumbing, `controls` already carries `onEdit`.\n controls.onEdit(id);\n };\n div.addEventListener(\"dblclick\", handler, true);\n return () => div.removeEventListener(\"dblclick\", handler, true);\n }, [controls]);\n\n const editingNode = nodes.find((n) => n.id === editingId);\n const editingStep = editingNode?.data.step ?? null;\n // The step the run modal is open on, resolved live so the collect phase reads\n // the current `with` (a trigger's declared `fields`) rather than a snapshot.\n const runningStep = runResult\n ? (nodes.find((n) => n.id === runResult.stepId)?.data.step ?? null)\n : null;\n // Phase 1 of the run modal: collect the run's incoming state, nothing invoked\n // yet. The collect form offers the same upstream seed chips the Test tab does,\n // so it needs the RUNNING step's graph ancestors — the step editor's own\n // `upstreamState` below is computed for `editingId`, a different step.\n const collecting = runResult?.status === \"collect\" && !!runningStep;\n\n const fanOutCounts = useMemo(() => {\n const m = new Map<string, number>();\n for (const n of nodes) m.set(n.id, fanOutState(n.id, edges).count);\n return m;\n }, [nodes, edges]);\n\n // Loop colours: keyed on loop membership only, so a drag keeps the same context value.\n const loopKey = loopPaintKey(nodes);\n const paint = useMemo(() => loopPaint(loopKey), [loopKey]);\n const paintedEdges = useMemo(\n () => paintLoopEdges(edges, paint.tones, paint.loopOf),\n [edges, paint],\n );\n\n const nodeTypes = useMemo(\n () => ({\n step: StepNodeCard,\n control: ControlNodeCard,\n }),\n [],\n );\n\n // The workflow state in scope for the step being edited: its upstream steps'\n // outputs (`steps.<id>.output`) and, if a trigger precedes it, `trigger.event`.\n //\n // Each upstream step also carries its pickable output FIELDS when a shape is\n // known (`output-shape.ts`): an app action's declared `output`, else its\n // `sample`, else that step's last test run — so a later step can reference\n // `steps.<id>.output.<field>` without running anything first.\n const [stepTestOutputs, setStepTestOutputs] = useState<Record<string, unknown>>({});\n const [stepTestMetas, setStepTestMetas] = useState<Record<string, StepMeta>>({});\n // A For each's own saved Test (its item sample), by step id — read only as the loop's\n // item-shape fallback (`loopSourceFor`), never as that step's output.\n const [stepLoopSamples, setStepLoopSamples] = useState<Record<string, unknown[]>>({});\n // When each of those saved tests last ran — a persisted node sample strictly newer than it wins.\n const [stepTestRunAt, setStepTestRunAt] = useState<Record<string, string | null | undefined>>({});\n // The workflow's PERSISTED node samples (`node-samples.ts`): each node's last output shape from\n // any Test / node run / run, written server-side. Loaded per workflow (and again whenever a step\n // editor or the builder opens, alongside the saved tests below), so upstream keys survive a\n // reload, a reopen or another browser. A host without `loadNodeSamples` keeps `[]` — as before.\n // While the add-step builder is open, the step being drafted (declared here, before its first read).\n const [draftStepId, setDraftStepId] = useState<string | null>(null);\n const [nodeSamples, setNodeSamples] = useState<NodeSample[]>([]);\n const nodeSampleOpenKey = editingId ?? draftStepId ?? \"\";\n useEffect(() => {\n // Read the key so the effect re-runs when a step editor / the builder opens.\n void nodeSampleOpenKey;\n const load = api.loadNodeSamples;\n if (typeof load !== \"function\" || !value.id) {\n setNodeSamples([]);\n return;\n }\n let canceled = false;\n // Best-effort: a failed load keeps whatever was loaded before and never breaks the editor.\n load(value.id).then(\n (rows) => {\n if (!canceled) setNodeSamples(Array.isArray(rows) ? rows : []);\n },\n () => {},\n );\n return () => {\n canceled = true;\n };\n }, [api, value.id, nodeSampleOpenKey]);\n const persistedSamples = useMemo(() => indexNodeSamples(nodeSamples), [nodeSamples]);\n // Fresh (saved-test) and persisted outputs stay SEPARATE tiers, for SHAPES (skeletons included):\n // a persisted sample is offered only where it wins (no saved test, or strictly newer).\n const shapeTiers = useMemo(\n () => splitNodeOutputs(stepTestOutputs, persistedSamples, stepTestRunAt),\n [stepTestOutputs, persistedSamples, stepTestRunAt],\n );\n // …and for the Result PREVIEWS (real values only, never a skeleton).\n const previewTiers = useMemo(\n () => splitPreviewOutputs(stepTestOutputs, persistedSamples, stepTestRunAt),\n [stepTestOutputs, persistedSamples, stepTestRunAt],\n );\n const stepShapes = useMemo<StepShapeContext>(\n () => ({\n actionDef: (app, action) => actionDefs[app]?.find((a) => a.key === action),\n triggerDef: (app, trigger) => triggerDefs[app]?.find((t) => t.key === trigger),\n testOutputs: shapeTiers.fresh,\n persistedOutputs: shapeTiers.persisted,\n loopSamples: stepLoopSamples,\n }),\n [actionDefs, triggerDefs, shapeTiers, stepLoopSamples],\n );\n // The ▶ Run modal's projection, kept WHOLE: ONE call yields both the seed chips' ancestors\n // (`.steps`) and the `loop` the Current item / Index seed comes from (never a second membership\n // derivation). It passes `stepShapes` so the loop's sample item resolves.\n const runUpstreamSteps = useMemo(\n () =>\n runResult ? upstreamStateSources(runResult.stepId, nodes, edges, stepShapes) : undefined,\n [runResult, nodes, edges, stepShapes],\n );\n const runSteps = useMemo(() => runUpstreamSteps?.steps ?? [], [runUpstreamSteps]);\n // While the add-step builder is open `editingId` is null: a wired draft anchors the rail on\n // `draftStepId`, but a floating one makes `upstreamStateSources` offer EVERY node — including\n // the step being drafted (progressively committed as a node). Exclude it from its own sources.\n const upstreamState = useMemo(() => {\n const st = upstreamStateSources(editingId, nodes, edges, stepShapes, draftStepId);\n return { ...st, steps: excludeSelfStep(st.steps, editingId ?? draftStepId) };\n }, [editingId, draftStepId, nodes, edges, stepShapes]);\n // The merged workflow STATE the edited step reads (starting data, variables, upstream\n // writers in run order) — the picker's \"State\" section and its `state.<path>` previews.\n const stateShape = useMemo(\n () =>\n computeStateShape({\n anchorId: editingId ?? draftStepId,\n nodes,\n edges,\n initialState: value.initialState,\n variables: value.variables,\n shapes: stepShapes,\n previewOutputs: { ...previewTiers.persisted, ...previewTiers.fresh },\n }),\n [\n editingId,\n draftStepId,\n nodes,\n edges,\n value.initialState,\n value.variables,\n stepShapes,\n previewTiers,\n ],\n );\n // A stable identity for *which* steps are upstream. The memo above rebuilds on\n // every node drag and every field edit; this string changes only when the SET\n // does, so the fetch below doesn't re-run on each keystroke.\n // Includes the saved tests the projection reads beyond `steps` (an after-loop For each's last body step).\n const upstreamIdsKey = JSON.stringify([\n ...upstreamState.steps.map((s) => s.id),\n ...(upstreamState.extraSampleIds ?? []),\n ]);\n\n // Design-time sample values for the expression editor's Result pane: what each\n // upstream step's LAST TEST RUN actually captured, flattened onto the very refs\n // the picker inserts (`steps.<id>.output` and `steps.<id>.output.<field>`). Read\n // from the saved fixtures (`StepTest.lastRunOutput`), so it survives a reload.\n //\n // ⚠️ EDITOR-SIDE ONLY, like `upstreamStateSources` above: this is a PREVIEW of\n // values a past test produced. It is not what a full run resolves — nothing here\n // is sent to the engine.\n useEffect(() => {\n const ids = JSON.parse(upstreamIdsKey) as string[];\n if ((!editingId && !draftStepId) || ids.length === 0) {\n setStepTestOutputs({});\n setStepTestMetas({});\n setStepLoopSamples({});\n setStepTestRunAt({});\n return;\n }\n let canceled = false;\n // Best-effort, per step: a failed or empty list contributes no entry and never\n // breaks the picker — the same shape as the step editor's seed effect.\n Promise.all(\n ids.map(async (id) => {\n try {\n const tests = await api.listStepTests(value.id, id);\n // `listStepTests` is oldest-first, so the LAST entry is the most recent\n // fixture — the \"latest\" convention this file already uses twice.\n const latest = tests.length ? tests[tests.length - 1] : null;\n return latest\n ? {\n id,\n output: latest.lastRunOutput,\n runAt: latest.lastRunAt,\n meta: latest.lastRunMeta,\n loopSample: foreachTestSample(latest),\n }\n : null;\n } catch {\n return null;\n }\n }),\n ).then((res) => {\n // LOAD-BEARING, and its failure mode is silent: without this guard a slow\n // list that resolves after the editor was closed and reopened overwrites\n // the fresh samples with the ones it read before — the pane then previews a\n // POPULATED, STALE value, which is worse than showing none. Pinned by\n // `artifacts/T5.1.3-r2-checks.sh` §X (mutant M11).\n if (canceled) return;\n const next: Record<string, unknown> = {};\n const nextMetas: Record<string, StepMeta> = {};\n const nextLoopSamples: Record<string, unknown[]> = {};\n const nextRunAt: Record<string, string | null | undefined> = {};\n for (const r of res) {\n if (r?.meta) nextMetas[r.id] = r.meta;\n if (r?.loopSample) nextLoopSamples[r.id] = r.loopSample;\n if (!r || r.output === undefined || r.output === null) continue;\n next[r.id] = r.output;\n nextRunAt[r.id] = r.runAt;\n }\n setStepTestOutputs(next);\n setStepTestRunAt(nextRunAt);\n setStepTestMetas(nextMetas);\n setStepLoopSamples(nextLoopSamples);\n });\n return () => {\n canceled = true;\n };\n }, [api, value.id, editingId, draftStepId, upstreamIdsKey]);\n // The last test output, flattened onto the very refs the picker inserts: the\n // whole output, and each offered field path (nested ones included). Values\n // pass through unstringified — the modal's `effectiveSamples` stringifies.\n const declared = useMemo(() => declaredSamples(nodes, stepShapes), [nodes, stepShapes]);\n const sampleTiers = useMemo(\n () => ({ persisted: previewTiers.persisted, samples: declared.samples, event: declared.event }),\n [previewTiers.persisted, declared],\n );\n const stepSampleValues = useMemo(\n () =>\n upstreamSampleValues(\n upstreamState.steps,\n previewTiers.fresh,\n stepTestMetas,\n upstreamState.loop,\n sampleTiers,\n ),\n [upstreamState.steps, upstreamState.loop, previewTiers.fresh, stepTestMetas, sampleTiers],\n );\n const stepValueSources = useMemo(\n () =>\n upstreamSampleValueSources(\n upstreamState.steps,\n previewTiers.fresh,\n stepTestMetas,\n upstreamState.loop,\n sampleTiers,\n ),\n [upstreamState.steps, upstreamState.loop, previewTiers.fresh, stepTestMetas, sampleTiers],\n );\n\n // …merged with the host-supplied vars/secrets/sealSecret so the expression\n // editor's left panel shows every source at once.\n //\n // `ExpressionOptionsProvider` below LAYERS over whatever this editor is\n // mounted under, so the project's vars/secrets/documents arrive on their own\n // and need not be restated here — the `exprOptions` PROP is now only for a\n // host that wants to override or add something at this level.\n //\n // `sampleValues` is the one key that must UNION rather than replace, and that\n // is why the inherited scope is read explicitly: three disjoint ref\n // namespaces contribute to it (`var.*`/`documents.*` from the app shell,\n // anything the prop adds, and `steps.*` computed here), and layering alone\n // would let the object built below shadow the inherited one wholesale.\n const inheritedExprOptions = useExpressionOptions();\n // Every node's `nodes.<id>.config` keys — offered whether or not the node is upstream.\n const nodeConfigs = useMemo(() => nodeConfigSources(nodes), [nodes]);\n // …and their values, so the Test tab previews a config ref instead of calling it unresolved.\n const nodeConfig = useMemo(\n () => nodeConfigValues(nodes, triggerRegistration.subs),\n [nodes, triggerRegistration.subs],\n );\n // …and every node's static metadata (`nodes.<id>.meta.app|version|action|connectionId`, a\n // webhook's subscription), readable without a run. `version` is the one the canvas labels.\n const nodeMeta = useMemo(\n () => nodeMetaValues(nodes, triggerRegistration.subs, appsById, connections),\n [nodes, triggerRegistration.subs, appsById, connections],\n );\n const mergedExprOptions = useMemo<ExpressionOptions>(\n () => ({\n ...(exprOptions ?? {}),\n steps: upstreamState.steps,\n hasTrigger: upstreamState.hasTrigger,\n eventOutputs: upstreamState.eventOutputs,\n eventOutputsFrom: upstreamState.eventOutputsFrom,\n loop: upstreamState.loop,\n stateShape: { fields: stateShape.fields },\n nodeConfigs: nodeConfigs,\n nodeConfig,\n nodeMeta,\n valueSources: stepValueSources,\n sampleValues: {\n ...(inheritedExprOptions.sampleValues ?? {}),\n ...(exprOptions?.sampleValues ?? {}),\n // Static meta under a test's reported meta, which wins.\n ...nodeMetaSampleValues(nodeMeta),\n ...stepSampleValues,\n ...stateShape.sampleValues,\n },\n }),\n [\n exprOptions,\n inheritedExprOptions.sampleValues,\n upstreamState,\n stateShape,\n stepSampleValues,\n stepValueSources,\n nodeConfigs,\n nodeConfig,\n nodeMeta,\n ],\n );\n\n const restoreEdit = (direction: \"undo\" | \"redo\") => {\n if (readOnly) return;\n const snapshot = editHistory[direction]();\n if (!snapshot) return;\n const graph = restoreFlowEdit(value, snapshot);\n setNodes(graph.nodes.map((n) => ({ ...n, selected: n.id === selectedId })));\n setEdges(graph.edges.map((e) => ({ ...e, selected: e.id === selectedEdgeId })));\n setCanvas(snapshot.canvas);\n setConnections(snapshot.connections);\n if (!graph.nodes.some((n) => n.id === selectedId)) setSelectedId(null);\n if (!graph.edges.some((e) => e.id === selectedEdgeId)) setSelectedEdgeId(null);\n const keepEditor = graph.nodes.some((n) => n.id === editingId);\n if (!keepEditor) setEditingId(null);\n setBuilderOpen(false);\n setDraftStepId(null);\n setPendingConnect(null);\n setPendingDelete(null);\n setPendingCanvasDelete(null);\n setBuilderPlace(null);\n setContextMenu(null);\n setLoopNotice(null);\n setLaneError(null);\n textEditGroup.current = undefined;\n // Repaint from CURRENT run/problem data, and refresh authored fields in an open modal.\n // Test results, cached samples and in-flight tests are deliberately left alone.\n setRestoreVersion((v) => v + 1);\n onChange(\n withCanvas(\n flowToWorkflow(\n { ...value, nodes: snapshot.nodes, connections: snapshot.connections },\n graph.nodes,\n graph.edges,\n ),\n snapshot.canvas,\n ),\n );\n if (!keepEditor && !runResult) flowContainerRef.current?.focus({ preventScroll: true });\n };\n const restoreEditRef = useRef(restoreEdit);\n restoreEditRef.current = restoreEdit;\n useEffect(() => {\n const editor = flowContainerRef.current;\n if (!editor) return;\n let active = editor.contains(document.activeElement);\n const trackActive = (event: Event) => {\n // Removing a focused flyout button returns focus to body. Keep its editor active\n // until the author actually focuses or clicks somewhere else.\n if (event.type === \"focusin\" && event.target === document.body) return;\n active = editor.contains(event.target as Node);\n };\n const onKey = (event: KeyboardEvent) => {\n if (readOnly || event.defaultPrevented || isFlowTextTarget(event.target)) return;\n if (!editor.contains(event.target as Node) && !(active && event.target === document.body))\n return;\n const key = event.key.toLowerCase();\n if (!(event.ctrlKey || event.metaKey) || event.altKey) return;\n if (key !== \"z\" && !(key === \"y\" && !event.shiftKey)) return;\n event.preventDefault();\n restoreEditRef.current(key === \"y\" || event.shiftKey ? \"redo\" : \"undo\");\n };\n document.addEventListener(\"pointerdown\", trackActive);\n document.addEventListener(\"focusin\", trackActive);\n document.addEventListener(\"keydown\", onKey);\n return () => {\n document.removeEventListener(\"pointerdown\", trackActive);\n document.removeEventListener(\"focusin\", trackActive);\n document.removeEventListener(\"keydown\", onKey);\n };\n }, [readOnly]);\n\n // ── Right-click menu ────────────────────────────────────────────────────────\n //\n // The native browser menu is suppressed only where this one opens: the pane, a node,\n // an edge and the selection box. A right-click inside a text field keeps the native\n // menu (copy/paste). Read-only still opens it, with every item greyed.\n const openContextMenu = useCallback(\n (\n event: {\n clientX: number;\n clientY: number;\n target: EventTarget | null;\n preventDefault(): void;\n },\n nodeId?: string,\n ) => {\n if (isFlowTextTarget(event.target)) return;\n const box = flowContainerRef.current?.getBoundingClientRect();\n if (!box) return;\n event.preventDefault();\n const selection = selectedFlowElements(nodes, edges);\n const selected = selection.nodeIds;\n const nodeIds = contextMenuTargets(selected, nodeId);\n const alone = nodeId !== undefined && !selected.includes(nodeId);\n // A node outside the selection becomes the selection, so the menu's target shows.\n if (alone) {\n setNodes(\n nodes.map((n) =>\n n.selected !== (n.id === nodeId) ? { ...n, selected: n.id === nodeId } : n,\n ),\n );\n }\n setContextMenu({\n x: event.clientX - box.left,\n y: event.clientY - box.top,\n flow: screenToFlowPosition({ x: event.clientX, y: event.clientY }),\n nodeIds,\n edgeIds: alone ? [] : selection.edgeIds,\n });\n },\n [nodes, edges, setNodes, screenToFlowPosition],\n );\n const closeContextMenu = useCallback((restoreFocus: boolean) => {\n setContextMenu(null);\n if (restoreFocus) flowContainerRef.current?.focus({ preventScroll: true });\n }, []);\n const onContextMenuAction = (action: CanvasMenuAction) => {\n const menu = contextMenu;\n if (!menu || readOnly) return;\n if (action === \"duplicate\") duplicateSteps(menu.nodeIds);\n // The same pending selection + confirm as the Delete key and the node trash button.\n else if (action === \"delete\")\n setPendingDelete({ nodeIds: menu.nodeIds, edgeIds: menu.edgeIds });\n else {\n setPendingConnect(null);\n setBuilderPlace({\n position: menu.flow,\n ...(action === \"add-trigger\" ? { tab: \"triggers\" as const } : {}),\n });\n setBuilderOpen(true);\n }\n };\n\n const editor = (\n <StepControlsCtx.Provider value={controls}>\n <PortsLookupCtx.Provider value={portsLookup}>\n <FanOutCountsCtx.Provider value={fanOutCounts}>\n <LoopPaintCtx.Provider value={paint}>\n <CardDataProvider apps={appsById} registration={triggerRegistration}>\n <WorkflowProjectProvider project={project} workflowId={value.id}>\n <ExpressionOptionsProvider value={mergedExprOptions}>\n <section\n ref={flowContainerRef}\n className=\"w6w-flow\"\n tabIndex={-1}\n aria-label=\"Workflow editor\"\n style={{ width: \"100%\", height, position: \"relative\" }}\n onFocusCapture={(e) => {\n textEditGroup.current = isFlowTextTarget(e.target) ? {} : undefined;\n }}\n onBlurCapture={() => {\n textEditGroup.current = undefined;\n }}\n onKeyDown={(e) => {\n if (e.defaultPrevented) return;\n if (e.key !== \"Backspace\" && e.key !== \"Delete\") return;\n // Only delete selected elements when the key is aimed at the\n // canvas — never while a modal is open or the user is editing a field.\n // The modal <dialog> is a DOM descendant here, so its keystrokes\n // bubble up; without this guard, backspacing a typo deletes a node.\n if (readOnly || editingId || builderOpen || pendingDelete) return;\n const t = e.target as HTMLElement;\n if (\n t.isContentEditable ||\n t.tagName === \"INPUT\" ||\n t.tagName === \"TEXTAREA\" ||\n t.tagName === \"SELECT\" ||\n t.closest(\"dialog, .w6w-modal\") !== null\n ) {\n return;\n }\n const selection = selectedFlowElements(nodes, edges);\n if (!selection.nodeIds.length && !selection.edgeIds.length) return;\n e.preventDefault();\n if (!selection.nodeIds.length && selection.edgeIds.length === 1) {\n deleteEdge(selection.edgeIds[0]);\n } else {\n setPendingDelete(selection);\n }\n }}\n >\n <ReactFlow\n nodes={displayedNodes}\n edges={paintedEdges}\n minZoom={0.05}\n // Straight segments with right-angle corners, not the library's\n // default bezier curve — reads clearer on a wide, branchy graph\n // than a sweeping curve does. One place: no edge object sets its\n // own `type`, so this alone governs every edge on the canvas.\n // `connectionLineType` matches it for the in-progress drag line,\n // so the preview doesn't curve while the settled edge won't.\n defaultEdgeOptions={{ type: \"smoothstep\" }}\n connectionLineType={ConnectionLineType.SmoothStep}\n onNodesChange={onNodesChange}\n onEdgesChange={onEdgesChange}\n onConnect={onConnect}\n onConnectStart={(_e, p) => {\n connectStartRef.current = p;\n }}\n onConnectEnd={onConnectEnd}\n onPaneClick={() => setLoopNotice(null)}\n onPaneContextMenu={(e) => openContextMenu(e)}\n onNodeContextMenu={(e, node) => openContextMenu(e, node.id)}\n onEdgeContextMenu={(e) => openContextMenu(e)}\n onSelectionContextMenu={(e) => openContextMenu(e)}\n // A pan or zoom moves the canvas out from under the menu's drop point.\n onMoveStart={() => setContextMenu(null)}\n isValidConnection={isValidConnection}\n // A finished drag is what makes a new coordinate stick: until this\n // existed, dragging went only through `onNodesChange` and never\n // marked the workflow changed, so the position was lost on reload.\n // `flowToWorkflow` (inside `emitChange`) does the conversion and the\n // rounding — nothing is converted here.\n //\n // Drag STOP, never `onNodeDrag`: the per-frame variant fires on every\n // animation frame of the gesture, and the host's auto-save is a\n // trailing debounce over emitted changes, so a per-frame emit is a\n // write storm by construction.\n //\n // No `readOnly` term is needed: `nodesDraggable={!readOnly}` below\n // means React Flow never starts the drag, so this cannot fire at all\n // in a read-only editor. Measured, not assumed — the probe's readOnly\n // fixture asserts the node does not move (F4-V1).\n onNodeDragStop={(_e, _n, dragged) => {\n const nextCanvas = membershipAfterDrag(dragged as StepNode[]);\n const membershipChanged = nextCanvas !== canvas;\n if (membershipChanged) setCanvas(nextCanvas);\n if (!savePosition && !membershipChanged) {\n editHistory.record(\n captureFlowEdit(\n value,\n nodes,\n edges,\n connectionsRef.current,\n nextCanvas,\n ),\n );\n return;\n }\n emitChange(nodes, edges, nextCanvas);\n }}\n onMoveEnd={(event, viewport) => {\n // FIRST statement, and load-bearing. React Flow passes\n // `event === null` when the move was NOT user-initiated\n // (@xyflow/react 12.11.1, `types/component-props.d.ts` on\n // `onMoveEnd`: \"If the movement is not user-initiated, the event\n // parameter will be `null`.\"). The `fitView` on open is exactly\n // such a move — without this guard every open would emit a change,\n // and with the host's auto-save every page load would be a write.\n if (!event) return;\n // `readOnly` is checked here and NOT delegated, because — unlike a\n // drag — panning and zooming stay enabled in a read-only editor (see\n // the prop's docstring), so this handler really does fire and a\n // viewer must not write to what they are only looking at.\n if (readOnly) return;\n // `savePosition` is deliberately NOT re-checked here: `withViewport`\n // is the single place that reads the flag for this path and returns\n // its argument unchanged when it is off, so a duplicate term would be\n // unobservable — measured as a surviving mutant (T3.3.2-mutants.sh\n // C5) and removed rather than shipped as an unpinnable branch.\n //\n // Emit ONLY when `withViewport` hands back a different reference:\n // it returns `value`'s base unchanged when the rounded viewport\n // already equals the stored one, so a pan that lands back where it\n // started emits nothing. Rate is bounded by the gesture, not the\n // frame — `onMoveEnd` is d3-zoom's terminal event, and\n // `@xyflow/system` additionally coalesces scroll-driven pans behind\n // a 150ms trailing timer of its own (no timer belongs here).\n const base = flowToWorkflow(value, nodes, edges);\n const next = withViewport(base, viewport);\n // `viewportOnly`: a camera move must not cost the host its run\n // paint (adhoc/run-paint) — only the definition changing does.\n if (next !== base) onChange(next, { viewportOnly: true });\n }}\n onSelectionChange={({ nodes: sel, edges: edgeSel }) => {\n // ⚠️ Only primitives are stored from this handler: React Flow re-invokes\n // it (inline) after every re-render of this component, so storing a\n // fresh array here defeats React's `Object.is` bail-out and loops —\n // a silent CPU burn in a page, a frozen main thread under Storybook.\n setSelectedId(sel[0]?.id ?? null);\n setSelectedEdgeId(edgeSel[0]?.id ?? null);\n if (loopNoticeSelRef.current !== (sel[0]?.id ?? null)) {\n loopNoticeSelRef.current = sel[0]?.id ?? null;\n setLoopNotice(null);\n }\n // Deliberately NOT clearing `laneError` here — see its declaration.\n }}\n nodeTypes={nodeTypes}\n nodesDraggable={!readOnly}\n nodesConnectable={!readOnly}\n // A click on a port adds a step from it (PortHandle) — not the library's\n // click-a-port-then-click-another connect mode, which shows nothing\n // after the first click and reads as a dead port.\n connectOnClick={false}\n elementsSelectable\n // Reopen at the camera the author left, when the workflow stores one;\n // otherwise fit the graph exactly as before. The two props are spread\n // in so only ONE of them is ever passed: they are mutually exclusive\n // by the library's own rule — \"If a default viewport is provided but\n // `fitView` is enabled, the default viewport will be ignored\"\n // (`types/component-props.d.ts` on `defaultViewport`) — and a stray\n // `fitView` would silently discard the restored view.\n {...(savedViewport ? { defaultViewport: savedViewport } : { fitView: true })}\n // Deletion is owned solely by the guarded onKeyDown handler above\n // (canvas-only, with a confirm). Disable React Flow's built-in\n // Backspace/Delete so it can't silently remove a node — e.g. while a\n // modal is open or the user is editing a field.\n deleteKeyCode={null}\n colorMode={colorMode}\n proOptions={{ hideAttribution: true }}\n >\n <Background gap={16} />\n {/* `showInteractive={false}` still suppresses the lock button; the\n child is appended AFTER the three built-ins (zoom in / zoom out /\n fit view), so auto-layout reads as the fourth control in the same\n stack — \"beside the zoom controls\", not a floating panel. It\n carries NO colour, background or border of its own: the\n `--xy-controls-button-*` → `--w6w-*` bridge in `styles.css` sets\n inherited custom properties on the `.w6w-flow` wrapper, so any\n control button added later is themed for free (measured in both\n stylesheet orders — T3.1.1's evaluation built this exact shape). */}\n <Controls showInteractive={false}>\n {!readOnly && (\n <ControlButton\n onClick={requestRelayout}\n title=\"Auto-layout — re-flow the graph into columns\"\n aria-label=\"Auto-layout the graph\"\n >\n {/* `icons.tsx`'s `layout` — the three-box hierarchy. It must NOT be a\n `fill=\"none\" stroke=…` glyph: the library styles a control button's\n svg as `svg { width: 100%; max-width: 12px; max-height: 12px;\n fill: currentColor }` (`@xyflow/react/dist/style.css`), so a stroked\n root would render as nothing at all in here — hence `layout`'s bare\n root (see its entry). */}\n <Icon name=\"layout\" />\n </ControlButton>\n )}\n </Controls>\n <MiniMap pannable zoomable style={{ background: \"var(--w6w-panel-2)\" }} />\n {!readOnly && (\n <Panel position=\"top-left\" className=\"w6w-flow-tools\">\n <button\n type=\"button\"\n className=\"w6w-btn\"\n onClick={() => setBuilderOpen(true)}\n >\n + Node\n </button>\n <IconButton\n label=\"Add note\"\n icon=\"sticky-note\"\n className=\"w6w-flow-tool\"\n data-testid=\"add-note\"\n onClick={addNote}\n />\n <IconButton\n label=\"Draw section\"\n title=\"Draw section — drag a frame on the canvas (Esc cancels)\"\n icon=\"frame\"\n className={`w6w-flow-tool${drawingSection ? \" active\" : \"\"}`}\n aria-pressed={drawingSection}\n data-testid=\"draw-section\"\n onClick={() => {\n setDrawingSection(!drawingSection);\n setSectionDraft(null);\n }}\n />\n </Panel>\n )}\n {/* The draw-section surface: above the graph (z 4, after the renderer)\n and below the panels (z 5), so the tool button stays clickable. */}\n {!readOnly && drawingSection && (\n <div\n className=\"w6w-section-draw nopan nodrag nowheel\"\n data-testid=\"section-draw-surface\"\n onPointerDown={(e) => {\n if (e.button !== 0) return;\n e.currentTarget.setPointerCapture(e.pointerId);\n const { clientX: x, clientY: y } = e;\n setSectionDraft({ sx: x, sy: y, ex: x, ey: y });\n }}\n onPointerMove={(e) => {\n const { clientX: x, clientY: y } = e;\n setSectionDraft((d) => d && { ...d, ex: x, ey: y });\n }}\n onPointerUp={() => {\n const d = sectionDraft;\n setSectionDraft(null);\n setDrawingSection(false);\n if (!d) return;\n const a = screenToFlowPosition({ x: d.sx, y: d.sy });\n const dragged = Math.abs(d.ex - d.sx) > 6 || Math.abs(d.ey - d.sy) > 6;\n addSectionAt(\n a,\n dragged ? screenToFlowPosition({ x: d.ex, y: d.ey }) : null,\n );\n }}\n >\n {sectionDraft &&\n (() => {\n const box = flowContainerRef.current?.getBoundingClientRect();\n const ox = box?.left ?? 0;\n const oy = box?.top ?? 0;\n return (\n <div\n className=\"w6w-section-draw-rect\"\n style={{\n left: Math.min(sectionDraft.sx, sectionDraft.ex) - ox,\n top: Math.min(sectionDraft.sy, sectionDraft.ey) - oy,\n width: Math.abs(sectionDraft.ex - sectionDraft.sx),\n height: Math.abs(sectionDraft.ey - sectionDraft.sy),\n }}\n />\n );\n })()}\n </div>\n )}\n {/* Which outcome the selected edge carries (core rfcs/workflow.md ·\n `Edge.when`). Revealed only when exactly ONE edge is selected —\n `selectedEdgeId` is already `edgeSel[0]`, so selecting a node or\n nothing hides it. top-left is `+ Node`, Controls are bottom-left,\n the MiniMap bottom-right. D-T1-7 SUPERSEDED (T1.1.1): id'd source\n handles now exist (the error exit port), so a fresh edge's lane IS\n chosen by which handle it was dragged from — this panel keeps its\n job as the RE-LANE affordance for an edge already drawn on the\n wrong port, not the only way to author an error edge. */}\n {!readOnly &&\n selectedEdge &&\n edgeLane(selectedEdge) !== \"each\" &&\n nodes.find((n) => n.id === selectedEdge.source)?.data.step.uses.app !==\n ROUTER_APP && (\n <Panel position=\"top-right\">\n <div className=\"w6w-edge-lane\">\n <span className=\"w6w-muted w6w-small\">Run on</span>\n {([\"success\", \"error\"] as const).map((lane) => (\n <button\n key={lane}\n type=\"button\"\n className={`w6w-btn w6w-btn-sm w6w-btn-ghost${\n edgeLane(selectedEdge) === lane ? \" active\" : \"\"\n }`}\n aria-pressed={edgeLane(selectedEdge) === lane}\n title={LANE_HINT}\n onClick={() => setEdgeLane(lane)}\n >\n {lane === \"success\" ? \"Success\" : \"Error\"}\n </button>\n ))}\n {laneError?.edgeId === selectedEdge.id && (\n <span className=\"w6w-edge-lane-err w6w-small\" role=\"alert\">\n {laneError.message}\n </span>\n )}\n </div>\n </Panel>\n )}\n {loopNotice && (\n <NodeToolbar\n nodeId={loopNotice.nodeId}\n position={Position.Bottom}\n isVisible\n >\n <div className=\"w6w-loop-notice w6w-small\" role=\"alert\">\n {loopRefusalMessage(loopNotice.reason)}\n </div>\n </NodeToolbar>\n )}\n <CanvasLayer\n canvas={canvas}\n readOnly={readOnly}\n savePosition={savePosition}\n onChange={onCanvasChange}\n onSectionDrop={onSectionDrop}\n onRequestDelete={(kind, id) =>\n !readOnly && setPendingCanvasDelete({ kind, id })\n }\n />\n </ReactFlow>\n {pendingCanvasDelete && (\n <ConfirmModal\n title={\n pendingCanvasDelete.kind === \"note\" ? \"Delete note\" : \"Delete section\"\n }\n message={\n pendingCanvasDelete.kind === \"note\"\n ? \"Delete this note?\"\n : \"Delete this section? Its nodes are kept.\"\n }\n confirmLabel=\"Delete\"\n onConfirm={() => {\n performCanvasDelete(pendingCanvasDelete.kind, pendingCanvasDelete.id);\n setPendingCanvasDelete(null);\n }}\n onClose={() => setPendingCanvasDelete(null)}\n />\n )}\n\n {builderOpen && (\n <StepBuilderModal\n initialTab={builderPlace?.tab}\n onClose={() => {\n setBuilderOpen(false);\n setPendingConnect(null);\n setBuilderPlace(null);\n setDraftStepId(null);\n }}\n onAdd={(built) => {\n const id = addBuiltStep(built);\n if (id) setDraftStepId(id);\n return id;\n }}\n // Progressive commit (T4.1.1): once `addBuiltStep` has minted\n // the step's id, every subsequent field change updates that\n // same node instead of waiting for a final \"Add node\" click.\n onDraftChange={(id, next) => updateStep(id, { id, ...next })}\n // The graph's node ids, so a name typed in the add flow is checked\n // for uniqueness the way a rename is.\n stepIds={nodes.map((n) => n.id)}\n // A picked app trigger lands in the node's own step editor,\n // on its config, the way any node opens.\n onOpenStep={(id) => {\n setBuilderOpen(false);\n setPendingConnect(null);\n setBuilderPlace(null);\n setDraftStepId(null);\n setEditView(\"props\");\n setEditingId(id);\n }}\n workflowId={value.id}\n // The new step's known upstream ancestors, from the handle a\n // connection drag was released from (T1.1.1) — so the builder's\n // own Test tab can seed `{{ steps.<id>.output.<field> }}` the\n // same way the step editor's Test tab already does.\n upstreamSteps={stepBuilderUpstreamSteps(pendingConnect, nodes, edges)}\n loop={stepBuilderLoop(pendingConnect, nodes, edges, stepShapes)}\n />\n )}\n\n {editingStep && editingId && (\n // No `key` on purpose: renaming a step updates `editingId`, and a keyed\n // remount would drop focus mid-keystroke. The modal seeds its own state\n // once and unmounts (editingId → null) between edits of different nodes.\n <StepEditModal\n workflowId={value.id}\n step={editingStep}\n restoreVersion={restoreVersion}\n // Graph ancestors of the editing step, from `upstreamStateSources`\n // (via `mergedExprOptions`) — the incoming-state picker seeds from\n // each ancestor's latest saved step-test rather than re-walking the graph.\n upstreamSteps={mergedExprOptions.steps ?? []}\n loop={mergedExprOptions.loop}\n readOnly={readOnly}\n fanOutCount={fanOutCounts.get(editingId) ?? 0}\n stateOutputFields={resolveOutputShape(\n stepShapes.actionDef?.(editingStep.uses.app, editingStep.uses.action),\n stepShapes.testOutputs?.[editingId],\n stepShapes.persistedOutputs?.[editingId],\n )?.fields.map((f) => f.key)}\n initialView={editView}\n stepProblems={editingNode?.data.stepProblems}\n otherStepIds={nodes.filter((n) => n.id !== editingId).map((n) => n.id)}\n onChange={(next) => updateStep(editingId, next)}\n onClose={() => setEditingId(null)}\n onTestRun={onTestRun}\n />\n )}\n\n {runResult && (\n <Modal\n title={`${collecting ? \"Run node\" : \"Test run\"}: ${runResult.stepId}`}\n onClose={() => setRunResult(null)}\n >\n {collecting && runningStep && (\n <StepRunCollect\n // Keyed on the step so switching nodes re-seeds the form.\n key={runResult.stepId}\n workflowId={value.id}\n step={runningStep}\n upstreamSteps={runSteps}\n loop={runUpstreamSteps?.loop}\n continues={\n onRunFromNode\n ? {\n stopAt: pausedStopAt(\n nodes.map((n) => n.data.step),\n runResult.stepId,\n ),\n }\n : undefined\n }\n onCancel={() => setRunResult(null)}\n onRun={(values, state) =>\n onRunFromNode\n ? performRunFromNode(runResult.stepId, values, state)\n : performRunStep(runResult.stepId, values, state)\n }\n />\n )}\n {/* The collect phase renders its own actions (Run + Cancel),\n gated on the required fields being filled. The status/result/log\n blocks scroll inside the body; Close stays pinned below it. */}\n {!collecting && (\n <>\n <div className=\"w6w-modal-body\">\n {runResult.status === \"running\" && (\n <p className=\"w6w-muted w6w-small\">Running…</p>\n )}\n {runResult.status === \"error\" && (\n <div className=\"w6w-result w6w-error\">\n {runResult.errorCode && (\n <div\n className=\"w6w-small\"\n style={{ opacity: 0.75, marginBottom: 4 }}\n >\n <code>{runResult.errorCode}</code>\n </div>\n )}\n {runResult.error || \"The node failed with no error message.\"}\n </div>\n )}\n {runResult.status === \"done\" && (\n <div>\n <div className=\"w6w-muted w6w-small\" style={{ marginBottom: 6 }}>\n Result\n </div>\n <ResultViewer value={runResult.value} maxHeight={360} />\n {runResult.meta && (\n <>\n <div\n className=\"w6w-muted w6w-small\"\n style={{ margin: \"10px 0 6px\" }}\n >\n Metadata\n </div>\n <ResultViewer value={runResult.meta} maxHeight={360} />\n </>\n )}\n </div>\n )}\n {runResult.logs && runResult.logs.length > 0 && (\n <div>\n <div\n className=\"w6w-muted w6w-small\"\n style={{ margin: \"10px 0 6px\" }}\n >\n Console output\n </div>\n <pre\n className=\"w6w-result\"\n style={{\n whiteSpace: \"pre-wrap\",\n maxHeight: 200,\n overflow: \"auto\",\n margin: 0,\n }}\n >\n {runResult.logs.join(\"\\n\")}\n </pre>\n </div>\n )}\n </div>\n <div className=\"w6w-modal-actions\">\n <button\n type=\"button\"\n className=\"w6w-btn\"\n onClick={() => setRunResult(null)}\n >\n Close\n </button>\n </div>\n </>\n )}\n </Modal>\n )}\n\n {pendingDelete !== null && (\n <ConfirmModal\n title={\n pendingDelete.nodeIds.length === 1\n ? \"Delete node\"\n : pendingDelete.nodeIds.length > 1\n ? `Delete ${pendingDelete.nodeIds.length} nodes`\n : `Delete ${pendingDelete.edgeIds.length} connections`\n }\n message={flowDeleteMessage(pendingDelete, nodes, edges)}\n confirmLabel=\"Delete\"\n onConfirm={() => {\n performDeleteSelection(pendingDelete);\n setPendingDelete(null);\n }}\n onClose={() => setPendingDelete(null)}\n />\n )}\n\n {contextMenu && (\n <CanvasContextMenu\n x={contextMenu.x}\n y={contextMenu.y}\n items={canvasMenuItems(contextMenu.nodeIds, !!readOnly)}\n onAction={onContextMenuAction}\n onClose={closeContextMenu}\n />\n )}\n </section>\n </ExpressionOptionsProvider>\n </WorkflowProjectProvider>\n </CardDataProvider>\n </LoopPaintCtx.Provider>\n </FanOutCountsCtx.Provider>\n </PortsLookupCtx.Provider>\n </StepControlsCtx.Provider>\n );\n return (\n <WorkflowConnectionsContext.Provider\n value={{ nodes: nodes.map((n) => n.data.step), connections, setConnections, readOnly }}\n >\n {editor}\n </WorkflowConnectionsContext.Provider>\n );\n}\n\n/** `@w6w/script`'s params the host passes through as source text, never resolved (engine `LITERAL_PARAMS`). */\nconst SCRIPT_LITERAL_KEYS = [\"code\"];\n\n/**\n * Parse the incoming-state box into the object it stands for. Anything that is\n * not a JSON **object** — unparseable, an array, a scalar, `null` — is not a\n * state at all and reads as `null`, which the callers turn into \"merge nothing\"\n * (Test) or \"don't run\" (▶ Run, a real execution).\n */\nfunction parseStateOverride(text: string): Record<string, unknown> | null {\n try {\n const v = JSON.parse(text);\n return v && typeof v === \"object\" && !Array.isArray(v) ? (v as Record<string, unknown>) : null;\n } catch {\n return null;\n }\n}\n\n/**\n * A For each Test's override box: the usual JSON object (its `items` key replaces the\n * binding), or — what a pasted sample usually is — a bare array, taken as `items` itself.\n */\nfunction parseForeachOverride(text: string): Record<string, unknown> | null {\n try {\n const v = JSON.parse(text);\n if (Array.isArray(v)) return { items: v };\n } catch {\n return null;\n }\n return parseStateOverride(text);\n}\n\ntype ForeachSave = \"idle\" | \"saving\" | \"saved\" | \"failed\";\n\n/**\n * A For each's Test result: what its Items resolve to against the incoming state — the count\n * and the first item. Nothing inside the loop runs; the footer's Test saves the sample\n * (`foreachTestFixture`) so the body steps' picker offers the item's keys.\n */\nfunction ForeachTestResult({ items, save }: { items: unknown[] | undefined; save: ForeachSave }) {\n if (!items) {\n return (\n <output className=\"w6w-small\" style={{ display: \"block\" }}>\n <strong>Items</strong> doesn't resolve to a list yet: no step before this one has a saved\n test that produces it. Test an earlier step, or paste a sample list under{\" \"}\n <strong>Override the incoming state</strong> below.\n </output>\n );\n }\n const first = items[0];\n const keys = first !== undefined ? (inferOutputFields(first) ?? []).map((o) => o.key) : [];\n return (\n <div className=\"w6w-testout\">\n <div className=\"w6w-testout-label\">\n {items.length} {items.length === 1 ? \"item\" : \"items\"}\n </div>\n {items.length === 0 ? (\n <p className=\"w6w-muted w6w-small\">The list is empty, so there is no item to sample.</p>\n ) : (\n <>\n <div className=\"w6w-testout-label\">First item</div>\n <ResultViewer value={first} maxHeight={220} />\n </>\n )}\n {save === \"saved\" && (\n <output className=\"w6w-small\" style={{ display: \"block\" }}>\n Saved as this loop's sample.\n {keys.length > 0 && (\n <>\n {\" \"}\n Steps on <strong>Each item</strong> now offer <strong>Current item</strong> ›{\" \"}\n {keys.map((k, i) => (\n <span key={k}>\n {i > 0 && \", \"}\n <code>{k}</code>\n </span>\n ))}\n .\n </>\n )}\n </output>\n )}\n {save === \"failed\" && (\n <p className=\"w6w-small\" role=\"alert\">\n Couldn't save the sample. Try Test again.\n </p>\n )}\n </div>\n );\n}\n\n/**\n * The loop seed a test of a For each BODY step is sent as `state.foreach`: the sample item\n * (editable JSON) and the index (default 0). While \"Current item\" is untouched it FOLLOWS the\n * loop's `itemSample` (which can arrive after mount); once edited, the edit wins.\n */\nfunction useLoopSeed(loop: ExpressionLoopSource | undefined) {\n const [editedItem, setEditedItem] = useState<string | null>(null);\n const [indexText, setIndexText] = useState(\"0\");\n const itemText = editedItem ?? loopItemText(loop);\n const parsed = loop ? parseLoopSeed(itemText, indexText) : undefined;\n return { active: !!loop, itemText, indexText, setItemText: setEditedItem, setIndexText, parsed };\n}\ntype LoopSeed = ReturnType<typeof useLoopSeed>;\n\n/** The seed `startStateFromSeeds` takes: absent off a loop and while the control is invalid. */\nfunction loopSeedValue(seed: LoopSeed): { item?: unknown; index?: number } | undefined {\n return seed.parsed?.ok ? seed.parsed.value : undefined;\n}\n\n/** Why a loop seed refuses the run (`null` when it is fine, or there is no loop). */\nfunction loopSeedError(seed: LoopSeed): string | null {\n return seed.parsed && !seed.parsed.ok ? seed.parsed.error : null;\n}\n\n/** Sibling of {@link IncomingStateField}: the Current item / Index a loop-body test runs with. */\nfunction LoopSeedField({ seed, readOnly }: { seed: LoopSeed; readOnly?: boolean }) {\n if (!seed.active) return null;\n const error = loopSeedError(seed);\n return (\n <div className=\"w6w-field w6w-loop-seed\">\n <span>Current item</span>\n <textarea\n rows={3}\n value={seed.itemText}\n readOnly={readOnly}\n spellCheck={false}\n aria-label=\"Current item\"\n onChange={(e) => seed.setItemText(e.target.value)}\n />\n <span>Index</span>\n <input\n type=\"text\"\n inputMode=\"numeric\"\n value={seed.indexText}\n readOnly={readOnly}\n aria-label=\"Index\"\n onChange={(e) => seed.setIndexText(e.target.value)}\n />\n <span className=\"w6w-hint\">\n This step runs once per item of the For each. Test it as one iteration — starting from the\n sample item, or edit it.\n </span>\n {error && (\n <span className=\"w6w-hint\" role=\"alert\">\n {error}\n </span>\n )}\n </div>\n );\n}\n\n/**\n * The **incoming state** control — the one implementation behind both the step\n * editor's Test tab and the canvas ▶ Run collect form for a non-trigger step.\n * What varies between two runs of an already-configured step is the data\n * arriving at it, not its parameters, so this is what both surfaces collect.\n *\n * The raw JSON box is an **override** and is titled as one: it sits behind a\n * closed disclosure so neither surface opens on a JSON textarea, while the\n * upstream seed chips stay in plain sight above it. The disclosure opens by\n * itself whenever an override actually exists — seeded from a chip, remembered\n * from the last run, or typed — so an active override is never hidden.\n *\n * ⚠️ This component says nothing about what a **production** run resolves; it\n * collects what the test/run call is given.\n */\nfunction IncomingStateField({\n text,\n onChange,\n seeds,\n readOnly,\n expand,\n hint,\n}: {\n /** Raw JSON text of the override. `{}` (the default) means \"no override\". */\n text: string;\n onChange: (next: string) => void;\n seeds: SeedSource[];\n readOnly?: boolean;\n /** Opens the override disclosure (a caller with nothing to show without one). */\n expand?: boolean;\n /** Replaces the default hint under the override box. */\n hint?: ReactNode;\n}) {\n const parsed = parseStateOverride(text);\n const keyCount = parsed ? Object.keys(parsed).length : 0;\n const hasOverride = keyCount > 0;\n const [open, setOpen] = useState(hasOverride);\n // An override usually arrives AFTER this field has mounted — the Test tab's\n // remembered-state effect (`StepEditModal`) sets the text a network hop later\n // — and `useState`'s argument is a MOUNT-TIME value that never re-derives. Do\n // not collapse this back into the initial value: with `listStepTests` delayed\n // 900 ms, that left a remembered override IN EFFECT behind a CLOSED\n // disclosure (measured in T6.1.1's evaluation; ▶ Run escaped it only because\n // it withholds the whole form until its fixture has loaded). Only the\n // \"nothing → something\" transition reopens it, so a disclosure the operator\n // closed themselves stays closed while they keep typing in it.\n useEffect(() => {\n if (hasOverride || expand) setOpen(true);\n }, [hasOverride, expand]);\n // Seeding from an ancestor uses the output its last run captured; only a\n // fixture that never ran falls back to its own captured incoming state.\n const seedFrom = (test: StepTest) => {\n onChange(JSON.stringify(test.lastRunOutput ?? test.input ?? {}, null, 2));\n setOpen(true);\n };\n return (\n <div className=\"w6w-field w6w-incoming-state\">\n <span>Incoming state</span>\n {seeds.length > 0 && (\n <div className=\"w6w-seed-picker\">\n <div className=\"w6w-seed-chips\">\n {seeds.map((s) => (\n <button\n key={s.stepId}\n type=\"button\"\n className=\"w6w-chip w6w-seed-chip\"\n title={`Use ${s.label}'s saved test as the incoming state`}\n disabled={readOnly}\n onClick={() => seedFrom(s.test)}\n >\n <code>{s.label}</code>\n {s.test.lastRunStatus ? (\n <span className=\"w6w-muted w6w-small\">\n {\" · \"}\n {s.test.lastRunStatus}\n </span>\n ) : null}\n </button>\n ))}\n </div>\n </div>\n )}\n <details\n className=\"w6w-state-override\"\n open={open}\n onToggle={(e) => setOpen(e.currentTarget.open)}\n >\n <summary>\n Override the incoming state\n {keyCount > 0 ? ` · ${keyCount} key${keyCount === 1 ? \"\" : \"s\"} set` : \"\"}\n </summary>\n <textarea\n rows={3}\n value={text}\n readOnly={readOnly}\n spellCheck={false}\n aria-label=\"Incoming state override (JSON)\"\n onChange={(e) => onChange(e.target.value)}\n />\n <span className=\"w6w-hint\">\n {hint ?? (\n <>\n JSON whose keys replace this step's parameters by name, for this test only — so a\n script's data goes under <code>input</code>: <code>{'{\"input\": {…}}'}</code>. Upstream\n outputs already reach <code>{\"{{ nodes.<id>.output }}\"}</code> bindings from their\n saved tests. Reach for this to test against a state the flow cannot currently produce\n — a field no upstream step returns yet, or a case you can't reproduce by running the\n flow.\n </>\n )}\n </span>\n </details>\n </div>\n );\n}\n\n/**\n * Phase 1 of the canvas ▶ run: **collect the run's incoming state**, then hand\n * it to the host to invoke. Rendered inside the run modal, which is the chrome.\n *\n * Two shapes, because the two kinds of step start from different things:\n * - a **trigger** has no incoming state — it *is* the start — so it projects\n * its configured `fields` *definitions* into params (`fieldsToParams`), seeds\n * from their declared defaults (`seedValues`) and renders them through\n * {@link PropertyEntryForm} (chrome-less by contract, so it is mounted bare\n * here). The filled values become the run's starting state (`{ input }`), and\n * the step's **last saved values** come back pre-filled on top (T4.1.3).\n * - **everything else** is already configured, and what changes between two\n * runs is the data arriving at it. So it collects exactly what the Test tab\n * collects — {@link IncomingStateField}, the same component — and runs the\n * step with its **stored** `with` underneath. The configuration is not\n * re-collected here and is never rewritten by a run (R-I-1: the ▶ modal used\n * to render the Configure form).\n *\n * The trigger check comes first on purpose: a trigger *is* an internal node, and\n * its internal schema is the `fields` **editor**, not the fields themselves.\n *\n * `params` is fetched on **both** paths — a trigger renders them, and a\n * non-trigger needs them for the same required-params gate the Test tab applies\n * to `{...step.with, ...state}`. An app action fetches its action definition\n * exactly as `StepEditModal` does, showing \"Loading parameters…\" until it lands.\n */\nfunction StepRunCollect({\n workflowId,\n step,\n upstreamSteps,\n loop,\n onRun,\n onCancel,\n continues,\n}: {\n /** Fixture key, with `step.id` — where the remembered values are read from. */\n workflowId: string;\n step: FlowStep;\n /** Graph ancestors of this step; their saved tests are offered as seeds. */\n upstreamSteps: ExpressionStepSource[];\n /** The enclosing For each when this step is in its body (from the same projection call). */\n loop?: ExpressionLoopSource;\n /**\n * Fired when the user presses Run — with the trigger's filled values, or (for\n * every other step) the incoming-state override alone, plus the start state\n * seeded from the upstream steps' saved outputs (so the step's own\n * `{{ steps.<id>.output.<field> }}` references resolve). The two are\n * different things and stay separate: `values` are params, `state` is scope.\n */\n onRun: (values: Record<string, unknown>, state?: StepStartState) => void;\n onCancel: () => void;\n /** Present when Run continues downstream (`onRunFromNode`): the paused ids it stops before. */\n continues?: { stopAt: string[] };\n}) {\n const api = useW6WApi();\n const isTrigger = isTriggerStep(step.uses);\n const isInternal = isInternalApp(step.uses.app);\n const defs = useMemo(\n () => (isTrigger ? asFieldDefs(step.with?.fields) : []),\n [isTrigger, step.with],\n );\n\n // Known synchronously for triggers and internal nodes; `null` means \"an app\n // action, still to be fetched\" so only that path shows a loading line.\n const localParams = useMemo<ActionParam[] | null>(() => {\n if (isTrigger) return fieldsToParams(defs);\n if (isInternal) return internalNodeParams(step.uses.app, step.uses.action);\n return null;\n }, [isTrigger, isInternal, defs, step.uses.app, step.uses.action]);\n const [fetched, setFetched] = useState<ActionParam[] | null>(null);\n const params = localParams ?? fetched;\n\n // Mirrors StepEditModal's \"refetch actions + params\" effect rather than\n // inventing a second fetch pattern.\n useEffect(() => {\n if (localParams) return;\n if (!step.uses.app || !step.uses.action) {\n setFetched([]);\n return;\n }\n let canceled = false;\n setFetched(null);\n api\n .getAppActions(step.uses.app)\n .then((acts) => {\n if (canceled) return;\n setFetched(acts.find((a) => a.key === step.uses.action)?.params ?? []);\n })\n .catch(() => !canceled && setFetched([]));\n return () => {\n canceled = true;\n };\n }, [api, localParams, step.uses.app, step.uses.action]);\n\n // THE TRIGGER PATH's value bag, seeded once from its declared defaults.\n const [values, setValues] = useState<Record<string, unknown>>(() =>\n isTrigger ? seedValues(asFieldDefs(step.with?.fields)) : {},\n );\n // EVERY OTHER STEP's collect surface: the incoming-state override, as raw\n // JSON text — the same thing the Test tab collects, in the same component.\n const [stateText, setStateText] = useState(\"{}\");\n const seeds = useSeedSources(workflowId, upstreamSteps, !isTrigger);\n // The same fixtures the chips offer, projected into the run's start state —\n // one source, so what the chips SAY is upstream is what the run is GIVEN.\n const loopSeed = useLoopSeed(loop);\n const startState = startStateFromSeeds(seeds, loopSeedValue(loopSeed));\n\n // …then layered with what was entered the last time this step was tested or\n // run. `listStepTests` is oldest-first, so the LAST entry is the most recent\n // fixture — the same convention the step editor's upstream-seed effect uses.\n // Which slot is remembered follows what the surface collects: a trigger's\n // filled fields live in the fixture's `with`, an ordinary step's incoming\n // state in its `input` (that is what the Test tab writes there too).\n // An `ExprValue` (`{type:\"expr\",…}`) round-trips untouched: `FxField` derives\n // expression mode from the value, so it comes back as a chip, not as text.\n //\n // The REMEMBERED test input (`node_test_inputs`, server-side, written by every\n // Run / Test of this node) wins over the fixture: it is what was last typed on\n // ANY surface, including this one. A row that is `{}` was cleared — the form\n // stays on its declared defaults and the fixture is not consulted.\n const remembered = useRememberedTestInput(workflowId, step.id);\n const [seeded, setSeeded] = useState(false);\n const [prefilled, setPrefilled] = useState(false);\n // biome-ignore lint/correctness/useExhaustiveDependencies: seeds ONCE, when the remembered read settles — a later save must not re-seed\n useEffect(() => {\n if (!remembered.loaded) return;\n let canceled = false;\n const apply = (input: Record<string, unknown> | undefined, fromMemory: boolean) => {\n if (input && Object.keys(input).length > 0) {\n if (isTrigger) setValues((v) => ({ ...v, ...input }));\n else setStateText(JSON.stringify(input, null, 2));\n if (fromMemory) setPrefilled(true);\n }\n setSeeded(true);\n };\n if (remembered.input !== undefined) {\n apply(remembered.input, true);\n return;\n }\n api\n .listStepTests(workflowId, step.id)\n .then((tests) => {\n if (canceled) return;\n const latest = tests.length ? tests[tests.length - 1] : null;\n apply(isTrigger ? latest?.with : latest?.input, false);\n })\n // Never block or break the form: no fixture (or a failed list) just leaves\n // the declared defaults in place, silently.\n .catch(() => {\n if (!canceled) setSeeded(true);\n });\n return () => {\n canceled = true;\n };\n }, [api, workflowId, step.id, isTrigger, remembered.loaded]);\n const [formKey, setFormKey] = useState(0);\n const clearRemembered = () => {\n remembered.clear();\n setPrefilled(false);\n if (isTrigger) setValues(seedValues(defs));\n else setStateText(\"{}\");\n setFormKey((k) => k + 1);\n };\n\n // A raw-JSON draft that is not a values map (unparseable, or an array/scalar/\n // `null`) never reaches `values` — the entry form holds it back and says so\n // here. Run is a REAL execution, so it must not silently run the *previous*\n // payload while the operator is looking at a different one. The same applies\n // to the incoming-state box, which is parsed by the same rule.\n const [draftValid, setDraftValid] = useState(true);\n const state = parseStateOverride(stateText);\n const validDraft = isTrigger ? draftValid : state !== null;\n // What the run will actually be given. A non-trigger runs on its STORED\n // configuration with the incoming state merged over it — byte-for-byte what\n // the Test tab sends — so the required-params gate is applied to that, not to\n // the override alone. Never a second required-check.\n const effective = isTrigger ? values : { ...(step.with ?? {}), ...(state ?? {}) };\n const loopError = isTrigger ? null : loopSeedError(loopSeed);\n const canRun =\n !!params && seeded && validDraft && !loopError && requiredParamsFilled(params, effective);\n\n return (\n // `.w6w-stepconfig` frame + body + pinned footer (D-3): this component is a\n // direct <Modal> child, so the frame's `height:100%` resolves against the\n // dialog and only the form scrolls. The `.w6w-stack` keeps its own spacing.\n <div className=\"w6w-stepconfig\">\n <div className=\"w6w-modal-body\">\n <div className=\"w6w-stack\">\n {continues && (\n <p className=\"w6w-muted w6w-small\" data-testid=\"run-from-node-hint\">\n Runs this node, then continues through every node after it\n {continues.stopAt.length > 0 ? (\n <>\n {\" \"}\n and stops before{\" \"}\n {continues.stopAt.length === 1 ? \"the paused node\" : \"paused nodes\"}{\" \"}\n {continues.stopAt.map((id, i) => (\n <span key={id}>\n {i > 0 ? \", \" : \"\"}\n <code>{id}</code>\n </span>\n ))}\n </>\n ) : null}\n . Disabled nodes are skipped.\n </p>\n )}\n {prefilled && params !== null && seeded && <LastUsedNote onClear={clearRemembered} />}\n {params === null || !seeded ? (\n <p className=\"w6w-muted w6w-small\">\n {params === null ? \"Loading parameters…\" : \"Loading saved values…\"}\n </p>\n ) : isTrigger ? (\n <>\n <PropertyEntryForm\n // Remounted on Clear, so a raw-JSON draft is re-derived from the defaults too.\n key={formKey}\n params={params}\n values={values}\n onChange={setValues}\n onValidityChange={setDraftValid}\n />\n {params.length === 0 && (\n <span className=\"w6w-hint\">\n This trigger declares no fields — provide a sample payload to run with. It becomes\n the trigger's output state (<code>input</code>).\n </span>\n )}\n </>\n ) : (\n <>\n <p className=\"w6w-muted w6w-small\">\n Runs <code>{step.uses.action}</code> with the configuration saved on this node —\n only the incoming state changes per run. Edit the node to change how it is\n configured.\n </p>\n <LoopSeedField seed={loopSeed} />\n <IncomingStateField text={stateText} onChange={setStateText} seeds={seeds} />\n </>\n )}\n </div>\n </div>\n <div className=\"w6w-modal-actions\">\n <button type=\"button\" className=\"w6w-btn w6w-btn-ghost\" onClick={onCancel}>\n Cancel\n </button>\n {!canRun && params !== null && seeded && (\n <span className=\"w6w-muted w6w-small\">\n {loopError\n ? `${loopError} Fix it to run.`\n : !validDraft\n ? isTrigger\n ? \"The payload must be a JSON object to run.\"\n : \"The incoming state must be a JSON object to run.\"\n : isTrigger\n ? \"Fill the required fields to test.\"\n : \"This step is missing required configuration — set it on the Configure tab.\"}\n </span>\n )}\n <button\n type=\"button\"\n className=\"w6w-btn\"\n disabled={!canRun}\n // A trigger IS the start state, so it seeds nothing from upstream —\n // its filled fields go out as params (`{ input }`) exactly as before.\n onClick={() => {\n // Remembered server-side BEFORE the run, so reopening this modal (or\n // the Test tab, or the header Run) comes back prefilled whatever the\n // run's outcome. Secret literals are dropped; bindings are kept.\n remembered.save(isTrigger ? values : (state ?? {}), params ?? []);\n onRun(isTrigger ? values : (state ?? {}), isTrigger ? undefined : startState);\n }}\n >\n ▶ Run\n </button>\n </div>\n </div>\n );\n}\n\n// ── Node renderers ────────────────────────────────────────────────────────\n\n/**\n * A single connection handle, drawn to distinguish a single port from a\n * **multiple**-connection (fan-in / fan-out) port: a lone port keeps React\n * Flow's default dot, while `multiple` (cardinality > 1) renders a taller,\n * segmented bar so a node that accepts several inbound edges reads differently\n * from a single-in node (see core rfcs/node-types.md · Ports & cardinality).\n *\n * `variant === \"error\"` (T1.1.1) renders the second, visually subordinate\n * source handle every step/control node's error exit uses — `id` is what\n * lets React Flow (and `laneForSourceHandle`) tell it apart from the node's\n * ordinary, unnamed exit. The ONE shared handle component for both — no\n * second handle component and no raw inline `<Handle>` at either node card's\n * call site (`building-blocks.md`'s anti-duplication callout).\n */\n/** `@w6w/control` · `foreach` — the only card that renders the Each item handle. */\nfunction isForeachCard(step: FlowStep): boolean {\n return step.uses.app === CONTROL_APP && step.uses.action === \"foreach\";\n}\n\n/**\n * The loop dots above a body step's top-right corner: one per enclosing For each,\n * outermost first, each in that loop's colour and named on hover.\n */\nfunction LoopDots({ id }: { id: string }) {\n const { tones, loopOf } = useContext(LoopPaintCtx);\n const chain = enclosingLoops(id, loopOf);\n if (chain.length === 0) return null;\n return (\n <span className=\"w6w-loop-dots\">\n {chain.map((loop) => (\n <span\n key={loop}\n className=\"w6w-loop-dot\"\n role=\"img\"\n aria-label={`In loop · ${loop}`}\n title={`In loop · ${loop}`}\n style={{ background: loopToneVar(tones.get(loop) ?? 1) }}\n />\n ))}\n </span>\n );\n}\n\n/** A card's loop colour: only a For each carries one, for its Each item port. */\nfunction useLoopStyle(id: string): CSSProperties | undefined {\n return loopCardStyle(id, useContext(LoopPaintCtx).tones);\n}\n\nfunction PortHandle({\n type,\n position,\n multiple,\n id,\n variant,\n top,\n routeLabel,\n}: {\n type: \"source\" | \"target\";\n position: Position;\n multiple: boolean;\n id?: string;\n variant?: \"error\" | \"each\";\n top?: string;\n routeLabel?: string;\n}) {\n const nodeId = useNodeId();\n const ctrl = useContext(StepControlsCtx);\n const canAdd = !!nodeId && !!ctrl && !ctrl.readOnly;\n const add = () => {\n if (canAdd && nodeId) ctrl.onAddFromPort(nodeId, type, id);\n };\n const what =\n variant === \"error\"\n ? \"a step that handles this step's failure\"\n : variant === \"each\"\n ? \"the first step of this loop's body\"\n : type === \"target\"\n ? \"a step before this one\"\n : \"the next step\";\n return (\n <Handle\n type={type}\n position={position}\n id={id}\n className={\n variant === \"error\"\n ? \"w6w-handle-error\"\n : variant === \"each\"\n ? \"w6w-handle-each\"\n : multiple\n ? \"w6w-handle-multi\"\n : undefined\n }\n style={{\n ...(multiple ? { height: 22, borderRadius: 3, width: 8 } : {}),\n ...(top ? { top } : {}),\n }}\n // A click (no drag) adds a step from this port; a drag still draws a connection.\n onClick={canAdd ? add : undefined}\n title={\n routeLabel\n ? `${routeLabel} — drag or click to connect`\n : canAdd\n ? `Drag to empty canvas (or click) to add ${what} · drag to a port to connect`\n : variant === \"error\"\n ? \"On error — drag to route this step's failure separately\"\n : variant === \"each\"\n ? \"Each item — drag to the first step to repeat for every item\"\n : multiple\n ? type === \"target\"\n ? \"Accepts multiple incoming connections\"\n : \"Multiple outgoing connections\"\n : undefined\n }\n />\n );\n}\n\n/**\n * The node's hover toolbar: the run controls — ▶ run, ⏸ pause, ⃠ disable — then a divider, then\n * the edit controls (edit, copy, delete).\n */\nfunction NodeControls({ id, step, runnable }: { id: string; step: FlowStep; runnable?: boolean }) {\n const ctrl = useContext(StepControlsCtx);\n if (!ctrl || ctrl.readOnly) return null;\n // A run that continues downstream is a real run, so any node — flow control too — can start it.\n const canRun = runnable || ctrl.runsFromNode;\n const runLabel = ctrl.runsFromNode\n ? \"Run from this node — continues through the nodes after it\"\n : \"Test-run this node\";\n const paused = isPausedStep(step);\n const disabled = isDisabledStep(step);\n return (\n <NodeToolbar position={Position.Top} className=\"w6w-node-toolbar\">\n {canRun && (\n <button\n type=\"button\"\n className=\"w6w-node-toolbar-btn\"\n title={runLabel}\n aria-label={runLabel}\n onClick={() => ctrl.onRun(id)}\n >\n <Icon name=\"run\" size={15} />\n </button>\n )}\n <button\n type=\"button\"\n className=\"w6w-node-toolbar-btn\"\n data-testid=\"node-pause-toggle\"\n aria-pressed={paused}\n title={\n paused\n ? \"Resume — test runs go through this node\"\n : \"Pause — test runs stop before this node\"\n }\n aria-label={paused ? \"Unpause node\" : \"Pause node\"}\n onClick={() => ctrl.onTogglePause(id)}\n >\n <Icon name=\"pause\" size={15} />\n </button>\n <button\n type=\"button\"\n className=\"w6w-node-toolbar-btn\"\n data-testid=\"node-disable-toggle\"\n aria-pressed={disabled}\n title={disabled ? \"Enable — this node runs again\" : \"Disable — skip this node in every run\"}\n aria-label={disabled ? \"Enable node\" : \"Disable node\"}\n onClick={() => ctrl.onToggleDisable(id)}\n >\n <Icon name=\"ban\" size={15} />\n </button>\n <span className=\"w6w-node-toolbar-divider\" aria-hidden=\"true\" />\n <button\n type=\"button\"\n className=\"w6w-node-toolbar-btn\"\n title=\"Edit\"\n aria-label=\"Edit node\"\n onClick={() => ctrl.onEdit(id)}\n >\n <Icon name=\"edit\" size={15} />\n </button>\n <button\n type=\"button\"\n className=\"w6w-node-toolbar-btn\"\n title=\"Duplicate\"\n aria-label=\"Duplicate node\"\n onClick={() => ctrl.onDuplicate(id)}\n >\n <Icon name=\"copy\" size={15} />\n </button>\n <button\n type=\"button\"\n className=\"w6w-node-toolbar-btn danger\"\n title=\"Delete\"\n aria-label=\"Delete node\"\n onClick={() => ctrl.onDelete(id)}\n >\n <Icon name=\"trash\" size={15} />\n </button>\n </NodeToolbar>\n );\n}\n\n/** Card badge: a text glyph per mode (not colour), only with 2+ outgoing edges in a lane. */\nfunction FanOutBadge({ step, count }: { step: FlowStep; count: number }) {\n if (count < 2) return null;\n const parallel = step.fanOut === \"parallel\";\n const label = fanOutLabel(count, parallel ? \"parallel\" : \"sequential\");\n return (\n <div className=\"w6w-fanout-badge\" role=\"img\" aria-label={label} title={label}>\n <span aria-hidden=\"true\">{parallel ? \"⇉\" : \"→\"}</span> {count}\n </div>\n );\n}\n\n/** Persistent flags under a card — visible without hovering: ⏸ paused, ⃠ disabled. */\nfunction NodeFlagBadges({ step }: { step: FlowStep }) {\n const paused = isPausedStep(step);\n const disabled = isDisabledStep(step);\n if (!paused && !disabled) return null;\n return (\n <div>\n {disabled && (\n <span\n className=\"w6w-node-flag w6w-node-flag-disabled\"\n data-testid=\"step-disabled-badge\"\n role=\"img\"\n aria-label={DISABLED_LABEL}\n title={DISABLED_LABEL}\n >\n <Icon name=\"ban\" size={11} /> Disabled\n </span>\n )}\n {paused && (\n <span\n className=\"w6w-node-flag w6w-node-flag-paused\"\n data-testid=\"step-paused-badge\"\n role=\"img\"\n aria-label={PAUSED_LABEL}\n title={PAUSED_LABEL}\n >\n <Icon name=\"pause\" size={11} /> Paused\n </span>\n )}\n </div>\n );\n}\n\n/** `data-step-problem` (codes, space-joined) + `title` (tooltips, newline-joined); absent with no problems. */\nfunction problemAttrs(problems: StepProblem[] | undefined) {\n if (!problems || problems.length === 0) return {};\n return {\n \"data-step-problem\": problems.map((p) => p.code).join(\" \"),\n title: problems.map(stepProblemTooltip).join(\"\\n\"),\n };\n}\n\nfunction ProblemBadge({ problems }: { problems: StepProblem[] | undefined }) {\n if (!problems || problems.length === 0) return null;\n const tip = problems.map(stepProblemTooltip).join(\"\\n\");\n return (\n <span\n data-step-problem-badge=\"\"\n role=\"img\"\n aria-label={tip}\n title={tip}\n style={{\n position: \"absolute\",\n top: -9,\n right: -9,\n width: 18,\n height: 18,\n borderRadius: \"50%\",\n display: \"flex\",\n alignItems: \"center\",\n justifyContent: \"center\",\n background: \"var(--w6w-danger)\",\n color: \"#fff\",\n }}\n >\n <Icon name=\"warning\" size={12} />\n </span>\n );\n}\n\n/**\n * The display title of an app trigger node's trigger (`api.getAppTriggers`),\n * falling back to its key until/unless the catalog answers. Read-only: the\n * editor never subscribes anything (the server derives that on publish).\n */\nfunction useAppTriggerTitle(step: FlowStep): string {\n const api = useW6WApi();\n const key = step.uses.action;\n const [title, setTitle] = useState<string | null>(null);\n const enabled = step.uses.trigger === true;\n const app = step.uses.app;\n useEffect(() => {\n if (!enabled || !api.getAppTriggers) return;\n let canceled = false;\n api\n .getAppTriggers(app)\n .then((ts) => !canceled && setTitle(ts.find((t) => t.key === key)?.title ?? null))\n .catch(() => {});\n return () => {\n canceled = true;\n };\n }, [api, app, key, enabled]);\n return title || key;\n}\n\n/**\n * ONE `listSubscriptionsForWorkflow` read per mounted workflow, shared with every\n * trigger card through context. Re-read when the workflow's trigger nodes change\n * (a publish rewrites them) and after a Retry. Absent API member => empty map.\n */\nfunction useTriggerRegistration(value: FlowWorkflow): TriggerRegistrationValue {\n const api = useW6WApi();\n const list = api.listSubscriptionsForWorkflow;\n const retrySub = api.retrySubscriptionRegistration;\n const workflowId = value.id;\n // App triggers, plus `@w6w/webhook` nodes: their URL is `nodes.<id>.meta.config.url`.\n const triggers = [\n ...appTriggerNodesOf(value.nodes),\n ...(value.nodes ?? []).filter((n) => n.uses?.app === WEBHOOK_APP && n.uses.trigger !== true),\n ];\n const hasTrigger = triggers.length > 0;\n const triggerSig = triggers\n .map(\n (n) =>\n `${n.id}:${n.uses.app}:${n.uses.action}:${connectionIdFor(n, value.connections) ?? \"\"}`,\n )\n .join(\"|\");\n const [subs, setSubs] = useState<readonly SubscriptionSummary[]>([]);\n const byNode = useMemo(() => subscriptionsByNode(subs), [subs]);\n const [tick, setTick] = useState(0);\n // biome-ignore lint/correctness/useExhaustiveDependencies: triggerSig/tick are refetch keys\n useEffect(() => {\n if (!list || !hasTrigger) {\n setSubs([]);\n return;\n }\n let canceled = false;\n list\n .call(api, workflowId)\n .then((next) => !canceled && setSubs(next))\n .catch(() => {});\n return () => {\n canceled = true;\n };\n }, [api, list, workflowId, hasTrigger, triggerSig, tick]);\n const retry = useMemo(\n () =>\n retrySub\n ? async (subscriptionId: string) => {\n try {\n await retrySub.call(api, subscriptionId);\n } finally {\n setTick((t) => t + 1);\n }\n }\n : undefined,\n [api, retrySub],\n );\n return useMemo(() => ({ byNode, subs, retry }), [byNode, subs, retry]);\n}\n\n/** Registration state, last error, last fire and Retry for a trigger node's bound subscription. */\nfunction TriggerRegistrationBadge({ nodeId }: { nodeId: string }) {\n const { byNode, retry } = useContext(TriggerRegistrationCtx);\n const [busy, setBusy] = useState(false);\n const sub = byNode.get(nodeId);\n const d = registrationDisplay(sub, retry !== undefined);\n if (!sub || !d) return null;\n return (\n <div\n className=\"w6w-small\"\n data-trigger-registration={sub.status}\n data-tone={d.tone}\n style={{ marginTop: 3, paddingLeft: 2 }}\n >\n <span style={d.tone === \"danger\" ? { color: \"var(--w6w-danger)\" } : undefined}>\n {d.label}\n </span>\n <span className=\"w6w-muted\"> · {d.lastFire}</span>\n {d.error && (\n <div role=\"alert\" style={{ color: \"var(--w6w-danger)\" }}>\n {d.error}\n </div>\n )}\n {d.retryVisible && retry && (\n <button\n type=\"button\"\n className=\"nodrag\"\n disabled={busy}\n onClick={() => {\n setBusy(true);\n retry(sub.id)\n .catch(() => {})\n .finally(() => setBusy(false));\n }}\n >\n Retry\n </button>\n )}\n </div>\n );\n}\n\nfunction StepNodeCard({ id, data, selected }: NodeProps<StepNode>) {\n const step = data.step;\n const apps = useContext(AppsCtx);\n const app = apps.get(step.uses.app);\n // The human app name (fall back to the raw id when the app isn't in the list).\n const appName = app?.displayName || step.uses.app || \"—\";\n // An app trigger node (`uses.trigger`): entry card — no inbound port, no error\n // exit — labelled \"<App> · <trigger title>\".\n const isTrigger = isTriggerStep(step.uses);\n const triggerTitle = useAppTriggerTitle(step);\n const cardName = step.uses.trigger ? `${appName} · ${triggerTitle}` : appName;\n // Per-step ports (T2.3.1): a persisted `ports.in > 1` renders a multi-input handle.\n const ports = nodePortsForStep(step, useContext(PortsLookupCtx));\n // T1.1.1 — run-execution visual, RunStatus × StepStatus (A3). `data.stepStatus`\n // is stamped by `Inner`'s live-run repaint effect, never by `workflowToFlow`.\n const visual = stepNodeVisual(data.stepStatus ?? \"no-run\", data.runStatus);\n const fanBadge = <FanOutBadge step={step} count={useContext(FanOutCountsCtx).get(id) ?? 0} />;\n const loopStyle = useLoopStyle(id);\n return (\n <div\n className={\n [data.loopOf ? \"w6w-node-in-loop\" : \"\", isDisabledStep(step) ? \"w6w-node-disabled\" : \"\"]\n .filter(Boolean)\n .join(\" \") || undefined\n }\n data-loop-of={data.loopOf}\n style={loopStyle}\n data-disabled={isDisabledStep(step) || undefined}\n data-paused={isPausedStep(step) || undefined}\n >\n <NodeControls id={id} step={step} runnable />\n <div\n // An app trigger gets the same half-pill entry chrome as a built-in trigger.\n className={isTrigger ? \"w6w-node-trigger\" : undefined}\n data-node-kind={isTrigger ? \"trigger\" : undefined}\n data-run-status={data.stepStatus ?? \"no-run\"}\n {...problemAttrs(data.stepProblems)}\n style={{\n // `relative` so the Handles center on the CARD, not the whole node\n // (which also spans the meta line below) — keeps ports vertically centered.\n position: \"relative\",\n // Missing-connection ring; the border stays the run-status visual.\n ...(data.stepProblems ? { boxShadow: \"0 0 0 2px var(--w6w-danger)\" } : {}),\n // Selection always wins the BORDER COLOUR (unchanged from before\n // T1.1.1 — the ternary this extends); width/style/opacity keep\n // reflecting the run status underneath so a selected running/failed\n // step is still distinguishable from a selected idle one.\n border: `${visual.borderWidth}px ${visual.borderStyle} ${\n selected ? \"var(--w6w-accent)\" : visual.borderColor\n }`,\n // A disabled node reads greyed out whatever its run status (`.w6w-node-disabled`).\n opacity: isDisabledStep(step) ? 0.45 : selected ? 1 : visual.opacity,\n background: \"var(--w6w-panel)\",\n color: \"var(--w6w-text)\",\n // The trigger half-pill's radius + padding live in `.w6w-node-trigger`.\n ...(isTrigger ? {} : { borderRadius: 4, padding: \"8px 12px\" }),\n minWidth: 180,\n fontSize: 13,\n display: \"flex\",\n alignItems: \"center\",\n gap: 10,\n }}\n >\n <ProblemBadge problems={data.stepProblems} />\n {ports.in > 0 && (\n <PortHandle type=\"target\" position={Position.Left} multiple={ports.in > 1} />\n )}\n <AppIcon\n src={app?.iconSvg}\n srcDark={app?.iconSvgDark}\n brandColor={app?.brandColor}\n name={appName}\n size={28}\n />\n <div style={{ minWidth: 0 }}>\n <div style={{ fontWeight: 600 }}>{cardName}</div>\n <div className=\"w6w-muted w6w-small\" style={{ marginTop: 2 }}>\n <code>{step.uses.action || \"—\"}</code>\n </div>\n </div>\n {ports.out > 0 && (\n <>\n <PortHandle type=\"source\" position={Position.Right} multiple={ports.out > 1} />\n {!isTrigger && (\n <PortHandle\n type=\"source\"\n position={Position.Bottom}\n multiple={false}\n id={ERROR_SOURCE_HANDLE}\n variant=\"error\"\n />\n )}\n </>\n )}\n </div>\n {fanBadge}\n <NodeFlagBadges step={step} />\n {isTrigger && step.uses.trigger === true && <TriggerRegistrationBadge nodeId={id} />}\n {data.loopOf && <LoopDots id={id} />}\n {/* Meta line under the card: the step id and (when known) the app version. */}\n <div\n className=\"w6w-muted\"\n style={{ marginTop: 3, fontSize: 10, opacity: 0.75, paddingLeft: 2 }}\n >\n {step.id}\n {app?.version ? ` - v${app.version}` : \"\"}\n </div>\n {/* The step's own Notes (settings → gear icon), shown here so a reader\n can associate it with the step without opening it — human override,\n 2026-08-30. Full text in `title=` for a hover, one visual line on\n the canvas itself; `.w6w-node-notes` (styles.css) truncates. */}\n {step.notes && (\n <div className=\"w6w-muted w6w-node-notes\" title={step.notes}>\n {step.notes}\n </div>\n )}\n </div>\n );\n}\n\nfunction ControlNodeCard({ id, data, selected }: NodeProps<StepNode>) {\n const step = data.step;\n const routes = routesForStep(step);\n const isRouter = step.uses.app === ROUTER_APP;\n // An If lays its True/False ports out like a Router's routes (ifPortLayout).\n const isIf = isIfStep(step);\n const routerPorts = routes.length ? routerPortLayout(routes) : isIf ? ifPortLayout() : undefined;\n const routeKey = JSON.stringify(routes.map((r) => r.id));\n const updateNodeInternals = useUpdateNodeInternals();\n // biome-ignore lint/correctness/useExhaustiveDependencies: route identities and order change handle positions.\n useEffect(() => {\n updateNodeInternals(id);\n }, [id, routeKey, updateNodeInternals]);\n const label = internalNodeLabel(step.uses.app, step.uses.action);\n const icon = internalNodeIcon(step.uses.app, step.uses.action);\n // Per-step ports (T2.3.1): triggers have no entry (0 in, 1 out); a fan-in node\n // (e.g. aggregate, or `ports.in > 1`) renders a multi-input handle.\n const ports = nodePortsForStep(step, useContext(PortsLookupCtx));\n // A trigger is the run's ENTRY, not a step that acts: it emits the start\n // payload and has no vendor call to fail, so there is no failure of its own\n // to route — no error exit port (human report, 2026-09-01). Triggers on the\n // canvas may be internal nodes or an app trigger node (uses.trigger, D-5);\n // an app trigger renders in StepNodeCard, which guards it separately.\n const isTrigger = isTriggerStep(step.uses);\n const isForeach = isForeachCard(step);\n // T1.1.1 — same run-execution visual StepNodeCard derives; see its comment.\n const visual = stepNodeVisual(data.stepStatus ?? \"no-run\", data.runStatus);\n const fanBadge = <FanOutBadge step={step} count={useContext(FanOutCountsCtx).get(id) ?? 0} />;\n const loopStyle = useLoopStyle(id);\n return (\n <div\n className={\n [\n isForeach ? \"w6w-node-foreach\" : \"\",\n data.loopOf ? \"w6w-node-in-loop\" : \"\",\n isDisabledStep(step) ? \"w6w-node-disabled\" : \"\",\n ]\n .filter(Boolean)\n .join(\" \") || undefined\n }\n data-loop-of={data.loopOf}\n style={loopStyle}\n data-disabled={isDisabledStep(step) || undefined}\n data-paused={isPausedStep(step) || undefined}\n >\n {/* Compute/trigger nodes can be test-run; flow-control nodes only start a run that continues. */}\n <NodeControls id={id} step={step} runnable={!isControlApp(step.uses.app)} />\n <div\n className={isTrigger ? \"w6w-node-trigger\" : isRouter ? \"w6w-node-router\" : undefined}\n data-node-kind={isTrigger ? \"trigger\" : undefined}\n data-run-status={data.stepStatus ?? \"no-run\"}\n {...problemAttrs(data.stepProblems)}\n style={{\n // `relative` so the Handles center on the CARD, not the whole node\n // (which also spans the meta line below) — keeps ports vertically centered.\n position: \"relative\",\n ...(data.stepProblems ? { boxShadow: \"0 0 0 2px var(--w6w-danger)\" } : {}),\n border: `${visual.borderWidth}px ${visual.borderStyle} ${\n selected ? \"var(--w6w-accent)\" : visual.borderColor\n }`,\n // A disabled node reads greyed out whatever its run status (`.w6w-node-disabled`).\n opacity: isDisabledStep(step) ? 0.45 : selected ? 1 : visual.opacity,\n background: \"var(--w6w-panel-2)\",\n color: \"var(--w6w-text)\",\n // A trigger's half-pill radius + padding live in `.w6w-node-trigger`\n // (styles/_flow.scss): an inline value here would beat the class.\n ...(isTrigger ? {} : { borderRadius: 4, padding: \"6px 14px 6px 8px\" }),\n minWidth: 140,\n // Past three route ports the Router grows a fixed step per port\n // (routerPortLayout); border-box so that height is the whole card's.\n ...(routerPorts?.minHeight\n ? { minHeight: routerPorts.minHeight, boxSizing: \"border-box\" as const }\n : {}),\n fontSize: 13,\n display: \"flex\",\n alignItems: \"center\",\n gap: 10,\n }}\n >\n <ProblemBadge problems={data.stepProblems} />\n {ports.in > 0 && (\n <PortHandle type=\"target\" position={Position.Left} multiple={ports.in > 1} />\n )}\n {icon && <InternalIcon icon={icon} />}\n <div style={{ minWidth: 0, textAlign: \"left\" }}>\n <div style={{ fontWeight: 600 }}>{label}</div>\n <div className=\"w6w-muted w6w-small\" style={{ marginTop: 2 }}>\n <code>{step.uses.action || \"—\"}</code>\n </div>\n </div>\n {isForeach && (\n <div className=\"w6w-foreach-ports w6w-small\" aria-hidden=\"true\">\n <span>Each item</span>\n <span>Done</span>\n </div>\n )}\n {/* Route labels inside the card, each beside its right-edge handle, the\n way For each labels Each item / Done. One row per port over the full\n card height, so a row's centre is its handle's `top`. */}\n {!!routerPorts?.right.length && (\n <div\n className=\"w6w-router-ports w6w-small\"\n style={{ gridTemplateRows: `repeat(${routerPorts.right.length}, 1fr)` }}\n aria-hidden=\"true\"\n >\n {routerPorts.right.map((port) => (\n <span key={port.id} title={port.label}>\n {port.label}\n </span>\n ))}\n </div>\n )}\n {ports.out > 0 && (\n <>\n {isForeach && (\n <PortHandle\n type=\"source\"\n position={Position.Right}\n multiple={false}\n id={EACH_SOURCE_HANDLE}\n variant=\"each\"\n />\n )}\n {routerPorts ? (\n <>\n {routerPorts.right.map((port) => (\n <PortHandle\n key={port.id}\n type=\"source\"\n position={Position.Right}\n multiple={false}\n id={port.handleId}\n top={port.top}\n routeLabel={port.label}\n />\n ))}\n {routerPorts.bottom && (\n <>\n <PortHandle\n type=\"source\"\n position={Position.Bottom}\n multiple={false}\n id={routerPorts.bottom.handleId}\n routeLabel={routerPorts.bottom.label}\n />\n <span className=\"w6w-router-fallback-label w6w-small\" aria-hidden=\"true\">\n {routerPorts.bottom.label}\n </span>\n </>\n )}\n </>\n ) : (\n // A For each's Done port is named: React Flow anchors a handle-less edge\n // to the FIRST source handle, which here is Each item.\n <PortHandle\n type=\"source\"\n position={Position.Right}\n multiple={ports.out > 1}\n id={isForeach ? routeHandle(FOREACH_DONE_ROUTE) : undefined}\n />\n )}\n {!isTrigger && !isRouter && !isIf && step.uses.app !== RACE_APP && (\n <PortHandle\n type=\"source\"\n position={Position.Bottom}\n multiple={false}\n id={ERROR_SOURCE_HANDLE}\n variant=\"error\"\n />\n )}\n </>\n )}\n </div>\n {fanBadge}\n <NodeFlagBadges step={step} />\n {data.loopOf && <LoopDots id={id} />}\n {data.legacyLoop && (\n <div className=\"w6w-loop-legacy-note w6w-small\">\n This loop was converted from an older definition. Its steps after For each now run once\n per item; check the order, then save.\n </div>\n )}\n {/* Meta line under the card: the step id (internal nodes carry no version). */}\n <div\n className=\"w6w-muted\"\n style={{ marginTop: 3, fontSize: 10, opacity: 0.75, paddingLeft: 2 }}\n >\n {step.id}\n </div>\n {/* The step's own Notes — see StepNodeCard's own copy for the rationale. */}\n {step.notes && (\n <div className=\"w6w-muted w6w-node-notes\" title={step.notes}>\n {step.notes}\n </div>\n )}\n </div>\n );\n}\n\n// ── Step edit modal (Form ⇄ JSON) ─────────────────────────────────────────\n\n/**\n * The state the Test tab PREVIEWS its resolved params against: the seeded `testStartState`\n * (what the test will actually send) with, for each upstream `nodes.<id>.output` and the\n * `trigger.event` that the seeds do not carry, the value the editor already previews in the ƒx\n * Result (`sampleValues`: a persisted test's kept value or the app's declared `sample`). A seeded\n * output always wins. Only the PREVIEW reads this; the invoke is still sent `testStartState`.\n */\nexport function previewStartState(\n state: StepStartState | undefined,\n sampleValues: Record<string, unknown> | undefined,\n): StepStartState | undefined {\n if (!sampleValues) return state;\n const steps: NonNullable<StepStartState[\"steps\"]> = { ...(state?.steps ?? {}) };\n let added = false;\n for (const [ref, value] of Object.entries(sampleValues)) {\n const m = /^nodes\\.([^.]+)\\.output$/.exec(ref);\n if (!m || steps[m[1]]?.output !== undefined) continue;\n steps[m[1]] = { ...(steps[m[1]] ?? {}), output: value };\n added = true;\n }\n const event = sampleValues[\"trigger.event\"];\n const addEvent = event !== undefined && state?.trigger?.event === undefined;\n if (!added && !addEvent) return state;\n return {\n ...(state ?? {}),\n ...(added ? { steps } : {}),\n ...(addEvent ? { trigger: { ...(state?.trigger ?? {}), event } } : {}),\n };\n}\n\nexport function StepEditModal(props: StepEditModalProps) {\n // One editor for every node. An app trigger node rides the action editor:\n // Setup (app, account, trigger) · Configure (its params) · Test.\n return <ActionStepEditModal {...props} />;\n}\n\ninterface StepEditModalProps {\n workflowId: string;\n step: FlowStep;\n /** Refresh authored fields after undo/redo without remounting the Test tab. */\n restoreVersion?: number;\n /** Graph ancestors of this step (from `upstreamStateSources`); the incoming-state picker seeds from their saved tests. */\n upstreamSteps: ExpressionStepSource[];\n /** The enclosing For each when this step is in its body: seeds `state.foreach` on Test. */\n loop?: ExpressionLoopSource;\n onChange: (next: FlowStep) => void;\n onClose: () => void;\n readOnly?: boolean;\n initialView?: EditView;\n /** Most outgoing edges this node has in one lane; \"Run next nodes\" needs >= 2. */\n fanOutCount?: number;\n /** This step's own output field keys, offered by \"Write to state\" › Pick fields (free text still accepted). */\n stateOutputFields?: string[];\n /** Fired the instant the footer Test button is clicked, before the test runs (T1.1.1). */\n onTestRun?: () => void;\n /** Host-supplied problems for this step; a dangling connection locks Configure/Test, a fixable one gets a button. */\n stepProblems?: StepProblem[];\n /** The graph's other node ids — a rename onto one of them is refused with a message. */\n otherStepIds?: string[];\n}\n\nfunction ActionStepEditModal({\n workflowId,\n step: initialStep,\n restoreVersion,\n upstreamSteps,\n loop,\n onChange,\n onClose,\n readOnly,\n initialView = \"props\",\n fanOutCount = 0,\n stateOutputFields,\n onTestRun,\n stepProblems,\n otherStepIds,\n}: StepEditModalProps) {\n const api = useW6WApi();\n const apps = useContext(AppsCtx);\n const [step, setStep] = useState<FlowStep>(initialStep);\n const connectionScope = useWorkflowConnections();\n const connectionId = connectionIdFor(step, connectionScope?.connections);\n const effectiveStep = { ...step, uses: { ...step.uses, connection: connectionId } };\n // Checked against the LOCAL step so choosing another connection unblocks at once.\n const unresolvedConnection = step.uses.connectionRef !== undefined && !connectionId;\n const blocked = unresolvedConnection || isConnectionBlocked(effectiveStep, stepProblems);\n const connectionProblem = stepProblems?.find(\n (p): p is Extract<StepProblem, { code: \"unknown_connection\" }> =>\n p.code === \"unknown_connection\" && p.connection === connectionId,\n );\n const fixable = (stepProblems ?? []).filter((p) => \"fix\" in p);\n // Same shape as the add modal: Setup/Configure/Test tabs with the Configure\n // tab showing form (props) / full-step JSON (code) / params JSON\n // (params-code) / node settings (config).\n const [tab, setTab] = useState<\"setup\" | \"configure\" | \"test\">(blocked ? \"setup\" : \"configure\");\n const [configView, setConfigView] = useState<ConfigView>(\n initialView === \"json\" ? \"code\" : initialView === \"settings\" ? \"config\" : \"props\",\n );\n // The Test tab's own props/JSON toggle state (A4/D-7) — deliberately NOT\n // `configView`, which ranges over `\"params-code\"`/`\"config\"` too, neither of\n // which is in the Test tab's narrowed `[\"props\",\"code\"]` set. Always starts\n // on the row list.\n const [testView, setTestView] = useState<\"props\" | \"code\">(\"props\");\n // Draft text backing the \"code\" (full-step, read-only) view.\n const [codeText, setCodeText] = useState(() => stepToJson(initialStep));\n // Draft text backing the \"params-code\" (params-only, writable) view.\n const [testState, setTestState] = useState(\"{}\");\n // Drives the footer \"Test\" button, which triggers the body's <StepTestRun> so\n // the run + persist logic isn't duplicated across two affordances.\n const testRunRef = useRef<StepTestRunHandle>(null);\n const [testBusy, setTestBusy] = useState(false);\n const lastRestoreVersion = useRef(restoreVersion);\n useEffect(() => {\n if (lastRestoreVersion.current === restoreVersion) return;\n lastRestoreVersion.current = restoreVersion;\n setStep(initialStep);\n setCodeText(stepToJson(initialStep));\n }, [restoreVersion, initialStep]);\n\n const [params, setParams] = useState<ActionParam[] | null>(null);\n const [actions, setActions] = useState<ActionDef[] | null>(null);\n const [conns, setConns] = useState<ConnectionSummary[] | null>(null);\n const [connsFailed, setConnsFailed] = useState(false);\n const isInternal = isInternalApp(step.uses.app);\n // An app trigger node (`uses.trigger`): its \"actions\" are the app's triggers.\n const isAppTrigger = step.uses.trigger === true;\n\n // Refetch actions + params whenever the app/action identity changes. P-3:\n // this must refetch on an APP change alone (action `\"\"` included) — an\n // early return here on a missing action left `actions` holding the\n // PREVIOUS app's list, stale-ing the Action <select> after Change (D-1).\n useEffect(() => {\n if (isInternal) {\n setParams(internalNodeParams(step.uses.app, step.uses.action));\n const grouped = INTERNAL_NODES.filter(\n (node) => node.app === step.uses.app && node.groupActions && !node.hidden,\n );\n setActions(\n grouped.length\n ? grouped.map((node) => ({\n key: node.action,\n title: node.label,\n params: node.params,\n }))\n : null,\n );\n return;\n }\n if (!step.uses.app) {\n setActions(null);\n setParams([]);\n return;\n }\n let canceled = false;\n setParams(null);\n (isAppTrigger ? getTriggerDefs(api, step.uses.app) : api.getAppActions(step.uses.app))\n .then((acts) => {\n if (canceled) return;\n setActions(acts);\n setParams(\n step.uses.action ? (acts.find((a) => a.key === step.uses.action)?.params ?? []) : [],\n );\n })\n .catch(() => !canceled && setParams([]));\n return () => {\n canceled = true;\n };\n }, [api, step.uses.app, step.uses.action, isInternal, isAppTrigger]);\n\n const appSelectionRequest = useRef(0);\n useEffect(\n () => () => {\n appSelectionRequest.current++;\n },\n [],\n );\n\n const refetchConns = useCallback(() => {\n if (isInternal || !step.uses.app) return;\n api\n .listConnectionsForApp(step.uses.app)\n .then((c) => {\n setConns(c);\n setConnsFailed(false);\n })\n .catch(() => setConnsFailed(true));\n }, [api, step.uses.app, isInternal]);\n\n useEffect(() => {\n if (isInternal || !step.uses.app) return;\n let canceled = false;\n setConns(null);\n setConnsFailed(false);\n api\n .listConnectionsForApp(step.uses.app)\n .then((c) => {\n if (canceled) return;\n setConns(c);\n setConnsFailed(false);\n })\n .catch(() => !canceled && setConnsFailed(true));\n return () => {\n canceled = true;\n };\n }, [api, step.uses.app, isInternal]);\n\n const commit = useCallback(\n (next: FlowStep) => {\n setStep(next);\n onChange(next);\n },\n [onChange],\n );\n\n // A script's `{{ }}` markers become code reads when the step opens (quiet note + Undo).\n const scriptConversion = useScriptConversion({\n enabled: step.uses.app === SCRIPT_APP && !readOnly,\n values: step.with ?? {},\n onChange: (w) => commit({ ...step, with: w }),\n });\n\n const changeConfigView = (v: ConfigView) => {\n if (v === \"code\") setCodeText(stepToJson(step));\n setConfigView(v);\n };\n // Inline step rename (pencil next to the name); `updateStep` fixes up edges. A refused\n // name is reported inline (the host also drops a duplicate id, silently).\n const rename = (id: string) => {\n const err = stepNameError(id, otherStepIds ?? []);\n if (!err) commit({ ...step, id });\n return err;\n };\n\n const testable = !!step.uses.app && !!step.uses.action && !isControlApp(step.uses.app);\n // A For each's Test resolves its Items (nothing runs) and saves the sample.\n const isForeach = isForeachStep(step);\n // A manual/webhook trigger's Test tab fills its configured `fields` into\n // `{ input }` (via TriggerFillForm) rather than running the raw config.\n const isTrigger = isTriggerStep(step.uses);\n // A4/D-7: the tabs-bar toggle is enabled and narrowed to props/code ONLY on\n // this arm — the non-trigger, testable Test tab, the one that mounts\n // `<ResolvedParams>`. The trigger arm keeps the dim four (`PropertyEntryForm`\n // renders its own toggle inside `TriggerFillForm`'s body); Setup/Configure\n // are unchanged.\n const isTestPropsCode = tab === \"test\" && testable && !isTrigger;\n\n // The editing step's graph ancestors that carry a saved step-test, offered as\n // one-click seeds for the incoming state. The SAME hook the canvas ▶ Run\n // collect form uses — one implementation, so the two surfaces cannot drift.\n const seedSources = useSeedSources(\n workflowId,\n upstreamSteps,\n (testable && !isTrigger) || isForeach,\n );\n // …and the start state the test is SENT with, from those same fixtures. This\n // is what makes `{{ steps.<id>.output.<field> }}` in this step's `with`\n // resolve to what that step last produced instead of to \"\".\n const loopSeed = useLoopSeed(testable && !isTrigger ? loop : undefined);\n const testStartState = startStateFromSeeds(seedSources, loopSeedValue(loopSeed));\n const previewState = previewStartState(testStartState, useExpressionOptions().sampleValues);\n\n // The incoming state this step was last tested or run with comes back (T4.1.3\n // on this surface's own noun): the fixture's `input` slot is where both\n // surfaces write it. Applied only while the box is still untouched, so a slow\n // list can never overwrite what the operator is typing.\n //\n // The remembered test input (`node_test_inputs`, written by every Run / Test\n // of this node on any surface) wins over the fixture; a `{}` row was cleared.\n // A For each keeps its fixture-only seeding (its Test saves a sample instead).\n const rememberedTest = useRememberedTestInput(\n (testable && !isTrigger) || isForeach ? workflowId : undefined,\n step.id,\n );\n const [testPrefilled, setTestPrefilled] = useState(false);\n // biome-ignore lint/correctness/useExhaustiveDependencies: seeds ONCE, when the remembered read settles — a later save must not re-seed\n useEffect(() => {\n if ((!testable || isTrigger) && !isForeach) return;\n if (!rememberedTest.loaded) return;\n if (!isForeach && rememberedTest.input !== undefined) {\n const input = rememberedTest.input;\n if (Object.keys(input).length === 0) return;\n const next = JSON.stringify(input, null, 2);\n setTestState((cur) => (cur.trim() === \"{}\" ? next : cur));\n setTestPrefilled(true);\n return;\n }\n let canceled = false;\n api\n .listStepTests(workflowId, step.id)\n .then((tests) => {\n if (canceled) return;\n const latest = tests.length ? tests[tests.length - 1] : null;\n if (!latest?.input || Object.keys(latest.input).length === 0) return;\n const next = JSON.stringify(latest.input, null, 2);\n setTestState((cur) => (cur.trim() === \"{}\" ? next : cur));\n })\n // Best-effort, exactly like the seed effect: no fixture (or a failed list)\n // just leaves the box empty.\n .catch(() => {});\n return () => {\n canceled = true;\n };\n }, [api, workflowId, step.id, testable, isTrigger, isForeach, rememberedTest.loaded]);\n\n // The incoming-state override, and the payload it produces. The step's STORED\n // configuration is what runs; the override is merged over it. A box that is\n // not a JSON object overrides nothing (see `parseStateOverride`).\n const testOverride = isForeach ? parseForeachOverride(testState) : parseStateOverride(testState);\n const testValues = { ...(step.with ?? {}), ...(testOverride ?? {}) };\n // The resolved incoming state saved alongside the fixture — the slot the ▶ Run\n // collect form reads back, and what the upstream seed chips write into.\n const testInput = testOverride ?? {};\n const canTest = !!params && !loopSeedError(loopSeed) && requiredParamsFilled(params, testValues);\n // A For each's Test: its Items against the same start state, and the save of the sample.\n const foreachItems = isForeach\n ? resolveLoopItemsInState(testValues.items, testStartState)\n : undefined;\n const [foreachSave, setForeachSave] = useState<ForeachSave>(\"idle\");\n const changeTestState = (next: string) => {\n setTestState(next);\n setForeachSave(\"idle\");\n };\n const saveForeachTest = async () => {\n if (!foreachItems) return;\n setForeachSave(\"saving\");\n try {\n await api.saveStepTest(workflowId, step.id, foreachTestFixture(foreachItems, testInput));\n setForeachSave(\"saved\");\n } catch {\n setForeachSave(\"failed\");\n }\n };\n\n // Header icon mirrors the canvas node: the app's icon for app steps, the\n // internal glyph for triggers/actions/control nodes (same as the node cards).\n const app = apps.get(step.uses.app);\n const internalIcon = isInternal ? internalNodeIcon(step.uses.app, step.uses.action) : null;\n const titleIcon = isInternal ? (\n internalIcon ? (\n <InternalIcon icon={internalIcon} />\n ) : null\n ) : (\n <AppIcon\n src={app?.iconSvg}\n srcDark={app?.iconSvgDark}\n brandColor={app?.brandColor}\n name={app?.displayName}\n />\n );\n\n return (\n <Modal\n ariaLabel=\"Edit step\"\n titleIcon={titleIcon}\n title={<StepNameEditor value={step.id} onCommit={rename} readOnly={readOnly} />}\n onClose={onClose}\n size=\"wide\"\n >\n <div className=\"w6w-stepconfig\">\n <div className=\"w6w-tabsbar\">\n <div className=\"w6w-subtabs\">\n {([\"setup\", \"configure\", \"test\"] as const)\n .filter((t) => step.uses.app !== RACE_APP || t !== \"test\")\n .map((t) => (\n <button\n key={t}\n type=\"button\"\n className={`w6w-subtab${tab === t ? \" active\" : \"\"}`}\n disabled={blocked && t !== \"setup\"}\n onClick={() => setTab(t)}\n >\n {t === \"setup\" ? \"Setup\" : t === \"configure\" ? \"Configure\" : \"Test\"}\n </button>\n ))}\n </div>\n {isTestPropsCode ? (\n <ConfigViewToggle\n view={testView}\n views={[\"props\", \"code\"]}\n onChange={(v) => setTestView(v as \"props\" | \"code\")}\n />\n ) : (\n <ConfigViewToggle\n view={configView}\n customized={hasParamCustomization(step.with ?? {})}\n onChange={changeConfigView}\n disabled={tab !== \"configure\"}\n />\n )}\n </div>\n\n {blocked && connectionProblem && (\n <div role=\"alert\" className=\"w6w-field-error\">\n Connection {connectionProblem.connection} no longer exists — choose another to continue.\n </div>\n )}\n {fixable.length > 0 && (\n <div className=\"w6w-stepproblem-fixes\" style={{ display: \"grid\", gap: 6 }}>\n {fixable.map((p) => (\n <div\n key={p.code}\n className=\"w6w-small\"\n style={{ display: \"flex\", gap: 8, alignItems: \"center\" }}\n >\n <span>{stepProblemTooltip(p)}</span>\n <button\n type=\"button\"\n className=\"w6w-btn\"\n data-fix-code={p.code}\n disabled={readOnly}\n onClick={() => {\n const next = applyStepProblemFix(step, p);\n commit(next);\n setCodeText(stepToJson(next));\n }}\n >\n {\"fix\" in p ? p.fix.label : \"\"}\n </button>\n </div>\n ))}\n </div>\n )}\n <div className=\"w6w-stepconfig-body\">\n {tab === \"setup\" && (\n <SetupTab\n step={step}\n app={app}\n actions={actions}\n conns={conns}\n connsFailed={connsFailed}\n isInternal={isInternal}\n actionLabel={isAppTrigger ? \"Trigger\" : \"Action\"}\n readOnly={readOnly}\n onChangeAction={(action) => {\n const values = isInternal ? internalNodeDefaults(step.uses.app, action) : {};\n if (isInternal) {\n for (const param of internalNodeParams(step.uses.app, action)) {\n if (param.key in (step.with ?? {})) values[param.key] = step.with?.[param.key];\n }\n }\n commit({ ...step, uses: { ...step.uses, action }, with: values });\n }}\n onChangeTriggerEvents={(action, events) =>\n commit({\n ...step,\n uses: { ...step.uses, action },\n with: { ...step.with, actions: events },\n })\n }\n onChangeConnection={(connection) => {\n // Standalone step editors have no workflow map to write to.\n if (!connectionScope) {\n const { connectionRef: _ref, ...uses } = step.uses;\n commit({ ...step, uses: { ...uses, connection } });\n return;\n }\n const selected = selectNodeConnection(\n step,\n connection,\n connectionScope?.nodes ?? [step],\n connectionScope?.connections ?? {},\n );\n connectionScope?.setConnections(selected.connections);\n commit(selected.step);\n }}\n onChangeConnectionRef={(ref) => commit(withConnectionRef(step, ref))}\n onConnectionCreated={refetchConns}\n onChangeApp={(appId) => {\n const request = ++appSelectionRequest.current;\n if (appId === step.uses.app) {\n commit(step);\n return;\n }\n // Commit the new app and its default account together, so one undo restores both.\n const next: FlowStep = {\n ...step,\n uses: {\n app: appId,\n action: \"\",\n ...(isAppTrigger ? { trigger: true as const } : {}),\n },\n with: {},\n };\n void (isInternalApp(appId) ? Promise.resolve([]) : api.listConnectionsForApp(appId))\n .catch(() => [])\n .then((choices) => {\n if (request !== appSelectionRequest.current) return;\n const selected = defaultConnectionFor(\n next,\n choices,\n connectionScope?.nodes ?? [],\n connectionScope?.connections ?? {},\n );\n commit({ ...next, uses: { ...next.uses, ...selected } });\n });\n }}\n />\n )}\n\n {tab === \"configure\" && (\n <>\n {step.uses.app === WEBHOOK_APP &&\n api.listSubscriptionsForWorkflow &&\n api.createSubscription && (\n <WebhookUrlPanel workflowId={workflowId} step={step} readOnly={readOnly} />\n )}\n {params === null ? (\n <p className=\"w6w-muted w6w-small\">Loading parameters…</p>\n ) : configView === \"props\" ? (\n step.uses.app === RACE_APP ? (\n <p className=\"w6w-muted w6w-small\">{RACE_DESCRIPTION}</p>\n ) : step.uses.action === \"wait\" && isControlApp(step.uses.app) ? (\n <WaitEditor\n values={step.with ?? {}}\n readOnly={readOnly}\n onChange={(w) => commit({ ...step, with: w })}\n />\n ) : step.uses.action === \"if\" && isControlApp(step.uses.app) ? (\n <ConditionEditor\n values={step.with ?? {}}\n readOnly={readOnly}\n onChange={(w) => commit({ ...step, with: w })}\n />\n ) : step.uses.app === \"@w6w/stop\" ? (\n <StopEditor\n values={step.with ?? {}}\n readOnly={readOnly}\n onChange={(w) => commit({ ...step, with: w })}\n />\n ) : step.uses.app === ROUTER_APP ? (\n <RouterEditor\n values={step.with ?? {}}\n readOnly={readOnly}\n onChange={(w) => commit({ ...step, with: w })}\n />\n ) : (\n <>\n {step.uses.app === SCRIPT_APP && (\n <ScriptBindingsNotice\n values={step.with ?? {}}\n conversion={scriptConversion}\n readOnly={readOnly}\n />\n )}\n <ParamsForm\n params={params}\n values={step.with ?? {}}\n readOnly={readOnly}\n onChange={(w) => commit({ ...step, with: w })}\n dynamic={\n isInternal || !step.uses.action\n ? undefined\n : {\n appId: step.uses.app,\n actionKey: step.uses.action,\n connectionId: blocked ? undefined : connectionId,\n appName: app?.displayName,\n }\n }\n />\n </>\n )\n ) : configView === \"code\" ? (\n // Full step, read-only (D-3) — `stepToJson` is the ONE serializer,\n // shared with the two other code-view hosts.\n <JsonEditor\n value={codeText}\n onChange={() => {}}\n readOnly\n minHeight=\"260px\"\n height=\"100%\"\n aria-label={`Node ${step.id} JSON`}\n copyable\n />\n ) : configView === \"params-code\" ? (\n <ParamCustomization\n values={step.with ?? {}}\n onChange={(w) => commit({ ...step, with: w })}\n readOnly={readOnly}\n />\n ) : (\n <div className=\"w6w-stack\">\n <NodeConfigForm\n config={{ retry: step.retry, onError: step.onError, notes: step.notes }}\n onChange={(c) => commit({ ...step, ...c })}\n readOnly={readOnly}\n // A trigger has no failure of its own to retry or police —\n // same reason its card renders no error exit port.\n failureHandling={!isTrigger}\n // A `@w6w/call`/`@w6w/control` step runs no retry loop of\n // its own (core rfcs/workflow.md \"Retries come first\"; D-3).\n retryControls={!isControlApp(step.uses.app) && step.uses.app !== CALL_APP}\n />\n {SHOW_STEP_PORTS && (\n <StepPortsControl step={step} readOnly={readOnly} onChange={commit} />\n )}\n <StepFanOutControl\n step={step}\n count={fanOutCount}\n readOnly={readOnly}\n onChange={commit}\n />\n {stateWriteVisible(step) && (\n <StepStateControl\n step={step}\n inLoop={loop !== undefined}\n outputFields={stateOutputFields}\n readOnly={readOnly}\n onChange={commit}\n />\n )}\n </div>\n )}\n </>\n )}\n\n {tab === \"test\" && (\n <div className=\"w6w-stack\">\n {testable ? (\n isAppTrigger ? (\n <AppTriggerTestNote\n title={\n actions?.find((a) => a.key === step.uses.action)?.title ?? step.uses.action\n }\n app={app?.displayName ?? step.uses.app}\n />\n ) : isTrigger ? (\n <TriggerFillForm\n app={step.uses.app}\n action={step.uses.action}\n fields={step.with?.fields}\n // Same fixture key the non-trigger Test path passes to\n // <StepTestRun> below, so the values entered here are\n // remembered and come back on the canvas ▶ Run form.\n persist={{ workflowId, stepId: step.id, input: testInput }}\n // A webhook trigger's primary test is a REAL request: listen for one.\n listen={\n step.uses.app === WEBHOOK_APP &&\n api.listSubscriptionsForWorkflow &&\n api.startWebhookListen\n ? { stepWith: step.with, readOnly }\n : undefined\n }\n />\n ) : (\n <>\n <p className=\"w6w-muted w6w-small\">\n Tests <code>{step.uses.action}</code> with the configuration saved on this\n step — only the incoming state changes per run.\n </p>\n <LoopSeedField seed={loopSeed} readOnly={readOnly} />\n {testPrefilled && !readOnly && (\n <LastUsedNote\n onClear={() => {\n rememberedTest.clear();\n setTestPrefilled(false);\n setTestState(\"{}\");\n }}\n />\n )}\n <IncomingStateField\n text={testState}\n onChange={setTestState}\n seeds={seedSources}\n readOnly={readOnly}\n />\n {/* What will actually be submitted, resolved against the\n incoming state above — `testValues` (post-override),\n never `step.with` alone, so overriding the incoming\n state visibly updates these rows. */}\n {params === null ? (\n <p className=\"w6w-muted w6w-small\">Loading parameters…</p>\n ) : (\n <ResolvedParams\n params={params}\n values={testValues}\n testStartState={previewState}\n view={testView}\n literalKeys={step.uses.app === SCRIPT_APP ? SCRIPT_LITERAL_KEYS : undefined}\n />\n )}\n <StepTestRun\n ref={testRunRef}\n app={step.uses.app}\n action={step.uses.action}\n connectionId={connectionId}\n values={testValues}\n state={testStartState}\n canRun={canTest}\n hideRunButton\n persist={{ workflowId, stepId: step.id, input: testInput }}\n onBusyChange={setTestBusy}\n />\n </>\n )\n ) : isForeach ? (\n <>\n <p className=\"w6w-muted w6w-small\">\n Resolves <strong>Items</strong> against the incoming state — nothing inside the\n loop runs. <strong>Test</strong> saves the first item as this loop's sample, so\n the steps on its <strong>Each item</strong> output can pick its keys. To run the\n loop's work, test a step on <strong>Each item</strong>: it runs once, on one\n item.\n </p>\n <IncomingStateField\n text={testState}\n onChange={changeTestState}\n seeds={seedSources}\n readOnly={readOnly}\n expand={!foreachItems}\n hint={\n <>\n Paste a sample list — <code>{'[{\"id\": 1, \"name\": \"…\"}]'}</code> — or{\" \"}\n <code>{'{\"items\": […]}'}</code>. It replaces what <strong>Items</strong>{\" \"}\n resolves to, for this test only.\n </>\n }\n />\n <ForeachTestResult items={foreachItems} save={foreachSave} />\n </>\n ) : (\n <p className=\"w6w-muted w6w-small\">\n Flow-control nodes can't be tested on their own.\n </p>\n )}\n </div>\n )}\n </div>\n\n <div className=\"w6w-modal-actions w6w-stepconfig-footer\">\n {step.uses.app === RACE_APP && tab === \"configure\" ? (\n <button type=\"button\" className=\"w6w-btn\" onClick={onClose}>\n Done\n </button>\n ) : tab !== \"test\" ? (\n <button\n type=\"button\"\n className=\"w6w-btn\"\n disabled={blocked}\n onClick={() => setTab(tab === \"setup\" ? \"configure\" : \"test\")}\n >\n Next →\n </button>\n ) : (\n <>\n <button type=\"button\" className=\"w6w-btn w6w-btn-ghost\" onClick={onClose}>\n Done\n </button>\n {testable && !isTrigger && (\n // Runs the step and persists the outcome (records a run + saves\n // the fixture) via the body's <StepTestRun>, so a step test is\n // saved and re-runnable. `readOnly` viewers can't write tests.\n <button\n type=\"button\"\n className=\"w6w-btn\"\n disabled={readOnly || !canTest || testBusy}\n onClick={() => {\n // T1.1.1: before the run, so the host clears whatever run\n // the canvas was showing on the click itself.\n onTestRun?.();\n testRunRef.current?.run();\n }}\n >\n {testBusy ? \"Testing…\" : \"Test\"}\n </button>\n )}\n {isForeach && (\n <button\n type=\"button\"\n className=\"w6w-btn\"\n disabled={readOnly || !foreachItems?.length || foreachSave === \"saving\"}\n onClick={() => void saveForeachTest()}\n >\n {foreachSave === \"saving\" ? \"Testing…\" : \"Test\"}\n </button>\n )}\n </>\n )}\n </div>\n </div>\n </Modal>\n );\n}\n\n/** Default in-cardinality applied when a step is opted into multiple inbound edges. */\nconst MULTI_IN_DEFAULT = 10;\n\n/** Hidden for now (26-08-30-00-fixes item 3). Flip to `true` to restore; nothing else changes. */\nconst SHOW_STEP_PORTS = false;\n\n/**\n * Opt a step into accepting **multiple** incoming edges by setting `step.ports.in`\n * (see core rfcs/node-types.md · Ports & cardinality). Unchecking reverts to the\n * node's default (drops the persisted `ports` so an untouched step stays `1/1`).\n * Hidden for entry nodes (triggers) that declare no inbound port.\n */\nfunction StepPortsControl({\n step,\n readOnly,\n onChange,\n}: {\n step: FlowStep;\n readOnly?: boolean;\n onChange: (next: FlowStep) => void;\n}) {\n const ports = nodePortsForStep(step, useContext(PortsLookupCtx));\n // Nothing flows into a node with no entry port (e.g. a trigger).\n if (ports.in < 1) return null;\n const multiple = ports.in > 1;\n return (\n <label className=\"w6w-field\" style={{ flexDirection: \"row\", alignItems: \"center\", gap: 8 }}>\n <input\n type=\"checkbox\"\n checked={multiple}\n disabled={readOnly}\n onChange={(e) => {\n if (e.target.checked) {\n onChange({ ...step, ports: { in: MULTI_IN_DEFAULT, out: ports.out } });\n } else {\n const { ports: _drop, ...rest } = step;\n onChange(rest);\n }\n }}\n />\n <span>Accept multiple incoming connections</span>\n </label>\n );\n}\n\n/** \"Run next nodes: In sequence / In parallel\" — only meaningful with 2+ outgoing edges in a lane. */\nfunction StepFanOutControl({\n step,\n count,\n readOnly,\n onChange,\n}: {\n step: FlowStep;\n count: number;\n readOnly?: boolean;\n onChange: (next: FlowStep) => void;\n}) {\n const enabled = count >= 2;\n const mode = step.fanOut === \"parallel\" ? \"parallel\" : \"sequential\";\n return (\n <label className=\"w6w-field\">\n <span>Run next nodes</span>\n <select\n aria-label=\"Run next nodes\"\n value={mode}\n disabled={readOnly || !enabled}\n onChange={(e) => onChange(setFanOut(step, e.target.value as \"sequential\" | \"parallel\"))}\n >\n <option value=\"sequential\">In sequence</option>\n <option value=\"parallel\">In parallel</option>\n </select>\n {!enabled && (\n <span className=\"w6w-muted w6w-small\">\n Connect two or more steps after this one to choose how they run.\n </span>\n )}\n </label>\n );\n}\n\n/** Column headers over the \"Write to state\" mapping rows: which side is the step, which is state. */\nfunction StateMapHead({ to }: { to: string }) {\n return (\n <div className=\"w6w-state-map-row w6w-state-map-head\" aria-hidden=\"true\">\n <span>From this step output</span>\n <span />\n <span>{to}</span>\n </div>\n );\n}\n\nfunction StateMapArrow() {\n return (\n <span className=\"w6w-state-map-arrow\" aria-hidden=\"true\">\n →\n </span>\n );\n}\n\n/**\n * A path in this step's output: picks from the fields `resolveOutputShape` found\n * (declared output, the last test or a saved sample) and takes free text for\n * anything else. Blank means the whole output.\n */\nfunction StateOutputPathInput({\n label,\n fields,\n value,\n readOnly,\n onChange,\n}: {\n label: string;\n fields?: string[];\n value: string;\n readOnly?: boolean;\n onChange: (next: string) => void;\n}) {\n const options = useMemo(() => (fields ?? []).map((k) => ({ value: k, label: k })), [fields]);\n return (\n <Combobox\n mode=\"combobox\"\n forceSelection={false}\n aria-label={label}\n placeholder=\"Whole output, or e.g. order\"\n options={options}\n value={value}\n disabled={readOnly}\n emptyText={\n options.length > 0\n ? \"No matching field — keep typing a path\"\n : \"Test this step to list its output fields, or type a path\"\n }\n onChange={onChange}\n />\n );\n}\n\n/**\n * \"Write to state\" — where this step's output lands in the run's state tree\n * (`Node.state`). Off is the key's absence (Merge at root on Set data, R14);\n * every rule about paths and keys comes from `@w6w/expr` `validateStateConfig`.\n */\nfunction StepStateControl({\n step,\n inLoop,\n outputFields,\n readOnly,\n onChange,\n}: {\n step: FlowStep;\n inLoop: boolean;\n outputFields?: string[];\n readOnly?: boolean;\n onChange: (next: FlowStep) => void;\n}) {\n const config = stateWriteFor(step);\n const issues = validateStateConfig(config);\n const commitConfig = (next: StateWriteConfig) => onChange(setStateWrite(step, next));\n const rows = config.mode === \"pick\" && Array.isArray(config.map) ? config.map : [];\n const setRow = (i: number, patch: Partial<{ from: string; to: string }>) =>\n commitConfig({\n mode: \"pick\",\n map: rows.map((r, j) => (j === i ? { ...r, ...patch } : r)),\n });\n const setAppend = (patch: { path?: string; from?: string }) => {\n if (config.mode !== \"append\") return;\n const path = patch.path ?? config.path;\n const from = \"from\" in patch ? patch.from : config.from;\n commitConfig({ mode: \"append\", path, ...(from ? { from } : {}) });\n };\n return (\n <div className=\"w6w-field w6w-stack\">\n <label className=\"w6w-field\">\n <span>Write to state</span>\n <select\n aria-label=\"Write to state\"\n value={config.mode}\n disabled={readOnly}\n onChange={(e) => commitConfig(seedStateWrite(step, e.target.value as StateMode))}\n >\n {STATE_MODES.map((m) => (\n <option key={m} value={m}>\n {STATE_MODE_LABELS[m]}\n </option>\n ))}\n </select>\n </label>\n {config.mode === \"key\" && (\n <label className=\"w6w-field\">\n <span>To state key</span>\n <input\n type=\"text\"\n aria-label=\"State key\"\n placeholder=\"e.g. order\"\n value={config.key}\n disabled={readOnly}\n onChange={(e) => commitConfig({ mode: \"key\", key: e.target.value })}\n />\n <span className=\"w6w-hint\">\n Copies the whole step output into <code>state.<key></code>. A dotted key such as{\" \"}\n <code>order.id</code> nests.\n </span>\n </label>\n )}\n {config.mode === \"pick\" && (\n <div className=\"w6w-stack\">\n <StateMapHead to=\"To state key\" />\n {rows.length === 0 && (\n <p className=\"w6w-muted w6w-small\">No fields yet — add one below.</p>\n )}\n {rows.map((row, i) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: rows are positional; their order is the write order\n <div key={i} className=\"w6w-datavar-row w6w-state-map-row\">\n <StateOutputPathInput\n label=\"From output field\"\n fields={outputFields}\n value={row.from}\n readOnly={readOnly}\n onChange={(from) => setRow(i, { from })}\n />\n <StateMapArrow />\n <input\n type=\"text\"\n aria-label=\"To state path\"\n placeholder=\"e.g. order\"\n value={row.to}\n disabled={readOnly}\n onChange={(e) => setRow(i, { to: e.target.value })}\n />\n {!readOnly && (\n <DeleteButton\n label=\"Remove field\"\n onClick={() =>\n commitConfig({ mode: \"pick\", map: rows.filter((_, j) => j !== i) })\n }\n />\n )}\n </div>\n ))}\n {!readOnly && (\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-ghost w6w-state-map-add\"\n aria-label=\"Add field\"\n onClick={() => commitConfig({ mode: \"pick\", map: [...rows, { from: \"\", to: \"\" }] })}\n >\n + Add field\n </button>\n )}\n <span className=\"w6w-hint\">\n Copies <code>output.<path></code> into <code>state.<key></code>. Leave the\n left side blank to copy the whole output.\n </span>\n </div>\n )}\n {config.mode === \"append\" && (\n <div className=\"w6w-stack\">\n <StateMapHead to=\"Append to state list\" />\n <div className=\"w6w-datavar-row w6w-state-map-row\">\n <StateOutputPathInput\n label=\"Output field to append\"\n fields={outputFields}\n value={config.from ?? \"\"}\n readOnly={readOnly}\n onChange={(from) => setAppend({ from })}\n />\n <StateMapArrow />\n <input\n type=\"text\"\n aria-label=\"Append to state path\"\n placeholder=\"e.g. orders\"\n value={config.path}\n disabled={readOnly}\n onChange={(e) => setAppend({ path: e.target.value })}\n />\n </div>\n <span className=\"w6w-hint\">\n Appends <code>output.<path></code> to the list at <code>state.<key></code>.\n Leave the left side blank to append the whole output.\n </span>\n </div>\n )}\n {issues.length > 0 && (\n <div role=\"alert\" className=\"w6w-state-write-issues w6w-small\">\n {issues.map((issue) => (\n <div key={`${issue.code}:${issue.message}`}>{issue.message}</div>\n ))}\n </div>\n )}\n {config.mode !== \"off\" && (\n <span className=\"w6w-muted w6w-small\">\n Writing <code>null</code> deletes the key, and secrets are stored masked.\n </span>\n )}\n {inLoop && (\n <span className=\"w6w-muted w6w-small\">\n This step is inside a For each, so it writes once per item — Append collects one entry per\n item.\n </span>\n )}\n </div>\n );\n}\n\n/**\n * \"Webhook URL\" panel (I-2) — rendered only for a `WEBHOOK_APP` step, above\n * the ParamsForm/JsonEditor arms. Get-or-create against the Subscription\n * mechanism (rfcs/trigger.md), per DECISIONS.md HITL-1 + plan.md D-5:\n * - on open, lists this workflow's Subscriptions ONCE and takes the first\n * `appId === WEBHOOK_APP` entry — never re-derived client-side\n * (gap-analysis-I2 §1's `SubscriptionsPage.tsx:24-28` correctness bug is\n * deliberately not reproduced here; the server's own `webhookUrl` is the\n * only source).\n * - if one exists, its URL renders through `Copyable` exactly as\n * `TenantSettingsPage.tsx:219-227` (full URL, readOnly, aria-label) — no\n * create call.\n * - if none exists, a labelled button creates one with the step's own\n * current `with` as the Subscription's `params`, then renders the result.\n * `sub_…` ids are server-minted, so this never re-fires on its own — only\n * an explicit click creates, and only once a subscription is confirmed\n * absent.\n */\nfunction WebhookUrlPanel({\n workflowId,\n step,\n readOnly,\n}: {\n workflowId: string;\n step: FlowStep;\n readOnly?: boolean;\n}) {\n const api = useW6WApi();\n // `undefined` while the initial list is in flight; `null` once resolved\n // with no existing webhook subscription for this workflow.\n const [sub, setSub] = useState<SubscriptionSummary | null | undefined>(undefined);\n const [error, setError] = useState<string | null>(null);\n const [creating, setCreating] = useState(false);\n\n // Deliberately keyed on [api, workflowId, step.id] only — NOT on `step` (its `with`\n // changes on every keystroke in the panel below). Re-running this on a\n // `with` edit would defeat the \"never re-creates\" guarantee this panel\n // exists to provide; the list is a one-shot get, not a live subscription.\n useEffect(() => {\n const list = api.listSubscriptionsForWorkflow;\n if (!list) return;\n let canceled = false;\n list(workflowId)\n .then((subs) => {\n if (!canceled) setSub(pickWebhookSubscription(subs, step.id));\n })\n .catch((e) => !canceled && setError((e as Error).message));\n return () => {\n canceled = true;\n };\n }, [api, workflowId, step.id]);\n\n const create = () => {\n const createSubscription = api.createSubscription;\n if (!createSubscription) return;\n setError(null);\n setCreating(true);\n createSubscription(WEBHOOK_APP, step.uses.action, {\n workflowId,\n connectionId: null,\n params: step.with ?? {},\n })\n .then((created) => {\n setCreating(false);\n setSub(created);\n })\n .catch((e) => {\n setCreating(false);\n setError(e instanceof Error ? e.message : String(e));\n });\n };\n\n return (\n <div className=\"w6w-stack\">\n <p className=\"w6w-muted w6w-small\">\n <strong>Webhook URL</strong> — the address a third party posts to.\n </p>\n {error && <div className=\"w6w-result w6w-error\">{error}</div>}\n {sub?.webhookUrl ? (\n <Copyable value={sub.webhookUrl} readOnly>\n <input type=\"text\" readOnly value={sub.webhookUrl} aria-label=\"Webhook URL\" />\n </Copyable>\n ) : sub === undefined ? (\n <p className=\"w6w-muted w6w-small\">Loading…</p>\n ) : (\n !readOnly && (\n <button type=\"button\" className=\"w6w-btn\" disabled={creating} onClick={create}>\n {creating ? \"Creating…\" : \"Create webhook URL\"}\n </button>\n )\n )}\n </div>\n );\n}\n\n/**\n * The Setup tab — an App button and a Connection button, spaced apart, then\n * the step's action (a dropdown for app steps). Two independent pickers\n * (2026-08-30, superseding D-1's single combined field — see intake for the\n * exact spec): App opens a searchable app picker; Connection opens a plain\n * list of connections FOR THE CURRENT APP plus \"+ New connection\" — no\n * search, per the ask (\"just list the connections for the same app\"). Both\n * render as an anchored flyout, not inline content that pushes the rest\n * of the tab down.\n */\nfunction SetupTab({\n step,\n app,\n actions,\n conns,\n connsFailed,\n isInternal,\n actionLabel = \"Action\",\n readOnly,\n onChangeAction,\n onChangeTriggerEvents,\n onChangeConnection,\n onChangeConnectionRef,\n onChangeApp,\n onConnectionCreated,\n}: {\n step: FlowStep;\n app: AppSummary | undefined;\n actions: ActionDef[] | null;\n conns: ConnectionSummary[] | null;\n /** The connections fetch rejected — a distinct state, never \"missing\". */\n connsFailed: boolean;\n isInternal: boolean;\n /** The picked thing's name: \"Action\", or \"Trigger\" on an app trigger node. */\n actionLabel?: string;\n readOnly?: boolean;\n onChangeAction: (action: string) => void;\n onChangeTriggerEvents: (action: string, events: string[]) => void;\n onChangeConnection: (connection: string | undefined) => void;\n onChangeConnectionRef: (ref: string) => void;\n /** Fires with whatever app is picked, same or different — the caller owns\n * the same-app-is-a-no-op / different-app-clears-action-and-with decision\n * (it already owns the equivalent decision for `onChangeAction`). */\n onChangeApp: (appId: string) => void;\n /** Fires after a new connection is created via the inline \"+ New\n * connection\" flow, so the caller can refetch its (app-scoped) connection\n * list — `conns` here is a prop, this component owns no fetch of its own. */\n onConnectionCreated: () => void;\n}) {\n const eventChoices = step.uses.trigger\n ? eventbriteTriggerChoices(step.uses.app, actions, step.uses.action, step.with ?? {})\n : null;\n // Which flyout (if either) is open. Local, ephemeral UI state: the tab\n // unmounts on tab-switch, so it always starts closed. `AppPicker` fetches\n // and searches its own catalog; the connection picker below just maps\n // `conns` (already app-scoped by the caller) — neither needs its own fetch.\n const [mode, setMode] = useState<\"app\" | \"conn\" | null>(null);\n const rowRef = useRef<HTMLDivElement>(null);\n const scope = useWorkflowConnections();\n const connectionId = connectionIdFor(step, scope?.connections);\n\n return (\n <div className=\"w6w-stack\">\n {step.uses.connectionRef && !connectionId && (\n <p role=\"alert\" className=\"w6w-field-error\">\n The shared connection is missing or unbound. Choose an account.\n </p>\n )}\n <div className=\"w6w-field\">\n <span>App</span>\n {/* One field, two buttons — `[App] <-- spacer --> [Connection]`\n (2026-08-30). Always rendered, never swapped out for the picker:\n each button IS the flyout's anchor, and stays clickable the whole\n time its own flyout is open (click again to close — the toggle\n is the only way back out short of picking something or clicking\n away, since there is no third \"cancel\" control). */}\n <div className=\"w6w-app-conn-row\" ref={rowRef}>\n <button\n type=\"button\"\n className=\"w6w-app-conn-btn\"\n aria-label=\"App\"\n aria-expanded={mode === \"app\"}\n disabled={readOnly}\n onClick={() => setMode((m) => (m === \"app\" ? null : \"app\"))}\n >\n {!isInternal && app && (\n <AppIcon\n src={app.iconSvg}\n srcDark={app.iconSvgDark}\n brandColor={app.brandColor}\n name={app.displayName}\n size={20}\n />\n )}\n <span className=\"w6w-conn-label-name\">\n {isInternal ? step.uses.app : (app?.displayName ?? step.uses.app)}\n </span>\n </button>\n {!isInternal && (\n <WorkflowConnectionPicker\n step={step}\n conns={conns}\n failed={connsFailed}\n readOnly={readOnly}\n open={mode === \"conn\"}\n onOpenChange={(open) => setMode(open ? \"conn\" : null)}\n anchorRef={rowRef}\n onChangeConnection={onChangeConnection}\n onChangeConnectionRef={onChangeConnectionRef}\n onConnectionCreated={onConnectionCreated}\n />\n )}\n </div>\n\n {mode === \"app\" && (\n <AnchoredFlyout anchorRef={rowRef} onClose={() => setMode(null)}>\n <AppPicker\n onSelectApp={(a) => {\n const sameAppReselected = a.id === step.uses.app;\n onChangeApp(a.id);\n // Same app: nothing else changed (action/config untouched, per\n // the ask) — go straight to the connection picker so they can\n // still pick a different connection. Different app: the caller\n // already wiped action/connection/with; close, exactly\n // \"start over\" on the fresh (connection-less) app.\n setMode(sameAppReselected ? \"conn\" : null);\n }}\n />\n </AnchoredFlyout>\n )}\n </div>\n\n {isInternal && !actions?.length ? (\n <div className=\"w6w-field\">\n <span>Action</span>\n <div className=\"w6w-muted w6w-small\">\n <code>{step.uses.action}</code>\n </div>\n </div>\n ) : eventChoices ? (\n <EventbriteTriggerPicker\n choices={eventChoices}\n readOnly={readOnly}\n onChange={(events) => onChangeTriggerEvents(eventChoices.triggerKey, events)}\n />\n ) : (\n // biome-ignore lint/a11y/noLabelWithoutControl: Combobox renders its own <select>/<input> INSIDE this label, so the field text labels the control at runtime; the rule cannot see through the component boundary.\n <label className=\"w6w-field\">\n <span>{actionLabel}</span>\n {/* While the action manifest is still loading there is nothing to pick\n from: the current action renders as the single option, so the field\n keeps showing the step's action instead of going empty. */}\n <Combobox\n value={step.uses.action}\n disabled={readOnly || actions === null}\n onChange={onChangeAction}\n options={\n actions === null\n ? [{ value: step.uses.action, label: step.uses.action }]\n : actions.map((a) => ({ value: a.key, label: a.title ?? a.key }))\n }\n />\n </label>\n )}\n </div>\n );\n}\n","import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { AddConnectionModal } from \"./AddConnectionModal.tsx\";\nimport { AppIcon } from \"./components/AppIcon.tsx\";\nimport { Combobox } from \"./components/Combobox.tsx\";\nimport { ConfirmModal } from \"./components/ConfirmModal.tsx\";\nimport { IconButton } from \"./components/IconButton.tsx\";\nimport { Modal } from \"./components/Modal.tsx\";\nimport { resolveConnectionAppMeta } from \"./connection-app-meta.ts\";\nimport { isTriggerStep } from \"./flow-types.ts\";\nimport { useW6WApi } from \"./provider.tsx\";\nimport type { AppSummary, ConnectionSummary } from \"./types.ts\";\nimport {\n type ConnectionResourceEdit,\n type WorkflowConnectionResources,\n nextWorkflowConnectionName,\n} from \"./workflow-connections.ts\";\n\nfunction NodeKindIcon({ trigger }: { trigger: boolean }) {\n return (\n <span className=\"w6w-connection-node-kind\" role=\"img\" aria-label={trigger ? \"Trigger\" : \"Node\"}>\n <svg\n aria-hidden=\"true\"\n width=\"20\"\n height=\"20\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.8\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n >\n {trigger ? (\n <path d=\"M13 2 4 14h7l-1 8 10-12h-7l1-8Z\" />\n ) : (\n <>\n <rect x=\"5\" y=\"5\" width=\"14\" height=\"14\" rx=\"3\" />\n <path d=\"M2 12h3m14 0h3\" />\n </>\n )}\n </svg>\n </span>\n );\n}\n\n/** Manage workflow bindings; credential creation stays in the existing connection flow. */\nexport function WorkflowConnectionsPanel({\n resources,\n}: { resources: WorkflowConnectionResources }) {\n const api = useW6WApi();\n const highlightNode = resources.highlightNode;\n useEffect(() => () => highlightNode?.(null), [highlightNode]);\n const [choices, setChoices] = useState<ConnectionSummary[]>([]);\n const [loading, setLoading] = useState(true);\n const [loadError, setLoadError] = useState<string>();\n const [error, setError] = useState<string>();\n const [draft, setDraft] = useState<{\n ref?: string;\n name: string;\n connection: string;\n allNodes: boolean;\n } | null>(null);\n const [removing, setRemoving] = useState(false);\n const [creating, setCreating] = useState(false);\n const request = useRef(0);\n const refresh = useCallback(async () => {\n const version = ++request.current;\n setLoading(true);\n setLoadError(undefined);\n try {\n const rows = await api.listConnections();\n if (version !== request.current) return;\n setChoices(rows);\n return rows;\n } catch (e) {\n if (version === request.current) setLoadError((e as Error).message);\n } finally {\n if (version === request.current) setLoading(false);\n }\n }, [api]);\n useEffect(() => {\n void refresh();\n return () => {\n request.current++;\n };\n }, [refresh]);\n\n const [apps, setApps] = useState<ReadonlyMap<string, AppSummary>>(new Map());\n const appIdsKey = JSON.stringify(\n [\n ...new Set([\n ...Object.values(resources.connections).map((binding) => binding.app),\n ...choices.map((connection) => connection.appId),\n ]),\n ]\n .filter(\n (id) =>\n !resources.apps?.has(id) &&\n !choices.some((connection) => connection.appId === id && connection.app !== undefined),\n )\n .sort(),\n );\n useEffect(() => {\n let cancelled = false;\n const ids: string[] = JSON.parse(appIdsKey);\n if (loading || !ids.length) return;\n const listAppsByIds = api.listAppsByIds?.bind(api);\n const lookup = listAppsByIds\n ? Promise.all(\n Array.from({ length: Math.ceil(ids.length / 50) }, (_, index) =>\n listAppsByIds(ids.slice(index * 50, (index + 1) * 50)),\n ),\n ).then((pages) => pages.flat())\n : api.listApps?.();\n void lookup\n ?.then((rows) => {\n if (!cancelled) setApps(new Map(rows.map((app) => [app.id, app])));\n })\n .catch(() => {\n /* The app ID remains visible when catalog lookup is unavailable. */\n });\n return () => {\n cancelled = true;\n };\n }, [api, appIdsKey, loading]);\n const appMeta = (id: string) => {\n const connection =\n choices.find((c) => c.appId === id && c.app) ??\n choices.find((c) => c.appId === id && c.app !== undefined);\n const meta = connection ? resolveConnectionAppMeta(connection, apps) : apps.get(id);\n const canvasApp = resources.apps?.get(id);\n return canvasApp ? { ...meta, ...canvasApp } : meta;\n };\n const appName = (id: string) => appMeta(id)?.displayName || id;\n\n const apply = (edit: ConnectionResourceEdit) => {\n if (resources.readOnly) return false;\n try {\n resources.edit(edit);\n setError(undefined);\n return true;\n } catch (e) {\n setError((e as Error).message);\n return false;\n }\n };\n const suggestName = (conn: ConnectionSummary) => {\n return nextWorkflowConnectionName(conn.appId, resources.connections);\n };\n const close = () => {\n setDraft(null);\n setError(undefined);\n setRemoving(false);\n };\n const binding = draft?.ref ? resources.connections[draft.ref] : undefined;\n const selected = choices.find((c) => c.id === draft?.connection);\n const selectedApp = binding?.app ?? selected?.appId;\n const eligible = resources.nodes.filter((node) => node.uses.app === selectedApp);\n const users = resources.nodes.filter(\n (node) => draft?.ref !== undefined && node.uses.connectionRef === draft.ref,\n );\n const options = choices\n .filter((c) => !binding || c.appId === binding.app)\n .map((c) => ({\n value: c.id,\n label: binding ? c.displayName || c.id : `${appName(c.appId)} · ${c.displayName || c.id}`,\n }));\n if (draft?.connection && !options.some((option) => option.value === draft.connection)) {\n options.unshift({\n value: draft.connection,\n label: draft.connection.startsWith(\"zerocred:\") ? \"Built-in\" : draft.connection,\n });\n }\n const appIdentity = (app: string, size = 28) => {\n const meta = appMeta(app);\n return (\n <AppIcon\n src={meta?.iconSvg}\n srcDark={meta?.iconSvgDark}\n brandColor={meta?.brandColor}\n name={appName(app)}\n size={size}\n />\n );\n };\n const save = () => {\n if (!draft || !draft.name.trim() || !draft.connection || !selectedApp) return;\n const edit: ConnectionResourceEdit =\n draft.ref !== undefined\n ? {\n type: \"update\",\n ref: draft.ref,\n name: draft.name,\n connection: draft.connection,\n nodeIds: draft.allNodes ? eligible.map((node) => node.id) : undefined,\n }\n : { type: \"add\", name: draft.name, app: selectedApp, connection: draft.connection };\n if (apply(edit)) close();\n };\n\n return (\n <div className=\"w6w-stack\" data-testid=\"workflow-connections-panel\">\n <div className=\"w6w-workflow-connections-heading\">\n <h3>Connections</h3>\n <IconButton\n label=\"Add connection\"\n disabled={resources.readOnly}\n onClick={() => {\n setError(undefined);\n setDraft({ name: \"\", connection: \"\", allNodes: false });\n }}\n >\n <svg\n aria-hidden=\"true\"\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n >\n <path d=\"M12 5v14M5 12h14\" />\n </svg>\n </IconButton>\n </div>\n {loadError && (\n <div role=\"alert\" className=\"w6w-stack\">\n <p className=\"w6w-field-error\">Couldn’t load connections: {loadError}</p>\n <button type=\"button\" className=\"w6w-btn w6w-btn-ghost\" onClick={() => void refresh()}>\n Retry\n </button>\n </div>\n )}\n {Object.entries(resources.connections).map(([ref, resource]) => {\n const linked = resources.nodes.filter((node) => node.uses.connectionRef === ref);\n const account = choices.find((c) => c.id === resource.connection);\n const accountName =\n account?.displayName ||\n (resource.connection?.startsWith(\"zerocred:\") ? \"Built-in\" : resource.connection) ||\n \"No credentials selected\";\n return (\n <section className=\"w6w-workflow-connection\" key={ref} data-connection-resource={ref}>\n <div className=\"w6w-connection-app-heading\">\n {appIdentity(resource.app)}\n <div className=\"w6w-connection-summary\">\n <strong>{appName(resource.app)}</strong>\n <span className=\"w6w-small\">{accountName}</span>\n <span className=\"w6w-muted w6w-small\">\n {ref}\n {account?.state ? ` · ${account.state}` : \"\"}\n </span>\n </div>\n <IconButton\n icon=\"edit\"\n label={`Edit connection ${ref}`}\n disabled={resources.readOnly}\n onClick={() => {\n setError(undefined);\n setDraft({\n ref,\n name: ref,\n connection: resource.connection ?? \"\",\n allNodes: false,\n });\n }}\n />\n </div>\n {linked.length > 0 ? (\n <details\n className=\"w6w-connection-consumers\"\n onToggle={(event) => {\n if (!event.currentTarget.open) highlightNode?.(null);\n }}\n >\n <summary className=\"w6w-muted w6w-small\">\n Used by {linked.length} {linked.length === 1 ? \"node\" : \"nodes\"}\n </summary>\n <ul className=\"w6w-connection-node-list\">\n {linked.map((node) => (\n <li key={node.id}>\n {resources.focusNode ? (\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-ghost\"\n aria-label={`Show ${node.id} on canvas`}\n onClick={() => resources.focusNode?.(node.id)}\n onMouseEnter={() => highlightNode?.(node.id)}\n onMouseLeave={() => highlightNode?.(null)}\n onFocus={() => highlightNode?.(node.id)}\n onBlur={() => highlightNode?.(null)}\n >\n <NodeKindIcon trigger={isTriggerStep(node.uses)} />\n <span className=\"w6w-connection-node-label\">\n <strong>{node.uses.action}</strong>\n <span className=\"w6w-muted w6w-small\">{node.id}</span>\n </span>\n </button>\n ) : (\n <span className=\"w6w-connection-app-heading\">\n <NodeKindIcon trigger={isTriggerStep(node.uses)} />\n <span className=\"w6w-connection-node-label\">\n <strong>{node.uses.action}</strong>\n <span className=\"w6w-muted w6w-small\">{node.id}</span>\n </span>\n </span>\n )}\n </li>\n ))}\n </ul>\n </details>\n ) : (\n <span className=\"w6w-muted w6w-small\">Not used by any nodes yet.</span>\n )}\n </section>\n );\n })}\n {!Object.keys(resources.connections).length && (\n <p className=\"w6w-muted w6w-small\">No workflow connections yet.</p>\n )}\n {draft && !creating && !removing && (\n <Modal\n title={draft.ref !== undefined ? \"Edit connection\" : \"Add connection\"}\n titleIcon={selectedApp ? appIdentity(selectedApp) : undefined}\n subtitle={selectedApp ? appName(selectedApp) : undefined}\n onClose={close}\n >\n <div className=\"w6w-modal-body w6w-stack\">\n {error && (\n <p role=\"alert\" className=\"w6w-field-error\">\n {error}\n </p>\n )}\n {loadError && (\n <div role=\"alert\" className=\"w6w-stack\">\n <p className=\"w6w-field-error\">Couldn’t load credentials: {loadError}</p>\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-ghost\"\n onClick={() => void refresh()}\n >\n Retry\n </button>\n </div>\n )}\n {draft.ref !== undefined && !binding && (\n <p role=\"alert\">This workflow connection no longer exists.</p>\n )}\n <label className=\"w6w-field\">\n <span>Workflow connection name</span>\n <input\n className=\"w6w-input\"\n aria-label=\"Workflow connection name\"\n value={draft.name}\n disabled={resources.readOnly}\n onChange={(event) => setDraft({ ...draft, name: event.target.value })}\n />\n </label>\n <div className=\"w6w-field\">\n <span>{binding ? \"Credentials\" : \"Existing connection\"}</span>\n <Combobox\n aria-label={binding ? \"Credentials\" : \"Connection to add\"}\n options={options}\n value={draft.connection}\n placeholder={loading ? \"Loading connections…\" : \"Choose a connection…\"}\n disabled={resources.readOnly || loading || !!loadError}\n onChange={(connection) => {\n const choice = choices.find((c) => c.id === connection);\n setDraft({\n ...draft,\n connection,\n name: !draft.name && choice ? suggestName(choice) : draft.name,\n });\n }}\n />\n </div>\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-ghost\"\n disabled={resources.readOnly}\n onClick={() => setCreating(true)}\n >\n Create new credentials\n </button>\n {binding && (\n <>\n <p className=\"w6w-muted w6w-small\">\n {draft.allNodes\n ? `Saving applies these credentials to all ${eligible.length} ${appName(binding.app)} nodes.`\n : `Saving updates credentials for ${users.length} linked ${users.length === 1 ? \"node\" : \"nodes\"}.`}\n </p>\n {eligible.length > 0 && (\n <label className=\"w6w-connection-scope\">\n <input\n type=\"checkbox\"\n checked={\n draft.allNodes ||\n eligible.every((node) => node.uses.connectionRef === draft.ref)\n }\n disabled={\n resources.readOnly ||\n eligible.every((node) => node.uses.connectionRef === draft.ref)\n }\n onChange={(event) => setDraft({ ...draft, allNodes: event.target.checked })}\n />\n Use for all {eligible.length} {appName(binding.app)}{\" \"}\n {eligible.length === 1 ? \"node\" : \"nodes\"} in this workflow\n </label>\n )}\n <div className=\"w6w-connection-remove\">\n <button\n type=\"button\"\n className=\"w6w-btn w6w-btn-ghost\"\n disabled={resources.readOnly || users.length > 0}\n onClick={() => setRemoving(true)}\n >\n Remove from workflow\n </button>\n {users.length > 0 && (\n <p className=\"w6w-muted w6w-small\">\n Assign another connection to the linked nodes before removing this one.\n </p>\n )}\n </div>\n </>\n )}\n </div>\n <div className=\"w6w-modal-actions\">\n <button type=\"button\" className=\"w6w-btn w6w-btn-ghost\" onClick={close}>\n Cancel\n </button>\n <button\n type=\"button\"\n className=\"w6w-btn\"\n disabled={\n resources.readOnly ||\n loading ||\n !!loadError ||\n !draft.name.trim() ||\n !draft.connection ||\n !selectedApp ||\n (draft.ref !== undefined && !binding)\n }\n onClick={save}\n >\n {draft.ref !== undefined ? \"Save changes\" : \"Add to workflow\"}\n </button>\n </div>\n </Modal>\n )}\n {draft && removing && (\n <ConfirmModal\n title=\"Remove workflow connection\"\n message={`Remove “${draft.ref}” from this workflow? The saved credentials will remain available.`}\n confirmLabel=\"Remove\"\n onClose={() => setRemoving(false)}\n onConfirm={() => {\n if (draft.ref && apply({ type: \"remove\", ref: draft.ref })) close();\n else setRemoving(false);\n }}\n />\n )}\n {draft && creating && (\n <AddConnectionModal\n initialAppId={binding?.app}\n onClose={() => setCreating(false)}\n onCreated={({ connectionId }) => {\n setCreating(false);\n void refresh().then((rows) => {\n const connection = rows?.find((row) => row.id === connectionId);\n if (connection)\n setDraft((current) =>\n current\n ? {\n ...current,\n connection: connection.id,\n name: current.name || suggestName(connection),\n }\n : null,\n );\n });\n }}\n />\n )}\n </div>\n );\n}\n"],"names":["CanvasContextMenu","x","y","items","onAction","onClose","ref","useRef","pos","setPos","useState","useLayoutEffect","el","box","w","h","useEffect","_b","_a","onDown","e","onScroll","onBlur","run","item","jsx","buttons","at","focus","i","contextMenuTargets","selectedIds","nodeId","canvasMenuItems","nodeIds","readOnly","suffix","MAX_NOTES","MAX_SECTIONS","MAX_NOTE_BYTES","roundGeometry","g","out","k","v","isFinitePos","p","isFiniteSize","z","mapItems","live","useLive","it","l","position","size","withCanvasGeometry","canvas","savePosition","pruneSectionMembers","deletedNodeId","renameSectionMember","from","to","s","n","assignMembership","sectionId","moving","kept","sectionsContaining","truncateBytes","text","max","enc","used","ch","clampCanvas","persistCanvas","stored","pin","old","o","base","RESOLVED_VALUE_CLIP","clipResolvedValue","ResolvedParams","params","values","testStartState","view","literalKeys","sampleValues","nodeConfig","nodeMeta","useExpressionOptions","scope","useMemo","buildResolveScope","flat","flattenParams","effective","key","visibleRows","isParamVisible","effectiveParam","hasParamCustomization","custom","previewCustomization","object","buildResolvedJson","value","merged","jsxs","JsonEditor","ResolvedParamRow","json","rows","deepEqual","param","ResolvedVarsRow","resolveParamValue","raw","vars","dataVarRows","resolveVarsJson","resolveParamJson","label","segments","ResolvedSegments","row","Fragment","seg","ResolvedSegmentView","segment","ExprChip","ResolvedValueText","expanded","setExpanded","full","formatResolvedValue","clip","Copyable","CHIP_SIGIL","kind","refName","varLabel","languageOf","useScriptConversion","enabled","onChange","done","setDone","ran","code","r","convertCodeBindingsToReads","ScriptBindingsNotice","conversion","left","findCodeBindings","selectedFlowElements","nodes","edges","deleteFlowSelection","selection","edgeIds","removed","ordered","isForeachStep","nextNodes","nextEdges","nextCanvas","node","bridgeDeletedBodyStep","flowDeleteMessage","extraEdges","messages","deleteStepMessage","id","detached","member","loopBody","fanOutState","stepId","per","lane","edgeLane","count","setFanOut","step","mode","_drop","rest","fanOutLabel","captureFlowEdit","connections","definition","flowToWorkflow","restoreFlowEdit","snapshot","graph","workflowToFlow","FlowEditHistory","initial","limit","__publicField","group","next","previous","isFlowTextTarget","target","element","GAP","SECTION_PADDING","SECTION_LABEL_HEIGHT","nodeSize","overlaps","a","b","spaceNodes","offsets","axis","dimension","extents","placed","end","extent","start","relayoutFlow","arranged","relayoutNodes","byId","occupied","note","section","sections","memberIds","members","right","bottom","frame","obstacles","obstacle","withLabel","dy","LOOP_TONES","hashId","assignLoopTones","foreachIds","taken","tone","loopToneVar","enclosingLoops","loopOfById","chain","seen","cur","paintLoopEdges","tones","owner","EACH_SOURCE_HANDLE","loopCardStyle","own","loopPaintKey","foreach","loopPaint","PAUSED_LABEL","DISABLED_LABEL","isPausedStep","isDisabledStep","withPaused","on","ui","_paused","otherUi","nextUi","withDisabled","_disabled","pausedStopAt","steps","startId","ROOTS","loopOutputRef","foreachId","root","prefix","rewrite","refs","parts","parseRootAnchoredTemplate","hit","serializeTemplate","isDollarPath","path","changed","isWholeRef","isWrappedItems","findLoopProblems","input","wf","normalizeInput","add","list","fid","loop","definitionLoops","f","branchIds","branch","collect","stateWriteConflicts","effectiveEdges","writers","paths","staticWritePaths","effectiveStateConfig","controlOwnedIds","anchor","c","succ","reachCache","reach","stack","m","reachesRefl","parallels","CONTROL_APP","branches","branchOf","fanGroups","lanes","isEachLink","targets","concurrent","ia","ib","aa","ab","ta","tb","j","A","B","pa","pb","statePathsOverlap","cmp","findStateWriteProblems","applyStepProblemFix","problem","dragLane","fromNodeId","fromHandle","laneForSourceHandle","connectDropRefusal","source","srcStep","inBody","loopMembership","effLane","loopRefusal","STATE_MODES","STATE_MODE_LABELS","stateWriteFor","setStateWrite","config","fallback","seedStateWrite","stateWriteVisible","isControlApp","execOf","runState","offPath","rec","RUN_ENDED","stepVisualState","loops","NO_RUN_VISUAL","stepNodeVisual","state","runStatus","runEnded","edgeRunState","when","route","edgeStateFromSource","exec","output","FOREACH_DONE_ROUTE","EMPTY","isPlainObject","stateWriteOrder","ids","known","indegree","outgoing","order","ready","d","DECLARED_TYPES","declaredShape","any","segs","t","leaf","writerShapeOutput","shapes","tested","app","action","TRIGGER_APP","_c","internalNodeDef","keys","fieldsToParams","asFieldDefs","_d","shapeToSkeleton","internal","_e","def","_f","_g","declared","writerPreviewOutput","real","variablePlaceholder","type","seedTree","tree","fieldKeys","inferOutputFields","computeStateShape","anchorId","ancestors","ancestorIds","shapeOps","previewOps","writersOf","ops","computeStateWrites","foldState","set","seed","seeded","parents","children","entries","onAllPaths","preview","fields","all","valueAtPath","LABELS","NEVER_FIRED","formatLastFire","iso","registrationDisplay","sub","canRetry","failed","subscriptionsByNode","subs","appTriggerNodesOf","useAppActionDefs","api","defs","setDefs","requested","appIdsKey","isInternalApp","missing","res","loaded","prev","useAppTriggerDefs","load","portsLookupFromDefs","LANE_HINT","clashInvolvedIds","conflictId","sitting","PortsLookupCtx","createContext","FanOutCountsCtx","LoopPaintCtx","outCapMessage","cap","AppsCtx","TriggerRegistrationCtx","CardDataProvider","apps","registration","StepControlsCtx","WorkflowFlowEditor","props","ReactFlowProvider","Inner","nextCanvasId","nodeRect","onConnectionResourcesChange","height","exprOptions","project","stepProblems","onTestRun","fitViewKey","onRunFromNode","useW6WApi","appsById","triggerRegistration","useTriggerRegistration","runResult","setRunResult","initialWorkflow","centralizeConnections","setConnectionsState","connectionsRef","setConnections","useCallback","prepareStep","savedViewport","storedViewport","setNodes","onNodesChange","useNodesState","actionDefs","triggerDefs","portsLookup","setEdges","onEdgesChange","useEdgesState","selectedId","setSelectedId","initialCanvas","setCanvas","editHistory","textEditGroup","restoreVersion","setRestoreVersion","drawingSection","setDrawingSection","sectionDraft","setSectionDraft","pendingCanvasDelete","setPendingCanvasDelete","selectedEdgeId","setSelectedEdgeId","builderOpen","setBuilderOpen","builderEditGroup","editingId","setEditingId","editView","setEditView","contextMenu","setContextMenu","builderPlace","setBuilderPlace","pendingDelete","setPendingDelete","relayoutPendingFitRef","flowContainerRef","pendingConnect","setPendingConnect","screenToFlowPosition","fitView","useReactFlow","colorMode","useEffectiveTheme","nds","loopOf","stampLoopOf","stepStatus","eds","visuals","edgeVisuals","applyStepProblems","withCanvas","emitChange","canvasOverride","connectionResourceEditRef","edit","editConnectionResources","editResource","focusResourceNode","current","edge","highlightedResourceNode","highlightResourceNode","displayedNodes","resourceNodes","resourceKey","resourceAppsKey","isValidConnection","canConnect","routeFromHandle","loopNotice","setLoopNotice","loopNoticeSelRef","connectStartRef","onConnect","applyConnect","refusal","connectRefusal","holder","setLaneError","conflict","connectConflict","idClashMessage","onConnectEnd","event","connectionState","fromNode","handleType","toNode","reason","originStep","nodePortsForStep","point","addFromPort","handleId","gap","deleteStep","performDeleteSelection","performRelayout","requestRelayout","lastFitViewKeyRef","laneError","selectedEdge","setEdgeLane","me","edgeWhenConflict","relaneRefusal","setEdgeWhen","relaned","deleteEdge","duplicateSteps","sources","copies","src","newId","suggestStepId","cloned","stripBody","duplicateStep","addBuiltStep","built","isInternal","stepNameError","slugifyLabel","internalNodeLabel","newNode","loopRefused","noteLoopRefusal","wired","existingTrigger","isTriggerStep","findChainRoot","findChainTail","updateStep","prevId","draft","selected","selectNodeConnection","withConnectionRef","idChanged","renameStepInEdges","routeIds","routesForStep","onCanvasChange","addNote","notes","addSectionAt","x0","y0","cx","cy","withNew","onKey","onSectionDrop","sec","performCanvasDelete","membershipAfterDrag","dragged","persistStepRun","fixture","outcome","saved","err","runStep","performRunFromNode","isTrigger","req","patchStep","fn","togglePause","toggleDisable","performRunStep","payload","result","connectionIdFor","logs","meta","controls","div","handler","card","editingNode","editingStep","runningStep","collecting","fanOutCounts","loopKey","paint","paintedEdges","nodeTypes","StepNodeCard","ControlNodeCard","stepTestOutputs","setStepTestOutputs","stepTestMetas","setStepTestMetas","stepLoopSamples","setStepLoopSamples","stepTestRunAt","setStepTestRunAt","draftStepId","setDraftStepId","nodeSamples","setNodeSamples","nodeSampleOpenKey","canceled","persistedSamples","indexNodeSamples","shapeTiers","splitNodeOutputs","previewTiers","splitPreviewOutputs","stepShapes","trigger","runUpstreamSteps","upstreamStateSources","runSteps","upstreamState","st","excludeSelfStep","stateShape","upstreamIdsKey","tests","latest","foreachTestSample","nextMetas","nextLoopSamples","nextRunAt","declaredSamples","sampleTiers","stepSampleValues","upstreamSampleValues","stepValueSources","upstreamSampleValueSources","inheritedExprOptions","nodeConfigs","nodeConfigSources","nodeConfigValues","nodeMetaValues","mergedExprOptions","nodeMetaSampleValues","restoreEdit","direction","keepEditor","restoreEditRef","editor","active","trackActive","openContextMenu","alone","closeContextMenu","restoreFocus","onContextMenuAction","menu","WorkflowProjectProvider","ExpressionOptionsProvider","ReactFlow","ConnectionLineType","_n","membershipChanged","viewport","withViewport","sel","edgeSel","Background","Controls","ControlButton","Icon","MiniMap","Panel","IconButton","ox","oy","ROUTER_APP","NodeToolbar","Position","loopRefusalMessage","CanvasLayer","ConfirmModal","StepBuilderModal","stepBuilderUpstreamSteps","stepBuilderLoop","StepEditModal","resolveOutputShape","Modal","StepRunCollect","ResultViewer","WorkflowConnectionsContext","SCRIPT_LITERAL_KEYS","parseStateOverride","parseForeachOverride","ForeachTestResult","save","first","useLoopSeed","editedItem","setEditedItem","indexText","setIndexText","itemText","loopItemText","parsed","parseLoopSeed","loopSeedValue","loopSeedError","LoopSeedField","error","IncomingStateField","seeds","expand","hint","keyCount","hasOverride","open","setOpen","seedFrom","test","workflowId","upstreamSteps","onRun","onCancel","continues","localParams","internalNodeParams","fetched","setFetched","acts","setValues","seedValues","stateText","setStateText","useSeedSources","loopSeed","startState","startStateFromSeeds","remembered","useRememberedTestInput","setSeeded","prefilled","setPrefilled","apply","fromMemory","formKey","setFormKey","clearRemembered","draftValid","setDraftValid","validDraft","loopError","canRun","requiredParamsFilled","LastUsedNote","PropertyEntryForm","isForeachCard","LoopDots","useContext","useLoopStyle","PortHandle","multiple","variant","top","routeLabel","useNodeId","ctrl","canAdd","what","Handle","NodeControls","runnable","runLabel","paused","disabled","FanOutBadge","parallel","NodeFlagBadges","problemAttrs","problems","stepProblemTooltip","ProblemBadge","tip","useAppTriggerTitle","title","setTitle","ts","retrySub","triggers","WEBHOOK_APP","hasTrigger","triggerSig","setSubs","byNode","tick","setTick","retry","subscriptionId","TriggerRegistrationBadge","busy","setBusy","data","appName","triggerTitle","cardName","ports","visual","fanBadge","loopStyle","AppIcon","ERROR_SOURCE_HANDLE","routes","isRouter","isIf","isIfStep","routerPorts","routerPortLayout","ifPortLayout","routeKey","updateNodeInternals","useUpdateNodeInternals","icon","internalNodeIcon","isForeach","InternalIcon","port","routeHandle","RACE_APP","previewStartState","added","addEvent","ActionStepEditModal","initialStep","initialView","fanOutCount","stateOutputFields","otherStepIds","setStep","connectionScope","useWorkflowConnections","connectionId","effectiveStep","blocked","isConnectionBlocked","connectionProblem","fixable","tab","setTab","configView","setConfigView","testView","setTestView","codeText","setCodeText","stepToJson","testState","setTestState","testRunRef","testBusy","setTestBusy","lastRestoreVersion","setParams","actions","setActions","conns","setConns","connsFailed","setConnsFailed","isAppTrigger","grouped","INTERNAL_NODES","getTriggerDefs","appSelectionRequest","refetchConns","commit","scriptConversion","SCRIPT_APP","changeConfigView","rename","testable","isTestPropsCode","seedSources","previewState","rememberedTest","testPrefilled","setTestPrefilled","testOverride","testValues","testInput","canTest","foreachItems","resolveLoopItemsInState","foreachSave","setForeachSave","changeTestState","saveForeachTest","foreachTestFixture","internalIcon","titleIcon","StepNameEditor","ConfigViewToggle","SetupTab","internalNodeDefaults","events","connection","_ref","uses","appId","request","choices","defaultConnectionFor","WebhookUrlPanel","RACE_DESCRIPTION","WaitEditor","ConditionEditor","StopEditor","RouterEditor","ParamsForm","ParamCustomization","NodeConfigForm","CALL_APP","SHOW_STEP_PORTS","StepFanOutControl","StepStateControl","AppTriggerTestNote","TriggerFillForm","StepTestRun","StateMapHead","StateMapArrow","StateOutputPathInput","options","Combobox","inLoop","outputFields","issues","validateStateConfig","commitConfig","setRow","patch","setAppend","DeleteButton","_","issue","setSub","setError","creating","setCreating","pickWebhookSubscription","create","createSubscription","created","actionLabel","onChangeAction","onChangeTriggerEvents","onChangeConnection","onChangeConnectionRef","onChangeApp","onConnectionCreated","eventChoices","eventbriteTriggerChoices","setMode","rowRef","WorkflowConnectionPicker","AnchoredFlyout","AppPicker","sameAppReselected","EventbriteTriggerPicker","NodeKindIcon","WorkflowConnectionsPanel","resources","highlightNode","setChoices","loading","setLoading","loadError","setLoadError","setDraft","removing","setRemoving","refresh","version","setApps","binding","cancelled","listAppsByIds","lookup","index","pages","appMeta","resolveConnectionAppMeta","canvasApp","suggestName","conn","nextWorkflowConnectionName","close","selectedApp","eligible","users","option","appIdentity","resource","linked","account","accountName","choice","AddConnectionModal"],"mappings":";;;;;;;;;;;AAaO,SAASA,GAAkB;AAAA,EAChC,GAAAC;AAAA,EACA,GAAAC;AAAA,EACA,OAAAC;AAAA,EACA,UAAAC;AAAA,EACA,SAAAC;AACF,GAOG;AACD,QAAMC,IAAMC,GAAuB,IAAI,GACjC,CAACC,GAAKC,CAAM,IAAIC,EAAS,EAAE,MAAMT,GAAG,KAAKC,GAAG;AAGlD,EAAAS,GAAgB,MAAM;AACpB,UAAMC,IAAKN,EAAI,SACTO,IAAMD,KAAA,gBAAAA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