Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
Workflow builder round 6 — edge delete, canvas overlay, centred ports, architecture pass
Spec / source: user description (round 6), plus .ai/research/2026-08-03-builder-architecture-audit.md
Branch: feat/automation
Decisions taken by the user (2026-08-03):
- Success/Failure handles → pair straddling the card's vertical midline, floating on the right edge, independent of form height.
- Architecture pass scope → correctness + perf only: audit findings 1, 2, 4, 7. Findings 3, 5, 6, 8–17 are explicitly OUT of scope for this round.
Progress
Phase A — user-visible fixes
- Task 1: Two-click disconnect button at the centre of every edge
- Task 2: Default the trigger schedule timezone to the user's local zone
- Task 3: One composed canvas overlay — controls stacked above the minimap
- Task 4: Centre Success/Failure handles on the card's vertical midline
- Task 5: Correct the "Nothing happens if this fails" copy
- Task 6: Verify Phase A
Phase B — architecture pass (audit findings 1, 2, 4, 7)
- Task 7: Type
node.datathrough the form registry (finding 1) - Task 8:
ports.ts— one source of truth for port labels/tones/placement (finding 2) - Task 9:
selectors.ts— scalar store subscriptions, stop the drag-frame re-render storm (finding 4) - Task 10:
useDefinition/useAvailableVariableshooks (finding 7) - Task 11: Verify Phase B, add the
portsFor ≡ getNodeHandlestest, sync module AGENTS.md
Deviations from plan
- Condition ports use
anchor: "inline", but a collapsed condition still needs handles. The plan hadNodeCardrender onlyanchor === "card", which would have left a collapsed condition node unwireable.NodeCardnow rendersanchor === "card" || !formVisible, whereformVisible = isExpanded && !!children.hidePortStripis still gone; the rule lives in one commented place. conditionPathLabelreturns the kind label, not the positional one. Returning the positional label made the pill and the heading render identical text and lost the If / Else if / Otherwise distinction. It now returnsIf/Else if N/Otherwise(used by the pill AND the port), with a separate exportedconditionPathIndexfor the heading — still one implementation of each.takenNamesstayed inWorkflowNodeCardas a lazystore.getState()read inside theisTakencallback, rather than moving the logic intoInlineNodeName. Same effect, one file fewer touched, andInlineNodeName's prop contract is unchanged.- Success/Failure labels are
title+aria-label, not visible text (flagged in Task 4). - Not committed — the user authorises commits explicitly.
Dependencies
- Tasks 1, 2, 3, 5 are independent of each other and of everything else — may run in parallel.
- Task 4 must land before Task 8 (Task 8 moves the code Task 4 writes).
- Task 6 needs Tasks 1–5.
- Task 7 must land before Task 8 (Task 8's
portsForwants the narrowed node type). - Tasks 9 and 10 are independent of 7 and 8 and of each other.
- Task 11 needs Tasks 7–10.
Project commands (confirmed to exist in this repo)
pnpm exec turbo run typecheck --filter=erp # the erp package is named `erp`, NOT `@carbon/erp`
pnpm exec biome check apps/erp/app/modules/workflows
cd apps/erp && npx vitest run app/modules/workflows && cd -
Never use npm. Whole-repo typecheck OOMs — always scope with --filter.
Task 1: Two-click disconnect button at the centre of every edge
Depends on: none Files:
- Modify:
apps/erp/app/modules/workflows/ui/Builder/edges/WorkflowEdge.tsx— capturelabelX/labelY, render anEdgeLabelRendererbutton, wire it to the store. - Copy from (precedent):
apps/erp/app/modules/workflows/ui/Builder/nodes/WorkflowNodeCard.tsx:81-90and:147-161— the existing two-click "arm then delete" pattern (state + 3 s auto-disarm +onBlurdisarm). Mirror it exactly; do not invent a second idiom.
Steps:
- Extend the import from
@xyflow/reactto includeEdgeLabelRenderer:import { EdgeLabelRenderer, getSmoothStepPath, useStore } from "@xyflow/react"; - Add these imports:
import { cn, IconButton } from "@carbon/react"; import { useLingui } from "@lingui/react/macro"; import { useEffect, useState } from "react"; import { LuCircleX } from "react-icons/lu"; import { useBuilderStore } from "../context"; - Capture the label coordinates — the current code discards them:
const [edgePath, labelX, labelY] = getSmoothStepPath({ ...unchanged }); - Add the arm state and the store hooks inside
WorkflowEdgeImpl:const { t } = useLingui(); const isReadOnly = useBuilderStore((s) => s.isReadOnly); const onEdgesChange = useBuilderStore((s) => s.onEdgesChange); const [armed, setArmed] = useState(false); // Two-click disconnect, same as the node delete button. Disarms itself so a // stray click never lingers. useEffect(() => { if (!armed) return; const timer = setTimeout(() => setArmed(false), 3000); return () => clearTimeout(timer); }, [armed]); - Wrap the existing
<path>in a fragment and add the button after it.EdgeLabelRenderer's container ispointer-events: none, so the button MUST re-enable them:return ( <> <path ...unchanged /> {!isReadOnly && ( <EdgeLabelRenderer> <div className="nodrag nopan pointer-events-auto absolute" style={{ transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)` }} > <IconButton aria-label={armed ? t`Confirm disconnect` : t`Disconnect`} icon={<LuCircleX />} variant="ghost" size="sm" className={cn( "rounded-full bg-card shadow-sm", armed && "text-destructive hover:text-destructive" )} onClick={(e) => { e.stopPropagation(); if (armed) onEdgesChange([{ type: "remove", id }]); else setArmed(true); }} onBlur={() => setArmed(false)} /> </div> </EdgeLabelRenderer> )} </> ); - Leave
edgeTypesand thememowrapper as they are.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: "Tasks: 1 successful, 1 total"
Manual check (browser, when the user runs it): a circled X sits at the middle of every edge; first click turns it red, second click removes the edge; clicking elsewhere reverts it to black; no button appears on a published/read-only version.
Out of scope: hover-only visibility, edge selection styling, the keyboard Delete path
(deleteKeyCode already works and must keep working).
If EdgeLabelRenderer is not exported by the installed @xyflow/react (v12.10.2), STOP and
report — do not hand-roll an SVG <foreignObject>.
Task 2: Default the trigger schedule timezone to the user's local zone
Depends on: none Files:
- Modify:
apps/erp/app/modules/workflows/ui/Builder/config/forms/TriggerForm.tsx— line 48 and the Select at line 309. - Copy from (precedent):
apps/erp/app/components/Form/Location.tsx:70—timezone: getLocalTimeZone(). This is the repo-wide idiom;TriggerForm.tsx:48is the only file in the ERP app that callsIntl.DateTimeFormat().resolvedOptions().timeZonedirectly.
Steps:
- Add the import:
(import { getLocalTimeZone } from "@internationalized/date";@internationalized/dateis already a dependency ofapps/erp— verified viaapps/erp/app/components/Form/Location.tsx.) - In
defaultSchedule()(around line 43-50) replacetz: Intl.DateTimeFormat().resolvedOptions().timeZonewithtz: getLocalTimeZone(). - A trigger node saved before this change can carry
tz: "", which leaves the Select showing its placeholder. Immediately above the<Select>at line 309, add:
and change the Select to// A schedule saved before we defaulted the zone can carry an empty tz. const tz = schedule.tz || getLocalTimeZone();value={tz}.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: "Tasks: 1 successful, 1 total"
grep -rn "resolvedOptions().timeZone" apps/erp/app
# Expected: no output
Out of scope: adding a timezone column to the user/employee record, switching to the shared
Timezone component from @carbon/form (it is remix-validated-form-bound and will not bind to
the zustand store), and changing scheduleSchema in packages/workflows.
Task 3: One composed canvas overlay — controls stacked above the minimap
Depends on: none Files:
- Modify:
apps/erp/app/modules/workflows/ui/Builder/BuilderControls.tsx— own the whole overlay, minimap included. - Modify:
apps/erp/app/modules/workflows/ui/Builder/WorkflowBuilder.tsx— drop the wrapping<Panel>and the standalone<MiniMap>.
Root cause (verified): both are React Flow <Panel>s anchored bottom-right with the same
z-index: 5 and a 15 px margin from @xyflow/react/dist/style.css. MiniMap is itself a Panel
(default position="bottom-right", 200×150) and is rendered after the controls Panel in the
DOM, so it paints on top. The style={{ bottom: 136, right: 10 }} on the controls Panel
(WorkflowBuilder.tsx:141) is a magic-number workaround that does not survive a size change.
The fix is one Panel containing both, with the minimap's own Panel positioning neutralised.
Steps:
- In
BuilderControls.tsx, add to the imports:import { MiniMap, Panel, useReactFlow } from "@xyflow/react"; - Rename the current returned element to an inner
<div>(unchanged markup) and wrap the whole export in a single Panel that stacks the toolbar above the minimap:return ( // One Panel owns the whole bottom-right overlay. The minimap is a Panel of its // own by default, so `!static !m-0` drops it into this column instead. <Panel position="bottom-right" className="flex flex-col items-end gap-2"> <div className="flex items-center gap-0.5 rounded-lg border bg-card p-1 shadow-sm"> {...the seven existing IconButtons, unchanged...} </div> <MiniMap pannable zoomable className="!static !m-0 rounded-lg border shadow-sm" style={{ width: 180, height: 120 }} /> </Panel> ); - In
WorkflowBuilder.tsx:- Remove
MiniMapandPanelfrom the@xyflow/reactimport (keepBackground,BackgroundVariant,ReactFlow,useReactFlow). - Replace lines 141-147 (the
<Panel>wrapper,<BuilderControls>, and<MiniMap>) with a bare:<BuilderControls panOnScroll={panOnScroll} onTogglePanOnScroll={() => setPanOnScroll((p) => !p)} /> - Leave
<Background>where it is.
- Remove
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: "Tasks: 1 successful, 1 total"
grep -n "MiniMap\|Panel" apps/erp/app/modules/workflows/ui/Builder/WorkflowBuilder.tsx
# Expected: no output
Manual check: the toolbar sits directly above the minimap in the bottom-right corner with a consistent gap, nothing overlaps at any window size, and the minimap still pans and zooms.
Out of scope: adding new controls, changing the minimap's node colouring, moving the overlay to a different corner.
If !static does not neutralise the minimap's positioning (i.e. it still absolutely
positions itself), STOP and report rather than reintroducing pixel offsets — the pixel-offset
approach is what is being removed.
Task 4: Centre Success/Failure handles on the card's vertical midline
Depends on: none (but must land before Task 8) Files:
- Modify:
apps/erp/app/modules/workflows/ui/Builder/NodeCard.tsx— replace the bottom port strip with a centred overlay. - Copy from (precedent): the same file's single-port branch at
NodeCard.tsx:116-123and the condition node'sPortAnchortreatment atapps/erp/app/modules/workflows/ui/Builder/PortAnchor.tsx— a<Handle>inside aposition: relativebox, with zero pixel measurement. React Flow measures handle bounds from the DOM and divides by zoom itself; anygetBoundingClientRecthere is a regression. See.ai/lessons.md— "Never hand-measure React Flow handle positions".
Current wrong behaviour: NodeCard.tsx:157-185 renders multi-port nodes as a labelled strip
appended after the form body, so Success/Failure end up at the bottom of a tall card instead of
on its midline.
Steps:
- Add
relativeto the card root's className (line ~101), so the overlay anchors to the card:"relative rounded-lg border bg-card shadow-sm transition-shadow", - Delete the entire
{ports.length > 1 && !hidePortStrip && ( ... )}block (lines 157-185), including thePORT_LABEL_TONEmap at lines 27-31 which becomes unused. - In its place — still inside the card root, as the last child — add the centred overlay:
{ports.length > 1 && !hidePortStrip && ( // Handles straddle the card's midline instead of trailing the body, so a tall // form never pushes them to the bottom. Zero-width rows: the Handle's own // `right: -4px` lands it on the card border. <div className="pointer-events-none absolute inset-y-0 right-0 flex flex-col justify-center gap-6"> {ports.map((port) => ( <div key={port.id} className="pointer-events-auto relative"> <Handle type="source" position={Position.Right} id={port.id} title={port.label} aria-label={port.label} className={handleClass(port.tone)} /> </div> ))} </div> )} PORT_LABEL_TONEis now unused — remove it.handleClass,HANDLE_CLASS,HANDLE_BASEandHANDLE_TONEall stay.- Do NOT touch the
useUpdateNodeInternalseffect at lines 89-96 — it is what tells React Flow to re-measure when the port set or expanded state changes, and it is still required.
Note on the dropped labels: the visible "SUCCESS"/"FAILURE" text is replaced by the green/red
dot colour plus a native tooltip (title) and an accessible name (aria-label). Rendering the
text inside the card would sit it on top of the form fields; rendering it outside would sit it on
top of the outgoing edge. Flag this to the user in the summary — a hover-revealed chip is the
fallback if they want the words back.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: "Tasks: 1 successful, 1 total"
grep -n "getBoundingClientRect" apps/erp/app/modules/workflows/ui/Builder/NodeCard.tsx
# Expected: no output
Manual check: on an action and a lookup node, expanded and collapsed, the green Success dot sits just above the card's vertical centre and the red Failure dot just below it; both stay put while zooming and while the form grows; the condition node is unchanged (its handles still centre on each path block); edges still attach to the right dot.
Out of scope: the condition node's inline PortAnchors, the single-port branch, the target
(in) handle, and hidePortStrip — that flag is removed in Task 8, not here.
Task 5: Correct the "Nothing happens if this fails" copy
Depends on: none Files:
- Modify:
apps/erp/app/modules/workflows/ui/Builder/nodes/WorkflowNodeCard.tsx:187-192
Why (verified against the engine, not assumed): the sentence is wrong in the two ways that matter.
- The step is written as
Failedwith its error text —packages/jobs/src/workflows/engine/execute.ts:186. - The whole run is marked
Failed—execute.ts:446-448setsfailed = truefromoutcome.status, andexecute.ts:460-463settles the run. So "nothing happens" is the opposite of the truth. - Wiring a failure edge does not make the run green;
failedis set from the outcome, never from whether an edge exists. A failure edge only lets recovery steps run before the run settles as Failed. - What actually stops is the continuation on that path:
outgoing()returns[](packages/jobs/src/workflows/engine/walk.ts:38-40). Sibling branches already on the frontier still run.
Steps:
- Replace the
<Trans>content on line 190 with:<Trans>No failure path — the run stops here and is marked failed</Trans> - Leave the warning's trigger condition (
hasFailureHandle && !hasFailureEdge), its styling and its icon unchanged.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: "Tasks: 1 successful, 1 total"
grep -rn "Nothing happens if this fails" apps/erp/app packages
# Expected: no output outside packages/locale/locales/**/*.po
Out of scope: changing engine behaviour, adding retries, changing when the warning shows, and
running pnpm lingui:extract (it dumps ~120k lines of stale .po churn on this branch — leave
the catalogues to the pre-commit hook).
Task 6: Verify Phase A
Depends on: Tasks 1, 2, 3, 4, 5 Files: none
Steps:
- Run all three commands below from the repo root.
- Fix only error-severity biome findings and any warning introduced by Tasks 1–5. The repo
has ~419 pre-existing warnings — leave them.
NodeCard.tsxhas one known false-positivelint/correctness/useExhaustiveDependencieson theisExpandedprop; leave it.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: "Tasks: 1 successful, 1 total"
pnpm exec biome check apps/erp/app/modules/workflows
# Expected: "Found 1 warning" (the known NodeCard.tsx false positive), zero errors
cd apps/erp && npx vitest run app/modules/workflows && cd -
# Expected: "Test Files 1 passed (1)" and "Tests 15 passed (15)"
Out of scope: committing. Do not commit — the user authorises commits explicitly.
Task 7: Type node.data through the form registry (audit finding 1)
Depends on: none (but must land before Task 8) Files:
- Modify:
apps/erp/app/modules/workflows/ui/Builder/config/forms/index.ts— narrowNodeFormPropsby kind. - Modify:
apps/erp/app/modules/workflows/ui/Builder/nodes/WorkflowNodeCard.tsx:184— pass the narrowed node. - Modify: all six forms in
apps/erp/app/modules/workflows/ui/Builder/config/forms/— delete the hand-writtenconst data = node.data as {…}cast.
The problem (verified): BuilderNode.data is Record<string, unknown>
(apps/erp/app/modules/workflows/types.ts:4-10), so every form re-declares the node's data shape
by hand — six copies of a schema that lives in packages/workflows. Renaming a field in
packages/workflows/src/definition/schema.ts leaves typecheck --filter=erp green while the
builder writes a definition the publish validator rejects. The six copies are at
TriggerForm.tsx:337-341, ConditionForm.tsx:127, EntityForm.tsx:121-124,
LookupForm.tsx:54-58, FilterForm.tsx:48-52, ActionForm.tsx:224-228.
Steps:
- In
config/forms/index.ts, make the props generic over the node kind:import type { WorkflowNode, WorkflowNodeType } from "@carbon/workflows"; export type NodeFormProps<K extends WorkflowNodeType = WorkflowNodeType> = { node: Omit<BuilderNode, "type" | "data"> & { type: K; data: Extract<WorkflowNode, { type: K }>["data"]; }; /** Issues for this node, so forms can highlight the affected field. */ issues?: WorkflowIssue[]; }; /** Spelled out: a missing kind is a TS2741, not a blank panel. */ export const NODE_FORMS: { [K in WorkflowNodeType]: ComponentType<NodeFormProps<K>>; } = { trigger: TriggerForm, condition: ConditionForm, entity: EntityForm, lookup: LookupForm, filter: FilterForm, action: ActionForm }; - Each form's signature becomes
({ node }: NodeFormProps<"trigger">)(etc. per kind). - Delete each form's
const data = node.data as {…}line and usenode.datadirectly. Remove the?? []/?? ""fallbacks only where the zod schema has a.default()for that key (packages/workflows/src/definition/schema.ts:34-98—events,origin,paths,inputs,returns,match,clauses,combinator,batchall have one, so those keys are never absent on a parsed node). Keep any other fallback. - Delete
LookupForm.tsx's privateWorkingMatchtype (lines 19-23) — it islookupMatchSchemawithvaluewidened. Use the sharedLookupMatchand widen only at the single edit site withPartial<…>. Keep thematchToClause/clauseToMatchconverters. - In
WorkflowNodeCard.tsx,<Form>(line 184) is dispatched off aWorkflowNodeTypevalue, so TypeScript cannot prove the component and the props share the sameK. Resolve it in the one place with a single, commented cast rather than sprinkling casts:
and pass a node object that carries// One narrowing site: the registry is keyed by kind but dispatched from a value. const Form = NODE_FORMS[node.type] as ComponentType<NodeFormProps>;name/expandedfrombuilderNodealongside the narrowedtype/datafromasWorkflowNode.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: "Tasks: 1 successful, 1 total"
grep -rn "node.data as" apps/erp/app/modules/workflows/ui/Builder/config/forms
# Expected: no output
Out of scope: changing anything in packages/workflows, changing BuilderNode in
apps/erp/app/modules/workflows/types.ts (React Flow requires the index-signature-compatible
Record<string, unknown> there), and audit finding 5 (field-level issues).
If narrowing BuilderNode breaks React Flow's Node<…> constraint, STOP and report — do not
weaken NodeFormProps back to Record<string, unknown>.
Task 8: ports.ts — one source of truth for port labels, tones and placement (audit finding 2)
Depends on: Tasks 4 and 7 Files:
- Create:
apps/erp/app/modules/workflows/ui/Builder/ports.ts - Modify:
apps/erp/app/modules/workflows/ui/Builder/nodes/WorkflowNodeCard.tsx— deleteportsFor,PORT_LABEL,PORT_TONE,hidePortStripand the secondgetNodeHandlescall. - Modify:
apps/erp/app/modules/workflows/ui/Builder/NodeCard.tsx— filter onanchor, drop thehidePortStripprop. - Modify:
apps/erp/app/modules/workflows/ui/Builder/config/forms/ConditionForm.tsx— take the pill/heading text from the shared helper instead of its localKIND_PILL+pathIndex.
The problem (verified, with a live divergence): four files decide what a port is called and
where it renders — getNodeHandles (packages/workflows/src/definition/nodes.ts:567, which
decides which handles exist and is correct), portsFor() (WorkflowNodeCard.tsx:36-53),
NodeCard's port rendering, and ConditionForm's inline <PortAnchor> (line 257) — glued by the
hidePortStrip boolean that exists only to stop two of them double-rendering the same ids. Today
the same condition port reads "Otherwise" when collapsed (WorkflowNodeCard.tsx:42,
untranslated) and "Else" when expanded (ConditionForm.tsx:115-119, translated), with two
separate implementations of the path index (ConditionForm.tsx:205-209 vs the inline
filter(...).findIndex(...) at WorkflowNodeCard.tsx:43).
Steps:
- Create
ports.tsexporting:export type PortAnchorKind = "card" | "inline"; export type BuilderPort = { id: string; label: string; tone: PortTone; anchor: PortAnchorKind }; /** The one place a handle gets a label, a tone and a place to render. */ export function portsFor(node: WorkflowNode, t: TFn): BuilderPort[]; /** One implementation of "what is this condition path called". */ export function conditionPathLabel(paths: ConditionPath[], pathId: string, t: TFn): string;portsForMUST derive its ids fromgetNodeHandles(node)and nothing else — never a hand-written list. This is the invariantapps/erp/app/modules/workflows/AGENTS.mdcalls out.- Key the label/tone maps off the exported constants
DEFAULT_HANDLE,SUCCESS_HANDLE,FAILURE_HANDLE(packages/workflows/src/definition/schema.ts:136-138), not the string literals"out"/"success"/"failure"currently hard-coded atWorkflowNodeCard.tsx:23-32. - Condition paths get
anchor: "inline"; everything else getsanchor: "card". tis the function fromuseLingui(). Pass it in rather than calling the hook, soports.tsstays callable outside React.
NodeCardrenders onlyports.filter(p => p.anchor === "card"), using the Task 4 overlay for two-or-more and the existing centred single<Handle>for exactly one. Delete thehidePortStripprop fromNodeCardPropsand from the call site.ConditionFormcallsconditionPathLabel(...)for both the pill and theposLabelheading; delete its localKIND_PILLmap andpathIndex()helper.<PortAnchor>stays where it is (it already centres correctly on the whole path block and the user approved it).- In
WorkflowNodeCard, derivehasFailureHandlefrom the ports array (ports.some(p => p.id === FAILURE_HANDLE)) instead of callinggetNodeHandlesa second time at line 102.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: "Tasks: 1 successful, 1 total"
grep -rn "hidePortStrip\|KIND_PILL" apps/erp/app/modules/workflows
# Expected: no output
Manual check: a condition path shows the same word on its pill and in its port tooltip, collapsed and expanded, and that word is translated.
Out of scope: changing getNodeHandles or anything else in packages/workflows; the
NODE_KIND_META i18n sweep (audit finding 11).
Task 9: selectors.ts — scalar store subscriptions (audit finding 4)
Depends on: none Files:
- Create:
apps/erp/app/modules/workflows/ui/Builder/selectors.ts - Modify:
apps/erp/app/modules/workflows/ui/Builder/nodes/WorkflowNodeCard.tsx:62-79, 117-119 - Modify:
apps/erp/app/modules/workflows/ui/Builder/BuilderControls.tsx:22, 55, 64 - Modify:
apps/erp/app/modules/workflows/ui/Builder/config/InlineNodeName.tsx— computetakenNameslazily. - Copy from (precedent):
WorkflowBuilder.tsx:47-57andAutosave.tsx:30— the correct "read once in a callback viauseBuilderStoreApi, don't subscribe" pattern already used in this codebase.
The problem (verified): WorkflowNodeCard takes seven store subscriptions, three of which
read the whole nodes array (:72, :76, :77-79). onNodesChange (store.ts:69-90) replaces
nodes on every React Flow position change — i.e. every pointer move during a drag — so dragging
one node re-renders every card, and each re-render then runs getNodeHandles twice, an
edges.some() over all edges, and a full new Set(allNodes.filter(...).map(...)). That is
O(nodes² + nodes·edges) per animation frame. memo(WorkflowNodeCardImpl) cannot help, because the
subscriptions are inside the component.
Steps:
- Create
selectors.ts:
These return primitives (or a stable element reference), so zustand's defaultexport const selectNode = (id: string) => (s: BuilderState) => s.nodes.find((n) => n.id === id); export const selectTriggerCount = (s: BuilderState) => s.nodes.reduce((n, x) => n + (x.type === "trigger" ? 1 : 0), 0); export const selectHasEdgeFrom = (id: string, handle: string) => (s: BuilderState) => s.edges.some((e) => e.source === id && e.sourceHandle === handle);Object.iscomparison stops the re-render at the subscription. WorkflowNodeCardusesselectTriggerCountandselectHasEdgeFromand stops subscribing tostate.edges(line 72) andstate.nodes(line 76).- Delete the eager
takenNamesSet (WorkflowNodeCard.tsx:117-119).InlineNodeNameonly needs it while editing — have it build the Set inside itsisTakencallback fromuseBuilderStoreApi().getState().nodes. Adjust theisTakenprop's plumbing accordingly. BuilderControlssubscribes to the wholenodesarray (line 22) only to iterate ids in two onClick handlers. Replace withuseBuilderStoreApi()and readstore.getState().nodesinside each handler. Keep thefor...ofloops — an arrow returning a value there tripslint/suspicious/useIterableCallbackReturn.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: "Tasks: 1 successful, 1 total"
pnpm exec biome check apps/erp/app/modules/workflows
# Expected: zero errors; no new warnings beyond the known NodeCard.tsx one
grep -n "useBuilderStore((s\?t\?a\?t\?e\?) => s\?t\?a\?t\?e\?.nodes)" apps/erp/app/modules/workflows/ui/Builder/nodes/WorkflowNodeCard.tsx apps/erp/app/modules/workflows/ui/Builder/BuilderControls.tsx
# Expected: no output
Manual check: dragging a node on a 10+ node workflow is visibly smooth; renaming still refuses a duplicate name; Collapse-all / Expand-all still work.
Out of scope: memoising WorkflowBuilder's own nodes/edges subscriptions — React Flow
genuinely needs those arrays. Do not touch useBuilderStoreShallow or the store's internals.
Task 10: useDefinition / useAvailableVariables hooks (audit finding 7)
Depends on: none Files:
- Create:
apps/erp/app/modules/workflows/ui/Builder/useDefinition.ts - Modify:
apps/erp/app/modules/workflows/ui/Builder/config/forms/ActionForm.tsx:239-240, 288-289 - Modify:
apps/erp/app/modules/workflows/ui/Builder/config/forms/FilterForm.tsx:62-63 - Modify:
apps/erp/app/modules/workflows/ui/Builder/config/fields/VariablePicker.tsx:82-83
The problem (verified): the fromReactFlow(nodes, edges) → availableVariables(...) pipeline
runs at five call sites. ActionForm runs it twice in one component over identical inputs.
VariablePicker runs it unmemoised on every render, and a picker is mounted per ValueField
and per TemplateField — i.e. once per input on the card. Combined with Task 9's drag-frame
storm, a 20-node / 60-input workflow currently walks the whole graph ~60× per frame while
dragging.
Steps:
- Create
useDefinition.ts:/** The current graph as a definition. Memoised so the graph is walked once per change. */ export function useDefinition(): WorkflowDefinition; /** Variables visible to one node. Memoised over `useDefinition()`. */ export function useAvailableVariables(nodeId: string): Variable[];useDefinitionreadsnodesandedgeswithuseBuilderStoreShallow(Builder/context.tsx:25-29— it exists for exactly this) and wrapsfromReactFlowin auseMemo. Match the existing call signature ofavailableVariables(definition, nodeId, catalog)atActionForm.tsx:239-240. - Replace all four call sites with the hook.
ActionForm's twouseMemos collapse to one call. - Leave
fromReactFlowinAutosave.tsx:31andstore.ts:52(snapshot) alone — those are serialisation, not rendering.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: "Tasks: 1 successful, 1 total"
grep -rn "availableVariables(" apps/erp/app/modules/workflows/ui/Builder --include=*.tsx
# Expected: no output (the only remaining call is inside useDefinition.ts)
Manual check: the variable picker still lists exactly the same variables as before on an action node, a filter node, and a template field.
Out of scope: caching the definition on the store itself, and changing availableVariables in
packages/workflows.
Task 11: Verify Phase B, add the port invariant test, sync module AGENTS.md
Depends on: Tasks 7, 8, 9, 10 Files:
- Modify:
apps/erp/app/modules/workflows/ui/Builder/graph.test.ts— or createports.test.tsalongside it, matching that file's existing vitest idiom. - Modify:
apps/erp/app/modules/workflows/AGENTS.md— three verified stale claims.
Steps:
- Add a test asserting the invariant that Task 8's refactor is protecting:
for every
WorkflowNodeType,portsFor(createNode(kind, {x:0,y:0}), identity).map(p => p.id)deep-equalsgetNodeHandles(asWorkflowNode(...)). UsecreateNodefrom./graphso the test covers a schema-valid node of each kind, exactly asgraph.test.ts:125-132already does. Pass a stubtthat returns its template input. - Fix the three verified drift items in
apps/erp/app/modules/workflows/AGENTS.md(per.claude/rules/keep-sources-in-sync.md):- line 79 — there is no
LOD_ZOOManywhere in the repo; collapse is a per-nodeexpandedflag (store.ts:202-205), toggled by the card button andBuilderControls. - line 80 — the
Not configured yetplaceholder does not exist; all six forms inconfig/forms/are implemented. - line 12 —
CURRENT_DEFINITION_FORMAT_VERSIONis 3, not 2. This one is dangerous: an agent trusting it could write2.
- line 79 — there is no
- Add two short rules to that AGENTS.md now that they are real: ports get their label/tone/anchor
from
ui/Builder/ports.ts(never a hand-written list), and card components subscribe to scalars viaui/Builder/selectors.ts, never tostate.nodes.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: "Tasks: 1 successful, 1 total"
pnpm exec biome check apps/erp/app/modules/workflows
# Expected: zero errors
cd apps/erp && npx vitest run app/modules/workflows && cd -
# Expected: all test files pass; the new port-invariant test appears in the count
Out of scope: committing (the user authorises commits explicitly), audit findings 3, 5, 6,
8–17, and any change to packages/workflows.