@lace-cloud/canvas 0.27.0 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/App.tsx","../src/Canvas.tsx","../src/components/CanvasControls.tsx","../src/components/icons.tsx","../src/components/ContextMenu.tsx","../src/core/sections.ts","../src/utils/key-chord.ts","../src/components/EmptyCanvas.tsx","../src/components/edges/DependencyEdge.tsx","../src/components/edges/dependency-edge-path.ts","../src/components/edges/obstacles-for.ts","../src/components/edges/scene-nodes.ts","../src/components/nodes/GroupNode.tsx","../src/core/editor-actions.ts","../src/utils/arrangement.ts","../src/core/entry-scope.ts","../src/state/canvas-context.ts","../src/core/panels/row-actions.ts","../src/components/nodes/use-rename-instance.ts","../src/core/pipeline.ts","../src/components/nodes/ModuleNode.tsx","../src/core/decorate.ts","../src/utils/handleId.ts","../src/utils/typed-name.ts","../src/components/nodes/node-config-bus.tsx","../src/components/nodes/pinColor.ts","../src/components/PaperGrid.tsx","../src/core/use-action-keys.ts","../src/contribution-types.ts","../src/hooks/useContextMenu.ts","../src/hooks/useGroupLogic.ts","../src/hooks/useNewNodeTracking.ts","../src/utils/viewport.ts","../src/components/Drawer.tsx","../src/utils/style-vars.ts","../src/components/ErrorBoundary.tsx","../src/components/ToolbarAction.tsx","../src/core/CommandArgsForm.tsx","../src/core/overlays/describe.ts","../src/core/define-overlay.ts","../src/core/use-command-read.ts","../src/core/panel-scope.tsx","../src/core/panels/RowActionBanner.tsx","../src/components/Banner.tsx","../src/core/panels/ConflictBanner.tsx","../src/core/panels/DiagnosticsPanel.tsx","../src/components/Identifier.tsx","../src/core/panels/edge-inspector.ts","../src/components/panels/EdgeInspectorPanel.tsx","../src/core/panels/Markers.tsx","../src/core/panels/module-config.ts","../src/components/panels/ModuleConfigPanel.tsx","../src/exhaustive.ts","../src/hooks/useUpdateState.ts","../src/components/AccordionSection.tsx","../src/components/UpdateButton.tsx","../src/components/panels/ModuleDetails.tsx","../src/components/panels/BlockEditor.tsx","../src/components/panels/LocalsPanel.tsx","../src/utils/duplicates.ts","../src/components/panels/ModuleInterfacePanel.tsx","../src/components/panels/module-actions.ts","../src/components/panels/ProvidersPanel.tsx","../src/components/panels/ResourcesPanel.tsx","../src/components/panels/TerraformConfigPanel.tsx","../src/core/panels/SourceRefusedBanner.tsx","../src/core/panels/settings.ts","../src/components/panels/UnifiedSettingsPanel.tsx","../src/core/contributions.ts","../src/adapters/snapshot-source.ts"],"sourcesContent":["// @lace-cloud/canvas — public library API.\n//\n// Two entries, no deep paths: this barrel (the React surface plus\n// everything below) and `@lace-cloud/canvas/engine` (`./engine/index.ts`),\n// the React-free entry a host imports outside the webview. Consumers\n// (canvas-stories, the VS Code webview entry, portal/JetBrains shells)\n// import from one of the two; internal file structure is not part of the\n// contract.\n\n// ── Projection (Bundle + optional CanvasArrangement → CanvasView) ──\n// Re-exported from @lace-cloud/proto so canvas consumers import it from\n// one place; the implementation lives in the proto package, beside the IR\n// types it projects, and runs without React.\nexport { type ProjectionMeta, projectCanvasView } from '@lace-cloud/proto';\nexport { Toast } from '@lace-cloud/ui/feedback';\n// ── Root component ──\nexport type { AppProps } from './App';\nexport { default as App } from './App';\nexport type { SnapshotSourceInput } from './adapters/snapshot-source';\n// ── Snapshot source (portal, Storybook — a read with no live session) ──\nexport { snapshotSource } from './adapters/snapshot-source';\n// ── Components ──\nexport { default as AccordionSection } from './components/AccordionSection';\nexport { default as ContextMenu } from './components/ContextMenu';\nexport { default as ErrorBoundary, ErrorState } from './components/ErrorBoundary';\nexport type { GroupNodeData, InterfacePin } from './components/nodes/GroupNode';\n// ── Node components ──\nexport { default as GroupNode } from './components/nodes/GroupNode';\nexport type { ModuleNodeData } from './components/nodes/ModuleNode';\nexport { default as ModuleNode } from './components/nodes/ModuleNode';\nexport { NodeConfigBusProvider } from './components/nodes/node-config-bus';\n// ── Panels ──\nexport { default as EdgeInspectorPanel } from './components/panels/EdgeInspectorPanel';\nexport { default as LocalsPanel, LocalsContent } from './components/panels/LocalsPanel';\nexport { default as ModuleConfigPanel } from './components/panels/ModuleConfigPanel';\nexport {\n default as ModuleInterfacePanel,\n ModuleInterfaceContent,\n} from './components/panels/ModuleInterfacePanel';\nexport { default as ProvidersPanel, ProvidersContent } from './components/panels/ProvidersPanel';\nexport {\n default as TerraformConfigPanel,\n TerraformConfigContent,\n} from './components/panels/TerraformConfigPanel';\nexport { default as UnifiedSettingsPanel } from './components/panels/UnifiedSettingsPanel';\nexport type {\n ArgsOf,\n BoundPath,\n CommandFailure,\n CommandPath,\n GateChangeRequest,\n JsonOf,\n} from './contracts';\n// ── Command contract (generated from command-tree.golden) ──\nexport {\n COMMANDS,\n carriesFailure,\n isBoundPath,\n parseBound,\n parseCommandFailure,\n SCHEMAS,\n toArgv,\n} from './contracts';\n// ── Contract types (ports, contributions, registry) — the client-extension\n// surface: everything a host needs to author its own panels/actions/\n// overlays through the identical registry the core registers through. ──\nexport type {\n ActionContribution,\n ActionIcon,\n ActionTarget,\n Badge,\n BindingRuntime,\n CanvasCtx,\n ClipboardStore,\n CommandBinding,\n CommandRead,\n ContextKey,\n ContributionSet,\n Contributions,\n Decorations,\n EdgeRef,\n EditorBinding,\n EditorEnv,\n ErasedCommand,\n HostBinding,\n NodeDecoration,\n OverlayContribution,\n Panel,\n PanelProps,\n PanelSpec,\n Placement,\n ResultKind,\n RunCtx,\n Sink,\n SinkInput,\n} from './contributions';\n// ── Core pipeline pieces ──\nexport { CommandArgsForm, type CommandArgsFormProps } from './core/CommandArgsForm';\nexport { decorate } from './core/decorate';\nexport { defineCommand } from './core/define-command';\nexport { defineOverlay } from './core/define-overlay';\nexport { diagnosticsOf, uniqueDiagnostics } from './core/diagnostics';\nexport { decorateDescribe, describeOverlay } from './core/overlays/describe';\nexport { PanelScope, type PanelScopeValue, usePanelScope } from './core/panel-scope';\nexport { ConflictBanner, conflictPanel } from './core/panels/ConflictBanner';\nexport {\n UngeneratedMarker,\n UnsavedMarker,\n ungeneratedMarker,\n unsavedMarker,\n} from './core/panels/Markers';\nexport { SourceRefusedBanner, sourceRefusedPanel } from './core/panels/SourceRefusedBanner';\nexport { useCanvasSource } from './core/pipeline';\nexport type { ReportEntry, ReportFold, ReportPath } from './core/report-fold';\nexport {\n currentReport,\n EMPTY_REPORT_FOLD,\n foldReport,\n reportDiagnostics,\n} from './core/report-fold';\nexport type {\n Busy,\n FollowSlot,\n PreviewOutcome,\n PreviewSlot,\n ReportSlot,\n ResultSlots,\n ResultStore,\n RunningMark,\n RunOutcome,\n RunSlot,\n SlotContext,\n SlotKind,\n Started,\n} from './core/results';\nexport { createResultStore } from './core/results';\nexport type {\n ActionRunner,\n ActionRunnerOptions,\n CommandRun,\n EditorEnvExtras,\n PendingForm,\n} from './core/run-binding';\nexport { createActionRunner } from './core/run-binding';\nexport type { CommandReadState } from './core/use-command-read';\nexport { useCommandRead } from './core/use-command-read';\nexport type {\n BridgeEngineCaller,\n ConnectCallerOptions,\n DirectEngineCaller,\n EngineCaller,\n EngineMethodResponse,\n EngineSession,\n EngineSessionOptions,\n EngineTarget,\n} from './engine';\n// ── Engine mapping and callers (the React-free entry's own exports) ──\nexport {\n bridgeCaller,\n ConnectError,\n connectCaller,\n openEngineCommands,\n openEngineSession,\n Reason,\n} from './engine';\nexport type {\n ApplyResult,\n CanvasPorts,\n CanvasSource,\n CommandResult,\n CommandsPort,\n ConfirmSpec,\n ContextPort,\n CreatedRef,\n EditorPort,\n GenerateEvent,\n GraphError,\n Invocation,\n PortName,\n PresenterPort,\n RunnerPorts,\n SourceConflict,\n SourceEnd,\n SourcePort,\n StackRef,\n ViewStatePort,\n WiringCandidate,\n WiringQuery,\n} from './ports';\nexport {\n ApplyUnobservedError,\n CommandDetachedError,\n CommandExitError,\n CommandUnobservedError,\n} from './ports';\nexport { answering, disabledReason, resolveContributions, rowActions } from './registry';\n// ── State ──\nexport type { CanvasContextValue } from './state/canvas-context';\nexport { CanvasContext, useCanvas } from './state/canvas-context';\n// ── Render-model types (re-exported from @lace-cloud/proto via ./types/render) ──\nexport type {\n CanvasArrangement,\n CanvasView,\n Conflict,\n Diagnostic,\n GeneratePhase,\n NodeConfig,\n NodePin,\n RenderEdge,\n RenderGroup,\n RenderInput,\n RenderNode,\n RenderOutput,\n SettingsConfig,\n ViewportIntent,\n} from './types/render';\n// The type an action's `keys` hold: a key that starts with `Mod+`, the\n// grammar's prefix; `parseChord` refuses the rest at runtime.\nexport type { KeySpec } from './utils/key-chord';\n","import { ReactFlowProvider } from '@xyflow/react';\nimport type React from 'react';\nimport {\n Fragment,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport './App.css';\nimport Canvas from './Canvas';\nimport Drawer from './components/Drawer';\nimport ErrorBoundary, { ErrorState } from './components/ErrorBoundary';\nimport { ToolbarAction } from './components/ToolbarAction';\nimport type { BoundPath } from './contracts';\nimport type {\n CanvasCtx,\n Contributions,\n Decorations,\n EdgeRef,\n LayoutHandle,\n Panel,\n} from './contributions';\nimport { CommandArgsForm } from './core/CommandArgsForm';\nimport { CORE_CONTRIBUTIONS } from './core/contributions';\nimport { decorate } from './core/decorate';\nimport { diagnosticsOf } from './core/diagnostics';\nimport { PanelScope } from './core/panel-scope';\nimport { projectFrame, reconcileSelection, useCanvasSource } from './core/pipeline';\nimport { reportDiagnostics } from './core/report-fold';\nimport { createResultStore, liveSlots, type ResultStore } from './core/results';\nimport { createActionRunner, type EditorEnvExtras, type PendingForm } from './core/run-binding';\nimport { isEmphasized, toolbarLayout } from './core/sections';\nimport { registerKeyTarget, useActionKeys, useFocusWhenNoneHeld } from './core/use-action-keys';\nimport type { CanvasPorts, CanvasSource, CommandResult, SourceEnd } from './ports';\nimport { actionState, resolveContributions } from './registry';\nimport { CanvasContext, type CanvasContextValue } from './state/canvas-context';\nimport type { CanvasArrangement } from './types/render';\nimport { gcArrangement } from './utils/arrangement';\n\nconst EMPTY_CONTRIBUTIONS: Contributions = { overlays: [], panels: [], actions: [] };\nconst NO_SELECTION: { nodes: readonly string[]; edge: EdgeRef | null } = { nodes: [], edge: null };\nconst NO_TARGET = {};\n\nexport type AppProps = {\n ports: CanvasPorts;\n /** Appended to the core contribution set — no core feature bypasses the registry. */\n contributions?: Contributions;\n /**\n * The result store the canvas writes and reads, owned by the host. A host\n * that refreshes the canvas's reads from outside — a run its own UI\n * started has settled — passes the store it owns and calls `bumpTick()`\n * on it. Omitted, the canvas owns one of its own.\n */\n results?: ResultStore;\n /**\n * Height of the canvas root. Defaults to `100vh`; a host that mounts the\n * canvas inside its own panel passes `100%` when that panel establishes an\n * explicit height.\n */\n height?: React.CSSProperties['height'];\n};\n\n// OverlayRunner mounts one resolved overlay's own `useDecorations` hook\n// inside the `PanelScope` its declared `paths` need — the identical\n// registry-gated read path a panel's own declared `reads` runs through, no\n// second overlay-fetch mechanism. Unlike `PanelSlot` (below), an overlay\n// decorates silently — there is no chrome slot to render a failed read\n// into — so a failure instead reaches `presenter.notify` once (`useCommandRead`'s\n// own effect calls `reportError` once per key/tick, never per render),\n// or a `stack describe` outage would show no drift badges and no notice.\nfunction OverlayRunner({\n overlay,\n ctx,\n tick,\n onDecorations,\n}: {\n overlay: Contributions['overlays'][number];\n ctx: CanvasCtx;\n tick: number;\n onDecorations: (id: string, decorations: Decorations) => void;\n}) {\n // `useCommandRead` reports the same still-failing error again on every\n // tick-only refetch of a path that keeps failing (an outage that\n // outlives one tick) — a toast per tick would spam the same notice.\n // Notify only when a path's own error actually changes: a new failure,\n // a different message, or clearing.\n const lastErrorRef = useRef<Map<BoundPath, string | null>>(new Map());\n const onReadError = useCallback(\n (path: BoundPath, error: Error | null) => {\n const next = error?.message ?? null;\n if (lastErrorRef.current.get(path) === next) return;\n lastErrorRef.current.set(path, next);\n if (error) ctx.ports.presenter.notify('error', `${path}: ${error.message}`);\n },\n [ctx.ports.presenter],\n );\n return (\n <PanelScope ctx={ctx} paths={overlay.paths} tick={tick} onReadError={onReadError}>\n <OverlayDecorations overlay={overlay} ctx={ctx} onDecorations={onDecorations} />\n </PanelScope>\n );\n}\n\nfunction OverlayDecorations({\n overlay,\n ctx,\n onDecorations,\n}: {\n overlay: Contributions['overlays'][number];\n ctx: CanvasCtx;\n onDecorations: (id: string, decorations: Decorations) => void;\n}) {\n const decorations = overlay.useDecorations(ctx);\n useEffect(() => {\n onDecorations(overlay.id, decorations);\n }, [overlay.id, decorations, onDecorations]);\n return null;\n}\n\n// PanelSlot wraps one resolved Panel in the `PanelScope` its own declared\n// `reads` need (the runtime guard that rejects an undeclared read) — every\n// rendered panel, regardless of slot, goes through this one wrapper so a\n// new panel needs no bespoke scoping at its call site. It is also the one\n// place a failed read renders: `onReadError` catches whatever\n// `useCommandRead` reports from inside `panel.Component` and shows it above\n// the panel's own content, so a panel needs only ever destructure `data`\n// (or ignore the read entirely) rather than each one deciding for itself\n// whether a failed fetch is worth a rendered word.\n//\n// A panel keyed on more than one declared read keeps one error per path — a\n// single shared slot would let a later success on one path silently clear a\n// still-failing other, or a still-failing one keep masking the other's own\n// recovery.\nfunction PanelSlot({ panel, ctx, tick }: { panel: Panel; ctx: CanvasCtx; tick: number }) {\n const [readErrors, setReadErrors] = useState<ReadonlyMap<BoundPath, Error>>(new Map());\n const onReadError = useCallback((path: BoundPath, error: Error | null) => {\n setReadErrors((prev) => {\n if (error === null) {\n if (!prev.has(path)) return prev;\n const next = new Map(prev);\n next.delete(path);\n return next;\n }\n const next = new Map(prev);\n next.set(path, error);\n return next;\n });\n }, []);\n return (\n <PanelScope\n ctx={ctx}\n paths={(panel.reads ?? []).map((r) => r.path)}\n tick={tick}\n onReadError={onReadError}\n >\n {[...readErrors].map(([path, error]) => (\n <p key={path} className=\"lace-app__panel-error\">\n Couldn't load {path}: {error.message}\n </p>\n ))}\n <panel.Component ctx={ctx} />\n </PanelScope>\n );\n}\n\n// BottomTabs (the \"bottom\" slot): at most one bottom panel visible at a\n// time, switched by a tab strip — every bottom panel is a pure view over\n// `ctx`/the ResultStore, so switching tabs mounts/unmounts a panel rather\n// than fetching anything itself.\nfunction BottomTabs({\n panels,\n ctx,\n tick,\n}: {\n panels: readonly Panel[];\n ctx: CanvasCtx;\n tick: number;\n}) {\n const [manualId, setManualId] = useState<string | null>(null);\n const manual = manualId !== null ? panels.find((p) => p.id === manualId) : undefined;\n const active = manual ?? panels[0] ?? null;\n\n if (panels.length === 0) return null;\n\n return (\n <div className=\"lace-app__bottom\">\n <div className=\"lace-app__bottom-tabs\" role=\"tablist\">\n {panels.map((panel) => (\n <button\n key={panel.id}\n type=\"button\"\n role=\"tab\"\n aria-selected={panel.id === active?.id}\n className={`lace-app__bottom-tab${panel.id === active?.id ? ' lace-app__bottom-tab--active' : ''}`}\n onClick={() => setManualId(panel.id)}\n >\n {panel.title}\n </button>\n ))}\n </div>\n <div className=\"lace-app__bottom-content\">\n {active && <PanelSlot panel={active} ctx={ctx} tick={tick} />}\n </div>\n </div>\n );\n}\n\n// What a canvas with no frame yet shows for its source's end: a failed\n// stream's own error, or the session's closing.\nfunction endMessage(end: SourceEnd): string {\n return end.kind === 'failed' ? end.error.message : 'The session was closed.';\n}\n\nexport default function App({\n ports,\n contributions = EMPTY_CONTRIBUTIONS,\n height = '100vh',\n results: hostResults,\n}: AppProps) {\n // One store, one owner: the host's when it passes one, else this mount's.\n const results = useMemo(() => hostResults ?? createResultStore(), [hostResults]);\n // The report slot's one writer: the result of every command that ran in\n // the session's root, whichever client ran it, folded under this mount's\n // own session (core/results.ts `reduceReport`), so a store the host\n // shares across canvases keeps each one's report apart. A report belongs\n // to no stack. A document the fold cannot read is a contract mismatch: it\n // is announced the way a command's own unreadable document is, and the\n // report stays as it was. The session's report goes when its\n // subscription ends.\n const writeReport = useCallback(\n (result: CommandResult, session: object) => {\n try {\n results.write('report', session, result, { stack: undefined });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n ports.presenter.notify('error', `${result.path}: ${message}`);\n }\n },\n [results, ports.presenter],\n );\n const dropReport = useCallback((session: object) => results.detach('report', session), [results]);\n const { source, end, session } = useCanvasSource(ports.source, writeReport, dropReport);\n const [arrangement, setArrangement] = useState<CanvasArrangement>(() => ports.viewState.load());\n // The stack is the host's: `context.stack` is its one source, read every\n // render, so a host that passes a `ports` object with another stack moves\n // every gate and read keyed on it (the describe overlay's `stack\n // describe`) in that same render. The canvas holds no pick of its own.\n const stack = ports.context.stack;\n const [selection, setSelection] = useState<{ nodes: readonly string[]; edge: EdgeRef | null }>(\n NO_SELECTION,\n );\n const [settingsOpen, setSettingsOpen] = useState(false);\n // The drawer shows Settings or the inspector of what is selected: Settings\n // comes first while it is open, and selecting a node or a connection\n // closes it, so the inspector of what was just picked is what shows.\n const select = useCallback((next: { nodes: readonly string[]; edge: EdgeRef | null }) => {\n setSelection(next);\n if (next.nodes.length > 0 || next.edge !== null) setSettingsOpen(false);\n }, []);\n const [pendingForm, setPendingForm] = useState<PendingForm>(null);\n const [overlayDecorations, setOverlayDecorations] = useState<Record<string, Decorations>>({});\n const layoutRef = useRef<LayoutHandle>({ panIntoView: () => {} });\n\n // The runner is keyed on the ports it closes over (`RunnerPorts`), never on\n // the `ports` object's identity: a host that passes a new object to change\n // `context.stack` keeps the runner it had, and with it every invocation\n // still running (a `run logs` follow, an in-flight apply).\n const { commands, presenter, editor } = ports;\n const runner = useMemo(\n () =>\n createActionRunner({ commands, presenter, editor }, results, {\n onPendingFormChange: setPendingForm,\n }),\n [commands, presenter, editor, results],\n );\n // Every runner instance owns its own outstanding invocations. Another\n // `commands`, `presenter` or `editor` port, or another store, replaces the\n // runner above, and unmount discards it entirely — either way the previous\n // instance's streams would otherwise keep running with nothing left to\n // read them, so this disposes the one being replaced/discarded.\n useEffect(() => {\n return () => {\n runner.dispose();\n };\n }, [runner]);\n const tick = useSyncExternalStore(results.subscribe, results.getTick);\n const updateArrangement = useCallback(\n (next: CanvasArrangement) => {\n setArrangement(next);\n ports.viewState.save(next);\n },\n [ports.viewState],\n );\n\n // A frame's Bundle may drop scopes/children the arrangement still holds\n // positions for — housekeeping, not correctness (a stale entry is simply\n // never read), so it updates local state and the host without\n // round-tripping through `updateArrangement`. Guarded on the Bundle's own\n // identity so it runs once per frame, not once per render.\n const gcSeenBundle = useRef<unknown>(null);\n if (source && gcSeenBundle.current !== source.bundle) {\n gcSeenBundle.current = source.bundle;\n const gced = gcArrangement(source.bundle, arrangement);\n if (gced !== arrangement) {\n queueMicrotask(() => {\n setArrangement(gced);\n ports.viewState.save(gced);\n });\n }\n }\n\n const view = useMemo(\n () => (source ? projectFrame(source, arrangement) : null),\n [source, arrangement],\n );\n\n // A selection names only what the frame holds: each frame that lands\n // drops from the selection what its view does not hold, whatever removed\n // it (a key, a panel's button, an undo, another client), so no inspector\n // stays open over it. Once per frame, as `gcArrangement`: a write ahead of\n // its frame (a rename's carry, `carrySelection`) keeps its copy until\n // the frame that holds it lands. Before paint, so no panel is drawn over\n // what the frame dropped. The raw setter, not `select`: dropping what is\n // gone picks nothing, so Settings stays as it is; a selection the view\n // holds whole is returned as itself and changes no state.\n const reconciledFrame = useRef<CanvasSource | null>(null);\n useLayoutEffect(() => {\n if (!source || !view || reconciledFrame.current === source) return;\n reconciledFrame.current = source;\n setSelection((current) => reconcileSelection(view, current));\n }, [source, view]);\n\n // The one read-only derivation: an editor port present and the session\n // not source-refused. Already threaded through the xyflow props and the\n // keymap below; also the `'editable'` context key (contextValue.ctx).\n const editable = ports.editor !== undefined && !source?.sourceRefused;\n\n // The core's own contributions (core/contributions.ts: the authoring set)\n // merge with whatever the host passes — no core feature bypasses the\n // registry.\n const merged = useMemo<Contributions>(\n () => ({\n overlays: [...CORE_CONTRIBUTIONS.overlays, ...contributions.overlays],\n panels: [...CORE_CONTRIBUTIONS.panels, ...contributions.panels],\n actions: [...CORE_CONTRIBUTIONS.actions, ...contributions.actions],\n }),\n [contributions],\n );\n\n // Every store write replaces the snapshot's reference, so everything\n // derived from it below re-derives the moment a slot fills or settles —\n // independent of `tick`, which only moves on `invalidates`.\n const resultSlots = useSyncExternalStore(results.subscribe, results.getSnapshot);\n const stackId = stack?.id;\n // Only the slots still about what is on screen (core/results.ts\n // `liveSlots`): this session's report while it is about the tree on\n // screen, and a run/preview of the chosen stack — anything else is gone\n // the moment that context moves.\n const live = useMemo(\n () =>\n source && session\n ? liveSlots(resultSlots, { session, treeHash: source.treeHash, stack: stackId })\n : null,\n [resultSlots, source, session, stackId],\n );\n\n // The one diagnostics list (core/diagnostics.ts): the engine's live\n // per-frame findings plus the current report's own — `decorate` and\n // every consumer of `ctx.diagnostics` (DiagnosticsPanel included) read\n // this, never `source.diagnostics` alone.\n const diagnostics = useMemo(\n () =>\n source && live\n ? diagnosticsOf(source.diagnostics, live.report ? reportDiagnostics(live.report) : [])\n : [],\n [source, live],\n );\n\n const ctx = useMemo<CanvasCtx | null>(() => {\n if (!source || !view) return null;\n return {\n ports,\n root: ports.context.root,\n sessionId: ports.context.sessionId,\n stack,\n editable,\n generating: source.generating,\n sourceRefused: source.sourceRefused,\n view,\n selection,\n settingsOpen,\n diagnostics,\n contributions: merged,\n };\n }, [ports, source, view, stack, selection, settingsOpen, merged, diagnostics, editable]);\n\n const resolved = useMemo<Contributions>(() => {\n if (!ctx) return EMPTY_CONTRIBUTIONS;\n return resolveContributions(merged, ports, ctx, NO_TARGET);\n }, [merged, ports, ctx]);\n\n const setOverlayDecoration = useCallback((id: string, next: Decorations) => {\n setOverlayDecorations((prev) => (prev[id] === next ? prev : { ...prev, [id]: next }));\n }, []);\n\n const decorations = useMemo(() => {\n if (!view || !source) return { nodes: {} };\n return decorate(view, Object.values(overlayDecorations), diagnostics);\n }, [view, source, overlayDecorations, diagnostics]);\n\n const envExtras = useMemo<EditorEnvExtras | null>(() => {\n if (!source) return null;\n return {\n bundle: source.bundle,\n arrangement: { get: () => arrangement, update: updateArrangement },\n layout: layoutRef.current,\n };\n }, [source, arrangement, updateArrangement]);\n\n const toolbar = toolbarLayout(\n resolved.actions.filter((action) => action.placement === 'toolbar'),\n resolved.panels.filter((panel) => panel.slot === 'toolbar'),\n );\n\n // The App root is the keymap's `app` target: an app-scoped key (Save)\n // is heard from the drawer and the bottom panels, siblings of\n // the canvas surface. Registered before the keymap effect below so the\n // same commit binds it.\n const rootRef = useRef<HTMLDivElement>(null);\n useEffect(() => {\n if (!ctx) return;\n registerKeyTarget(ctx, 'app', rootRef.current);\n return () => registerKeyTarget(ctx, 'app', null);\n }, [ctx]);\n // The root is focusable (`tabIndex={-1}`) and holds focus while nothing\n // else does, so a key pressed with the window focused and no element\n // focused still reaches the keymap.\n useFocusWhenNoneHeld(rootRef, Boolean(ctx && view && source && envExtras));\n\n // The one keymap, gated by focus (form controls / defaultPrevented)\n // inside the hook itself — installed once ctx/envExtras exist, torn down\n // when they don't (unmount, load error). Every resolved action with its\n // own `keys` binds, not just the toolbar's — a node-menu action (copy/\n // cut/paste/group) has no toolbar button but still owns a shortcut.\n useActionKeys(ctx && envExtras ? resolved.actions : [], ctx, runner, envExtras);\n\n if (!ctx || !view || !source || !envExtras) {\n return end ? <ErrorState message={endMessage(end)} /> : null;\n }\n\n const contextValue: CanvasContextValue = {\n ports,\n bundle: source.bundle,\n view,\n ctx,\n decorations,\n editable,\n arrangement,\n updateArrangement,\n selection,\n setSelection: select,\n runner,\n layout: layoutRef.current,\n setSettingsOpen,\n };\n\n const bannerPanels = resolved.panels.filter((panel) => panel.slot === 'banner');\n const bottomPanels = resolved.panels.filter((panel) => panel.slot === 'bottom');\n // The drawer holds one panel: the first drawer panel that resolves,\n // Settings first. Selecting closes Settings (`select`, above), but opening\n // Settings leaves the selection, so both can resolve and Settings shows; a\n // host's own drawer panel shows while neither resolves.\n const drawerPanel = resolved.panels.find((panel) => panel.slot === 'drawer');\n\n return (\n <ErrorBoundary>\n {resolved.overlays.map((overlay) => (\n <OverlayRunner\n key={overlay.id}\n overlay={overlay}\n ctx={ctx}\n tick={tick}\n onDecorations={setOverlayDecoration}\n />\n ))}\n <CanvasContext.Provider value={contextValue}>\n <div ref={rootRef} className=\"lace-app\" style={{ height }} tabIndex={-1}>\n {(toolbar.sections.length > 0 || toolbar.trailing.length > 0) && (\n <div className=\"lace-app__toolbar\">\n {toolbar.sections.map((section, index) => (\n <Fragment key={section.key ?? ''}>\n {index > 0 ? (\n <span className=\"lace-app__toolbar-separator\" aria-hidden=\"true\" />\n ) : null}\n <div className=\"lace-app__toolbar-section\">\n {section.actions.map((action) => (\n // `runner.busy` reads the store, whose every write\n // re-renders App (`resultSlots`).\n <ToolbarAction\n key={action.id}\n action={action}\n {...actionState(action, ctx, runner.busy(action, ctx, NO_TARGET))}\n emphasized={isEmphasized(action, ctx)}\n onRun={() => void runner.run(action, ctx, NO_TARGET, envExtras)}\n />\n ))}\n {section.panels.map((panel) => (\n <PanelSlot key={panel.id} panel={panel} ctx={ctx} tick={tick} />\n ))}\n </div>\n </Fragment>\n ))}\n {toolbar.trailing.length > 0 && (\n <div className=\"lace-app__toolbar-end\">\n {toolbar.trailing.map((panel) => (\n <PanelSlot key={panel.id} panel={panel} ctx={ctx} tick={tick} />\n ))}\n </div>\n )}\n </div>\n )}\n {/* A banner takes its own row between the toolbar and the canvas:\n the toolbar keeps its place when a conflict opens under the\n pointer, and the canvas gives up the row's height. */}\n <div className=\"lace-app__banners\">\n {bannerPanels.map((panel) => (\n <PanelSlot key={panel.id} panel={panel} ctx={ctx} tick={tick} />\n ))}\n </div>\n <div className=\"lace-app__body\">\n <div className=\"lace-app__main\">\n <div className=\"lace-app__canvas\">\n <ReactFlowProvider>\n <Canvas height=\"100%\" />\n </ReactFlowProvider>\n </div>\n <BottomTabs panels={bottomPanels} ctx={ctx} tick={tick} />\n </div>\n {drawerPanel && (\n <Drawer label={drawerPanel.title}>\n <PanelSlot key={drawerPanel.id} panel={drawerPanel} ctx={ctx} tick={tick} />\n </Drawer>\n )}\n </div>\n <CommandArgsForm form={pendingForm} />\n </div>\n </CanvasContext.Provider>\n </ErrorBoundary>\n );\n}\n","// xyflow's base stylesheet is part of the canvas, not of the app that\n// mounts it: `.react-flow__node` / `.react-flow__pane` / `.react-flow__panel`\n// carry the `position: absolute` that makes nodes shrink-wrap their card and\n// keeps the Controls panel above the pane. Without it, the pane paints over\n// the zoom buttons and swallows their clicks, and fitView measures a node\n// wrapper stretched to the container width. It is imported here — ahead of\n// Canvas.css, so our unlayered rules still win — so every consumer gets it\n// from the React import chain rather than remembering to import it.\nimport '@xyflow/react/dist/style.css';\nimport './Canvas.css';\nimport { drawnRect, extentOf, instanceAddress, localIn } from '@lace-cloud/proto';\nimport {\n applyEdgeChanges,\n applyNodeChanges,\n type Connection,\n type Edge,\n type EdgeChange,\n type FitViewOptions,\n type Node,\n type NodeChange,\n ReactFlow,\n type ReactFlowInstance,\n useNodesInitialized,\n useReactFlow,\n} from '@xyflow/react';\nimport type React from 'react';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport CanvasControls from './components/CanvasControls';\nimport ContextMenu from './components/ContextMenu';\nimport EmptyCanvas from './components/EmptyCanvas';\nimport { edgeTypes } from './components/edges/DependencyEdge';\nimport GroupNode from './components/nodes/GroupNode';\nimport ModuleNode from './components/nodes/ModuleNode';\nimport { NodeConfigBusProvider } from './components/nodes/node-config-bus';\nimport PaperGrid from './components/PaperGrid';\nimport type {\n ActionContribution,\n ActionTarget,\n CanvasCtx,\n EdgeRef,\n LayoutHandle,\n} from './contributions';\nimport type { DrawnDecorations } from './core/decorate';\nimport { groupTarget } from './core/editor-actions';\nimport type { EditorEnvExtras } from './core/run-binding';\nimport { isFormTarget, registerKeyTarget } from './core/use-action-keys';\nimport { type ContextMenuRequest, useContextMenu } from './hooks/useContextMenu';\nimport { drawnPosition, rfEdgeData, useGroupLogic } from './hooks/useGroupLogic';\nimport { useNewNodeTracking } from './hooks/useNewNodeTracking';\nimport { resolveContributions } from './registry';\nimport { useCanvas } from './state/canvas-context';\nimport type { CanvasView } from './types/render';\nimport { withNodePositions, withScopesPinned } from './utils/arrangement';\nimport { NODE_HANDLE, parseHandleId } from './utils/handleId';\nimport {\n computeMinimalPanDelta,\n type FlowRect,\n viewportAfterResize,\n withMargin,\n} from './utils/viewport';\n\n// ── Node types registration ──\n\nconst nodeTypes = {\n moduleNode: ModuleNode,\n groupNode: GroupNode,\n};\n\n// `edgeTypes` (DependencyEdge.tsx) registers the canvas's only edge type —\n// every RenderEdge (useGroupLogic.ts) is emitted under it so a connector's\n// path never cuts through an unrelated node, regardless of where the depth\n// layout or a drag places either endpoint.\n\n// Every way the canvas fits the whole graph — the first frame of an\n// engine, the Fit view control, a drawer that no longer leaves room for a\n// graph that was wholly in view — lands on these options, so a user who\n// pans away and fits again gets the framing they started with. A fit never\n// zooms past 100%: a three-node module is drawn at its own size, not blown\n// up to fill the pane.\nconst FIT_VIEW_OPTIONS: FitViewOptions = { padding: 0.2, duration: 300, maxZoom: 1 };\n\n// Screen pixels kept clear around a node brought into view.\nconst REVEAL_MARGIN = 24;\n\nconst NO_ENV_EXTRAS_TARGET: ActionTarget = {};\n\n// A drag joins a pin to a pin, or one node's grip to another node's card. A\n// mixed pair, or a grip dropped on its own card, is no connection, so xyflow\n// never ends one there and never hands one to `onConnect`.\nconst isValidConnection = (c: Connection | Edge) =>\n c.sourceHandle === NODE_HANDLE\n ? c.targetHandle === NODE_HANDLE && c.source !== c.target\n : c.targetHandle !== NODE_HANDLE;\n\n// The wire an xyflow edge draws, as the selection names it; null for an edge\n// this canvas did not draw.\nfunction edgeRefOf(edge: Edge): EdgeRef | null {\n const data = rfEdgeData(edge);\n if (!data) return null;\n return {\n id: edge.id,\n source: edge.source,\n target: edge.target,\n sourceOutput: data.source_output,\n targetInput: data.target_input,\n };\n}\n\n// ══════════════════════════════════════════════════════════════════════\n// CompositeEditor — renders the ReactFlow viewport for a valid graph.\n//\n// Separated from Canvas so that its hooks (useMemo for rfNodes/rfEdges)\n// only mount when a valid CanvasView exists. This avoids React's\n// \"rendered fewer hooks\" error (#300) — Canvas can safely early-return\n// the loading placeholder without skipping any hooks, because the\n// graph-dependent hooks live here and are never mounted in that path.\n// ══════════════════════════════════════════════════════════════════════\n\ntype CompositeEditorProps = {\n view: CanvasView;\n editable: boolean;\n // Every card a frame has added this session and still draws; the cards\n // among them the developer has not selected yet draw as new.\n addedIds: Set<string>;\n newNodeIds: Set<string>;\n // Whether a canvas edit is in progress (`ActionRunner.editing`).\n editing: boolean;\n // Every dragged node's position to store, by canvas path, each in the\n // frame of the scope that owns it.\n onDragStop: (positions: Record<string, { x: number; y: number }>) => void;\n onConnect: (conn: Connection) => void;\n onEdgeClick: (e: React.MouseEvent, edge: Edge) => void;\n onEdgesDelete: (edges: Edge[]) => void;\n onNodesDelete: (nodes: Node[]) => void;\n onSelectionChange: (params: { nodes: Node[]; edges: Edge[] }) => void;\n onInit: (instance: ReactFlowInstance) => void;\n onContextMenu: (request: ContextMenuRequest) => void;\n registerGoToNode: (fn: (nodeId: string) => void) => void;\n // The one shared handle (state/canvas-context.ts) every `EditorEnvExtras`\n // consumer reads — CompositeEditor is `panIntoView`'s one owner: it holds\n // the real xyflow viewport helpers, so it assigns the method directly in\n // a single effect below rather than routing through an intermediate\n // register-callback + ref that Canvas would have to re-wrap.\n layout: LayoutHandle;\n // What is selected, as node ids: the selected nodes, or a selected\n // connection's two ends. Kept in view when the pane changes size.\n focusIds: readonly string[];\n // The selection, which xyflow draws selected beside its own.\n selection: CanvasCtx['selection'];\n // The DOM node whose visible size is the pane pan-into-view measures\n // against — owned by Canvas (it wraps this component) so the measurement\n // matches exactly what `.lace-app__main`/`.lace-app__canvas`'s\n // `overflow: hidden` clips against.\n paneRef: React.RefObject<HTMLDivElement | null>;\n decorations: DrawnDecorations;\n};\n\nfunction CompositeEditor({\n view,\n editable,\n addedIds,\n newNodeIds,\n editing,\n onDragStop,\n onConnect,\n onEdgeClick,\n onEdgesDelete,\n onNodesDelete,\n onSelectionChange,\n onInit,\n onContextMenu,\n registerGoToNode,\n layout,\n focusIds,\n selection,\n paneRef,\n decorations,\n}: CompositeEditorProps) {\n const { fitView, getNode, getNodes, getNodesBounds, getViewport, setViewport } = useReactFlow();\n\n // Stable-render barrier. xyflow measures every node asynchronously after\n // mount; until that completes, `.react-flow__node` elements have no\n // transform and pin Handles haven't laid out their absolute positions.\n // `useNodesInitialized` flips to true once every visible node has\n // width/height. With zero nodes there's nothing to measure —\n // `useNodesInitialized` stays `false` forever, so an empty canvas counts\n // as rendered the moment xyflow has mounted.\n const xyflowInitialized = useNodesInitialized();\n const nodesInitialized = xyflowInitialized || view.nodes.length === 0;\n\n // Go to a node (its header clicked, opening its inspector): pan it the\n // least distance into view at the zoom the developer chose. Re-register\n // if the parent supplies a new callback or xyflow swaps out its helpers.\n useEffect(() => {\n registerGoToNode((nodeId: string) => {\n if (!getNode(nodeId)) return;\n const bounds = getNodesBounds([nodeId]);\n layout.panIntoView(withMargin(bounds, REVEAL_MARGIN, getViewport().zoom));\n });\n }, [registerGoToNode, getNode, getNodesBounds, getViewport, layout]);\n\n // When the pane changes size — the drawer opening or closing, the window\n // resizing — the camera keeps what the developer was looking at\n // (`viewportAfterResize`): a graph wholly in view stays wholly in view,\n // and what is selected stays in view.\n const focusRef = useRef(focusIds);\n focusRef.current = focusIds;\n useEffect(() => {\n const pane = paneRef.current;\n if (!pane || typeof ResizeObserver === 'undefined') return;\n let before = { width: pane.clientWidth, height: pane.clientHeight };\n let frame = 0;\n const keep = () => {\n const after = { width: pane.clientWidth, height: pane.clientHeight };\n if (after.width === before.width && after.height === before.height) return;\n const was = before;\n before = after;\n const viewport = getViewport();\n const nodes = getNodes();\n const focus = focusRef.current.filter((id) => getNode(id));\n const outcome = viewportAfterResize(\n viewport,\n was,\n after,\n nodes.length > 0 ? getNodesBounds(nodes) : null,\n focus.length > 0 ? withMargin(getNodesBounds(focus), REVEAL_MARGIN, viewport.zoom) : null,\n );\n if (outcome.kind === 'fit') void fitView(FIT_VIEW_OPTIONS);\n else if (outcome.kind === 'move') void setViewport(outcome.viewport, { duration: 200 });\n };\n // A frame later, so xyflow has taken the pane's new size too: a fit\n // measures the pane through xyflow's own store.\n const observer = new ResizeObserver(() => {\n cancelAnimationFrame(frame);\n frame = requestAnimationFrame(keep);\n });\n observer.observe(pane);\n return () => {\n cancelAnimationFrame(frame);\n observer.disconnect();\n };\n }, [paneRef, getViewport, getNodes, getNode, getNodesBounds, fitView, setViewport]);\n\n // Own `layout.panIntoView` directly — one assignment, in the one place\n // that holds the real xyflow viewport helpers, rather than Canvas relaying\n // a registered callback through its own ref. A fresh group's header can\n // extend above/beyond its members' bounds (padding for the Expand/Collapse\n // chrome) — this pans the camera by the minimal delta that clears\n // whichever edge is clipped, keeping zoom and every node's position\n // untouched.\n useEffect(() => {\n layout.panIntoView = (rect: FlowRect) => {\n const pane = paneRef.current?.getBoundingClientRect();\n if (!pane) return;\n const viewport = getViewport();\n const { dx, dy } = computeMinimalPanDelta(\n rect,\n { width: pane.width, height: pane.height },\n viewport,\n );\n if (dx === 0 && dy === 0) return;\n setViewport(\n { x: viewport.x + dx, y: viewport.y + dy, zoom: viewport.zoom },\n { duration: 300 },\n );\n };\n }, [layout, getViewport, setViewport, paneRef]);\n\n // Fit the whole graph once xyflow has measured every node. Fires once\n // per mount; a later reposition (drag, group collapse) never re-triggers\n // it because `firedRef` only resets when the component itself remounts\n // (a new source/session).\n const firedRef = useRef(false);\n useEffect(() => {\n if (firedRef.current || !nodesInitialized || view.nodes.length === 0) return;\n firedRef.current = true;\n requestAnimationFrame(() => fitView(FIT_VIEW_OPTIONS));\n }, [nodesInitialized, view.nodes.length, fitView]);\n\n // ── Nodes + Edges (group-aware) ──\n const groupLogic = useGroupLogic(view.nodes, view.edges, view.groups, newNodeIds, decorations);\n\n // Every card a frame adds — a module's or a group's — is brought into\n // view where it is drawn, the least distance at the zoom the developer\n // chose (`layout.panIntoView`), so a change made on the canvas or away\n // from it — a placement from the registry, a group, a tool's edit, an edit\n // to the tf — shows on it. A canvas edit places what it creates only once\n // its batch has settled (paste a clone in the free slot, store a new\n // group past what the layout keeps before it, ungroup the members where\n // they were drawn), so the cards that land while one is in progress are\n // brought into view once it has settled, where they are drawn then. A\n // card a collapsed group hides is not drawn, so nothing of it is brought\n // into view. What has been brought into view is kept apart from what\n // draws as new: selecting a card never brings it into view again.\n const revealedRef = useRef(addedIds);\n useEffect(() => {\n if (editing) return;\n const arrived = [...addedIds].filter((id) => !revealedRef.current.has(id));\n revealedRef.current = addedIds;\n const shown = arrived.flatMap((id) => {\n const node = groupLogic.rfNodes.find((n) => n.id === id);\n const rect = node && !node.hidden ? drawnRect(view, id) : undefined;\n return rect ? [rect] : [];\n });\n if (shown.length === 0) return;\n layout.panIntoView(withMargin(extentOf(shown), REVEAL_MARGIN, getViewport().zoom));\n }, [editing, addedIds, groupLogic.rfNodes, view, layout, getViewport]);\n\n const rfEdgesFromView = groupLogic.rfEdges;\n\n // What xyflow draws selected is what it holds selected and what the\n // selection names: a rebuild keeps both, so a frame never clears the wire\n // under the inspector, and a card a rename carried the selection to is\n // drawn selected under its new id.\n const selectedNodeIds = useMemo(() => new Set(selection.nodes), [selection.nodes]);\n const selectedEdgeId = selection.edge?.id;\n\n const [rfEdges, setRfEdges] = useState<Edge[]>(rfEdgesFromView);\n useEffect(() => {\n setRfEdges((prev) => {\n const held = new Set(prev.filter((e) => e.selected).map((e) => e.id));\n return rfEdgesFromView.map((e) =>\n held.has(e.id) || e.id === selectedEdgeId ? { ...e, selected: true } : e,\n );\n });\n }, [rfEdgesFromView, selectedEdgeId]);\n\n const onEdgesChange = useCallback((changes: EdgeChange[]) => {\n setRfEdges((prev) => applyEdgeChanges(changes, prev));\n }, []);\n\n const rfNodesFromView = groupLogic.rfNodes;\n\n const [rfNodes, setRfNodes] = useState<Node[]>(rfNodesFromView);\n\n // Every projection is drawn where it says — a drop the layout placed\n // elsewhere snaps there, a box that grew pushes its siblings at once, an\n // undo puts everything back — except a node xyflow is dragging right now,\n // which stays under the pointer. What xyflow alone knows about a node\n // (whether it is being dragged or is selected, the size it measured)\n // carries over, so a drop never clears the selection, and a node the\n // selection names is drawn selected — but a member a collapsed group hides\n // is never selected: no gesture can reach it.\n useEffect(() => {\n setRfNodes((prev) => {\n const current = new Map(prev.map((n) => [n.id, n]));\n return rfNodesFromView.map((n) => {\n const existing = current.get(n.id);\n const selected = (existing?.selected === true || selectedNodeIds.has(n.id)) && !n.hidden;\n if (!existing) return selected ? { ...n, selected } : n;\n return {\n ...n,\n position: existing.dragging ? existing.position : n.position,\n dragging: existing.dragging,\n selected,\n measured: existing.measured,\n };\n });\n });\n }, [rfNodesFromView, selectedNodeIds]);\n\n const onNodesChange = useCallback((changes: NodeChange[]) => {\n setRfNodes((prev) => applyNodeChanges(changes, prev));\n }, []);\n\n // A drop stores every dragged node where it was dropped, in the frame of\n // the scope that owns it (`localIn`): a card by its top-left, a group by\n // its anchor, so its members — stored in its own frame — move with it.\n const onNodeDragStop = useCallback(\n (_e: React.MouseEvent, _draggedNode: Node, draggedNodes: Node[]) => {\n const positions: Record<string, { x: number; y: number }> = {};\n for (const n of draggedNodes) {\n positions[n.id] = localIn(view, n.id, drawnPosition(view.groups, n));\n }\n if (draggedNodes.length > 0) onDragStop(positions);\n },\n [onDragStop, view],\n );\n\n // ── Edge defaults ──\n // Colors reference design tokens via CSS custom properties: React's inline\n // `style` resolves `var(--...)` at render time. No arrowhead: a wire\n // always runs from an output on a node's right to an input on another's\n // left, and the filled pin it lands on already says the input is wired —\n // a marker there would only sit on top of the pin.\n const defaultEdgeOptions = {\n style: { stroke: 'var(--lace-canvas-edge-stroke)', strokeWidth: 1.5 },\n animated: false,\n };\n\n return (\n <ReactFlow\n onInit={onInit}\n nodes={rfNodes}\n edges={rfEdges}\n nodeTypes={nodeTypes}\n edgeTypes={edgeTypes}\n onNodesChange={onNodesChange}\n onEdgesChange={onEdgesChange}\n onConnect={onConnect}\n isValidConnection={isValidConnection}\n onEdgeClick={onEdgeClick}\n onEdgesDelete={onEdgesDelete}\n onNodesDelete={onNodesDelete}\n onSelectionChange={onSelectionChange}\n onNodeDragStop={onNodeDragStop}\n onNodeContextMenu={(e, node) => {\n e.preventDefault();\n // With no editor port we suppress the menu entirely — every\n // current item is a mutation. Render-gate at the dispatch source\n // so ContextMenu itself stays dumb.\n if (!editable) return;\n onContextMenu({\n instanceId: node.type === 'groupNode' ? null : node.id,\n groupId: node.type === 'groupNode' ? node.id : null,\n x: e.clientX,\n y: e.clientY,\n });\n }}\n onPaneContextMenu={(e) => {\n e.preventDefault();\n if (!editable) return;\n onContextMenu({ instanceId: null, groupId: null, x: e.clientX, y: e.clientY });\n }}\n defaultEdgeOptions={defaultEdgeOptions}\n connectionRadius={30}\n minZoom={0.15}\n maxZoom={2}\n // xyflow owns connect / reconnect / key-based delete. Drive its\n // native props instead of re-implementing the gates at our\n // handler layer.\n nodesConnectable={editable}\n edgesReconnectable={editable}\n deleteKeyCode={editable ? ['Backspace', 'Delete'] : null}\n fitView={false}\n proOptions={{ hideAttribution: true }}\n style={{ background: 'var(--lace-color-bg-canvas)' }}\n >\n <CanvasControls fitViewOptions={FIT_VIEW_OPTIONS} />\n <PaperGrid />\n {nodesInitialized ? <div hidden data-rendered=\"\" /> : null}\n </ReactFlow>\n );\n}\n\n// ══════════════════════════════════════════════════════════════════════\n// Canvas — top-level component that renders the pipeline's CanvasView.\n// All IR logic lives behind `ports.editor`/`ports.commands` — we only\n// render, and every mutation runs through the one `ActionRunner`\n// (`useCanvas().runner`) — `runner.apply` for a bare xyflow gesture with no\n// registered contribution (connect/disconnect), `runner.run` for everything\n// registered (toolbar/menu/row/key).\n// ══════════════════════════════════════════════════════════════════════\n\ntype CanvasProps = {\n height: React.CSSProperties['height'];\n};\n\nexport default function Canvas({ height }: CanvasProps) {\n const {\n ctx,\n runner,\n view,\n bundle,\n decorations,\n editable,\n arrangement,\n updateArrangement,\n selection,\n setSelection,\n layout,\n } = useCanvas();\n const editor = ctx.ports.editor;\n\n const makeEnvExtras = useCallback(\n (): EditorEnvExtras => ({\n bundle,\n arrangement: { get: () => arrangement, update: updateArrangement },\n layout,\n }),\n [bundle, arrangement, updateArrangement, layout],\n );\n\n // What the camera keeps in view when the pane changes size: the selected\n // nodes, or a selected connection's two ends.\n const focusIds = useMemo(\n () => (selection.edge ? [selection.edge.source, selection.edge.target] : selection.nodes),\n [selection],\n );\n\n // ── Hooks ──\n const { contextMenu, showContextMenu, dismissContextMenu } = useContextMenu();\n\n const { addedIds, newNodeIds, clearNew } = useNewNodeTracking(view);\n\n // A card the developer selects — by a click, a drag or opening it — no\n // longer draws as new.\n useEffect(() => {\n clearNew(...selection.nodes);\n }, [selection.nodes, clearNew]);\n\n // Whether a canvas edit is in progress, held as state: the runner reports\n // an edit settling right after the edit's last write, so the render that\n // draws what the edit placed reads it settled.\n const [editing, setEditing] = useState(() => runner.editing());\n useEffect(() => {\n setEditing(runner.editing());\n return runner.onEditingChange(setEditing);\n }, [runner]);\n\n // The pane's own DOM node — pan-into-view measures its visible size\n // against this, the same element `.lace-app__main`/`.lace-app__canvas`'s\n // `overflow: hidden` clips against.\n const paneRef = useRef<HTMLDivElement>(null);\n\n // This Canvas instance's own rendered subtree is the keymap's `surface`\n // target (`useActionKeys`, called by App against the same `ctx` object) —\n // registering it here, keyed on `ctx`, means a surface-scoped Mod+C never\n // fires from a keydown whose target is outside this element (a sibling\n // run-logs or diagnostics panel's selected text), and two Canvas mounts\n // on one page each register their own surface under their own `ctx`,\n // never the other's.\n const surfaceRef = useRef<HTMLDivElement>(null);\n useEffect(() => {\n registerKeyTarget(ctx, 'surface', surfaceRef.current);\n return () => registerKeyTarget(ctx, 'surface', null);\n }, [ctx]);\n\n // Standard canvas focus behaviour: a keydown only reaches the surface's\n // own listener when the surface (or a descendant) holds DOM focus — a\n // physical keypress targets `document.activeElement`, not wherever the\n // listener happens to be attached. Clicking a node or the pane takes\n // focus here so the very next Mod+S/Mod+Z reaches the keymap; a\n // pointerdown on a form control inside one of the canvas's own panels is\n // left alone so the control keeps the focus the browser already gives it.\n const onSurfacePointerDown = useCallback((e: React.PointerEvent<HTMLDivElement>) => {\n if (isFormTarget(e.target)) return;\n surfaceRef.current?.focus();\n }, []);\n\n // Stable ref for go-to-node — set by CompositeEditor\n const goToNodeRef = useRef<((nodeId: string) => void) | null>(null);\n const registerGoToNode = useCallback((fn: (nodeId: string) => void) => {\n goToNodeRef.current = fn;\n }, []);\n\n // ModuleNode's header click reaches this through `NodeConfigBusProvider`\n // (below) instead of a window `CustomEvent` — selecting the node opens\n // the module-config inspector panel (App's `selection.node`-gated slot),\n // and go-to-node re-centers the camera on it.\n const onOpenNodeConfig = useCallback(\n (instanceId: string) => {\n setSelection({ nodes: [instanceId], edge: null });\n goToNodeRef.current?.(instanceId);\n },\n [setSelection],\n );\n\n // ── Event: drag stop → write positions into the arrangement ──\n // Position is consumer-owned view state — it never touches the wire in\n // either mode, so drag persists identically whether editable or not\n // (unlike an IR mutation, there's nothing to gate). The Bundle is needed\n // to resolve each dragged canvas-path id to its (scopeKey, localId)\n // arrangement slot; the positions arrive already in that scope's frame.\n // A drop first stores what is around it where it is drawn\n // (`withScopesPinned`): each stays there unless what was dragged takes its\n // room, when it steps down just past that, and a box the drop grows grows\n // from where it is.\n const onDragStop = useCallback(\n (positions: Record<string, { x: number; y: number }>) => {\n const pinned = Object.keys(positions).reduce(\n (next, id) => withScopesPinned(bundle, view, next, id),\n arrangement,\n );\n updateArrangement(withNodePositions(bundle, pinned, positions));\n },\n [bundle, view, arrangement, updateArrangement],\n );\n\n // ── Event: new connection — connect/auto-connect have no registered\n // contribution (nothing places them on a toolbar/menu/key), so this\n // gesture goes straight through `runner.apply`, never `runner.run`. The\n // handles the drag joined pick the action: `node` to `node` is an\n // auto_connect, an output pin to an input pin a connect. xyflow calls this\n // only with a pair `isValidConnection` accepted, so a drag from the grip\n // ended on another node's card. The action names\n // each endpoint in the scope that owns it (`instanceAddress`): a wire is\n // an edit of one module, so a drag across a group's boundary names two\n // scopes and the engine refuses it, which the runner shows. The canvas\n // holds no wiring rule of its own: a drag onto an input that is already\n // bound is sent too, and the engine's connect replaces the binding as one\n // undoable edit.\n const onConnect = useCallback(\n async (conn: Connection) => {\n if (!conn.source || !conn.target || !editor) return;\n\n const source = instanceAddress(bundle, conn.source);\n const target = instanceAddress(bundle, conn.target);\n const ends = {\n scope: target.scope,\n source_scope: source.scope,\n source: source.id,\n target: target.id,\n };\n\n if (conn.sourceHandle === NODE_HANDLE) {\n await runner.apply([{ auto_connect: ends }]);\n return;\n }\n\n const srcName = parseHandleId(conn.sourceHandle, 'out');\n const tgtName = parseHandleId(conn.targetHandle, 'in');\n if (!srcName || !tgtName) return;\n\n await runner.apply([{ connect: { ...ends, source_output: srcName, target_input: tgtName } }]);\n },\n [editor, runner, bundle],\n );\n\n // ── Event: edge click → selects it, opening the edge-inspector panel ──\n const onEdgeClick = useCallback(\n (_e: React.MouseEvent, edge: Edge) => {\n const ref = edgeRefOf(edge);\n if (ref) setSelection({ nodes: [], edge: ref });\n },\n [setSelection],\n );\n\n // ── Event: edge delete — disconnect has no registered contribution. A\n // disconnect names the deleted edge's target in the scope that owns it.\n const onEdgesDelete = useCallback(\n async (edges: Edge[]) => {\n for (const edge of edges) {\n const data = rfEdgeData(edge);\n if (!data) continue;\n const target = instanceAddress(bundle, edge.target);\n await runner.apply([\n { disconnect: { scope: target.scope, target: target.id, input_name: data.target_input } },\n ]);\n }\n },\n [runner, bundle],\n );\n\n // ── Event: node delete (Backspace/Delete with a selection, or the\n // context menu) — every id routes through the registered `delete-node`\n // editor action via the runner, which itself falls back to `ungroup` for\n // a group node — one migration path, not a second copy of it here.\n const onNodesDelete = useCallback(\n async (nodes: Node[]) => {\n const action = ctx.contributions.actions.find((a) => a.id === 'delete-node');\n if (!action) return;\n const envExtras = makeEnvExtras();\n for (const node of nodes) {\n await runner.run(action, ctx, { nodeId: node.id }, envExtras);\n }\n },\n [ctx, runner, makeEnvExtras],\n );\n\n // What xyflow reports selected is the selection: its nodes, and its wire\n // when xyflow reports one wire alone. The selection names nodes or one\n // wire, so several wires, or wires beside nodes, name no wire.\n const onSelectionChange = useCallback(\n (params: { nodes: Node[]; edges: Edge[] }) => {\n const [wire, ...more] = params.edges;\n setSelection({\n nodes: params.nodes.map((n) => n.id),\n edge: wire && more.length === 0 && params.nodes.length === 0 ? edgeRefOf(wire) : null,\n });\n },\n [setSelection],\n );\n\n // ── Menu resolution — what the menu opened on decides its placement and\n // target: a node or a group opens the `node-menu` with it as the target,\n // the empty canvas the `pane-menu` with none.\n const menuTarget: ActionTarget = contextMenu\n ? contextMenu.groupId\n ? groupTarget(contextMenu.groupId)\n : { nodeId: contextMenu.nodeId ?? undefined }\n : NO_ENV_EXTRAS_TARGET;\n const menuActions = useMemo<readonly ActionContribution[]>(() => {\n if (!contextMenu) return [];\n const placement = menuTarget.nodeId === undefined ? 'pane-menu' : 'node-menu';\n return resolveContributions(ctx.contributions, ctx.ports, ctx, menuTarget).actions.filter(\n (a) => a.placement === placement,\n );\n }, [contextMenu, ctx, menuTarget]);\n\n const runMenuAction = useCallback(\n (action: ActionContribution) => {\n void runner.run(action, ctx, menuTarget, makeEnvExtras());\n },\n [runner, ctx, menuTarget, makeEnvExtras],\n );\n\n // ── Render ──\n // Inline layout instead of Tailwind utilities so this works in Storybook\n // (Tailwind v4 only scans canvas-stories, not @lace-cloud/canvas).\n // Children rely on the outer explicit height to place xyflow's docked\n // panels correctly — without it the ReactFlow container collapses. `App`\n // defaults it to the viewport for a canvas that owns the window; a host\n // panel that establishes its own height passes `100%`.\n return (\n <NodeConfigBusProvider onOpen={onOpenNodeConfig}>\n <div\n ref={surfaceRef}\n className=\"lace-canvas-surface\"\n tabIndex={0}\n onPointerDown={onSurfacePointerDown}\n style={{\n position: 'relative',\n display: 'flex',\n flexDirection: 'column',\n height,\n outline: 'none',\n }}\n >\n <ContextMenu\n contextMenu={contextMenu}\n actions={menuActions}\n onRun={runMenuAction}\n onDismiss={dismissContextMenu}\n />\n\n <div ref={paneRef} style={{ position: 'relative', flex: '1 1 auto', minHeight: 0 }}>\n <CompositeEditor\n view={view}\n editable={editable}\n addedIds={addedIds}\n newNodeIds={newNodeIds}\n editing={editing}\n onDragStop={onDragStop}\n onConnect={onConnect}\n onEdgeClick={onEdgeClick}\n onEdgesDelete={onEdgesDelete}\n onNodesDelete={onNodesDelete}\n onSelectionChange={onSelectionChange}\n onInit={() => {}}\n onContextMenu={showContextMenu}\n registerGoToNode={registerGoToNode}\n layout={layout}\n focusIds={focusIds}\n selection={selection}\n paneRef={paneRef}\n decorations={decorations}\n />\n {view.nodes.length === 0 && view.groups.length === 0 ? (\n <EmptyCanvas editable={editable} />\n ) : null}\n </div>\n </div>\n </NodeConfigBusProvider>\n );\n}\n","// The canvas's view controls — zoom out, the zoom level, zoom in, fit, the\n// minimap toggle — as one compact bar, the minimap above it while shown.\n// Both dock bottom-left: the toolbar holds the top edge and the drawer\n// opens on the right, its resize handle on that edge, so the bottom-left is\n// the one corner no other chrome claims or moves. View chrome, not\n// capabilities: these change what the developer sees, never the module,\n// so they render in every host, read-only ones included. Mounted as a\n// child of `ReactFlow`.\nimport { IconButton } from '@lace-cloud/ui';\nimport {\n type FitViewOptions,\n Panel as FlowPanel,\n MiniMap,\n type ReactFlowState,\n useReactFlow,\n useStore,\n} from '@xyflow/react';\nimport { useState } from 'react';\nimport { CanvasIcon } from './icons';\nimport './CanvasControls.css';\n\nconst zoomOf = (s: ReactFlowState) => s.transform[2];\nconst STEP = { duration: 150 };\n\nexport default function CanvasControls({ fitViewOptions }: { fitViewOptions: FitViewOptions }) {\n const { zoomIn, zoomOut, fitView } = useReactFlow();\n const zoom = useStore(zoomOf);\n const [showMiniMap, setShowMiniMap] = useState(false);\n return (\n <>\n {showMiniMap ? (\n <MiniMap\n position=\"bottom-left\"\n className=\"lace-canvas-minimap\"\n maskColor=\"var(--lace-canvas-minimap-mask)\"\n nodeColor=\"var(--lace-canvas-minimap-node)\"\n nodeStrokeWidth={0}\n pannable\n zoomable\n />\n ) : null}\n <FlowPanel position=\"bottom-left\" className=\"lace-canvas-controls\">\n <IconButton\n icon={<CanvasIcon name=\"zoom-out\" />}\n aria-label=\"Zoom out\"\n tooltipPlacement=\"top-start\"\n onClick={() => void zoomOut(STEP)}\n />\n <span className=\"lace-canvas-controls__zoom\" aria-live=\"polite\">\n {Math.round(zoom * 100)}%\n </span>\n <IconButton\n icon={<CanvasIcon name=\"zoom-in\" />}\n aria-label=\"Zoom in\"\n tooltipPlacement=\"top-start\"\n onClick={() => void zoomIn(STEP)}\n />\n <span className=\"lace-canvas-controls__rule\" aria-hidden=\"true\" />\n <IconButton\n icon={<CanvasIcon name=\"fit\" />}\n aria-label=\"Fit view\"\n tooltipPlacement=\"top-start\"\n onClick={() => void fitView(fitViewOptions)}\n />\n <IconButton\n icon={<CanvasIcon name=\"minimap\" />}\n aria-label=\"Minimap\"\n tooltipPlacement=\"top-start\"\n pressed={showMiniMap}\n onClick={() => setShowMiniMap((v) => !v)}\n />\n </FlowPanel>\n </>\n );\n}\n","// The canvas's glyphs, in Lace's house style — the portal's own icon\n// contract (apps/portal/src/components/icons): 24-unit outlines, a 1.5\n// stroke with round caps and joins, nothing filled. At the 16px a toolbar\n// draws them that is a one-pixel line, the weight of VS Code's Codicons, so\n// the chrome sits in either host. Each glyph is drawn at the size of the\n// text around it, in the current colour: a control's token colour\n// (muted, hover, disabled, primary) is its glyph's.\nimport type { ReactElement } from 'react';\nimport type { ActionIcon } from '../contribution-types';\nimport './icons.css';\n\nexport type CanvasGlyph =\n | ActionIcon\n | 'settings'\n | 'warning'\n | 'error'\n | 'info'\n | 'chevron-down'\n | 'chevron-right'\n | 'module'\n | 'group'\n | 'close'\n | 'minimap'\n | 'zoom-in'\n | 'zoom-out'\n | 'fit'\n | 'add';\n\nconst CIRCLE = 'M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z';\n\nconst GLYPHS: Record<CanvasGlyph, readonly string[]> = {\n // A tick in a circle: the tree checks out.\n validate: [CIRCLE, 'm8.5 12.5 2.5 2.5 4.5-5'],\n // Two opposed arrows: the module turned from one form into the other.\n convert: ['M8 3 4 7l4 4', 'M4 7h16', 'm16 21 4-4-4-4', 'M20 17H4'],\n save: [\n 'M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z',\n 'M17 21v-8H7v8',\n 'M7 3v5h8',\n ],\n // A wand: the saved IR made into the module's Terraform.\n generate: [\n 'm3 21 9-9',\n 'M15 4V2',\n 'M15 16v-2',\n 'M8 9h2',\n 'M20 9h2',\n 'M17.8 11.8 19 13',\n 'M17.8 6.2 19 5',\n 'M12.2 6.2 11 5',\n ],\n undo: ['M9 14 4 9l5-5', 'M4 9h10.5a5.5 5.5 0 0 1 0 11H11'],\n redo: ['m15 14 5-5-5-5', 'M20 9H9.5a5.5 5.5 0 0 0 0 11H13'],\n clear: [\n 'M3 6h18',\n 'M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6',\n 'M10 11v6',\n 'M14 11v6',\n 'M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2',\n ],\n settings: [\n 'M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z',\n 'M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z',\n ],\n warning: [\n 'M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z',\n 'M12 9v4',\n 'M12 17h.01',\n ],\n error: [CIRCLE, 'M12 8v4', 'M12 16h.01'],\n info: [CIRCLE, 'M12 16v-4', 'M12 8h.01'],\n 'chevron-down': ['m6 9 6 6 6-6'],\n 'chevron-right': ['m9 18 6-6-6-6'],\n // A box: one module call.\n module: [\n 'M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z',\n 'M3.27 6.96 12 12.01l8.73-5.05',\n 'M12 22.08V12',\n ],\n // Two boxes inside a frame's corners: calls held in one group.\n group: [\n 'M3 7V5a2 2 0 0 1 2-2h2',\n 'M17 3h2a2 2 0 0 1 2 2v2',\n 'M21 17v2a2 2 0 0 1-2 2h-2',\n 'M7 21H5a2 2 0 0 1-2-2v-2',\n 'M8 7h5a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1z',\n 'M11 12h5a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1h-5a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1z',\n ],\n close: ['M18 6 6 18', 'm6 6 12 12'],\n minimap: ['M1 6v16l7-4 8 4 7-4V2l-7 4-8-4-7 4z', 'M8 2v16', 'M16 6v16'],\n 'zoom-in': ['M12 5v14', 'M5 12h14'],\n 'zoom-out': ['M5 12h14'],\n // Four corners closing on the view: fit it to the graph.\n fit: [\n 'M3 8V5a2 2 0 0 1 2-2h3',\n 'M16 3h3a2 2 0 0 1 2 2v3',\n 'M21 16v3a2 2 0 0 1-2 2h-3',\n 'M8 21H5a2 2 0 0 1-2-2v-3',\n ],\n add: ['M12 5v14', 'M5 12h14'],\n};\n\nexport function CanvasIcon({ name }: { name: CanvasGlyph }): ReactElement {\n return (\n <svg className=\"lace-canvas-icon\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\">\n {GLYPHS[name].map((d) => (\n <path key={d} d={d} />\n ))}\n </svg>\n );\n}\n","// ContextMenu renders the menu contributions Canvas.tsx resolved for what\n// it opened on — the `node-menu` for a node or a group, the `pane-menu`\n// for the empty canvas — in their sections, a rule between sections and a\n// removing action in the danger tone (core/sections.ts). It owns no\n// copy/cut/paste/group semantics of its own, so a host-supplied menu action\n// renders exactly the way a core one does.\n//\n// It opens at the pointer and keeps all of itself inside the window: before\n// it paints, it measures its own box and moves to where `placeFloating`\n// (@lace-cloud/ui) puts a box hung from the pointer — upward when the\n// pointer is near the bottom, left when near the right, capped and scrolling\n// when taller than the window —\n// and it closes when the window it was placed in resizes or loses focus.\nimport { type FloatingPosition, placeFloating } from '@lace-cloud/ui';\nimport type React from 'react';\nimport { Fragment, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport type { ActionContribution } from '../contributions';\nimport { sectionsOf } from '../core/sections';\nimport type { ContextMenuState } from '../hooks/useContextMenu';\nimport { formatChord, isMacPlatform } from '../utils/key-chord';\nimport './ContextMenu.css';\n\n// The point a menu opens at, as the box it hangs from.\nconst atPoint = (x: number, y: number) => ({ left: x, right: x, top: y, bottom: y });\n\nfunction naturalSize(menu: HTMLElement): { width: number; height: number } {\n const box = menu.getBoundingClientRect();\n const borders = menu.offsetHeight - menu.clientHeight;\n return { width: box.width, height: Math.max(box.height, menu.scrollHeight + borders) };\n}\n\n// `Object.is`, so a placement that is not a number (an event that carried no\n// pointer coordinates) still equals itself and the menu settles.\nfunction samePlacement(a: FloatingPosition | null, b: FloatingPosition | null): boolean {\n return (\n a === b ||\n (a !== null &&\n b !== null &&\n Object.is(a.left, b.left) &&\n Object.is(a.top, b.top) &&\n Object.is(a.maxHeight, b.maxHeight))\n );\n}\n\ntype Props = {\n contextMenu: ContextMenuState;\n actions: readonly ActionContribution[];\n onRun: (action: ActionContribution) => void;\n onDismiss: () => void;\n};\n\nexport default function ContextMenu({ contextMenu, actions, onRun, onDismiss }: Props) {\n const menuRef = useRef<HTMLDivElement>(null);\n const [placement, setPlacement] = useState<FloatingPosition | null>(null);\n\n // After every render, before the browser paints: whatever the menu now\n // holds and wherever it opened, place it. Its natural height is its\n // content's (`scrollHeight` plus its borders), not the capped box an\n // earlier placement left it with.\n useLayoutEffect(() => {\n const menu = menuRef.current;\n const next =\n contextMenu && menu\n ? placeFloating(\n atPoint(contextMenu.x, contextMenu.y),\n naturalSize(menu),\n { width: window.innerWidth, height: window.innerHeight },\n 'bottom-start',\n { gap: 0, margin: 0 },\n )\n : null;\n setPlacement((current) => (samePlacement(current, next) ? current : next));\n });\n\n // A menu is placed for the window it opened in: a resize (a sash drag, a\n // panel toggled) or the window losing focus closes it rather than\n // leaving it placed for a window that has changed.\n const open = contextMenu !== null;\n useEffect(() => {\n if (!open) return;\n window.addEventListener('resize', onDismiss);\n window.addEventListener('blur', onDismiss);\n return () => {\n window.removeEventListener('resize', onDismiss);\n window.removeEventListener('blur', onDismiss);\n };\n }, [open, onDismiss]);\n\n // Keyboard: the first item takes focus as the menu opens; the arrows,\n // Home and End move between items; Escape and Tab close it.\n useEffect(() => {\n if (open) menuRef.current?.querySelector<HTMLButtonElement>('[role=\"menuitem\"]')?.focus();\n }, [open]);\n const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n e.stopPropagation();\n const items = Array.from(\n menuRef.current?.querySelectorAll<HTMLButtonElement>('[role=\"menuitem\"]') ?? [],\n );\n const at = items.findIndex((item) => item === document.activeElement);\n const focus = (index: number) => {\n e.preventDefault();\n items[(index + items.length) % items.length]?.focus();\n };\n if (e.key === 'ArrowDown') focus(at + 1);\n else if (e.key === 'ArrowUp') focus(at - 1);\n else if (e.key === 'Home') focus(0);\n else if (e.key === 'End') focus(items.length - 1);\n else if (e.key === 'Escape' || e.key === 'Tab') {\n e.preventDefault();\n onDismiss();\n }\n };\n\n if (!contextMenu) return null;\n const at = placement ?? { left: contextMenu.x, top: contextMenu.y };\n\n return (\n <>\n <div\n ref={menuRef}\n className=\"lace-ctx-menu\"\n role=\"menu\"\n style={{ left: at.left, top: at.top, maxHeight: placement?.maxHeight }}\n onMouseDown={(e) => e.stopPropagation()}\n onKeyDown={onKeyDown}\n >\n {sectionsOf(actions).map((section, index) => (\n <Fragment key={section.key ?? ''}>\n {index > 0 ? <hr className=\"lace-ctx-menu__separator\" /> : null}\n {section.actions.map((action) => {\n const chord = action.keys?.[0]\n ? formatChord(action.keys[0], isMacPlatform())\n : undefined;\n return (\n <button\n key={action.id}\n type=\"button\"\n role=\"menuitem\"\n className={`lace-ctx-menu__item${action.tone === 'danger' ? ' lace-ctx-menu__item--danger' : ''}`}\n onClick={() => {\n onRun(action);\n onDismiss();\n }}\n >\n <span>{action.label}</span>\n {chord ? <span className=\"lace-ctx-menu__shortcut\">{chord}</span> : null}\n </button>\n );\n })}\n </Fragment>\n ))}\n </div>\n <div className=\"lace-ctx-menu__scrim\" onClick={onDismiss} />\n </>\n );\n}\n","// How the toolbar and the menus arrange what resolved into them: actions in\n// sections by intent (`ActionContribution.section`), in the order each\n// section first appears, the actions naming none as one section after the\n// named ones. The toolbar also places its panels: each at the end of the\n// section it names, and those naming none (or a section no action resolved\n// into) at the row's far end. Both draw a hairline between sections.\nimport type { ActionContribution, PanelSpec } from '../contribution-types';\nimport { keySatisfied } from '../registry';\n\nexport type Section = {\n key: string | undefined;\n actions: readonly ActionContribution[];\n};\n\nexport function sectionsOf(actions: readonly ActionContribution[]): Section[] {\n const named = new Map<string, ActionContribution[]>();\n const unnamed: ActionContribution[] = [];\n for (const action of actions) {\n if (action.section === undefined) {\n unnamed.push(action);\n continue;\n }\n named.set(action.section, [...(named.get(action.section) ?? []), action]);\n }\n const sections: Section[] = [...named].map(([key, held]) => ({ key, actions: held }));\n if (unnamed.length > 0) sections.push({ key: undefined, actions: unnamed });\n return sections;\n}\n\nexport type ToolbarSection<P extends PanelSpec> = Section & { panels: readonly P[] };\n\nexport type ToolbarLayout<P extends PanelSpec> = {\n sections: readonly ToolbarSection<P>[];\n trailing: readonly P[];\n};\n\nexport function toolbarLayout<P extends PanelSpec>(\n actions: readonly ActionContribution[],\n panels: readonly P[],\n): ToolbarLayout<P> {\n const sections = sectionsOf(actions);\n const keys = new Set(\n sections.flatMap((section) => (section.key === undefined ? [] : [section.key])),\n );\n const placed = (panel: P) => panel.section !== undefined && keys.has(panel.section);\n return {\n sections: sections.map((section) => ({\n ...section,\n panels: panels.filter((panel) => placed(panel) && panel.section === section.key),\n })),\n trailing: panels.filter((panel) => !placed(panel)),\n };\n}\n\ntype KeyCtx = Parameters<typeof keySatisfied>[0];\n\n// Whether a primary action draws in the accent now: while its\n// `primary.when` holds, or always when it names none.\nexport function isEmphasized(action: ActionContribution, ctx: KeyCtx): boolean {\n if (!action.primary) return false;\n return action.primary.when === undefined || keySatisfied(ctx, action.primary.when);\n}\n","// The keymap's grammar for an action's key (`ActionContribution.keys`), read\n// and spelled in one place: `Mod`, an optional `Shift`, then the key —\n// `Mod+s`, `Mod+Shift+z`. The keymap (core/use-action-keys.ts) matches a\n// press by `parseChord`; the toolbar's tooltips and the menus spell it with\n// `formatChord`.\n\n/** The type an action's `keys` hold: a key that starts with `Mod+`. It is the\n * grammar's prefix check alone — the type cannot spell an optional `Shift`\n * then one key — and `parseChord` refuses the rest at runtime. */\nexport type KeySpec = `Mod+${string}`;\n\n/** A `keys` entry, read: whether it holds Shift, and the literal key. */\nexport type Chord = { shift: boolean; key: string };\n\n/**\n * The one parser of the grammar. `Mod` matches metaKey or ctrlKey on any\n * platform (the convention xyflow's own docs use). Undefined for an entry\n * outside the grammar, which no press matches.\n */\nexport function parseChord(spec: string): Chord | undefined {\n const [mod, ...rest] = spec.split('+');\n if (mod !== 'Mod') return undefined;\n if (rest.length === 1 && rest[0] !== '') return { shift: false, key: rest[0] };\n if (rest.length === 2 && rest[0] === 'Shift' && rest[1] !== '') {\n return { shift: true, key: rest[1] };\n }\n return undefined;\n}\n\n// How a key reads to the person pressing it. The keymap matches `Mod` on ⌘\n// or Ctrl on any platform; macOS spells it ⌘, after ⇧ in Apple's order\n// (⇧⌘Z), and elsewhere it is Ctrl, the names joined with `+`\n// (Ctrl+Shift+Z). Undefined for an entry outside the grammar, which no\n// press runs.\nexport function formatChord(spec: string, mac: boolean): string | undefined {\n const chord = parseChord(spec);\n if (!chord) return undefined;\n const key = chord.key.length === 1 ? chord.key.toUpperCase() : chord.key;\n if (mac) return `${chord.shift ? '⇧' : ''}⌘${key}`;\n return ['Ctrl', ...(chord.shift ? ['Shift'] : []), key].join('+');\n}\n\n// Whether the canvas runs on macOS, where `Mod` is spelled ⌘.\nexport function isMacPlatform(): boolean {\n return typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.userAgent);\n}\n","// What a canvas with nothing on it says, centred on the paper: that the\n// module calls no other modules, and on an editable canvas what a module\n// added to it becomes. It names no host's way of adding one; each host has\n// its own. It takes no pointer events, so the paper under it still pans and\n// still opens its menu (Paste).\nimport { EmptyState } from '@lace-cloud/ui';\nimport { CanvasIcon } from './icons';\nimport './EmptyCanvas.css';\n\nexport default function EmptyCanvas({ editable }: { editable: boolean }) {\n return (\n <div className=\"lace-canvas-empty\">\n <EmptyState\n icon={<CanvasIcon name=\"module\" />}\n title={\n editable ? 'This module calls no other modules yet' : 'This module calls no other modules'\n }\n description={\n editable\n ? 'A module you add lands here with its inputs and outputs, ready to wire.'\n : undefined\n }\n />\n </div>\n );\n}\n","// DependencyEdge.tsx — the canvas's only edge type. Endpoints stay on the\n// pin handles xyflow computed (sourceX/Y, targetX/Y) — see\n// dependency-edge-path.ts for why the path between them sometimes has to\n// loop rather than follow the stock bezier. Styling (stroke, selection,\n// hover) is identical to xyflow's default edge: it comes from\n// `defaultEdgeOptions`/CSS in Canvas.tsx, not from anything here.\n\nimport { BaseEdge, type EdgeProps, type EdgeTypes, useStore } from '@xyflow/react';\nimport { type Box, computeDependencyEdgePath } from './dependency-edge-path';\nimport { obstaclesFor } from './obstacles-for';\nimport { sceneNodesEqual, selectSceneNodes } from './scene-nodes';\n\n/** The `type` every RenderEdge is emitted with (useGroupLogic.ts) and the\n * key Canvas.tsx registers this component under — one name, so an edge\n * cannot be emitted under a type no renderer is registered for. */\nexport const DEPENDENCY_EDGE_TYPE = 'dependency';\n\nexport default function DependencyEdge({\n id,\n source,\n target,\n sourceX,\n sourceY,\n targetX,\n targetY,\n sourcePosition,\n targetPosition,\n style,\n markerStart,\n markerEnd,\n}: EdgeProps) {\n // Subscribed, not read once: a node this edge must bow around can move\n // without any prop of the edge changing (see scene-nodes.ts).\n const sceneNodes = useStore(selectSceneNodes, sceneNodesEqual);\n\n // An endpoint absent from the scene (an edge that arrived a frame before\n // its node) collapses to a point at its handle, so the path helper still\n // has a box to reason about.\n const endpointBox = (nodeId: string, x: number, y: number): Box =>\n sceneNodes.find((n) => n.id === nodeId)?.box ?? { x, y, width: 0, height: 0 };\n\n // Obstacle candidates are scope-resolved by `obstaclesFor`, not just\n // \"every other top-level node\" — a node inside an expanded group only\n // obstructs edges sharing its scope, and a group's own box is never an\n // obstacle for an edge leaving that same group (see obstacles-for.ts).\n const { path, labelX, labelY } = computeDependencyEdgePath({\n sourceX,\n sourceY,\n targetX,\n targetY,\n sourcePosition,\n targetPosition,\n sourceBox: endpointBox(source, sourceX, sourceY),\n targetBox: endpointBox(target, targetX, targetY),\n obstacleBoxes: obstaclesFor({ sourceId: source, targetId: target }, sceneNodes),\n });\n\n return (\n <BaseEdge\n id={id}\n path={path}\n labelX={labelX}\n labelY={labelY}\n style={style}\n markerStart={markerStart}\n markerEnd={markerEnd}\n // A test hook: the one thing that distinguishes this\n // connector's rendered path from xyflow's stock edge in the DOM.\n data-edge-kind=\"dependency\"\n />\n );\n}\n\n/** What Canvas.tsx hands xyflow as `edgeTypes`. */\nexport const edgeTypes = { [DEPENDENCY_EDGE_TYPE]: DependencyEdge } satisfies EdgeTypes;\n","// dependency-edge-path.ts — pure geometry for the canvas's directional\n// connector. Handle facing is fixed by side (inputs on a node's left,\n// outputs on its right — ModuleNode.tsx, GroupNode.tsx) regardless of\n// where the depth layout or a drag places either node, so the path from a\n// source OUTPUT handle to a target INPUT handle must always depart the\n// source heading +x and arrive at the target heading +x — that is the only\n// tangent pair that leaves an output and enters an input. xyflow's\n// stock bezier keeps that tangent pair by construction only while the\n// target sits to the right of the source; once it doesn't (a stored\n// arrangement or a drag places the consumer left of its source — the\n// BACKWARD shape), the same formula overshoots into a degenerate curve\n// that enters the input from the wrong side. And a bezier that IS forward can still cut\n// straight through an unrelated node sitting between source and target\n// (the SKIP-LEVEL shape). Both are solved the same way here: keep the\n// endpoints on the pin handles (never float them) and, whenever the\n// straight run between them isn't clear, route a straight-legged loop\n// through a vertical \"clearance rail\" that sits outside the vertical\n// extent of whatever it needs to clear, held at a horizontal offset\n// outside the box it just departed — each leg is a literal line segment\n// (not a bezier control point), which is what lets every leg's\n// box-clearance be proven from its own endpoints rather than from where a\n// curve merely passes near.\n\nimport { getBezierPath, type Position } from '@xyflow/react';\n\nexport type Box = { x: number; y: number; width: number; height: number };\nexport type Point = { x: number; y: number };\n\nexport type DependencyEdgePathParams = {\n sourceX: number;\n sourceY: number;\n targetX: number;\n targetY: number;\n sourcePosition: Position;\n targetPosition: Position;\n /** The source node's own box, in the same coordinate space as sourceX/Y. */\n sourceBox: Box;\n /** The target node's own box, in the same coordinate space as targetX/Y. */\n targetBox: Box;\n /**\n * Every other node's box that could sit between source and target — a\n * skip-level edge is bowed around whichever of these its straight\n * run would otherwise cross. Source's and target's own boxes are never\n * part of this list; they are handled via sourceBox/targetBox instead.\n */\n obstacleBoxes: readonly Box[];\n};\n\nexport type DependencyEdgePathResult = {\n path: string;\n labelX: number;\n labelY: number;\n};\n\n// LOOP_STUB is the horizontal run at each end of a bowed/looped path before\n// it turns toward the clearance rail — it exists solely to hold the\n// departure/arrival tangent at +x (see file header) for however many\n// pixels the SVG renders as a straight run before curving.\nconst LOOP_STUB = 24;\n// CLEARANCE is the margin every clearance rail keeps past the vertical\n// extent of whatever box (or pair of boxes) it clears.\nconst CLEARANCE = 24;\n\nfunction boxTop(b: Box): number {\n return b.y;\n}\nfunction boxBottom(b: Box): number {\n return b.y + b.height;\n}\nfunction boxLeft(b: Box): number {\n return b.x;\n}\nfunction boxRight(b: Box): number {\n return b.x + b.width;\n}\n\n// segmentCrossesBox is a coarse (bounding-box) overlap test between the\n// straight run [p0,p1] and a box — enough to decide whether a forward edge\n// needs to bow around an intermediate node, since the stock bezier between\n// two same-row nodes is itself nearly straight.\nfunction segmentCrossesBox(p0: Point, p1: Point, box: Box): boolean {\n const segMinX = Math.min(p0.x, p1.x);\n const segMaxX = Math.max(p0.x, p1.x);\n const segMinY = Math.min(p0.y, p1.y);\n const segMaxY = Math.max(p0.y, p1.y);\n return (\n segMaxX >= boxLeft(box) &&\n segMinX <= boxRight(box) &&\n segMaxY >= boxTop(box) &&\n segMinY <= boxBottom(box)\n );\n}\n\n// chooseClearanceY picks the vertical rail — above the topmost box's top\n// edge, or below the bottommost box's bottom edge, whichever is the\n// shorter detour from `referenceY` — so the loop always clears every box\n// in `boxes` by CLEARANCE regardless of which side it settles on.\nfunction chooseClearanceY(boxes: readonly Box[], referenceY: number): number {\n const top = Math.min(...boxes.map(boxTop));\n const bottom = Math.max(...boxes.map(boxBottom));\n const aboveDist = referenceY - top;\n const belowDist = bottom - referenceY;\n return aboveDist <= belowDist ? top - CLEARANCE : bottom + CLEARANCE;\n}\n\n/**\n * loopWaypoints returns the six points of the straight-legged loop shared\n * by the backward case and the forward-with-obstacle case, in order:\n * `source`, out to `railX1` at source's own y, up/down to `clearanceY`,\n * across to `railX2` at `clearanceY`, down/up to target's own y, into\n * `target`. Exported so the regression test walks the exact geometry\n * `loopedPath` renders rather than re-deriving it.\n */\nexport function loopWaypoints(\n source: Point,\n target: Point,\n railX1: number,\n railX2: number,\n clearanceY: number,\n): [Point, Point, Point, Point, Point, Point] {\n return [\n source,\n { x: railX1, y: source.y },\n { x: railX1, y: clearanceY },\n { x: railX2, y: clearanceY },\n { x: railX2, y: target.y },\n target,\n ];\n}\n\n// loopedPath renders `loopWaypoints` as a straight-legged SVG path (`L`\n// between each waypoint). Every leg is a literal line segment, so each\n// leg's box-clearance is a property of its own two endpoints — outside\n// its own endpoint's box (the source/target stub legs) or outside every\n// relevant box's y-range entirely (the clearanceY leg) — not of a curve\n// that merely passes near the waypoints without touching them.\nfunction loopedPath(\n source: Point,\n target: Point,\n railX1: number,\n railX2: number,\n clearanceY: number,\n): DependencyEdgePathResult {\n const points = loopWaypoints(source, target, railX1, railX2, clearanceY);\n const path = points.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x},${p.y}`).join(' ');\n return { path, labelX: (railX1 + railX2) / 2, labelY: clearanceY };\n}\n\n/**\n * computeDependencyEdgePath is the single pure function behind\n * `DependencyEdge`: given both endpoints' handle points/positions and the\n * boxes that matter (source, target, everything else on the canvas), it\n * returns an SVG path that always departs the source heading +x and\n * arrives at the target heading +x.\n *\n * - Backward (target sits left of source): loops above or below BOTH\n * node boxes via a clearance rail held outside their combined box range.\n * - Forward and clear: the stock xyflow bezier, unchanged.\n * - Forward but blocked (a skip-level edge over an intermediate\n * node): the same loop shape, railed around whichever obstacle box(es)\n * the straight run would otherwise cross.\n */\nexport function computeDependencyEdgePath(\n params: DependencyEdgePathParams,\n): DependencyEdgePathResult {\n const {\n sourceX,\n sourceY,\n targetX,\n targetY,\n sourcePosition,\n targetPosition,\n sourceBox,\n targetBox,\n obstacleBoxes,\n } = params;\n const source: Point = { x: sourceX, y: sourceY };\n const target: Point = { x: targetX, y: targetY };\n\n // xyflow's bezier curvature offset overshoots specifically once\n // target.x < source.x.\n if (targetX < sourceX) {\n const clearanceY = chooseClearanceY([sourceBox, targetBox], (sourceY + targetY) / 2);\n const railX1 = boxRight(sourceBox) + CLEARANCE;\n const railX2 = boxLeft(targetBox) - CLEARANCE;\n return loopedPath(source, target, railX1, railX2, clearanceY);\n }\n\n const blocking = obstacleBoxes.filter((box) => segmentCrossesBox(source, target, box));\n if (blocking.length === 0) {\n const [path, labelX, labelY] = getBezierPath({\n sourceX,\n sourceY,\n sourcePosition,\n targetX,\n targetY,\n targetPosition,\n });\n return { path, labelX, labelY };\n }\n\n const clearanceY = chooseClearanceY(blocking, (sourceY + targetY) / 2);\n const railX1 = sourceX + LOOP_STUB;\n const railX2 = targetX - LOOP_STUB;\n return loopedPath(source, target, railX1, railX2, clearanceY);\n}\n","// obstacles-for.ts — pure scope resolution for `computeDependencyEdgePath`'s\n// `obstacleBoxes`. A box is only a genuine obstacle if it sits\n// in the same rendering scope as the edge it might block:\n//\n// - Two top-level nodes: every OTHER top-level box is a candidate — an\n// expanded group renders as one box on that same top-level canvas, so it\n// counts as a single obstacle the same as any module node.\n// - Two siblings inside the same expanded group: only their fellow\n// siblings in that group are candidates. A top-level node three group\n// widths away is nowhere near the edge and would never legitimately\n// block it.\n// - A cross-boundary edge (a node inside an expanded group wired to\n// something outside it): candidates are every top-level box PLUS the\n// inside endpoint's siblings — the edge visually crosses both scopes,\n// so both scopes' boxes are in play.\n//\n// Whichever candidates that scope resolution produces, one rule prunes\n// them down to genuine obstacles: a box that CONTAINS either endpoint is\n// never an obstacle. Without it, an edge leaving an expanded group would\n// see its own enclosing container as something to bow around — every edge\n// leaving a group would loop around the group it just left.\n\nimport type { Box } from './dependency-edge-path';\n\nexport type SceneNode = {\n id: string;\n box: Box;\n /** Absent/undefined for a top-level node; the enclosing group's id for a\n * node rendered inside an expanded group. */\n parentId?: string;\n};\n\nexport type SceneEdge = {\n sourceId: string;\n targetId: string;\n};\n\nconst TOP_LEVEL = Symbol('top-level scope');\n\nfunction scopeOf(node: SceneNode): string | typeof TOP_LEVEL {\n return node.parentId ?? TOP_LEVEL;\n}\n\nfunction boxContains(outer: Box, inner: Box): boolean {\n return (\n outer.x <= inner.x &&\n outer.y <= inner.y &&\n outer.x + outer.width >= inner.x + inner.width &&\n outer.y + outer.height >= inner.y + inner.height\n );\n}\n\nexport function obstaclesFor(edge: SceneEdge, nodes: readonly SceneNode[]): Box[] {\n const byId = new Map(nodes.map((n) => [n.id, n]));\n const source = byId.get(edge.sourceId);\n const target = byId.get(edge.targetId);\n if (!source || !target) return [];\n\n const sourceScope = scopeOf(source);\n const targetScope = scopeOf(target);\n\n const candidates = new Map<string, SceneNode>();\n const addScope = (scope: string | typeof TOP_LEVEL) => {\n for (const n of nodes) {\n if (scopeOf(n) === scope) candidates.set(n.id, n);\n }\n };\n\n if (sourceScope === TOP_LEVEL && targetScope === TOP_LEVEL) {\n addScope(TOP_LEVEL);\n } else if (sourceScope === targetScope) {\n addScope(sourceScope);\n } else {\n // Cross-boundary: the edge is visible on the top-level canvas AND\n // inside whichever group its inside endpoint belongs to.\n addScope(TOP_LEVEL);\n if (sourceScope !== TOP_LEVEL) addScope(sourceScope);\n if (targetScope !== TOP_LEVEL) addScope(targetScope);\n }\n\n candidates.delete(source.id);\n candidates.delete(target.id);\n\n return [...candidates.values()]\n .map((n) => n.box)\n .filter((box) => !boxContains(box, source.box) && !boxContains(box, target.box));\n}\n","// scene-nodes.ts — the xyflow store read `DependencyEdge` routes from, as a\n// selector plus its equality. An edge's own props (its two handle points)\n// change only when ITS endpoints move; the boxes it must bow around belong\n// to other nodes, and a drag of one of those changes nothing xyflow hands\n// the edge. So the boxes are subscribed to through the store, compared by\n// value: the edge re-renders exactly when a visible node's box or scope\n// changes, and not on the store writes (selection, viewport, hover) that\n// move no box.\n\nimport type { InternalNode, ReactFlowState } from '@xyflow/react';\nimport type { Box } from './dependency-edge-path';\nimport type { SceneNode } from './obstacles-for';\n\n/**\n * A node's box in flow coordinates. A node not yet measured (first paint,\n * before xyflow's ResizeObserver has reported its size) has no size, so its\n * box collapses to a point at its position — enough for the path helper to\n * reason about until layout settles a frame later.\n */\nexport function nodeBox(node: InternalNode): Box {\n return {\n x: node.internals.positionAbsolute.x,\n y: node.internals.positionAbsolute.y,\n width: node.measured.width ?? 0,\n height: node.measured.height ?? 0,\n };\n}\n\n/** Every visible node's id, scope and box, in lookup order. */\nexport function selectSceneNodes(state: Pick<ReactFlowState, 'nodeLookup'>): SceneNode[] {\n const scene: SceneNode[] = [];\n for (const node of state.nodeLookup.values()) {\n if (node.hidden) continue;\n scene.push({ id: node.id, parentId: node.parentId, box: nodeBox(node) });\n }\n return scene;\n}\n\nfunction sameBox(a: Box, b: Box): boolean {\n return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;\n}\n\n/** True when no box, scope or membership differs — the render is skipped. */\nexport function sceneNodesEqual(a: readonly SceneNode[], b: readonly SceneNode[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((node, i) => {\n const other = b[i];\n return node.id === other.id && node.parentId === other.parentId && sameBox(node.box, other.box);\n });\n}\n","import {\n COLLAPSED_GROUP_WIDTH,\n collapsedGroupSize,\n GROUP_HEADER_HEIGHT,\n groupPinY,\n NODE_ROW_HEIGHT,\n} from '@lace-cloud/proto';\nimport { Handle, type Node, type NodeProps, Position } from '@xyflow/react';\nimport type React from 'react';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { Badge } from '../../contributions';\nimport { groupTarget } from '../../core/editor-actions';\nimport { useEditorEnvExtras } from '../../core/panels/row-actions';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { NodePin } from '../../types/render';\nimport { withGroupCollapsed } from '../../utils/arrangement';\nimport { CanvasIcon } from '../icons';\nimport './GroupNode.css';\nimport { useRenameInstance } from './use-rename-instance';\n\n// ── Data contract ──\n\n// One pin of a collapsed group's interface, on its card's rail.\nexport type InterfacePin = NodePin & {\n handleId: string; // e.g. \"out:vpc_id\"\n side: 'input' | 'output';\n color: { fill: string; stroke: string };\n};\n\nexport type GroupNodeData = {\n groupId: string;\n // The target module the group Use points at. Every group is a Use\n // whose target has its own sub-Uses (CreateGroupAction mints a\n // module) — this is that module's key, needed to migrate the group's\n // interior arrangement back to the parent scope on ungroup.\n moduleKey: string;\n label: string;\n memberCount: number;\n collapsed: boolean;\n hasErrors: boolean;\n // Badges the diagnostics decoration attached to this group's own scope —\n // `nodeIdForAddress` resolves a submodule-root address to the group's\n // own id, not any member's, so these are the one place that decoration\n // is visible at all while collapsed (every member's own badge is\n // hidden). Same chip shape ModuleNode's own `badges` renders.\n badges: readonly Badge[];\n interfacePins: InterfacePin[];\n};\n\ntype GroupNodeNode = Node<GroupNodeData, 'groupNode'>;\n\n// ── Layout constants ──\n\n// The group's geometry is the projection's (proto geometry.ts): its\n// collapsed card is drawn here at `collapsedGroupSize`, each pin's row\n// centred at `groupPinY`, where the layout lands its wire; its expanded box\n// at the size the projection gives the xyflow node (useGroupLogic).\n\n// ── Shared header ──\n\ntype GroupHeaderProps = {\n label: string;\n memberCount: number;\n collapsed: boolean;\n hovered: boolean;\n editing: boolean;\n editValue: string;\n inputRef: React.RefObject<HTMLInputElement>;\n onToggleCollapsed: (e: React.MouseEvent) => void;\n onUngroup: (e: React.MouseEvent) => void;\n onDoubleClick: (e: React.MouseEvent) => void;\n onEditChange: (value: string) => void;\n onEditBlur: () => void;\n onEditKeyDown: (e: React.KeyboardEvent) => void;\n};\n\nconst GroupHeader: React.FC<GroupHeaderProps> = ({\n label,\n memberCount,\n collapsed,\n hovered,\n editing,\n editValue,\n inputRef,\n onToggleCollapsed,\n onUngroup,\n onDoubleClick,\n onEditChange,\n onEditBlur,\n onEditKeyDown,\n}) => (\n <div\n className={`lace-group-node__header lace-group-node__header--${collapsed ? 'collapsed' : 'expanded'}`}\n style={collapsed ? { height: GROUP_HEADER_HEIGHT } : undefined}\n >\n <button\n type=\"button\"\n onClick={onToggleCollapsed}\n className=\"lace-group-node__collapse-btn\"\n title={collapsed ? 'Expand' : 'Collapse'}\n aria-label={collapsed ? 'Expand' : 'Collapse'}\n >\n <CanvasIcon name={collapsed ? 'chevron-right' : 'chevron-down'} />\n </button>\n <span className=\"lace-group-node__glyph\">\n <CanvasIcon name=\"group\" />\n </span>\n\n {editing ? (\n <input\n ref={inputRef}\n value={editValue}\n onChange={(e) => onEditChange(e.target.value)}\n onBlur={onEditBlur}\n onKeyDown={onEditKeyDown}\n className=\"lace-group-node__rename-input\"\n onClick={(e) => e.stopPropagation()}\n />\n ) : (\n <span className=\"lace-group-node__label\" onDoubleClick={onDoubleClick} title={label}>\n {label}\n </span>\n )}\n\n <span className=\"lace-group-node__count\">\n {memberCount} {memberCount === 1 ? 'module' : 'modules'}\n </span>\n\n {hovered && (\n <button\n type=\"button\"\n onClick={onUngroup}\n className=\"lace-group-node__ungroup-btn\"\n title=\"Ungroup\"\n aria-label=\"Ungroup\"\n >\n <CanvasIcon name=\"close\" />\n </button>\n )}\n </div>\n);\n\n// ── Badges: same chip shape and `data-badge`/`data-tone` contract\n// ModuleNode's own badge row renders — a diagnostic addressed to this\n// group's own scope is otherwise invisible while collapsed. ──\n\nconst GroupBadges: React.FC<{ badges: readonly Badge[] }> = ({ badges }) =>\n badges.length === 0 ? null : (\n <div className=\"lace-group-node__badges\">\n {badges.map((b) => (\n <span\n key={b.id}\n data-badge={b.id}\n data-tone={b.tone}\n className={`lace-group-node__badge lace-group-node__badge--${b.tone}`}\n title={b.title ?? b.label}\n >\n {b.label}\n </span>\n ))}\n </div>\n );\n\n// ── Interface pin row (collapsed state) ──\n\n// One pin's row on the card, centred on `y` from the card's top\n// (`groupPinY`), where the layout lands its wire.\nconst InterfacePinRow: React.FC<{ pin: InterfacePin; y: number }> = ({ pin, y }) => {\n const isInput = pin.side === 'input';\n return (\n <div\n style={{\n position: 'absolute',\n top: y - NODE_ROW_HEIGHT / 2,\n left: 0,\n right: 0,\n height: NODE_ROW_HEIGHT,\n paddingLeft: isInput ? 12 : 8,\n paddingRight: isInput ? 8 : 12,\n display: 'flex',\n alignItems: 'center',\n justifyContent: isInput ? 'flex-start' : 'flex-end',\n }}\n title={pin.name}\n >\n <Handle\n id={pin.handleId}\n type={isInput ? 'target' : 'source'}\n position={isInput ? Position.Left : Position.Right}\n isConnectable={false}\n className=\"lace-pin-handle\"\n style={{\n background: pin.color.fill,\n borderColor: pin.color.stroke,\n borderWidth: 1,\n borderStyle: 'solid',\n width: 10,\n height: 10,\n [isInput ? 'left' : 'right']: -5,\n top: NODE_ROW_HEIGHT / 2,\n }}\n />\n <span className=\"lace-group-node__pin-label\" style={{ maxWidth: COLLAPSED_GROUP_WIDTH - 28 }}>\n {pin.name}\n </span>\n </div>\n );\n};\n\n// ── Component ──\n\nconst GroupNode: React.FC<NodeProps<GroupNodeNode>> = ({ data }) => {\n const { editable, ctx, runner, bundle, arrangement, updateArrangement } = useCanvas();\n const rename = useRenameInstance();\n const envExtras = useEditorEnvExtras();\n const [editing, setEditing] = useState(false);\n const [editValue, setEditValue] = useState(data.label);\n const [hovered, setHovered] = useState(false);\n const inputRef = useRef<HTMLInputElement>(null);\n\n // `data.collapsed` is the projection's: the arrangement's collapsed\n // state, read into the view by `projectCanvasView`, so there is nothing\n // to derive here.\n const collapsed = data.collapsed;\n\n useEffect(() => {\n if (editing && inputRef.current) {\n inputRef.current.focus();\n inputRef.current.select();\n }\n }, [editing]);\n\n const onDoubleClick = useCallback(\n (e: React.MouseEvent) => {\n if (!editable) return;\n e.stopPropagation();\n setEditValue(data.label);\n setEditing(true);\n },\n [data.label, editable],\n );\n\n // A group's one name is its Use id, so renaming it renames the instance\n // in the scope that owns it — the same rename a module node sends\n // (`useRenameInstance`) — and the group keeps its place, its collapsed\n // state and its selection under the new name.\n const renamingRef = useRef(false);\n const commitRename = useCallback(async () => {\n if (renamingRef.current) return;\n renamingRef.current = true;\n setEditing(false);\n await rename(data.groupId, editValue.trim());\n renamingRef.current = false;\n }, [editValue, data.groupId, rename]);\n\n const onKeyDown = useCallback(\n (e: React.KeyboardEvent) => {\n e.stopPropagation();\n if (e.key === 'Enter') commitRename();\n else if (e.key === 'Escape') setEditing(false);\n },\n [commitRename],\n );\n\n const toggleCollapsed = useCallback(\n (e: React.MouseEvent) => {\n e.stopPropagation();\n updateArrangement(withGroupCollapsed(bundle, arrangement, data.groupId, !data.collapsed));\n },\n [bundle, data.groupId, data.collapsed, arrangement, updateArrangement],\n );\n\n // Ungroup runs the registered `ungroup` contribution through the runner —\n // the identical migration path (arrangement migration included) the node\n // menu's own Ungroup entry uses, so a failure takes the runner's one\n // error path (`presenter.notify`) instead of a console log nobody sees.\n const onUngroup = useCallback(\n async (e: React.MouseEvent) => {\n e.stopPropagation();\n const action = ctx.contributions.actions.find((a) => a.id === 'ungroup');\n if (!action) return;\n await runner.run(action, ctx, groupTarget(data.groupId), envExtras);\n },\n [ctx, runner, envExtras, data.groupId],\n );\n\n const headerProps = {\n label: data.label,\n memberCount: data.memberCount,\n collapsed,\n hovered: hovered && editable,\n editing,\n editValue,\n inputRef,\n onToggleCollapsed: toggleCollapsed,\n onUngroup,\n onDoubleClick,\n onEditChange: setEditValue,\n onEditBlur: commitRename,\n onEditKeyDown: onKeyDown,\n };\n\n // ── Collapsed rendering ──\n\n if (collapsed) {\n const inputs = data.interfacePins.filter((p) => p.side === 'input');\n const outputs = data.interfacePins.filter((p) => p.side === 'output');\n const bare = data.interfacePins.length === 0;\n\n return (\n <div\n data-group={data.groupId}\n data-collapsed=\"true\"\n className={`lace-group-node lace-group-node--collapsed${bare ? ' lace-group-node--bare' : ''}${data.hasErrors ? ' lace-group-node--error' : ''}`}\n style={collapsedGroupSize({ inputs, outputs })}\n onMouseEnter={() => setHovered(true)}\n onMouseLeave={() => setHovered(false)}\n >\n <GroupHeader {...headerProps} />\n <GroupBadges badges={data.badges} />\n {inputs.map((pin, i) => (\n <InterfacePinRow key={pin.handleId} pin={pin} y={groupPinY(i)} />\n ))}\n {outputs.map((pin, i) => (\n <InterfacePinRow key={pin.handleId} pin={pin} y={groupPinY(i)} />\n ))}\n </div>\n );\n }\n\n // ── Expanded rendering ──\n\n return (\n <div\n data-group={data.groupId}\n data-collapsed=\"false\"\n className=\"lace-group-node lace-group-node--expanded\"\n style={{ width: '100%', height: '100%' }}\n onMouseEnter={() => setHovered(true)}\n onMouseLeave={() => setHovered(false)}\n >\n <GroupHeader {...headerProps} />\n <GroupBadges badges={data.badges} />\n </div>\n );\n};\n\nexport default GroupNode;\n","// The editor bindings: every IR edit / generate / conflict-resolution the\n// canvas core registers, bound the same way a command is — through\n// `EditorBinding` (contributions.ts) — so a mutation the toolbar, a node\n// menu, or a keybinding fires runs through the one `ActionRunner` execution\n// path (confirm → invoke → route → tick), never a direct `ports.editor`\n// call from a component. `run()` bodies are pure functions of `EditorEnv`:\n// copy/cut/paste/group/ungroup source their selection from `ctx.selection`/\n// `target.nodeId`, never an imperative xyflow ref, so the identical binding\n// runs from a node-menu click, a keybinding, or any future host contribution.\nimport {\n boxAt,\n drawnRect,\n extentOf,\n freeSlot,\n groupBoxSize,\n groupPins,\n groupReach,\n instanceAddress,\n joinPath,\n type KeepKey,\n keepOrder,\n localIn,\n originAt,\n type Rect,\n reachRect,\n splitPath,\n stepDown,\n type XY,\n} from '@lace-cloud/proto';\nimport type { ActionContribution, ActionTarget, EditorBinding, EditorEnv } from '../contributions';\nimport { Reason } from '../generated/service';\nimport type { Bundle } from '../generated/state';\nimport { type ApplyResult, type CreatedRef, currentFrame, type GenerateEvent } from '../ports';\nimport type { CanvasArrangement, CanvasView } from '../types/render';\nimport { migrateUngroup, setScopeEntry, withScopesPinned } from '../utils/arrangement';\nimport { entryScopeIds, inEntryScope } from './entry-scope';\n\nfunction emptyApplyResult(message?: string): ApplyResult {\n if (!message) return { success: true, errors: [], created: [], ties: [] };\n return {\n success: false,\n errors: [\n { moduleKey: '', instanceId: '', inputName: '', message, reason: Reason.REASON_UNSPECIFIED },\n ],\n created: [],\n ties: [],\n };\n}\n\n// Every copy/cut source is the selection the host reports through\n// `ctx.selection`, plus the node the context menu was opened on when that\n// node isn't already part of it, narrowed to the ids the engine addresses:\n// the entry scope's own (`entryScopeIds`). When that narrowing leaves\n// nothing there is no source, and `refusal` names which of the two causes\n// it was — nothing was chosen, or everything chosen sits inside a group —\n// read off the chosen ids against their entry-scope part.\ntype CopySource = { ids: readonly string[] } | { refusal: string };\n\nfunction copySource(env: EditorEnv): CopySource {\n const selected = env.ctx.selection.nodes;\n const menuId = env.target.nodeId;\n const chosen = menuId && !selected.includes(menuId) ? [...selected, menuId] : selected;\n const ids = inEntryScope(env.ctx.view, chosen);\n if (ids.length > 0) return { ids };\n return {\n refusal:\n chosen.length === 0\n ? 'Nothing selected — click a node first'\n : 'The selection is inside a group — copy and cut act on top-level nodes and groups',\n };\n}\n\n// placeCreatedClones positions every pasted clone from the mutation's\n// `created` refs (never by diffing before/after CanvasView frames — the\n// CreatedRef contract exists precisely so callers don't have to guess\n// which ids are new). A paste addresses the entry scope, so its clones and\n// their sources are the entry's. The clones are one cluster: each drawn\n// where its source is, relative to the others. The cluster's extent is\n// everything the clones can draw — a card's rect, a group's reach, its card\n// and its expanded box alike (`reachRect`). Expanding a pasted group later\n// takes its room as its source's does, over a card of its own cluster too;\n// what that pushes depends on what is around it. The cluster takes the\n// scope's free slot for that extent (`freeSlot`), clear of everything the\n// scope draws by the layout's gap; and the scope is pinned where it is drawn\n// (`withScopesPinned`), so the paste moves nothing already there.\nfunction placeCreatedClones(\n bundle: Bundle,\n view: CanvasView,\n arrangement: CanvasArrangement,\n created: readonly CreatedRef[],\n): CanvasArrangement {\n // Each source by what it can draw and the position that draws it there: a\n // group's is its anchor, its box reaching past it as its members do — as\n // the clone's will, sharing the source's module.\n const sources = new Map<string, { sourceId: string; rect: Rect; stored: XY }>();\n for (const ref of created) {\n const rect =\n ref.scope === bundle.entry && ref.sourceId ? reachRect(view, ref.sourceId) : undefined;\n if (rect) {\n sources.set(ref.id, {\n sourceId: ref.sourceId,\n rect,\n stored: localIn(view, ref.sourceId, rect),\n });\n }\n }\n const first = sources.values().next().value;\n if (!first) return arrangement;\n const extent = extentOf([...sources.values()].map((s) => s.rect));\n const occupied = entryScopeIds(view).flatMap((id) => drawnRect(view, id) ?? []);\n const slot = freeSlot(extent, occupied);\n\n const pinned = withScopesPinned(bundle, view, arrangement, first.sourceId);\n const scopeEntry = pinned[bundle.entry] ?? {};\n const placed: Record<string, XY> = {};\n for (const [id, { stored }] of sources) {\n placed[id] = { x: slot.x - extent.x + stored.x, y: slot.y - extent.y + stored.y };\n }\n return setScopeEntry(pinned, bundle.entry, {\n ...scopeEntry,\n nodes: { ...scopeEntry.nodes, ...placed },\n });\n}\n\nasync function saveRun(env: EditorEnv): Promise<void> {\n // No \"Saved\" notify — the Unsaved marker clearing (App.tsx) is the status.\n await env.editor.save();\n}\n\nfunction generateRun(env: EditorEnv): AsyncIterable<GenerateEvent> {\n return env.editor.generate();\n}\n\n// Run only while the frame holds an edit to undo or redo: the runner refuses\n// Undo and Redo otherwise (their `enabledWhen`), saying so.\nasync function undoRun(env: EditorEnv): Promise<ApplyResult> {\n return env.apply([{ undo: {} }]);\n}\n\nasync function redoRun(env: EditorEnv): Promise<ApplyResult> {\n return env.apply([{ redo: {} }]);\n}\n\n// One `apply` batch with one delete per entry-scope node and group — a\n// single undo entry, not a loop of N separate ApplyAction calls. Deleting a\n// group Use deletes its children with it, so the batch addresses the entry\n// alone.\nasync function clearGraphRun(env: EditorEnv): Promise<ApplyResult> {\n const ids = entryScopeIds(env.ctx.view);\n if (ids.length === 0) return emptyApplyResult();\n const scope = env.bundle.entry;\n return env.apply(ids.map((id) => ({ delete_instance: { scope, instance_id: id } })));\n}\n\n// Copy and cut are the same clipboard write; `cut` marks the sources for\n// deletion in the batch a paste sends.\nfunction clipRun(cut: boolean): (env: EditorEnv) => Promise<void> {\n return async (env) => {\n const source = copySource(env);\n if ('refusal' in source) {\n env.ctx.ports.presenter.notify('error', source.refusal);\n return;\n }\n const { ids } = source;\n env.clipboard.set(ids, cut);\n env.ctx.ports.presenter.notify(\n 'info',\n `${cut ? 'Cut' : 'Copied'} ${ids.length} node${ids.length > 1 ? 's' : ''}`,\n );\n };\n}\n\nasync function pasteRun(env: EditorEnv): Promise<ApplyResult> {\n const clip = env.clipboard.get();\n if (!clip) {\n env.ctx.ports.presenter.notify('error', 'Clipboard empty — copy a node first');\n return emptyApplyResult();\n }\n const { ids, cut } = clip;\n // The clipboard holds entry-scope ids (`copySource`), so the batch\n // addresses the entry. Cut+paste is the clone plus every original's own\n // delete in the ONE apply batch (one undo entry) — a cut+paste an undo\n // has to walk back through N+1 entries because the deletes were N\n // separate calls is the same \"N+1 undo entries\" this batches away.\n const scope = env.bundle.entry;\n const actions = cut\n ? [\n { copy_instances: { scope, instance_ids: [...ids] } },\n ...ids.map((id) => ({ delete_instance: { scope, instance_id: id } })),\n ]\n : [{ copy_instances: { scope, instance_ids: [...ids] } }];\n const result = await env.apply(actions);\n if (!result.success) return result;\n\n const created = result.created.filter((c) => c.sourceId);\n if (created.length === 0) {\n if (!cut) {\n // The engine reported success but named no created children — the\n // user has no visual feedback to lean on otherwise. Cut + paste runs\n // into this naturally when the clone reuses freed ids; left alone.\n env.ctx.ports.presenter.notify('error', 'Paste produced no new nodes — nothing pasted');\n }\n } else {\n env.arrangement.update(\n placeCreatedClones(env.bundle, env.ctx.view, env.arrangement.get(), created),\n );\n }\n\n if (cut) env.clipboard.clear();\n return result;\n}\n\n// CreateGroupAction's wire payload carries only membership. The server\n// reports the minted module via `result.created` (one CreatedRef: scope =\n// the parent scope the group was created in, id = the new group Use's id,\n// moduleKey = the new module). The group's members' frame starts where the\n// top-left-most member is drawn, so every member — a card or a group,\n// stored or laid out — is stored in the new module's scope where it is\n// drawn now, keeping their arrangement, and the group itself in the\n// parent's frame at its anchor, its header and padding up and left of them\n// (`boxAt`). Inside a group's scope the anchor is first lowered, if need\n// be, to the top of what the enclosing group holds — its members and its\n// members' frame origin, which its box always holds (`originAt`) — so the\n// enclosing group grows left, right or down by the padding to hold it,\n// never up. A member group's collapsed\n// state moves with it, and everything in the scopes around the write is\n// stored where it is drawn (`withScopesPinned`). A fresh group is collapsed.\n//\n// The group is placed for everything it can draw: its card, sized from the\n// interface the engine minted (the frame `apply` settled on,\n// `currentFrame`), and its expanded box, its members' drawn extent with its\n// padding (`groupReach`). It steps down its column (`stepDown`), its members\n// with it, past everything the layout keeps before it (`keepOrder`: drawn\n// above its anchor, or level and left of it, or at its anchor and declared\n// first) until nothing more comes before it, so it is drawn where it is stored,\n// collapsed and expanded alike: Group moves nothing the layout keeps before\n// the new group. What its room covers after it, the layout steps down just\n// past it, in order (`layoutByDepth`) — a card closer than the group's\n// padding beside the selection steps down rather than sideways. An\n// enclosing group that grows into what its own scope keeps before it steps\n// down past that, the new group with it. Group brings nothing into view of\n// its own: the canvas brings the card the frame adds into view once the\n// edit has settled, where Group stored it.\n//\n// A group is made in one scope: the scope that owns the first selected\n// node. A selected node another scope owns is sent as it was addressed, so\n// the engine refuses the selection by naming it.\nasync function groupRun(env: EditorEnv): Promise<ApplyResult> {\n const ids = env.ctx.selection.nodes;\n if (ids.length < 2) {\n env.ctx.ports.presenter.notify('error', 'Select at least two nodes to group');\n return emptyApplyResult();\n }\n const { scope } = instanceAddress(env.bundle, ids[0]);\n const nodeIds = ids.map((id) => {\n const address = instanceAddress(env.bundle, id);\n return address.scope === scope ? address.id : id;\n });\n const result = await env.apply([{ create_group: { scope, node_ids: nodeIds } }]);\n if (!result.success) return result;\n\n const created = result.created[0];\n if (!created?.moduleKey) return result;\n const frame = await currentFrame(env.ctx.ports.source);\n const minted = frame?.bundle.modules[created.moduleKey];\n if (!minted) {\n throw new Error(`Group: the source delivered no module ${created.moduleKey} after the apply`);\n }\n\n const view = env.ctx.view;\n const before = withScopesPinned(env.bundle, view, env.arrangement.get(), ids[0]);\n const parentEntry = before[created.scope] ?? {};\n const drawn = ids.flatMap((id) => {\n const rect = drawnRect(view, id);\n return rect ? [{ id, localId: splitPath(id).localId, rect }] : [];\n });\n if (drawn.length === 0) return result;\n\n // The members' frame starts where the top-left-most member is drawn.\n const members = extentOf(drawn.map((m) => m.rect));\n const origin = { x: members.x, y: members.y };\n const memberGroups = Object.fromEntries(\n drawn.flatMap(({ localId }) => {\n const entry = parentEntry.groups?.[localId];\n return entry ? [[localId, entry]] : [];\n }),\n );\n const next = setScopeEntry(before, created.moduleKey, {\n nodes: Object.fromEntries(\n drawn.map(({ id, localId, rect }) => [localId, localIn(view, id, rect, origin)]),\n ),\n groups: Object.keys(memberGroups).length > 0 ? memberGroups : undefined,\n });\n\n const reach = groupReach(groupPins(minted), groupBoxSize(members));\n const { parentPath } = splitPath(ids[0]);\n const groupPath = joinPath(parentPath, created.id);\n // Where each of the scope's Uses stands among its declarations once the\n // group is made.\n const declared = new Map(\n (frame.bundle.modules[created.scope]?.modules ?? []).map((use, i) => [use.id, i]),\n );\n const keyOf = (id: string, at: XY): KeepKey => ({ ...at, declared: declared.get(id) ?? 0 });\n const selected = new Set(ids);\n const others = [...view.nodes, ...view.groups].flatMap(({ id }) => {\n const { parentPath: scopePath, localId } = splitPath(id);\n const rect = selected.has(id) || scopePath !== parentPath ? undefined : drawnRect(view, id);\n return rect ? [{ rect, key: keyOf(localId, rect) }] : [];\n });\n // Inside a group, no higher than the top of what that group holds now:\n // its members and its members' frame origin.\n const enclosing = view.groups.find((g) => g.id === parentPath);\n const wanted = boxAt(origin);\n let anchor = enclosing\n ? { x: wanted.x, y: Math.max(wanted.y, originAt(enclosing.position).y) }\n : wanted;\n // Past what the layout keeps before the group at its anchor. A step only\n // goes down, so that set only grows, and the steps end.\n for (let moved = true; moved; ) {\n const groupKey = keyOf(created.id, anchor);\n const keptFirst = others.filter((o) => keepOrder(o.key, groupKey) < 0).map((o) => o.rect);\n const stepped = stepDown(anchor, reach, keptFirst);\n moved = stepped.y !== anchor.y;\n anchor = stepped;\n }\n const written = setScopeEntry(next, created.scope, {\n nodes: { ...parentEntry.nodes, [created.id]: localIn(view, groupPath, anchor) },\n groups: { ...parentEntry.groups, [created.id]: { collapsed: true } },\n });\n env.arrangement.update(written);\n return result;\n}\n\n// What an action on a group addresses: the group, as a node of its scope\n// and as the group (`groupId`, which Ungroup requires).\nexport function groupTarget(id: string): ActionTarget {\n return { nodeId: id, groupId: id };\n}\n\n// Shared by the \"Ungroup\" node-menu action and delete-node's own\n// group-node branch — both dissolve the group the same way, storing every\n// member where it is drawn in the parent scope (`migrateUngroup`).\nasync function ungroupRun(env: EditorEnv): Promise<ApplyResult> {\n const groupId = env.target.groupId;\n if (!groupId) return emptyApplyResult();\n const group = env.ctx.view.groups.find((g) => g.id === groupId);\n const address = instanceAddress(env.bundle, groupId);\n const result = await env.apply([{ ungroup: { scope: address.scope, group_id: address.id } }]);\n if (result.success && group?.module_key) {\n env.arrangement.update(\n migrateUngroup(\n env.bundle,\n env.ctx.view,\n env.arrangement.get(),\n groupId,\n group.module_key,\n result.created,\n ),\n );\n }\n return result;\n}\n\n// A group node's delete-node routes through the identical `ungroupRun`\n// migration path a menu-driven Ungroup uses, so every ungroup entry point\n// shares one migration path — there is no second copy that could drift.\n// The delete names the instance the gesture addressed in the scope that\n// owns it.\nasync function deleteNodeRun(env: EditorEnv): Promise<ApplyResult> {\n const id = env.target.nodeId;\n if (!id) return emptyApplyResult();\n if (env.ctx.view.groups.some((g) => g.id === id)) {\n return ungroupRun({ ...env, target: groupTarget(id) });\n }\n const address = instanceAddress(env.bundle, id);\n return env.apply([{ delete_instance: { scope: address.scope, instance_id: address.id } }]);\n}\n\nasync function conflictKeepRun(env: EditorEnv): Promise<void> {\n const conflict = env.ctx.view.conflict;\n if (!conflict) return;\n await env.editor.resolveConflict('keep', conflict.tree_hash);\n}\n\nasync function conflictReloadRun(env: EditorEnv): Promise<void> {\n const conflict = env.ctx.view.conflict;\n if (!conflict) return;\n await env.editor.resolveConflict('reload', conflict.tree_hash);\n}\n\nconst save: EditorBinding = { kind: 'editor', result: 'none', run: saveRun };\nconst generate: EditorBinding = { kind: 'editor', result: 'generate', run: generateRun };\nconst undo: EditorBinding = { kind: 'editor', result: 'apply', run: undoRun };\nconst redo: EditorBinding = { kind: 'editor', result: 'apply', run: redoRun };\nconst clearGraph: EditorBinding = { kind: 'editor', result: 'apply', run: clearGraphRun };\nconst copy: EditorBinding = { kind: 'editor', result: 'none', run: clipRun(false) };\nconst cut: EditorBinding = { kind: 'editor', result: 'none', run: clipRun(true) };\nconst paste: EditorBinding = { kind: 'editor', result: 'apply', run: pasteRun };\nconst group: EditorBinding = { kind: 'editor', result: 'apply', run: groupRun };\nconst ungroup: EditorBinding = { kind: 'editor', result: 'apply', run: ungroupRun };\nconst deleteNode: EditorBinding = { kind: 'editor', result: 'apply', run: deleteNodeRun };\nconst conflictKeep: EditorBinding = { kind: 'editor', result: 'none', run: conflictKeepRun };\nconst conflictReload: EditorBinding = {\n kind: 'editor',\n result: 'none',\n run: conflictReloadRun,\n confirm: () => ({\n text: \"Reload from the module's .tf files? They replace the canvas's saved and unsaved edits.\",\n }),\n};\n\nexport const CORE_EDITOR_ACTIONS: readonly ActionContribution[] = [\n {\n id: 'save',\n label: 'Save',\n icon: 'save',\n section: 'write',\n placement: 'toolbar',\n keys: ['Mod+s'],\n // Heard at the App root: Save is reachable from an inspector field.\n keyScope: 'app',\n requiredPorts: ['editor'],\n requiredContext: ['root', 'editable'],\n binding: save,\n },\n {\n id: 'generate',\n label: 'Generate',\n icon: 'generate',\n section: 'write',\n // The toolbar's call to action while the saved IR waits to be\n // generated; in flight from the click until the engine answers.\n primary: { when: 'ungenerated' },\n busy: { when: 'generating', label: 'Generating…' },\n placement: 'toolbar',\n requiredPorts: ['editor'],\n requiredContext: ['root', 'editable'],\n // Hidden under the lock (requiredContext 'editable') exactly like Save;\n // shown disabled while editable, positive keys in order: `generateIdle`\n // (the engine runs one Generate at a time per session, and this one is\n // running until the engine answers), then `resolved` (no open\n // Keep/Reload conflict), then `saved` (nothing unsaved).\n enabledWhen: [\n { key: 'generateIdle', reason: 'A Generate is running' },\n { key: 'resolved', reason: 'Keep or Reload the conflicting tree first' },\n { key: 'saved', reason: 'Save first' },\n ],\n binding: generate,\n },\n {\n id: 'undo',\n label: 'Undo',\n icon: 'undo',\n section: 'history',\n placement: 'toolbar',\n keys: ['Mod+z'],\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n enabledWhen: [{ key: 'undoable', reason: 'Nothing to undo' }],\n binding: undo,\n },\n {\n id: 'redo',\n label: 'Redo',\n icon: 'redo',\n section: 'history',\n placement: 'toolbar',\n keys: ['Mod+Shift+z'],\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n enabledWhen: [{ key: 'redoable', reason: 'Nothing to redo' }],\n binding: redo,\n },\n {\n id: 'clear-graph',\n label: 'Clear graph',\n icon: 'clear',\n section: 'graph',\n placement: 'toolbar',\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n binding: clearGraph,\n },\n {\n id: 'copy',\n label: 'Copy',\n placement: 'node-menu',\n section: 'clipboard',\n keys: ['Mod+c'],\n requiredPorts: ['editor'],\n // Gated on a node selection existing at all — without it, Mod+C never\n // resolves into the keymap's own action list, so it falls through to\n // the browser's native copy (selected text in run logs/diagnostics)\n // instead of hijacking the shortcut for an empty clipboard op.\n requiredContext: ['editable', 'selection.node'],\n binding: copy,\n },\n {\n id: 'cut',\n label: 'Cut',\n placement: 'node-menu',\n section: 'clipboard',\n keys: ['Mod+x'],\n requiredPorts: ['editor'],\n requiredContext: ['editable', 'selection.node'],\n binding: cut,\n },\n {\n id: 'paste',\n label: 'Paste',\n // Pastes onto the canvas, not onto a node: the empty canvas's menu.\n placement: 'pane-menu',\n keys: ['Mod+v'],\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n binding: paste,\n },\n {\n id: 'group',\n label: 'Group selected',\n placement: 'node-menu',\n section: 'group',\n requiredPorts: ['editor'],\n requiredContext: ['editable', 'selection.node'],\n binding: group,\n },\n {\n id: 'ungroup',\n label: 'Ungroup',\n placement: 'node-menu',\n section: 'group',\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n requiredTarget: ['groupId'],\n binding: ungroup,\n },\n {\n id: 'delete-node',\n label: 'Delete',\n placement: 'node-menu',\n section: 'remove',\n tone: 'danger',\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n requiredTarget: ['nodeId'],\n binding: deleteNode,\n },\n {\n id: 'conflict-keep',\n label: 'Keep canvas IR',\n placement: { row: 'conflict' },\n // Hidden under the source-refused lock exactly like Save/Generate —\n // `editable` gates Keep/Reload the same as every other mutating action.\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n binding: conflictKeep,\n },\n {\n id: 'conflict-reload',\n label: 'Reload from tf…',\n placement: { row: 'conflict' },\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n binding: conflictReload,\n },\n];\n","// Helpers that translate between canvas-path node/group ids (as emitted\n// on RenderNode.id / RenderGroup.id — dot-joined, e.g.\n// \"cloudwatch_logs_policy.attachment\") and the (scopeKey, localId) pair a\n// CanvasArrangement write targets. Arrangement is keyed by the module key\n// that scope resolves to, not by canvas path — see\n// packages/proto/src/projection/arrangement.ts. An arrangement entry holds\n// rendered nodes and groups, which are Uses, so the local id beside the\n// scope key is the path's trailing Use id (`splitPath`).\n\nimport type { CanvasArrangement } from '@lace-cloud/proto';\nimport { drawnAt, frameOf, localIn, resolveInstance, splitPath } from '@lace-cloud/proto';\nimport type { Bundle } from '../generated/state';\nimport type { CreatedRef } from '../ports';\nimport type { CanvasView } from '../types/render';\n\n// scopeKeyForCanvasPath resolves the key of the module that owns the\n// instance a canvas path addresses — the scope whose arrangement entry that\n// node's or group's own position and collapse state live under. The\n// owner is `resolveInstance`'s, so a path naming a resource child\n// (`grp.resource.<type>.<name>`) yields the scope that holds it. Returns\n// null when the path addresses nothing in the current Bundle (e.g. stale\n// id after a delete).\nexport function scopeKeyForCanvasPath(bundle: Bundle, canvasPath: string): string | null {\n return resolveInstance(bundle, canvasPath)?.scopeKey ?? null;\n}\n\nfunction cloneArrangement(arrangement: CanvasArrangement): CanvasArrangement {\n const next: CanvasArrangement = {};\n for (const [scope, entry] of Object.entries(arrangement)) {\n next[scope] = {\n nodes: entry.nodes ? { ...entry.nodes } : undefined,\n groups: entry.groups ? { ...entry.groups } : undefined,\n };\n }\n return next;\n}\n\n// withNodePosition writes a single node's position into the arrangement\n// entry for its scope, returning a new (copy-on-write) CanvasArrangement.\nexport function withNodePosition(\n bundle: Bundle,\n arrangement: CanvasArrangement,\n canvasPath: string,\n position: { x: number; y: number },\n): CanvasArrangement {\n const scopeKey = scopeKeyForCanvasPath(bundle, canvasPath);\n if (!scopeKey) return arrangement;\n const { localId } = splitPath(canvasPath);\n const next = cloneArrangement(arrangement);\n const scopeEntry = next[scopeKey] ?? {};\n next[scopeKey] = { ...scopeEntry, nodes: { ...scopeEntry.nodes, [localId]: position } };\n return next;\n}\n\n// withNodePositions applies a batch of canvasPath → position writes as a\n// single copy-on-write pass (avoids re-cloning per node on a multi-select\n// drag).\nexport function withNodePositions(\n bundle: Bundle,\n arrangement: CanvasArrangement,\n positions: Record<string, { x: number; y: number }>,\n): CanvasArrangement {\n let next = arrangement;\n for (const [canvasPath, position] of Object.entries(positions)) {\n next = withNodePosition(bundle, next, canvasPath, position);\n }\n return next;\n}\n\n// withScopesPinned stores, where it is drawn now (`localIn`), every card\n// and group in the scopes a write at `canvasPath` can move: the scope that\n// owns it and every scope around that, up to the entry. The layout lays out\n// afresh what it placed, and keeps a stored position only until something\n// kept before it takes its room, so a card dropped in a new place, or a\n// group made or dissolved, would move the siblings the layout placed, and a\n// card the layout stepped down from where it is stored would spring back\n// once what displaced it moves away. So a write first stores every one of\n// them where it is drawn, overwriting a stored position it is not\n// drawn at: each stays where it is drawn unless what the write stores takes\n// its room, when it steps down just past that (`layoutByDepth`), and a box\n// the write grows grows from where it is.\nexport function withScopesPinned(\n bundle: Bundle,\n view: Pick<CanvasView, 'nodes' | 'groups'>,\n arrangement: CanvasArrangement,\n canvasPath: string,\n): CanvasArrangement {\n const scopes = new Set<string>();\n for (let scope = splitPath(canvasPath).parentPath; ; scope = splitPath(scope).parentPath) {\n scopes.add(scope);\n if (scope === '') break;\n }\n let next = arrangement;\n for (const id of [...view.groups.map((g) => g.id), ...view.nodes.map((n) => n.id)]) {\n const { parentPath } = splitPath(id);\n if (!scopes.has(parentPath)) continue;\n const scopeKey = scopeKeyForCanvasPath(bundle, id);\n const at = drawnAt(view, id);\n if (!scopeKey || !at) continue;\n next = withNodePosition(bundle, next, id, localIn(view, id, at));\n }\n return next;\n}\n\n// withGroupCollapsed writes whether a group is collapsed into the PARENT\n// scope's arrangement entry (a group Use's collapsed state is consumer-owned\n// view state of the scope that CONTAINS the group Use, not the scope the\n// group's own module defines).\nexport function withGroupCollapsed(\n bundle: Bundle,\n arrangement: CanvasArrangement,\n canvasPath: string,\n collapsed: boolean,\n): CanvasArrangement {\n const scopeKey = scopeKeyForCanvasPath(bundle, canvasPath);\n if (!scopeKey) return arrangement;\n const { localId } = splitPath(canvasPath);\n const next = cloneArrangement(arrangement);\n const scopeEntry = next[scopeKey] ?? {};\n next[scopeKey] = {\n ...scopeEntry,\n groups: { ...scopeEntry.groups, [localId]: { collapsed } },\n };\n return next;\n}\n\n// withRenameCarried gives an instance about to be renamed its arrangement\n// under the new id too, in the scope that owns it: its position and, for a\n// group, its collapsed state. Written before the rename is sent, as a copy\n// beside the old, because the renamed frame can arrive before the rename's\n// answer and `gcArrangement` drops the old id the moment it does; it drops\n// the copy instead if the rename is refused and the new id never appears. A\n// group's members keep theirs: they live under the group's module key, which\n// a rename leaves alone. An instance with nothing arranged is returned as\n// the arrangement itself.\nexport function withRenameCarried(\n arrangement: CanvasArrangement,\n scopeKey: string,\n oldId: string,\n newId: string,\n): CanvasArrangement {\n const scopeEntry = arrangement[scopeKey];\n const position = scopeEntry?.nodes?.[oldId];\n const group = scopeEntry?.groups?.[oldId];\n if (!position && !group) return arrangement;\n const next = cloneArrangement(arrangement);\n next[scopeKey] = {\n nodes: position ? { ...scopeEntry?.nodes, [newId]: position } : scopeEntry?.nodes,\n groups: group ? { ...scopeEntry?.groups, [newId]: group } : scopeEntry?.groups,\n };\n return next;\n}\n\n// setScopeEntry writes a whole arrangement scope entry verbatim — used by\n// group-create (which stores its members' positions in the new module's\n// scope) and ungroup (the reverse migration).\nexport function setScopeEntry(\n arrangement: CanvasArrangement,\n scopeKey: string,\n entry: CanvasArrangement[string],\n): CanvasArrangement {\n const next = cloneArrangement(arrangement);\n next[scopeKey] = entry;\n return next;\n}\n\n// migrateUngroup applies the arrangement side of dissolving a group Use:\n// every member — whether its position was stored or laid out — is stored\n// where it is drawn, now in the parent scope's frame (`localIn`), so the\n// members stay where they were on screen; a member group's collapsed state\n// moves with it; the dissolved group's own entries leave the parent; and\n// the scopes around it are pinned where they are drawn (`withScopesPinned`).\n// Shared by every ungroup entry point (context-menu action, GroupNode's\n// inline ungroup button, xyflow's native node-delete on a selected group)\n// so the migration logic lives in exactly one place. `view` and `bundle`\n// are the ones the group was drawn from, before the ungroup.\n//\n// `promoted` is the ungroup mutation's `ApplyResult.created` — the CLI\n// reports a CreatedRef{id, sourceId, scope: parentScope} for EVERY\n// promoted child, renamed or not: an unrenamed child (the common case)\n// simply has sourceId === id, so `rename()` below is the identity for it.\n// A collision with an existing sibling in the parent scope is the one\n// case where id and sourceId actually differ.\nexport function migrateUngroup(\n bundle: Bundle,\n view: Pick<CanvasView, 'nodes' | 'groups'>,\n arrangement: CanvasArrangement,\n groupCanvasPath: string,\n groupModuleKey: string,\n promoted: CreatedRef[] = [],\n): CanvasArrangement {\n const parentScopeKey = scopeKeyForCanvasPath(bundle, groupCanvasPath);\n const group = view.groups.find((g) => g.id === groupCanvasPath);\n if (!parentScopeKey || !group) return arrangement;\n\n const { localId } = splitPath(groupCanvasPath);\n const pinned = withScopesPinned(bundle, view, arrangement, groupCanvasPath);\n const parentEntry = pinned[parentScopeKey] ?? {};\n const groupEntry = pinned[groupModuleKey] ?? {};\n\n const renameMap = new Map(\n promoted\n .filter((ref) => ref.scope === parentScopeKey && ref.sourceId)\n .map((ref) => [ref.sourceId, ref.id] as const),\n );\n const rename = (id: string) => renameMap.get(id) ?? id;\n\n const frame = frameOf(view, groupCanvasPath);\n const nodes = { ...parentEntry.nodes };\n delete nodes[localId];\n for (const member of group.node_ids) {\n const at = drawnAt(view, member);\n if (at) nodes[rename(splitPath(member).localId)] = localIn(view, member, at, frame);\n }\n\n const remainingGroups = parentEntry.groups ? { ...parentEntry.groups } : undefined;\n if (remainingGroups) delete remainingGroups[localId];\n const migratedGroups = groupEntry.groups\n ? Object.fromEntries(Object.entries(groupEntry.groups).map(([id, g]) => [rename(id), g]))\n : undefined;\n const groups =\n remainingGroups || migratedGroups ? { ...remainingGroups, ...migratedGroups } : undefined;\n\n return setScopeEntry(pinned, parentScopeKey, { nodes, groups });\n}\n\n// gcArrangement drops arrangement entries for scopes and children that no\n// longer exist in the current Bundle — an id that was deleted (or whose\n// scope was deleted) leaks memory and stale visual state forever\n// otherwise, since nothing else ever removes an arrangement entry.\nexport function gcArrangement(bundle: Bundle, arrangement: CanvasArrangement): CanvasArrangement {\n const next: CanvasArrangement = {};\n let changed = false;\n\n for (const [scopeKey, entry] of Object.entries(arrangement)) {\n const mod = bundle.modules[scopeKey];\n if (!mod) {\n changed = true; // scope no longer exists — drop entirely.\n continue;\n }\n const liveIds = new Set((mod.modules ?? []).map((u) => u.id));\n\n const nodeEntries = entry.nodes ? Object.entries(entry.nodes) : [];\n const liveNodeEntries = nodeEntries.filter(([id]) => liveIds.has(id));\n const groupEntries = entry.groups ? Object.entries(entry.groups) : [];\n const liveGroupEntries = groupEntries.filter(([id]) => liveIds.has(id));\n\n if (\n liveNodeEntries.length !== nodeEntries.length ||\n liveGroupEntries.length !== groupEntries.length\n ) {\n changed = true;\n }\n\n const nodes = entry.nodes ? Object.fromEntries(liveNodeEntries) : undefined;\n const groups = entry.groups ? Object.fromEntries(liveGroupEntries) : undefined;\n\n if ((nodes && Object.keys(nodes).length > 0) || (groups && Object.keys(groups).length > 0)) {\n next[scopeKey] = { nodes, groups };\n }\n }\n\n // Identity-preserving when nothing was pruned — callers (App's\n // stateUpdated handler) skip a state update + host notification when\n // GC is a no-op.\n return changed ? next : arrangement;\n}\n","// A view renders every scope flat — the entry's children plus, under each\n// group, that group's children by their own dotted ids — and each group\n// lists its children in `node_ids`. The entry scope's ids are therefore the\n// view's node and group ids that no group claims as a child. This is the\n// one derivation the gestures that are entry-scope by meaning read: Clear\n// graph (a group's delete takes its children) and copy/cut (a copy is an\n// entry-scope operation). A gesture that addresses one instance of the\n// user's choosing — delete, edge delete, drag-connect, rename, a config\n// panel edit — addresses it in the scope that owns it (`instanceAddress`).\nimport type { CanvasView } from '../types/render';\n\ntype ViewScopes = Pick<CanvasView, 'nodes' | 'groups'>;\n\nexport function entryScopeIds(view: ViewScopes): string[] {\n const nested = new Set(view.groups.flatMap((g) => g.node_ids));\n return [...view.nodes, ...view.groups].map((n) => n.id).filter((id) => !nested.has(id));\n}\n\n// inEntryScope keeps, in their given order, the ids among `ids` that the\n// entry scope owns.\nexport function inEntryScope(view: ViewScopes, ids: readonly string[]): string[] {\n const entry = new Set(entryScopeIds(view));\n return ids.filter((id) => entry.has(id));\n}\n","// The canvas context: the pipeline's output, read by Canvas.tsx and every\n// component/hook below it. `editable` is App's one read-only derivation,\n// `ports.editor !== undefined && !source.sourceRefused` — there is no\n// `readOnly` field.\nimport type { CanvasView } from '@lace-cloud/proto';\nimport { createContext, useContext } from 'react';\nimport type { CanvasCtx, EdgeRef, LayoutHandle } from '../contributions';\nimport type { DrawnDecorations } from '../core/decorate';\nimport type { ActionRunner } from '../core/run-binding';\nimport type { Bundle } from '../generated/state';\nimport type { CanvasPorts } from '../ports';\nimport type { CanvasArrangement } from '../types/render';\n\nexport type CanvasContextValue = {\n ports: CanvasPorts;\n // The raw Bundle behind `view` — panels that show what the graph does not\n // draw (a Use's Binding, a module's resources, directives and\n // declarations) derive it from here (`deriveNodeConfig` /\n // `deriveSettingsConfig`), so inspection-only content (no editor port)\n // renders the same way an editable panel's read model does.\n bundle: Bundle;\n view: CanvasView;\n // The resolution-time context every contribution's own gating and every\n // binding's `args()` reads (registry.ts, contributions.ts) — App builds\n // one per render and every panel receives it as a prop too\n // (`PanelProps.ctx`), but the surfaces below App (Canvas, its panels,\n // node-menu resolution) that aren't themselves a `Panel` read it here.\n ctx: CanvasCtx;\n // This frame's per-node decorations (`core/decorate.ts`'s merge of every\n // resolved overlay + `ctx.diagnostics`) — ModuleNode reads its own badges\n // off this map; App is the one place that recomputes it.\n decorations: DrawnDecorations;\n editable: boolean;\n // The consumer-owned CanvasArrangement (node positions, group\n // collapse). Both editable and read-only mounts route drag /\n // collapse-toggle / rename through `updateArrangement` — the core is the\n // single projection site (`bundle-shows-on-canvas`), so a read-only\n // mount re-projects the same way an editable one does; it just has no\n // `editor` port to issue an IR-mutating action through.\n arrangement: CanvasArrangement;\n updateArrangement: (next: CanvasArrangement) => void;\n selection: { nodes: readonly string[]; edge: EdgeRef | null };\n setSelection: (next: { nodes: readonly string[]; edge: EdgeRef | null }) => void;\n // The one execution path: every action (toolbar, node-menu, row, key)\n // runs through `runner.run`, every bare xyflow gesture through\n // `runner.apply`.\n runner: ActionRunner;\n // A stable object Canvas overwrites with its own xyflow-backed\n // implementation once mounted, so App's own toolbar-run\n // `EditorEnvExtras` and a panel's `useEditorEnvExtras`\n // (core/panels/row-actions.ts) share the one instance rather than each\n // inventing their own no-op.\n layout: LayoutHandle;\n // Opens and closes the settings panel. App owns whether it is open and\n // carries it as `ctx.settingsOpen`, which the panel's `'settingsOpen'`\n // context key gates on, so a closed panel resolves nothing and its column\n // takes no space; the Settings toggle opens it and the panel's Close\n // closes it.\n setSettingsOpen: (next: boolean) => void;\n};\n\nexport const CanvasContext = createContext<CanvasContextValue | null>(null);\n\nexport function useCanvas(): CanvasContextValue {\n const value = useContext(CanvasContext);\n if (!value) throw new Error('CanvasContext not available: mount inside <App>');\n return value;\n}\n","// The one path a panel's row/inline buttons reach an action through:\n// `rowActionsFor` resolves `ctx.contributions` — the merged core + host set\n// App built — against this panel's own `ctx` and a\n// row's `target` (registry.ts `resolveContributions` + `rowActions`), never\n// a core-only list — a host row action (e.g. VS Code's own Open source on a\n// `row:diagnostics` entry) renders next to a core one with no panel edit. `useEditorEnvExtras`\n// supplies the pieces `ActionRunner.run` needs for an editor binding that a\n// panel (never the Canvas surface itself) can actually provide —\n// `layout` is the one shared instance Canvas overwrites once mounted\n// (state/canvas-context.ts), so a row action that pans the camera needs no\n// second wiring.\nimport type { ActionContribution, ActionTarget, CanvasCtx } from '../../contributions';\nimport { resolveContributions, rowActions } from '../../registry';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { EditorEnvExtras } from '../run-binding';\n\nexport function rowActionsFor(\n ctx: CanvasCtx,\n panelId: string,\n target: ActionTarget = {},\n): readonly ActionContribution[] {\n const resolved = resolveContributions(ctx.contributions, ctx.ports, ctx, target);\n return rowActions(resolved, panelId);\n}\n\nexport function useEditorEnvExtras(): EditorEnvExtras {\n const { bundle, arrangement, updateArrangement, layout } = useCanvas();\n return {\n bundle,\n arrangement: { get: () => arrangement, update: updateArrangement },\n layout,\n };\n}\n","// useRenameInstance is the one rename a card or a group header sends. It\n// writes what the rename carries under the new id, each slice by its own\n// owner — the arrangement (`withRenameCarried`) and the selection\n// (`carrySelection`) — then sends `rename_instance` in the scope that owns\n// the instance through `runner.apply`: the same one-batch apply plus\n// `presenter.notify` failure routing every other node-chrome mutation uses,\n// so a refusal (a taken or invalid name) reaches the developer. A new id the\n// scope already holds carries nothing: the engine refuses that rename, and\n// the copy would land on the instance that holds it. A refused rename lands\n// no frame, so no frame drops the copied names: the selection is reconciled\n// with the view the session stands at once the refusal is answered.\nimport { instanceAddress } from '@lace-cloud/proto';\nimport { useCallback, useRef } from 'react';\nimport { carrySelection, reconcileSelection } from '../../core/pipeline';\nimport { useCanvas } from '../../state/canvas-context';\nimport { withRenameCarried } from '../../utils/arrangement';\n\nexport function useRenameInstance(): (canvasPath: string, newId: string) => Promise<void> {\n const { bundle, view, arrangement, updateArrangement, selection, setSelection, runner } =\n useCanvas();\n // What a refusal's answer meets is what stands when it arrives, not what\n // stood when the rename was sent.\n const latest = useRef({ view, selection });\n latest.current = { view, selection };\n\n return useCallback(\n async (canvasPath: string, newId: string) => {\n const { scope, id: oldId } = instanceAddress(bundle, canvasPath);\n if (!newId || newId === oldId) return;\n const taken = bundle.modules[scope]?.modules?.some((u) => u.id === newId) ?? false;\n // A canvas path ends with the instance's own id, which may hold dots of\n // its own (a resource child's), so the new path replaces that suffix.\n const newPath = canvasPath.slice(0, canvasPath.length - oldId.length) + newId;\n const carriedArrangement = taken\n ? arrangement\n : withRenameCarried(arrangement, scope, oldId, newId);\n const carriedSelection = taken ? selection : carrySelection(selection, canvasPath, newPath);\n if (carriedArrangement !== arrangement) updateArrangement(carriedArrangement);\n if (carriedSelection !== selection) setSelection(carriedSelection);\n const result = await runner.apply([\n { rename_instance: { scope, old_id: oldId, new_id: newId } },\n ]);\n if (result?.success || carriedSelection === selection) return;\n const now = latest.current;\n const held = reconcileSelection(now.view, now.selection);\n if (held !== now.selection) setSelection(held);\n },\n [bundle, arrangement, updateArrangement, selection, setSelection, runner],\n );\n}\n","// useCanvasSource is the canvas's standing subscription: it mounts\n// `ports.source.subscribe` for as long as the canvas is mounted and returns\n// the latest `CanvasSource` frame, which App renders. (`currentFrame`,\n// ports.ts, reads the frame the source stands at once, for a write's caller\n// to read its own write.) The stream's end leaves the last good frame in place (it means \"no\n// further frame will ever follow\", not \"the current one is wrong\") — App\n// renders it once, as the load-error state, when no frame ever arrived.\n//\n// The same subscription delivers the results of the commands that ran in\n// the session's root. Each `subscribe` mints one token, the session's: the\n// results are handed to `onCommandResult` with it, the state carries it as\n// `session`, and `onSessionEnd` receives it once the subscription ends, so a\n// consumer folding the results keeps each session's fold apart and drops a\n// fold no subscription delivers to any more.\n//\n// projectFrame is the view of a frame: its Bundle projected with the\n// reader's arrangement (`projectCanvasView`) and the frame's own state. App\n// draws it; a write that must know where something it stored is drawn reads\n// it from the frame its apply settled on (`currentFrame`).\n//\n// reconcileSelection is what of a selection a frame's view still holds. The\n// frame is the one truth of what exists, so App reconciles its selection\n// against each view it projects, whatever removed the selected thing.\n// carrySelection is what a selection names across a rename, beside what it\n// named before, until a frame drops the old names.\nimport { type CanvasView, projectCanvasView } from '@lace-cloud/proto';\nimport { useEffect, useState } from 'react';\nimport type { CanvasCtx } from '../contributions';\nimport type { CanvasSource, CommandResult, SourceEnd, SourcePort } from '../ports';\nimport type { CanvasArrangement } from '../types/render';\n\nexport function projectFrame(frame: CanvasSource, arrangement: CanvasArrangement): CanvasView {\n return projectCanvasView(frame.bundle, arrangement, {\n canUndo: frame.canUndo,\n canRedo: frame.canRedo,\n unsaved: frame.unsaved,\n conflict: frame.conflict\n ? { base_tree_hash: frame.conflict.baseTreeHash, tree_hash: frame.conflict.treeHash }\n : undefined,\n ungenerated: frame.ungenerated,\n });\n}\n\n// The selection with what `view` does not hold dropped: a node or group\n// by its id among the view's nodes and groups, the wire by its id among the\n// view's edges. A selection the view holds whole is returned as itself.\nexport function reconcileSelection(\n view: CanvasView,\n selection: CanvasCtx['selection'],\n): CanvasCtx['selection'] {\n const held = new Set([...view.nodes, ...view.groups].map((n) => n.id));\n const nodes = selection.nodes.filter((id) => held.has(id));\n const { edge } = selection;\n const keptEdge = edge && view.edges.some((e) => e.id === edge.id) ? edge : null;\n if (nodes.length === selection.nodes.length && keptEdge === edge) return selection;\n return { nodes, edge: keptEdge };\n}\n\n// The selection with its names of the instance at `oldPath` and of\n// everything under it, whose canvas paths change with its own, named under\n// `newPath` too, beside the old: the renamed frame can arrive before the\n// rename's answer, and it drops the old names (`reconcileSelection`) and\n// keeps the new. A selection naming nothing under the instance is returned\n// as itself.\nexport function carrySelection(\n selection: CanvasCtx['selection'],\n oldPath: string,\n newPath: string,\n): CanvasCtx['selection'] {\n const copies = selection.nodes.flatMap((id) =>\n id === oldPath || id.startsWith(`${oldPath}.`) ? [newPath + id.slice(oldPath.length)] : [],\n );\n if (copies.length === 0) return selection;\n return { ...selection, nodes: [...selection.nodes, ...copies] };\n}\n\nexport type SourceState = {\n source: CanvasSource | null;\n end: SourceEnd | null;\n // The token of the subscription the state came from; null until the\n // first subscription.\n session: object | null;\n};\n\nexport function useCanvasSource(\n source: SourcePort,\n onCommandResult: (result: CommandResult, session: object) => void,\n onSessionEnd: (session: object) => void,\n): SourceState {\n const [state, setState] = useState<SourceState>({ source: null, end: null, session: null });\n\n useEffect(() => {\n const session = {};\n setState({ source: null, end: null, session });\n const unsubscribe = source.subscribe(\n (next) => setState({ source: next, end: null, session }),\n (end) => setState((prev) => ({ source: prev.source, end, session })),\n (result) => onCommandResult(result, session),\n );\n return () => {\n unsubscribe();\n onSessionEnd(session);\n };\n }, [source, onCommandResult, onSessionEnd]);\n\n return state;\n}\n","import {\n instanceAddress,\n NODE_HEADER_HEIGHT,\n NODE_ROW_HEIGHT,\n NODE_WIDTH,\n nodeRows,\n visibleInputs,\n} from '@lace-cloud/proto';\nimport {\n Handle,\n type Node,\n type NodeProps,\n Position,\n type ReactFlowState,\n useStore,\n useUpdateNodeInternals,\n} from '@xyflow/react';\nimport type React from 'react';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { Badge } from '../../contributions';\nimport { hasErrorBadge, type PinFinding } from '../../core/decorate';\nimport { useEditorEnvExtras } from '../../core/panels/row-actions';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { NodePin, RenderNode } from '../../types/render';\nimport { NODE_HANDLE, sourceHandleId } from '../../utils/handleId';\nimport { typedName } from '../../utils/typed-name';\nimport { CanvasIcon } from '../icons';\nimport './ModuleNode.css';\nimport { useOpenNodeConfig } from './node-config-bus';\nimport { ANY_PIN_COLOR, pinColor } from './pinColor';\nimport { useRenameInstance } from './use-rename-instance';\n\n// ── Node data contract (serializable — no callbacks) ──\n\nexport type ModuleNodeData = RenderNode & {\n hasValidationError?: boolean;\n isNew?: boolean;\n /** Badges the diagnostics decoration attached to this node — tone\n * `'error'` drives the error border/title. `RenderNode` carries no\n * error state of its own; a node's error styling comes only from its\n * decoration badges. The same field name and chip shape GroupNode's own\n * `badges` renders — a badge addressed to a collapsed group's own id\n * (nodeIdForAddress can return a group id) is not a ModuleNode concern\n * either way. */\n badges?: readonly Badge[];\n /** What the engine found on this node's inputs, by input name — the\n * decoration's `pins`. */\n pins?: Readonly<Record<string, PinFinding>>;\n};\n\ntype ModuleNodeNode = Node<ModuleNodeData, 'moduleNode'>;\n\n// ── Layout constants ──\n// The card's geometry is the projection's (proto geometry.ts): the layout\n// that places a card and the card itself read one set of numbers.\n\nconst ICON_SIZE = 16;\n\n// True while a drag that started on a `node` handle is in progress: only\n// then is a card a place to end one.\nconst nodeDragging = (s: ReactFlowState) => s.connection.fromHandle?.id === NODE_HANDLE;\n\n// Border / shadow variants now live in ModuleNode.css as\n// `.lace-module-node--error` / `--new` classes. Node colors flow\n// through design tokens.\n\n// ── Pin row ──\n\ntype PinRowProps = {\n pin: NodePin;\n side: 'input' | 'output';\n top: number; // vertical offset inside the node body\n // Another pin sits on this row on the other side: each label then keeps to\n // its own half of the card, so an input's name and an output's never\n // overlap; a label longer than its room ends in an ellipsis and carries the\n // full name as its tooltip.\n shared: boolean;\n // What the engine found on this pin (`BundleState.diagnostics`, an\n // input's own): its ring takes the finding's tone and its tooltip leads\n // with the finding — a required input nothing sets is the common one.\n problem?: PinFinding;\n isConnectable: boolean;\n};\n\nconst PROBLEM_RING: Record<PinFinding['tone'], string | undefined> = {\n error: 'var(--lace-node-error-border)',\n warn: 'var(--lace-color-warning-fg)',\n neutral: undefined,\n};\n\n// A pin is a dot in its type's colour, by one rule on both rails: filled\n// while a wire runs to or from it (`wired`), hollow while none does. A pin\n// the engine has a finding on draws its ring in the finding's tone.\nconst PinRow: React.FC<PinRowProps> = ({ pin, side, top, shared, problem, isConnectable }) => {\n const color = pinColor(pin);\n const isInput = side === 'input';\n const filled = !!pin.wired;\n const ring = problem ? PROBLEM_RING[problem.tone] : undefined;\n const isError = problem?.tone === 'error';\n const handleStyle: React.CSSProperties = {\n background: filled ? color.fill : 'var(--lace-node-bg)',\n borderColor: ring ?? (filled ? color.stroke : color.fill),\n borderWidth: ring ? 2 : 1.5,\n borderStyle: 'solid',\n width: 10,\n height: 10,\n [isInput ? 'left' : 'right']: -5,\n top: NODE_ROW_HEIGHT / 2,\n };\n const about = `${typedName(pin.name, pin.type)}${pin.description ? ` — ${pin.description}` : ''}`;\n return (\n <div\n className=\"lace-pin-row\"\n style={{\n position: 'absolute',\n top,\n left: 0,\n right: 0,\n height: NODE_ROW_HEIGHT,\n paddingLeft: isInput ? 12 : 8,\n paddingRight: isInput ? 8 : 12,\n display: 'flex',\n alignItems: 'center',\n justifyContent: isInput ? 'flex-start' : 'flex-end',\n }}\n title={problem ? `${problem.message}\\n${about}` : about}\n >\n <Handle\n id={`${isInput ? 'in' : 'out'}:${pin.name}`}\n type={isInput ? 'target' : 'source'}\n position={isInput ? Position.Left : Position.Right}\n isConnectable={isConnectable}\n className=\"lace-pin-handle\"\n style={handleStyle}\n />\n <span\n className={`lace-module-node__pin-row-label lace-module-node__pin-row-label--${isError ? 'error' : filled ? 'wired' : 'default'}`}\n style={{ maxWidth: shared ? (NODE_WIDTH - 28) / 2 - 4 : NODE_WIDTH - 28 }}\n >\n {pin.name}\n </span>\n </div>\n );\n};\n\n// ── Component ──\n\nconst ModuleNode: React.FC<NodeProps<ModuleNodeNode>> = ({ id, data }) => {\n const { editable, ctx, runner, bundle } = useCanvas();\n const rename = useRenameInstance();\n const connecting = useStore(nodeDragging);\n const openNodeConfig = useOpenNodeConfig();\n const envExtras = useEditorEnvExtras();\n const [editing, setEditing] = useState(false);\n const [editValue, setEditValue] = useState(id);\n const [hovered, setHovered] = useState(false);\n const [imgFailed, setImgFailed] = useState(false);\n const [collapsed, setCollapsed] = useState(false);\n const [showAllInputs, setShowAllInputs] = useState(false);\n const inputRef = useRef<HTMLInputElement>(null);\n const renamingRef = useRef(false);\n\n useEffect(() => {\n if (editing && inputRef.current) {\n inputRef.current.focus();\n inputRef.current.select();\n }\n }, [editing]);\n\n // ── Pin filtering ──\n\n const inputs = data.inputs ?? [];\n const outputs = data.outputs ?? [];\n\n const { shownInputs, hiddenInputCount } = useMemo(() => {\n if (showAllInputs) {\n return { shownInputs: inputs, hiddenInputCount: 0 };\n }\n const visible = visibleInputs(inputs);\n return {\n shownInputs: visible,\n hiddenInputCount: inputs.length - visible.length,\n };\n }, [inputs, showAllInputs]);\n\n // xyflow measures a card's handles when the card mounts or resizes, and\n // draws a wire only between handles it has measured. The handles a card\n // draws change without its size changing — a folded row becoming the row\n // of the pin a wire now feeds keeps the row count — so the card says when\n // its drawn handle set changes, and the wire to the new pin is drawn.\n const updateNodeInternals = useUpdateNodeInternals();\n const drawnHandles = [\n ...shownInputs.map((pin) => `in:${pin.name}`),\n ...outputs.map((pin) => sourceHandleId(pin.name)),\n ].join('|');\n // biome-ignore lint/correctness/useExhaustiveDependencies: re-measured whenever the drawn handle set changes.\n useEffect(() => {\n updateNodeInternals(id);\n }, [id, drawnHandles, updateNodeInternals]);\n\n // ── Callbacks ──\n\n const onDoubleClick = useCallback(\n (e: React.MouseEvent) => {\n if (!editable) return;\n e.stopPropagation();\n setEditValue(instanceAddress(bundle, id).id);\n setEditing(true);\n },\n [id, editable, bundle],\n );\n\n // The name edited is the instance's own id in the scope that owns it,\n // which is where the rename applies (`useRenameInstance`): the node keeps\n // its place, and its selection, under the new name.\n const commitRename = useCallback(async () => {\n if (renamingRef.current) return;\n renamingRef.current = true;\n setEditing(false);\n await rename(id, editValue.trim());\n renamingRef.current = false;\n }, [editValue, id, rename]);\n\n const onKeyDown = useCallback(\n (e: React.KeyboardEvent) => {\n e.stopPropagation();\n if (e.key === 'Enter') commitRename();\n else if (e.key === 'Escape') setEditing(false);\n },\n [commitRename],\n );\n\n const onHeaderClick = useCallback(\n (e: React.MouseEvent) => {\n if (!e.shiftKey && !e.metaKey && !e.ctrlKey) {\n openNodeConfig(data.id);\n }\n },\n [data.id, openNodeConfig],\n );\n\n // Delete runs the registered `delete-node` contribution through the\n // runner — the same one mutation path (and error routing to\n // `presenter.notify`) the node menu's own Delete entry and Backspace/\n // Delete key both use, never a second `editor.apply` call site that\n // could drop a failing `ApplyResult` silently.\n const onDeleteInstance = useCallback(\n async (e: React.MouseEvent) => {\n e.stopPropagation();\n const action = ctx.contributions.actions.find((a) => a.id === 'delete-node');\n if (!action) return;\n await runner.run(action, ctx, { nodeId: data.id }, envExtras);\n },\n [ctx, runner, envExtras, data.id],\n );\n\n const toggleCollapsed = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n setCollapsed((v) => !v);\n }, []);\n\n // React.SyntheticEvent — not React.MouseEvent — since the Enter/Space\n // keyboard activation on the hidden-count row shares this handler with\n // its click, and both only ever call `stopPropagation`.\n const toggleShowAllInputs = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n setShowAllInputs((v) => !v);\n }, []);\n\n // ── Styling ──\n\n const showIcon = data.icon_url && !imgFailed;\n const badges = data.badges ?? [];\n // A node's error styling comes only from a badge whose own tone is\n // 'error' — a neutral \"3 resources\" count or a warn \"drifted\" badge\n // decorates the node without painting it as broken.\n const hasAnyError = hasErrorBadge(badges) || !!data.hasValidationError;\n const isNew = !!data.isNew && !hasAnyError;\n\n // Body height — when collapsed, header only. Folded, the rows `nodeRows`\n // counts, so the card is the size the layout placed it by; with every\n // input shown, whichever rail is taller.\n const rowCount = collapsed\n ? 0\n : showAllInputs\n ? Math.max(inputs.length, outputs.length)\n : nodeRows({ inputs, outputs });\n const bodyHeight = rowCount * NODE_ROW_HEIGHT;\n const nodeHeight = NODE_HEADER_HEIGHT + bodyHeight;\n\n const stateClass = hasAnyError ? 'lace-module-node--error' : isNew ? 'lace-module-node--new' : '';\n\n return (\n <div\n className={`lace-module-node${collapsed ? ' lace-module-node--collapsed' : ''}${stateClass ? ` ${stateClass}` : ''}`}\n style={{ width: NODE_WIDTH, height: nodeHeight }}\n onMouseEnter={() => setHovered(true)}\n onMouseLeave={() => setHovered(false)}\n >\n {/* ── Header ── */}\n <div\n className=\"lace-module-node__header\"\n style={{ height: NODE_HEADER_HEIGHT }}\n onClick={onHeaderClick}\n title={badges.length > 0 ? badges.map((b) => b.title ?? b.label).join('\\n') : data.label}\n >\n <button\n type=\"button\"\n onClick={toggleCollapsed}\n className=\"lace-module-node__collapse-btn\"\n title={collapsed ? 'Expand' : 'Collapse'}\n aria-label={collapsed ? 'Expand' : 'Collapse'}\n >\n <CanvasIcon name={collapsed ? 'chevron-right' : 'chevron-down'} />\n </button>\n\n {showIcon ? (\n <img\n src={data.icon_url}\n alt=\"\"\n className=\"lace-module-node__icon\"\n style={{ width: ICON_SIZE, height: ICON_SIZE }}\n onError={() => setImgFailed(true)}\n />\n ) : (\n <span className=\"lace-module-node__icon-fallback\">\n <CanvasIcon name=\"module\" />\n </span>\n )}\n\n {editing ? (\n <input\n ref={inputRef}\n value={editValue}\n onChange={(e) => setEditValue(e.target.value)}\n onBlur={commitRename}\n onKeyDown={onKeyDown}\n className=\"lace-module-node__rename-input\"\n onClick={(e) => e.stopPropagation()}\n />\n ) : (\n <span\n className=\"lace-module-node__label\"\n onDoubleClick={onDoubleClick}\n title={data.label}\n >\n {data.label}\n </span>\n )}\n\n {hovered && editable && (\n <button\n type=\"button\"\n onClick={onDeleteInstance}\n className=\"lace-module-node__delete-btn\"\n title=\"Delete instance\"\n aria-label=\"Delete instance\"\n >\n <CanvasIcon name=\"clear\" />\n </button>\n )}\n </div>\n\n {/* ── Badges: every decoration badge renders as its own chip by its\n own tone, floating above the card so it never perturbs the\n pin-row height math below — only a badge whose tone is 'error'\n drives the card's own error border (above), the rest are\n informational (a resource count, a drift warning). Each chip\n carries `data-badge` (its own id — 'resources', 'drift', a\n diagnostic's own id, …) and `data-tone`, so a DOM assertion can\n tell which badge is which without parsing chip text. ── */}\n {badges.length > 0 && (\n <div className=\"lace-module-node__badges\">\n {badges.map((b) => (\n <span\n key={b.id}\n data-badge={b.id}\n data-tone={b.tone}\n className={`lace-module-node__badge lace-module-node__badge--${b.tone}`}\n title={b.title ?? b.label}\n >\n {b.label}\n </span>\n ))}\n </div>\n )}\n\n {/* ── Call handle: an edge whose reference reads the whole call, naming\n no output, leaves the node here. No wire starts from it. ── */}\n {data.call_wired && (\n <Handle\n id={sourceHandleId('')}\n type=\"source\"\n position={Position.Right}\n isConnectable={false}\n className=\"lace-pin-handle\"\n style={{\n background: ANY_PIN_COLOR.fill,\n borderColor: ANY_PIN_COLOR.stroke,\n borderWidth: 1,\n borderStyle: 'solid',\n width: 8,\n height: 8,\n top: NODE_HEADER_HEIGHT / 2,\n right: -4,\n }}\n />\n )}\n\n {/* ── Body: input rail (left) + output rail (right), absolutely positioned rows ── */}\n {!collapsed && (\n <div className=\"lace-module-node__body\" style={{ height: bodyHeight }}>\n {shownInputs.map((pin, i) => (\n <PinRow\n key={`in:${pin.name}`}\n pin={pin}\n side=\"input\"\n top={i * NODE_ROW_HEIGHT}\n shared={i < outputs.length}\n problem={data.pins?.[pin.name]}\n isConnectable={editable}\n />\n ))}\n {outputs.map((pin, i) => (\n <PinRow\n key={`out:${pin.name}`}\n pin={pin}\n side=\"output\"\n top={i * NODE_ROW_HEIGHT}\n shared={i < shownInputs.length}\n isConnectable={editable}\n />\n ))}\n\n {hiddenInputCount > 0 && (\n <div\n className=\"lace-module-node__hidden-count\"\n onClick={toggleShowAllInputs}\n onKeyDown={(e) => {\n if (e.key === 'Enter' || e.key === ' ') toggleShowAllInputs(e);\n }}\n role=\"button\"\n tabIndex={0}\n style={{\n top: shownInputs.length * NODE_ROW_HEIGHT,\n left: 12,\n right: 12,\n height: NODE_ROW_HEIGHT,\n }}\n title=\"Show all inputs\"\n >\n +{hiddenInputCount} more\n </div>\n )}\n </div>\n )}\n\n {/* ── Collapsed: stack all input handles on the left edge, outputs on right ── */}\n {collapsed && (\n <>\n {inputs.map((pin, i) => {\n const color = pinColor(pin);\n return (\n <Handle\n key={`in:${pin.name}`}\n id={`in:${pin.name}`}\n type=\"target\"\n position={Position.Left}\n isConnectable={editable}\n className=\"lace-pin-handle\"\n style={{\n background: pin.wired ? color.fill : 'var(--lace-node-bg)',\n borderColor: pin.wired ? color.stroke : color.fill,\n borderWidth: 1,\n borderStyle: 'solid',\n width: 8,\n height: 8,\n top: NODE_HEADER_HEIGHT / 2 - 4 + (i - (inputs.length - 1) / 2) * 3,\n left: -4,\n }}\n />\n );\n })}\n {outputs.map((pin, i) => {\n const color = pinColor(pin);\n return (\n <Handle\n key={`out:${pin.name}`}\n id={`out:${pin.name}`}\n type=\"source\"\n position={Position.Right}\n isConnectable={editable}\n className=\"lace-pin-handle\"\n style={{\n background: pin.wired ? color.fill : 'var(--lace-node-bg)',\n borderColor: pin.wired ? color.stroke : color.fill,\n borderWidth: 1,\n borderStyle: 'solid',\n width: 8,\n height: 8,\n top: NODE_HEADER_HEIGHT / 2 - 4 + (i - (outputs.length - 1) / 2) * 3,\n right: -4,\n }}\n />\n );\n })}\n </>\n )}\n\n {/* ── Node-to-node drag, on an editable canvas only: a drag from the\n grip below the card starts it and the card itself ends it. The\n card's target never starts a connection and is an end only while a\n drag from a `node` handle is in progress; at rest xyflow gives it\n no pointer events, so the header's gestures and a pin drag's drop\n reach what lies under it. Rendered last, so during a node drag it\n lies above the header and the pins. ── */}\n {editable && (\n <>\n <Handle\n id={NODE_HANDLE}\n type=\"source\"\n position={Position.Bottom}\n // xyflow arms click-to-connect from a handle's click, and a\n // Handle spreads its own props over that handler: an `onClick` of\n // `undefined` leaves the grip a drag start only.\n onClick={undefined}\n className=\"lace-module-node__grip\"\n />\n <Handle\n id={NODE_HANDLE}\n type=\"target\"\n position={Position.Top}\n isConnectableStart={false}\n isConnectableEnd={connecting}\n className=\"lace-module-node__drop\"\n />\n </>\n )}\n </div>\n );\n};\n\nexport default ModuleNode;\n","// decorate merges every rendering overlay's own decorations with the\n// engine's diagnostics (via `diagnosticsOf`) for this frame into one\n// per-node badge set. A node's diagnostics fold into one badge — how many,\n// in the tone of the worst, each message on its own line of the badge's\n// title: the messages themselves are read where they belong, on the pin a\n// finding names (`pins`, the worst finding per input) and in the\n// Diagnostics tab, so the card carries a count, not a stack of truncated\n// sentences. The canvas runs no validator of its own:\n// `certify.CheckWorkspace` is the one rule set, and this function only\n// renders findings it is handed — it computes none itself. Node\n// resolution is the proto `nodeIdForDiagnostic` — the one Diagnostic →\n// node/group id mapping, so this file carries no second copy of it.\nimport type { CanvasView, Diagnostic } from '@lace-cloud/proto';\nimport { nodeIdForDiagnostic } from '@lace-cloud/proto';\nimport type { Badge, Decorations, NodeDecoration } from '../contributions';\n\n/** What the engine found on one of a node's inputs: the worst finding,\n * when it found more than one. */\nexport type PinFinding = { message: string; tone: Badge['tone'] };\n\n/** The decorations the canvas draws: each node's badges — the overlays'\n * and the engine's — and the engine's findings on its inputs, by input\n * name. An overlay hands in badges only (`Decorations`). */\nexport type DrawnDecorations = {\n nodes: Readonly<Record<string, NodeDecoration & { pins?: Readonly<Record<string, PinFinding>> }>>;\n};\n\nconst EMPTY_DECORATIONS: DrawnDecorations = { nodes: {} };\n\n// A node or group renders as errored on a badge's tone, never on a badge\n// merely being present — a neutral drift or warn badge must not turn it\n// red. The one gate ModuleNode and both group shapes (useGroupLogic) read;\n// the badges are the engine's findings, never a canvas-computed check.\nexport function hasErrorBadge(badges: readonly Badge[] | undefined): boolean {\n return (badges ?? []).some((b) => b.tone === 'error');\n}\n\nexport function decorate(\n view: Pick<CanvasView, 'nodes' | 'groups'>,\n overlayDecorations: readonly Decorations[],\n diagnostics: readonly Diagnostic[],\n): DrawnDecorations {\n if (overlayDecorations.length === 0 && diagnostics.length === 0) return EMPTY_DECORATIONS;\n\n const nodes: Record<string, { badges: Badge[]; pins?: Record<string, PinFinding> }> = {};\n const addBadge = (nodeId: string, badge: Badge) => {\n if (!nodes[nodeId]) nodes[nodeId] = { badges: [] };\n nodes[nodeId].badges.push(badge);\n };\n\n for (const overlayResult of overlayDecorations) {\n for (const [nodeId, decoration] of Object.entries(overlayResult.nodes)) {\n for (const badge of decoration.badges) addBadge(nodeId, badge);\n }\n }\n\n const byNode = new Map<string, Diagnostic[]>();\n for (const diagnostic of diagnostics) {\n const nodeId = nodeIdForDiagnostic(view, diagnostic);\n if (nodeId === null) continue;\n byNode.set(nodeId, [...(byNode.get(nodeId) ?? []), diagnostic]);\n }\n for (const [nodeId, held] of byNode) {\n addBadge(nodeId, diagnosticsBadge(held));\n const pins = pinFindings(held);\n if (pins) nodes[nodeId].pins = pins;\n }\n\n return { nodes };\n}\n\nconst TONE_RANK: Record<Badge['tone'], number> = { neutral: 0, warn: 1, error: 2 };\n\nfunction toneOf(d: Diagnostic): Badge['tone'] {\n return d.severity === 'error' ? 'error' : d.severity === 'warning' ? 'warn' : 'neutral';\n}\n\n// The worst finding the engine reported on each input of one node, by\n// input name; undefined when none names an input.\nfunction pinFindings(held: readonly Diagnostic[]): Record<string, PinFinding> | undefined {\n const pins: Record<string, PinFinding> = {};\n for (const d of held) {\n if (!d.input_name) continue;\n const tone = toneOf(d);\n const kept = pins[d.input_name];\n if (!kept || TONE_RANK[tone] > TONE_RANK[kept.tone]) {\n pins[d.input_name] = { message: d.message, tone };\n }\n }\n return Object.keys(pins).length > 0 ? pins : undefined;\n}\n\n// One node's findings as one badge.\nexport function diagnosticsBadge(held: readonly Diagnostic[]): Badge {\n const tone = held.map(toneOf).reduce((worst, t) => (TONE_RANK[t] > TONE_RANK[worst] ? t : worst));\n return {\n id: 'diagnostics',\n label: `${held.length} ${held.length === 1 ? 'problem' : 'problems'}`,\n tone,\n title: held.map((d) => d.message).join('\\n'),\n };\n}\n","/**\n * The id of a node's own handle pair, the grip below its card (source) and\n * the card itself (target): a drag from one node's grip onto another node\n * wires the pairs Lace's matcher finds between them. It names no pin, so it\n * never parses as one.\n */\nexport const NODE_HANDLE = 'node';\n\n/**\n * Extract the variable name from a handle ID of the form \"in:<name>\" or \"out:<name>\".\n * Returns null if the handle is missing or doesn't match the expected prefix.\n */\nexport function parseHandleId(\n handleId: string | null | undefined,\n prefix: 'in' | 'out',\n): string | null {\n if (!handleId) return null;\n const marker = `${prefix}:`;\n if (!handleId.startsWith(marker)) return null;\n const name = handleId.slice(marker.length);\n return name.length > 0 ? name : null;\n}\n\n/**\n * The source handle an edge leaves a node by: the handle of the output it\n * reads, or, for an edge that reads the whole call and names no output, the\n * node's call handle.\n */\nexport function sourceHandleId(output: string): string {\n return `out:${output}`;\n}\n","// A variable, output or pin as the canvas names it: its name and the type it\n// declares, or its name alone when it declares none — an empty type, as the IR\n// holds a variable with no type line.\nexport function typedName(name: string, type: string): string {\n return type ? `${name}: ${type}` : name;\n}\n","// A per-Canvas-instance channel for \"open this node's config\" requests.\n// ModuleNode's header click needs to reach Canvas.tsx's own selection +\n// go-to-node wiring; a window `CustomEvent` would cross-talk between two\n// Canvas mounts sharing one page (a global listener installed by one\n// mount fires for a click inside the other's tree too). A React context\n// scopes the channel to this Canvas's own component subtree instead —\n// there is exactly one provider per mounted Canvas, so exactly one\n// listener ever receives a given click.\nimport { createContext, type ReactNode, useContext, useRef } from 'react';\n\ntype OpenNodeConfig = (instanceId: string) => void;\n\nconst NodeConfigBusContext = createContext<OpenNodeConfig | null>(null);\n\nexport function NodeConfigBusProvider({\n onOpen,\n children,\n}: {\n onOpen: OpenNodeConfig;\n children: ReactNode;\n}) {\n // The callback Canvas passes in closes over per-render state (selection,\n // the xyflow-backed go-to-node ref) — capturing it in a ref keeps the\n // context value itself stable across renders while every call still\n // reaches the latest closure.\n const onOpenRef = useRef(onOpen);\n onOpenRef.current = onOpen;\n const stableRef = useRef<OpenNodeConfig>((instanceId) => onOpenRef.current(instanceId));\n return (\n <NodeConfigBusContext.Provider value={stableRef.current}>\n {children}\n </NodeConfigBusContext.Provider>\n );\n}\n\nexport function useOpenNodeConfig(): OpenNodeConfig {\n const fn = useContext(NodeConfigBusContext);\n if (!fn) throw new Error('useOpenNodeConfig: mount inside <NodeConfigBusProvider>');\n return fn;\n}\n","// pinColor maps a type family to a handle color, so inputs and outputs\n// of the same type family render with a consistent hue — Blender-style.\n//\n// Colors reference design tokens via CSS variable names. React accepts\n// `var(--…)` in inline style fields (`fill`, `background`, `borderColor`,\n// etc.), so xyflow's Handle + our SVG pins pick the tokenised color up\n// transparently.\n//\n// Palette is tuned to sit on the dark Lace canvas and stay legible\n// against the primary accent. These are the only socket colors — do\n// not add more families without discussing; too many hues become noise.\n\nexport type PinColor = {\n fill: string;\n stroke: string;\n};\n\nconst STRING: PinColor = {\n fill: 'var(--lace-pin-string-fill)',\n stroke: 'var(--lace-pin-string-stroke)',\n};\nconst NUMBER: PinColor = {\n fill: 'var(--lace-pin-number-fill)',\n stroke: 'var(--lace-pin-number-stroke)',\n};\nconst BOOL: PinColor = {\n fill: 'var(--lace-pin-bool-fill)',\n stroke: 'var(--lace-pin-bool-stroke)',\n};\nconst LIST: PinColor = {\n fill: 'var(--lace-pin-list-fill)',\n stroke: 'var(--lace-pin-list-stroke)',\n};\nconst MAP: PinColor = {\n fill: 'var(--lace-pin-map-fill)',\n stroke: 'var(--lace-pin-map-stroke)',\n};\nconst OBJECT: PinColor = {\n fill: 'var(--lace-pin-object-fill)',\n stroke: 'var(--lace-pin-object-stroke)',\n};\nconst ANY: PinColor = {\n fill: 'var(--lace-pin-any-fill)',\n stroke: 'var(--lace-pin-any-stroke)',\n};\n\nconst FAMILY_COLORS: Record<string, PinColor> = {\n string: STRING,\n number: NUMBER,\n bool: BOOL,\n boolean: BOOL,\n list: LIST,\n set: LIST,\n tuple: LIST,\n map: MAP,\n object: OBJECT,\n any: ANY,\n};\n\n/** Fallback pin color used when a pin's type family can't be matched.\n * Exported so downstream fallbacks don't duplicate the literal. */\nexport const ANY_PIN_COLOR: PinColor = ANY;\n\n/**\n * Infer type family from a raw HCL type string (fallback for when CLI\n * doesn't yet send type_family on NodePin).\n */\nfunction inferTypeFamily(type: string): string {\n const t = (type || '').trim().toLowerCase();\n if (t === '' || t === 'any') return 'any';\n // Check for compound types like \"list(string)\", \"map(object({...}))\"\n for (const family of ['list', 'set', 'tuple', 'map', 'object']) {\n if (t.startsWith(family)) return family;\n }\n return t; // \"string\", \"number\", \"bool\" fall through as-is\n}\n\n/**\n * Get the pin color for a NodePin. Prefers `type_family` if provided (from CLI),\n * falls back to inferring from the raw HCL type string.\n */\nexport function pinColor(pin: { type: string; type_family?: string }): PinColor {\n const family = pin.type_family ?? inferTypeFamily(pin.type);\n return FAMILY_COLORS[family] ?? ANY;\n}\n","// The canvas's surface: the brand's engineering paper, drawn with the\n// design tokens' own recipe (`.lace-paper-layers`: fine and major threads\n// in a 1:5 rhythm) on a layer behind the graph — so the forced-colors and\n// print escape that recipe carries applies here too.\n//\n// The paper is a backdrop: it stays where it is while the graph pans and\n// zooms over it, at the shell paper's own pitch and threads. Mounted as a\n// child of `ReactFlow`.\nimport './PaperGrid.css';\n\nexport default function PaperGrid() {\n return <div className=\"lace-paper-layers lace-canvas-paper\" aria-hidden=\"true\" />;\n}\n","// useActionKeys is the one keymap: every action's own `keys` (a declarative\n// binding, not a second imperative shortcut table) runs through the\n// identical `runner.run` a click does. A binding's `keyScope` names the\n// element that hears it, and each scope has one target an owner registers\n// (`registerKeyTarget`): `surface` is the canvas's own rendering surface\n// (Canvas.tsx), `app` the App root (App.tsx), which also holds the\n// drawer and the bottom panels — siblings of the surface a key\n// typed there never reaches. Never `window`: a window-level listener\n// intercepts every keydown on the page, including Mod+C over selected text\n// in a sibling panel that has nothing to do with the canvas.\n//\n// Focus guard, per scope: on the surface an event whose target is a form\n// control (input/textarea/select/contenteditable) is left alone — a\n// Backspace or Mod+Z typed into a node's rename field must keep the field's\n// own meaning; at the App root a form control's keys are matched too, so\n// Mod+S saves from an inspector field (no field uses the chord). Both skip\n// an event something upstream already handled (`defaultPrevented`). Node\n// delete itself stays on xyflow's own `deleteKeyCode` (Canvas.tsx), never a\n// second Backspace handler here.\n//\n// A handled key is consumed — `preventDefault` and `stopPropagation` — so\n// the host's own listener above the canvas (VS Code's undo and save on the\n// webview's window) never sees it; a key the keymap does not handle\n// propagates untouched.\n//\n// `App` (this hook's one call site) and `Canvas` (the surface owner) are\n// siblings under the same `CanvasCtx` object App builds each render, so the\n// registry keys on that object's identity — the one thing both share —\n// rather than threading DOM refs between components that don't otherwise\n// pass props to each other. With no target registered for a scope there is\n// nothing to bind its listener to, so the effect installs none.\n//\n// A key is delivered to the focused element, so the keymap hears it only\n// while focus is inside a target. A host can show the canvas with its\n// window focused and no element in it focused (a webview revealed without\n// taking focus, then activated by its tab header; a rebooted page): the\n// focused element is the body, outside every target. `useFocusWhenNoneHeld`\n// gives the `app` target's owner the remedy: the root takes focus when it\n// mounts with its window focused and when its window gains focus, each\n// time only while the body holds it, so focus in a field, or on any other\n// element inside or outside the App, stays where it is. A page whose window\n// is not focused when it mounts (a webview a host opened without taking\n// focus, beside the chat or editor that holds it) takes nothing: an unfocused\n// document's active element is its body too, and focusing the root from\n// inside that frame would pull the host's focus into it.\nimport { type RefObject, useEffect } from 'react';\nimport {\n type ActionContribution,\n type ActionTarget,\n type CanvasCtx,\n KEY_SCOPES,\n type KeyScope,\n} from '../contribution-types';\nimport { parseChord } from '../utils/key-chord';\nimport type { ActionRunner, EditorEnvExtras } from './run-binding';\n\n// One rule per scope, total over `KeyScope`: the effect binds a listener\n// for every name in `KEY_SCOPES` and reads that scope's rule here.\nexport type KeyScopeRules = Record<KeyScope, { handlesFormTargets: boolean }>;\n\nconst KEY_SCOPE_RULES: KeyScopeRules = {\n surface: { handlesFormTargets: false },\n app: { handlesFormTargets: true },\n};\n\nconst targetsByCtx = new WeakMap<CanvasCtx, Partial<Record<KeyScope, EventTarget>>>();\n\nexport function registerKeyTarget(\n ctx: CanvasCtx,\n scope: KeyScope,\n target: EventTarget | null,\n): void {\n const targets = targetsByCtx.get(ctx) ?? {};\n if (target) targets[scope] = target;\n else delete targets[scope];\n targetsByCtx.set(ctx, targets);\n}\n\nexport function isFormTarget(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLElement)) return false;\n const tag = target.tagName;\n return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable;\n}\n\nexport function useFocusWhenNoneHeld(root: RefObject<HTMLElement>, mounted: boolean): void {\n useEffect(() => {\n const element = root.current;\n if (!mounted || !element) return;\n const doc = element.ownerDocument;\n const takeFocus = () => {\n if (doc.activeElement === null || doc.activeElement === doc.body) {\n element.focus({ preventScroll: true });\n }\n };\n if (doc.hasFocus()) takeFocus();\n const view = doc.defaultView;\n view?.addEventListener('focus', takeFocus);\n return () => view?.removeEventListener('focus', takeFocus);\n }, [root, mounted]);\n}\n\nfunction keyScopeOf(action: ActionContribution): KeyScope {\n return action.keyScope ?? 'surface';\n}\n\nfunction matchesKey(e: KeyboardEvent, spec: string): boolean {\n const chord = parseChord(spec);\n if (!chord) return false;\n if (!(e.metaKey || e.ctrlKey) || e.shiftKey !== chord.shift) return false;\n return e.key.toLowerCase() === chord.key.toLowerCase();\n}\n\nexport function useActionKeys(\n actions: readonly ActionContribution[],\n ctx: CanvasCtx | null,\n runner: ActionRunner,\n envExtras: EditorEnvExtras | null,\n): void {\n useEffect(() => {\n if (!ctx || !envExtras) return;\n // Rebind to `const`s TS can carry into the nested `onKeyDown` closure —\n // the guard above already proved both non-null for this effect run.\n const activeCtx = ctx;\n const activeEnvExtras = envExtras;\n const targets = targetsByCtx.get(ctx) ?? {};\n const target: ActionTarget = {};\n\n function bind(scope: KeyScope): (() => void) | undefined {\n const { handlesFormTargets } = KEY_SCOPE_RULES[scope];\n const element = targets[scope];\n if (!element) return undefined;\n const keyed = actions.filter((a) => (a.keys?.length ?? 0) > 0 && keyScopeOf(a) === scope);\n\n function onKeyDown(e: Event) {\n // `addEventListener`'s own type is generic over `Event` — the target\n // is whatever `EventTarget` its owner registered, so this narrows at\n // runtime rather than asserting a `KeyboardEvent` the type system\n // can't actually prove a `keydown` listener receives.\n if (!(e instanceof KeyboardEvent)) return;\n if (e.defaultPrevented) return;\n if (!handlesFormTargets && isFormTarget(e.target)) return;\n for (const action of keyed) {\n for (const spec of action.keys ?? []) {\n if (matchesKey(e, spec)) {\n e.preventDefault();\n e.stopPropagation();\n void runner.run(action, activeCtx, target, activeEnvExtras);\n return;\n }\n }\n }\n }\n\n element.addEventListener('keydown', onKeyDown);\n return () => element.removeEventListener('keydown', onKeyDown);\n }\n\n const unbind = KEY_SCOPES.map(bind);\n return () => {\n for (const off of unbind) off?.();\n };\n }, [actions, ctx, runner, envExtras]);\n}\n","// The React-free contribution types: overlays, actions, the bindings an\n// action runs, the contexts a binding runs over and what a panel declares.\n// The core registers through these, so a host extension registers through\n// the same surface its own features use — no canvas-private mechanism\n// bypasses the registry. Every capability the canvas renders is one of: a\n// `command` binding (a bound CLI path), an `editor` binding (an IR edit or\n// generate), or a `host` binding — a host-supplied handler for a capability\n// that is neither (a VS Code command, a webview message, the host's own\n// navigation). A `host` binding runs through the identical\n// available/confirm/tick path every other binding does (registry.ts,\n// core/run-binding.ts); the only extra thing it may touch is whatever the\n// host closure captures. Core never constructs one — a core capability is\n// always `command` or `editor` (contributions-contract.test.ts).\n//\n// This file holds the contribution types and the one value they are\n// derived from (`KEY_SCOPES`), and imports nothing from React, not even a type:\n// every module the React-free entry (`engine/index.ts`) reaches takes its\n// contribution types from here, so the entry's declarations typecheck in a\n// host with no React types installed (`__tests__/engine-entry-static.test.ts`).\n// The one React-typed shape, a panel's component, lives in contributions.ts.\n// The two constructors live beside the primitives they compose\n// (`defineCommand`, core/define-command.ts; `defineOverlay`,\n// core/define-overlay.ts), so importing a contract type loads nothing.\nimport type { CanvasView, Diagnostic } from '@lace-cloud/proto';\nimport type { ArgsOf, BoundPath, CommandFailure, JsonOf, LaceReason } from './contracts';\nimport type { Bundle } from './generated/state';\nimport type {\n CanvasPorts,\n CommandResult,\n ConfirmSpec,\n EditorPort,\n PortName,\n RunnerPorts,\n StackRef,\n} from './ports';\nimport type { CanvasArrangement } from './types/render';\nimport type { KeySpec } from './utils/key-chord';\n\n// The two edge endpoints an inspector shows — App resolves the pairing off\n// xyflow's own edge-click event and holds it as `CanvasCtx.selection.edge`.\nexport type EdgeRef = {\n id: string;\n source: string;\n target: string;\n sourceOutput: string;\n targetInput: string;\n};\n\nexport type ContextKey =\n | 'root'\n | 'sessionId'\n | 'stack'\n // Satisfied iff `ctx.editable` — the editor port is present and the\n // session is not source-refused. The one read-only derivation\n // (registry.ts's `contextSatisfied`); mutation contributions keep their\n // own `requiredPorts: ['editor']` for port presence and add this key to\n // gate on the lock too.\n | 'editable'\n // Satisfied iff `!ctx.view.unsaved` — nothing for Save to write.\n | 'saved'\n // Satisfied iff `ctx.view.unsaved` — an edit Save has not written yet.\n // The Unsaved marker's gate.\n | 'unsaved'\n // Satisfied iff `ctx.view.conflict === undefined` — no open Keep/Reload\n // conflict.\n | 'resolved'\n // Satisfied iff `ctx.view.conflict` is set — the tf changed under an\n // unsaved or ungenerated working IR and waits on Keep or Reload. The\n // conflict banner's gate.\n | 'conflict'\n // Satisfied iff `ctx.sourceRefused` — the engine refuses the module's tf,\n // and with it every edit, save, generate, Keep and Reload. The\n // source-refused banner's gate.\n | 'sourceRefused'\n // Satisfied iff `ctx.sourceRefused` and the refusal is lace shape's — a\n // `not_lace_shape` diagnostic among `ctx.diagnostics`: the tree is out of\n // lace shape. The source-refused banner's out-of-lace-shape opening, and\n // the gate Convert declares on its row.\n | 'needsConversion'\n | 'selection.node'\n | 'selection.edge'\n // Satisfied iff `ctx.diagnostics` is non-empty — the diagnostics panel's\n // own gate, so a mount with nothing to show never draws an empty bottom\n // tab (registry.ts's `contextSatisfied`).\n | 'diagnostics'\n // Satisfied iff `ctx.settingsOpen` — the settings panel's own gate, so a\n // closed settings panel resolves nothing and its column takes no space.\n | 'settingsOpen'\n // Satisfied iff `ctx.generating` is false — no Generate is running on the\n // session (`CanvasSource.generating`), the one gate that keeps the\n // canvas from asking for a second.\n | 'generateIdle'\n // Satisfied iff `ctx.generating` — a Generate is running. Generate's\n // `busy.when`: the toolbar draws it in flight.\n | 'generating'\n // Satisfied iff `ctx.view.ungenerated` — the saved IR has not been\n // generated into the module's tree. Generate's `primary.when`: the\n // toolbar draws it as the call to action while there is something to\n // generate; with `generateIdle`, the Not generated marker's gate.\n | 'ungenerated'\n // Satisfied iff `ctx.view.can_undo` / `ctx.view.can_redo` — the session\n // holds an edit to step back over / forward over again.\n | 'undoable'\n | 'redoable';\n\n// What a command or host binding runs over: the authoring root, the\n// session open on it and the stack the host chose. A host with no canvas\n// (an extension's stacks tree) runs the same bindings over this alone, one\n// runner for every root it holds: a command whose action declares `root`\n// runs in this `root` (`BindingRuntime.cwd`). `CanvasCtx` is this plus the\n// canvas's own facts, its three fields read off the host's `context` port.\nexport type RunCtx = {\n root?: string;\n sessionId?: string;\n stack?: StackRef;\n};\n\nexport type CanvasCtx = RunCtx & {\n ports: CanvasPorts;\n // `ports.editor !== undefined && !source.sourceRefused` — the one\n // read-only derivation, already threaded through xyflow's own props and\n // the keymap; carried here too so it doubles as the `'editable'` context\n // key.\n editable: boolean;\n // `source.generating` of this frame: a Generate is running on the\n // session, from the call until the engine answers it. The\n // `'generateIdle'` and `'generating'` context keys read it.\n generating: boolean;\n // `source.sourceRefused` of this frame: the engine refuses the module's\n // tf. `editable` is derived from it; the `'sourceRefused'` context key\n // reads it.\n sourceRefused: boolean;\n view: CanvasView;\n selection: { nodes: readonly string[]; edge: EdgeRef | null };\n // Whether the developer has the settings panel open — App's own state,\n // opened by the Settings toolbar toggle and closed by the panel's Close.\n // The `'settingsOpen'` context key reads it.\n settingsOpen: boolean;\n // `source.diagnostics` of this same frame — the engine's live findings,\n // unfiltered by scope resolution — merged with the current report's\n // findings (`diagnosticsOf`, core/diagnostics.ts). decorate and\n // DiagnosticsPanel both read this one list.\n diagnostics: readonly Diagnostic[];\n // The merged core + host contribution set (App's `merged`, unresolved) —\n // a panel's own row actions (`rowActionsFor`, core/panels/row-actions.ts)\n // resolve against this, so a host-supplied row action renders next to a\n // core one instead of the panel only ever seeing `CORE_ACTIONS`. A panel\n // in it is its `PanelSpec`: nothing reading a context renders a panel.\n contributions: ContributionSet;\n};\n\nexport type Badge = {\n id: string;\n label: string;\n tone: 'neutral' | 'warn' | 'error';\n title?: string;\n};\nexport type NodeDecoration = { badges: readonly Badge[] };\nexport type Decorations = { nodes: Readonly<Record<string, NodeDecoration>> };\n\nexport type OverlayContribution = {\n id: string;\n paths: readonly BoundPath[];\n useDecorations: (ctx: CanvasCtx) => Decorations;\n};\n\nexport type CommandRead<P extends BoundPath> = {\n path: P;\n args: (ctx: CanvasCtx, target: ActionTarget) => ArgsOf<P> | null; // null = don't fetch\n};\n\n// What a panel declares apart from the component that draws it: the fields\n// the registry resolves it on and the chrome lists it by. The React surface's\n// `Panel` (contributions.ts) is this plus its `Component`.\nexport type PanelSpec = {\n id: string;\n // The label chrome lists the panel by — the bottom-tab strip's tab, the\n // drawer's accessible name — never the bare `id`, which is a stable\n // identifier, not UI copy.\n title: string;\n // Where App draws it: a row under the toolbar (`banner`), in the toolbar,\n // in the right-hand drawer — one panel at a time, the first that resolves\n // — or as a tab under the canvas (`bottom`).\n slot: 'banner' | 'toolbar' | 'drawer' | 'bottom';\n requiredPorts: readonly PortName[];\n // requiredCommands is derived from `reads` + row actions, not declared —\n // a panel that reads through `useCommandRead` needs no second list naming\n // the same path.\n reads?: readonly { path: BoundPath }[];\n requiredContext?: readonly ContextKey[];\n // A toolbar panel's place in the row: the end of the section of actions it\n // names (`ActionContribution.section`); naming none, or a section no\n // action resolved into, the row's far end (the Settings toggle).\n section?: string;\n};\n\n// A row action's target is the row's own datum, passed through generically\n// — `diagnostic` for a diagnostics row, `runId` for a run a host lists,\n// `failure` for a failure row — never a single-purpose field minted for one\n// consumer; a host row action reads whichever row datum it needs off here.\nexport type ActionTarget = {\n // The node or group a menu opened on.\n nodeId?: string;\n // Set too when that node is a group: an action only a group takes\n // (Ungroup) requires it.\n groupId?: string;\n diagnostic?: Diagnostic;\n runId?: string;\n // A failure row's datum: the failure document a command ended on, whole,\n // which a host passes as `{ failure }`.\n failure?: CommandFailure;\n};\n\n// Where an action is offered: the toolbar; the menu a node or a group opens\n// on (`node-menu`, its target the node); the menu the empty canvas opens on\n// (`pane-menu`, no target — Paste); or a panel's row.\nexport type Placement = 'toolbar' | 'node-menu' | 'pane-menu' | { row: string };\n\nexport type ResultKind = 'run' | 'preview' | 'report' | 'notify' | 'follow';\n\n// The result kinds `ResultStore` actually holds a slot for — every kind but\n// `notify`, which routes straight to `presenter.notify` and never persists\n// (the store marks a notify invocation running while it runs, by the target\n// it runs on, and holds nothing of what it said).\n// `write` (below) is typed over this narrower set, not `ResultKind`: a\n// generic `K extends ResultKind` would range over `notify` too, and\n// `SinkInput['notify']` (`unknown`, since `notify` carries no shape of its\n// own) collapses `SinkInput[K]` back to `unknown` inside the function body —\n// forcing an `as` at the one place that indexes it.\nexport type SlotKind = Exclude<ResultKind, 'notify'>;\n\n// `report`'s input is no command's own event stream: it is the result of a\n// command that ran in the session's root, as the session publishes it to\n// every subscriber (`CommandResult`, ports.ts). No command binding's sink\n// writes it; the source subscription does (App).\nexport type SinkInput = {\n run: JsonOf<'stack apply'>;\n preview: JsonOf<'stack preview'>;\n report: CommandResult;\n notify: unknown;\n follow: JsonOf<'run logs'>;\n};\n\ntype ResultFor<P extends BoundPath> = {\n [K in ResultKind]: JsonOf<P> extends SinkInput[K] ? K : never;\n}[ResultKind];\n\n// A store write carries the token the runner minted for this invocation: a\n// write for a token the runner has since detached (a new invoke on the\n// same slot, or an explicit cancel/unmount) is dropped by the store, not\n// by the sink — the sink stays a pure mapping from an event to a value.\nexport type BindingRuntime = {\n ports: RunnerPorts;\n token: object;\n // The directory this run's command runs in (`CommandsPort.invoke`'s\n // `cwd`): the run's `root` when the action declares `root` in its\n // `requiredContext`, which the runner has checked is present; absent for\n // an action that declares none, which runs in the port's own directory.\n cwd?: string;\n write: <K extends SlotKind>(kind: K, token: object, value: SinkInput[K]) => void;\n detach: <K extends ResultKind>(kind: K, token: object) => void;\n // Seeds what this invocation's kind holds before any wire event exists —\n // its slot, or a notify invocation's running mark — not a fake wire event\n // through `write`; what a seed is per result kind is the ResultStore's\n // (core/results.ts `begin`), never the binding's.\n begin: () => void;\n // Settles this invocation's own slot on a failed stream; `false` when its\n // result kind has no failed state to render, so the binding surfaces the\n // failure itself.\n fail: (error: unknown) => boolean;\n tick: () => void;\n // Called once this invocation's own event-consuming loop actually ends\n // (success or failure) — not when `ErasedCommand.start` merely resolves,\n // which happens as soon as the invocation begins so the runner can hold\n // its `cancel(slot)` handle while consumption keeps running in the\n // background. A `notify` sink has no store slot of its own to ever\n // detach/supersede it, so this is the one hook the runner has to end its\n // running mark and prune its own bookkeeping (`notifyControllers`,\n // run-binding.ts) once the invocation is truly done.\n settled?: () => void;\n};\n\n// A `Sink<T>` is a value, not a function type, so `CommandBinding.result` is\n// cast-free: `SinkInput[K] extends T` narrows `consume`'s event parameter\n// without an `as` at the call site.\nexport type Sink<T> = { kind: ResultKind; consume: (rt: BindingRuntime, e: T) => void };\n\nexport type CommandBinding<P extends BoundPath> = {\n kind: 'command';\n path: P;\n args: (ctx: RunCtx, target: ActionTarget) => Partial<ArgsOf<P>>;\n confirm?: (ctx: RunCtx, args: ArgsOf<P>, target: ActionTarget) => ConfirmSpec;\n result: Sink<JsonOf<P>> & { kind: ResultFor<P> };\n invalidates?: true | 'start+settle';\n};\n\n// The runner owns one clipboard slot (copy/cut record the selection here;\n// paste reads and clears it) — module-scope state would leak across\n// concurrent runners (Storybook mounts several), so it travels through\n// EditorEnv like arrangement/layout rather than living in editor-actions.ts.\nexport type ClipboardStore = {\n get: () => { ids: readonly string[]; cut: boolean } | null;\n set: (ids: readonly string[], cut: boolean) => void;\n clear: () => void;\n};\n\n// A stable object Canvas overwrites with its own xyflow-backed\n// implementation once mounted. `panIntoView` is view chrome: it pans the\n// camera the least distance that brings a rect inside the pane, never a\n// node, never the zoom, and stores nothing. The canvas composes it to bring\n// what a frame adds into view and to go to a node. Shared by `EditorEnv`\n// and `CanvasContextValue` so App's toolbar-run extras and a panel's\n// row-run extras see the identical instance rather than each inventing\n// their own.\nexport type LayoutHandle = {\n panIntoView: (rect: { x: number; y: number; width: number; height: number }) => void;\n};\n\nexport type EditorEnv = {\n editor: EditorPort;\n // The one `editor.apply` entry point — the identical `applyActions`\n // helper `ActionRunner.apply` exposes for an ungoverned gesture\n // (run-binding.ts), so a registered binding's own multi-step mutation\n // (paste's copy-then-delete, group's create) reports a rejected batch to\n // `presenter.notify` at the exact call that failed, never a second time\n // from a wrapper reading the same result back.\n apply: (\n actions: readonly import('./generated/service').Action[],\n ) => Promise<import('./ports').ApplyResult>;\n ctx: CanvasCtx;\n target: ActionTarget;\n // The Bundle backing `ctx.view` — group/ungroup/paste resolve a canvas\n // path to its arrangement scope key (`scopeKeyForCanvasPath`), which\n // needs the Bundle the view was projected from, not the view itself.\n bundle: Bundle;\n clipboard: ClipboardStore;\n arrangement: { get: () => CanvasArrangement; update: (a: CanvasArrangement) => void };\n layout: LayoutHandle;\n};\n\nexport type EditorBinding = { kind: 'editor'; confirm?: (ctx: CanvasCtx) => ConfirmSpec } & (\n | { result: 'apply'; run: (env: EditorEnv) => Promise<import('./ports').ApplyResult> }\n | { result: 'generate'; run: (env: EditorEnv) => AsyncIterable<import('./ports').GenerateEvent> }\n | { result: 'none'; run: (env: EditorEnv) => Promise<void> }\n);\n\n// A host-supplied handler for a capability with no CLI command — e.g. a VS\n// Code command a canvas action merely triggers, or opening a diagnostic's\n// source file. `run` gets the same `BindingRuntime` a command binding's\n// `start` does, so a host action that does invalidate a read can call\n// `rt.tick()` (or set `invalidates` and let the runner call it at settle)\n// the same way a core action would; anything beyond that is the host's own\n// closure, not a second port the registry has to know about.\nexport type HostBinding = {\n kind: 'host';\n confirm?: (ctx: RunCtx) => ConfirmSpec;\n invalidates?: true;\n run: (rt: BindingRuntime, ctx: RunCtx, target: ActionTarget) => Promise<void>;\n};\n\n// Built by `defineCommand<P>` (core/define-command.ts): erases the\n// path-specific generics behind one shape the runner and registry share, so\n// an `ActionContribution[]` array mixing bindings for different paths\n// type-checks without a cast.\nexport type ErasedCommand = {\n kind: 'command';\n path: BoundPath;\n confirms: boolean;\n resultKind: ResultKind;\n invalidates?: true | 'start+settle';\n // The same `args(ctx, target)`, erased to a plain record rather than a\n // typed `Partial<ArgsOf<P>>` — the runner completes it with `completeArgs`\n // (a value-based required-key check; a key present with `undefined` still\n // counts as missing) before ever asking for a form.\n partialArgs: (ctx: RunCtx, target: ActionTarget) => Record<string, unknown>;\n // The binding's own confirm spec against the completed args (its own\n // `args` merged with any form-collected values via `completeArgs`) —\n // `undefined` when the binding declares no confirm, or when the args\n // aren't complete yet. Building the spec is this binding's own concern\n // (it alone knows its typed `args`/`confirm`); asking the user is the\n // runner's — `core/run-binding.ts` is the one `presenter.confirm(` call\n // site for every binding kind, command included.\n confirmSpec: (\n ctx: RunCtx,\n target: ActionTarget,\n formArgs: Record<string, unknown>,\n ) => ConfirmSpec | undefined;\n // Resolves as soon as the invocation starts, so the ActionRunner can hold\n // the returned handle for `cancel(slot)` while the event-consuming loop\n // keeps running in the background; `null` when the binding declined to\n // run (no `commands` port, or the args still aren't complete). Confirming\n // has already happened by the time `start` is called — this never asks.\n start: (\n rt: BindingRuntime,\n ctx: RunCtx,\n target: ActionTarget,\n formArgs: Record<string, unknown>,\n signal: AbortSignal,\n ) => Promise<{ cancel: () => Promise<void> } | null>;\n};\n\n// Which element hears an action's `keys` (`core/use-action-keys.ts`):\n// `surface` is the canvas's own rendering surface, where a form control\n// keeps every key for itself; `app` is the App root, which also covers the\n// drawer and the bottom panels, and where a bound chord is handled\n// even from a form control (a field has no use for Mod+S). The names are\n// declared once, here: the keymap binds one listener per entry and holds one\n// rule per `KeyScope`, so a scope added to this tuple has both or does not\n// compile.\nexport const KEY_SCOPES = ['surface', 'app'] as const;\nexport type KeyScope = (typeof KEY_SCOPES)[number];\n\n// The glyphs an action may name for the toolbar to draw\n// (components/icons.tsx).\nexport type ActionIcon = 'validate' | 'convert' | 'save' | 'generate' | 'undo' | 'redo' | 'clear';\n\nexport type ActionContribution = {\n id: string;\n label: string;\n // The sentence a banner says of this action as one of its choices: a\n // banner states its fact, then the `choice` of each action resolved on its\n // row, in resolve order (core/panels/RowActionBanner.tsx). The toolbar and\n // the menus ignore it.\n choice?: string;\n // How the toolbar draws the action. With `icon` and no `primary`, an\n // icon button whose tooltip names it (and its key); with `primary`, the\n // labelled call to action, its glyph beside the label, filled in the\n // accent while `primary.when` holds (always, with no `when`) and quiet\n // otherwise. With neither, a text button carrying the label — a host's\n // action with no glyph of its own still reads.\n icon?: ActionIcon;\n primary?: { when?: ContextKey };\n // While `busy.when` holds the action is running: the toolbar draws it\n // with a spinner and `busy.label` (Generate's \"Generating…\"). A command\n // binding's own running slot draws the same way, under the action's label.\n busy?: { when: ContextKey; label: string };\n // The toolbar and the menus draw their actions in sections by intent —\n // Validate and Convert check, Save and Generate write, Undo and Redo walk\n // history; Copy and Cut, then Group and Ungroup, then Delete — with a\n // hairline between sections, in the order each first appears. A toolbar\n // panel naming a section sits at its end (the Unsaved and Not generated\n // chips beside Generate). Actions naming none form one section after the\n // named ones.\n section?: string;\n // An action that removes something: a menu draws it in the danger tone.\n tone?: 'danger';\n // The keys that run the action, in the keymap's grammar: `Mod`, an\n // optional `Shift`, then the key. The type (`KeySpec`) checks the `Mod+`\n // prefix; `parseChord` refuses the rest at runtime.\n keys?: readonly KeySpec[];\n /** Defaults to `surface`. */\n keyScope?: KeyScope;\n placement: Placement;\n requiredPorts: readonly PortName[];\n requiredContext?: readonly ContextKey[];\n requiredTarget?: readonly (keyof ActionTarget)[];\n // The failure reasons the action answers. An action on the failure row\n // (`row: 'failure'`) names them: it resolves only on a target whose\n // `failure` has one of them, and one there that names none answers no\n // failure. An action elsewhere that names them resolves the same way.\n // Either needs no `requiredTarget: ['failure']` beside it.\n answers?: readonly LaceReason[];\n // The action still resolves (renders) when a key here fails — it's shown\n // disabled instead, carrying the first failing entry's `reason` for the\n // toolbar/menu/row renderer's disabled title and for `ActionRunner.run`'s\n // own refusal notify. Order matters: the first entry that fails wins, so\n // Generate lists `resolved` before `saved` (registry.ts's\n // `disabledReason`).\n enabledWhen?: readonly { key: ContextKey; reason: string }[];\n binding: ErasedCommand | EditorBinding | HostBinding;\n};\n\n// A contribution set over the panel shape its holder needs: the registry and\n// `CanvasCtx` read a panel's `PanelSpec` alone, so the default set carries\n// no component; the React surface's `Contributions` (contributions.ts) is the\n// set over `Panel`.\nexport type ContributionSet<P extends PanelSpec = PanelSpec> = {\n overlays: readonly OverlayContribution[];\n panels: readonly P[];\n actions: readonly ActionContribution[];\n};\n","import { useCallback, useState } from 'react';\n\nexport type ContextMenuState = {\n x: number;\n y: number;\n nodeId: string | null;\n groupId: string | null;\n} | null;\n\nexport type ContextMenuRequest = {\n instanceId: string | null;\n groupId: string | null;\n x: number;\n y: number;\n};\n\n// The state (and the `showContextMenu` setter below) is owned by the one\n// Canvas instance that calls this hook — xyflow's own\n// `onNodeContextMenu`/`onPaneContextMenu` handlers call `showContextMenu`\n// directly rather than a window `CustomEvent`, so two Canvas mounts on one\n// page never see each other's right-clicks (a window listener is global;\n// this state is per-component-tree).\nexport function useContextMenu() {\n const [contextMenu, setContextMenu] = useState<ContextMenuState>(null);\n\n const showContextMenu = useCallback((request: ContextMenuRequest) => {\n setContextMenu({\n x: request.x,\n y: request.y,\n nodeId: request.instanceId,\n groupId: request.groupId,\n });\n }, []);\n\n const dismissContextMenu = useCallback(() => {\n setContextMenu(null);\n }, []);\n\n return { contextMenu, showContextMenu, dismissContextMenu };\n}\n","// Turns the projected CanvasView into the nodes and edges xyflow draws.\n// Where everything is drawn is the projection's (packages/proto's\n// projectCanvasView): a card's top-left, a group's box and its members'\n// origin. This file only re-expresses it the way xyflow nests nodes — every\n// member, card or group, is a child of its group (`parentId`), positioned\n// from the group's box — and hides a collapsed group's members and the\n// wires between them behind its card. Every edge the projection draws joins\n// two children of one scope, so no wire crosses a group's boundary; a\n// collapsed group's card draws its interface's pins, and the wires that\n// read or feed them land there. Whether a group is collapsed lives in the\n// consumer-owned CanvasArrangement and never reaches Terraform.\n\nimport type { XY } from '@lace-cloud/proto';\nimport type { Edge, Node } from '@xyflow/react';\nimport { useMemo } from 'react';\nimport { DEPENDENCY_EDGE_TYPE } from '../components/edges/DependencyEdge';\nimport type { InterfacePin } from '../components/nodes/GroupNode';\nimport { pinColor } from '../components/nodes/pinColor';\n\nimport { type DrawnDecorations, hasErrorBadge } from '../core/decorate';\nimport type { NodePin, RenderEdge, RenderGroup, RenderNode } from '../types/render';\nimport { sourceHandleId } from '../utils/handleId';\n\ntype GroupLogicResult = {\n rfNodes: Node[];\n rfEdges: Edge[];\n};\n\n/**\n * Where an xyflow node is drawn, in canvas coordinates: its own position,\n * or — for a member, which xyflow positions from its group's box — that\n * position plus where the projection drew the box. The inverse of the\n * nesting `useGroupLogic` builds, read against the projected groups, so a\n * drag reads what the projection drew around it rather than where xyflow\n * has the group mid-gesture.\n */\nexport function drawnPosition(\n groups: readonly RenderGroup[],\n node: Pick<Node, 'position' | 'parentId'>,\n): XY {\n const parent = node.parentId ? groups.find((g) => g.id === node.parentId) : undefined;\n if (!parent) return node.position;\n return { x: parent.position.x + node.position.x, y: parent.position.y + node.position.y };\n}\n\n// ── Hook ──\n\nexport function useGroupLogic(\n nodes: RenderNode[],\n edges: RenderEdge[],\n groups: RenderGroup[],\n newNodeIds: Set<string>,\n decorations?: DrawnDecorations,\n): GroupLogicResult {\n return useMemo(() => {\n // Who contains whom: a group's `node_ids` name its members, cards and\n // groups alike. A collapsed group hides every member and every\n // descendant, however deep.\n const parentOf = new Map<string, RenderGroup>();\n for (const g of groups) {\n for (const id of g.node_ids) parentOf.set(id, g);\n }\n const hiddenCache = new Map<string, boolean>();\n // Whether the members of group `g` are hidden: it or an ancestor is\n // collapsed.\n const membersHidden = (g: RenderGroup): boolean => {\n const cached = hiddenCache.get(g.id);\n if (cached !== undefined) return cached;\n const parent = parentOf.get(g.id);\n const hidden = g.collapsed || (parent ? membersHidden(parent) : false);\n hiddenCache.set(g.id, hidden);\n return hidden;\n };\n // xyflow positions a child from its parent's box.\n const nested = (id: string, at: XY): Pick<Node, 'position' | 'parentId' | 'hidden'> => {\n const parent = parentOf.get(id);\n if (!parent) return { position: at };\n return {\n position: { x: at.x - parent.position.x, y: at.y - parent.position.y },\n parentId: parent.id,\n hidden: membersHidden(parent) || undefined,\n };\n };\n\n const rfNodes: Node[] = [];\n\n // Groups first, in the projection's order — a parent before its\n // children, which xyflow needs to place a child from its parent.\n for (const group of groups) {\n const memberCount = group.node_ids.length;\n const groupBadges = decorations?.nodes[group.id]?.badges ?? [];\n const base = {\n id: group.id,\n type: 'groupNode',\n ...nested(group.id, group.position),\n };\n if (group.collapsed) {\n // A diagnostic addressed to the group's own scope (a submodule\n // root) resolves through `nodeIdForAddress` to the group's own id,\n // not any member's — those badges live in `decorations.nodes[group.id]`\n // and, collapsed, are the only decoration a user can see at all\n // (every member carrying its own badge is hidden). `hasErrors`\n // also rolls up a hidden member's own error so the collapsed\n // group's border reflects it.\n const hasErrors =\n group.node_ids.some((id) => hasErrorBadge(decorations?.nodes[id]?.badges)) ||\n hasErrorBadge(groupBadges);\n rfNodes.push({\n ...base,\n data: {\n groupId: group.id,\n moduleKey: group.module_key ?? '',\n label: group.label,\n memberCount,\n collapsed: true,\n hasErrors,\n badges: groupBadges,\n interfacePins: pinsOf(group),\n },\n });\n } else {\n rfNodes.push({\n ...base,\n style: { width: group.size.width, height: group.size.height },\n data: {\n groupId: group.id,\n moduleKey: group.module_key ?? '',\n label: group.label,\n memberCount,\n collapsed: false,\n hasErrors: hasErrorBadge(groupBadges),\n badges: groupBadges,\n interfacePins: [],\n },\n });\n }\n }\n\n // Every card, a member placed from its group's box. A hidden member\n // stays in the list: xyflow still keeps its bookkeeping.\n for (const n of nodes) {\n rfNodes.push({\n id: n.id,\n type: 'moduleNode',\n ...nested(n.id, n.position),\n data: {\n ...n,\n isNew: newNodeIds.has(n.id),\n badges: decorations?.nodes[n.id]?.badges,\n pins: decorations?.nodes[n.id]?.pins,\n },\n });\n }\n\n // A wire joins two children of one scope, so it is hidden with them\n // when that scope is a group whose members are hidden.\n const rfEdges = edges\n .filter((e) => {\n const scope = parentOf.get(e.source);\n return !(scope && membersHidden(scope));\n })\n .map(renderEdgeToRfEdge);\n\n return { rfNodes, rfEdges };\n }, [nodes, edges, groups, newNodeIds, decorations]);\n}\n\n// ── Helpers ──\n\n// A collapsed group's pins: its module's Interface (`groupPins`, which\n// `projectGroup` reads), inputs on the left rail and outputs on the right,\n// each whether or not a wire reaches it.\nfunction pinsOf(group: RenderGroup): InterfacePin[] {\n const pins = (side: InterfacePin['side'], prefix: string, of: readonly NodePin[] = []) =>\n of.map((pin) => ({ ...pin, handleId: `${prefix}:${pin.name}`, side, color: pinColor(pin) }));\n return [...pins('input', 'in', group.inputs), ...pins('output', 'out', group.outputs)];\n}\n\n// The `data` shape every rfEdge this file builds carries.\nexport type RfEdgeData = {\n source_output: string;\n target_input: string;\n};\n\n// Runtime-narrows an xyflow `Edge.data` (typed `Record<string, unknown> |\n// undefined` by xyflow itself) back to the shape this file produced it in,\n// rather than a component reading it back (Canvas.tsx's edge click/delete\n// handlers) asserting the type with `as`. `null` when the edge wasn't one\n// of this file's own — a required field missing or the wrong type.\nexport function rfEdgeData(edge: Edge): RfEdgeData | null {\n const data = edge.data;\n const sourceOutput = data?.source_output;\n const targetInput = data?.target_input;\n if (typeof sourceOutput !== 'string' || typeof targetInput !== 'string') return null;\n return { source_output: sourceOutput, target_input: targetInput };\n}\n\nfunction renderEdgeToRfEdge(e: RenderEdge): Edge {\n return {\n id: e.id,\n source: e.source,\n target: e.target,\n sourceHandle: sourceHandleId(e.source_output),\n targetHandle: `in:${e.target_input}`,\n data: { source_output: e.source_output, target_input: e.target_input },\n type: DEPENDENCY_EDGE_TYPE,\n };\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport type { CanvasView } from '../types/render';\n\n// What the frames after the session's first have added: `addedIds`, every\n// card a frame added that is still drawn — a module's card or a group's —\n// and of the module cards among them `newNodeIds`, the ones the developer\n// has not selected yet, which draw as new. An added card stays new across\n// later frames until the developer selects it — a click, a drag (xyflow\n// selects what it drags), opening it — and `clearNew` names the cards\n// selected; selecting one never takes it out of `addedIds`. A card a frame\n// no longer holds leaves both, so one a later frame adds again is added,\n// and new, again.\nexport function useNewNodeTracking(view: CanvasView | null) {\n const [addedIds, setAddedIds] = useState<Set<string>>(new Set());\n const [newNodeIds, setNewNodeIds] = useState<Set<string>>(new Set());\n const prevCardIdsRef = useRef<Set<string>>(new Set());\n const sessionLoadedRef = useRef(false);\n\n useEffect(() => {\n if (!view) return;\n const nodeIds = new Set(view.nodes.map((n) => n.id));\n const cardIds = new Set([...nodeIds, ...view.groups.map((g) => g.id)]);\n\n if (!sessionLoadedRef.current) {\n sessionLoadedRef.current = true;\n prevCardIdsRef.current = cardIds;\n return;\n }\n\n const prev = prevCardIdsRef.current;\n const added = [...cardIds].filter((id) => !prev.has(id));\n // `s` kept to the cards `drawn` holds, with what this frame added among\n // them.\n const track = (drawn: Set<string>) => (s: Set<string>) => {\n const arrived = added.filter((id) => drawn.has(id));\n const next = new Set([...s].filter((id) => drawn.has(id)));\n for (const id of arrived) next.add(id);\n return next.size !== s.size || arrived.length > 0 ? next : s;\n };\n setAddedIds(track(cardIds));\n setNewNodeIds(track(nodeIds));\n prevCardIdsRef.current = cardIds;\n }, [view]);\n\n const clearNew = useCallback((...ids: string[]) => {\n setNewNodeIds((s) => {\n const next = new Set(s);\n let changed = false;\n for (const id of ids) {\n if (next.delete(id)) changed = true;\n }\n return changed ? next : s;\n });\n }, []);\n\n return { addedIds, newNodeIds, clearNew };\n}\n","// Pure viewport-geometry helpers. A group made around members drawn near\n// the pane's edge has its card up and left of them, so it can sit outside\n// the visible area even though every member stays exactly where it was.\n// This computes the minimal camera pan — never a node move, never a zoom\n// change — that brings a flow-space rect fully inside the pane.\n\nexport type FlowRect = { x: number; y: number; width: number; height: number };\nexport type PaneSize = { width: number; height: number };\nexport type Viewport = { x: number; y: number; zoom: number };\n\n/**\n * The (dx, dy) to add to the current viewport's translation so `rect`\n * (in flow coordinates) is fully within the pane's [0, width] x [0, height]\n * screen bounds. Zero on either axis where `rect` is already fully\n * visible. Zoom never changes.\n */\nexport function computeMinimalPanDelta(\n rect: FlowRect,\n pane: PaneSize,\n viewport: Viewport,\n): { dx: number; dy: number } {\n const screenLeft = rect.x * viewport.zoom + viewport.x;\n const screenTop = rect.y * viewport.zoom + viewport.y;\n const screenRight = screenLeft + rect.width * viewport.zoom;\n const screenBottom = screenTop + rect.height * viewport.zoom;\n\n let dx = 0;\n if (screenLeft < 0) {\n dx = -screenLeft;\n } else if (screenRight > pane.width) {\n dx = pane.width - screenRight;\n }\n\n let dy = 0;\n if (screenTop < 0) {\n dy = -screenTop;\n } else if (screenBottom > pane.height) {\n dy = pane.height - screenBottom;\n }\n\n return { dx, dy };\n}\n\n/** `rect` grown by `margin` screen pixels on every side, in flow units at\n * `zoom`: room around a node brought into view, so it never lands flush\n * against the pane's edge. */\nexport function withMargin(rect: FlowRect, margin: number, zoom: number): FlowRect {\n const m = margin / zoom;\n return { x: rect.x - m, y: rect.y - m, width: rect.width + 2 * m, height: rect.height + 2 * m };\n}\n\nfunction fullyVisible(rect: FlowRect, pane: PaneSize, viewport: Viewport): boolean {\n const { dx, dy } = computeMinimalPanDelta(rect, pane, viewport);\n return dx === 0 && dy === 0;\n}\n\nexport type ResizeOutcome =\n | { kind: 'stay' }\n | { kind: 'fit' }\n | { kind: 'move'; viewport: Viewport };\n\n/**\n * Where the camera goes when the pane changes size from `before` to `after`\n * — the drawer opening or closing, the window resizing — so the developer\n * keeps what they were looking at:\n * - a graph that was wholly in view and still is stays put;\n * - a graph that was wholly in view and no longer fits is fitted again;\n * - otherwise the view keeps its centre, and `focus` (what is selected)\n * is then panned the least distance into view.\n * `graph` is null for an empty canvas, `focus` null when nothing is\n * selected. Zoom changes only by the fit.\n */\nexport function viewportAfterResize(\n viewport: Viewport,\n before: PaneSize,\n after: PaneSize,\n graph: FlowRect | null,\n focus: FlowRect | null,\n): ResizeOutcome {\n if (!graph) return { kind: 'stay' };\n if (fullyVisible(graph, before, viewport)) {\n return fullyVisible(graph, after, viewport) ? { kind: 'stay' } : { kind: 'fit' };\n }\n const centred: Viewport = {\n x: viewport.x + (after.width - before.width) / 2,\n y: viewport.y + (after.height - before.height) / 2,\n zoom: viewport.zoom,\n };\n if (!focus) return { kind: 'move', viewport: centred };\n const { dx, dy } = computeMinimalPanDelta(focus, after, centred);\n return { kind: 'move', viewport: { x: centred.x + dx, y: centred.y + dy, zoom: centred.zoom } };\n}\n","// The right-hand drawer App opens for a `slot: 'drawer'` panel — Settings,\n// or the inspector of what is selected. It is a column beside the canvas,\n// never over it, so the canvas's own width is what is left: Fit View fits\n// the graph beside an open drawer.\n//\n// The developer sizes it by its left edge, by pointer or by keyboard (a\n// focusable `separator`: arrows move it a step, Home and End take it to its\n// narrowest and widest). Its bounds are the design tokens\n// `--lace-size-drawer-min` / `-default` / `-max`, read where it is mounted;\n// the stylesheet clamps to the same tokens, so a width held from a wider\n// window still fits.\nimport type React from 'react';\nimport { type ReactNode, useCallback, useLayoutEffect, useRef, useState } from 'react';\nimport { readTokenPx, type StyleWithVars } from '../utils/style-vars';\nimport './Drawer.css';\n\nconst KEY_STEP = 16;\n\ntype Bounds = { min: number; max: number };\n\n// The drawer's bounds, in px, from the tokens in effect at `el`; null while\n// they are not loaded.\nexport function readDrawerBounds(el: Element): Bounds | null {\n const min = readTokenPx(el, '--lace-size-drawer-min');\n const max = readTokenPx(el, '--lace-size-drawer-max');\n return min > 0 && max >= min ? { min, max } : null;\n}\n\nexport function clampWidth(width: number, bounds: Bounds | null): number {\n if (!bounds) return width;\n return Math.min(bounds.max, Math.max(bounds.min, width));\n}\n\nexport default function Drawer({ label, children }: { label: string; children: ReactNode }) {\n const ref = useRef<HTMLElement>(null);\n const [bounds, setBounds] = useState<Bounds | null>(null);\n // Null until the developer sizes it: the stylesheet's default width.\n const [width, setWidth] = useState<number | null>(null);\n // The width it is drawn at, for the separator's value and a key's step.\n const [measured, setMeasured] = useState(0);\n const drag = useRef<{ x: number; width: number } | null>(null);\n\n useLayoutEffect(() => {\n if (ref.current) setBounds(readDrawerBounds(ref.current));\n }, []);\n // biome-ignore lint/correctness/useExhaustiveDependencies: re-measured whenever the developer resizes it.\n useLayoutEffect(() => {\n if (ref.current) setMeasured(Math.round(ref.current.getBoundingClientRect().width));\n }, [width]);\n\n const onPointerDown = useCallback((e: React.PointerEvent<HTMLDivElement>) => {\n e.preventDefault();\n e.currentTarget.setPointerCapture(e.pointerId);\n drag.current = { x: e.clientX, width: ref.current?.getBoundingClientRect().width ?? 0 };\n }, []);\n\n const onPointerMove = useCallback(\n (e: React.PointerEvent<HTMLDivElement>) => {\n if (!drag.current) return;\n // The handle is the drawer's left edge: moving it left widens it.\n setWidth(clampWidth(drag.current.width + drag.current.x - e.clientX, bounds));\n },\n [bounds],\n );\n\n const onPointerUp = useCallback((e: React.PointerEvent<HTMLDivElement>) => {\n drag.current = null;\n e.currentTarget.releasePointerCapture(e.pointerId);\n }, []);\n\n const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n const next =\n e.key === 'ArrowLeft'\n ? measured + KEY_STEP\n : e.key === 'ArrowRight'\n ? measured - KEY_STEP\n : e.key === 'Home' && bounds\n ? bounds.min\n : e.key === 'End' && bounds\n ? bounds.max\n : undefined;\n if (next === undefined) return;\n e.preventDefault();\n setWidth(clampWidth(next, bounds));\n };\n\n const style: StyleWithVars | undefined =\n width === null ? undefined : { '--drawer-width': `${width}px` };\n\n return (\n <aside ref={ref} className=\"lace-app__drawer\" aria-label={label} style={style}>\n <div\n className=\"lace-app__drawer-handle\"\n role=\"separator\"\n aria-orientation=\"vertical\"\n aria-label=\"Resize panel\"\n aria-valuenow={measured}\n aria-valuemin={bounds?.min}\n aria-valuemax={bounds?.max}\n tabIndex={0}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n onKeyDown={onKeyDown}\n />\n <div className=\"lace-app__drawer-body\">{children}</div>\n </aside>\n );\n}\n","import type { CSSProperties } from 'react';\n\n// An inline style that sets CSS custom properties beside the standard ones:\n// React hands a `--name` key straight to `style.setProperty`, so a\n// component's stylesheet can read a value only the component knows (the\n// viewport's zoom, a width the developer dragged).\nexport type StyleWithVars = CSSProperties & { [name: `--${string}`]: string | number };\n\n// A design token's length, in px, as it is in effect at `el`; NaN while it\n// is not set (the tokens' stylesheet not loaded) or not a length.\nexport function readTokenPx(el: Element, name: `--${string}`): number {\n return Number.parseFloat(getComputedStyle(el).getPropertyValue(name));\n}\n","import React from 'react';\nimport './ErrorBoundary.css';\n\ntype ErrorStateProps = { message: string };\n\nexport function ErrorState({ message }: ErrorStateProps) {\n return (\n <div className=\"lace-error-state\" role=\"alert\">\n <h3 className=\"lace-error-state__title\">Something went wrong</h3>\n <pre className=\"lace-error-state__message\">{message}</pre>\n <button\n type=\"button\"\n className=\"lace-error-state__reload\"\n onClick={() => window.location.reload()}\n >\n Reload\n </button>\n </div>\n );\n}\n\nexport default class ErrorBoundary extends React.Component<\n { children: React.ReactNode },\n { error: Error | null }\n> {\n state: { error: Error | null } = { error: null };\n\n static getDerivedStateFromError(error: Error) {\n return { error };\n }\n\n render() {\n if (this.state.error) {\n return <ErrorState message={this.state.error.message} />;\n }\n return this.props.children;\n }\n}\n","// One toolbar action, drawn with the design system's controls at the\n// toolbar's 28px rung:\n// - an action with `primary`: the labelled call to action, its glyph\n// beside the label, filled in the accent while it is the thing to do next\n// and a quiet secondary button otherwise;\n// - an action with an `icon`: an icon button;\n// - an action with neither: a text button carrying its label, so a host's\n// action with no glyph of its own still reads.\n// Each carries a themed tooltip naming the action, its key beside the name\n// and, while it cannot run, why under them; the key and the reason are what\n// the name lacks, and all that describes it. A running action shows a\n// spinner in place of its glyph, and a primary its `busy` label\n// (\"Generating…\").\nimport { Button, IconButton, Spinner, type TooltipPlacement } from '@lace-cloud/ui';\nimport type { ReactNode } from 'react';\nimport type { ActionContribution } from '../contributions';\nimport { formatChord, isMacPlatform } from '../utils/key-chord';\nimport { CanvasIcon } from './icons';\nimport './ToolbarAction.css';\n\ntype Props = {\n action: ActionContribution;\n // Why the action cannot run now; undefined while it can.\n disabledReason: string | undefined;\n // `primary.when` holds: the accent fill.\n emphasized: boolean;\n // The action is running: its `busy.label` when it declares one, else its\n // own label. Undefined while idle.\n busyLabel: string | undefined;\n onRun: () => void;\n};\n\n// A toolbar control's tooltip hangs under it from its start edge.\nconst TIP: TooltipPlacement = 'bottom-start';\n\n// The tooltip's description: the action's key, and why it cannot run.\n// Nothing when it has neither, so a control with no key that can run is\n// described by nothing.\nfunction actionTip(keys: readonly string[] | undefined, reason: string | undefined): ReactNode {\n const chord = keys?.[0] ? formatChord(keys[0], isMacPlatform()) : undefined;\n if (!chord && !reason) return undefined;\n return (\n <span className=\"lace-action-tip\">\n {chord ? <kbd className=\"lace-action-tip__key\">{chord}</kbd> : null}\n {reason ? <span className=\"lace-action-tip__reason\">{reason}</span> : null}\n </span>\n );\n}\n\nexport function ToolbarAction({ action, disabledReason, emphasized, busyLabel, onRun }: Props) {\n const busy = busyLabel !== undefined;\n const disabled = disabledReason !== undefined;\n const tooltip = actionTip(action.keys, disabledReason);\n const glyph = action.icon ? <CanvasIcon name={action.icon} /> : undefined;\n\n if (action.primary) {\n return (\n <Button\n rung\n size=\"sm\"\n variant={emphasized ? 'primary' : 'secondary'}\n icon={busy ? undefined : glyph}\n loading={busy}\n disabled={disabled}\n tooltip={tooltip}\n tooltipName={action.label}\n tooltipPlacement={TIP}\n className=\"lace-toolbar-action\"\n onClick={onRun}\n >\n {busyLabel ?? action.label}\n </Button>\n );\n }\n if (glyph) {\n return (\n <IconButton\n icon={busy ? <Spinner size={14} aria-hidden=\"true\" /> : glyph}\n aria-label={action.label}\n size=\"md\"\n disabled={disabled}\n tooltip={tooltip}\n tooltipPlacement={TIP}\n onClick={onRun}\n />\n );\n }\n return (\n <Button\n rung\n size=\"sm\"\n variant=\"ghost\"\n loading={busy}\n disabled={disabled}\n tooltip={tooltip}\n tooltipName={action.label}\n tooltipPlacement={TIP}\n className=\"lace-toolbar-action\"\n onClick={onRun}\n >\n {busyLabel ?? action.label}\n </Button>\n );\n}\n","// CommandArgsForm is the one form mechanism for every action: it renders\n// the `ActionRunner`'s own `pendingForm` (`core/run-binding.ts`) — the\n// missing required keys a binding's `args(ctx, target)` left unset — typed\n// from the golden (`COMMANDS[path]`) where the path is a bound command\n// (every `pendingForm.path` always is, since only `defineCommand`'s\n// `start()` opens one). Submit hands the values back to `runner`, which\n// re-runs `completeArgs` and invokes.\nimport { useState } from 'react';\nimport type { CommandPath } from '../contracts';\nimport { COMMANDS } from '../contracts';\nimport type { PendingForm } from './run-binding';\n\nexport type CommandArgsFormProps = {\n form: PendingForm;\n};\n\n// `pendingForm.path` is a plain `string` (run-binding.ts's `PendingForm`\n// erases the path-specific generic `ErasedCommand` already carries) — this\n// guard is the one narrowing back to a `CommandPath` so `COMMANDS[path]`\n// indexes without a cast.\nfunction isCommandPath(path: string): path is CommandPath {\n return path in COMMANDS;\n}\n\n// Every one of the golden's ~40 per-command flag records shares this\n// shape (`type`, and for a required one, `required`) — the return type\n// annotation is the one widening boundary from the golden's own literal\n// per-command flags type to a plain lookup, checked structurally, not\n// asserted.\nfunction flagsOf(path: CommandPath): Record<string, { type?: string }> {\n return COMMANDS[path].flags;\n}\n\nexport function CommandArgsForm({ form }: CommandArgsFormProps) {\n const [values, setValues] = useState<Record<string, string | boolean>>({});\n\n if (!form) return null;\n\n const flags = isCommandPath(form.path) ? flagsOf(form.path) : {};\n\n return (\n <form\n className=\"lace-command-args-form\"\n onSubmit={(e) => {\n e.preventDefault();\n form.submit(values);\n }}\n >\n {form.missing.map((key) => {\n const flagType = flags[key]?.type;\n return (\n <label className=\"lace-command-args-form__field\" key={key}>\n <span>{key}</span>\n {flagType === 'bool' ? (\n <input\n type=\"checkbox\"\n checked={Boolean(values[key])}\n onChange={(e) => setValues((prev) => ({ ...prev, [key]: e.target.checked }))}\n />\n ) : (\n <input\n type=\"text\"\n required\n value={typeof values[key] === 'string' ? values[key] : ''}\n onChange={(e) => setValues((prev) => ({ ...prev, [key]: e.target.value }))}\n />\n )}\n </label>\n );\n })}\n <div className=\"lace-command-args-form__actions\">\n <button type=\"submit\">Continue</button>\n <button type=\"button\" onClick={form.cancel}>\n Cancel\n </button>\n </div>\n </form>\n );\n}\n\nexport default CommandArgsForm;\n","// The describe overlay: the one overlay the canvas core registers. It\n// reads `stack describe` and decorates the view with the resource count\n// and drift state a stack's Terraform state carries per node, resolving\n// each resource's address to a node with `nodeIdForAddress`\n// (@lace-cloud/proto) — the same resolver `nodeIdForDiagnostic` composes\n// on for an address-carrying diagnostic.\n//\n// The describe command is suppressed for a historical/CR mount by that\n// mount's own `commands.available()` — the overlay itself declares no\n// run-id logic; `resolveContributions` (registry.ts) already checks the\n// declared path against `available()` before this ever fetches.\nimport type { CanvasView } from '@lace-cloud/proto';\nimport { nodeIdForAddress } from '@lace-cloud/proto';\nimport type { ArgsOf, JsonOf } from '../../contracts';\nimport type { Badge, CanvasCtx, Decorations } from '../../contributions';\nimport { defineOverlay } from '../define-overlay';\n\ntype DescribeData = JsonOf<'stack describe'>;\n\nexport function decorateDescribe(view: CanvasView, data: DescribeData): Decorations {\n const nodes: Record<string, { badges: Badge[] }> = {};\n const addBadge = (nodeId: string, badge: Badge) => {\n if (!nodes[nodeId]) nodes[nodeId] = { badges: [] };\n nodes[nodeId].badges.push(badge);\n };\n\n // A null `state` means the stack has never applied — there is nothing to\n // count, so no resource badge, not a \"0 resources\" one.\n if (data.state) {\n const countByNode = new Map<string, number>();\n for (const resource of data.state.resources) {\n const nodeId = nodeIdForAddress(view, resource.address);\n if (nodeId === null) continue;\n countByNode.set(nodeId, (countByNode.get(nodeId) ?? 0) + 1);\n }\n for (const [nodeId, count] of countByNode) {\n addBadge(nodeId, {\n id: 'resources',\n tone: 'neutral',\n label: `${count} resource${count === 1 ? '' : 's'}`,\n });\n }\n }\n\n // A null `drift` means no scan has run — that's not \"in sync\", so it\n // renders no drift badge either.\n if (data.drift) {\n const driftedNodes = new Set<string>();\n for (const resource of data.drift.driftedResources) {\n const nodeId = nodeIdForAddress(view, resource.address);\n if (nodeId === null) continue;\n driftedNodes.add(nodeId);\n }\n for (const nodeId of driftedNodes) {\n addBadge(nodeId, { id: 'drift', tone: 'warn', label: 'drifted' });\n }\n }\n\n return { nodes };\n}\n\nexport const describeOverlay = defineOverlay({\n id: 'describe',\n read: {\n path: 'stack describe',\n args: (ctx: CanvasCtx): ArgsOf<'stack describe'> | null =>\n ctx.stack ? { stack: ctx.stack.id } : null,\n },\n decorate: decorateDescribe,\n});\n","// The one overlay decoration hook: it composes `useCommandRead` (a mounting\n// OverlayRunner wraps every overlay in the same `PanelScope` a panel's\n// declared reads run inside), so an overlay fetches through the identical\n// registry-gated path a panel does — no second overlay-fetch mechanism.\n// The decorations are memoized on (view, data): OverlayRunner publishes them\n// from an effect keyed on their identity into App state, so a fresh object\n// every render would re-render App, re-run the effect, and never settle.\n// It lives apart from ../contributions.ts so the contract types load no\n// React of their own.\nimport type { CanvasView } from '@lace-cloud/proto';\nimport { useMemo } from 'react';\nimport type { BoundPath, JsonOf } from '../contracts';\nimport type { CommandRead, Decorations, OverlayContribution } from '../contributions';\nimport { useCommandRead } from './use-command-read';\n\nconst EMPTY_DECORATIONS: Decorations = { nodes: {} };\n\nexport function defineOverlay<P extends BoundPath>(o: {\n id: string;\n read: CommandRead<P>;\n decorate(v: CanvasView, d: JsonOf<P>): Decorations;\n}): OverlayContribution {\n return {\n id: o.id,\n paths: [o.read.path],\n useDecorations(ctx) {\n const { data } = useCommandRead(o.read);\n const view = ctx.view;\n return useMemo(\n () => (data ? o.decorate(view, data) : EMPTY_DECORATIONS),\n [o.decorate, view, data],\n );\n },\n };\n}\n","// useCommandRead is the only read: every panel and overlay that fetches\n// through `commands.invoke` goes through this one hook, keyed on the\n// declared read's own args plus the shared invalidation tick — never a\n// hand-rolled fetch loop. A refetch key change or unmount aborts the\n// in-flight signal — a\n// detach, never `Invocation.cancel()`; this hook never holds a `cancel`\n// reference at all.\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport type { BoundPath, JsonOf } from '../contracts';\nimport type { ActionTarget, CommandRead } from '../contributions';\nimport { isPlainObject } from '../utils/is-plain-object';\nimport { usePanelScope } from './panel-scope';\n\nexport type CommandReadState<P extends BoundPath> = {\n data: JsonOf<P> | null;\n error: Error | null;\n pending: boolean;\n};\n\nconst INITIAL = { data: null, error: null, pending: false };\n\n// Distinguishes \"no read has ever run yet\" from a real key of `null` (a\n// declared read whose `args` currently declines) — a plain `null` sentinel\n// for \"unset\" would make the very first effect run look like a tick-only\n// refetch of a declined read.\nconst NOT_YET_READ = Symbol('not-yet-read');\n\n// A deep, key-sorted JSON string: two args objects with the same content in\n// a different key order refetch key-equal, so a binding's own `args()`\n// building its return value in a different property order each render\n// never causes a spurious refetch.\nfunction stableJson(value: unknown): string {\n return JSON.stringify(value, (_key, val) => {\n if (isPlainObject(val)) {\n const sorted: Record<string, unknown> = {};\n for (const k of Object.keys(val).sort()) {\n sorted[k] = val[k];\n }\n return sorted;\n }\n return val;\n });\n}\n\nexport function useCommandRead<P extends BoundPath>(\n read: CommandRead<P>,\n target?: ActionTarget,\n): CommandReadState<P> {\n const scope = usePanelScope();\n if (!scope.paths.has(read.path)) {\n throw new Error(\n `useCommandRead('${read.path}') is not declared in this panel's reads — add it to the Panel's \\`reads\\``,\n );\n }\n\n const effectiveTarget = target ?? scope.target;\n const args = read.args(scope.ctx, effectiveTarget);\n const key = args === null ? null : stableJson(args);\n const [state, setState] = useState<CommandReadState<P>>(INITIAL);\n const prevKeyRef = useRef<string | null | typeof NOT_YET_READ>(NOT_YET_READ);\n\n // This render's inputs, read by the fetch effect below when it runs: the\n // refetch key is `stableJson(args)` + tick alone, so the commands port,\n // the error sink or `args` itself moving without moving either must not\n // refetch on their own — yet the run that does fire uses the latest of\n // each. Declared before the fetch effect, so it has already updated by\n // the time that one runs in the same commit.\n const inputs = {\n path: read.path,\n args,\n commands: scope.ctx.ports.commands,\n reportError: scope.reportError,\n };\n const inputsRef = useRef(inputs);\n useEffect(() => {\n inputsRef.current = inputs;\n });\n const request = useMemo(() => ({ key, tick: scope.tick }), [key, scope.tick]);\n\n useEffect(() => {\n const { path, args, commands, reportError } = inputsRef.current;\n // A tick-only refetch (the key itself hasn't moved) keeps the last\n // page's `data` and error on screen while the new one loads — only a\n // real key change (a different stack, a different target) clears both,\n // so switching from stack A to stack B never shows a beat of A's own\n // rows, badges or load error under B's own tab.\n const keyChanged = prevKeyRef.current !== request.key;\n prevKeyRef.current = request.key;\n // Narrows `args` itself (not just `key`, which is derived from it) so\n // the `commands.invoke` call below sees `ArgsOf<P>`, never `| null`.\n if (args === null || !commands) {\n setState(INITIAL);\n reportError(path, null);\n return;\n }\n if (keyChanged) {\n setState({ data: null, error: null, pending: true });\n reportError(path, null);\n } else {\n setState((s) => ({ ...s, pending: true }));\n }\n const controller = new AbortController();\n const invocation = commands.invoke(path, args, controller.signal);\n (async () => {\n try {\n for await (const event of invocation.events) {\n if (controller.signal.aborted) return;\n setState({ data: event, error: null, pending: false });\n reportError(path, null);\n }\n } catch (err) {\n if (controller.signal.aborted) return;\n const error = err instanceof Error ? err : new Error(String(err));\n setState({ data: null, error, pending: false });\n reportError(path, error);\n }\n })();\n return () => controller.abort();\n }, [request]);\n\n return state;\n}\n","// PanelScope declares, for the panel/overlay React is about to render, the\n// exact set of `BoundPath`s it may read and the `CanvasCtx`/`ActionTarget`/\n// tick generation those reads run against. `useCommandRead` asserts its own\n// path is in this set — an undeclared read is a defect the type system\n// can't catch (a path string, not a type), so this is the runtime guard.\n\nimport type { ReactNode } from 'react';\nimport { createContext, useContext, useMemo } from 'react';\nimport type { BoundPath } from '../contracts';\nimport type { ActionTarget, CanvasCtx } from '../contributions';\n\nexport type PanelScopeValue = {\n ctx: CanvasCtx;\n target: ActionTarget;\n paths: ReadonlySet<BoundPath>;\n tick: number;\n // `useCommandRead` reports every read's own success/failure here — the one\n // place a failed read surfaces, instead of each panel's own render\n // deciding whether to show the `error` its call site happens to destructure.\n // A scope with no `onReadError` wired up gets the no-op default.\n reportError(path: BoundPath, error: Error | null): void;\n};\n\nconst noopReportError = () => {};\n\nconst PanelScopeContext = createContext<PanelScopeValue | null>(null);\n\nexport function PanelScope({\n ctx,\n target = {},\n paths,\n tick,\n onReadError,\n children,\n}: {\n ctx: CanvasCtx;\n target?: ActionTarget;\n paths: readonly BoundPath[];\n tick: number;\n onReadError?: (path: BoundPath, error: Error | null) => void;\n children: ReactNode;\n}) {\n const reportError = onReadError ?? noopReportError;\n const value = useMemo<PanelScopeValue>(\n () => ({ ctx, target, paths: new Set(paths), tick, reportError }),\n [ctx, target, paths, tick, reportError],\n );\n return <PanelScopeContext.Provider value={value}>{children}</PanelScopeContext.Provider>;\n}\n\nexport function usePanelScope(): PanelScopeValue {\n const value = useContext(PanelScopeContext);\n if (!value) {\n throw new Error(\n 'usePanelScope: not inside a <PanelScope> — mount panels/overlays through App, which wraps every declared-read contribution',\n );\n }\n return value;\n}\n","// A banner over its panel's row actions, the one way a core banner draws\n// them: the opening sentence states the fact, the `choice` of each action\n// resolved on the panel's row (`rowActionsFor`) follows it in resolve order\n// — core's, then a host's — and the actions are its buttons, each run\n// through the runner like any row action. The buttons are drawn alike, none\n// as a call to action: the developer picks among them. An action with no\n// `choice` is a button that adds no sentence, and a row that resolves no\n// action leaves the opening alone. A button is drawn as the toolbar draws\n// its action (`actionState`): disabled, saying why, while another\n// command runs on its target, and spinning while its own does.\nimport { Button } from '@lace-cloud/ui';\nimport Banner from '../../components/Banner';\nimport type { ActionContribution, CanvasCtx } from '../../contributions';\nimport { actionState } from '../../registry';\nimport { useCanvas } from '../../state/canvas-context';\nimport { rowActionsFor, useEditorEnvExtras } from './row-actions';\n\ntype Props = {\n ctx: CanvasCtx;\n // The panel whose `row:` actions the banner draws.\n panelId: string;\n severity: 'warning' | 'error';\n // The banner's own hook class; each button carries `<className>__<action id>`.\n className: string;\n opening: string;\n};\n\nfunction bannerMessage(opening: string, actions: readonly ActionContribution[]): string {\n return [opening, ...actions.flatMap((action) => (action.choice ? [action.choice] : []))].join(\n ' ',\n );\n}\n\nexport function RowActionBanner({ ctx, panelId, severity, className, opening }: Props) {\n const { runner } = useCanvas();\n const envExtras = useEditorEnvExtras();\n const actions = rowActionsFor(ctx, panelId);\n\n return (\n <Banner\n severity={severity}\n className={className}\n message={bannerMessage(opening, actions)}\n actions={\n actions.length === 0\n ? undefined\n : actions.map((action) => {\n const state = actionState(action, ctx, runner.busy(action, ctx, {}));\n return (\n <Button\n key={action.id}\n rung\n size=\"sm\"\n variant=\"secondary\"\n className={`${className}__${action.id}`}\n disabled={state.disabledReason !== undefined}\n loading={state.busyLabel !== undefined}\n tooltip={state.disabledReason}\n onClick={() => void runner.run(action, ctx, {}, envExtras)}\n >\n {action.label}\n </Button>\n );\n })\n }\n />\n );\n}\n","// A banner row in App's strip under the toolbar: one fact that needs the\n// developer, then the choices that settle it — its severity's colour and\n// glyph, the message, then the actions as real buttons. `warning` is a\n// decision waiting (announced politely, `status`); `error` is something\n// locked (`alert`).\nimport type { ReactNode } from 'react';\nimport { CanvasIcon } from './icons';\nimport './Banner.css';\n\ntype Props = {\n severity: 'warning' | 'error';\n message: ReactNode;\n // The banner's own hook class (`lace-conflict-banner`, …).\n className: string;\n actions?: ReactNode;\n};\n\nexport default function Banner({ severity, message, className, actions }: Props) {\n return (\n <div\n className={`lace-banner lace-banner--${severity} ${className}`}\n role={severity === 'error' ? 'alert' : 'status'}\n >\n <span className=\"lace-banner__icon\">\n <CanvasIcon name={severity} />\n </span>\n <span className=\"lace-banner__message\">{message}</span>\n {actions ? <span className=\"lace-banner__actions\">{actions}</span> : null}\n </div>\n );\n}\n","// The conflict banner: the tf changed under an unsaved or ungenerated\n// working IR and needs Keep or Reload. Keep/Reload are `row:conflict`\n// editor bindings drawn through RowActionBanner, so Reload's own `confirm`\n// runs through the runner's one `presenter.confirm(` call site, never a\n// second inline confirm here. The banner resolves while a conflict is open\n// (its `requiredContext`, `conflict`), independently of `editable` — the\n// conflict stays visible under the lock too — but its row resolves no\n// actions there: Keep/Reload require `editable`, hidden alongside Save\n// and Generate.\nimport type { Panel, PanelProps } from '../../contributions';\nimport { RowActionBanner } from './RowActionBanner';\n\nexport function ConflictBanner({ ctx }: PanelProps) {\n return (\n <RowActionBanner\n ctx={ctx}\n panelId=\"conflict\"\n severity=\"warning\"\n className=\"lace-conflict-banner\"\n opening=\"The module's .tf files changed outside the canvas while it held edits of its own.\"\n />\n );\n}\n\nexport const conflictPanel: Panel = {\n id: 'conflict',\n title: 'Conflict',\n slot: 'banner',\n requiredPorts: [],\n requiredContext: ['conflict'],\n Component: ConflictBanner,\n};\n\nexport default ConflictBanner;\n","// The diagnostics panel: `ctx.diagnostics` is already\n// the one merged list (App's own `diagnosticsOf`, core/diagnostics.ts) of\n// the engine's live findings and the current report's — the fold over the\n// results of the commands that ran in the session's root, whichever client\n// ran them (core/report-fold.ts). The canvas runs no validator of its own,\n// and merging a second time here would double every report-derived row, so\n// this panel reads `ctx.diagnostics` directly, the same list `decorate`'s\n// per-node badges read.\n//\n// Every row passes its own datum — the whole `Diagnostic` — as the target\n// through `rowActionsFor(ctx, 'diagnostics', target)`, the same resolver\n// every other row-action panel (the conflict banner, the edge inspector)\n// uses, never a panel-private one. A host contributes its own row action (e.g. jump to\n// source) through the identical registry, reading whichever fields off\n// `target.diagnostic` it needs — that's the seam (seam-ports.test.tsx), not\n// a core mechanism or a field minted for one hypothetical consumer. Each\n// row's button is drawn as the toolbar draws its action (`actionState`).\n\nimport type { Diagnostic } from '@lace-cloud/proto';\nimport { Button } from '@lace-cloud/ui';\nimport Identifier from '../../components/Identifier';\nimport { CanvasIcon } from '../../components/icons';\nimport type { Panel, PanelProps } from '../../contributions';\nimport { actionState } from '../../registry';\nimport { useCanvas } from '../../state/canvas-context';\nimport { rowActionsFor, useEditorEnvExtras } from './row-actions';\nimport './DiagnosticsPanel.css';\n\nfunction rowKey(d: Diagnostic, index: number): string {\n return `${d.severity}:${d.module_key ?? ''}.${d.instance_id ?? ''}:${index}`;\n}\n\nexport function DiagnosticsPanel({ ctx }: PanelProps) {\n const { runner } = useCanvas();\n const envExtras = useEditorEnvExtras();\n const diagnostics = ctx.diagnostics;\n\n return (\n <ul className=\"lace-diagnostics-panel\" role=\"list\">\n {diagnostics.map((d, index) => {\n const key = rowKey(d, index);\n const target = { diagnostic: d };\n const actions = rowActionsFor(ctx, 'diagnostics', target);\n return (\n <li\n key={key}\n className={`lace-diagnostics-panel__row lace-diagnostics-panel__row--${d.severity}`}\n >\n <span className=\"lace-diagnostics-panel__icon\">\n <CanvasIcon name={d.severity} />\n </span>\n <span className=\"lace-diagnostics-panel__body\">\n <span className=\"lace-diagnostics-panel__message\">{d.message}</span>\n {d.instance_id !== undefined && (\n <Identifier\n className=\"lace-diagnostics-panel__where\"\n text={d.input_name ? `${d.instance_id}.${d.input_name}` : d.instance_id}\n />\n )}\n {d.code !== undefined && (\n <Identifier className=\"lace-diagnostics-panel__code\" text={d.code} />\n )}\n {actions.map((action) => {\n const state = actionState(action, ctx, runner.busy(action, ctx, target));\n return (\n <Button\n key={action.id}\n rung\n size=\"sm\"\n variant=\"ghost\"\n className=\"lace-diagnostics-panel__action\"\n disabled={state.disabledReason !== undefined}\n loading={state.busyLabel !== undefined}\n tooltip={state.disabledReason}\n onClick={() => void runner.run(action, ctx, target, envExtras)}\n >\n {action.label}\n </Button>\n );\n })}\n </span>\n </li>\n );\n })}\n </ul>\n );\n}\n\nexport const diagnosticsPanel: Panel = {\n id: 'diagnostics',\n title: 'Diagnostics',\n slot: 'bottom',\n requiredPorts: [],\n // Resolves only once there is something to show — `ctx.diagnostics`\n // non-empty (registry.ts's `contextSatisfied`) — so an otherwise-clean\n // mount never draws an empty 240px Diagnostics tab.\n requiredContext: ['diagnostics'],\n Component: DiagnosticsPanel,\n};\n\nexport default DiagnosticsPanel;\n","// An identifier as the canvas shows it — an instance, an input, an output,\n// a module address: monospace, and broken across lines only after a `_` or\n// a `.`, so a long snake_case name wraps at its word joins rather than\n// mid-word. Each join carries a <wbr>, a break the browser prefers to the\n// panel's last-resort `overflow-wrap: anywhere`, which still applies to a\n// single segment longer than a line.\nimport { Fragment } from 'react';\nimport './Identifier.css';\n\n// `text` cut after every `_` and `.`, each joint kept on the piece before\n// it: the places an identifier may break.\nexport function identifierSegments(text: string): string[] {\n return text.split(/(?<=[_.])/);\n}\n\nexport default function Identifier({ text, className }: { text: string; className?: string }) {\n return (\n <span className={className ? `lace-identifier ${className}` : 'lace-identifier'}>\n {identifierSegments(text).map((segment, i) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: a segment's place in the name is its identity.\n <Fragment key={i}>\n {i > 0 ? <wbr /> : null}\n {segment}\n </Fragment>\n ))}\n </span>\n );\n}\n","// The edge-inspector panel: a thin Panel wrapper around\n// `components/panels/EdgeInspectorPanel`, deriving its props from\n// `ctx.selection.edge` (already the exact `{source, target, sourceOutput,\n// targetInput}` shape the component wants).\n//\n// \"Delete connection\" is the panel's own `row: 'edge-inspector'` action\n// (`disconnectEdge`, below), resolved through `rowActionsFor` and dispatched\n// through `runner.run` — the same `ActionRunner` path every other IR edit\n// takes (confirm → apply → route the `ApplyResult` → tick), so a host's own\n// confirm or `run` on the resolved contribution is what executes. Like every\n// editor binding it declares the `editor` port and the `editable` context,\n// so it resolves nowhere a canvas is read-only (no `editor` port, or the\n// source-refused lock), and the component draws its button only for the\n// action that resolved. The inspector closes only by its own Close or when\n// a frame does not hold the wire (App's `reconcileSelection`): a\n// disconnect that lands closes it with the frame that drops the wire, and a\n// failing `ApplyResult` reaches `presenter.notify` and leaves it open over\n// the still-wired edge.\nimport { instanceAddress } from '@lace-cloud/proto';\nimport { createElement } from 'react';\nimport EdgeInspectorPanelComponent from '../../components/panels/EdgeInspectorPanel';\nimport type { ActionContribution, EditorBinding, Panel, PanelProps } from '../../contributions';\nimport { useCanvas } from '../../state/canvas-context';\nimport { rowActionsFor, useEditorEnvExtras } from './row-actions';\n\nconst disconnectBinding: EditorBinding = {\n kind: 'editor',\n result: 'apply',\n async run(env) {\n const edge = env.ctx.selection.edge;\n // `disconnectEdge`'s own `requiredContext` ('selection.edge') already\n // ensures this when the row action resolves at all — no edge means\n // nothing to disconnect, not a failure.\n if (!edge) return { success: true, errors: [], created: [], ties: [] };\n const target = instanceAddress(env.bundle, edge.target);\n return env.apply([\n { disconnect: { scope: target.scope, target: target.id, input_name: edge.targetInput } },\n ]);\n },\n};\n\nexport const disconnectEdge: ActionContribution = {\n id: 'disconnect',\n label: 'Delete connection',\n placement: { row: 'edge-inspector' },\n requiredPorts: ['editor'],\n requiredContext: ['editable', 'selection.edge'],\n binding: disconnectBinding,\n};\n\nfunction EdgeInspectorPanel({ ctx }: PanelProps) {\n const { runner, setSelection } = useCanvas();\n const envExtras = useEditorEnvExtras();\n const edge = ctx.selection.edge;\n if (!edge) return null;\n\n const disconnect = rowActionsFor(ctx, 'edge-inspector').find((a) => a.id === 'disconnect');\n\n return createElement(EdgeInspectorPanelComponent, {\n source: edge.source,\n target: edge.target,\n sourceOutput: edge.sourceOutput,\n targetInput: edge.targetInput,\n // The delete button exists exactly when `disconnect` resolved.\n ...(disconnect\n ? {\n onDelete: () => {\n void runner.run(disconnect, ctx, {}, envExtras);\n },\n }\n : {}),\n onClose: () => setSelection({ nodes: [], edge: null }),\n });\n}\n\nexport const edgeInspectorPanel: Panel = {\n id: 'edge-inspector',\n title: 'Connection',\n slot: 'drawer',\n requiredPorts: [],\n requiredContext: ['selection.edge'],\n Component: EdgeInspectorPanel,\n};\n\nexport default EdgeInspectorPanel;\n","import { callText } from '@lace-cloud/proto';\nimport { Button, Panel } from '@lace-cloud/ui';\nimport Identifier from '../Identifier';\nimport './EdgeInspectorPanel.css';\n\n// `onDelete` is present exactly when deleting the connection is an action\n// the canvas can take: its presence is the one decision whether the delete\n// button and its hint are drawn.\ntype Props = {\n source: string;\n target: string;\n sourceOutput: string;\n targetInput: string;\n onDelete?: () => void;\n onClose: () => void;\n};\n\nexport default function EdgeInspectorPanel({\n source,\n target,\n sourceOutput,\n targetInput,\n onDelete,\n onClose,\n}: Props) {\n const title = (\n <div>\n <div className=\"lace-edge-panel__title-eyebrow\">Connection</div>\n <div className=\"lace-edge-panel__title\">\n <Identifier text={source} /> → <Identifier text={target} />\n </div>\n </div>\n );\n\n const footer = onDelete ? (\n <Button rung variant=\"danger\" fullWidth onClick={onDelete}>\n Delete connection\n </Button>\n ) : undefined;\n\n return (\n <Panel title={title} footer={footer} onClose={onClose}>\n <div className=\"lace-edge-panel__section-label\">Wiring</div>\n <div className=\"lace-edge-panel__wiring\">\n <Identifier text={sourceOutput ? `${source}.outputs.${sourceOutput}` : callText(source)} />\n <div className=\"lace-edge-panel__wiring-arrow\">↓</div>\n <Identifier text={`${target}.inputs.${targetInput}`} />\n </div>\n {onDelete && (\n <div className=\"lace-edge-panel__hint\">\n Delete or press Backspace with the edge selected to remove this connection. Create new\n edges by dragging between the pins on each node's edge.\n </div>\n )}\n </Panel>\n );\n}\n","// The two state chips beside Generate (`section: 'write'`): \"Unsaved\"\n// in the warning tone, \"Not generated\" neutral, nothing when the IR is saved\n// and generated. Quiet chips, not banners — the conflict and source-refused\n// facts get the banner treatment. Both are `slot: 'toolbar'` panels, visible\n// under the source-refused lock too (requiredPorts `editor`, requiredContext\n// `root`, no `editable` requirement); each resolves only while the fact it\n// states holds (its other `requiredContext` keys).\nimport { Badge } from '@lace-cloud/ui';\nimport type { Panel } from '../../contributions';\n\nexport function UnsavedMarker() {\n return (\n <Badge variant=\"warning\" dot role=\"status\" className=\"lace-marker lace-marker--unsaved\">\n Unsaved\n </Badge>\n );\n}\n\nexport const unsavedMarker: Panel = {\n id: 'unsaved-marker',\n title: 'Unsaved',\n slot: 'toolbar',\n section: 'write',\n requiredPorts: ['editor'],\n requiredContext: ['root', 'unsaved'],\n Component: UnsavedMarker,\n};\n\nexport function UngeneratedMarker() {\n return (\n <Badge variant=\"neutral\" role=\"status\" className=\"lace-marker lace-marker--ungenerated\">\n Not generated\n </Badge>\n );\n}\n\n// While a Generate runs the chip says nothing (`generateIdle`): Generate\n// itself shows it in flight (`busy`), and the engine re-bases the session as\n// soon as it has written the tree (`ungenerated: false`) and only then\n// certifies it, so \"Not generated\" clearing mid-run would announce an\n// outcome the engine has not reached. The chip shows the outcome once the\n// engine has answered.\nexport const ungeneratedMarker: Panel = {\n id: 'ungenerated-marker',\n title: 'Not generated',\n slot: 'toolbar',\n section: 'write',\n requiredPorts: ['editor'],\n requiredContext: ['root', 'ungenerated', 'generateIdle'],\n Component: UngeneratedMarker,\n};\n","// The module-config inspector panel: a Panel wrapper around\n// `components/panels/ModuleConfigPanel`, which reads `editable`/`bundle`/\n// `runner` straight off `useCanvas()` and gates every mutating control on\n// `editable` itself — this file only derives the component's\n// `instance_id`/`onClose` props from `ctx.selection` and `setSelection`,\n// the one selection surface `useCanvas()` exposes.\nimport { createElement } from 'react';\nimport ModuleConfigPanelComponent from '../../components/panels/ModuleConfigPanel';\nimport type { Panel, PanelProps } from '../../contributions';\nimport { useCanvas } from '../../state/canvas-context';\n\nfunction ModuleConfigPanel({ ctx }: PanelProps) {\n const { setSelection } = useCanvas();\n const instanceId = ctx.selection.nodes[0];\n if (!instanceId) return null;\n\n return createElement(ModuleConfigPanelComponent, {\n instance_id: instanceId,\n onClose: () => setSelection({ nodes: [], edge: null }),\n });\n}\n\nexport const moduleConfigPanel: Panel = {\n id: 'module-config',\n title: 'Module',\n slot: 'drawer',\n requiredPorts: [],\n requiredContext: ['selection.node'],\n Component: ModuleConfigPanel,\n};\n\nexport default ModuleConfigPanel;\n","import { deriveNodeConfig, instanceAddress } from '@lace-cloud/proto';\nimport { Button, IconButton, Input, ModeToggle, Panel, Textarea } from '@lace-cloud/ui';\nimport type React from 'react';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { assertNever } from '../../exhaustive';\nimport type { Action } from '../../generated/service';\nimport { InputMode } from '../../generated/service';\nimport { useUpdateState } from '../../hooks/useUpdateState';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { NodeConfig, RenderInput, RenderOutput } from '../../types/render';\nimport AccordionSection from '../AccordionSection';\nimport Identifier from '../Identifier';\nimport { CanvasIcon } from '../icons';\nimport './ModuleConfigPanel.css';\nimport './panels-shared.css';\nimport UpdateButton from '../UpdateButton';\nimport ModuleDetails from './ModuleDetails';\n\n// ── Binding mode type ──\n\ntype BindingMode = 'empty' | 'literal' | 'variable' | 'expression' | 'wired';\n\nconst MODE_ITEMS: { value: BindingMode; label: string }[] = [\n { value: 'literal', label: 'Lit' },\n { value: 'variable', label: 'Var' },\n { value: 'expression', label: 'Expr' },\n { value: 'wired', label: 'Wired' },\n];\n\nfunction toInputMode(mode: BindingMode): InputMode {\n switch (mode) {\n case 'empty':\n return InputMode.INPUT_MODE_EMPTY;\n case 'literal':\n return InputMode.INPUT_MODE_LITERAL;\n case 'variable':\n return InputMode.INPUT_MODE_VARIABLE;\n case 'expression':\n return InputMode.INPUT_MODE_EXPRESSION;\n case 'wired':\n return InputMode.INPUT_MODE_WIRED;\n default:\n return assertNever(mode);\n }\n}\n\n// ── Props ──\n\ntype Props = {\n instance_id: string;\n onClose: () => void;\n onModified?: (instanceId: string) => void;\n};\n\n// ── Component ──\n\nexport default function ModuleConfigPanel({ instance_id, onClose, onModified }: Props) {\n const { editable, bundle, runner } = useCanvas();\n // Derived straight from the Bundle the canvas already has. No RPC\n // needed for either mode; only mutations go through `editor`.\n const config = useMemo<NodeConfig | null>(\n () => deriveNodeConfig(bundle, instance_id),\n [bundle, instance_id],\n );\n\n type InputState = {\n modes: Record<string, BindingMode>;\n values: Record<string, unknown>;\n variables: Record<string, string>;\n expressions: Record<string, string>;\n };\n const [inputState, setInputState] = useState<InputState>({\n modes: {},\n values: {},\n variables: {},\n expressions: {},\n });\n\n const {\n modes: localModes,\n values: localValues,\n variables: localVariables,\n expressions: localExpressions,\n } = inputState;\n\n // Memoized so callers using these in dep arrays (switchMode etc.)\n // get a stable reference. setInputState itself is React-stable.\n const setLocalModes = useCallback(\n (fn: (prev: Record<string, BindingMode>) => Record<string, BindingMode>) =>\n setInputState((s) => ({ ...s, modes: fn(s.modes) })),\n [],\n );\n const setLocalValues = useCallback(\n (fn: (prev: Record<string, unknown>) => Record<string, unknown>) =>\n setInputState((s) => ({ ...s, values: fn(s.values) })),\n [],\n );\n const setLocalVariables = useCallback(\n (fn: (prev: Record<string, string>) => Record<string, string>) =>\n setInputState((s) => ({ ...s, variables: fn(s.variables) })),\n [],\n );\n const setLocalExpressions = useCallback(\n (fn: (prev: Record<string, string>) => Record<string, string>) =>\n setInputState((s) => ({ ...s, expressions: fn(s.expressions) })),\n [],\n );\n\n const [localDependsOn, setLocalDependsOn] = useState<Set<string>>(new Set());\n // The module call's `providers = {}` map, held as ordered rows so the user\n // can edit both the child-local name (key) and the root reference (value).\n const [localProviders, setLocalProviders] = useState<Array<{ key: string; value: string }>>([]);\n // The call's `count` and `for_each`, as text.\n const [localRepetition, setLocalRepetition] = useState({ count: '', for_each: '' });\n\n // `config`'s identity is the re-seed trigger — a new Bundle (after a\n // save, a tool call, an undo) derives a new `config`, so local edit\n // state resyncs even though instance_id hasn't changed. Any in-progress\n // edit the user hasn't saved yet is discarded.\n useEffect(() => {\n if (!config) return;\n\n const modes: Record<string, BindingMode> = {};\n const values: Record<string, unknown> = {};\n const variables: Record<string, string> = {};\n const expressions: Record<string, string> = {};\n\n for (const input of config.inputs) {\n modes[input.name] = input.mode;\n if (input.value !== undefined) values[input.name] = input.value;\n if (input.variable) variables[input.name] = input.variable;\n if (input.expression) expressions[input.name] = input.expression;\n }\n\n setInputState({ modes, values, variables, expressions });\n setLocalDependsOn(new Set(config.depends_on));\n setLocalProviders(\n Object.entries(config.providers ?? {}).map(([key, value]) => ({ key, value })),\n );\n setLocalRepetition({ count: config.count, for_each: config.for_each });\n }, [config]);\n\n const switchMode = useCallback(\n (name: string, mode: BindingMode, input: RenderInput) => {\n setLocalModes((prev) => ({ ...prev, [name]: mode }));\n switch (mode) {\n case 'literal':\n setLocalValues((prev) => ({ ...prev, [name]: input.default_value ?? null }));\n break;\n case 'variable':\n setLocalVariables((prev) => ({ ...prev, [name]: '' }));\n break;\n case 'expression':\n setLocalExpressions((prev) => ({ ...prev, [name]: '' }));\n break;\n case 'empty':\n setLocalValues((prev) => {\n const next = { ...prev };\n delete next[name];\n return next;\n });\n break;\n case 'wired':\n // Cannot switch to wired manually.\n break;\n default:\n assertNever(mode);\n }\n },\n [setLocalModes, setLocalValues, setLocalVariables, setLocalExpressions],\n );\n\n const { requiredInputs, optionalInputs } = useMemo(\n () => ({\n requiredInputs: (config?.inputs ?? []).filter((i) => i.required),\n optionalInputs: (config?.inputs ?? []).filter((i) => !i.required),\n }),\n [config?.inputs],\n );\n\n // The instance this panel edits, as the engine addresses it: the module\n // whose scope owns it and its own id there.\n const address = useMemo(() => instanceAddress(bundle, instance_id), [bundle, instance_id]);\n\n // Every field this panel edits of the call — inputs, depends-on,\n // providers, repetition — lands in ONE `apply` batch (one undo entry), routed through `runner.apply`'s\n // shared notify-on-failure path, so a rejected write is read from the one\n // `ApplyResult` rather than assumed to have succeeded. Throwing on a\n // failed apply (rather than a silent return) is what lets `useUpdateState`\n // (below) show \"Update failed\" instead of reading back \"Updated!\" on a\n // write the engine refused.\n const { status: updateStatus, handleUpdate } = useUpdateState(async () => {\n if (!config || !editable) return;\n\n const actions: Action[] = [];\n\n for (const input of config.inputs) {\n const mode = localModes[input.name] ?? input.mode;\n if (mode === 'wired') continue;\n\n actions.push({\n update_input: {\n scope: address.scope,\n instance_id: address.id,\n input_name: input.name,\n mode: toInputMode(mode),\n value: mode === 'literal' ? localValues[input.name] : undefined,\n variable: mode === 'variable' ? (localVariables[input.name] ?? '') : '',\n expression: mode === 'expression' ? (localExpressions[input.name] ?? '') : '',\n },\n });\n }\n\n actions.push({\n set_depends_on: {\n scope: address.scope,\n instance_id: address.id,\n depends_on: [...localDependsOn],\n },\n });\n\n const providersRecord: Record<string, string> = {};\n for (const { key, value } of localProviders) {\n const name = key.trim();\n if (name) providersRecord[name] = value.trim();\n }\n actions.push({\n set_use_providers: {\n scope: address.scope,\n instance_id: address.id,\n providers: providersRecord,\n },\n });\n\n if (localRepetition.count !== config.count || localRepetition.for_each !== config.for_each) {\n actions.push({\n set_meta_arguments: {\n scope: address.scope,\n instance_id: address.id,\n count: localRepetition.count,\n for_each: localRepetition.for_each,\n provider: '',\n },\n });\n }\n\n const result = await runner.apply(actions);\n if (!result?.success) throw new Error('apply failed');\n\n const requiredToCheck = config.inputs.filter((i) => i.required);\n const hasFilledRequired =\n requiredToCheck.length === 0 ||\n requiredToCheck.some((input) => {\n const mode = localModes[input.name] ?? input.mode;\n if (mode === 'wired') return true;\n if (mode === 'literal') {\n const v = localValues[input.name];\n return v !== undefined && v !== null && v !== '';\n }\n if (mode === 'variable') {\n return (localVariables[input.name] ?? '').trim().length > 0;\n }\n if (mode === 'expression') {\n return (localExpressions[input.name] ?? '').trim().length > 0;\n }\n return false;\n });\n\n if (hasFilledRequired) {\n onModified?.(instance_id);\n }\n onClose();\n });\n\n const handleDisconnect = async (inputName: string) => {\n if (!editable) return;\n const result = await runner.apply([\n { disconnect: { scope: address.scope, target: address.id, input_name: inputName } },\n ]);\n // A rejected disconnect (a graph error, the engine gone) leaves the\n // input wired on the server; `runner.apply` already routed the failure\n // to `presenter.notify`, so setting local state to `empty` here too\n // would show a disconnected input the Subscribe stream is about to\n // contradict the moment its next frame lands.\n if (!result?.success) return;\n // The Subscribe stream pushes the post-disconnect Bundle; `config`\n // (derived from it) and the config-keyed re-seed effect above pick up\n // the now-empty mode without a manual re-query.\n setLocalModes((prev) => ({ ...prev, [inputName]: 'empty' }));\n };\n\n function renderModeSelector(input: RenderInput): React.ReactNode {\n const currentMode = localModes[input.name] ?? input.mode;\n const isWired = currentMode === 'wired';\n // Wired is always disabled (set by connect/disconnect). When the\n // current mode is wired, Lit/Var/Expr are also disabled so the user\n // can't silently overwrite a live binding. In read-only, every\n // item disables.\n const items = MODE_ITEMS.map((m) => ({\n ...m,\n disabled: !editable || m.value === 'wired' || isWired,\n }));\n return (\n <ModeToggle<BindingMode>\n value={currentMode}\n onChange={(next) => switchMode(input.name, next, input)}\n items={items}\n aria-label={`${input.name} binding mode`}\n />\n );\n }\n\n function renderInputField(input: RenderInput): React.ReactNode {\n const currentMode = localModes[input.name] ?? input.mode;\n\n return (\n <div key={input.name} className=\"lace-panel-field\">\n <label className=\"lace-panel-row-label\">\n <Identifier text={input.name} />\n {input.required && <span className=\"lace-mcp__required-star\">*</span>}\n </label>\n\n {renderModeSelector(input)}\n\n <div className=\"lace-panel-row-content\">\n {currentMode === 'wired' && renderWiredEditor(input)}\n {currentMode === 'variable' && renderVariableEditor(input)}\n {currentMode === 'expression' && renderExpressionEditor(input)}\n {currentMode === 'literal' && renderLiteralEditor(input)}\n </div>\n\n {input.description && (\n <div className=\"lace-panel-field__description\">{input.description}</div>\n )}\n </div>\n );\n }\n\n function renderWiredEditor(input: RenderInput): React.ReactNode {\n const label = input.wired_source ?? 'Not wired';\n return (\n <div className=\"lace-mcp__wired-row\">\n <div className=\"lace-mcp__wired-input\">\n <Input value={label} readOnly fullWidth mono />\n </div>\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label=\"Disconnect this input\"\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => handleDisconnect(input.name)}\n />\n )}\n </div>\n );\n }\n\n function renderVariableEditor(input: RenderInput): React.ReactNode {\n const currentVar = localVariables[input.name] ?? input.variable ?? '';\n return (\n <Input\n value={currentVar}\n onChange={(e) => {\n const raw = e.target.value;\n const name = raw.startsWith('var.') ? raw.slice(4) : raw;\n setLocalVariables((prev) => ({ ...prev, [input.name]: name }));\n }}\n placeholder=\"e.g. region\"\n fullWidth\n mono\n readOnly={!editable}\n />\n );\n }\n\n function renderExpressionEditor(input: RenderInput): React.ReactNode {\n const currentExpr = localExpressions[input.name] ?? input.expression ?? '';\n return (\n <Textarea\n value={currentExpr}\n onChange={(e) => setLocalExpressions((prev) => ({ ...prev, [input.name]: e.target.value }))}\n rows={3}\n placeholder='e.g. join(\"-\", [var.prefix, var.name])'\n fullWidth\n mono\n readOnly={!editable}\n />\n );\n }\n\n function renderLiteralEditor(input: RenderInput): React.ReactNode {\n const value = localValues[input.name] ?? input.value ?? input.default_value ?? null;\n const type = input.type || 'string';\n\n const updateValue = (val: unknown) => {\n setLocalValues((prev) => ({ ...prev, [input.name]: val }));\n };\n\n if (type === 'bool') {\n return (\n <select\n className=\"lace-mcp__select\"\n value={String(value ?? false)}\n onChange={(e) => updateValue(e.target.value === 'true')}\n disabled={!editable}\n >\n <option value=\"true\">True</option>\n <option value=\"false\">False</option>\n </select>\n );\n }\n\n if (type === 'number') {\n return (\n <Input\n type=\"number\"\n value={String(value ?? '')}\n onChange={(e) => updateValue(e.target.value === '' ? '' : Number(e.target.value))}\n fullWidth\n readOnly={!editable}\n />\n );\n }\n\n if (\n type.startsWith('list(') ||\n type.startsWith('map(') ||\n type.startsWith('set(') ||\n type === 'object' ||\n type.startsWith('object(')\n ) {\n const jsonStr = typeof value === 'string' ? value : JSON.stringify(value ?? null, null, 2);\n return (\n <Textarea\n value={jsonStr}\n onChange={(e) => {\n try {\n updateValue(JSON.parse(e.target.value));\n } catch {\n updateValue(e.target.value);\n }\n }}\n rows={4}\n fullWidth\n mono\n readOnly={!editable}\n />\n );\n }\n\n return (\n <Input\n value={String(value ?? '')}\n onChange={(e) => {\n let v = e.target.value;\n if (\n v.length >= 2 &&\n ((v[0] === '\"' && v[v.length - 1] === '\"') || (v[0] === \"'\" && v[v.length - 1] === \"'\"))\n ) {\n v = v.slice(1, -1);\n }\n updateValue(v);\n }}\n fullWidth\n readOnly={!editable}\n />\n );\n }\n\n if (!config) {\n return (\n <Panel title=\"Error\" onClose={onClose}>\n <div className=\"lace-mcp__error-title\">\n Failed to load configuration for \"{instance_id}\":\n </div>\n <div className=\"lace-mcp__error-detail\">Instance not found in the current Bundle.</div>\n </Panel>\n );\n }\n\n const dependsOnCount = localDependsOn.size;\n\n const title = (\n <div className=\"lace-mcp__title\">\n <div className=\"lace-mcp__title-eyebrow\">Module</div>\n <h3 className=\"lace-mcp__title-id\">\n <Identifier text={instance_id} />\n </h3>\n </div>\n );\n\n const footer = editable ? (\n <UpdateButton status={updateStatus} label=\"Update configuration\" onClick={handleUpdate} />\n ) : undefined;\n\n return (\n <Panel title={title} footer={footer} flush onClose={onClose}>\n {requiredInputs.length > 0 && (\n <AccordionSection title=\"Required Inputs\" defaultOpen badge={`(${requiredInputs.length})`}>\n {requiredInputs.map(renderInputField)}\n </AccordionSection>\n )}\n\n {optionalInputs.length > 0 && (\n <AccordionSection title=\"Optional Inputs\" defaultOpen badge={`(${optionalInputs.length})`}>\n {optionalInputs.map(renderInputField)}\n </AccordionSection>\n )}\n\n {config.sibling_ids.length > 0 && (\n <AccordionSection\n title=\"Depends On\"\n badge={dependsOnCount > 0 ? `(${dependsOnCount})` : undefined}\n >\n <div className=\"lace-mcp__depends-hint\">\n Select sibling instances this module depends on.\n </div>\n {config.sibling_ids.map((sibId) => {\n const depKey = `module.${sibId}`;\n return (\n <label key={sibId} className=\"lace-mcp__depends-item\">\n <input\n type=\"checkbox\"\n className=\"lace-mcp__depends-checkbox\"\n checked={localDependsOn.has(depKey)}\n disabled={!editable}\n onChange={(e) => {\n setLocalDependsOn((prev) => {\n const next = new Set(prev);\n if (e.target.checked) next.add(depKey);\n else next.delete(depKey);\n return next;\n });\n }}\n />\n <Identifier className=\"lace-mcp__depends-label\" text={depKey} />\n </label>\n );\n })}\n </AccordionSection>\n )}\n\n {(localProviders.length > 0 || editable) && (\n <AccordionSection\n title=\"Providers\"\n badge={localProviders.length > 0 ? `(${localProviders.length})` : undefined}\n >\n <div className=\"lace-mcp__depends-hint\">\n Map each child-local provider name to the root provider reference passed down (e.g.{' '}\n <code>aws</code> → <code>aws.west</code>).\n </div>\n {localProviders.map((row, i) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: rows are positional and freely editable\n <div key={i} className=\"lace-mcp__provider-row\">\n <Input\n value={row.key}\n onChange={(e) =>\n setLocalProviders((prev) =>\n prev.map((r, j) => (j === i ? { ...r, key: e.target.value } : r)),\n )\n }\n placeholder=\"child local (e.g. aws)\"\n mono\n readOnly={!editable}\n />\n <span className=\"lace-mcp__provider-arrow\">=</span>\n <Input\n value={row.value}\n onChange={(e) =>\n setLocalProviders((prev) =>\n prev.map((r, j) => (j === i ? { ...r, value: e.target.value } : r)),\n )\n }\n placeholder=\"root ref (e.g. aws.west)\"\n mono\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label=\"Remove this provider mapping\"\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => setLocalProviders((prev) => prev.filter((_, j) => j !== i))}\n />\n )}\n </div>\n ))}\n {editable && (\n <Button\n variant=\"secondary\"\n size=\"sm\"\n onClick={() => setLocalProviders((prev) => [...prev, { key: '', value: '' }])}\n >\n Add provider mapping\n </Button>\n )}\n </AccordionSection>\n )}\n\n {(localRepetition.count || localRepetition.for_each || editable) && (\n <AccordionSection title=\"Repetition\">\n <div className=\"lace-mcp__depends-hint\">\n The call's <code>count</code> or <code>for_each</code>: one module, called once per\n instance.\n </div>\n <Input\n label=\"count\"\n value={localRepetition.count}\n onChange={(e) => setLocalRepetition((prev) => ({ ...prev, count: e.target.value }))}\n placeholder=\"e.g. 2 or var.instances\"\n fullWidth\n mono\n readOnly={!editable}\n />\n <Input\n label=\"for_each\"\n value={localRepetition.for_each}\n onChange={(e) => setLocalRepetition((prev) => ({ ...prev, for_each: e.target.value }))}\n placeholder=\"e.g. var.regions\"\n fullWidth\n mono\n readOnly={!editable}\n />\n </AccordionSection>\n )}\n\n {config.outputs.length > 0 && (\n <AccordionSection title=\"Outputs\" badge={`(${config.outputs.length})`}>\n {config.outputs.map((o: RenderOutput) => (\n <div key={o.name} className=\"lace-mcp__output-card\">\n <div className=\"lace-mcp__output-header\">\n <Identifier className=\"lace-mcp__output-name\" text={o.name} />\n <Identifier className=\"lace-mcp__output-type\" text={o.type ?? ''} />\n </div>\n {o.description && <div className=\"lace-mcp__output-description\">{o.description}</div>}\n {o.sensitive && <div className=\"lace-mcp__output-sensitive\">sensitive</div>}\n </div>\n ))}\n </AccordionSection>\n )}\n\n {config.module_key && (\n <>\n <div className=\"lace-mcp__module-heading\">\n <div className=\"lace-mcp__title-eyebrow\">Called module</div>\n <Identifier text={config.module_key} />\n </div>\n <ModuleDetails key={config.module_key} moduleKey={config.module_key} />\n </>\n )}\n </Panel>\n );\n}\n","/** Compile-time exhaustiveness guard. See apps/api/src/lib/helpers.ts. */\nexport function assertNever(value: never): never {\n throw new Error(`Unhandled closed-enum branch: ${JSON.stringify(value)}`);\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\n\nexport type UpdateStatus = 'idle' | 'updating' | 'updated' | 'error';\n\n/**\n * Shared update state machine for settings panels — the panel's own commit\n * button writes the working IR (`env.apply`), a distinct operation from the\n * canvas's Save (which writes `state.lace`), hence \"Update\", not \"Save\".\n *\n * Handles: idle → updating → updated (1.5s) → idle\n * → error (2s) → idle\n *\n * A second update fired before the first resolves runs in parallel; this\n * is intentional — settings panels coalesce at the form level, not here.\n * A second update fired during the updated → idle window cancels the\n * pending timer so the new flow doesn't get yanked back to idle\n * mid-stream.\n */\nexport function useUpdateState(updateFn: () => Promise<void>) {\n const [status, setStatus] = useState<UpdateStatus>('idle');\n const mountedRef = useRef(true);\n const resetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const safeSetStatus = useCallback((next: UpdateStatus) => {\n if (mountedRef.current) setStatus(next);\n }, []);\n\n const scheduleReset = useCallback(\n (delay: number) => {\n if (resetTimerRef.current !== null) clearTimeout(resetTimerRef.current);\n resetTimerRef.current = setTimeout(() => {\n resetTimerRef.current = null;\n safeSetStatus('idle');\n }, delay);\n },\n [safeSetStatus],\n );\n\n const handleUpdate = useCallback(async () => {\n safeSetStatus('updating');\n try {\n await updateFn();\n safeSetStatus('updated');\n scheduleReset(1500);\n } catch {\n safeSetStatus('error');\n scheduleReset(2000);\n }\n }, [updateFn, safeSetStatus, scheduleReset]);\n\n useEffect(() => {\n return () => {\n mountedRef.current = false;\n if (resetTimerRef.current !== null) {\n clearTimeout(resetTimerRef.current);\n resetTimerRef.current = null;\n }\n };\n }, []);\n\n return { status, handleUpdate };\n}\n","import type React from 'react';\nimport { useState } from 'react';\nimport './AccordionSection.css';\nimport { CanvasIcon } from './icons';\n\ntype Props = {\n title: string;\n defaultOpen?: boolean;\n badge?: string;\n children: React.ReactNode;\n};\n\nexport default function AccordionSection({ title, defaultOpen = false, badge, children }: Props) {\n const [open, setOpen] = useState(defaultOpen);\n\n return (\n <div className={`lace-accordion${open ? ' lace-accordion--open' : ''}`}>\n <button\n type=\"button\"\n className=\"lace-accordion__header\"\n onClick={() => setOpen((v) => !v)}\n aria-expanded={open}\n >\n <span className=\"lace-accordion__chevron\">\n <CanvasIcon name=\"chevron-right\" />\n </span>\n <span className=\"lace-accordion__title\">{title}</span>\n {badge && <span className=\"lace-accordion__badge\">{badge}</span>}\n </button>\n\n <div className=\"lace-accordion__body\">\n <div className=\"lace-accordion__body-inner\">\n <div className=\"lace-accordion__body-content\">{children}</div>\n </div>\n </div>\n </div>\n );\n}\n","import { Button, type ButtonVariant } from '@lace-cloud/ui';\nimport type { UpdateStatus } from '../hooks/useUpdateState';\nimport './UpdateButton.css';\n\ntype Props = {\n status: UpdateStatus;\n label: string;\n onClick: () => void;\n disabled?: boolean;\n disabledTitle?: string;\n};\n\n// Status → UI-primitive mapping. `idle` uses the caller-supplied label; the\n// other statuses carry their own user-facing text since the status itself\n// is the message (updating, updated, error). `updating` is represented by\n// loading state on the primary Button so the spinner renders consistently\n// with any other loading button in the app.\nconst variantByStatus: Record<UpdateStatus, ButtonVariant> = {\n idle: 'primary',\n updating: 'primary',\n updated: 'success',\n error: 'danger',\n};\n\nconst labelByStatus: Record<Exclude<UpdateStatus, 'idle'>, string> = {\n updating: 'Updating…',\n updated: 'Updated!',\n error: 'Update failed — try again',\n};\n\nexport default function UpdateButton({ status, label, onClick, disabled, disabledTitle }: Props) {\n // Pinned to the foot of the panel's scroll while its section is in view:\n // a long section's commit is never scrolled out of reach.\n return (\n <div className=\"lace-commit-foot\">\n <Button\n rung\n variant={variantByStatus[status]}\n fullWidth\n loading={status === 'updating'}\n disabled={disabled || status === 'updated'}\n onClick={onClick}\n tooltip={disabled ? disabledTitle : undefined}\n >\n {status === 'idle' ? label : labelByStatus[status]}\n </Button>\n </div>\n );\n}\n","// One module's details, every construct the IR holds of it beside its\n// calls (`deriveSettingsConfig`): a definition's resources and data\n// sources, interface, moved and import blocks, locals, providers and\n// terraform block, each section editing that module through actions that\n// name it (`module-actions.ts`); a reference's source, pin and the\n// interface the IR holds for it, read-only. The settings panel shows the\n// entry's, and a call's panel the module the call reads, so a definition\n// many calls read is edited once for all of them. Every definition shows\n// its resources and data sources, since a data source is a detail of any\n// module; it takes a managed resource only where lace shape lets it hold\n// one.\nimport { deriveSettingsConfig } from '@lace-cloud/proto';\nimport { Input } from '@lace-cloud/ui';\nimport { useMemo, useState } from 'react';\nimport type { Action } from '../../generated/service';\nimport { useUpdateState } from '../../hooks/useUpdateState';\nimport type { ApplyResult } from '../../ports';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { BlockConfig, SettingsConfig } from '../../types/render';\nimport { typedName } from '../../utils/typed-name';\nimport AccordionSection from '../AccordionSection';\nimport Identifier from '../Identifier';\nimport UpdateButton from '../UpdateButton';\nimport BlockEditor from './BlockEditor';\nimport { LocalsContent } from './LocalsPanel';\nimport { ModuleInterfaceContent } from './ModuleInterfacePanel';\nimport {\n addResource,\n removeResource,\n resourceActions,\n setDirectives,\n setLocals,\n setOutputs,\n setProviders,\n setTerraform,\n setVariables,\n} from './module-actions';\nimport './panels-shared.css';\nimport { ProvidersContent } from './ProvidersPanel';\nimport { ResourcesContent } from './ResourcesPanel';\nimport { TerraformConfigContent } from './TerraformConfigPanel';\n\n// A section's own update-state machine (`useUpdateState`, driving each\n// `UpdateButton`) reads success from whether its `onSave` promise rejects —\n// so a rejected `ApplyResult` has to reject here too, or the button reads\n// back \"Updated!\" on a write the engine refused. `runner.apply` already\n// routes the failure to `presenter.notify` once; this only turns that same\n// result into the rejection the update-state machine is watching for.\nfunction assertApplied(result: ApplyResult | undefined): asserts result is ApplyResult {\n if (!result?.success) throw new Error('apply failed');\n}\n\n// A section's key: a new frame that changes what the section shows\n// re-seeds its rows, so a change made in the tf shows in an open panel.\nconst keyOf = (value: unknown) => JSON.stringify(value);\n\ntype Props = {\n moduleKey: string;\n // Sections that open by default.\n open?: readonly string[];\n};\n\nexport default function ModuleDetails({ moduleKey, open = [] }: Props) {\n const { bundle, runner, editable } = useCanvas();\n const settings = useMemo(() => deriveSettingsConfig(bundle, moduleKey), [bundle, moduleKey]);\n if (!settings) return null;\n if (settings.reference) return <ReferenceDetails settings={settings} />;\n\n const apply = async (actions: Action[]) => {\n if (!editable) return;\n assertApplied(await runner.apply(actions));\n };\n return (\n <>\n <AccordionSection\n title=\"Resources\"\n defaultOpen={open.includes('Resources')}\n badge={`(${settings.resources.length})`}\n >\n <ResourcesContent\n resources={settings.resources}\n dependencyOptions={settings.dependency_options}\n managed={settings.holds_managed_resources}\n onUpdate={(before, after) => apply(resourceActions(moduleKey, before, after))}\n onRemove={(id) => apply([removeResource(moduleKey, id)])}\n onAdd={(kind, type, name) => apply([addResource(moduleKey, kind, type, name)])}\n />\n </AccordionSection>\n\n <AccordionSection title=\"Interface\" defaultOpen={open.includes('Interface')}>\n <ModuleInterfaceContent\n key={keyOf([settings.variables, settings.outputs, settings.call_outputs])}\n settings={settings}\n onSave={(variables, outputs) =>\n apply([setVariables(moduleKey, variables), setOutputs(moduleKey, outputs)])\n }\n />\n </AccordionSection>\n\n <AccordionSection\n title=\"Moved and import blocks\"\n defaultOpen={open.includes('Moved and import blocks')}\n badge={settings.directives.length > 0 ? `(${settings.directives.length})` : undefined}\n >\n <DirectivesContent\n key={keyOf(settings.directives)}\n directives={settings.directives}\n onSave={(blocks) => apply([setDirectives(moduleKey, blocks)])}\n />\n </AccordionSection>\n\n <AccordionSection title=\"Locals\" defaultOpen={open.includes('Locals')}>\n <LocalsContent\n key={keyOf(settings.locals)}\n locals={settings.locals}\n onSave={(locals) => apply([setLocals(moduleKey, locals)])}\n />\n </AccordionSection>\n\n <AccordionSection title=\"Providers\" defaultOpen={open.includes('Providers')}>\n <ProvidersContent\n key={keyOf(settings.providers)}\n providers={settings.providers}\n onSave={(providers) => apply([setProviders(moduleKey, providers)])}\n />\n </AccordionSection>\n\n <AccordionSection title=\"Terraform Config\" defaultOpen={open.includes('Terraform Config')}>\n <TerraformConfigContent\n key={keyOf(settings.terraform)}\n terraform={settings.terraform}\n onSave={(terraform) => apply([setTerraform(moduleKey, terraform)])}\n />\n </AccordionSection>\n </>\n );\n}\n\n// A module's moved and import blocks, set whole by one Update.\nfunction DirectivesContent({\n directives,\n onSave,\n}: {\n directives: BlockConfig[];\n onSave: (blocks: BlockConfig[]) => Promise<void>;\n}) {\n const { editable } = useCanvas();\n const [blocks, setBlocks] = useState(directives);\n const { status, handleUpdate } = useUpdateState(() => onSave(blocks));\n return (\n <>\n {blocks.length === 0 && <div className=\"lace-panel-hint\">No moved or import blocks.</div>}\n <BlockEditor\n blocks={blocks}\n editable={editable}\n onChange={setBlocks}\n templates={[\n { type: 'moved', attributes: ['from', 'to'] },\n { type: 'import', attributes: ['to', 'id'] },\n ]}\n />\n {editable && (\n <UpdateButton\n status={status}\n label=\"Update moved and import blocks\"\n onClick={handleUpdate}\n />\n )}\n </>\n );\n}\n\n// A reference holds no content the IR reads: its panel shows where its\n// source points, the version its calls pin, and the interface a placement\n// certified, and edits nothing.\nfunction ReferenceDetails({ settings }: { settings: SettingsConfig }) {\n const reference = settings.reference;\n if (!reference) return null;\n return (\n <>\n <AccordionSection title=\"Source\" defaultOpen>\n <div className=\"lace-panel-hint\">\n A reference: Lace reads it where its source points and never edits it.\n </div>\n <div className=\"lace-panel-row-actions lace-panel-row-actions--stacked\">\n <Input label=\"Source\" value={reference.source} fullWidth mono readOnly />\n <Input label=\"Version\" value={reference.version} fullWidth mono readOnly />\n </div>\n </AccordionSection>\n <AccordionSection title=\"Interface\" defaultOpen>\n <h4 className=\"lace-panel-section-title\">Inputs</h4>\n {settings.variables.length === 0 && (\n <div className=\"lace-panel-hint\">The IR holds no interface for this reference.</div>\n )}\n {settings.variables.map((v) => (\n <div key={v.name} className=\"lace-panel-depends-item\">\n <Identifier text={`${typedName(v.name, v.type)}${v.required ? ' (required)' : ''}`} />\n </div>\n ))}\n <h4 className=\"lace-panel-section-title\">Outputs</h4>\n {settings.outputs.map((o) => (\n <div key={o.name} className=\"lace-panel-depends-item\">\n <Identifier text={typedName(o.name, o.type)} />\n </div>\n ))}\n </AccordionSection>\n </>\n );\n}\n","// BlockEditor shows and edits a list of blocks — a resource's or a provider\n// configuration's nested blocks, a module's moved and import blocks — each\n// attribute's value as the HCL text the render writes for it\n// (`BlockConfig`), which the engine reads back as the parse reads it. It is\n// controlled: the list is its parent's, every edit a new list through\n// `onChange`. Read-only, it shows the same rows with no control.\nimport { Button, IconButton, Input } from '@lace-cloud/ui';\nimport { useState } from 'react';\nimport type { BlockConfig } from '../../types/render';\nimport Identifier from '../Identifier';\nimport { CanvasIcon } from '../icons';\nimport './panels-shared.css';\n\n// A block a list offers to add: its type and the attributes it starts with.\ntype BlockTemplate = { type: string; attributes: string[] };\n\ntype Props = {\n blocks: BlockConfig[];\n onChange: (blocks: BlockConfig[]) => void;\n editable: boolean;\n // The blocks the list offers to add, one button each. Unset, the list\n // adds a block of the type (and label) the developer names.\n templates?: BlockTemplate[];\n};\n\nfunction replaceAt<T>(list: readonly T[], index: number, item: T): T[] {\n return list.map((x, i) => (i === index ? item : x));\n}\n\nfunction blockTitle(block: BlockConfig): string {\n return [block.type, ...block.labels.map((l) => `\"${l}\"`)].join(' ');\n}\n\nexport default function BlockEditor({ blocks, onChange, editable, templates }: Props) {\n return (\n <>\n {blocks.map((block, i) => (\n <BlockCard\n // biome-ignore lint/suspicious/noArrayIndexKey: blocks are positional; the render writes them in this order\n key={i}\n block={block}\n editable={editable}\n onChange={(next) => onChange(replaceAt(blocks, i, next))}\n onRemove={() => onChange(blocks.filter((_, j) => j !== i))}\n />\n ))}\n {editable &&\n (templates ? (\n <div className=\"lace-panel-row-actions\">\n {templates.map((t) => (\n <Button\n key={t.type}\n variant=\"secondary\"\n size=\"sm\"\n onClick={() =>\n onChange([\n ...blocks,\n {\n type: t.type,\n labels: [],\n attributes: t.attributes.map((name) => ({ name, value: '' })),\n blocks: [],\n },\n ])\n }\n >\n + Add {t.type} block\n </Button>\n ))}\n </div>\n ) : (\n <NewBlockRow\n onAdd={(type, label) =>\n onChange([\n ...blocks,\n { type, labels: label ? [label] : [], attributes: [], blocks: [] },\n ])\n }\n />\n ))}\n </>\n );\n}\n\nfunction NewBlockRow({ onAdd }: { onAdd: (type: string, label: string) => void }) {\n const [type, setType] = useState('');\n const [label, setLabel] = useState('');\n return (\n <div className=\"lace-panel-row-actions\">\n <Input\n value={type}\n onChange={(e) => setType(e.target.value)}\n placeholder=\"Block type (e.g. lifecycle)\"\n aria-label=\"New block type\"\n mono\n />\n <Input\n value={label}\n onChange={(e) => setLabel(e.target.value)}\n placeholder=\"Label (optional)\"\n aria-label=\"New block label\"\n mono\n />\n <Button\n variant=\"secondary\"\n size=\"sm\"\n disabled={!type.trim()}\n onClick={() => {\n onAdd(type.trim(), label.trim());\n setType('');\n setLabel('');\n }}\n >\n + Add block\n </Button>\n </div>\n );\n}\n\ntype CardProps = {\n block: BlockConfig;\n editable: boolean;\n onChange: (block: BlockConfig) => void;\n onRemove: () => void;\n};\n\nfunction BlockCard({ block, editable, onChange, onRemove }: CardProps) {\n const setAttribute = (index: number, field: 'name' | 'value', value: string) =>\n onChange({\n ...block,\n attributes: replaceAt(block.attributes, index, {\n ...block.attributes[index],\n [field]: value,\n }),\n });\n return (\n <div className=\"lace-panel-validation-block\">\n <div className=\"lace-panel-row-actions\">\n <Identifier className=\"lace-panel-row-card__name\" text={blockTitle(block)} />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label={`Remove the ${block.type} block`}\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={onRemove}\n />\n )}\n </div>\n {block.attributes.map((attribute, i) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: attributes are positional; the render keeps their order\n <div key={i} className=\"lace-panel-row-actions\">\n <Input\n value={attribute.name}\n onChange={(e) => setAttribute(i, 'name', e.target.value)}\n placeholder=\"Argument\"\n aria-label={`${block.type} argument name`}\n mono\n readOnly={!editable}\n />\n <Input\n value={attribute.value}\n onChange={(e) => setAttribute(i, 'value', e.target.value)}\n placeholder=\"Value\"\n aria-label={`${attribute.name || block.type} value`}\n mono\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label={`Remove ${attribute.name || 'the argument'}`}\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() =>\n onChange({ ...block, attributes: block.attributes.filter((_, j) => j !== i) })\n }\n />\n )}\n </div>\n ))}\n {editable && (\n <Button\n variant=\"secondary\"\n size=\"sm\"\n onClick={() =>\n onChange({ ...block, attributes: [...block.attributes, { name: '', value: '' }] })\n }\n >\n + Add argument\n </Button>\n )}\n {(block.blocks.length > 0 || editable) && (\n <BlockEditor\n blocks={block.blocks}\n editable={editable}\n onChange={(blocks) => onChange({ ...block, blocks })}\n />\n )}\n </div>\n );\n}\n","import { Button, IconButton, Input, Panel, Textarea } from '@lace-cloud/ui';\nimport { useCallback, useState } from 'react';\nimport { useUpdateState } from '../../hooks/useUpdateState';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { SettingsConfig } from '../../types/render';\nimport { findDuplicateIndices } from '../../utils/duplicates';\nimport { CanvasIcon } from '../icons';\nimport UpdateButton from '../UpdateButton';\nimport './panels-shared.css';\n\n// ── Types derived from SettingsConfig ──\n\ntype LocalEntry = SettingsConfig['locals'][number];\n\n// A local's value is the HCL text the render writes for it — a literal,\n// `var.<name>`, or any expression — which the engine reads back as the\n// parse reads it, so one text field edits every kind of value.\n\ntype LocalRow = LocalEntry & {\n // Stable per-row id, used as React key. Generated when the row is\n // created (toRows / addLocal), survives edits + reorders. NOT\n // persisted — fromRows strips it before sending to the engine.\n id: string;\n};\n\nfunction toRows(locals: LocalEntry[] | undefined): LocalRow[] {\n return (locals ?? []).map((l) => ({ id: crypto.randomUUID(), ...l }));\n}\n\nfunction fromRows(rows: LocalRow[]): LocalEntry[] {\n return rows.filter((r) => r.name.trim()).map((r) => ({ name: r.name.trim(), value: r.value }));\n}\n\n// ── Content-only component (used by ModuleDetails) ──\n\ntype ContentProps = {\n locals: LocalEntry[] | undefined;\n onSave: (locals: LocalEntry[]) => void | Promise<void>;\n};\n\nexport function LocalsContent({ locals, onSave }: ContentProps) {\n const { editable } = useCanvas();\n const [rows, setRows] = useState<LocalRow[]>(() => toRows(locals));\n\n const addLocal = useCallback(() => {\n setRows((prev) => [...prev, { id: crypto.randomUUID(), name: '', value: '' }]);\n }, []);\n\n const removeLocal = useCallback((index: number) => {\n setRows((prev) => prev.filter((_, i) => i !== index));\n }, []);\n\n const updateRow = useCallback((index: number, field: 'name' | 'value', value: string) => {\n setRows((prev) => prev.map((r, i) => (i === index ? { ...r, [field]: value } : r)));\n }, []);\n\n const nameDupes = findDuplicateIndices(rows, (r) => r.name);\n const hasErrors = nameDupes.size > 0;\n\n const { status: updateStatus, handleUpdate } = useUpdateState(\n useCallback(async () => {\n if (hasErrors) return;\n await onSave(fromRows(rows));\n }, [onSave, rows, hasErrors]),\n );\n\n return (\n <>\n {rows.map((row, i) => (\n <div key={row.id} className=\"lace-panel-row-card lace-panel-row-card--with-footer\">\n <div className=\"lace-panel-row-actions\">\n <Input\n value={row.name}\n onChange={(e) => updateRow(i, 'name', e.target.value)}\n placeholder=\"Local name\"\n aria-label=\"Local name\"\n fullWidth\n mono\n error={nameDupes.has(i)}\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label=\"Remove local\"\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => removeLocal(i)}\n />\n )}\n </div>\n {nameDupes.has(i) && <div className=\"lace-panel-row-error\">Duplicate local name</div>}\n\n <div className=\"lace-panel-row-content\">\n <Textarea\n value={row.value}\n onChange={(e) => updateRow(i, 'value', e.target.value)}\n placeholder='e.g. \"my-bucket\" or \"${var.environment}-logs\"'\n aria-label={`${row.name || 'Local'} value`}\n rows={3}\n fullWidth\n mono\n readOnly={!editable}\n />\n </div>\n </div>\n ))}\n\n {editable && (\n <>\n <Button variant=\"secondary\" size=\"sm\" onClick={addLocal}>\n + Add local\n </Button>\n\n <UpdateButton\n status={updateStatus}\n label=\"Update locals\"\n onClick={handleUpdate}\n disabled={hasErrors}\n disabledTitle=\"Fix errors before saving\"\n />\n </>\n )}\n </>\n );\n}\n\n// ── The standalone panel ──\n\ntype Props = {\n locals: LocalEntry[] | undefined;\n onSave: (locals: LocalEntry[]) => void | Promise<void>;\n onClose: () => void;\n};\n\nexport default function LocalsPanel({ locals, onSave, onClose }: Props) {\n return (\n <Panel title=\"Locals\" onClose={onClose}>\n <LocalsContent locals={locals} onSave={onSave} />\n </Panel>\n );\n}\n","/**\n * Find indices of items with duplicate keys (case-insensitive).\n * Returns a Set of all indices that participate in a duplicate group.\n */\nexport function findDuplicateIndices<T>(items: T[], keyFn: (item: T) => string): Set<number> {\n const seen = new Map<string, number>();\n const dupes = new Set<number>();\n items.forEach((item, i) => {\n const key = keyFn(item).trim().toLowerCase();\n if (!key) return;\n if (seen.has(key)) {\n dupes.add(i);\n dupes.add(seen.get(key)!);\n }\n seen.set(key, i);\n });\n return dupes;\n}\n","import { Button, IconButton, Input, Panel, Select, Textarea } from '@lace-cloud/ui';\nimport { useCallback, useState } from 'react';\nimport { useUpdateState } from '../../hooks/useUpdateState';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { SettingsConfig } from '../../types/render';\nimport { findDuplicateIndices } from '../../utils/duplicates';\nimport Identifier from '../Identifier';\nimport { CanvasIcon } from '../icons';\nimport UpdateButton from '../UpdateButton';\nimport './panels-shared.css';\n\n// Host-facing DTOs for the batch this panel's Update issues (its variables\n// and its outputs) — distinct from the wire InputDef/OutputDef (e.g.\n// `default` not `default_value`) because the panel edits them as flat rows\n// before ModuleDetails converts to the SetVariablesAction /\n// SetExportsAction shape.\nexport type VariableDef = {\n name: string;\n type: string;\n required: boolean;\n description?: string;\n default?: unknown;\n validation?: { condition: string; error_message: string }[];\n ephemeral?: boolean;\n sensitive?: boolean;\n nullable?: boolean;\n};\n\n// An output: its name, its value as the HCL text the render writes for it,\n// and what its definition carries beside the value.\nexport type OutputDefEntry = {\n name: string;\n value: string;\n description?: string;\n sensitive?: boolean;\n depends_on?: string[];\n};\n\n// The Interface section is a module's public surface: the variables its\n// callers set and the outputs they read.\n//\n// A variable's name is what its readers read, so an existing one is shown,\n// not renamed; its type, description, flags and validation are edited, and\n// its default (written by the source or the call that declared it) is\n// shown as the render writes it and kept as it is. A variable is added by\n// name and removed whole. An empty type is no declared type, as the IR\n// holds a variable with no type line: it is shown as such and set as such,\n// never filled in.\n//\n// An output is its name and its value: a resource's attribute, a call's\n// output, a literal, a variable or any expression, as text. The outputs the\n// module's calls offer are listed to expose one in a step.\n\ntype ValidationRow = { id: string; condition: string; error_message: string };\n\ntype VariableRow = {\n id: string;\n name: string;\n // A variable the panel added: its name is still the panel's to set.\n added: boolean;\n type: string;\n required: boolean;\n description: string;\n // Round-tripped as it is; `defaultText` shows it.\n default_value?: unknown;\n defaultText: string;\n validation: ValidationRow[];\n ephemeral: boolean;\n sensitive: boolean;\n // `nullable` — whether `null` is an allowed value. Defaults to true\n // (Terraform's default); unchecking authors an explicit `nullable = false`.\n nullable: boolean;\n};\n\ntype OutputRow = {\n id: string;\n name: string;\n value: string;\n description: string;\n sensitive: boolean;\n depends_on: string[];\n};\n\nfunction variablesToRows(variables: SettingsConfig['variables']): VariableRow[] {\n return variables.map((v) => ({\n id: crypto.randomUUID(),\n name: v.name,\n added: false,\n type: v.type,\n required: v.required,\n description: v.description ?? '',\n default_value: v.default_value,\n defaultText: v.default,\n validation: (v.validation ?? []).map((b) => ({\n id: crypto.randomUUID(),\n condition: b.condition,\n error_message: b.error_message,\n })),\n ephemeral: v.ephemeral ?? false,\n sensitive: v.sensitive ?? false,\n // Wire `nullable` is tri-state: unset means Terraform's default (null\n // allowed), so an absent value shows the toggle ON.\n nullable: v.nullable ?? true,\n }));\n}\n\nfunction outputsToRows(outputs: SettingsConfig['outputs']): OutputRow[] {\n return outputs.map((o) => ({\n id: crypto.randomUUID(),\n name: o.name,\n value: o.value,\n description: o.description ?? '',\n sensitive: o.sensitive ?? false,\n depends_on: o.depends_on ?? [],\n }));\n}\n\n// The output a call's output text names: `module.<call>.<output>` exposes\n// as `<output>`.\nfunction outputName(text: string): string {\n return text.slice(text.lastIndexOf('.') + 1);\n}\n\n// ── Content-only component (used by ModuleDetails) ──\n\ntype ContentProps = {\n settings: SettingsConfig;\n // One Update sets the variables and the outputs in one batch.\n onSave: (variables: VariableDef[], outputs: OutputDefEntry[]) => void | Promise<void>;\n};\n\nexport function ModuleInterfaceContent({ settings, onSave }: ContentProps) {\n const { editable } = useCanvas();\n const [variables, setVariables] = useState<VariableRow[]>(() =>\n variablesToRows(settings.variables),\n );\n const [outputs, setOutputs] = useState<OutputRow[]>(() => outputsToRows(settings.outputs));\n\n const updateVariable = useCallback(\n <K extends keyof VariableRow>(index: number, field: K, value: VariableRow[K]) => {\n setVariables((prev) => prev.map((v, i) => (i === index ? { ...v, [field]: value } : v)));\n },\n [],\n );\n\n const addVariable = useCallback(() => {\n setVariables((prev) => [\n ...prev,\n {\n id: crypto.randomUUID(),\n name: '',\n added: true,\n type: '',\n required: true,\n description: '',\n defaultText: '',\n validation: [],\n ephemeral: false,\n sensitive: false,\n nullable: true,\n },\n ]);\n }, []);\n\n const addValidation = useCallback((index: number) => {\n setVariables((prev) =>\n prev.map((v, i) =>\n i === index\n ? {\n ...v,\n validation: [\n ...v.validation,\n { id: crypto.randomUUID(), condition: '', error_message: '' },\n ],\n }\n : v,\n ),\n );\n }, []);\n\n const removeValidation = useCallback((index: number, vIndex: number) => {\n setVariables((prev) =>\n prev.map((v, i) =>\n i === index ? { ...v, validation: v.validation.filter((_, j) => j !== vIndex) } : v,\n ),\n );\n }, []);\n\n const updateValidation = useCallback(\n (index: number, vIndex: number, field: keyof ValidationRow, value: string) => {\n setVariables((prev) =>\n prev.map((v, i) =>\n i === index\n ? {\n ...v,\n validation: v.validation.map((b, j) =>\n j === vIndex ? { ...b, [field]: value } : b,\n ),\n }\n : v,\n ),\n );\n },\n [],\n );\n\n const updateOutput = useCallback(\n <K extends keyof OutputRow>(index: number, field: K, value: OutputRow[K]) => {\n setOutputs((prev) => prev.map((o, i) => (i === index ? { ...o, [field]: value } : o)));\n },\n [],\n );\n\n const addOutput = useCallback((name: string, value: string) => {\n setOutputs((prev) => [\n ...prev,\n { id: crypto.randomUUID(), name, value, description: '', sensitive: false, depends_on: [] },\n ]);\n }, []);\n\n const toggleDependsOn = useCallback((index: number, dep: string) => {\n setOutputs((prev) =>\n prev.map((o, i) => {\n if (i !== index) return o;\n const has = o.depends_on.includes(dep);\n return {\n ...o,\n depends_on: has ? o.depends_on.filter((k) => k !== dep) : [...o.depends_on, dep],\n };\n }),\n );\n }, []);\n\n const variableDupes = findDuplicateIndices(variables, (v) => v.name);\n const outputDupes = findDuplicateIndices(outputs, (o) => o.name);\n const unnamedOutput = outputs.some((o) => !o.name.trim() || !o.value.trim());\n const hasErrors = variableDupes.size > 0 || outputDupes.size > 0 || unnamedOutput;\n\n const { status: updateStatus, handleUpdate } = useUpdateState(\n useCallback(async () => {\n if (hasErrors) return;\n const variableDefs: VariableDef[] = variables\n .filter((v) => v.name.trim())\n .map((v) => {\n const validation = v.validation\n .map((b) => ({ condition: b.condition.trim(), error_message: b.error_message.trim() }))\n .filter((b) => b.condition || b.error_message);\n return {\n name: v.name.trim(),\n type: v.type.trim(),\n required: v.required,\n description: v.description.trim() || undefined,\n default: v.default_value,\n validation: validation.length > 0 ? validation : undefined,\n ephemeral: v.ephemeral || undefined,\n // `false` turns sensitive off: the variables are set whole.\n sensitive: v.sensitive,\n // `nullable` is tri-state on the wire (unset = default true). The\n // toggle ON keeps the default by omitting the field; OFF authors\n // an explicit `false`.\n nullable: v.nullable ? undefined : false,\n };\n });\n const outputDefs: OutputDefEntry[] = outputs.map((o) => ({\n name: o.name.trim(),\n value: o.value,\n description: o.description || undefined,\n sensitive: o.sensitive || undefined,\n depends_on: o.depends_on.length > 0 ? o.depends_on : undefined,\n }));\n await onSave(variableDefs, outputDefs);\n }, [variables, outputs, hasErrors, onSave]),\n );\n\n const exposable = settings.call_outputs.filter((text) => !outputs.some((o) => o.value === text));\n\n return (\n <>\n <div className=\"lace-panel-hint\">\n The module's public surface: the variables its callers set and the outputs they read.\n </div>\n\n <h4 className=\"lace-panel-section-title\">Inputs</h4>\n {variables.length === 0 && <div className=\"lace-panel-hint\">No variables.</div>}\n {variables.map((v, i) => (\n <div key={v.id} className=\"lace-panel-row-card lace-panel-row-card--with-footer\">\n <div className=\"lace-panel-row-actions\">\n {v.added ? (\n <Input\n label=\"Name\"\n value={v.name}\n onChange={(e) => updateVariable(i, 'name', e.target.value)}\n placeholder=\"Variable name\"\n fullWidth\n mono\n error={variableDupes.has(i)}\n />\n ) : (\n <Identifier className=\"lace-panel-row-card__name\" text={v.name} />\n )}\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label={`Remove variable ${v.name}`}\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => setVariables((prev) => prev.filter((_, j) => j !== i))}\n />\n )}\n </div>\n {variableDupes.has(i) && (\n <div className=\"lace-panel-row-error\">Duplicate variable name</div>\n )}\n <div className=\"lace-panel-row-actions\">\n <Input\n label=\"Type\"\n value={v.type}\n onChange={(e) => updateVariable(i, 'type', e.target.value)}\n placeholder=\"No declared type\"\n fullWidth\n mono\n readOnly={!editable}\n />\n </div>\n {v.defaultText && (\n <div className=\"lace-panel-row-actions\">\n <Input label=\"Default\" value={v.defaultText} fullWidth mono readOnly />\n </div>\n )}\n <div className=\"lace-panel-row-content\">\n <Textarea\n label=\"Description\"\n value={v.description}\n onChange={(e) => updateVariable(i, 'description', e.target.value)}\n placeholder=\"Optional\"\n rows={2}\n fullWidth\n readOnly={!editable}\n />\n </div>\n <div className=\"lace-panel-row-actions\">\n <label className=\"lace-panel-checkbox-row\">\n <input\n type=\"checkbox\"\n checked={v.required}\n onChange={(e) => updateVariable(i, 'required', e.target.checked)}\n disabled={!editable}\n />\n <span>Required</span>\n </label>\n <label className=\"lace-panel-checkbox-row\">\n <input\n type=\"checkbox\"\n checked={v.ephemeral}\n onChange={(e) => updateVariable(i, 'ephemeral', e.target.checked)}\n disabled={!editable}\n />\n <span>Ephemeral</span>\n </label>\n <label className=\"lace-panel-checkbox-row\">\n <input\n type=\"checkbox\"\n checked={v.sensitive}\n onChange={(e) => updateVariable(i, 'sensitive', e.target.checked)}\n disabled={!editable}\n />\n <span>Sensitive</span>\n </label>\n <label className=\"lace-panel-checkbox-row\">\n <input\n type=\"checkbox\"\n checked={v.nullable}\n onChange={(e) => updateVariable(i, 'nullable', e.target.checked)}\n disabled={!editable}\n />\n <span>Nullable</span>\n </label>\n </div>\n {(v.validation.length > 0 || editable) && (\n <div className=\"lace-panel-row-content\">\n <div className=\"lace-panel-subsection-label\">Validation</div>\n {v.validation.map((block, j) => (\n <div key={block.id} className=\"lace-panel-validation-block\">\n <Input\n value={block.condition}\n onChange={(e) => updateValidation(i, j, 'condition', e.target.value)}\n placeholder=\"condition (e.g. length(var.x) > 0)\"\n aria-label=\"Validation condition\"\n fullWidth\n mono\n readOnly={!editable}\n />\n <Input\n value={block.error_message}\n onChange={(e) => updateValidation(i, j, 'error_message', e.target.value)}\n placeholder=\"error message\"\n aria-label=\"Validation error message\"\n fullWidth\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label=\"Remove validation rule\"\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => removeValidation(i, j)}\n />\n )}\n </div>\n ))}\n {editable && (\n <Button variant=\"secondary\" size=\"sm\" onClick={() => addValidation(i)}>\n + Add validation rule\n </Button>\n )}\n </div>\n )}\n </div>\n ))}\n {editable && (\n <Button variant=\"secondary\" size=\"sm\" onClick={addVariable}>\n + Add variable\n </Button>\n )}\n\n <h4 className=\"lace-panel-section-title\">Outputs</h4>\n {outputs.length === 0 && <div className=\"lace-panel-hint\">No outputs.</div>}\n {outputs.map((o, i) => (\n <div key={o.id} className=\"lace-panel-row-card lace-panel-row-card--with-footer\">\n <div className=\"lace-panel-row-actions\">\n <Input\n label=\"Name\"\n value={o.name}\n onChange={(e) => updateOutput(i, 'name', e.target.value)}\n placeholder=\"Output name\"\n fullWidth\n mono\n readOnly={!editable}\n error={outputDupes.has(i) || (editable && !o.name.trim())}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label={`Remove output ${o.name}`}\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => setOutputs((prev) => prev.filter((_, j) => j !== i))}\n />\n )}\n </div>\n <div className=\"lace-panel-row-actions\">\n <Input\n label=\"Value\"\n value={o.value}\n onChange={(e) => updateOutput(i, 'value', e.target.value)}\n placeholder=\"e.g. aws_s3_bucket.this.arn\"\n fullWidth\n mono\n readOnly={!editable}\n error={editable && !o.value.trim()}\n />\n </div>\n <div className=\"lace-panel-row-content\">\n <Textarea\n label=\"Description\"\n value={o.description}\n onChange={(e) => updateOutput(i, 'description', e.target.value)}\n placeholder=\"Optional\"\n rows={2}\n fullWidth\n readOnly={!editable}\n />\n </div>\n <label className=\"lace-panel-checkbox-row\">\n <input\n type=\"checkbox\"\n checked={o.sensitive}\n onChange={(e) => updateOutput(i, 'sensitive', e.target.checked)}\n disabled={!editable}\n />\n <span>Sensitive</span>\n </label>\n {(o.depends_on.length > 0 || (editable && settings.dependency_options.length > 0)) && (\n <div className=\"lace-panel-row-content\">\n <div className=\"lace-panel-subsection-label\">Depends on</div>\n {!editable\n ? o.depends_on.map((dep) => (\n <div key={dep} className=\"lace-panel-depends-item\">\n <Identifier text={dep} />\n </div>\n ))\n : settings.dependency_options.map((dep) => (\n <label key={dep} className=\"lace-panel-checkbox-row\">\n <input\n type=\"checkbox\"\n checked={o.depends_on.includes(dep)}\n onChange={() => toggleDependsOn(i, dep)}\n />\n <Identifier text={dep} />\n </label>\n ))}\n </div>\n )}\n {outputDupes.has(i) && (\n <div className=\"lace-panel-row-error\">Output names must be unique.</div>\n )}\n </div>\n ))}\n\n {editable && (\n <div className=\"lace-panel-row-actions\">\n <Button variant=\"secondary\" size=\"sm\" onClick={() => addOutput('', '')}>\n + Add output\n </Button>\n {exposable.length > 0 && (\n <Select\n aria-label=\"Expose a call's output\"\n options={[\n { value: '', label: \"Expose a call's output…\" },\n ...exposable.map((text) => ({ value: text, label: text })),\n ]}\n value=\"\"\n onChange={(e) => {\n const text = e.target.value;\n if (text) addOutput(outputName(text), text);\n }}\n />\n )}\n </div>\n )}\n\n {editable && (\n <UpdateButton\n status={updateStatus}\n label=\"Update interface\"\n onClick={handleUpdate}\n disabled={hasErrors}\n disabledTitle=\"Give every output a unique name and a value, and every variable a unique name\"\n />\n )}\n </>\n );\n}\n\n// ── The standalone panel ──\n\ntype Props = ContentProps & { onClose: () => void };\n\nexport default function ModuleInterfacePanel({ onClose, ...content }: Props) {\n return (\n <Panel title=\"Module Interface\" onClose={onClose}>\n <ModuleInterfaceContent {...content} />\n </Panel>\n );\n}\n","// The actions a module's panel sends, each naming the module it edits by\n// `scope`: its declarations set whole by the settings actions, a resource's\n// arguments, meta-arguments, nested blocks and depends_on edited by the\n// actions the engine addresses to the resource's id. Every value is the\n// HCL text the panel shows, which the engine reads as the parse reads it.\n// Pure: a panel composes them into one `apply` batch, one undo entry.\nimport type { Action, InputDef } from '../../generated/service';\nimport { InputMode } from '../../generated/service';\nimport type { BlockConfig, ResourceConfig, SettingsConfig } from '../../types/render';\nimport type { OutputDefEntry, VariableDef } from './ModuleInterfacePanel';\n\nexport function setVariables(scope: string, variables: readonly VariableDef[]): Action {\n return {\n set_variables: {\n scope,\n variables: variables.map(\n (v): InputDef => ({\n name: v.name,\n type: v.type,\n required: v.required,\n description: v.description ?? '',\n default_value: v.default,\n validation: v.validation ?? [],\n ephemeral: v.ephemeral,\n nullable: v.nullable,\n sensitive: v.sensitive ?? false,\n }),\n ),\n },\n };\n}\n\nexport function setOutputs(scope: string, outputs: readonly OutputDefEntry[]): Action {\n return {\n set_exports: {\n scope,\n outputs: outputs.map((o) => ({ name: o.name, value: o.value })),\n output_defs: outputs.map((o) => ({\n name: o.name,\n type: '',\n description: o.description ?? '',\n sensitive: o.sensitive ?? false,\n depends_on: o.depends_on ?? [],\n })),\n },\n };\n}\n\nexport function setTerraform(scope: string, terraform: SettingsConfig['terraform']): Action {\n return {\n set_terraform: {\n scope,\n required_version: terraform.required_version,\n required_providers: terraform.required_providers.map((p) => ({\n name: p.name,\n source: p.source,\n version: p.version,\n configuration_aliases: p.configuration_aliases ?? [],\n })),\n },\n };\n}\n\nexport function setProviders(scope: string, providers: SettingsConfig['providers']): Action {\n return { set_providers: { scope, providers: providers.map((p) => ({ ...p })) } };\n}\n\nexport function setLocals(scope: string, locals: SettingsConfig['locals']): Action {\n return { set_locals: { scope, locals: locals.map((l) => ({ ...l })) } };\n}\n\nexport function setDirectives(scope: string, blocks: readonly BlockConfig[]): Action {\n return { set_directives: { scope, blocks: [...blocks] } };\n}\n\nexport function addResource(\n scope: string,\n kind: ResourceConfig['kind'],\n type: string,\n name: string,\n): Action {\n return { add_resource: { scope, kind, type, name } };\n}\n\nexport function removeResource(scope: string, id: string): Action {\n return { delete_instance: { scope, instance_id: id } };\n}\n\n// resourceActions is the batch that takes a resource from `before` to\n// `after`, the edits a panel made: an argument set or changed is its text\n// as an expression input, one removed is disconnected, and the\n// meta-arguments, nested blocks and depends_on are each set when they\n// changed. Nothing the panel left as it was is sent, so an unchanged\n// construct is never rewritten.\nexport function resourceActions(\n scope: string,\n before: ResourceConfig,\n after: ResourceConfig,\n): Action[] {\n const actions: Action[] = [];\n const was = new Map(before.arguments.map((a) => [a.name, a.value]));\n const now = new Map(after.arguments.map((a) => [a.name, a.value]));\n for (const [name, value] of now) {\n if (was.get(name) === value) continue;\n actions.push({\n update_input: {\n scope,\n instance_id: before.id,\n input_name: name,\n mode: InputMode.INPUT_MODE_EXPRESSION,\n value: undefined,\n variable: '',\n expression: value,\n },\n });\n }\n for (const name of was.keys()) {\n if (!now.has(name)) {\n actions.push({ disconnect: { scope, target: before.id, input_name: name } });\n }\n }\n if (\n before.count !== after.count ||\n before.for_each !== after.for_each ||\n before.provider !== after.provider\n ) {\n actions.push({\n set_meta_arguments: {\n scope,\n instance_id: before.id,\n count: after.count,\n for_each: after.for_each,\n provider: after.provider,\n },\n });\n }\n if (JSON.stringify(before.blocks) !== JSON.stringify(after.blocks)) {\n actions.push({ set_blocks: { scope, instance_id: before.id, blocks: after.blocks } });\n }\n if (JSON.stringify(before.depends_on) !== JSON.stringify(after.depends_on)) {\n actions.push({\n set_depends_on: { scope, instance_id: before.id, depends_on: after.depends_on },\n });\n }\n return actions;\n}\n","import { Button, IconButton, Input, Panel } from '@lace-cloud/ui';\nimport { useCallback, useState } from 'react';\nimport { useUpdateState } from '../../hooks/useUpdateState';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { BlockConfig, SettingsConfig } from '../../types/render';\nimport { CanvasIcon } from '../icons';\nimport UpdateButton from '../UpdateButton';\nimport BlockEditor from './BlockEditor';\nimport './panels-shared.css';\n\n// A provider configuration is edited whole: its settings, each value as\n// the HCL text the render writes for it, and its nested blocks\n// (default_tags, assume_role, …) through the one block editor.\n\n// ── Types derived from SettingsConfig ──\n\ntype ProviderEntry = SettingsConfig['providers'][number];\n\n// ── Local editing state ──\n\n// Stable per-row id, used as React key. Generated when rows are\n// created (toRows / addProvider / addConfigEntry), survives edits +\n// reorders. NOT persisted — fromRows discards it.\ntype ProviderRow = {\n id: string;\n name: string;\n alias: string;\n configEntries: Array<{ id: string; key: string; value: string }>;\n blocks: BlockConfig[];\n};\n\nfunction toRows(providers: ProviderEntry[] | undefined): ProviderRow[] {\n if (!providers || providers.length === 0) return [];\n return providers.map((p) => ({\n id: crypto.randomUUID(),\n name: p.name,\n alias: p.alias ?? '',\n configEntries: Object.entries(p.config).map(([key, value]) => ({\n id: crypto.randomUUID(),\n key,\n value: String(value),\n })),\n blocks: p.blocks,\n }));\n}\n\nfunction fromRows(rows: ProviderRow[]): ProviderEntry[] {\n return rows\n .filter((r) => r.name.trim())\n .map((r) => {\n const config: Record<string, string> = {};\n for (const c of r.configEntries) {\n if (c.key.trim()) {\n config[c.key.trim()] = c.value;\n }\n }\n return { name: r.name.trim(), alias: r.alias.trim() || '', config, blocks: r.blocks };\n });\n}\n\n// ── Content-only component (used by ModuleDetails) ──\n\ntype ContentProps = {\n providers: ProviderEntry[] | undefined;\n onSave: (providers: ProviderEntry[]) => void | Promise<void>;\n};\n\nexport function ProvidersContent({ providers, onSave }: ContentProps) {\n const { editable } = useCanvas();\n const [rows, setRows] = useState<ProviderRow[]>(() => toRows(providers));\n\n const addProvider = useCallback(() => {\n setRows((prev) => [\n ...prev,\n {\n id: crypto.randomUUID(),\n name: '',\n alias: '',\n configEntries: [{ id: crypto.randomUUID(), key: '', value: '' }],\n blocks: [],\n },\n ]);\n }, []);\n\n const removeProvider = useCallback((index: number) => {\n setRows((prev) => prev.filter((_, i) => i !== index));\n }, []);\n\n const updateField = useCallback((index: number, field: 'name' | 'alias', value: string) => {\n setRows((prev) => prev.map((r, i) => (i === index ? { ...r, [field]: value } : r)));\n }, []);\n\n const updateBlocks = useCallback((index: number, blocks: BlockConfig[]) => {\n setRows((prev) => prev.map((r, i) => (i === index ? { ...r, blocks } : r)));\n }, []);\n\n const addConfigEntry = useCallback((providerIndex: number) => {\n setRows((prev) =>\n prev.map((r, i) =>\n i === providerIndex\n ? {\n ...r,\n configEntries: [...r.configEntries, { id: crypto.randomUUID(), key: '', value: '' }],\n }\n : r,\n ),\n );\n }, []);\n\n const removeConfigEntry = useCallback((providerIndex: number, entryIndex: number) => {\n setRows((prev) =>\n prev.map((r, i) =>\n i === providerIndex\n ? { ...r, configEntries: r.configEntries.filter((_, ei) => ei !== entryIndex) }\n : r,\n ),\n );\n }, []);\n\n const updateConfigEntry = useCallback(\n (providerIndex: number, entryIndex: number, field: 'key' | 'value', value: string) => {\n setRows((prev) =>\n prev.map((r, i) =>\n i === providerIndex\n ? {\n ...r,\n configEntries: r.configEntries.map((c, ei) =>\n ei === entryIndex ? { ...c, [field]: value } : c,\n ),\n }\n : r,\n ),\n );\n },\n [],\n );\n\n const { status: updateStatus, handleUpdate } = useUpdateState(\n useCallback(async () => {\n await onSave(fromRows(rows));\n }, [onSave, rows]),\n );\n\n return (\n <>\n {rows.map((row, pi) => (\n <div key={row.id} className=\"lace-panel-row-card lace-panel-row-card--with-footer\">\n <div className=\"lace-panel-row-actions\">\n <Input\n value={row.name}\n onChange={(e) => updateField(pi, 'name', e.target.value)}\n placeholder=\"Provider name (e.g. aws)\"\n fullWidth\n readOnly={!editable}\n />\n <Input\n value={row.alias}\n onChange={(e) => updateField(pi, 'alias', e.target.value)}\n placeholder=\"Alias (optional)\"\n fullWidth\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label=\"Remove provider\"\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => removeProvider(pi)}\n />\n )}\n </div>\n\n <div className=\"lace-panel-row-sublabel\">Config</div>\n {row.configEntries.map((entry, ei) => (\n <div key={entry.id} className=\"lace-panel-row-actions\">\n <Input\n value={entry.key}\n onChange={(e) => updateConfigEntry(pi, ei, 'key', e.target.value)}\n placeholder=\"Key\"\n fullWidth\n readOnly={!editable}\n />\n <Input\n value={entry.value}\n onChange={(e) => updateConfigEntry(pi, ei, 'value', e.target.value)}\n placeholder=\"Value\"\n fullWidth\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label=\"Remove config key\"\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => removeConfigEntry(pi, ei)}\n />\n )}\n </div>\n ))}\n {editable && (\n <Button variant=\"secondary\" size=\"sm\" onClick={() => addConfigEntry(pi)}>\n + Add config key\n </Button>\n )}\n\n {(row.blocks.length > 0 || editable) && (\n <>\n <div className=\"lace-panel-row-sublabel\">Nested blocks</div>\n <BlockEditor\n blocks={row.blocks}\n editable={editable}\n onChange={(blocks) => updateBlocks(pi, blocks)}\n />\n </>\n )}\n </div>\n ))}\n\n {editable && (\n <>\n <Button variant=\"secondary\" size=\"sm\" onClick={addProvider}>\n + Add provider\n </Button>\n\n <UpdateButton status={updateStatus} label=\"Update providers\" onClick={handleUpdate} />\n </>\n )}\n </>\n );\n}\n\n// ── The standalone panel ──\n\ntype Props = {\n providers: ProviderEntry[] | undefined;\n onSave: (providers: ProviderEntry[]) => void | Promise<void>;\n onClose: () => void;\n};\n\nexport default function ProvidersPanel({ providers, onSave, onClose }: Props) {\n return (\n <Panel title=\"Providers\" onClose={onClose}>\n <ProvidersContent providers={providers} onSave={onSave} />\n </Panel>\n );\n}\n","// A module's resources and data sources, each one card: its kind, type and\n// name, its meta-arguments, its arguments, its nested blocks and what it\n// depends on, every value the HCL text the render writes for it. A\n// resource is one block however many instances its count or for_each\n// makes. Editable, a card's Update sends what the developer changed as one\n// batch, and a resource or data source is added by kind, type and name and\n// removed whole. A data source may be added to any module; a managed\n// resource only where lace shape lets the module hold one.\nimport { Badge, Button, IconButton, Input, Select } from '@lace-cloud/ui';\nimport { useCallback, useState } from 'react';\nimport { useUpdateState } from '../../hooks/useUpdateState';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { ResourceConfig } from '../../types/render';\nimport { findDuplicateIndices } from '../../utils/duplicates';\nimport Identifier from '../Identifier';\nimport { CanvasIcon } from '../icons';\nimport UpdateButton from '../UpdateButton';\nimport BlockEditor from './BlockEditor';\nimport './panels-shared.css';\n\ntype ContentProps = {\n resources: ResourceConfig[];\n // What a depends_on in the module names (`SettingsConfig.dependency_options`).\n dependencyOptions: string[];\n // Whether the module may hold a managed resource\n // (`SettingsConfig.holds_managed_resources`): the add row offers one only\n // then, and a data source always.\n managed: boolean;\n onUpdate: (before: ResourceConfig, after: ResourceConfig) => Promise<void>;\n onRemove: (id: string) => Promise<void>;\n onAdd: (kind: ResourceConfig['kind'], type: string, name: string) => Promise<void>;\n};\n\nexport function ResourcesContent({\n resources,\n dependencyOptions,\n managed,\n onUpdate,\n onRemove,\n onAdd,\n}: ContentProps) {\n const { editable } = useCanvas();\n return (\n <>\n {resources.length === 0 && (\n <div className=\"lace-panel-hint\">No resources or data sources.</div>\n )}\n {resources.map((resource) => (\n <ResourceCard\n // A new frame that changes the resource re-seeds the card.\n key={JSON.stringify(resource)}\n resource={resource}\n dependencyOptions={dependencyOptions.filter(\n (dep) => dep !== resource.id.replace(/^resource\\./, ''),\n )}\n editable={editable}\n onUpdate={onUpdate}\n onRemove={onRemove}\n />\n ))}\n {editable && <NewResourceRow managed={managed} onAdd={onAdd} />}\n </>\n );\n}\n\nconst MANAGED_OPTION = { value: 'resource', label: 'Resource' };\nconst DATA_OPTION = { value: 'data', label: 'Data source' };\n\nfunction NewResourceRow({\n managed,\n onAdd,\n}: {\n managed: ContentProps['managed'];\n onAdd: ContentProps['onAdd'];\n}) {\n const options = managed ? [MANAGED_OPTION, DATA_OPTION] : [DATA_OPTION];\n const [chosen, setChosen] = useState<ResourceConfig['kind']>('resource');\n const kind = managed ? chosen : 'data';\n const [type, setType] = useState('');\n const [name, setName] = useState('');\n return (\n <div className=\"lace-panel-row-card\">\n <div className=\"lace-panel-subsection-label\">Add a resource</div>\n <div className=\"lace-panel-row-actions\">\n <Select\n aria-label=\"New resource kind\"\n options={options}\n value={kind}\n onChange={(e) => setChosen(e.target.value === 'data' ? 'data' : 'resource')}\n />\n <Input\n value={type}\n onChange={(e) => setType(e.target.value)}\n placeholder=\"Type (e.g. aws_s3_bucket)\"\n aria-label=\"New resource type\"\n mono\n />\n <Input\n value={name}\n onChange={(e) => setName(e.target.value)}\n placeholder=\"Name\"\n aria-label=\"New resource name\"\n mono\n />\n <Button\n variant=\"secondary\"\n size=\"sm\"\n disabled={!type.trim() || !name.trim()}\n onClick={async () => {\n await onAdd(kind, type.trim(), name.trim());\n setType('');\n setName('');\n }}\n >\n + Add\n </Button>\n </div>\n </div>\n );\n}\n\ntype CardProps = {\n resource: ResourceConfig;\n dependencyOptions: string[];\n editable: boolean;\n onUpdate: ContentProps['onUpdate'];\n onRemove: ContentProps['onRemove'];\n};\n\nfunction ResourceCard({ resource, dependencyOptions, editable, onUpdate, onRemove }: CardProps) {\n const [draft, setDraft] = useState<ResourceConfig>(resource);\n const set = useCallback(\n <K extends keyof ResourceConfig>(field: K, value: ResourceConfig[K]) =>\n setDraft((prev) => ({ ...prev, [field]: value })),\n [],\n );\n const setArgument = (index: number, field: 'name' | 'value', value: string) =>\n set(\n 'arguments',\n draft.arguments.map((a, i) => (i === index ? { ...a, [field]: value } : a)),\n );\n\n const argumentDupes = findDuplicateIndices(draft.arguments, (a) => a.name);\n const hasErrors = argumentDupes.size > 0 || draft.arguments.some((a) => !a.name.trim());\n\n const { status, handleUpdate } = useUpdateState(\n useCallback(async () => {\n if (hasErrors) return;\n await onUpdate(resource, draft);\n }, [onUpdate, resource, draft, hasErrors]),\n );\n\n const metaArguments: Array<{ field: 'count' | 'for_each' | 'provider'; placeholder: string }> = [\n { field: 'count', placeholder: 'e.g. 2 or var.instances' },\n { field: 'for_each', placeholder: 'e.g. var.names' },\n { field: 'provider', placeholder: 'e.g. aws.west' },\n ];\n\n return (\n <div className=\"lace-panel-row-card lace-panel-row-card--with-footer\">\n <div className=\"lace-panel-row-actions\">\n <Badge variant={resource.kind === 'data' ? 'info' : 'neutral'}>\n {resource.kind === 'data' ? 'data' : 'resource'}\n </Badge>\n <Identifier\n className=\"lace-panel-row-card__name\"\n text={`${resource.type}.${resource.name}`}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label={`Remove ${resource.type}.${resource.name}`}\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => onRemove(resource.id)}\n />\n )}\n </div>\n\n {metaArguments.map(({ field, placeholder }) =>\n draft[field] || editable ? (\n <div key={field} className=\"lace-panel-row-actions\">\n <Input\n label={field}\n value={draft[field]}\n onChange={(e) => set(field, e.target.value)}\n placeholder={placeholder}\n fullWidth\n mono\n readOnly={!editable}\n />\n </div>\n ) : null,\n )}\n\n <div className=\"lace-panel-row-sublabel\">Arguments</div>\n {draft.arguments.map((argument, i) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: argument rows are positional while edited\n <div key={i} className=\"lace-panel-row-actions\">\n <Input\n value={argument.name}\n onChange={(e) => setArgument(i, 'name', e.target.value)}\n placeholder=\"Argument\"\n aria-label=\"Argument name\"\n mono\n readOnly={!editable}\n error={argumentDupes.has(i)}\n />\n <Input\n value={argument.value}\n onChange={(e) => setArgument(i, 'value', e.target.value)}\n placeholder=\"Value\"\n aria-label={`${argument.name || 'Argument'} value`}\n mono\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label={`Remove ${argument.name || 'the argument'}`}\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() =>\n set(\n 'arguments',\n draft.arguments.filter((_, j) => j !== i),\n )\n }\n />\n )}\n </div>\n ))}\n {editable && (\n <Button\n variant=\"secondary\"\n size=\"sm\"\n onClick={() => set('arguments', [...draft.arguments, { name: '', value: '' }])}\n >\n + Add argument\n </Button>\n )}\n\n {(draft.blocks.length > 0 || editable) && (\n <>\n <div className=\"lace-panel-row-sublabel\">Nested blocks</div>\n <BlockEditor\n blocks={draft.blocks}\n editable={editable}\n onChange={(blocks) => set('blocks', blocks)}\n />\n </>\n )}\n\n {(draft.depends_on.length > 0 || (editable && dependencyOptions.length > 0)) && (\n <>\n <div className=\"lace-panel-row-sublabel\">Depends on</div>\n {!editable\n ? draft.depends_on.map((dep) => (\n <div key={dep} className=\"lace-panel-depends-item\">\n <Identifier text={dep} />\n </div>\n ))\n : dependencyOptions.map((dep) => (\n <label key={dep} className=\"lace-panel-checkbox-row\">\n <input\n type=\"checkbox\"\n checked={draft.depends_on.includes(dep)}\n onChange={(e) =>\n set(\n 'depends_on',\n e.target.checked\n ? [...draft.depends_on, dep]\n : draft.depends_on.filter((d) => d !== dep),\n )\n }\n />\n <Identifier text={dep} />\n </label>\n ))}\n </>\n )}\n\n {editable && (\n <UpdateButton\n status={status}\n label=\"Update resource\"\n onClick={handleUpdate}\n disabled={hasErrors}\n disabledTitle=\"Give every argument a unique name\"\n />\n )}\n </div>\n );\n}\n","import { Button, IconButton, Input, Panel } from '@lace-cloud/ui';\nimport { useCallback, useState } from 'react';\nimport { useUpdateState } from '../../hooks/useUpdateState';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { SettingsConfig } from '../../types/render';\nimport { CanvasIcon } from '../icons';\nimport UpdateButton from '../UpdateButton';\nimport './panels-shared.css';\n\n// ── Types derived from SettingsConfig ──\n\ntype TerraformConfig = SettingsConfig['terraform'];\n\n// Stable per-row id, used as React key. NOT persisted.\ntype ProviderRequirementRow = {\n id: string;\n name: string;\n source: string;\n version: string;\n // The provider configurations the module takes from its callers\n // (`configuration_aliases = [aws.src, aws.dst]`), comma-separated.\n aliases: string;\n};\n\n// ── Content-only component (used by ModuleDetails) ──\n\ntype ContentProps = {\n terraform: TerraformConfig | undefined;\n onSave: (terraform: TerraformConfig) => void | Promise<void>;\n};\n\nexport function TerraformConfigContent({ terraform, onSave }: ContentProps) {\n const { editable } = useCanvas();\n const [requiredVersion, setRequiredVersion] = useState(terraform?.required_version ?? '');\n const [providers, setProviders] = useState<ProviderRequirementRow[]>(() => {\n if (!terraform?.required_providers) return [];\n return terraform.required_providers.map((req) => ({\n id: crypto.randomUUID(),\n name: req.name,\n source: req.source ?? '',\n version: req.version ?? '',\n aliases: (req.configuration_aliases ?? []).join(', '),\n }));\n });\n\n const addProvider = useCallback(() => {\n setProviders((prev) => [\n ...prev,\n { id: crypto.randomUUID(), name: '', source: '', version: '', aliases: '' },\n ]);\n }, []);\n\n const removeProvider = useCallback((index: number) => {\n setProviders((prev) => prev.filter((_, i) => i !== index));\n }, []);\n\n const updateProvider = useCallback(\n (index: number, field: 'name' | 'source' | 'version' | 'aliases', value: string) => {\n setProviders((prev) => prev.map((p, i) => (i === index ? { ...p, [field]: value } : p)));\n },\n [],\n );\n\n const { status: updateStatus, handleUpdate } = useUpdateState(\n useCallback(async () => {\n const block: TerraformConfig = {\n required_version: requiredVersion.trim() || '',\n required_providers: providers\n .filter((p) => p.name.trim())\n .map((p) => ({\n name: p.name.trim(),\n source: p.source.trim(),\n version: p.version.trim(),\n configuration_aliases: p.aliases\n .split(',')\n .map((alias) => alias.trim())\n .filter((alias) => alias !== ''),\n })),\n };\n await onSave(block);\n }, [onSave, requiredVersion, providers]),\n );\n\n return (\n <>\n <h4 className=\"lace-panel-section-title\">Required Version</h4>\n <div className=\"lace-panel-field\">\n <Input\n value={requiredVersion}\n onChange={(e) => setRequiredVersion(e.target.value)}\n placeholder=\">= 1.5\"\n fullWidth\n readOnly={!editable}\n />\n </div>\n\n <h4 className=\"lace-panel-section-title\">Required Providers</h4>\n {providers.map((p, i) => (\n <div key={p.id} className=\"lace-panel-row-card lace-panel-row-card--with-footer\">\n <div className=\"lace-panel-row-actions\">\n <Input\n value={p.name}\n onChange={(e) => updateProvider(i, 'name', e.target.value)}\n placeholder=\"Name (e.g. aws)\"\n fullWidth\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label=\"Remove provider\"\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => removeProvider(i)}\n />\n )}\n </div>\n <div className=\"lace-panel-row-actions\">\n <Input\n value={p.source}\n onChange={(e) => updateProvider(i, 'source', e.target.value)}\n placeholder=\"Source (e.g. hashicorp/aws)\"\n fullWidth\n readOnly={!editable}\n />\n </div>\n <div className=\"lace-panel-row-actions\">\n <Input\n value={p.version}\n onChange={(e) => updateProvider(i, 'version', e.target.value)}\n placeholder=\"Version (e.g. ~> 5.0)\"\n fullWidth\n readOnly={!editable}\n />\n </div>\n {(p.aliases || editable) && (\n <div className=\"lace-panel-row-actions\">\n <Input\n value={p.aliases}\n onChange={(e) => updateProvider(i, 'aliases', e.target.value)}\n aria-label={`${p.name || 'provider'} configuration_aliases`}\n placeholder=\"configuration_aliases (e.g. aws.src, aws.dst)\"\n fullWidth\n mono\n readOnly={!editable}\n />\n </div>\n )}\n </div>\n ))}\n {editable && (\n <Button variant=\"secondary\" size=\"sm\" onClick={addProvider}>\n + Add provider\n </Button>\n )}\n\n <h4 className=\"lace-panel-section-title\">Backend</h4>\n <div className=\"lace-panel-hint\">\n Terraform state is managed by Lace Cloud. The HTTP backend is configured automatically\n during generation.\n </div>\n\n {editable && (\n <UpdateButton status={updateStatus} label=\"Update terraform block\" onClick={handleUpdate} />\n )}\n </>\n );\n}\n\n// ── The standalone panel ──\n\ntype Props = {\n terraform: TerraformConfig | undefined;\n onSave: (terraform: TerraformConfig) => void | Promise<void>;\n onClose: () => void;\n};\n\nexport default function TerraformConfigPanel({ terraform, onSave, onClose }: Props) {\n return (\n <Panel title=\"Terraform Configuration\" onClose={onClose}>\n <TerraformConfigContent terraform={terraform} onSave={onSave} />\n </Panel>\n );\n}\n","// The source-refused banner: it shows whenever the engine refuses the\n// module's tf (`requiredContext: ['sourceRefused']`, the fact itself),\n// whatever ports the host supplies. Its opening states the lock or, when\n// the refusal's cause is lace shape (`needsConversion`), that the tree is\n// not in lace shape yet; its choices and buttons are the actions resolved\n// on its row (RowActionBanner): Convert, and any a host adds. The\n// diagnostics render once, through the DiagnosticsPanel's own\n// `ctx.diagnostics` (`diagnosticsOf`) — this banner never lists them a\n// second time.\nimport type { Panel, PanelProps } from '../../contributions';\nimport { keySatisfied } from '../../registry';\nimport { RowActionBanner } from './RowActionBanner';\n\nconst LOCKED =\n \"The canvas can't take this module's .tf, so editing, saving and generating are locked until it can; the Diagnostics tab says why.\";\nconst OUT_OF_LACE_SHAPE =\n 'This Terraform is not in lace shape yet, so the canvas shows it read-only.';\n\nexport function SourceRefusedBanner({ ctx }: PanelProps) {\n return (\n <RowActionBanner\n ctx={ctx}\n panelId=\"source-refused\"\n severity=\"error\"\n className=\"lace-source-refused-banner\"\n opening={keySatisfied(ctx, 'needsConversion') ? OUT_OF_LACE_SHAPE : LOCKED}\n />\n );\n}\n\nexport const sourceRefusedPanel: Panel = {\n id: 'source-refused',\n title: 'Source refused',\n slot: 'banner',\n requiredPorts: [],\n requiredContext: ['sourceRefused'],\n Component: SourceRefusedBanner,\n};\n\nexport default SourceRefusedBanner;\n","// The settings panel: a drawer panel wrapping\n// `components/panels/UnifiedSettingsPanel`, the entry's details, which\n// reads `editable`/`bundle`/`runner` straight off `useCanvas()` and gates\n// every section's Update control on `editable` itself. It resolves only\n// while the developer has it open (`requiredContext: ['settingsOpen']`,\n// App's own state carried on `ctx`), so a closed settings panel draws\n// nothing and opens no drawer; this file derives `onClose` from\n// `setSettingsOpen` (state/canvas-context.ts).\n//\n// `settingsToggle` is the toolbar's gear that opens and closes it — a\n// contribution like every other capability, not a button App hard-codes. It\n// needs no port: the entry's details are constructs the Bundle holds, which\n// every canvas shows (invariant bundle-shows-on-canvas), and a read-only\n// canvas shows them with no control. It names no toolbar group, so it sits\n// at the row's far end.\nimport { IconButton } from '@lace-cloud/ui';\nimport { createElement } from 'react';\nimport { CanvasIcon } from '../../components/icons';\nimport UnifiedSettingsPanelComponent from '../../components/panels/UnifiedSettingsPanel';\nimport type { Panel, PanelProps } from '../../contributions';\nimport { useCanvas } from '../../state/canvas-context';\n\nfunction SettingsPanel(_props: PanelProps) {\n const { setSettingsOpen } = useCanvas();\n return createElement(UnifiedSettingsPanelComponent, {\n onClose: () => setSettingsOpen(false),\n });\n}\n\nexport const settingsPanel: Panel = {\n id: 'settings',\n title: 'Settings',\n slot: 'drawer',\n requiredPorts: [],\n requiredContext: ['settingsOpen'],\n Component: SettingsPanel,\n};\n\n// A gear, pressed while the panel is open; a second press closes it. A\n// toggle: its name is Settings either way, and its tooltip that name alone.\nfunction SettingsToggle({ ctx }: PanelProps) {\n const { setSettingsOpen } = useCanvas();\n return createElement(IconButton, {\n icon: createElement(CanvasIcon, { name: 'settings' }),\n 'aria-label': 'Settings',\n size: 'md',\n tooltipPlacement: 'bottom-end',\n pressed: ctx.settingsOpen,\n onClick: () => setSettingsOpen(!ctx.settingsOpen),\n });\n}\n\nexport const settingsToggle: Panel = {\n id: 'settings-toggle',\n title: 'Settings',\n slot: 'toolbar',\n requiredPorts: [],\n Component: SettingsToggle,\n};\n\nexport default SettingsPanel;\n","// The settings panel: the entry's details (`ModuleDetails`), the module\n// the canvas's top scope is. A called module's details are its call's\n// panel's (ModuleConfigPanel).\nimport { Panel } from '@lace-cloud/ui';\nimport { useCanvas } from '../../state/canvas-context';\nimport ModuleDetails from './ModuleDetails';\nimport './panels-shared.css';\n\ntype Props = {\n onClose: () => void;\n};\n\nexport default function UnifiedSettingsPanel({ onClose }: Props) {\n const { bundle } = useCanvas();\n return (\n <Panel title=\"Settings\" flush onClose={onClose}>\n <ModuleDetails key={bundle.entry} moduleKey={bundle.entry} open={['Interface']} />\n </Panel>\n );\n}\n","// CORE_CONTRIBUTIONS: what the canvas draws, which is module authoring,\n// registered through the same Contributions surface a host extension uses —\n// no core feature bypasses the registry. `App` merges this set with\n// whatever a host passes: the conflict and source-refused banners, the\n// Unsaved/Not-generated toolbar chips, the diagnostics list, the module\n// and edge inspectors and the settings panel in the drawer, Validate and Convert, every\n// editor action, and the describe overlay (node badges for the stack the\n// host supplies), each gated only by its own declared ports/context like\n// any other contribution.\n//\n// The stack and run commands (`STACK_COMMAND_ACTIONS`, core/actions.ts) are\n// not in this set: the package carries their bindings, the runner and the\n// reducers over their output, and a host draws them in its own UI.\nimport type { Contributions } from '../contributions';\nimport { MODULE_COMMAND_ACTIONS } from './actions';\nimport { CORE_EDITOR_ACTIONS } from './editor-actions';\nimport { describeOverlay } from './overlays/describe';\nimport { conflictPanel } from './panels/ConflictBanner';\nimport { diagnosticsPanel } from './panels/DiagnosticsPanel';\nimport { disconnectEdge, edgeInspectorPanel } from './panels/edge-inspector';\nimport { ungeneratedMarker, unsavedMarker } from './panels/Markers';\nimport { moduleConfigPanel } from './panels/module-config';\nimport { sourceRefusedPanel } from './panels/SourceRefusedBanner';\nimport { settingsPanel, settingsToggle } from './panels/settings';\n\nexport const CORE_CONTRIBUTIONS: Contributions = {\n overlays: [describeOverlay],\n panels: [\n conflictPanel,\n sourceRefusedPanel,\n unsavedMarker,\n ungeneratedMarker,\n diagnosticsPanel,\n // The drawer shows the first of these that resolves: Settings while it\n // is open, else the inspector of what is selected.\n settingsPanel,\n moduleConfigPanel,\n edgeInspectorPanel,\n settingsToggle,\n ],\n actions: [...MODULE_COMMAND_ACTIONS, ...CORE_EDITOR_ACTIONS, disconnectEdge],\n};\n","// snapshotSource is the read-only `SourcePort` a host without a live engine\n// mounts — portal's control-plane dashboards, any inspection-only view.\n// It fetches one Bundle proto snapshot and never changes: `unsaved`,\n// `ungenerated` and `conflict` are always false/null, `sourceRefused` and\n// `generating` are always false, `diagnostics` is always empty — a RunSnapshot has no\n// live validator, and the run's own certification already vouched for it —\n// and `treeHash` is always '': no session stands behind it to observe a\n// tree or publish a command's result.\n// No `editor`/`commands` port — a host that omits them renders read-only by\n// the absence of those ports, never a flag.\nimport { Bundle as BundleCodec } from '../generated/state';\nimport type { CanvasSource, SourcePort } from '../ports';\n\nexport type SnapshotSourceInput = {\n bundleUrl: string;\n /** Fetch impl override — used by tests. Defaults to globalThis.fetch. */\n fetch?: typeof fetch;\n /**\n * Extra request headers sent with the bundle GET. Same-origin portal\n * fetches carry the session cookie via `credentials: include`, but the\n * API still resolves org/team scope from `x-org-slug`/`x-team-slug`\n * headers — the caller must supply them here or the read 400s. Embed\n * routes authenticate via the token in the URL and omit this.\n */\n headers?: Record<string, string>;\n};\n\nexport function snapshotSource(input: SnapshotSourceInput): SourcePort {\n const fetchImpl = input.fetch ?? globalThis.fetch.bind(globalThis);\n let cached: CanvasSource | null = null;\n let loadPromise: Promise<CanvasSource> | null = null;\n\n async function load(): Promise<CanvasSource> {\n if (cached) return cached;\n const res = await fetchImpl(input.bundleUrl, {\n method: 'GET',\n headers: { accept: 'application/octet-stream', ...input.headers },\n credentials: 'include',\n });\n if (!res.ok) {\n throw new Error(`snapshotSource: failed to fetch bundle (status ${res.status})`);\n }\n const bytes = new Uint8Array(await res.arrayBuffer());\n const source: CanvasSource = {\n bundle: BundleCodec.decode(bytes),\n canUndo: false,\n canRedo: false,\n unsaved: false,\n ungenerated: false,\n conflict: null,\n sourceRefused: false,\n generating: false,\n diagnostics: [],\n treeHash: '',\n };\n cached = source;\n return source;\n }\n\n return {\n subscribe(on, onEnd) {\n let cancelled = false;\n if (cached) {\n const source = cached;\n queueMicrotask(() => {\n if (!cancelled) on(source);\n });\n } else {\n loadPromise ??= load();\n void loadPromise\n .then((source) => {\n if (!cancelled) on(source);\n })\n .catch((err: unknown) => {\n if (cancelled) return;\n // The one fetch is this source's whole stream: its failure is\n // the stream's end, and no session stands behind a snapshot.\n onEnd({ kind: 'failed', error: err instanceof Error ? err : new Error(String(err)) });\n });\n }\n return () => {\n cancelled = true;\n };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAA,MACT,aAAa;AAAA,MACb,UAAU;AAAA,MACV,eAAe;AAAA,MACf,YAAY;AAAA,MACZ,aAAa,CAAC;AAAA,MACd,UAAU;AAAA,IACZ;AACA,aAAS;AACT,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,UAAU,IAAI,OAAO;AACnB,UAAI,YAAY;AAChB,UAAI,QAAQ;AACV,cAAM,SAAS;AACf,uBAAe,MAAM;AACnB,cAAI,CAAC,UAAW,IAAG,MAAM;AAAA,QAC3B,CAAC;AAAA,MACH,OAAO;AACL,sCAAgB,KAAK;AACrB,aAAK,YACF,KAAK,CAAC,WAAW;AAChB,cAAI,CAAC,UAAW,IAAG,MAAM;AAAA,QAC3B,CAAC,EACA,MAAM,CAAC,QAAiB;AACvB,cAAI,UAAW;AAGf,gBAAM,EAAE,MAAM,UAAU,OAAO,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC,EAAE,CAAC;AAAA,QACtF,CAAC;AAAA,MACL;AACA,aAAO,MAAM;AACX,oBAAY;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF;","names":["projectCanvasView","Fragment","useCallback","useEffect","useLayoutEffect","useMemo","useRef","useState","drawnRect","extentOf","instanceAddress","localIn","useReactFlow","useCallback","useEffect","useMemo","useRef","useState","jsx","Fragment","useState","Fragment","jsx","jsxs","useState","at","jsx","useStore","clearanceY","railX1","railX2","jsx","useStore","useCallback","useEffect","useRef","useState","localIn","splitPath","group","localIn","cut","splitPath","keyOf","group","instanceAddress","useRef","useEffect","useState","useRef","instanceAddress","jsx","jsxs","useState","useRef","useEffect","useCallback","instanceAddress","NODE_ROW_HEIGHT","Handle","Position","useStore","useCallback","useEffect","useRef","useState","createContext","useContext","useRef","jsx","Fragment","jsx","jsxs","NODE_ROW_HEIGHT","Handle","Position","useStore","useState","useRef","useEffect","useCallback","instanceAddress","jsx","useEffect","useEffect","useCallback","useState","useMemo","useMemo","group","useCallback","useEffect","useRef","useState","jsx","jsxs","useReactFlow","useEffect","useRef","drawnRect","extentOf","useMemo","useState","useCallback","localIn","instanceAddress","useCallback","useLayoutEffect","useRef","useState","jsx","jsxs","useRef","useState","useLayoutEffect","useCallback","jsx","jsxs","IconButton","jsx","jsxs","disabledReason","IconButton","useState","jsx","jsxs","useState","useMemo","useEffect","useMemo","useRef","useState","createContext","useContext","useMemo","jsx","useState","useRef","useEffect","useMemo","args","EMPTY_DECORATIONS","useMemo","Button","jsx","jsxs","jsx","Button","jsx","Button","Fragment","jsx","jsxs","jsx","jsxs","Button","instanceAddress","Button","jsx","jsxs","Button","instanceAddress","EdgeInspectorPanel","jsx","createElement","instanceAddress","Button","IconButton","Input","Panel","Textarea","useCallback","useEffect","useMemo","useState","useCallback","useEffect","useRef","useState","useState","jsx","jsxs","useState","Button","jsx","Input","useMemo","useState","Button","IconButton","useState","Fragment","jsx","jsxs","Button","useState","IconButton","Button","IconButton","Input","Panel","useCallback","useState","Fragment","jsx","jsxs","useState","useCallback","Input","IconButton","Button","Panel","Button","IconButton","Input","Panel","Textarea","useCallback","useState","Fragment","jsx","jsxs","setVariables","useState","setOutputs","useCallback","Input","IconButton","Textarea","Button","Panel","Button","IconButton","Input","Panel","useCallback","useState","Fragment","jsx","jsxs","toRows","fromRows","useState","useCallback","Input","IconButton","Button","Panel","Badge","Button","IconButton","Input","Select","useCallback","useState","Fragment","jsx","jsxs","useState","Select","Input","Button","useCallback","Badge","IconButton","Button","IconButton","Input","Panel","useCallback","useState","Fragment","jsx","jsxs","useState","setProviders","useCallback","Input","IconButton","Button","Panel","Fragment","jsx","jsxs","useMemo","useState","Input","Fragment","jsx","jsxs","useMemo","useState","useCallback","useEffect","instanceAddress","Input","IconButton","Textarea","Panel","Button","ModuleConfigPanel","createElement","jsx","IconButton","createElement","Panel","jsx","Panel","createElement","IconButton","jsx","jsxs","useRef","useCallback","useEffect","useState","next","useMemo","session","useLayoutEffect","Fragment"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/App.tsx","../src/Canvas.tsx","../src/components/CanvasControls.tsx","../src/components/icons.tsx","../src/components/ContextMenu.tsx","../src/core/sections.ts","../src/utils/key-chord.ts","../src/components/EmptyCanvas.tsx","../src/components/edges/DependencyEdge.tsx","../src/components/edges/dependency-edge-path.ts","../src/components/edges/obstacles-for.ts","../src/components/edges/scene-nodes.ts","../src/components/nodes/GroupNode.tsx","../src/core/editor-actions.ts","../src/utils/arrangement.ts","../src/core/entry-scope.ts","../src/state/canvas-context.ts","../src/core/panels/row-actions.ts","../src/components/nodes/use-rename-instance.ts","../src/core/pipeline.ts","../src/components/nodes/ModuleNode.tsx","../src/core/decorate.ts","../src/utils/handleId.ts","../src/utils/typed-name.ts","../src/components/nodes/node-config-bus.tsx","../src/components/nodes/pinColor.ts","../src/components/PaperGrid.tsx","../src/core/use-action-keys.ts","../src/contribution-types.ts","../src/hooks/useContextMenu.ts","../src/hooks/useGroupLogic.ts","../src/hooks/useNewNodeTracking.ts","../src/utils/viewport.ts","../src/components/Drawer.tsx","../src/utils/style-vars.ts","../src/components/ErrorBoundary.tsx","../src/components/ToolbarAction.tsx","../src/core/CommandArgsForm.tsx","../src/core/overlays/describe.ts","../src/core/define-overlay.ts","../src/core/use-command-read.ts","../src/core/panel-scope.tsx","../src/core/panels/RowActionBanner.tsx","../src/components/Banner.tsx","../src/core/panels/ConflictBanner.tsx","../src/core/panels/DiagnosticsPanel.tsx","../src/components/Identifier.tsx","../src/core/panels/edge-inspector.ts","../src/components/panels/EdgeInspectorPanel.tsx","../src/core/panels/Markers.tsx","../src/core/panels/module-config.ts","../src/components/panels/ModuleConfigPanel.tsx","../src/exhaustive.ts","../src/hooks/useUpdateState.ts","../src/components/AccordionSection.tsx","../src/components/UpdateButton.tsx","../src/components/panels/ModuleDetails.tsx","../src/components/panels/BlockEditor.tsx","../src/components/panels/LocalsPanel.tsx","../src/utils/duplicates.ts","../src/components/panels/ModuleInterfacePanel.tsx","../src/components/panels/module-actions.ts","../src/components/panels/ProvidersPanel.tsx","../src/components/panels/ResourcesPanel.tsx","../src/components/panels/TerraformConfigPanel.tsx","../src/core/panels/SourceRefusedBanner.tsx","../src/core/panels/settings.ts","../src/components/panels/UnifiedSettingsPanel.tsx","../src/core/contributions.ts","../src/adapters/snapshot-source.ts"],"sourcesContent":["// @lace-cloud/canvas — public library API.\n//\n// Two entries, no deep paths: this barrel (the React surface plus\n// everything below) and `@lace-cloud/canvas/engine` (`./engine/index.ts`),\n// the React-free entry a host imports outside the webview. Consumers\n// (canvas-stories, the VS Code webview entry, portal/JetBrains shells)\n// import from one of the two; internal file structure is not part of the\n// contract.\n\n// ── Projection (Bundle + optional CanvasArrangement → CanvasView) ──\n// Re-exported from @lace-cloud/proto so canvas consumers import it from\n// one place; the implementation lives in the proto package, beside the IR\n// types it projects, and runs without React.\nexport { type ProjectionMeta, projectCanvasView } from '@lace-cloud/proto';\nexport { Toast } from '@lace-cloud/ui/feedback';\n// ── Root component ──\nexport type { AppProps } from './App';\nexport { default as App } from './App';\nexport type { SnapshotSourceInput } from './adapters/snapshot-source';\n// ── Snapshot source (portal, Storybook — a read with no live session) ──\nexport { SnapshotFetchError, snapshotSource } from './adapters/snapshot-source';\n// ── Components ──\nexport { default as AccordionSection } from './components/AccordionSection';\nexport { default as ContextMenu } from './components/ContextMenu';\nexport { default as ErrorBoundary, ErrorState } from './components/ErrorBoundary';\nexport type { GroupNodeData, InterfacePin } from './components/nodes/GroupNode';\n// ── Node components ──\nexport { default as GroupNode } from './components/nodes/GroupNode';\nexport type { ModuleNodeData } from './components/nodes/ModuleNode';\nexport { default as ModuleNode } from './components/nodes/ModuleNode';\nexport { NodeConfigBusProvider } from './components/nodes/node-config-bus';\n// ── Panels ──\nexport { default as EdgeInspectorPanel } from './components/panels/EdgeInspectorPanel';\nexport { default as LocalsPanel, LocalsContent } from './components/panels/LocalsPanel';\nexport { default as ModuleConfigPanel } from './components/panels/ModuleConfigPanel';\nexport {\n default as ModuleInterfacePanel,\n ModuleInterfaceContent,\n} from './components/panels/ModuleInterfacePanel';\nexport { default as ProvidersPanel, ProvidersContent } from './components/panels/ProvidersPanel';\nexport {\n default as TerraformConfigPanel,\n TerraformConfigContent,\n} from './components/panels/TerraformConfigPanel';\nexport { default as UnifiedSettingsPanel } from './components/panels/UnifiedSettingsPanel';\nexport type {\n ArgsOf,\n BoundPath,\n CommandFailure,\n CommandPath,\n GateChangeRequest,\n JsonOf,\n} from './contracts';\n// ── Command contract (generated from command-tree.golden) ──\nexport {\n COMMANDS,\n carriesFailure,\n isBoundPath,\n parseBound,\n parseCommandFailure,\n SCHEMAS,\n toArgv,\n} from './contracts';\n// ── Contract types (ports, contributions, registry) — the client-extension\n// surface: everything a host needs to author its own panels/actions/\n// overlays through the identical registry the core registers through. ──\nexport type {\n ActionContribution,\n ActionIcon,\n ActionTarget,\n Badge,\n BindingRuntime,\n CanvasCtx,\n ClipboardStore,\n CommandBinding,\n CommandRead,\n ContextKey,\n ContributionSet,\n Contributions,\n Decorations,\n EdgeRef,\n EditorBinding,\n EditorEnv,\n ErasedCommand,\n HostBinding,\n NodeDecoration,\n OverlayContribution,\n Panel,\n PanelProps,\n PanelSpec,\n Placement,\n ResultKind,\n RunCtx,\n Sink,\n SinkInput,\n} from './contributions';\n// ── Core pipeline pieces ──\nexport { CommandArgsForm, type CommandArgsFormProps } from './core/CommandArgsForm';\nexport { decorate } from './core/decorate';\nexport { defineCommand } from './core/define-command';\nexport { defineOverlay } from './core/define-overlay';\nexport { diagnosticsOf, uniqueDiagnostics } from './core/diagnostics';\nexport { decorateDescribe, describeOverlay } from './core/overlays/describe';\nexport { PanelScope, type PanelScopeValue, usePanelScope } from './core/panel-scope';\nexport { ConflictBanner, conflictPanel } from './core/panels/ConflictBanner';\nexport {\n UngeneratedMarker,\n UnsavedMarker,\n ungeneratedMarker,\n unsavedMarker,\n} from './core/panels/Markers';\nexport { SourceRefusedBanner, sourceRefusedPanel } from './core/panels/SourceRefusedBanner';\nexport { useCanvasSource } from './core/pipeline';\nexport type { ReportEntry, ReportFold, ReportPath } from './core/report-fold';\nexport {\n currentReport,\n EMPTY_REPORT_FOLD,\n foldReport,\n reportDiagnostics,\n} from './core/report-fold';\nexport type {\n Busy,\n FollowSlot,\n PreviewOutcome,\n PreviewSlot,\n ReportSlot,\n ResultSlots,\n ResultStore,\n RunningMark,\n RunOutcome,\n RunSlot,\n SlotContext,\n SlotKind,\n Started,\n} from './core/results';\nexport { commandUnderWay, createResultStore } from './core/results';\nexport type {\n ActionRunner,\n ActionRunnerOptions,\n CommandRun,\n EditorEnvExtras,\n PendingForm,\n} from './core/run-binding';\nexport { createActionRunner } from './core/run-binding';\nexport type { CommandReadState } from './core/use-command-read';\nexport { useCommandRead } from './core/use-command-read';\nexport type {\n BridgeEngineCaller,\n ConnectCallerOptions,\n DirectEngineCaller,\n EngineCaller,\n EngineMethodResponse,\n EngineSession,\n EngineSessionOptions,\n EngineTarget,\n} from './engine';\n// ── Engine mapping and callers (the React-free entry's own exports) ──\nexport {\n bridgeCaller,\n ConnectError,\n connectCaller,\n openEngineCommands,\n openEngineSession,\n Reason,\n} from './engine';\nexport type {\n ApplyResult,\n CanvasPorts,\n CanvasSource,\n CommandResult,\n CommandsPort,\n ConfirmSpec,\n ContextPort,\n CreatedRef,\n EditorPort,\n GenerateEvent,\n GraphError,\n Invocation,\n PortName,\n PresenterPort,\n RunnerPorts,\n SourceConflict,\n SourceEnd,\n SourcePort,\n StackRef,\n ViewStatePort,\n WiringCandidate,\n WiringQuery,\n} from './ports';\nexport {\n ApplyUnobservedError,\n CommandDetachedError,\n CommandExitError,\n CommandUnobservedError,\n} from './ports';\nexport { answering, disabledReason, resolveContributions, rowActions } from './registry';\n// ── State ──\nexport type { CanvasContextValue } from './state/canvas-context';\nexport { CanvasContext, useCanvas } from './state/canvas-context';\n// ── Render-model types (re-exported from @lace-cloud/proto via ./types/render) ──\nexport type {\n CanvasArrangement,\n CanvasView,\n Conflict,\n Diagnostic,\n GeneratePhase,\n NodeConfig,\n NodePin,\n RenderEdge,\n RenderGroup,\n RenderInput,\n RenderNode,\n RenderOutput,\n SettingsConfig,\n ViewportIntent,\n} from './types/render';\n// The type an action's `keys` hold: a key that starts with `Mod+`, the\n// grammar's prefix; `parseChord` refuses the rest at runtime.\nexport type { KeySpec } from './utils/key-chord';\n","import { ReactFlowProvider } from '@xyflow/react';\nimport type React from 'react';\nimport {\n Fragment,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport './App.css';\nimport Canvas from './Canvas';\nimport Drawer from './components/Drawer';\nimport ErrorBoundary, { ErrorState } from './components/ErrorBoundary';\nimport { ToolbarAction } from './components/ToolbarAction';\nimport type { BoundPath } from './contracts';\nimport type {\n CanvasCtx,\n Contributions,\n Decorations,\n EdgeRef,\n LayoutHandle,\n Panel,\n} from './contributions';\nimport { CommandArgsForm } from './core/CommandArgsForm';\nimport { CORE_CONTRIBUTIONS } from './core/contributions';\nimport { decorate } from './core/decorate';\nimport { diagnosticsOf } from './core/diagnostics';\nimport { PanelScope } from './core/panel-scope';\nimport { projectFrame, reconcileSelection, useCanvasSource } from './core/pipeline';\nimport { reportDiagnostics } from './core/report-fold';\nimport { createResultStore, liveSlots, type ResultStore } from './core/results';\nimport { createActionRunner, type EditorEnvExtras, type PendingForm } from './core/run-binding';\nimport { isEmphasized, toolbarLayout } from './core/sections';\nimport { registerKeyTarget, useActionKeys, useFocusWhenNoneHeld } from './core/use-action-keys';\nimport type { CanvasPorts, CanvasSource, CommandResult, SourceEnd } from './ports';\nimport { actionState, resolveContributions } from './registry';\nimport { CanvasContext, type CanvasContextValue } from './state/canvas-context';\nimport type { CanvasArrangement } from './types/render';\nimport { gcArrangement } from './utils/arrangement';\n\nconst EMPTY_CONTRIBUTIONS: Contributions = { overlays: [], panels: [], actions: [] };\nconst NO_SELECTION: { nodes: readonly string[]; edge: EdgeRef | null } = { nodes: [], edge: null };\nconst NO_TARGET = {};\n\nexport type AppProps = {\n ports: CanvasPorts;\n /** Appended to the core contribution set — no core feature bypasses the registry. */\n contributions?: Contributions;\n /**\n * The result store the canvas writes and reads, owned by the host. A host\n * that refreshes the canvas's reads from outside — a run its own UI\n * started has settled — passes the store it owns and calls `bumpTick()`\n * on it. Omitted, the canvas owns one of its own.\n */\n results?: ResultStore;\n /**\n * Height of the canvas root. Defaults to `100vh`; a host that mounts the\n * canvas inside its own panel passes `100%` when that panel establishes an\n * explicit height.\n */\n height?: React.CSSProperties['height'];\n};\n\n// OverlayRunner mounts one resolved overlay's own `useDecorations` hook\n// inside the `PanelScope` its declared `paths` need — the identical\n// registry-gated read path a panel's own declared `reads` runs through, no\n// second overlay-fetch mechanism. Unlike `PanelSlot` (below), an overlay\n// decorates silently — there is no chrome slot to render a failed read\n// into — so a failure instead reaches `presenter.notify` once (`useCommandRead`'s\n// own effect calls `reportError` once per key/tick, never per render),\n// or a `stack describe` outage would show no drift badges and no notice.\nfunction OverlayRunner({\n overlay,\n ctx,\n tick,\n onDecorations,\n}: {\n overlay: Contributions['overlays'][number];\n ctx: CanvasCtx;\n tick: number;\n onDecorations: (id: string, decorations: Decorations) => void;\n}) {\n // `useCommandRead` reports the same still-failing error again on every\n // tick-only refetch of a path that keeps failing (an outage that\n // outlives one tick) — a toast per tick would spam the same notice.\n // Notify only when a path's own error actually changes: a new failure,\n // a different message, or clearing.\n const lastErrorRef = useRef<Map<BoundPath, string | null>>(new Map());\n const onReadError = useCallback(\n (path: BoundPath, error: Error | null) => {\n const next = error?.message ?? null;\n if (lastErrorRef.current.get(path) === next) return;\n lastErrorRef.current.set(path, next);\n if (error) ctx.ports.presenter.notify('error', `${path}: ${error.message}`);\n },\n [ctx.ports.presenter],\n );\n return (\n <PanelScope ctx={ctx} paths={overlay.paths} tick={tick} onReadError={onReadError}>\n <OverlayDecorations overlay={overlay} ctx={ctx} onDecorations={onDecorations} />\n </PanelScope>\n );\n}\n\nfunction OverlayDecorations({\n overlay,\n ctx,\n onDecorations,\n}: {\n overlay: Contributions['overlays'][number];\n ctx: CanvasCtx;\n onDecorations: (id: string, decorations: Decorations) => void;\n}) {\n const decorations = overlay.useDecorations(ctx);\n useEffect(() => {\n onDecorations(overlay.id, decorations);\n }, [overlay.id, decorations, onDecorations]);\n return null;\n}\n\n// PanelSlot wraps one resolved Panel in the `PanelScope` its own declared\n// `reads` need (the runtime guard that rejects an undeclared read) — every\n// rendered panel, regardless of slot, goes through this one wrapper so a\n// new panel needs no bespoke scoping at its call site. It is also the one\n// place a failed read renders: `onReadError` catches whatever\n// `useCommandRead` reports from inside `panel.Component` and shows it above\n// the panel's own content, so a panel needs only ever destructure `data`\n// (or ignore the read entirely) rather than each one deciding for itself\n// whether a failed fetch is worth a rendered word.\n//\n// A panel keyed on more than one declared read keeps one error per path — a\n// single shared slot would let a later success on one path silently clear a\n// still-failing other, or a still-failing one keep masking the other's own\n// recovery.\nfunction PanelSlot({ panel, ctx, tick }: { panel: Panel; ctx: CanvasCtx; tick: number }) {\n const [readErrors, setReadErrors] = useState<ReadonlyMap<BoundPath, Error>>(new Map());\n const onReadError = useCallback((path: BoundPath, error: Error | null) => {\n setReadErrors((prev) => {\n if (error === null) {\n if (!prev.has(path)) return prev;\n const next = new Map(prev);\n next.delete(path);\n return next;\n }\n const next = new Map(prev);\n next.set(path, error);\n return next;\n });\n }, []);\n return (\n <PanelScope\n ctx={ctx}\n paths={(panel.reads ?? []).map((r) => r.path)}\n tick={tick}\n onReadError={onReadError}\n >\n {[...readErrors].map(([path, error]) => (\n <p key={path} className=\"lace-app__panel-error\">\n Couldn't load {path}: {error.message}\n </p>\n ))}\n <panel.Component ctx={ctx} />\n </PanelScope>\n );\n}\n\n// BottomTabs (the \"bottom\" slot): at most one bottom panel visible at a\n// time, switched by a tab strip — every bottom panel is a pure view over\n// `ctx`/the ResultStore, so switching tabs mounts/unmounts a panel rather\n// than fetching anything itself.\nfunction BottomTabs({\n panels,\n ctx,\n tick,\n}: {\n panels: readonly Panel[];\n ctx: CanvasCtx;\n tick: number;\n}) {\n const [manualId, setManualId] = useState<string | null>(null);\n const manual = manualId !== null ? panels.find((p) => p.id === manualId) : undefined;\n const active = manual ?? panels[0] ?? null;\n\n if (panels.length === 0) return null;\n\n return (\n <div className=\"lace-app__bottom\">\n <div className=\"lace-app__bottom-tabs\" role=\"tablist\">\n {panels.map((panel) => (\n <button\n key={panel.id}\n type=\"button\"\n role=\"tab\"\n aria-selected={panel.id === active?.id}\n className={`lace-app__bottom-tab${panel.id === active?.id ? ' lace-app__bottom-tab--active' : ''}`}\n onClick={() => setManualId(panel.id)}\n >\n {panel.title}\n </button>\n ))}\n </div>\n <div className=\"lace-app__bottom-content\">\n {active && <PanelSlot panel={active} ctx={ctx} tick={tick} />}\n </div>\n </div>\n );\n}\n\n// What a canvas with no frame yet shows for its source's end: a failed\n// stream's own error, or the session's closing.\nfunction endMessage(end: SourceEnd): string {\n return end.kind === 'failed' ? end.error.message : 'The session was closed.';\n}\n\nexport default function App({\n ports,\n contributions = EMPTY_CONTRIBUTIONS,\n height = '100vh',\n results: hostResults,\n}: AppProps) {\n // One store, one owner: the host's when it passes one, else this mount's.\n const results = useMemo(() => hostResults ?? createResultStore(), [hostResults]);\n // The report slot's one writer: the result of every command that ran in\n // the session's root, whichever client ran it, folded under this mount's\n // own session (core/results.ts `reduceReport`), so a store the host\n // shares across canvases keeps each one's report apart. A report belongs\n // to no stack. A document the fold cannot read is a contract mismatch: it\n // is announced the way a command's own unreadable document is, and the\n // report stays as it was. The session's report goes when its\n // subscription ends.\n const writeReport = useCallback(\n (result: CommandResult, session: object) => {\n try {\n results.write('report', session, result, { stack: undefined });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n ports.presenter.notify('error', `${result.path}: ${message}`);\n }\n },\n [results, ports.presenter],\n );\n const dropReport = useCallback((session: object) => results.detach('report', session), [results]);\n const { source, end, session } = useCanvasSource(ports.source, writeReport, dropReport);\n const [arrangement, setArrangement] = useState<CanvasArrangement>(() => ports.viewState.load());\n // The stack is the host's: `context.stack` is its one source, read every\n // render, so a host that passes a `ports` object with another stack moves\n // every gate and read keyed on it (the describe overlay's `stack\n // describe`) in that same render. The canvas holds no pick of its own.\n const stack = ports.context.stack;\n const [selection, setSelection] = useState<{ nodes: readonly string[]; edge: EdgeRef | null }>(\n NO_SELECTION,\n );\n const [settingsOpen, setSettingsOpen] = useState(false);\n // The drawer shows Settings or the inspector of what is selected: Settings\n // comes first while it is open, and selecting a node or a connection\n // closes it, so the inspector of what was just picked is what shows.\n const select = useCallback((next: { nodes: readonly string[]; edge: EdgeRef | null }) => {\n setSelection(next);\n if (next.nodes.length > 0 || next.edge !== null) setSettingsOpen(false);\n }, []);\n const [pendingForm, setPendingForm] = useState<PendingForm>(null);\n const [overlayDecorations, setOverlayDecorations] = useState<Record<string, Decorations>>({});\n const layoutRef = useRef<LayoutHandle>({ panIntoView: () => {} });\n\n // The runner is keyed on the ports it closes over (`RunnerPorts`), never on\n // the `ports` object's identity: a host that passes a new object to change\n // `context.stack` keeps the runner it had, and with it every invocation\n // still running (a `run logs` follow, an in-flight apply).\n const { commands, presenter, editor } = ports;\n const runner = useMemo(\n () =>\n createActionRunner({ commands, presenter, editor }, results, {\n onPendingFormChange: setPendingForm,\n }),\n [commands, presenter, editor, results],\n );\n // Every runner instance owns its own outstanding invocations. Another\n // `commands`, `presenter` or `editor` port, or another store, replaces the\n // runner above, and unmount discards it entirely — either way the previous\n // instance's streams would otherwise keep running with nothing left to\n // read them, so this disposes the one being replaced/discarded.\n useEffect(() => {\n return () => {\n runner.dispose();\n };\n }, [runner]);\n const tick = useSyncExternalStore(results.subscribe, results.getTick);\n const updateArrangement = useCallback(\n (next: CanvasArrangement) => {\n setArrangement(next);\n ports.viewState.save(next);\n },\n [ports.viewState],\n );\n\n // A frame's Bundle may drop scopes/children the arrangement still holds\n // positions for — housekeeping, not correctness (a stale entry is simply\n // never read), so it updates local state and the host without\n // round-tripping through `updateArrangement`. Guarded on the Bundle's own\n // identity so it runs once per frame, not once per render.\n const gcSeenBundle = useRef<unknown>(null);\n if (source && gcSeenBundle.current !== source.bundle) {\n gcSeenBundle.current = source.bundle;\n const gced = gcArrangement(source.bundle, arrangement);\n if (gced !== arrangement) {\n queueMicrotask(() => {\n setArrangement(gced);\n ports.viewState.save(gced);\n });\n }\n }\n\n const view = useMemo(\n () => (source ? projectFrame(source, arrangement) : null),\n [source, arrangement],\n );\n\n // A selection names only what the frame holds: each frame that lands\n // drops from the selection what its view does not hold, whatever removed\n // it (a key, a panel's button, an undo, another client), so no inspector\n // stays open over it. Once per frame, as `gcArrangement`: a write ahead of\n // its frame (a rename's carry, `carrySelection`) keeps its copy until\n // the frame that holds it lands. Before paint, so no panel is drawn over\n // what the frame dropped. The raw setter, not `select`: dropping what is\n // gone picks nothing, so Settings stays as it is; a selection the view\n // holds whole is returned as itself and changes no state.\n const reconciledFrame = useRef<CanvasSource | null>(null);\n useLayoutEffect(() => {\n if (!source || !view || reconciledFrame.current === source) return;\n reconciledFrame.current = source;\n setSelection((current) => reconcileSelection(view, current));\n }, [source, view]);\n\n // The one read-only derivation: an editor port present and the session\n // not source-refused. Already threaded through the xyflow props and the\n // keymap below; also the `'editable'` context key (contextValue.ctx).\n const editable = ports.editor !== undefined && !source?.sourceRefused;\n\n // The core's own contributions (core/contributions.ts: the authoring set)\n // merge with whatever the host passes — no core feature bypasses the\n // registry.\n const merged = useMemo<Contributions>(\n () => ({\n overlays: [...CORE_CONTRIBUTIONS.overlays, ...contributions.overlays],\n panels: [...CORE_CONTRIBUTIONS.panels, ...contributions.panels],\n actions: [...CORE_CONTRIBUTIONS.actions, ...contributions.actions],\n }),\n [contributions],\n );\n\n // Every store write replaces the snapshot's reference, so everything\n // derived from it below re-derives the moment a slot fills or settles —\n // independent of `tick`, which only moves on `invalidates`.\n const resultSlots = useSyncExternalStore(results.subscribe, results.getSnapshot);\n const stackId = stack?.id;\n // Only the slots still about what is on screen (core/results.ts\n // `liveSlots`): this session's report while it is about the tree on\n // screen, and a run/preview of the chosen stack — anything else is gone\n // the moment that context moves.\n const live = useMemo(\n () =>\n source && session\n ? liveSlots(resultSlots, { session, treeHash: source.treeHash, stack: stackId })\n : null,\n [resultSlots, source, session, stackId],\n );\n\n // The one diagnostics list (core/diagnostics.ts): the engine's live\n // per-frame findings plus the current report's own — `decorate` and\n // every consumer of `ctx.diagnostics` (DiagnosticsPanel included) read\n // this, never `source.diagnostics` alone.\n const diagnostics = useMemo(\n () =>\n source && live\n ? diagnosticsOf(source.diagnostics, live.report ? reportDiagnostics(live.report) : [])\n : [],\n [source, live],\n );\n\n const ctx = useMemo<CanvasCtx | null>(() => {\n if (!source || !view) return null;\n return {\n ports,\n root: ports.context.root,\n sessionId: ports.context.sessionId,\n stack,\n editable,\n generating: source.generating,\n sourceRefused: source.sourceRefused,\n view,\n selection,\n settingsOpen,\n diagnostics,\n contributions: merged,\n };\n }, [ports, source, view, stack, selection, settingsOpen, merged, diagnostics, editable]);\n\n const resolved = useMemo<Contributions>(() => {\n if (!ctx) return EMPTY_CONTRIBUTIONS;\n return resolveContributions(merged, ports, ctx, NO_TARGET);\n }, [merged, ports, ctx]);\n\n const setOverlayDecoration = useCallback((id: string, next: Decorations) => {\n setOverlayDecorations((prev) => (prev[id] === next ? prev : { ...prev, [id]: next }));\n }, []);\n\n const decorations = useMemo(() => {\n if (!view || !source) return { nodes: {} };\n return decorate(view, Object.values(overlayDecorations), diagnostics);\n }, [view, source, overlayDecorations, diagnostics]);\n\n const envExtras = useMemo<EditorEnvExtras | null>(() => {\n if (!source) return null;\n return {\n bundle: source.bundle,\n arrangement: { get: () => arrangement, update: updateArrangement },\n layout: layoutRef.current,\n };\n }, [source, arrangement, updateArrangement]);\n\n const toolbar = toolbarLayout(\n resolved.actions.filter((action) => action.placement === 'toolbar'),\n resolved.panels.filter((panel) => panel.slot === 'toolbar'),\n );\n\n // The App root is the keymap's `app` target: an app-scoped key (Save)\n // is heard from the drawer and the bottom panels, siblings of\n // the canvas surface. Registered before the keymap effect below so the\n // same commit binds it.\n const rootRef = useRef<HTMLDivElement>(null);\n useEffect(() => {\n if (!ctx) return;\n registerKeyTarget(ctx, 'app', rootRef.current);\n return () => registerKeyTarget(ctx, 'app', null);\n }, [ctx]);\n // The root is focusable (`tabIndex={-1}`) and holds focus while nothing\n // else does, so a key pressed with the window focused and no element\n // focused still reaches the keymap.\n useFocusWhenNoneHeld(rootRef, Boolean(ctx && view && source && envExtras));\n\n // The one keymap, gated by focus (form controls / defaultPrevented)\n // inside the hook itself — installed once ctx/envExtras exist, torn down\n // when they don't (unmount, load error). Every resolved action with its\n // own `keys` binds, not just the toolbar's — a node-menu action (copy/\n // cut/paste/group) has no toolbar button but still owns a shortcut.\n useActionKeys(ctx && envExtras ? resolved.actions : [], ctx, runner, envExtras);\n\n if (!ctx || !view || !source || !envExtras) {\n return end ? <ErrorState message={endMessage(end)} /> : null;\n }\n\n const contextValue: CanvasContextValue = {\n ports,\n bundle: source.bundle,\n view,\n ctx,\n decorations,\n editable,\n arrangement,\n updateArrangement,\n selection,\n setSelection: select,\n runner,\n layout: layoutRef.current,\n setSettingsOpen,\n };\n\n const bannerPanels = resolved.panels.filter((panel) => panel.slot === 'banner');\n const bottomPanels = resolved.panels.filter((panel) => panel.slot === 'bottom');\n // The drawer holds one panel: the first drawer panel that resolves,\n // Settings first. Selecting closes Settings (`select`, above), but opening\n // Settings leaves the selection, so both can resolve and Settings shows; a\n // host's own drawer panel shows while neither resolves.\n const drawerPanel = resolved.panels.find((panel) => panel.slot === 'drawer');\n\n return (\n <ErrorBoundary>\n {resolved.overlays.map((overlay) => (\n <OverlayRunner\n key={overlay.id}\n overlay={overlay}\n ctx={ctx}\n tick={tick}\n onDecorations={setOverlayDecoration}\n />\n ))}\n <CanvasContext.Provider value={contextValue}>\n <div ref={rootRef} className=\"lace-app\" style={{ height }} tabIndex={-1}>\n {(toolbar.sections.length > 0 || toolbar.trailing.length > 0) && (\n <div className=\"lace-app__toolbar\">\n {toolbar.sections.map((section, index) => (\n <Fragment key={section.key ?? ''}>\n {index > 0 ? (\n <span className=\"lace-app__toolbar-separator\" aria-hidden=\"true\" />\n ) : null}\n <div className=\"lace-app__toolbar-section\">\n {section.actions.map((action) => (\n // `runner.busy` reads the store, whose every write\n // re-renders App (`resultSlots`).\n <ToolbarAction\n key={action.id}\n action={action}\n {...actionState(action, ctx, runner.busy(action, ctx, NO_TARGET))}\n emphasized={isEmphasized(action, ctx)}\n onRun={() => void runner.run(action, ctx, NO_TARGET, envExtras)}\n />\n ))}\n {section.panels.map((panel) => (\n <PanelSlot key={panel.id} panel={panel} ctx={ctx} tick={tick} />\n ))}\n </div>\n </Fragment>\n ))}\n {toolbar.trailing.length > 0 && (\n <div className=\"lace-app__toolbar-end\">\n {toolbar.trailing.map((panel) => (\n <PanelSlot key={panel.id} panel={panel} ctx={ctx} tick={tick} />\n ))}\n </div>\n )}\n </div>\n )}\n {/* A banner takes its own row between the toolbar and the canvas:\n the toolbar keeps its place when a conflict opens under the\n pointer, and the canvas gives up the row's height. */}\n <div className=\"lace-app__banners\">\n {bannerPanels.map((panel) => (\n <PanelSlot key={panel.id} panel={panel} ctx={ctx} tick={tick} />\n ))}\n </div>\n <div className=\"lace-app__body\">\n <div className=\"lace-app__main\">\n <div className=\"lace-app__canvas\">\n <ReactFlowProvider>\n <Canvas height=\"100%\" />\n </ReactFlowProvider>\n </div>\n <BottomTabs panels={bottomPanels} ctx={ctx} tick={tick} />\n </div>\n {drawerPanel && (\n <Drawer label={drawerPanel.title}>\n <PanelSlot key={drawerPanel.id} panel={drawerPanel} ctx={ctx} tick={tick} />\n </Drawer>\n )}\n </div>\n <CommandArgsForm form={pendingForm} />\n </div>\n </CanvasContext.Provider>\n </ErrorBoundary>\n );\n}\n","// xyflow's base stylesheet is part of the canvas, not of the app that\n// mounts it: `.react-flow__node` / `.react-flow__pane` / `.react-flow__panel`\n// carry the `position: absolute` that makes nodes shrink-wrap their card and\n// keeps the Controls panel above the pane. Without it, the pane paints over\n// the zoom buttons and swallows their clicks, and fitView measures a node\n// wrapper stretched to the container width. It is imported here — ahead of\n// Canvas.css, so our unlayered rules still win — so every consumer gets it\n// from the React import chain rather than remembering to import it.\nimport '@xyflow/react/dist/style.css';\nimport './Canvas.css';\nimport { drawnRect, extentOf, instanceAddress, localIn } from '@lace-cloud/proto';\nimport {\n applyEdgeChanges,\n applyNodeChanges,\n type Connection,\n type Edge,\n type EdgeChange,\n type FitViewOptions,\n type Node,\n type NodeChange,\n ReactFlow,\n type ReactFlowInstance,\n useNodesInitialized,\n useReactFlow,\n} from '@xyflow/react';\nimport type React from 'react';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport CanvasControls from './components/CanvasControls';\nimport ContextMenu from './components/ContextMenu';\nimport EmptyCanvas from './components/EmptyCanvas';\nimport { edgeTypes } from './components/edges/DependencyEdge';\nimport GroupNode from './components/nodes/GroupNode';\nimport ModuleNode from './components/nodes/ModuleNode';\nimport { NodeConfigBusProvider } from './components/nodes/node-config-bus';\nimport PaperGrid from './components/PaperGrid';\nimport type {\n ActionContribution,\n ActionTarget,\n CanvasCtx,\n EdgeRef,\n LayoutHandle,\n} from './contributions';\nimport type { DrawnDecorations } from './core/decorate';\nimport { groupTarget } from './core/editor-actions';\nimport type { EditorEnvExtras } from './core/run-binding';\nimport { isFormTarget, registerKeyTarget } from './core/use-action-keys';\nimport { type ContextMenuRequest, useContextMenu } from './hooks/useContextMenu';\nimport { drawnPosition, rfEdgeData, useGroupLogic } from './hooks/useGroupLogic';\nimport { useNewNodeTracking } from './hooks/useNewNodeTracking';\nimport { resolveContributions } from './registry';\nimport { useCanvas } from './state/canvas-context';\nimport type { CanvasView } from './types/render';\nimport { withNodePositions, withScopesPinned } from './utils/arrangement';\nimport { NODE_HANDLE, parseHandleId } from './utils/handleId';\nimport {\n computeMinimalPanDelta,\n type FlowRect,\n viewportAfterResize,\n withMargin,\n} from './utils/viewport';\n\n// ── Node types registration ──\n\nconst nodeTypes = {\n moduleNode: ModuleNode,\n groupNode: GroupNode,\n};\n\n// `edgeTypes` (DependencyEdge.tsx) registers the canvas's only edge type —\n// every RenderEdge (useGroupLogic.ts) is emitted under it so a connector's\n// path never cuts through an unrelated node, regardless of where the depth\n// layout or a drag places either endpoint.\n\n// Every way the canvas fits the whole graph — the first frame of an\n// engine, the Fit view control, a drawer that no longer leaves room for a\n// graph that was wholly in view — lands on these options, so a user who\n// pans away and fits again gets the framing they started with. A fit never\n// zooms past 100%: a three-node module is drawn at its own size, not blown\n// up to fill the pane.\nconst FIT_VIEW_OPTIONS: FitViewOptions = { padding: 0.2, duration: 300, maxZoom: 1 };\n\n// Screen pixels kept clear around a node brought into view.\nconst REVEAL_MARGIN = 24;\n\nconst NO_ENV_EXTRAS_TARGET: ActionTarget = {};\n\n// A drag joins a pin to a pin, or one node's grip to another node's card. A\n// mixed pair, or a grip dropped on its own card, is no connection, so xyflow\n// never ends one there and never hands one to `onConnect`.\nconst isValidConnection = (c: Connection | Edge) =>\n c.sourceHandle === NODE_HANDLE\n ? c.targetHandle === NODE_HANDLE && c.source !== c.target\n : c.targetHandle !== NODE_HANDLE;\n\n// The wire an xyflow edge draws, as the selection names it; null for an edge\n// this canvas did not draw.\nfunction edgeRefOf(edge: Edge): EdgeRef | null {\n const data = rfEdgeData(edge);\n if (!data) return null;\n return {\n id: edge.id,\n source: edge.source,\n target: edge.target,\n sourceOutput: data.source_output,\n targetInput: data.target_input,\n };\n}\n\n// ══════════════════════════════════════════════════════════════════════\n// CompositeEditor — renders the ReactFlow viewport for a valid graph.\n//\n// Separated from Canvas so that its hooks (useMemo for rfNodes/rfEdges)\n// only mount when a valid CanvasView exists. This avoids React's\n// \"rendered fewer hooks\" error (#300) — Canvas can safely early-return\n// the loading placeholder without skipping any hooks, because the\n// graph-dependent hooks live here and are never mounted in that path.\n// ══════════════════════════════════════════════════════════════════════\n\ntype CompositeEditorProps = {\n view: CanvasView;\n editable: boolean;\n // Every card a frame has added this session and still draws; the cards\n // among them the developer has not selected yet draw as new.\n addedIds: Set<string>;\n newNodeIds: Set<string>;\n // Whether a canvas edit is in progress (`ActionRunner.editing`).\n editing: boolean;\n // Every dragged node's position to store, by canvas path, each in the\n // frame of the scope that owns it.\n onDragStop: (positions: Record<string, { x: number; y: number }>) => void;\n onConnect: (conn: Connection) => void;\n onEdgeClick: (e: React.MouseEvent, edge: Edge) => void;\n onEdgesDelete: (edges: Edge[]) => void;\n onNodesDelete: (nodes: Node[]) => void;\n onSelectionChange: (params: { nodes: Node[]; edges: Edge[] }) => void;\n onInit: (instance: ReactFlowInstance) => void;\n onContextMenu: (request: ContextMenuRequest) => void;\n registerGoToNode: (fn: (nodeId: string) => void) => void;\n // The one shared handle (state/canvas-context.ts) every `EditorEnvExtras`\n // consumer reads — CompositeEditor is `panIntoView`'s one owner: it holds\n // the real xyflow viewport helpers, so it assigns the method directly in\n // a single effect below rather than routing through an intermediate\n // register-callback + ref that Canvas would have to re-wrap.\n layout: LayoutHandle;\n // What is selected, as node ids: the selected nodes, or a selected\n // connection's two ends. Kept in view when the pane changes size.\n focusIds: readonly string[];\n // The selection, which xyflow draws selected beside its own.\n selection: CanvasCtx['selection'];\n // The DOM node whose visible size is the pane pan-into-view measures\n // against — owned by Canvas (it wraps this component) so the measurement\n // matches exactly what `.lace-app__main`/`.lace-app__canvas`'s\n // `overflow: hidden` clips against.\n paneRef: React.RefObject<HTMLDivElement | null>;\n decorations: DrawnDecorations;\n};\n\nfunction CompositeEditor({\n view,\n editable,\n addedIds,\n newNodeIds,\n editing,\n onDragStop,\n onConnect,\n onEdgeClick,\n onEdgesDelete,\n onNodesDelete,\n onSelectionChange,\n onInit,\n onContextMenu,\n registerGoToNode,\n layout,\n focusIds,\n selection,\n paneRef,\n decorations,\n}: CompositeEditorProps) {\n const { fitView, getNode, getNodes, getNodesBounds, getViewport, setViewport } = useReactFlow();\n\n // Stable-render barrier. xyflow measures every node asynchronously after\n // mount; until that completes, `.react-flow__node` elements have no\n // transform and pin Handles haven't laid out their absolute positions.\n // `useNodesInitialized` flips to true once every visible node has\n // width/height. With zero nodes there's nothing to measure —\n // `useNodesInitialized` stays `false` forever, so an empty canvas counts\n // as rendered the moment xyflow has mounted.\n const xyflowInitialized = useNodesInitialized();\n const nodesInitialized = xyflowInitialized || view.nodes.length === 0;\n\n // Go to a node (its header clicked, opening its inspector): pan it the\n // least distance into view at the zoom the developer chose. Re-register\n // if the parent supplies a new callback or xyflow swaps out its helpers.\n useEffect(() => {\n registerGoToNode((nodeId: string) => {\n if (!getNode(nodeId)) return;\n const bounds = getNodesBounds([nodeId]);\n layout.panIntoView(withMargin(bounds, REVEAL_MARGIN, getViewport().zoom));\n });\n }, [registerGoToNode, getNode, getNodesBounds, getViewport, layout]);\n\n // When the pane changes size — the drawer opening or closing, the window\n // resizing — the camera keeps what the developer was looking at\n // (`viewportAfterResize`): a graph wholly in view stays wholly in view,\n // and what is selected stays in view.\n const focusRef = useRef(focusIds);\n focusRef.current = focusIds;\n useEffect(() => {\n const pane = paneRef.current;\n if (!pane || typeof ResizeObserver === 'undefined') return;\n let before = { width: pane.clientWidth, height: pane.clientHeight };\n let frame = 0;\n const keep = () => {\n const after = { width: pane.clientWidth, height: pane.clientHeight };\n if (after.width === before.width && after.height === before.height) return;\n const was = before;\n before = after;\n const viewport = getViewport();\n const nodes = getNodes();\n const focus = focusRef.current.filter((id) => getNode(id));\n const outcome = viewportAfterResize(\n viewport,\n was,\n after,\n nodes.length > 0 ? getNodesBounds(nodes) : null,\n focus.length > 0 ? withMargin(getNodesBounds(focus), REVEAL_MARGIN, viewport.zoom) : null,\n );\n if (outcome.kind === 'fit') void fitView(FIT_VIEW_OPTIONS);\n else if (outcome.kind === 'move') void setViewport(outcome.viewport, { duration: 200 });\n };\n // A frame later, so xyflow has taken the pane's new size too: a fit\n // measures the pane through xyflow's own store.\n const observer = new ResizeObserver(() => {\n cancelAnimationFrame(frame);\n frame = requestAnimationFrame(keep);\n });\n observer.observe(pane);\n return () => {\n cancelAnimationFrame(frame);\n observer.disconnect();\n };\n }, [paneRef, getViewport, getNodes, getNode, getNodesBounds, fitView, setViewport]);\n\n // Own `layout.panIntoView` directly — one assignment, in the one place\n // that holds the real xyflow viewport helpers, rather than Canvas relaying\n // a registered callback through its own ref. A fresh group's header can\n // extend above/beyond its members' bounds (padding for the Expand/Collapse\n // chrome) — this pans the camera by the minimal delta that clears\n // whichever edge is clipped, keeping zoom and every node's position\n // untouched.\n useEffect(() => {\n layout.panIntoView = (rect: FlowRect) => {\n const pane = paneRef.current?.getBoundingClientRect();\n if (!pane) return;\n const viewport = getViewport();\n const { dx, dy } = computeMinimalPanDelta(\n rect,\n { width: pane.width, height: pane.height },\n viewport,\n );\n if (dx === 0 && dy === 0) return;\n setViewport(\n { x: viewport.x + dx, y: viewport.y + dy, zoom: viewport.zoom },\n { duration: 300 },\n );\n };\n }, [layout, getViewport, setViewport, paneRef]);\n\n // Fit the whole graph once xyflow has measured every node. Fires once\n // per mount; a later reposition (drag, group collapse) never re-triggers\n // it because `firedRef` only resets when the component itself remounts\n // (a new source/session).\n const firedRef = useRef(false);\n useEffect(() => {\n if (firedRef.current || !nodesInitialized || view.nodes.length === 0) return;\n firedRef.current = true;\n requestAnimationFrame(() => fitView(FIT_VIEW_OPTIONS));\n }, [nodesInitialized, view.nodes.length, fitView]);\n\n // ── Nodes + Edges (group-aware) ──\n const groupLogic = useGroupLogic(view.nodes, view.edges, view.groups, newNodeIds, decorations);\n\n // Every card a frame adds — a module's or a group's — is brought into\n // view where it is drawn, the least distance at the zoom the developer\n // chose (`layout.panIntoView`), so a change made on the canvas or away\n // from it — a placement from the registry, a group, a tool's edit, an edit\n // to the tf — shows on it. A canvas edit places what it creates only once\n // its batch has settled (paste a clone in the free slot, store a new\n // group past what the layout keeps before it, ungroup the members where\n // they were drawn), so the cards that land while one is in progress are\n // brought into view once it has settled, where they are drawn then. A\n // card a collapsed group hides is not drawn, so nothing of it is brought\n // into view. What has been brought into view is kept apart from what\n // draws as new: selecting a card never brings it into view again.\n const revealedRef = useRef(addedIds);\n useEffect(() => {\n if (editing) return;\n const arrived = [...addedIds].filter((id) => !revealedRef.current.has(id));\n revealedRef.current = addedIds;\n const shown = arrived.flatMap((id) => {\n const node = groupLogic.rfNodes.find((n) => n.id === id);\n const rect = node && !node.hidden ? drawnRect(view, id) : undefined;\n return rect ? [rect] : [];\n });\n if (shown.length === 0) return;\n layout.panIntoView(withMargin(extentOf(shown), REVEAL_MARGIN, getViewport().zoom));\n }, [editing, addedIds, groupLogic.rfNodes, view, layout, getViewport]);\n\n const rfEdgesFromView = groupLogic.rfEdges;\n\n // What xyflow draws selected is what it holds selected and what the\n // selection names: a rebuild keeps both, so a frame never clears the wire\n // under the inspector, and a card a rename carried the selection to is\n // drawn selected under its new id.\n const selectedNodeIds = useMemo(() => new Set(selection.nodes), [selection.nodes]);\n const selectedEdgeId = selection.edge?.id;\n\n const [rfEdges, setRfEdges] = useState<Edge[]>(rfEdgesFromView);\n useEffect(() => {\n setRfEdges((prev) => {\n const held = new Set(prev.filter((e) => e.selected).map((e) => e.id));\n return rfEdgesFromView.map((e) =>\n held.has(e.id) || e.id === selectedEdgeId ? { ...e, selected: true } : e,\n );\n });\n }, [rfEdgesFromView, selectedEdgeId]);\n\n const onEdgesChange = useCallback((changes: EdgeChange[]) => {\n setRfEdges((prev) => applyEdgeChanges(changes, prev));\n }, []);\n\n const rfNodesFromView = groupLogic.rfNodes;\n\n const [rfNodes, setRfNodes] = useState<Node[]>(rfNodesFromView);\n\n // Every projection is drawn where it says — a drop the layout placed\n // elsewhere snaps there, a box that grew pushes its siblings at once, an\n // undo puts everything back — except a node xyflow is dragging right now,\n // which stays under the pointer. What xyflow alone knows about a node\n // (whether it is being dragged or is selected, the size it measured)\n // carries over, so a drop never clears the selection, and a node the\n // selection names is drawn selected — but a member a collapsed group hides\n // is never selected: no gesture can reach it.\n useEffect(() => {\n setRfNodes((prev) => {\n const current = new Map(prev.map((n) => [n.id, n]));\n return rfNodesFromView.map((n) => {\n const existing = current.get(n.id);\n const selected = (existing?.selected === true || selectedNodeIds.has(n.id)) && !n.hidden;\n if (!existing) return selected ? { ...n, selected } : n;\n return {\n ...n,\n position: existing.dragging ? existing.position : n.position,\n dragging: existing.dragging,\n selected,\n measured: existing.measured,\n };\n });\n });\n }, [rfNodesFromView, selectedNodeIds]);\n\n const onNodesChange = useCallback((changes: NodeChange[]) => {\n setRfNodes((prev) => applyNodeChanges(changes, prev));\n }, []);\n\n // A drop stores every dragged node where it was dropped, in the frame of\n // the scope that owns it (`localIn`): a card by its top-left, a group by\n // its anchor, so its members — stored in its own frame — move with it.\n const onNodeDragStop = useCallback(\n (_e: React.MouseEvent, _draggedNode: Node, draggedNodes: Node[]) => {\n const positions: Record<string, { x: number; y: number }> = {};\n for (const n of draggedNodes) {\n positions[n.id] = localIn(view, n.id, drawnPosition(view.groups, n));\n }\n if (draggedNodes.length > 0) onDragStop(positions);\n },\n [onDragStop, view],\n );\n\n // ── Edge defaults ──\n // Colors reference design tokens via CSS custom properties: React's inline\n // `style` resolves `var(--...)` at render time. No arrowhead: a wire\n // always runs from an output on a node's right to an input on another's\n // left, and the filled pin it lands on already says the input is wired —\n // a marker there would only sit on top of the pin.\n const defaultEdgeOptions = {\n style: { stroke: 'var(--lace-canvas-edge-stroke)', strokeWidth: 1.5 },\n animated: false,\n };\n\n return (\n <ReactFlow\n onInit={onInit}\n nodes={rfNodes}\n edges={rfEdges}\n nodeTypes={nodeTypes}\n edgeTypes={edgeTypes}\n onNodesChange={onNodesChange}\n onEdgesChange={onEdgesChange}\n onConnect={onConnect}\n isValidConnection={isValidConnection}\n onEdgeClick={onEdgeClick}\n onEdgesDelete={onEdgesDelete}\n onNodesDelete={onNodesDelete}\n onSelectionChange={onSelectionChange}\n onNodeDragStop={onNodeDragStop}\n onNodeContextMenu={(e, node) => {\n e.preventDefault();\n // With no editor port we suppress the menu entirely — every\n // current item is a mutation. Render-gate at the dispatch source\n // so ContextMenu itself stays dumb.\n if (!editable) return;\n onContextMenu({\n instanceId: node.type === 'groupNode' ? null : node.id,\n groupId: node.type === 'groupNode' ? node.id : null,\n x: e.clientX,\n y: e.clientY,\n });\n }}\n onPaneContextMenu={(e) => {\n e.preventDefault();\n if (!editable) return;\n onContextMenu({ instanceId: null, groupId: null, x: e.clientX, y: e.clientY });\n }}\n defaultEdgeOptions={defaultEdgeOptions}\n connectionRadius={30}\n minZoom={0.15}\n maxZoom={2}\n // xyflow owns connect / reconnect / key-based delete. Drive its\n // native props instead of re-implementing the gates at our\n // handler layer.\n nodesConnectable={editable}\n edgesReconnectable={editable}\n deleteKeyCode={editable ? ['Backspace', 'Delete'] : null}\n fitView={false}\n proOptions={{ hideAttribution: true }}\n style={{ background: 'var(--lace-color-bg-canvas)' }}\n >\n <CanvasControls fitViewOptions={FIT_VIEW_OPTIONS} />\n <PaperGrid />\n {nodesInitialized ? <div hidden data-rendered=\"\" /> : null}\n </ReactFlow>\n );\n}\n\n// ══════════════════════════════════════════════════════════════════════\n// Canvas — top-level component that renders the pipeline's CanvasView.\n// All IR logic lives behind `ports.editor`/`ports.commands` — we only\n// render, and every mutation runs through the one `ActionRunner`\n// (`useCanvas().runner`) — `runner.apply` for a bare xyflow gesture with no\n// registered contribution (connect/disconnect), `runner.run` for everything\n// registered (toolbar/menu/row/key).\n// ══════════════════════════════════════════════════════════════════════\n\ntype CanvasProps = {\n height: React.CSSProperties['height'];\n};\n\nexport default function Canvas({ height }: CanvasProps) {\n const {\n ctx,\n runner,\n view,\n bundle,\n decorations,\n editable,\n arrangement,\n updateArrangement,\n selection,\n setSelection,\n layout,\n } = useCanvas();\n const editor = ctx.ports.editor;\n\n const makeEnvExtras = useCallback(\n (): EditorEnvExtras => ({\n bundle,\n arrangement: { get: () => arrangement, update: updateArrangement },\n layout,\n }),\n [bundle, arrangement, updateArrangement, layout],\n );\n\n // What the camera keeps in view when the pane changes size: the selected\n // nodes, or a selected connection's two ends.\n const focusIds = useMemo(\n () => (selection.edge ? [selection.edge.source, selection.edge.target] : selection.nodes),\n [selection],\n );\n\n // ── Hooks ──\n const { contextMenu, showContextMenu, dismissContextMenu } = useContextMenu();\n\n const { addedIds, newNodeIds, clearNew } = useNewNodeTracking(view);\n\n // A card the developer selects — by a click, a drag or opening it — no\n // longer draws as new.\n useEffect(() => {\n clearNew(...selection.nodes);\n }, [selection.nodes, clearNew]);\n\n // Whether a canvas edit is in progress, held as state: the runner reports\n // an edit settling right after the edit's last write, so the render that\n // draws what the edit placed reads it settled.\n const [editing, setEditing] = useState(() => runner.editing());\n useEffect(() => {\n setEditing(runner.editing());\n return runner.onEditingChange(setEditing);\n }, [runner]);\n\n // The pane's own DOM node — pan-into-view measures its visible size\n // against this, the same element `.lace-app__main`/`.lace-app__canvas`'s\n // `overflow: hidden` clips against.\n const paneRef = useRef<HTMLDivElement>(null);\n\n // This Canvas instance's own rendered subtree is the keymap's `surface`\n // target (`useActionKeys`, called by App against the same `ctx` object) —\n // registering it here, keyed on `ctx`, means a surface-scoped Mod+C never\n // fires from a keydown whose target is outside this element (a sibling\n // run-logs or diagnostics panel's selected text), and two Canvas mounts\n // on one page each register their own surface under their own `ctx`,\n // never the other's.\n const surfaceRef = useRef<HTMLDivElement>(null);\n useEffect(() => {\n registerKeyTarget(ctx, 'surface', surfaceRef.current);\n return () => registerKeyTarget(ctx, 'surface', null);\n }, [ctx]);\n\n // Standard canvas focus behaviour: a keydown only reaches the surface's\n // own listener when the surface (or a descendant) holds DOM focus — a\n // physical keypress targets `document.activeElement`, not wherever the\n // listener happens to be attached. Clicking a node or the pane takes\n // focus here so the very next Mod+S/Mod+Z reaches the keymap; a\n // pointerdown on a form control inside one of the canvas's own panels is\n // left alone so the control keeps the focus the browser already gives it.\n const onSurfacePointerDown = useCallback((e: React.PointerEvent<HTMLDivElement>) => {\n if (isFormTarget(e.target)) return;\n surfaceRef.current?.focus();\n }, []);\n\n // Stable ref for go-to-node — set by CompositeEditor\n const goToNodeRef = useRef<((nodeId: string) => void) | null>(null);\n const registerGoToNode = useCallback((fn: (nodeId: string) => void) => {\n goToNodeRef.current = fn;\n }, []);\n\n // ModuleNode's header click reaches this through `NodeConfigBusProvider`\n // (below) instead of a window `CustomEvent` — selecting the node opens\n // the module-config inspector panel (App's `selection.node`-gated slot),\n // and go-to-node re-centers the camera on it.\n const onOpenNodeConfig = useCallback(\n (instanceId: string) => {\n setSelection({ nodes: [instanceId], edge: null });\n goToNodeRef.current?.(instanceId);\n },\n [setSelection],\n );\n\n // ── Event: drag stop → write positions into the arrangement ──\n // Position is consumer-owned view state — it never touches the wire in\n // either mode, so drag persists identically whether editable or not\n // (unlike an IR mutation, there's nothing to gate). The Bundle is needed\n // to resolve each dragged canvas-path id to its (scopeKey, localId)\n // arrangement slot; the positions arrive already in that scope's frame.\n // A drop first stores what is around it where it is drawn\n // (`withScopesPinned`): each stays there unless what was dragged takes its\n // room, when it steps down just past that, and a box the drop grows grows\n // from where it is.\n const onDragStop = useCallback(\n (positions: Record<string, { x: number; y: number }>) => {\n const pinned = Object.keys(positions).reduce(\n (next, id) => withScopesPinned(bundle, view, next, id),\n arrangement,\n );\n updateArrangement(withNodePositions(bundle, pinned, positions));\n },\n [bundle, view, arrangement, updateArrangement],\n );\n\n // ── Event: new connection — connect/auto-connect have no registered\n // contribution (nothing places them on a toolbar/menu/key), so this\n // gesture goes straight through `runner.apply`, never `runner.run`. The\n // handles the drag joined pick the action: `node` to `node` is an\n // auto_connect, an output pin to an input pin a connect. xyflow calls this\n // only with a pair `isValidConnection` accepted, so a drag from the grip\n // ended on another node's card. The action names\n // each endpoint in the scope that owns it (`instanceAddress`): a wire is\n // an edit of one module, so a drag across a group's boundary names two\n // scopes and the engine refuses it, which the runner shows. The canvas\n // holds no wiring rule of its own: a drag onto an input that is already\n // bound is sent too, and the engine's connect replaces the binding as one\n // undoable edit.\n const onConnect = useCallback(\n async (conn: Connection) => {\n if (!conn.source || !conn.target || !editor) return;\n\n const source = instanceAddress(bundle, conn.source);\n const target = instanceAddress(bundle, conn.target);\n const ends = {\n scope: target.scope,\n source_scope: source.scope,\n source: source.id,\n target: target.id,\n };\n\n if (conn.sourceHandle === NODE_HANDLE) {\n await runner.apply([{ auto_connect: ends }]);\n return;\n }\n\n const srcName = parseHandleId(conn.sourceHandle, 'out');\n const tgtName = parseHandleId(conn.targetHandle, 'in');\n if (!srcName || !tgtName) return;\n\n await runner.apply([{ connect: { ...ends, source_output: srcName, target_input: tgtName } }]);\n },\n [editor, runner, bundle],\n );\n\n // ── Event: edge click → selects it, opening the edge-inspector panel ──\n const onEdgeClick = useCallback(\n (_e: React.MouseEvent, edge: Edge) => {\n const ref = edgeRefOf(edge);\n if (ref) setSelection({ nodes: [], edge: ref });\n },\n [setSelection],\n );\n\n // ── Event: edge delete — disconnect has no registered contribution. A\n // disconnect names the deleted edge's target in the scope that owns it.\n const onEdgesDelete = useCallback(\n async (edges: Edge[]) => {\n for (const edge of edges) {\n const data = rfEdgeData(edge);\n if (!data) continue;\n const target = instanceAddress(bundle, edge.target);\n await runner.apply([\n { disconnect: { scope: target.scope, target: target.id, input_name: data.target_input } },\n ]);\n }\n },\n [runner, bundle],\n );\n\n // ── Event: node delete (Backspace/Delete with a selection, or the\n // context menu) — every id routes through the registered `delete-node`\n // editor action via the runner, which itself falls back to `ungroup` for\n // a group node — one migration path, not a second copy of it here.\n const onNodesDelete = useCallback(\n async (nodes: Node[]) => {\n const action = ctx.contributions.actions.find((a) => a.id === 'delete-node');\n if (!action) return;\n const envExtras = makeEnvExtras();\n for (const node of nodes) {\n await runner.run(action, ctx, { nodeId: node.id }, envExtras);\n }\n },\n [ctx, runner, makeEnvExtras],\n );\n\n // What xyflow reports selected is the selection: its nodes, and its wire\n // when xyflow reports one wire alone. The selection names nodes or one\n // wire, so several wires, or wires beside nodes, name no wire.\n const onSelectionChange = useCallback(\n (params: { nodes: Node[]; edges: Edge[] }) => {\n const [wire, ...more] = params.edges;\n setSelection({\n nodes: params.nodes.map((n) => n.id),\n edge: wire && more.length === 0 && params.nodes.length === 0 ? edgeRefOf(wire) : null,\n });\n },\n [setSelection],\n );\n\n // ── Menu resolution — what the menu opened on decides its placement and\n // target: a node or a group opens the `node-menu` with it as the target,\n // the empty canvas the `pane-menu` with none.\n const menuTarget: ActionTarget = contextMenu\n ? contextMenu.groupId\n ? groupTarget(contextMenu.groupId)\n : { nodeId: contextMenu.nodeId ?? undefined }\n : NO_ENV_EXTRAS_TARGET;\n const menuActions = useMemo<readonly ActionContribution[]>(() => {\n if (!contextMenu) return [];\n const placement = menuTarget.nodeId === undefined ? 'pane-menu' : 'node-menu';\n return resolveContributions(ctx.contributions, ctx.ports, ctx, menuTarget).actions.filter(\n (a) => a.placement === placement,\n );\n }, [contextMenu, ctx, menuTarget]);\n\n const runMenuAction = useCallback(\n (action: ActionContribution) => {\n void runner.run(action, ctx, menuTarget, makeEnvExtras());\n },\n [runner, ctx, menuTarget, makeEnvExtras],\n );\n\n // ── Render ──\n // Inline layout instead of Tailwind utilities so this works in Storybook\n // (Tailwind v4 only scans canvas-stories, not @lace-cloud/canvas).\n // Children rely on the outer explicit height to place xyflow's docked\n // panels correctly — without it the ReactFlow container collapses. `App`\n // defaults it to the viewport for a canvas that owns the window; a host\n // panel that establishes its own height passes `100%`.\n return (\n <NodeConfigBusProvider onOpen={onOpenNodeConfig}>\n <div\n ref={surfaceRef}\n className=\"lace-canvas-surface\"\n tabIndex={0}\n onPointerDown={onSurfacePointerDown}\n style={{\n position: 'relative',\n display: 'flex',\n flexDirection: 'column',\n height,\n outline: 'none',\n }}\n >\n <ContextMenu\n contextMenu={contextMenu}\n actions={menuActions}\n onRun={runMenuAction}\n onDismiss={dismissContextMenu}\n />\n\n <div ref={paneRef} style={{ position: 'relative', flex: '1 1 auto', minHeight: 0 }}>\n <CompositeEditor\n view={view}\n editable={editable}\n addedIds={addedIds}\n newNodeIds={newNodeIds}\n editing={editing}\n onDragStop={onDragStop}\n onConnect={onConnect}\n onEdgeClick={onEdgeClick}\n onEdgesDelete={onEdgesDelete}\n onNodesDelete={onNodesDelete}\n onSelectionChange={onSelectionChange}\n onInit={() => {}}\n onContextMenu={showContextMenu}\n registerGoToNode={registerGoToNode}\n layout={layout}\n focusIds={focusIds}\n selection={selection}\n paneRef={paneRef}\n decorations={decorations}\n />\n {view.nodes.length === 0 && view.groups.length === 0 ? (\n <EmptyCanvas editable={editable} />\n ) : null}\n </div>\n </div>\n </NodeConfigBusProvider>\n );\n}\n","// The canvas's view controls — zoom out, the zoom level, zoom in, fit, the\n// minimap toggle — as one compact bar, the minimap above it while shown.\n// Both dock bottom-left: the toolbar holds the top edge and the drawer\n// opens on the right, its resize handle on that edge, so the bottom-left is\n// the one corner no other chrome claims or moves. View chrome, not\n// capabilities: these change what the developer sees, never the module,\n// so they render in every host, read-only ones included. Mounted as a\n// child of `ReactFlow`.\nimport { IconButton } from '@lace-cloud/ui';\nimport {\n type FitViewOptions,\n Panel as FlowPanel,\n MiniMap,\n type ReactFlowState,\n useReactFlow,\n useStore,\n} from '@xyflow/react';\nimport { useState } from 'react';\nimport { CanvasIcon } from './icons';\nimport './CanvasControls.css';\n\nconst zoomOf = (s: ReactFlowState) => s.transform[2];\nconst STEP = { duration: 150 };\n\nexport default function CanvasControls({ fitViewOptions }: { fitViewOptions: FitViewOptions }) {\n const { zoomIn, zoomOut, fitView } = useReactFlow();\n const zoom = useStore(zoomOf);\n const [showMiniMap, setShowMiniMap] = useState(false);\n return (\n <>\n {showMiniMap ? (\n <MiniMap\n position=\"bottom-left\"\n className=\"lace-canvas-minimap\"\n maskColor=\"var(--lace-canvas-minimap-mask)\"\n nodeColor=\"var(--lace-canvas-minimap-node)\"\n nodeStrokeWidth={0}\n pannable\n zoomable\n />\n ) : null}\n <FlowPanel position=\"bottom-left\" className=\"lace-canvas-controls\">\n <IconButton\n icon={<CanvasIcon name=\"zoom-out\" />}\n aria-label=\"Zoom out\"\n tooltipPlacement=\"top-start\"\n onClick={() => void zoomOut(STEP)}\n />\n <span className=\"lace-canvas-controls__zoom\" aria-live=\"polite\">\n {Math.round(zoom * 100)}%\n </span>\n <IconButton\n icon={<CanvasIcon name=\"zoom-in\" />}\n aria-label=\"Zoom in\"\n tooltipPlacement=\"top-start\"\n onClick={() => void zoomIn(STEP)}\n />\n <span className=\"lace-canvas-controls__rule\" aria-hidden=\"true\" />\n <IconButton\n icon={<CanvasIcon name=\"fit\" />}\n aria-label=\"Fit view\"\n tooltipPlacement=\"top-start\"\n onClick={() => void fitView(fitViewOptions)}\n />\n <IconButton\n icon={<CanvasIcon name=\"minimap\" />}\n aria-label=\"Minimap\"\n tooltipPlacement=\"top-start\"\n pressed={showMiniMap}\n onClick={() => setShowMiniMap((v) => !v)}\n />\n </FlowPanel>\n </>\n );\n}\n","// The canvas's glyphs, in Lace's house style — the portal's own icon\n// contract (apps/portal/src/components/icons): 24-unit outlines, a 1.5\n// stroke with round caps and joins, nothing filled. At the 16px a toolbar\n// draws them that is a one-pixel line, the weight of VS Code's Codicons, so\n// the chrome sits in either host. Each glyph is drawn at the size of the\n// text around it, in the current colour: a control's token colour\n// (muted, hover, disabled, primary) is its glyph's.\nimport type { ReactElement } from 'react';\nimport type { ActionIcon } from '../contribution-types';\nimport './icons.css';\n\nexport type CanvasGlyph =\n | ActionIcon\n | 'settings'\n | 'warning'\n | 'error'\n | 'info'\n | 'chevron-down'\n | 'chevron-right'\n | 'module'\n | 'group'\n | 'close'\n | 'minimap'\n | 'zoom-in'\n | 'zoom-out'\n | 'fit'\n | 'add';\n\nconst CIRCLE = 'M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0z';\n\nconst GLYPHS: Record<CanvasGlyph, readonly string[]> = {\n // A tick in a circle: the tree checks out.\n validate: [CIRCLE, 'm8.5 12.5 2.5 2.5 4.5-5'],\n // Two opposed arrows: the module turned from one form into the other.\n convert: ['M8 3 4 7l4 4', 'M4 7h16', 'm16 21 4-4-4-4', 'M20 17H4'],\n save: [\n 'M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z',\n 'M17 21v-8H7v8',\n 'M7 3v5h8',\n ],\n // A wand: the saved IR made into the module's Terraform.\n generate: [\n 'm3 21 9-9',\n 'M15 4V2',\n 'M15 16v-2',\n 'M8 9h2',\n 'M20 9h2',\n 'M17.8 11.8 19 13',\n 'M17.8 6.2 19 5',\n 'M12.2 6.2 11 5',\n ],\n undo: ['M9 14 4 9l5-5', 'M4 9h10.5a5.5 5.5 0 0 1 0 11H11'],\n redo: ['m15 14 5-5-5-5', 'M20 9H9.5a5.5 5.5 0 0 0 0 11H13'],\n clear: [\n 'M3 6h18',\n 'M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6',\n 'M10 11v6',\n 'M14 11v6',\n 'M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2',\n ],\n settings: [\n 'M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z',\n 'M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z',\n ],\n warning: [\n 'M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z',\n 'M12 9v4',\n 'M12 17h.01',\n ],\n error: [CIRCLE, 'M12 8v4', 'M12 16h.01'],\n info: [CIRCLE, 'M12 16v-4', 'M12 8h.01'],\n 'chevron-down': ['m6 9 6 6 6-6'],\n 'chevron-right': ['m9 18 6-6-6-6'],\n // A box: one module call.\n module: [\n 'M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z',\n 'M3.27 6.96 12 12.01l8.73-5.05',\n 'M12 22.08V12',\n ],\n // Two boxes inside a frame's corners: calls held in one group.\n group: [\n 'M3 7V5a2 2 0 0 1 2-2h2',\n 'M17 3h2a2 2 0 0 1 2 2v2',\n 'M21 17v2a2 2 0 0 1-2 2h-2',\n 'M7 21H5a2 2 0 0 1-2-2v-2',\n 'M8 7h5a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1z',\n 'M11 12h5a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1h-5a1 1 0 0 1-1-1v-3a1 1 0 0 1 1-1z',\n ],\n close: ['M18 6 6 18', 'm6 6 12 12'],\n minimap: ['M1 6v16l7-4 8 4 7-4V2l-7 4-8-4-7 4z', 'M8 2v16', 'M16 6v16'],\n 'zoom-in': ['M12 5v14', 'M5 12h14'],\n 'zoom-out': ['M5 12h14'],\n // Four corners closing on the view: fit it to the graph.\n fit: [\n 'M3 8V5a2 2 0 0 1 2-2h3',\n 'M16 3h3a2 2 0 0 1 2 2v3',\n 'M21 16v3a2 2 0 0 1-2 2h-3',\n 'M8 21H5a2 2 0 0 1-2-2v-3',\n ],\n add: ['M12 5v14', 'M5 12h14'],\n};\n\nexport function CanvasIcon({ name }: { name: CanvasGlyph }): ReactElement {\n return (\n <svg className=\"lace-canvas-icon\" viewBox=\"0 0 24 24\" aria-hidden=\"true\" focusable=\"false\">\n {GLYPHS[name].map((d) => (\n <path key={d} d={d} />\n ))}\n </svg>\n );\n}\n","// ContextMenu renders the menu contributions Canvas.tsx resolved for what\n// it opened on — the `node-menu` for a node or a group, the `pane-menu`\n// for the empty canvas — in their sections, a rule between sections and a\n// removing action in the danger tone (core/sections.ts). It owns no\n// copy/cut/paste/group semantics of its own, so a host-supplied menu action\n// renders exactly the way a core one does.\n//\n// It opens at the pointer and keeps all of itself inside the window: before\n// it paints, it measures its own box and moves to where `placeFloating`\n// (@lace-cloud/ui) puts a box hung from the pointer — upward when the\n// pointer is near the bottom, left when near the right, capped and scrolling\n// when taller than the window —\n// and it closes when the window it was placed in resizes or loses focus.\nimport { type FloatingPosition, placeFloating } from '@lace-cloud/ui';\nimport type React from 'react';\nimport { Fragment, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport type { ActionContribution } from '../contributions';\nimport { sectionsOf } from '../core/sections';\nimport type { ContextMenuState } from '../hooks/useContextMenu';\nimport { formatChord, isMacPlatform } from '../utils/key-chord';\nimport './ContextMenu.css';\n\n// The point a menu opens at, as the box it hangs from.\nconst atPoint = (x: number, y: number) => ({ left: x, right: x, top: y, bottom: y });\n\nfunction naturalSize(menu: HTMLElement): { width: number; height: number } {\n const box = menu.getBoundingClientRect();\n const borders = menu.offsetHeight - menu.clientHeight;\n return { width: box.width, height: Math.max(box.height, menu.scrollHeight + borders) };\n}\n\n// `Object.is`, so a placement that is not a number (an event that carried no\n// pointer coordinates) still equals itself and the menu settles.\nfunction samePlacement(a: FloatingPosition | null, b: FloatingPosition | null): boolean {\n return (\n a === b ||\n (a !== null &&\n b !== null &&\n Object.is(a.left, b.left) &&\n Object.is(a.top, b.top) &&\n Object.is(a.maxHeight, b.maxHeight))\n );\n}\n\ntype Props = {\n contextMenu: ContextMenuState;\n actions: readonly ActionContribution[];\n onRun: (action: ActionContribution) => void;\n onDismiss: () => void;\n};\n\nexport default function ContextMenu({ contextMenu, actions, onRun, onDismiss }: Props) {\n const menuRef = useRef<HTMLDivElement>(null);\n const [placement, setPlacement] = useState<FloatingPosition | null>(null);\n\n // After every render, before the browser paints: whatever the menu now\n // holds and wherever it opened, place it. Its natural height is its\n // content's (`scrollHeight` plus its borders), not the capped box an\n // earlier placement left it with.\n useLayoutEffect(() => {\n const menu = menuRef.current;\n const next =\n contextMenu && menu\n ? placeFloating(\n atPoint(contextMenu.x, contextMenu.y),\n naturalSize(menu),\n { width: window.innerWidth, height: window.innerHeight },\n 'bottom-start',\n { gap: 0, margin: 0 },\n )\n : null;\n setPlacement((current) => (samePlacement(current, next) ? current : next));\n });\n\n // A menu is placed for the window it opened in: a resize (a sash drag, a\n // panel toggled) or the window losing focus closes it rather than\n // leaving it placed for a window that has changed.\n const open = contextMenu !== null;\n useEffect(() => {\n if (!open) return;\n window.addEventListener('resize', onDismiss);\n window.addEventListener('blur', onDismiss);\n return () => {\n window.removeEventListener('resize', onDismiss);\n window.removeEventListener('blur', onDismiss);\n };\n }, [open, onDismiss]);\n\n // Keyboard: the first item takes focus as the menu opens; the arrows,\n // Home and End move between items; Escape and Tab close it.\n useEffect(() => {\n if (open) menuRef.current?.querySelector<HTMLButtonElement>('[role=\"menuitem\"]')?.focus();\n }, [open]);\n const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n e.stopPropagation();\n const items = Array.from(\n menuRef.current?.querySelectorAll<HTMLButtonElement>('[role=\"menuitem\"]') ?? [],\n );\n const at = items.findIndex((item) => item === document.activeElement);\n const focus = (index: number) => {\n e.preventDefault();\n items[(index + items.length) % items.length]?.focus();\n };\n if (e.key === 'ArrowDown') focus(at + 1);\n else if (e.key === 'ArrowUp') focus(at - 1);\n else if (e.key === 'Home') focus(0);\n else if (e.key === 'End') focus(items.length - 1);\n else if (e.key === 'Escape' || e.key === 'Tab') {\n e.preventDefault();\n onDismiss();\n }\n };\n\n if (!contextMenu) return null;\n const at = placement ?? { left: contextMenu.x, top: contextMenu.y };\n\n return (\n <>\n <div\n ref={menuRef}\n className=\"lace-ctx-menu\"\n role=\"menu\"\n style={{ left: at.left, top: at.top, maxHeight: placement?.maxHeight }}\n onMouseDown={(e) => e.stopPropagation()}\n onKeyDown={onKeyDown}\n >\n {sectionsOf(actions).map((section, index) => (\n <Fragment key={section.key ?? ''}>\n {index > 0 ? <hr className=\"lace-ctx-menu__separator\" /> : null}\n {section.actions.map((action) => {\n const chord = action.keys?.[0]\n ? formatChord(action.keys[0], isMacPlatform())\n : undefined;\n return (\n <button\n key={action.id}\n type=\"button\"\n role=\"menuitem\"\n className={`lace-ctx-menu__item${action.tone === 'danger' ? ' lace-ctx-menu__item--danger' : ''}`}\n onClick={() => {\n onRun(action);\n onDismiss();\n }}\n >\n <span>{action.label}</span>\n {chord ? <span className=\"lace-ctx-menu__shortcut\">{chord}</span> : null}\n </button>\n );\n })}\n </Fragment>\n ))}\n </div>\n <div className=\"lace-ctx-menu__scrim\" onClick={onDismiss} />\n </>\n );\n}\n","// How the toolbar and the menus arrange what resolved into them: actions in\n// sections by intent (`ActionContribution.section`), in the order each\n// section first appears, the actions naming none as one section after the\n// named ones. The toolbar also places its panels: each at the end of the\n// section it names, and those naming none (or a section no action resolved\n// into) at the row's far end. Both draw a hairline between sections.\nimport type { ActionContribution, PanelSpec } from '../contribution-types';\nimport { keySatisfied } from '../registry';\n\nexport type Section = {\n key: string | undefined;\n actions: readonly ActionContribution[];\n};\n\nexport function sectionsOf(actions: readonly ActionContribution[]): Section[] {\n const named = new Map<string, ActionContribution[]>();\n const unnamed: ActionContribution[] = [];\n for (const action of actions) {\n if (action.section === undefined) {\n unnamed.push(action);\n continue;\n }\n named.set(action.section, [...(named.get(action.section) ?? []), action]);\n }\n const sections: Section[] = [...named].map(([key, held]) => ({ key, actions: held }));\n if (unnamed.length > 0) sections.push({ key: undefined, actions: unnamed });\n return sections;\n}\n\nexport type ToolbarSection<P extends PanelSpec> = Section & { panels: readonly P[] };\n\nexport type ToolbarLayout<P extends PanelSpec> = {\n sections: readonly ToolbarSection<P>[];\n trailing: readonly P[];\n};\n\nexport function toolbarLayout<P extends PanelSpec>(\n actions: readonly ActionContribution[],\n panels: readonly P[],\n): ToolbarLayout<P> {\n const sections = sectionsOf(actions);\n const keys = new Set(\n sections.flatMap((section) => (section.key === undefined ? [] : [section.key])),\n );\n const placed = (panel: P) => panel.section !== undefined && keys.has(panel.section);\n return {\n sections: sections.map((section) => ({\n ...section,\n panels: panels.filter((panel) => placed(panel) && panel.section === section.key),\n })),\n trailing: panels.filter((panel) => !placed(panel)),\n };\n}\n\ntype KeyCtx = Parameters<typeof keySatisfied>[0];\n\n// Whether a primary action draws in the accent now: while its\n// `primary.when` holds, or always when it names none.\nexport function isEmphasized(action: ActionContribution, ctx: KeyCtx): boolean {\n if (!action.primary) return false;\n return action.primary.when === undefined || keySatisfied(ctx, action.primary.when);\n}\n","// The keymap's grammar for an action's key (`ActionContribution.keys`), read\n// and spelled in one place: `Mod`, an optional `Shift`, then the key —\n// `Mod+s`, `Mod+Shift+z`. The keymap (core/use-action-keys.ts) matches a\n// press by `parseChord`; the toolbar's tooltips and the menus spell it with\n// `formatChord`.\n\n/** The type an action's `keys` hold: a key that starts with `Mod+`. It is the\n * grammar's prefix check alone — the type cannot spell an optional `Shift`\n * then one key — and `parseChord` refuses the rest at runtime. */\nexport type KeySpec = `Mod+${string}`;\n\n/** A `keys` entry, read: whether it holds Shift, and the literal key. */\nexport type Chord = { shift: boolean; key: string };\n\n/**\n * The one parser of the grammar. `Mod` matches metaKey or ctrlKey on any\n * platform (the convention xyflow's own docs use). Undefined for an entry\n * outside the grammar, which no press matches.\n */\nexport function parseChord(spec: string): Chord | undefined {\n const [mod, ...rest] = spec.split('+');\n if (mod !== 'Mod') return undefined;\n if (rest.length === 1 && rest[0] !== '') return { shift: false, key: rest[0] };\n if (rest.length === 2 && rest[0] === 'Shift' && rest[1] !== '') {\n return { shift: true, key: rest[1] };\n }\n return undefined;\n}\n\n// How a key reads to the person pressing it. The keymap matches `Mod` on ⌘\n// or Ctrl on any platform; macOS spells it ⌘, after ⇧ in Apple's order\n// (⇧⌘Z), and elsewhere it is Ctrl, the names joined with `+`\n// (Ctrl+Shift+Z). Undefined for an entry outside the grammar, which no\n// press runs.\nexport function formatChord(spec: string, mac: boolean): string | undefined {\n const chord = parseChord(spec);\n if (!chord) return undefined;\n const key = chord.key.length === 1 ? chord.key.toUpperCase() : chord.key;\n if (mac) return `${chord.shift ? '⇧' : ''}⌘${key}`;\n return ['Ctrl', ...(chord.shift ? ['Shift'] : []), key].join('+');\n}\n\n// Whether the canvas runs on macOS, where `Mod` is spelled ⌘.\nexport function isMacPlatform(): boolean {\n return typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.userAgent);\n}\n","// What a canvas with nothing on it says, centred on the paper: that the\n// module calls no other modules, and on an editable canvas what a module\n// added to it becomes. It names no host's way of adding one; each host has\n// its own. It takes no pointer events, so the paper under it still pans and\n// still opens its menu (Paste).\nimport { EmptyState } from '@lace-cloud/ui';\nimport { CanvasIcon } from './icons';\nimport './EmptyCanvas.css';\n\nexport default function EmptyCanvas({ editable }: { editable: boolean }) {\n return (\n <div className=\"lace-canvas-empty\">\n <EmptyState\n icon={<CanvasIcon name=\"module\" />}\n title={\n editable ? 'This module calls no other modules yet' : 'This module calls no other modules'\n }\n description={\n editable\n ? 'A module you add lands here with its inputs and outputs, ready to wire.'\n : undefined\n }\n />\n </div>\n );\n}\n","// DependencyEdge.tsx — the canvas's only edge type. Endpoints stay on the\n// pin handles xyflow computed (sourceX/Y, targetX/Y) — see\n// dependency-edge-path.ts for why the path between them sometimes has to\n// loop rather than follow the stock bezier. Styling (stroke, selection,\n// hover) is identical to xyflow's default edge: it comes from\n// `defaultEdgeOptions`/CSS in Canvas.tsx, not from anything here.\n\nimport { BaseEdge, type EdgeProps, type EdgeTypes, useStore } from '@xyflow/react';\nimport { type Box, computeDependencyEdgePath } from './dependency-edge-path';\nimport { obstaclesFor } from './obstacles-for';\nimport { sceneNodesEqual, selectSceneNodes } from './scene-nodes';\n\n/** The `type` every RenderEdge is emitted with (useGroupLogic.ts) and the\n * key Canvas.tsx registers this component under — one name, so an edge\n * cannot be emitted under a type no renderer is registered for. */\nexport const DEPENDENCY_EDGE_TYPE = 'dependency';\n\nexport default function DependencyEdge({\n id,\n source,\n target,\n sourceX,\n sourceY,\n targetX,\n targetY,\n sourcePosition,\n targetPosition,\n style,\n markerStart,\n markerEnd,\n}: EdgeProps) {\n // Subscribed, not read once: a node this edge must bow around can move\n // without any prop of the edge changing (see scene-nodes.ts).\n const sceneNodes = useStore(selectSceneNodes, sceneNodesEqual);\n\n // An endpoint absent from the scene (an edge that arrived a frame before\n // its node) collapses to a point at its handle, so the path helper still\n // has a box to reason about.\n const endpointBox = (nodeId: string, x: number, y: number): Box =>\n sceneNodes.find((n) => n.id === nodeId)?.box ?? { x, y, width: 0, height: 0 };\n\n // Obstacle candidates are scope-resolved by `obstaclesFor`, not just\n // \"every other top-level node\" — a node inside an expanded group only\n // obstructs edges sharing its scope, and a group's own box is never an\n // obstacle for an edge leaving that same group (see obstacles-for.ts).\n const { path, labelX, labelY } = computeDependencyEdgePath({\n sourceX,\n sourceY,\n targetX,\n targetY,\n sourcePosition,\n targetPosition,\n sourceBox: endpointBox(source, sourceX, sourceY),\n targetBox: endpointBox(target, targetX, targetY),\n obstacleBoxes: obstaclesFor({ sourceId: source, targetId: target }, sceneNodes),\n });\n\n return (\n <BaseEdge\n id={id}\n path={path}\n labelX={labelX}\n labelY={labelY}\n style={style}\n markerStart={markerStart}\n markerEnd={markerEnd}\n // A test hook: the one thing that distinguishes this\n // connector's rendered path from xyflow's stock edge in the DOM.\n data-edge-kind=\"dependency\"\n />\n );\n}\n\n/** What Canvas.tsx hands xyflow as `edgeTypes`. */\nexport const edgeTypes = { [DEPENDENCY_EDGE_TYPE]: DependencyEdge } satisfies EdgeTypes;\n","// dependency-edge-path.ts — pure geometry for the canvas's directional\n// connector. Handle facing is fixed by side (inputs on a node's left,\n// outputs on its right — ModuleNode.tsx, GroupNode.tsx) regardless of\n// where the depth layout or a drag places either node, so the path from a\n// source OUTPUT handle to a target INPUT handle must always depart the\n// source heading +x and arrive at the target heading +x — that is the only\n// tangent pair that leaves an output and enters an input. xyflow's\n// stock bezier keeps that tangent pair by construction only while the\n// target sits to the right of the source; once it doesn't (a stored\n// arrangement or a drag places the consumer left of its source — the\n// BACKWARD shape), the same formula overshoots into a degenerate curve\n// that enters the input from the wrong side. And a bezier that IS forward can still cut\n// straight through an unrelated node sitting between source and target\n// (the SKIP-LEVEL shape). Both are solved the same way here: keep the\n// endpoints on the pin handles (never float them) and, whenever the\n// straight run between them isn't clear, route a straight-legged loop\n// through a vertical \"clearance rail\" that sits outside the vertical\n// extent of whatever it needs to clear, held at a horizontal offset\n// outside the box it just departed — each leg is a literal line segment\n// (not a bezier control point), which is what lets every leg's\n// box-clearance be proven from its own endpoints rather than from where a\n// curve merely passes near.\n\nimport { getBezierPath, type Position } from '@xyflow/react';\n\nexport type Box = { x: number; y: number; width: number; height: number };\nexport type Point = { x: number; y: number };\n\nexport type DependencyEdgePathParams = {\n sourceX: number;\n sourceY: number;\n targetX: number;\n targetY: number;\n sourcePosition: Position;\n targetPosition: Position;\n /** The source node's own box, in the same coordinate space as sourceX/Y. */\n sourceBox: Box;\n /** The target node's own box, in the same coordinate space as targetX/Y. */\n targetBox: Box;\n /**\n * Every other node's box that could sit between source and target — a\n * skip-level edge is bowed around whichever of these its straight\n * run would otherwise cross. Source's and target's own boxes are never\n * part of this list; they are handled via sourceBox/targetBox instead.\n */\n obstacleBoxes: readonly Box[];\n};\n\nexport type DependencyEdgePathResult = {\n path: string;\n labelX: number;\n labelY: number;\n};\n\n// LOOP_STUB is the horizontal run at each end of a bowed/looped path before\n// it turns toward the clearance rail — it exists solely to hold the\n// departure/arrival tangent at +x (see file header) for however many\n// pixels the SVG renders as a straight run before curving.\nconst LOOP_STUB = 24;\n// CLEARANCE is the margin every clearance rail keeps past the vertical\n// extent of whatever box (or pair of boxes) it clears.\nconst CLEARANCE = 24;\n\nfunction boxTop(b: Box): number {\n return b.y;\n}\nfunction boxBottom(b: Box): number {\n return b.y + b.height;\n}\nfunction boxLeft(b: Box): number {\n return b.x;\n}\nfunction boxRight(b: Box): number {\n return b.x + b.width;\n}\n\n// segmentCrossesBox is a coarse (bounding-box) overlap test between the\n// straight run [p0,p1] and a box — enough to decide whether a forward edge\n// needs to bow around an intermediate node, since the stock bezier between\n// two same-row nodes is itself nearly straight.\nfunction segmentCrossesBox(p0: Point, p1: Point, box: Box): boolean {\n const segMinX = Math.min(p0.x, p1.x);\n const segMaxX = Math.max(p0.x, p1.x);\n const segMinY = Math.min(p0.y, p1.y);\n const segMaxY = Math.max(p0.y, p1.y);\n return (\n segMaxX >= boxLeft(box) &&\n segMinX <= boxRight(box) &&\n segMaxY >= boxTop(box) &&\n segMinY <= boxBottom(box)\n );\n}\n\n// chooseClearanceY picks the vertical rail — above the topmost box's top\n// edge, or below the bottommost box's bottom edge, whichever is the\n// shorter detour from `referenceY` — so the loop always clears every box\n// in `boxes` by CLEARANCE regardless of which side it settles on.\nfunction chooseClearanceY(boxes: readonly Box[], referenceY: number): number {\n const top = Math.min(...boxes.map(boxTop));\n const bottom = Math.max(...boxes.map(boxBottom));\n const aboveDist = referenceY - top;\n const belowDist = bottom - referenceY;\n return aboveDist <= belowDist ? top - CLEARANCE : bottom + CLEARANCE;\n}\n\n/**\n * loopWaypoints returns the six points of the straight-legged loop shared\n * by the backward case and the forward-with-obstacle case, in order:\n * `source`, out to `railX1` at source's own y, up/down to `clearanceY`,\n * across to `railX2` at `clearanceY`, down/up to target's own y, into\n * `target`. Exported so the regression test walks the exact geometry\n * `loopedPath` renders rather than re-deriving it.\n */\nexport function loopWaypoints(\n source: Point,\n target: Point,\n railX1: number,\n railX2: number,\n clearanceY: number,\n): [Point, Point, Point, Point, Point, Point] {\n return [\n source,\n { x: railX1, y: source.y },\n { x: railX1, y: clearanceY },\n { x: railX2, y: clearanceY },\n { x: railX2, y: target.y },\n target,\n ];\n}\n\n// loopedPath renders `loopWaypoints` as a straight-legged SVG path (`L`\n// between each waypoint). Every leg is a literal line segment, so each\n// leg's box-clearance is a property of its own two endpoints — outside\n// its own endpoint's box (the source/target stub legs) or outside every\n// relevant box's y-range entirely (the clearanceY leg) — not of a curve\n// that merely passes near the waypoints without touching them.\nfunction loopedPath(\n source: Point,\n target: Point,\n railX1: number,\n railX2: number,\n clearanceY: number,\n): DependencyEdgePathResult {\n const points = loopWaypoints(source, target, railX1, railX2, clearanceY);\n const path = points.map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x},${p.y}`).join(' ');\n return { path, labelX: (railX1 + railX2) / 2, labelY: clearanceY };\n}\n\n/**\n * computeDependencyEdgePath is the single pure function behind\n * `DependencyEdge`: given both endpoints' handle points/positions and the\n * boxes that matter (source, target, everything else on the canvas), it\n * returns an SVG path that always departs the source heading +x and\n * arrives at the target heading +x.\n *\n * - Backward (target sits left of source): loops above or below BOTH\n * node boxes via a clearance rail held outside their combined box range.\n * - Forward and clear: the stock xyflow bezier, unchanged.\n * - Forward but blocked (a skip-level edge over an intermediate\n * node): the same loop shape, railed around whichever obstacle box(es)\n * the straight run would otherwise cross.\n */\nexport function computeDependencyEdgePath(\n params: DependencyEdgePathParams,\n): DependencyEdgePathResult {\n const {\n sourceX,\n sourceY,\n targetX,\n targetY,\n sourcePosition,\n targetPosition,\n sourceBox,\n targetBox,\n obstacleBoxes,\n } = params;\n const source: Point = { x: sourceX, y: sourceY };\n const target: Point = { x: targetX, y: targetY };\n\n // xyflow's bezier curvature offset overshoots specifically once\n // target.x < source.x.\n if (targetX < sourceX) {\n const clearanceY = chooseClearanceY([sourceBox, targetBox], (sourceY + targetY) / 2);\n const railX1 = boxRight(sourceBox) + CLEARANCE;\n const railX2 = boxLeft(targetBox) - CLEARANCE;\n return loopedPath(source, target, railX1, railX2, clearanceY);\n }\n\n const blocking = obstacleBoxes.filter((box) => segmentCrossesBox(source, target, box));\n if (blocking.length === 0) {\n const [path, labelX, labelY] = getBezierPath({\n sourceX,\n sourceY,\n sourcePosition,\n targetX,\n targetY,\n targetPosition,\n });\n return { path, labelX, labelY };\n }\n\n const clearanceY = chooseClearanceY(blocking, (sourceY + targetY) / 2);\n const railX1 = sourceX + LOOP_STUB;\n const railX2 = targetX - LOOP_STUB;\n return loopedPath(source, target, railX1, railX2, clearanceY);\n}\n","// obstacles-for.ts — pure scope resolution for `computeDependencyEdgePath`'s\n// `obstacleBoxes`. A box is only a genuine obstacle if it sits\n// in the same rendering scope as the edge it might block:\n//\n// - Two top-level nodes: every OTHER top-level box is a candidate — an\n// expanded group renders as one box on that same top-level canvas, so it\n// counts as a single obstacle the same as any module node.\n// - Two siblings inside the same expanded group: only their fellow\n// siblings in that group are candidates. A top-level node three group\n// widths away is nowhere near the edge and would never legitimately\n// block it.\n// - A cross-boundary edge (a node inside an expanded group wired to\n// something outside it): candidates are every top-level box PLUS the\n// inside endpoint's siblings — the edge visually crosses both scopes,\n// so both scopes' boxes are in play.\n//\n// Whichever candidates that scope resolution produces, one rule prunes\n// them down to genuine obstacles: a box that CONTAINS either endpoint is\n// never an obstacle. Without it, an edge leaving an expanded group would\n// see its own enclosing container as something to bow around — every edge\n// leaving a group would loop around the group it just left.\n\nimport type { Box } from './dependency-edge-path';\n\nexport type SceneNode = {\n id: string;\n box: Box;\n /** Absent/undefined for a top-level node; the enclosing group's id for a\n * node rendered inside an expanded group. */\n parentId?: string;\n};\n\nexport type SceneEdge = {\n sourceId: string;\n targetId: string;\n};\n\nconst TOP_LEVEL = Symbol('top-level scope');\n\nfunction scopeOf(node: SceneNode): string | typeof TOP_LEVEL {\n return node.parentId ?? TOP_LEVEL;\n}\n\nfunction boxContains(outer: Box, inner: Box): boolean {\n return (\n outer.x <= inner.x &&\n outer.y <= inner.y &&\n outer.x + outer.width >= inner.x + inner.width &&\n outer.y + outer.height >= inner.y + inner.height\n );\n}\n\nexport function obstaclesFor(edge: SceneEdge, nodes: readonly SceneNode[]): Box[] {\n const byId = new Map(nodes.map((n) => [n.id, n]));\n const source = byId.get(edge.sourceId);\n const target = byId.get(edge.targetId);\n if (!source || !target) return [];\n\n const sourceScope = scopeOf(source);\n const targetScope = scopeOf(target);\n\n const candidates = new Map<string, SceneNode>();\n const addScope = (scope: string | typeof TOP_LEVEL) => {\n for (const n of nodes) {\n if (scopeOf(n) === scope) candidates.set(n.id, n);\n }\n };\n\n if (sourceScope === TOP_LEVEL && targetScope === TOP_LEVEL) {\n addScope(TOP_LEVEL);\n } else if (sourceScope === targetScope) {\n addScope(sourceScope);\n } else {\n // Cross-boundary: the edge is visible on the top-level canvas AND\n // inside whichever group its inside endpoint belongs to.\n addScope(TOP_LEVEL);\n if (sourceScope !== TOP_LEVEL) addScope(sourceScope);\n if (targetScope !== TOP_LEVEL) addScope(targetScope);\n }\n\n candidates.delete(source.id);\n candidates.delete(target.id);\n\n return [...candidates.values()]\n .map((n) => n.box)\n .filter((box) => !boxContains(box, source.box) && !boxContains(box, target.box));\n}\n","// scene-nodes.ts — the xyflow store read `DependencyEdge` routes from, as a\n// selector plus its equality. An edge's own props (its two handle points)\n// change only when ITS endpoints move; the boxes it must bow around belong\n// to other nodes, and a drag of one of those changes nothing xyflow hands\n// the edge. So the boxes are subscribed to through the store, compared by\n// value: the edge re-renders exactly when a visible node's box or scope\n// changes, and not on the store writes (selection, viewport, hover) that\n// move no box.\n\nimport type { InternalNode, ReactFlowState } from '@xyflow/react';\nimport type { Box } from './dependency-edge-path';\nimport type { SceneNode } from './obstacles-for';\n\n/**\n * A node's box in flow coordinates. A node not yet measured (first paint,\n * before xyflow's ResizeObserver has reported its size) has no size, so its\n * box collapses to a point at its position — enough for the path helper to\n * reason about until layout settles a frame later.\n */\nexport function nodeBox(node: InternalNode): Box {\n return {\n x: node.internals.positionAbsolute.x,\n y: node.internals.positionAbsolute.y,\n width: node.measured.width ?? 0,\n height: node.measured.height ?? 0,\n };\n}\n\n/** Every visible node's id, scope and box, in lookup order. */\nexport function selectSceneNodes(state: Pick<ReactFlowState, 'nodeLookup'>): SceneNode[] {\n const scene: SceneNode[] = [];\n for (const node of state.nodeLookup.values()) {\n if (node.hidden) continue;\n scene.push({ id: node.id, parentId: node.parentId, box: nodeBox(node) });\n }\n return scene;\n}\n\nfunction sameBox(a: Box, b: Box): boolean {\n return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;\n}\n\n/** True when no box, scope or membership differs — the render is skipped. */\nexport function sceneNodesEqual(a: readonly SceneNode[], b: readonly SceneNode[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((node, i) => {\n const other = b[i];\n return node.id === other.id && node.parentId === other.parentId && sameBox(node.box, other.box);\n });\n}\n","import {\n COLLAPSED_GROUP_WIDTH,\n collapsedGroupSize,\n GROUP_HEADER_HEIGHT,\n groupPinY,\n NODE_ROW_HEIGHT,\n} from '@lace-cloud/proto';\nimport { Handle, type Node, type NodeProps, Position } from '@xyflow/react';\nimport type React from 'react';\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type { Badge } from '../../contributions';\nimport { groupTarget } from '../../core/editor-actions';\nimport { useEditorEnvExtras } from '../../core/panels/row-actions';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { NodePin } from '../../types/render';\nimport { withGroupCollapsed } from '../../utils/arrangement';\nimport { CanvasIcon } from '../icons';\nimport './GroupNode.css';\nimport { useRenameInstance } from './use-rename-instance';\n\n// ── Data contract ──\n\n// One pin of a collapsed group's interface, on its card's rail.\nexport type InterfacePin = NodePin & {\n handleId: string; // e.g. \"out:vpc_id\"\n side: 'input' | 'output';\n color: { fill: string; stroke: string };\n};\n\nexport type GroupNodeData = {\n groupId: string;\n // The target module the group Use points at. Every group is a Use\n // whose target has its own sub-Uses (CreateGroupAction mints a\n // module) — this is that module's key, needed to migrate the group's\n // interior arrangement back to the parent scope on ungroup.\n moduleKey: string;\n label: string;\n memberCount: number;\n collapsed: boolean;\n hasErrors: boolean;\n // Badges the diagnostics decoration attached to this group's own scope —\n // `nodeIdForAddress` resolves a submodule-root address to the group's\n // own id, not any member's, so these are the one place that decoration\n // is visible at all while collapsed (every member's own badge is\n // hidden). Same chip shape ModuleNode's own `badges` renders.\n badges: readonly Badge[];\n interfacePins: InterfacePin[];\n};\n\ntype GroupNodeNode = Node<GroupNodeData, 'groupNode'>;\n\n// ── Layout constants ──\n\n// The group's geometry is the projection's (proto geometry.ts): its\n// collapsed card is drawn here at `collapsedGroupSize`, each pin's row\n// centred at `groupPinY`, where the layout lands its wire; its expanded box\n// at the size the projection gives the xyflow node (useGroupLogic).\n\n// ── Shared header ──\n\ntype GroupHeaderProps = {\n label: string;\n memberCount: number;\n collapsed: boolean;\n hovered: boolean;\n editing: boolean;\n editValue: string;\n inputRef: React.RefObject<HTMLInputElement>;\n onToggleCollapsed: (e: React.MouseEvent) => void;\n onUngroup: (e: React.MouseEvent) => void;\n onDoubleClick: (e: React.MouseEvent) => void;\n onEditChange: (value: string) => void;\n onEditBlur: () => void;\n onEditKeyDown: (e: React.KeyboardEvent) => void;\n};\n\nconst GroupHeader: React.FC<GroupHeaderProps> = ({\n label,\n memberCount,\n collapsed,\n hovered,\n editing,\n editValue,\n inputRef,\n onToggleCollapsed,\n onUngroup,\n onDoubleClick,\n onEditChange,\n onEditBlur,\n onEditKeyDown,\n}) => (\n <div\n className={`lace-group-node__header lace-group-node__header--${collapsed ? 'collapsed' : 'expanded'}`}\n style={collapsed ? { height: GROUP_HEADER_HEIGHT } : undefined}\n >\n <button\n type=\"button\"\n onClick={onToggleCollapsed}\n className=\"lace-group-node__collapse-btn\"\n title={collapsed ? 'Expand' : 'Collapse'}\n aria-label={collapsed ? 'Expand' : 'Collapse'}\n >\n <CanvasIcon name={collapsed ? 'chevron-right' : 'chevron-down'} />\n </button>\n <span className=\"lace-group-node__glyph\">\n <CanvasIcon name=\"group\" />\n </span>\n\n {editing ? (\n <input\n ref={inputRef}\n value={editValue}\n onChange={(e) => onEditChange(e.target.value)}\n onBlur={onEditBlur}\n onKeyDown={onEditKeyDown}\n className=\"lace-group-node__rename-input\"\n onClick={(e) => e.stopPropagation()}\n />\n ) : (\n <span className=\"lace-group-node__label\" onDoubleClick={onDoubleClick} title={label}>\n {label}\n </span>\n )}\n\n <span className=\"lace-group-node__count\">\n {memberCount} {memberCount === 1 ? 'module' : 'modules'}\n </span>\n\n {hovered && (\n <button\n type=\"button\"\n onClick={onUngroup}\n className=\"lace-group-node__ungroup-btn\"\n title=\"Ungroup\"\n aria-label=\"Ungroup\"\n >\n <CanvasIcon name=\"close\" />\n </button>\n )}\n </div>\n);\n\n// ── Badges: same chip shape and `data-badge`/`data-tone` contract\n// ModuleNode's own badge row renders — a diagnostic addressed to this\n// group's own scope is otherwise invisible while collapsed. ──\n\nconst GroupBadges: React.FC<{ badges: readonly Badge[] }> = ({ badges }) =>\n badges.length === 0 ? null : (\n <div className=\"lace-group-node__badges\">\n {badges.map((b) => (\n <span\n key={b.id}\n data-badge={b.id}\n data-tone={b.tone}\n className={`lace-group-node__badge lace-group-node__badge--${b.tone}`}\n title={b.title ?? b.label}\n >\n {b.label}\n </span>\n ))}\n </div>\n );\n\n// ── Interface pin row (collapsed state) ──\n\n// One pin's row on the card, centred on `y` from the card's top\n// (`groupPinY`), where the layout lands its wire.\nconst InterfacePinRow: React.FC<{ pin: InterfacePin; y: number }> = ({ pin, y }) => {\n const isInput = pin.side === 'input';\n return (\n <div\n style={{\n position: 'absolute',\n top: y - NODE_ROW_HEIGHT / 2,\n left: 0,\n right: 0,\n height: NODE_ROW_HEIGHT,\n paddingLeft: isInput ? 12 : 8,\n paddingRight: isInput ? 8 : 12,\n display: 'flex',\n alignItems: 'center',\n justifyContent: isInput ? 'flex-start' : 'flex-end',\n }}\n title={pin.name}\n >\n <Handle\n id={pin.handleId}\n type={isInput ? 'target' : 'source'}\n position={isInput ? Position.Left : Position.Right}\n isConnectable={false}\n className=\"lace-pin-handle\"\n style={{\n background: pin.color.fill,\n borderColor: pin.color.stroke,\n borderWidth: 1,\n borderStyle: 'solid',\n width: 10,\n height: 10,\n [isInput ? 'left' : 'right']: -5,\n top: NODE_ROW_HEIGHT / 2,\n }}\n />\n <span className=\"lace-group-node__pin-label\" style={{ maxWidth: COLLAPSED_GROUP_WIDTH - 28 }}>\n {pin.name}\n </span>\n </div>\n );\n};\n\n// ── Component ──\n\nconst GroupNode: React.FC<NodeProps<GroupNodeNode>> = ({ data }) => {\n const { editable, ctx, runner, bundle, arrangement, updateArrangement } = useCanvas();\n const rename = useRenameInstance();\n const envExtras = useEditorEnvExtras();\n const [editing, setEditing] = useState(false);\n const [editValue, setEditValue] = useState(data.label);\n const [hovered, setHovered] = useState(false);\n const inputRef = useRef<HTMLInputElement>(null);\n\n // `data.collapsed` is the projection's: the arrangement's collapsed\n // state, read into the view by `projectCanvasView`, so there is nothing\n // to derive here.\n const collapsed = data.collapsed;\n\n useEffect(() => {\n if (editing && inputRef.current) {\n inputRef.current.focus();\n inputRef.current.select();\n }\n }, [editing]);\n\n const onDoubleClick = useCallback(\n (e: React.MouseEvent) => {\n if (!editable) return;\n e.stopPropagation();\n setEditValue(data.label);\n setEditing(true);\n },\n [data.label, editable],\n );\n\n // A group's one name is its Use id, so renaming it renames the instance\n // in the scope that owns it — the same rename a module node sends\n // (`useRenameInstance`) — and the group keeps its place, its collapsed\n // state and its selection under the new name.\n const renamingRef = useRef(false);\n const commitRename = useCallback(async () => {\n if (renamingRef.current) return;\n renamingRef.current = true;\n setEditing(false);\n await rename(data.groupId, editValue.trim());\n renamingRef.current = false;\n }, [editValue, data.groupId, rename]);\n\n const onKeyDown = useCallback(\n (e: React.KeyboardEvent) => {\n e.stopPropagation();\n if (e.key === 'Enter') commitRename();\n else if (e.key === 'Escape') setEditing(false);\n },\n [commitRename],\n );\n\n const toggleCollapsed = useCallback(\n (e: React.MouseEvent) => {\n e.stopPropagation();\n updateArrangement(withGroupCollapsed(bundle, arrangement, data.groupId, !data.collapsed));\n },\n [bundle, data.groupId, data.collapsed, arrangement, updateArrangement],\n );\n\n // Ungroup runs the registered `ungroup` contribution through the runner —\n // the identical migration path (arrangement migration included) the node\n // menu's own Ungroup entry uses, so a failure takes the runner's one\n // error path (`presenter.notify`) instead of a console log nobody sees.\n const onUngroup = useCallback(\n async (e: React.MouseEvent) => {\n e.stopPropagation();\n const action = ctx.contributions.actions.find((a) => a.id === 'ungroup');\n if (!action) return;\n await runner.run(action, ctx, groupTarget(data.groupId), envExtras);\n },\n [ctx, runner, envExtras, data.groupId],\n );\n\n const headerProps = {\n label: data.label,\n memberCount: data.memberCount,\n collapsed,\n hovered: hovered && editable,\n editing,\n editValue,\n inputRef,\n onToggleCollapsed: toggleCollapsed,\n onUngroup,\n onDoubleClick,\n onEditChange: setEditValue,\n onEditBlur: commitRename,\n onEditKeyDown: onKeyDown,\n };\n\n // ── Collapsed rendering ──\n\n if (collapsed) {\n const inputs = data.interfacePins.filter((p) => p.side === 'input');\n const outputs = data.interfacePins.filter((p) => p.side === 'output');\n const bare = data.interfacePins.length === 0;\n\n return (\n <div\n data-group={data.groupId}\n data-collapsed=\"true\"\n className={`lace-group-node lace-group-node--collapsed${bare ? ' lace-group-node--bare' : ''}${data.hasErrors ? ' lace-group-node--error' : ''}`}\n style={collapsedGroupSize({ inputs, outputs })}\n onMouseEnter={() => setHovered(true)}\n onMouseLeave={() => setHovered(false)}\n >\n <GroupHeader {...headerProps} />\n <GroupBadges badges={data.badges} />\n {inputs.map((pin, i) => (\n <InterfacePinRow key={pin.handleId} pin={pin} y={groupPinY(i)} />\n ))}\n {outputs.map((pin, i) => (\n <InterfacePinRow key={pin.handleId} pin={pin} y={groupPinY(i)} />\n ))}\n </div>\n );\n }\n\n // ── Expanded rendering ──\n\n return (\n <div\n data-group={data.groupId}\n data-collapsed=\"false\"\n className=\"lace-group-node lace-group-node--expanded\"\n style={{ width: '100%', height: '100%' }}\n onMouseEnter={() => setHovered(true)}\n onMouseLeave={() => setHovered(false)}\n >\n <GroupHeader {...headerProps} />\n <GroupBadges badges={data.badges} />\n </div>\n );\n};\n\nexport default GroupNode;\n","// The editor bindings: every IR edit / generate / conflict-resolution the\n// canvas core registers, bound the same way a command is — through\n// `EditorBinding` (contributions.ts) — so a mutation the toolbar, a node\n// menu, or a keybinding fires runs through the one `ActionRunner` execution\n// path (confirm → invoke → route → tick), never a direct `ports.editor`\n// call from a component. `run()` bodies are pure functions of `EditorEnv`:\n// copy/cut/paste/group/ungroup source their selection from `ctx.selection`/\n// `target.nodeId`, never an imperative xyflow ref, so the identical binding\n// runs from a node-menu click, a keybinding, or any future host contribution.\nimport {\n boxAt,\n drawnRect,\n extentOf,\n freeSlot,\n groupBoxSize,\n groupPins,\n groupReach,\n instanceAddress,\n joinPath,\n type KeepKey,\n keepOrder,\n localIn,\n originAt,\n type Rect,\n reachRect,\n splitPath,\n stepDown,\n type XY,\n} from '@lace-cloud/proto';\nimport type { ActionContribution, ActionTarget, EditorBinding, EditorEnv } from '../contributions';\nimport { Reason } from '../generated/service';\nimport type { Bundle } from '../generated/state';\nimport { type ApplyResult, type CreatedRef, currentFrame, type GenerateEvent } from '../ports';\nimport type { CanvasArrangement, CanvasView } from '../types/render';\nimport { migrateUngroup, setScopeEntry, withScopesPinned } from '../utils/arrangement';\nimport { entryScopeIds, inEntryScope } from './entry-scope';\n\nfunction emptyApplyResult(message?: string): ApplyResult {\n if (!message) return { success: true, errors: [], created: [], ties: [] };\n return {\n success: false,\n errors: [\n { moduleKey: '', instanceId: '', inputName: '', message, reason: Reason.REASON_UNSPECIFIED },\n ],\n created: [],\n ties: [],\n };\n}\n\n// Every copy/cut source is the selection the host reports through\n// `ctx.selection`, plus the node the context menu was opened on when that\n// node isn't already part of it, narrowed to the ids the engine addresses:\n// the entry scope's own (`entryScopeIds`). When that narrowing leaves\n// nothing there is no source, and `refusal` names which of the two causes\n// it was — nothing was chosen, or everything chosen sits inside a group —\n// read off the chosen ids against their entry-scope part.\ntype CopySource = { ids: readonly string[] } | { refusal: string };\n\nfunction copySource(env: EditorEnv): CopySource {\n const selected = env.ctx.selection.nodes;\n const menuId = env.target.nodeId;\n const chosen = menuId && !selected.includes(menuId) ? [...selected, menuId] : selected;\n const ids = inEntryScope(env.ctx.view, chosen);\n if (ids.length > 0) return { ids };\n return {\n refusal:\n chosen.length === 0\n ? 'Nothing selected — click a node first'\n : 'The selection is inside a group — copy and cut act on top-level nodes and groups',\n };\n}\n\n// placeCreatedClones positions every pasted clone from the mutation's\n// `created` refs (never by diffing before/after CanvasView frames — the\n// CreatedRef contract exists precisely so callers don't have to guess\n// which ids are new). A paste addresses the entry scope, so its clones and\n// their sources are the entry's. The clones are one cluster: each drawn\n// where its source is, relative to the others. The cluster's extent is\n// everything the clones can draw — a card's rect, a group's reach, its card\n// and its expanded box alike (`reachRect`). Expanding a pasted group later\n// takes its room as its source's does, over a card of its own cluster too;\n// what that pushes depends on what is around it. The cluster takes the\n// scope's free slot for that extent (`freeSlot`), clear of everything the\n// scope draws by the layout's gap; and the scope is pinned where it is drawn\n// (`withScopesPinned`), so the paste moves nothing already there.\nfunction placeCreatedClones(\n bundle: Bundle,\n view: CanvasView,\n arrangement: CanvasArrangement,\n created: readonly CreatedRef[],\n): CanvasArrangement {\n // Each source by what it can draw and the position that draws it there: a\n // group's is its anchor, its box reaching past it as its members do — as\n // the clone's will, sharing the source's module.\n const sources = new Map<string, { sourceId: string; rect: Rect; stored: XY }>();\n for (const ref of created) {\n const rect =\n ref.scope === bundle.entry && ref.sourceId ? reachRect(view, ref.sourceId) : undefined;\n if (rect) {\n sources.set(ref.id, {\n sourceId: ref.sourceId,\n rect,\n stored: localIn(view, ref.sourceId, rect),\n });\n }\n }\n const first = sources.values().next().value;\n if (!first) return arrangement;\n const extent = extentOf([...sources.values()].map((s) => s.rect));\n const occupied = entryScopeIds(view).flatMap((id) => drawnRect(view, id) ?? []);\n const slot = freeSlot(extent, occupied);\n\n const pinned = withScopesPinned(bundle, view, arrangement, first.sourceId);\n const scopeEntry = pinned[bundle.entry] ?? {};\n const placed: Record<string, XY> = {};\n for (const [id, { stored }] of sources) {\n placed[id] = { x: slot.x - extent.x + stored.x, y: slot.y - extent.y + stored.y };\n }\n return setScopeEntry(pinned, bundle.entry, {\n ...scopeEntry,\n nodes: { ...scopeEntry.nodes, ...placed },\n });\n}\n\nasync function saveRun(env: EditorEnv): Promise<void> {\n // No \"Saved\" notify — the Unsaved marker clearing (App.tsx) is the status.\n await env.editor.save();\n}\n\nfunction generateRun(env: EditorEnv): AsyncIterable<GenerateEvent> {\n return env.editor.generate();\n}\n\n// Run only while the frame holds an edit to undo or redo: the runner refuses\n// Undo and Redo otherwise (their `enabledWhen`), saying so.\nasync function undoRun(env: EditorEnv): Promise<ApplyResult> {\n return env.apply([{ undo: {} }]);\n}\n\nasync function redoRun(env: EditorEnv): Promise<ApplyResult> {\n return env.apply([{ redo: {} }]);\n}\n\n// One `apply` batch with one delete per entry-scope node and group — a\n// single undo entry, not a loop of N separate ApplyAction calls. Deleting a\n// group Use deletes its children with it, so the batch addresses the entry\n// alone.\nasync function clearGraphRun(env: EditorEnv): Promise<ApplyResult> {\n const ids = entryScopeIds(env.ctx.view);\n if (ids.length === 0) return emptyApplyResult();\n const scope = env.bundle.entry;\n return env.apply(ids.map((id) => ({ delete_instance: { scope, instance_id: id } })));\n}\n\n// Copy and cut are the same clipboard write; `cut` marks the sources for\n// deletion in the batch a paste sends.\nfunction clipRun(cut: boolean): (env: EditorEnv) => Promise<void> {\n return async (env) => {\n const source = copySource(env);\n if ('refusal' in source) {\n env.ctx.ports.presenter.notify('error', source.refusal);\n return;\n }\n const { ids } = source;\n env.clipboard.set(ids, cut);\n env.ctx.ports.presenter.notify(\n 'info',\n `${cut ? 'Cut' : 'Copied'} ${ids.length} node${ids.length > 1 ? 's' : ''}`,\n );\n };\n}\n\nasync function pasteRun(env: EditorEnv): Promise<ApplyResult> {\n const clip = env.clipboard.get();\n if (!clip) {\n env.ctx.ports.presenter.notify('error', 'Clipboard empty — copy a node first');\n return emptyApplyResult();\n }\n const { ids, cut } = clip;\n // The clipboard holds entry-scope ids (`copySource`), so the batch\n // addresses the entry. Cut+paste is the clone plus every original's own\n // delete in the ONE apply batch (one undo entry) — a cut+paste an undo\n // has to walk back through N+1 entries because the deletes were N\n // separate calls is the same \"N+1 undo entries\" this batches away.\n const scope = env.bundle.entry;\n const actions = cut\n ? [\n { copy_instances: { scope, instance_ids: [...ids] } },\n ...ids.map((id) => ({ delete_instance: { scope, instance_id: id } })),\n ]\n : [{ copy_instances: { scope, instance_ids: [...ids] } }];\n const result = await env.apply(actions);\n if (!result.success) return result;\n\n const created = result.created.filter((c) => c.sourceId);\n if (created.length === 0) {\n if (!cut) {\n // The engine reported success but named no created children — the\n // user has no visual feedback to lean on otherwise. Cut + paste runs\n // into this naturally when the clone reuses freed ids; left alone.\n env.ctx.ports.presenter.notify('error', 'Paste produced no new nodes — nothing pasted');\n }\n } else {\n env.arrangement.update(\n placeCreatedClones(env.bundle, env.ctx.view, env.arrangement.get(), created),\n );\n }\n\n if (cut) env.clipboard.clear();\n return result;\n}\n\n// CreateGroupAction's wire payload carries only membership. The server\n// reports the minted module via `result.created` (one CreatedRef: scope =\n// the parent scope the group was created in, id = the new group Use's id,\n// moduleKey = the new module). The group's members' frame starts where the\n// top-left-most member is drawn, so every member — a card or a group,\n// stored or laid out — is stored in the new module's scope where it is\n// drawn now, keeping their arrangement, and the group itself in the\n// parent's frame at its anchor, its header and padding up and left of them\n// (`boxAt`). Inside a group's scope the anchor is first lowered, if need\n// be, to the top of what the enclosing group holds — its members and its\n// members' frame origin, which its box always holds (`originAt`) — so the\n// enclosing group grows left, right or down by the padding to hold it,\n// never up. A member group's collapsed\n// state moves with it, and everything in the scopes around the write is\n// stored where it is drawn (`withScopesPinned`). A fresh group is collapsed.\n//\n// The group is placed for everything it can draw: its card, sized from the\n// interface the engine minted (the frame `apply` settled on,\n// `currentFrame`), and its expanded box, its members' drawn extent with its\n// padding (`groupReach`). It steps down its column (`stepDown`), its members\n// with it, past everything the layout keeps before it (`keepOrder`: drawn\n// above its anchor, or level and left of it, or at its anchor and declared\n// first) until nothing more comes before it, so it is drawn where it is stored,\n// collapsed and expanded alike: Group moves nothing the layout keeps before\n// the new group. What its room covers after it, the layout steps down just\n// past it, in order (`layoutByDepth`) — a card closer than the group's\n// padding beside the selection steps down rather than sideways. An\n// enclosing group that grows into what its own scope keeps before it steps\n// down past that, the new group with it. Group brings nothing into view of\n// its own: the canvas brings the card the frame adds into view once the\n// edit has settled, where Group stored it.\n//\n// A group is made in one scope: the scope that owns the first selected\n// node. A selected node another scope owns is sent as it was addressed, so\n// the engine refuses the selection by naming it.\nasync function groupRun(env: EditorEnv): Promise<ApplyResult> {\n const ids = env.ctx.selection.nodes;\n if (ids.length < 2) {\n env.ctx.ports.presenter.notify('error', 'Select at least two nodes to group');\n return emptyApplyResult();\n }\n const { scope } = instanceAddress(env.bundle, ids[0]);\n const nodeIds = ids.map((id) => {\n const address = instanceAddress(env.bundle, id);\n return address.scope === scope ? address.id : id;\n });\n const result = await env.apply([{ create_group: { scope, node_ids: nodeIds } }]);\n if (!result.success) return result;\n\n const created = result.created[0];\n if (!created?.moduleKey) return result;\n const frame = await currentFrame(env.ctx.ports.source);\n const minted = frame?.bundle.modules[created.moduleKey];\n if (!minted) {\n throw new Error(`Group: the source delivered no module ${created.moduleKey} after the apply`);\n }\n\n const view = env.ctx.view;\n const before = withScopesPinned(env.bundle, view, env.arrangement.get(), ids[0]);\n const parentEntry = before[created.scope] ?? {};\n const drawn = ids.flatMap((id) => {\n const rect = drawnRect(view, id);\n return rect ? [{ id, localId: splitPath(id).localId, rect }] : [];\n });\n if (drawn.length === 0) return result;\n\n // The members' frame starts where the top-left-most member is drawn.\n const members = extentOf(drawn.map((m) => m.rect));\n const origin = { x: members.x, y: members.y };\n const memberGroups = Object.fromEntries(\n drawn.flatMap(({ localId }) => {\n const entry = parentEntry.groups?.[localId];\n return entry ? [[localId, entry]] : [];\n }),\n );\n const next = setScopeEntry(before, created.moduleKey, {\n nodes: Object.fromEntries(\n drawn.map(({ id, localId, rect }) => [localId, localIn(view, id, rect, origin)]),\n ),\n groups: Object.keys(memberGroups).length > 0 ? memberGroups : undefined,\n });\n\n const reach = groupReach(groupPins(minted), groupBoxSize(members));\n const { parentPath } = splitPath(ids[0]);\n const groupPath = joinPath(parentPath, created.id);\n // Where each of the scope's Uses stands among its declarations once the\n // group is made.\n const declared = new Map(\n (frame.bundle.modules[created.scope]?.modules ?? []).map((use, i) => [use.id, i]),\n );\n const keyOf = (id: string, at: XY): KeepKey => ({ ...at, declared: declared.get(id) ?? 0 });\n const selected = new Set(ids);\n const others = [...view.nodes, ...view.groups].flatMap(({ id }) => {\n const { parentPath: scopePath, localId } = splitPath(id);\n const rect = selected.has(id) || scopePath !== parentPath ? undefined : drawnRect(view, id);\n return rect ? [{ rect, key: keyOf(localId, rect) }] : [];\n });\n // Inside a group, no higher than the top of what that group holds now:\n // its members and its members' frame origin.\n const enclosing = view.groups.find((g) => g.id === parentPath);\n const wanted = boxAt(origin);\n let anchor = enclosing\n ? { x: wanted.x, y: Math.max(wanted.y, originAt(enclosing.position).y) }\n : wanted;\n // Past what the layout keeps before the group at its anchor. A step only\n // goes down, so that set only grows, and the steps end.\n for (let moved = true; moved; ) {\n const groupKey = keyOf(created.id, anchor);\n const keptFirst = others.filter((o) => keepOrder(o.key, groupKey) < 0).map((o) => o.rect);\n const stepped = stepDown(anchor, reach, keptFirst);\n moved = stepped.y !== anchor.y;\n anchor = stepped;\n }\n const written = setScopeEntry(next, created.scope, {\n nodes: { ...parentEntry.nodes, [created.id]: localIn(view, groupPath, anchor) },\n groups: { ...parentEntry.groups, [created.id]: { collapsed: true } },\n });\n env.arrangement.update(written);\n return result;\n}\n\n// What an action on a group addresses: the group, as a node of its scope\n// and as the group (`groupId`, which Ungroup requires).\nexport function groupTarget(id: string): ActionTarget {\n return { nodeId: id, groupId: id };\n}\n\n// Shared by the \"Ungroup\" node-menu action and delete-node's own\n// group-node branch — both dissolve the group the same way, storing every\n// member where it is drawn in the parent scope (`migrateUngroup`).\nasync function ungroupRun(env: EditorEnv): Promise<ApplyResult> {\n const groupId = env.target.groupId;\n if (!groupId) return emptyApplyResult();\n const group = env.ctx.view.groups.find((g) => g.id === groupId);\n const address = instanceAddress(env.bundle, groupId);\n const result = await env.apply([{ ungroup: { scope: address.scope, group_id: address.id } }]);\n if (result.success && group?.module_key) {\n env.arrangement.update(\n migrateUngroup(\n env.bundle,\n env.ctx.view,\n env.arrangement.get(),\n groupId,\n group.module_key,\n result.created,\n ),\n );\n }\n return result;\n}\n\n// A group node's delete-node routes through the identical `ungroupRun`\n// migration path a menu-driven Ungroup uses, so every ungroup entry point\n// shares one migration path — there is no second copy that could drift.\n// The delete names the instance the gesture addressed in the scope that\n// owns it.\nasync function deleteNodeRun(env: EditorEnv): Promise<ApplyResult> {\n const id = env.target.nodeId;\n if (!id) return emptyApplyResult();\n if (env.ctx.view.groups.some((g) => g.id === id)) {\n return ungroupRun({ ...env, target: groupTarget(id) });\n }\n const address = instanceAddress(env.bundle, id);\n return env.apply([{ delete_instance: { scope: address.scope, instance_id: address.id } }]);\n}\n\nasync function conflictKeepRun(env: EditorEnv): Promise<void> {\n const conflict = env.ctx.view.conflict;\n if (!conflict) return;\n await env.editor.resolveConflict('keep', conflict.tree_hash);\n}\n\nasync function conflictReloadRun(env: EditorEnv): Promise<void> {\n const conflict = env.ctx.view.conflict;\n if (!conflict) return;\n await env.editor.resolveConflict('reload', conflict.tree_hash);\n}\n\nconst save: EditorBinding = { kind: 'editor', result: 'none', run: saveRun };\nconst generate: EditorBinding = { kind: 'editor', result: 'generate', run: generateRun };\nconst undo: EditorBinding = { kind: 'editor', result: 'apply', run: undoRun };\nconst redo: EditorBinding = { kind: 'editor', result: 'apply', run: redoRun };\nconst clearGraph: EditorBinding = { kind: 'editor', result: 'apply', run: clearGraphRun };\nconst copy: EditorBinding = { kind: 'editor', result: 'none', run: clipRun(false) };\nconst cut: EditorBinding = { kind: 'editor', result: 'none', run: clipRun(true) };\nconst paste: EditorBinding = { kind: 'editor', result: 'apply', run: pasteRun };\nconst group: EditorBinding = { kind: 'editor', result: 'apply', run: groupRun };\nconst ungroup: EditorBinding = { kind: 'editor', result: 'apply', run: ungroupRun };\nconst deleteNode: EditorBinding = { kind: 'editor', result: 'apply', run: deleteNodeRun };\nconst conflictKeep: EditorBinding = { kind: 'editor', result: 'none', run: conflictKeepRun };\nconst conflictReload: EditorBinding = {\n kind: 'editor',\n result: 'none',\n run: conflictReloadRun,\n confirm: () => ({\n text: \"Reload from the module's .tf files? They replace the canvas's saved and unsaved edits.\",\n }),\n};\n\nexport const CORE_EDITOR_ACTIONS: readonly ActionContribution[] = [\n {\n id: 'save',\n label: 'Save',\n icon: 'save',\n section: 'write',\n placement: 'toolbar',\n keys: ['Mod+s'],\n // Heard at the App root: Save is reachable from an inspector field.\n keyScope: 'app',\n requiredPorts: ['editor'],\n requiredContext: ['root', 'editable'],\n binding: save,\n },\n {\n id: 'generate',\n label: 'Generate',\n icon: 'generate',\n section: 'write',\n // The toolbar's call to action while the saved IR waits to be\n // generated; in flight from the click until the engine answers.\n primary: { when: 'ungenerated' },\n busy: { when: 'generating', label: 'Generating…' },\n placement: 'toolbar',\n requiredPorts: ['editor'],\n requiredContext: ['root', 'editable'],\n // Hidden under the lock (requiredContext 'editable') exactly like Save;\n // shown disabled while editable, positive keys in order: `generateIdle`\n // (the engine runs one Generate at a time per session, and this one is\n // running until the engine answers), then `resolved` (no open\n // Keep/Reload conflict), then `saved` (nothing unsaved).\n enabledWhen: [\n { key: 'generateIdle', reason: 'A Generate is running' },\n { key: 'resolved', reason: 'Keep or Reload the conflicting tree first' },\n { key: 'saved', reason: 'Save first' },\n ],\n binding: generate,\n },\n {\n id: 'undo',\n label: 'Undo',\n icon: 'undo',\n section: 'history',\n placement: 'toolbar',\n keys: ['Mod+z'],\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n enabledWhen: [{ key: 'undoable', reason: 'Nothing to undo' }],\n binding: undo,\n },\n {\n id: 'redo',\n label: 'Redo',\n icon: 'redo',\n section: 'history',\n placement: 'toolbar',\n keys: ['Mod+Shift+z'],\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n enabledWhen: [{ key: 'redoable', reason: 'Nothing to redo' }],\n binding: redo,\n },\n {\n id: 'clear-graph',\n label: 'Clear graph',\n icon: 'clear',\n section: 'graph',\n placement: 'toolbar',\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n binding: clearGraph,\n },\n {\n id: 'copy',\n label: 'Copy',\n placement: 'node-menu',\n section: 'clipboard',\n keys: ['Mod+c'],\n requiredPorts: ['editor'],\n // Gated on a node selection existing at all — without it, Mod+C never\n // resolves into the keymap's own action list, so it falls through to\n // the browser's native copy (selected text in run logs/diagnostics)\n // instead of hijacking the shortcut for an empty clipboard op.\n requiredContext: ['editable', 'selection.node'],\n binding: copy,\n },\n {\n id: 'cut',\n label: 'Cut',\n placement: 'node-menu',\n section: 'clipboard',\n keys: ['Mod+x'],\n requiredPorts: ['editor'],\n requiredContext: ['editable', 'selection.node'],\n binding: cut,\n },\n {\n id: 'paste',\n label: 'Paste',\n // Pastes onto the canvas, not onto a node: the empty canvas's menu.\n placement: 'pane-menu',\n keys: ['Mod+v'],\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n binding: paste,\n },\n {\n id: 'group',\n label: 'Group selected',\n placement: 'node-menu',\n section: 'group',\n requiredPorts: ['editor'],\n requiredContext: ['editable', 'selection.node'],\n binding: group,\n },\n {\n id: 'ungroup',\n label: 'Ungroup',\n placement: 'node-menu',\n section: 'group',\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n requiredTarget: ['groupId'],\n binding: ungroup,\n },\n {\n id: 'delete-node',\n label: 'Delete',\n placement: 'node-menu',\n section: 'remove',\n tone: 'danger',\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n requiredTarget: ['nodeId'],\n binding: deleteNode,\n },\n {\n id: 'conflict-keep',\n label: 'Keep canvas IR',\n placement: { row: 'conflict' },\n // Hidden under the source-refused lock exactly like Save/Generate —\n // `editable` gates Keep/Reload the same as every other mutating action.\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n binding: conflictKeep,\n },\n {\n id: 'conflict-reload',\n label: 'Reload from tf…',\n placement: { row: 'conflict' },\n requiredPorts: ['editor'],\n requiredContext: ['editable'],\n binding: conflictReload,\n },\n];\n","// Helpers that translate between canvas-path node/group ids (as emitted\n// on RenderNode.id / RenderGroup.id — dot-joined, e.g.\n// \"cloudwatch_logs_policy.attachment\") and the (scopeKey, localId) pair a\n// CanvasArrangement write targets. Arrangement is keyed by the module key\n// that scope resolves to, not by canvas path — see\n// packages/proto/src/projection/arrangement.ts. An arrangement entry holds\n// rendered nodes and groups, which are Uses, so the local id beside the\n// scope key is the path's trailing Use id (`splitPath`).\n\nimport type { CanvasArrangement } from '@lace-cloud/proto';\nimport { drawnAt, frameOf, localIn, resolveInstance, splitPath } from '@lace-cloud/proto';\nimport type { Bundle } from '../generated/state';\nimport type { CreatedRef } from '../ports';\nimport type { CanvasView } from '../types/render';\n\n// scopeKeyForCanvasPath resolves the key of the module that owns the\n// instance a canvas path addresses — the scope whose arrangement entry that\n// node's or group's own position and collapse state live under. The\n// owner is `resolveInstance`'s, so a path naming a resource child\n// (`grp.resource.<type>.<name>`) yields the scope that holds it. Returns\n// null when the path addresses nothing in the current Bundle (e.g. stale\n// id after a delete).\nexport function scopeKeyForCanvasPath(bundle: Bundle, canvasPath: string): string | null {\n return resolveInstance(bundle, canvasPath)?.scopeKey ?? null;\n}\n\nfunction cloneArrangement(arrangement: CanvasArrangement): CanvasArrangement {\n const next: CanvasArrangement = {};\n for (const [scope, entry] of Object.entries(arrangement)) {\n next[scope] = {\n nodes: entry.nodes ? { ...entry.nodes } : undefined,\n groups: entry.groups ? { ...entry.groups } : undefined,\n };\n }\n return next;\n}\n\n// withNodePosition writes a single node's position into the arrangement\n// entry for its scope, returning a new (copy-on-write) CanvasArrangement.\nexport function withNodePosition(\n bundle: Bundle,\n arrangement: CanvasArrangement,\n canvasPath: string,\n position: { x: number; y: number },\n): CanvasArrangement {\n const scopeKey = scopeKeyForCanvasPath(bundle, canvasPath);\n if (!scopeKey) return arrangement;\n const { localId } = splitPath(canvasPath);\n const next = cloneArrangement(arrangement);\n const scopeEntry = next[scopeKey] ?? {};\n next[scopeKey] = { ...scopeEntry, nodes: { ...scopeEntry.nodes, [localId]: position } };\n return next;\n}\n\n// withNodePositions applies a batch of canvasPath → position writes as a\n// single copy-on-write pass (avoids re-cloning per node on a multi-select\n// drag).\nexport function withNodePositions(\n bundle: Bundle,\n arrangement: CanvasArrangement,\n positions: Record<string, { x: number; y: number }>,\n): CanvasArrangement {\n let next = arrangement;\n for (const [canvasPath, position] of Object.entries(positions)) {\n next = withNodePosition(bundle, next, canvasPath, position);\n }\n return next;\n}\n\n// withScopesPinned stores, where it is drawn now (`localIn`), every card\n// and group in the scopes a write at `canvasPath` can move: the scope that\n// owns it and every scope around that, up to the entry. The layout lays out\n// afresh what it placed, and keeps a stored position only until something\n// kept before it takes its room, so a card dropped in a new place, or a\n// group made or dissolved, would move the siblings the layout placed, and a\n// card the layout stepped down from where it is stored would spring back\n// once what displaced it moves away. So a write first stores every one of\n// them where it is drawn, overwriting a stored position it is not\n// drawn at: each stays where it is drawn unless what the write stores takes\n// its room, when it steps down just past that (`layoutByDepth`), and a box\n// the write grows grows from where it is.\nexport function withScopesPinned(\n bundle: Bundle,\n view: Pick<CanvasView, 'nodes' | 'groups'>,\n arrangement: CanvasArrangement,\n canvasPath: string,\n): CanvasArrangement {\n const scopes = new Set<string>();\n for (let scope = splitPath(canvasPath).parentPath; ; scope = splitPath(scope).parentPath) {\n scopes.add(scope);\n if (scope === '') break;\n }\n let next = arrangement;\n for (const id of [...view.groups.map((g) => g.id), ...view.nodes.map((n) => n.id)]) {\n const { parentPath } = splitPath(id);\n if (!scopes.has(parentPath)) continue;\n const scopeKey = scopeKeyForCanvasPath(bundle, id);\n const at = drawnAt(view, id);\n if (!scopeKey || !at) continue;\n next = withNodePosition(bundle, next, id, localIn(view, id, at));\n }\n return next;\n}\n\n// withGroupCollapsed writes whether a group is collapsed into the PARENT\n// scope's arrangement entry (a group Use's collapsed state is consumer-owned\n// view state of the scope that CONTAINS the group Use, not the scope the\n// group's own module defines).\nexport function withGroupCollapsed(\n bundle: Bundle,\n arrangement: CanvasArrangement,\n canvasPath: string,\n collapsed: boolean,\n): CanvasArrangement {\n const scopeKey = scopeKeyForCanvasPath(bundle, canvasPath);\n if (!scopeKey) return arrangement;\n const { localId } = splitPath(canvasPath);\n const next = cloneArrangement(arrangement);\n const scopeEntry = next[scopeKey] ?? {};\n next[scopeKey] = {\n ...scopeEntry,\n groups: { ...scopeEntry.groups, [localId]: { collapsed } },\n };\n return next;\n}\n\n// withRenameCarried gives an instance about to be renamed its arrangement\n// under the new id too, in the scope that owns it: its position and, for a\n// group, its collapsed state. Written before the rename is sent, as a copy\n// beside the old, because the renamed frame can arrive before the rename's\n// answer and `gcArrangement` drops the old id the moment it does; it drops\n// the copy instead if the rename is refused and the new id never appears. A\n// group's members keep theirs: they live under the group's module key, which\n// a rename leaves alone. An instance with nothing arranged is returned as\n// the arrangement itself.\nexport function withRenameCarried(\n arrangement: CanvasArrangement,\n scopeKey: string,\n oldId: string,\n newId: string,\n): CanvasArrangement {\n const scopeEntry = arrangement[scopeKey];\n const position = scopeEntry?.nodes?.[oldId];\n const group = scopeEntry?.groups?.[oldId];\n if (!position && !group) return arrangement;\n const next = cloneArrangement(arrangement);\n next[scopeKey] = {\n nodes: position ? { ...scopeEntry?.nodes, [newId]: position } : scopeEntry?.nodes,\n groups: group ? { ...scopeEntry?.groups, [newId]: group } : scopeEntry?.groups,\n };\n return next;\n}\n\n// setScopeEntry writes a whole arrangement scope entry verbatim — used by\n// group-create (which stores its members' positions in the new module's\n// scope) and ungroup (the reverse migration).\nexport function setScopeEntry(\n arrangement: CanvasArrangement,\n scopeKey: string,\n entry: CanvasArrangement[string],\n): CanvasArrangement {\n const next = cloneArrangement(arrangement);\n next[scopeKey] = entry;\n return next;\n}\n\n// migrateUngroup applies the arrangement side of dissolving a group Use:\n// every member — whether its position was stored or laid out — is stored\n// where it is drawn, now in the parent scope's frame (`localIn`), so the\n// members stay where they were on screen; a member group's collapsed state\n// moves with it; the dissolved group's own entries leave the parent; and\n// the scopes around it are pinned where they are drawn (`withScopesPinned`).\n// Shared by every ungroup entry point (context-menu action, GroupNode's\n// inline ungroup button, xyflow's native node-delete on a selected group)\n// so the migration logic lives in exactly one place. `view` and `bundle`\n// are the ones the group was drawn from, before the ungroup.\n//\n// `promoted` is the ungroup mutation's `ApplyResult.created` — the CLI\n// reports a CreatedRef{id, sourceId, scope: parentScope} for EVERY\n// promoted child, renamed or not: an unrenamed child (the common case)\n// simply has sourceId === id, so `rename()` below is the identity for it.\n// A collision with an existing sibling in the parent scope is the one\n// case where id and sourceId actually differ.\nexport function migrateUngroup(\n bundle: Bundle,\n view: Pick<CanvasView, 'nodes' | 'groups'>,\n arrangement: CanvasArrangement,\n groupCanvasPath: string,\n groupModuleKey: string,\n promoted: CreatedRef[] = [],\n): CanvasArrangement {\n const parentScopeKey = scopeKeyForCanvasPath(bundle, groupCanvasPath);\n const group = view.groups.find((g) => g.id === groupCanvasPath);\n if (!parentScopeKey || !group) return arrangement;\n\n const { localId } = splitPath(groupCanvasPath);\n const pinned = withScopesPinned(bundle, view, arrangement, groupCanvasPath);\n const parentEntry = pinned[parentScopeKey] ?? {};\n const groupEntry = pinned[groupModuleKey] ?? {};\n\n const renameMap = new Map(\n promoted\n .filter((ref) => ref.scope === parentScopeKey && ref.sourceId)\n .map((ref) => [ref.sourceId, ref.id] as const),\n );\n const rename = (id: string) => renameMap.get(id) ?? id;\n\n const frame = frameOf(view, groupCanvasPath);\n const nodes = { ...parentEntry.nodes };\n delete nodes[localId];\n for (const member of group.node_ids) {\n const at = drawnAt(view, member);\n if (at) nodes[rename(splitPath(member).localId)] = localIn(view, member, at, frame);\n }\n\n const remainingGroups = parentEntry.groups ? { ...parentEntry.groups } : undefined;\n if (remainingGroups) delete remainingGroups[localId];\n const migratedGroups = groupEntry.groups\n ? Object.fromEntries(Object.entries(groupEntry.groups).map(([id, g]) => [rename(id), g]))\n : undefined;\n const groups =\n remainingGroups || migratedGroups ? { ...remainingGroups, ...migratedGroups } : undefined;\n\n return setScopeEntry(pinned, parentScopeKey, { nodes, groups });\n}\n\n// gcArrangement drops arrangement entries for scopes and children that no\n// longer exist in the current Bundle — an id that was deleted (or whose\n// scope was deleted) leaks memory and stale visual state forever\n// otherwise, since nothing else ever removes an arrangement entry.\nexport function gcArrangement(bundle: Bundle, arrangement: CanvasArrangement): CanvasArrangement {\n const next: CanvasArrangement = {};\n let changed = false;\n\n for (const [scopeKey, entry] of Object.entries(arrangement)) {\n const mod = bundle.modules[scopeKey];\n if (!mod) {\n changed = true; // scope no longer exists — drop entirely.\n continue;\n }\n const liveIds = new Set((mod.modules ?? []).map((u) => u.id));\n\n const nodeEntries = entry.nodes ? Object.entries(entry.nodes) : [];\n const liveNodeEntries = nodeEntries.filter(([id]) => liveIds.has(id));\n const groupEntries = entry.groups ? Object.entries(entry.groups) : [];\n const liveGroupEntries = groupEntries.filter(([id]) => liveIds.has(id));\n\n if (\n liveNodeEntries.length !== nodeEntries.length ||\n liveGroupEntries.length !== groupEntries.length\n ) {\n changed = true;\n }\n\n const nodes = entry.nodes ? Object.fromEntries(liveNodeEntries) : undefined;\n const groups = entry.groups ? Object.fromEntries(liveGroupEntries) : undefined;\n\n if ((nodes && Object.keys(nodes).length > 0) || (groups && Object.keys(groups).length > 0)) {\n next[scopeKey] = { nodes, groups };\n }\n }\n\n // Identity-preserving when nothing was pruned — callers (App's\n // stateUpdated handler) skip a state update + host notification when\n // GC is a no-op.\n return changed ? next : arrangement;\n}\n","// A view renders every scope flat — the entry's children plus, under each\n// group, that group's children by their own dotted ids — and each group\n// lists its children in `node_ids`. The entry scope's ids are therefore the\n// view's node and group ids that no group claims as a child. This is the\n// one derivation the gestures that are entry-scope by meaning read: Clear\n// graph (a group's delete takes its children) and copy/cut (a copy is an\n// entry-scope operation). A gesture that addresses one instance of the\n// user's choosing — delete, edge delete, drag-connect, rename, a config\n// panel edit — addresses it in the scope that owns it (`instanceAddress`).\nimport type { CanvasView } from '../types/render';\n\ntype ViewScopes = Pick<CanvasView, 'nodes' | 'groups'>;\n\nexport function entryScopeIds(view: ViewScopes): string[] {\n const nested = new Set(view.groups.flatMap((g) => g.node_ids));\n return [...view.nodes, ...view.groups].map((n) => n.id).filter((id) => !nested.has(id));\n}\n\n// inEntryScope keeps, in their given order, the ids among `ids` that the\n// entry scope owns.\nexport function inEntryScope(view: ViewScopes, ids: readonly string[]): string[] {\n const entry = new Set(entryScopeIds(view));\n return ids.filter((id) => entry.has(id));\n}\n","// The canvas context: the pipeline's output, read by Canvas.tsx and every\n// component/hook below it. `editable` is App's one read-only derivation,\n// `ports.editor !== undefined && !source.sourceRefused` — there is no\n// `readOnly` field.\nimport type { CanvasView } from '@lace-cloud/proto';\nimport { createContext, useContext } from 'react';\nimport type { CanvasCtx, EdgeRef, LayoutHandle } from '../contributions';\nimport type { DrawnDecorations } from '../core/decorate';\nimport type { ActionRunner } from '../core/run-binding';\nimport type { Bundle } from '../generated/state';\nimport type { CanvasPorts } from '../ports';\nimport type { CanvasArrangement } from '../types/render';\n\nexport type CanvasContextValue = {\n ports: CanvasPorts;\n // The raw Bundle behind `view` — panels that show what the graph does not\n // draw (a Use's Binding, a module's resources, directives and\n // declarations) derive it from here (`deriveNodeConfig` /\n // `deriveSettingsConfig`), so inspection-only content (no editor port)\n // renders the same way an editable panel's read model does.\n bundle: Bundle;\n view: CanvasView;\n // The resolution-time context every contribution's own gating and every\n // binding's `args()` reads (registry.ts, contributions.ts) — App builds\n // one per render and every panel receives it as a prop too\n // (`PanelProps.ctx`), but the surfaces below App (Canvas, its panels,\n // node-menu resolution) that aren't themselves a `Panel` read it here.\n ctx: CanvasCtx;\n // This frame's per-node decorations (`core/decorate.ts`'s merge of every\n // resolved overlay + `ctx.diagnostics`) — ModuleNode reads its own badges\n // off this map; App is the one place that recomputes it.\n decorations: DrawnDecorations;\n editable: boolean;\n // The consumer-owned CanvasArrangement (node positions, group\n // collapse). Both editable and read-only mounts route drag /\n // collapse-toggle / rename through `updateArrangement` — the core is the\n // single projection site (`bundle-shows-on-canvas`), so a read-only\n // mount re-projects the same way an editable one does; it just has no\n // `editor` port to issue an IR-mutating action through.\n arrangement: CanvasArrangement;\n updateArrangement: (next: CanvasArrangement) => void;\n selection: { nodes: readonly string[]; edge: EdgeRef | null };\n setSelection: (next: { nodes: readonly string[]; edge: EdgeRef | null }) => void;\n // The one execution path: every action (toolbar, node-menu, row, key)\n // runs through `runner.run`, every bare xyflow gesture through\n // `runner.apply`.\n runner: ActionRunner;\n // A stable object Canvas overwrites with its own xyflow-backed\n // implementation once mounted, so App's own toolbar-run\n // `EditorEnvExtras` and a panel's `useEditorEnvExtras`\n // (core/panels/row-actions.ts) share the one instance rather than each\n // inventing their own no-op.\n layout: LayoutHandle;\n // Opens and closes the settings panel. App owns whether it is open and\n // carries it as `ctx.settingsOpen`, which the panel's `'settingsOpen'`\n // context key gates on, so a closed panel resolves nothing and its column\n // takes no space; the Settings toggle opens it and the panel's Close\n // closes it.\n setSettingsOpen: (next: boolean) => void;\n};\n\nexport const CanvasContext = createContext<CanvasContextValue | null>(null);\n\nexport function useCanvas(): CanvasContextValue {\n const value = useContext(CanvasContext);\n if (!value) throw new Error('CanvasContext not available: mount inside <App>');\n return value;\n}\n","// The one path a panel's row/inline buttons reach an action through:\n// `rowActionsFor` resolves `ctx.contributions` — the merged core + host set\n// App built — against this panel's own `ctx` and a\n// row's `target` (registry.ts `resolveContributions` + `rowActions`), never\n// a core-only list — a host row action (e.g. VS Code's own Open source on a\n// `row:diagnostics` entry) renders next to a core one with no panel edit. `useEditorEnvExtras`\n// supplies the pieces `ActionRunner.run` needs for an editor binding that a\n// panel (never the Canvas surface itself) can actually provide —\n// `layout` is the one shared instance Canvas overwrites once mounted\n// (state/canvas-context.ts), so a row action that pans the camera needs no\n// second wiring.\nimport type { ActionContribution, ActionTarget, CanvasCtx } from '../../contributions';\nimport { resolveContributions, rowActions } from '../../registry';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { EditorEnvExtras } from '../run-binding';\n\nexport function rowActionsFor(\n ctx: CanvasCtx,\n panelId: string,\n target: ActionTarget = {},\n): readonly ActionContribution[] {\n const resolved = resolveContributions(ctx.contributions, ctx.ports, ctx, target);\n return rowActions(resolved, panelId);\n}\n\nexport function useEditorEnvExtras(): EditorEnvExtras {\n const { bundle, arrangement, updateArrangement, layout } = useCanvas();\n return {\n bundle,\n arrangement: { get: () => arrangement, update: updateArrangement },\n layout,\n };\n}\n","// useRenameInstance is the one rename a card or a group header sends. It\n// writes what the rename carries under the new id, each slice by its own\n// owner — the arrangement (`withRenameCarried`) and the selection\n// (`carrySelection`) — then sends `rename_instance` in the scope that owns\n// the instance through `runner.apply`: the same one-batch apply plus\n// `presenter.notify` failure routing every other node-chrome mutation uses,\n// so a refusal (a taken or invalid name) reaches the developer. A new id the\n// scope already holds carries nothing: the engine refuses that rename, and\n// the copy would land on the instance that holds it. A refused rename lands\n// no frame, so no frame drops the copied names: the selection is reconciled\n// with the view the session stands at once the refusal is answered.\nimport { instanceAddress } from '@lace-cloud/proto';\nimport { useCallback, useRef } from 'react';\nimport { carrySelection, reconcileSelection } from '../../core/pipeline';\nimport { useCanvas } from '../../state/canvas-context';\nimport { withRenameCarried } from '../../utils/arrangement';\n\nexport function useRenameInstance(): (canvasPath: string, newId: string) => Promise<void> {\n const { bundle, view, arrangement, updateArrangement, selection, setSelection, runner } =\n useCanvas();\n // What a refusal's answer meets is what stands when it arrives, not what\n // stood when the rename was sent.\n const latest = useRef({ view, selection });\n latest.current = { view, selection };\n\n return useCallback(\n async (canvasPath: string, newId: string) => {\n const { scope, id: oldId } = instanceAddress(bundle, canvasPath);\n if (!newId || newId === oldId) return;\n const taken = bundle.modules[scope]?.modules?.some((u) => u.id === newId) ?? false;\n // A canvas path ends with the instance's own id, which may hold dots of\n // its own (a resource child's), so the new path replaces that suffix.\n const newPath = canvasPath.slice(0, canvasPath.length - oldId.length) + newId;\n const carriedArrangement = taken\n ? arrangement\n : withRenameCarried(arrangement, scope, oldId, newId);\n const carriedSelection = taken ? selection : carrySelection(selection, canvasPath, newPath);\n if (carriedArrangement !== arrangement) updateArrangement(carriedArrangement);\n if (carriedSelection !== selection) setSelection(carriedSelection);\n const result = await runner.apply([\n { rename_instance: { scope, old_id: oldId, new_id: newId } },\n ]);\n if (result?.success || carriedSelection === selection) return;\n const now = latest.current;\n const held = reconcileSelection(now.view, now.selection);\n if (held !== now.selection) setSelection(held);\n },\n [bundle, arrangement, updateArrangement, selection, setSelection, runner],\n );\n}\n","// useCanvasSource is the canvas's standing subscription: it mounts\n// `ports.source.subscribe` for as long as the canvas is mounted and returns\n// the latest `CanvasSource` frame, which App renders. (`currentFrame`,\n// ports.ts, reads the frame the source stands at once, for a write's caller\n// to read its own write.) The stream's end leaves the last good frame in place (it means \"no\n// further frame will ever follow\", not \"the current one is wrong\") — App\n// renders it once, as the load-error state, when no frame ever arrived.\n//\n// The same subscription delivers the results of the commands that ran in\n// the session's root. Each `subscribe` mints one token, the session's: the\n// results are handed to `onCommandResult` with it, the state carries it as\n// `session`, and `onSessionEnd` receives it once the subscription ends, so a\n// consumer folding the results keeps each session's fold apart and drops a\n// fold no subscription delivers to any more.\n//\n// projectFrame is the view of a frame: its Bundle projected with the\n// reader's arrangement (`projectCanvasView`) and the frame's own state. App\n// draws it; a write that must know where something it stored is drawn reads\n// it from the frame its apply settled on (`currentFrame`).\n//\n// reconcileSelection is what of a selection a frame's view still holds. The\n// frame is the one truth of what exists, so App reconciles its selection\n// against each view it projects, whatever removed the selected thing.\n// carrySelection is what a selection names across a rename, beside what it\n// named before, until a frame drops the old names.\nimport { type CanvasView, projectCanvasView } from '@lace-cloud/proto';\nimport { useEffect, useState } from 'react';\nimport type { CanvasCtx } from '../contributions';\nimport type { CanvasSource, CommandResult, SourceEnd, SourcePort } from '../ports';\nimport type { CanvasArrangement } from '../types/render';\n\nexport function projectFrame(frame: CanvasSource, arrangement: CanvasArrangement): CanvasView {\n return projectCanvasView(frame.bundle, arrangement, {\n canUndo: frame.canUndo,\n canRedo: frame.canRedo,\n unsaved: frame.unsaved,\n conflict: frame.conflict\n ? { base_tree_hash: frame.conflict.baseTreeHash, tree_hash: frame.conflict.treeHash }\n : undefined,\n ungenerated: frame.ungenerated,\n });\n}\n\n// The selection with what `view` does not hold dropped: a node or group\n// by its id among the view's nodes and groups, the wire by its id among the\n// view's edges. A selection the view holds whole is returned as itself.\nexport function reconcileSelection(\n view: CanvasView,\n selection: CanvasCtx['selection'],\n): CanvasCtx['selection'] {\n const held = new Set([...view.nodes, ...view.groups].map((n) => n.id));\n const nodes = selection.nodes.filter((id) => held.has(id));\n const { edge } = selection;\n const keptEdge = edge && view.edges.some((e) => e.id === edge.id) ? edge : null;\n if (nodes.length === selection.nodes.length && keptEdge === edge) return selection;\n return { nodes, edge: keptEdge };\n}\n\n// The selection with its names of the instance at `oldPath` and of\n// everything under it, whose canvas paths change with its own, named under\n// `newPath` too, beside the old: the renamed frame can arrive before the\n// rename's answer, and it drops the old names (`reconcileSelection`) and\n// keeps the new. A selection naming nothing under the instance is returned\n// as itself.\nexport function carrySelection(\n selection: CanvasCtx['selection'],\n oldPath: string,\n newPath: string,\n): CanvasCtx['selection'] {\n const copies = selection.nodes.flatMap((id) =>\n id === oldPath || id.startsWith(`${oldPath}.`) ? [newPath + id.slice(oldPath.length)] : [],\n );\n if (copies.length === 0) return selection;\n return { ...selection, nodes: [...selection.nodes, ...copies] };\n}\n\nexport type SourceState = {\n source: CanvasSource | null;\n end: SourceEnd | null;\n // The token of the subscription the state came from; null until the\n // first subscription.\n session: object | null;\n};\n\nexport function useCanvasSource(\n source: SourcePort,\n onCommandResult: (result: CommandResult, session: object) => void,\n onSessionEnd: (session: object) => void,\n): SourceState {\n const [state, setState] = useState<SourceState>({ source: null, end: null, session: null });\n\n useEffect(() => {\n const session = {};\n setState({ source: null, end: null, session });\n const unsubscribe = source.subscribe(\n (next) => setState({ source: next, end: null, session }),\n (end) => setState((prev) => ({ source: prev.source, end, session })),\n (result) => onCommandResult(result, session),\n );\n return () => {\n unsubscribe();\n onSessionEnd(session);\n };\n }, [source, onCommandResult, onSessionEnd]);\n\n return state;\n}\n","import {\n instanceAddress,\n NODE_HEADER_HEIGHT,\n NODE_ROW_HEIGHT,\n NODE_WIDTH,\n nodeRows,\n visibleInputs,\n} from '@lace-cloud/proto';\nimport {\n Handle,\n type Node,\n type NodeProps,\n Position,\n type ReactFlowState,\n useStore,\n useUpdateNodeInternals,\n} from '@xyflow/react';\nimport type React from 'react';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { Badge } from '../../contributions';\nimport { hasErrorBadge, type PinFinding } from '../../core/decorate';\nimport { useEditorEnvExtras } from '../../core/panels/row-actions';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { NodePin, RenderNode } from '../../types/render';\nimport { NODE_HANDLE, sourceHandleId } from '../../utils/handleId';\nimport { typedName } from '../../utils/typed-name';\nimport { CanvasIcon } from '../icons';\nimport './ModuleNode.css';\nimport { useOpenNodeConfig } from './node-config-bus';\nimport { ANY_PIN_COLOR, pinColor } from './pinColor';\nimport { useRenameInstance } from './use-rename-instance';\n\n// ── Node data contract (serializable — no callbacks) ──\n\nexport type ModuleNodeData = RenderNode & {\n hasValidationError?: boolean;\n isNew?: boolean;\n /** Badges the diagnostics decoration attached to this node — tone\n * `'error'` drives the error border/title. `RenderNode` carries no\n * error state of its own; a node's error styling comes only from its\n * decoration badges. The same field name and chip shape GroupNode's own\n * `badges` renders — a badge addressed to a collapsed group's own id\n * (nodeIdForAddress can return a group id) is not a ModuleNode concern\n * either way. */\n badges?: readonly Badge[];\n /** What the engine found on this node's inputs, by input name — the\n * decoration's `pins`. */\n pins?: Readonly<Record<string, PinFinding>>;\n};\n\ntype ModuleNodeNode = Node<ModuleNodeData, 'moduleNode'>;\n\n// ── Layout constants ──\n// The card's geometry is the projection's (proto geometry.ts): the layout\n// that places a card and the card itself read one set of numbers.\n\nconst ICON_SIZE = 16;\n\n// True while a drag that started on a `node` handle is in progress: only\n// then is a card a place to end one.\nconst nodeDragging = (s: ReactFlowState) => s.connection.fromHandle?.id === NODE_HANDLE;\n\n// Border / shadow variants now live in ModuleNode.css as\n// `.lace-module-node--error` / `--new` classes. Node colors flow\n// through design tokens.\n\n// ── Pin row ──\n\ntype PinRowProps = {\n pin: NodePin;\n side: 'input' | 'output';\n top: number; // vertical offset inside the node body\n // Another pin sits on this row on the other side: each label then keeps to\n // its own half of the card, so an input's name and an output's never\n // overlap; a label longer than its room ends in an ellipsis and carries the\n // full name as its tooltip.\n shared: boolean;\n // What the engine found on this pin (`BundleState.diagnostics`, an\n // input's own): its ring takes the finding's tone and its tooltip leads\n // with the finding — a required input nothing sets is the common one.\n problem?: PinFinding;\n isConnectable: boolean;\n};\n\nconst PROBLEM_RING: Record<PinFinding['tone'], string | undefined> = {\n error: 'var(--lace-node-error-border)',\n warn: 'var(--lace-color-warning-fg)',\n neutral: undefined,\n};\n\n// A pin is a dot in its type's colour, by one rule on both rails: filled\n// while a wire runs to or from it (`wired`), hollow while none does. A pin\n// the engine has a finding on draws its ring in the finding's tone.\nconst PinRow: React.FC<PinRowProps> = ({ pin, side, top, shared, problem, isConnectable }) => {\n const color = pinColor(pin);\n const isInput = side === 'input';\n const filled = !!pin.wired;\n const ring = problem ? PROBLEM_RING[problem.tone] : undefined;\n const isError = problem?.tone === 'error';\n const handleStyle: React.CSSProperties = {\n background: filled ? color.fill : 'var(--lace-node-bg)',\n borderColor: ring ?? (filled ? color.stroke : color.fill),\n borderWidth: ring ? 2 : 1.5,\n borderStyle: 'solid',\n width: 10,\n height: 10,\n [isInput ? 'left' : 'right']: -5,\n top: NODE_ROW_HEIGHT / 2,\n };\n const about = `${typedName(pin.name, pin.type)}${pin.description ? ` — ${pin.description}` : ''}`;\n return (\n <div\n className=\"lace-pin-row\"\n style={{\n position: 'absolute',\n top,\n left: 0,\n right: 0,\n height: NODE_ROW_HEIGHT,\n paddingLeft: isInput ? 12 : 8,\n paddingRight: isInput ? 8 : 12,\n display: 'flex',\n alignItems: 'center',\n justifyContent: isInput ? 'flex-start' : 'flex-end',\n }}\n title={problem ? `${problem.message}\\n${about}` : about}\n >\n <Handle\n id={`${isInput ? 'in' : 'out'}:${pin.name}`}\n type={isInput ? 'target' : 'source'}\n position={isInput ? Position.Left : Position.Right}\n isConnectable={isConnectable}\n className=\"lace-pin-handle\"\n style={handleStyle}\n />\n <span\n className={`lace-module-node__pin-row-label lace-module-node__pin-row-label--${isError ? 'error' : filled ? 'wired' : 'default'}`}\n style={{ maxWidth: shared ? (NODE_WIDTH - 28) / 2 - 4 : NODE_WIDTH - 28 }}\n >\n {pin.name}\n </span>\n </div>\n );\n};\n\n// ── Component ──\n\nconst ModuleNode: React.FC<NodeProps<ModuleNodeNode>> = ({ id, data }) => {\n const { editable, ctx, runner, bundle } = useCanvas();\n const rename = useRenameInstance();\n const connecting = useStore(nodeDragging);\n const openNodeConfig = useOpenNodeConfig();\n const envExtras = useEditorEnvExtras();\n const [editing, setEditing] = useState(false);\n const [editValue, setEditValue] = useState(id);\n const [hovered, setHovered] = useState(false);\n const [imgFailed, setImgFailed] = useState(false);\n const [collapsed, setCollapsed] = useState(false);\n const [showAllInputs, setShowAllInputs] = useState(false);\n const inputRef = useRef<HTMLInputElement>(null);\n const renamingRef = useRef(false);\n\n useEffect(() => {\n if (editing && inputRef.current) {\n inputRef.current.focus();\n inputRef.current.select();\n }\n }, [editing]);\n\n // ── Pin filtering ──\n\n const inputs = data.inputs ?? [];\n const outputs = data.outputs ?? [];\n\n const { shownInputs, hiddenInputCount } = useMemo(() => {\n if (showAllInputs) {\n return { shownInputs: inputs, hiddenInputCount: 0 };\n }\n const visible = visibleInputs(inputs);\n return {\n shownInputs: visible,\n hiddenInputCount: inputs.length - visible.length,\n };\n }, [inputs, showAllInputs]);\n\n // xyflow measures a card's handles when the card mounts or resizes, and\n // draws a wire only between handles it has measured. The handles a card\n // draws change without its size changing — a folded row becoming the row\n // of the pin a wire now feeds keeps the row count — so the card says when\n // its drawn handle set changes, and the wire to the new pin is drawn.\n const updateNodeInternals = useUpdateNodeInternals();\n const drawnHandles = [\n ...shownInputs.map((pin) => `in:${pin.name}`),\n ...outputs.map((pin) => sourceHandleId(pin.name)),\n ].join('|');\n // biome-ignore lint/correctness/useExhaustiveDependencies: re-measured whenever the drawn handle set changes.\n useEffect(() => {\n updateNodeInternals(id);\n }, [id, drawnHandles, updateNodeInternals]);\n\n // ── Callbacks ──\n\n const onDoubleClick = useCallback(\n (e: React.MouseEvent) => {\n if (!editable) return;\n e.stopPropagation();\n setEditValue(instanceAddress(bundle, id).id);\n setEditing(true);\n },\n [id, editable, bundle],\n );\n\n // The name edited is the instance's own id in the scope that owns it,\n // which is where the rename applies (`useRenameInstance`): the node keeps\n // its place, and its selection, under the new name.\n const commitRename = useCallback(async () => {\n if (renamingRef.current) return;\n renamingRef.current = true;\n setEditing(false);\n await rename(id, editValue.trim());\n renamingRef.current = false;\n }, [editValue, id, rename]);\n\n const onKeyDown = useCallback(\n (e: React.KeyboardEvent) => {\n e.stopPropagation();\n if (e.key === 'Enter') commitRename();\n else if (e.key === 'Escape') setEditing(false);\n },\n [commitRename],\n );\n\n const onHeaderClick = useCallback(\n (e: React.MouseEvent) => {\n if (!e.shiftKey && !e.metaKey && !e.ctrlKey) {\n openNodeConfig(data.id);\n }\n },\n [data.id, openNodeConfig],\n );\n\n // Delete runs the registered `delete-node` contribution through the\n // runner — the same one mutation path (and error routing to\n // `presenter.notify`) the node menu's own Delete entry and Backspace/\n // Delete key both use, never a second `editor.apply` call site that\n // could drop a failing `ApplyResult` silently.\n const onDeleteInstance = useCallback(\n async (e: React.MouseEvent) => {\n e.stopPropagation();\n const action = ctx.contributions.actions.find((a) => a.id === 'delete-node');\n if (!action) return;\n await runner.run(action, ctx, { nodeId: data.id }, envExtras);\n },\n [ctx, runner, envExtras, data.id],\n );\n\n const toggleCollapsed = useCallback((e: React.MouseEvent) => {\n e.stopPropagation();\n setCollapsed((v) => !v);\n }, []);\n\n // React.SyntheticEvent — not React.MouseEvent — since the Enter/Space\n // keyboard activation on the hidden-count row shares this handler with\n // its click, and both only ever call `stopPropagation`.\n const toggleShowAllInputs = useCallback((e: React.SyntheticEvent) => {\n e.stopPropagation();\n setShowAllInputs((v) => !v);\n }, []);\n\n // ── Styling ──\n\n const showIcon = data.icon_url && !imgFailed;\n const badges = data.badges ?? [];\n // A node's error styling comes only from a badge whose own tone is\n // 'error' — a neutral \"3 resources\" count or a warn \"drifted\" badge\n // decorates the node without painting it as broken.\n const hasAnyError = hasErrorBadge(badges) || !!data.hasValidationError;\n const isNew = !!data.isNew && !hasAnyError;\n\n // Body height — when collapsed, header only. Folded, the rows `nodeRows`\n // counts, so the card is the size the layout placed it by; with every\n // input shown, whichever rail is taller.\n const rowCount = collapsed\n ? 0\n : showAllInputs\n ? Math.max(inputs.length, outputs.length)\n : nodeRows({ inputs, outputs });\n const bodyHeight = rowCount * NODE_ROW_HEIGHT;\n const nodeHeight = NODE_HEADER_HEIGHT + bodyHeight;\n\n const stateClass = hasAnyError ? 'lace-module-node--error' : isNew ? 'lace-module-node--new' : '';\n\n return (\n <div\n className={`lace-module-node${collapsed ? ' lace-module-node--collapsed' : ''}${stateClass ? ` ${stateClass}` : ''}`}\n style={{ width: NODE_WIDTH, height: nodeHeight }}\n onMouseEnter={() => setHovered(true)}\n onMouseLeave={() => setHovered(false)}\n >\n {/* ── Header ── */}\n <div\n className=\"lace-module-node__header\"\n style={{ height: NODE_HEADER_HEIGHT }}\n onClick={onHeaderClick}\n title={badges.length > 0 ? badges.map((b) => b.title ?? b.label).join('\\n') : data.label}\n >\n <button\n type=\"button\"\n onClick={toggleCollapsed}\n className=\"lace-module-node__collapse-btn\"\n title={collapsed ? 'Expand' : 'Collapse'}\n aria-label={collapsed ? 'Expand' : 'Collapse'}\n >\n <CanvasIcon name={collapsed ? 'chevron-right' : 'chevron-down'} />\n </button>\n\n {showIcon ? (\n <img\n src={data.icon_url}\n alt=\"\"\n className=\"lace-module-node__icon\"\n style={{ width: ICON_SIZE, height: ICON_SIZE }}\n onError={() => setImgFailed(true)}\n />\n ) : (\n <span className=\"lace-module-node__icon-fallback\">\n <CanvasIcon name=\"module\" />\n </span>\n )}\n\n {editing ? (\n <input\n ref={inputRef}\n value={editValue}\n onChange={(e) => setEditValue(e.target.value)}\n onBlur={commitRename}\n onKeyDown={onKeyDown}\n className=\"lace-module-node__rename-input\"\n onClick={(e) => e.stopPropagation()}\n />\n ) : (\n <span\n className=\"lace-module-node__label\"\n onDoubleClick={onDoubleClick}\n title={data.label}\n >\n {data.label}\n </span>\n )}\n\n {hovered && editable && (\n <button\n type=\"button\"\n onClick={onDeleteInstance}\n className=\"lace-module-node__delete-btn\"\n title=\"Delete instance\"\n aria-label=\"Delete instance\"\n >\n <CanvasIcon name=\"clear\" />\n </button>\n )}\n </div>\n\n {/* ── Badges: every decoration badge renders as its own chip by its\n own tone, floating above the card so it never perturbs the\n pin-row height math below — only a badge whose tone is 'error'\n drives the card's own error border (above), the rest are\n informational (a resource count, a drift warning). Each chip\n carries `data-badge` (its own id — 'resources', 'drift', a\n diagnostic's own id, …) and `data-tone`, so a DOM assertion can\n tell which badge is which without parsing chip text. ── */}\n {badges.length > 0 && (\n <div className=\"lace-module-node__badges\">\n {badges.map((b) => (\n <span\n key={b.id}\n data-badge={b.id}\n data-tone={b.tone}\n className={`lace-module-node__badge lace-module-node__badge--${b.tone}`}\n title={b.title ?? b.label}\n >\n {b.label}\n </span>\n ))}\n </div>\n )}\n\n {/* ── Call handle: an edge whose reference reads the whole call, naming\n no output, leaves the node here. No wire starts from it. ── */}\n {data.call_wired && (\n <Handle\n id={sourceHandleId('')}\n type=\"source\"\n position={Position.Right}\n isConnectable={false}\n className=\"lace-pin-handle\"\n style={{\n background: ANY_PIN_COLOR.fill,\n borderColor: ANY_PIN_COLOR.stroke,\n borderWidth: 1,\n borderStyle: 'solid',\n width: 8,\n height: 8,\n top: NODE_HEADER_HEIGHT / 2,\n right: -4,\n }}\n />\n )}\n\n {/* ── Body: input rail (left) + output rail (right), absolutely positioned rows ── */}\n {!collapsed && (\n <div className=\"lace-module-node__body\" style={{ height: bodyHeight }}>\n {shownInputs.map((pin, i) => (\n <PinRow\n key={`in:${pin.name}`}\n pin={pin}\n side=\"input\"\n top={i * NODE_ROW_HEIGHT}\n shared={i < outputs.length}\n problem={data.pins?.[pin.name]}\n isConnectable={editable}\n />\n ))}\n {outputs.map((pin, i) => (\n <PinRow\n key={`out:${pin.name}`}\n pin={pin}\n side=\"output\"\n top={i * NODE_ROW_HEIGHT}\n shared={i < shownInputs.length}\n isConnectable={editable}\n />\n ))}\n\n {hiddenInputCount > 0 && (\n <div\n className=\"lace-module-node__hidden-count\"\n onClick={toggleShowAllInputs}\n onKeyDown={(e) => {\n if (e.key === 'Enter' || e.key === ' ') toggleShowAllInputs(e);\n }}\n role=\"button\"\n tabIndex={0}\n style={{\n top: shownInputs.length * NODE_ROW_HEIGHT,\n left: 12,\n right: 12,\n height: NODE_ROW_HEIGHT,\n }}\n title=\"Show all inputs\"\n >\n +{hiddenInputCount} more\n </div>\n )}\n </div>\n )}\n\n {/* ── Collapsed: stack all input handles on the left edge, outputs on right ── */}\n {collapsed && (\n <>\n {inputs.map((pin, i) => {\n const color = pinColor(pin);\n return (\n <Handle\n key={`in:${pin.name}`}\n id={`in:${pin.name}`}\n type=\"target\"\n position={Position.Left}\n isConnectable={editable}\n className=\"lace-pin-handle\"\n style={{\n background: pin.wired ? color.fill : 'var(--lace-node-bg)',\n borderColor: pin.wired ? color.stroke : color.fill,\n borderWidth: 1,\n borderStyle: 'solid',\n width: 8,\n height: 8,\n top: NODE_HEADER_HEIGHT / 2 - 4 + (i - (inputs.length - 1) / 2) * 3,\n left: -4,\n }}\n />\n );\n })}\n {outputs.map((pin, i) => {\n const color = pinColor(pin);\n return (\n <Handle\n key={`out:${pin.name}`}\n id={`out:${pin.name}`}\n type=\"source\"\n position={Position.Right}\n isConnectable={editable}\n className=\"lace-pin-handle\"\n style={{\n background: pin.wired ? color.fill : 'var(--lace-node-bg)',\n borderColor: pin.wired ? color.stroke : color.fill,\n borderWidth: 1,\n borderStyle: 'solid',\n width: 8,\n height: 8,\n top: NODE_HEADER_HEIGHT / 2 - 4 + (i - (outputs.length - 1) / 2) * 3,\n right: -4,\n }}\n />\n );\n })}\n </>\n )}\n\n {/* ── Node-to-node drag, on an editable canvas only: a drag from the\n grip below the card starts it and the card itself ends it. The\n card's target never starts a connection and is an end only while a\n drag from a `node` handle is in progress; at rest xyflow gives it\n no pointer events, so the header's gestures and a pin drag's drop\n reach what lies under it. Rendered last, so during a node drag it\n lies above the header and the pins. ── */}\n {editable && (\n <>\n <Handle\n id={NODE_HANDLE}\n type=\"source\"\n position={Position.Bottom}\n // xyflow arms click-to-connect from a handle's click, and a\n // Handle spreads its own props over that handler: an `onClick` of\n // `undefined` leaves the grip a drag start only.\n onClick={undefined}\n className=\"lace-module-node__grip\"\n />\n <Handle\n id={NODE_HANDLE}\n type=\"target\"\n position={Position.Top}\n isConnectableStart={false}\n isConnectableEnd={connecting}\n className=\"lace-module-node__drop\"\n />\n </>\n )}\n </div>\n );\n};\n\nexport default ModuleNode;\n","// decorate merges every rendering overlay's own decorations with the\n// engine's diagnostics (via `diagnosticsOf`) for this frame into one\n// per-node badge set. A node's diagnostics fold into one badge — how many,\n// in the tone of the worst, each message on its own line of the badge's\n// title: the messages themselves are read where they belong, on the pin a\n// finding names (`pins`, the worst finding per input) and in the\n// Diagnostics tab, so the card carries a count, not a stack of truncated\n// sentences. The canvas runs no validator of its own:\n// `certify.CheckWorkspace` is the one rule set, and this function only\n// renders findings it is handed — it computes none itself. Node\n// resolution is the proto `nodeIdForDiagnostic` — the one Diagnostic →\n// node/group id mapping, so this file carries no second copy of it.\nimport type { CanvasView, Diagnostic } from '@lace-cloud/proto';\nimport { nodeIdForDiagnostic } from '@lace-cloud/proto';\nimport type { Badge, Decorations, NodeDecoration } from '../contributions';\n\n/** What the engine found on one of a node's inputs: the worst finding,\n * when it found more than one. */\nexport type PinFinding = { message: string; tone: Badge['tone'] };\n\n/** The decorations the canvas draws: each node's badges — the overlays'\n * and the engine's — and the engine's findings on its inputs, by input\n * name. An overlay hands in badges only (`Decorations`). */\nexport type DrawnDecorations = {\n nodes: Readonly<Record<string, NodeDecoration & { pins?: Readonly<Record<string, PinFinding>> }>>;\n};\n\nconst EMPTY_DECORATIONS: DrawnDecorations = { nodes: {} };\n\n// A node or group renders as errored on a badge's tone, never on a badge\n// merely being present — a neutral drift or warn badge must not turn it\n// red. The one gate ModuleNode and both group shapes (useGroupLogic) read;\n// the badges are the engine's findings, never a canvas-computed check.\nexport function hasErrorBadge(badges: readonly Badge[] | undefined): boolean {\n return (badges ?? []).some((b) => b.tone === 'error');\n}\n\nexport function decorate(\n view: Pick<CanvasView, 'nodes' | 'groups'>,\n overlayDecorations: readonly Decorations[],\n diagnostics: readonly Diagnostic[],\n): DrawnDecorations {\n if (overlayDecorations.length === 0 && diagnostics.length === 0) return EMPTY_DECORATIONS;\n\n const nodes: Record<string, { badges: Badge[]; pins?: Record<string, PinFinding> }> = {};\n const addBadge = (nodeId: string, badge: Badge) => {\n if (!nodes[nodeId]) nodes[nodeId] = { badges: [] };\n nodes[nodeId].badges.push(badge);\n };\n\n for (const overlayResult of overlayDecorations) {\n for (const [nodeId, decoration] of Object.entries(overlayResult.nodes)) {\n for (const badge of decoration.badges) addBadge(nodeId, badge);\n }\n }\n\n const byNode = new Map<string, Diagnostic[]>();\n for (const diagnostic of diagnostics) {\n const nodeId = nodeIdForDiagnostic(view, diagnostic);\n if (nodeId === null) continue;\n byNode.set(nodeId, [...(byNode.get(nodeId) ?? []), diagnostic]);\n }\n for (const [nodeId, held] of byNode) {\n addBadge(nodeId, diagnosticsBadge(held));\n const pins = pinFindings(held);\n if (pins) nodes[nodeId].pins = pins;\n }\n\n return { nodes };\n}\n\nconst TONE_RANK: Record<Badge['tone'], number> = { neutral: 0, warn: 1, error: 2 };\n\nfunction toneOf(d: Diagnostic): Badge['tone'] {\n return d.severity === 'error' ? 'error' : d.severity === 'warning' ? 'warn' : 'neutral';\n}\n\n// The worst finding the engine reported on each input of one node, by\n// input name; undefined when none names an input.\nfunction pinFindings(held: readonly Diagnostic[]): Record<string, PinFinding> | undefined {\n const pins: Record<string, PinFinding> = {};\n for (const d of held) {\n if (!d.input_name) continue;\n const tone = toneOf(d);\n const kept = pins[d.input_name];\n if (!kept || TONE_RANK[tone] > TONE_RANK[kept.tone]) {\n pins[d.input_name] = { message: d.message, tone };\n }\n }\n return Object.keys(pins).length > 0 ? pins : undefined;\n}\n\n// One node's findings as one badge.\nexport function diagnosticsBadge(held: readonly Diagnostic[]): Badge {\n const tone = held.map(toneOf).reduce((worst, t) => (TONE_RANK[t] > TONE_RANK[worst] ? t : worst));\n return {\n id: 'diagnostics',\n label: `${held.length} ${held.length === 1 ? 'problem' : 'problems'}`,\n tone,\n title: held.map((d) => d.message).join('\\n'),\n };\n}\n","/**\n * The id of a node's own handle pair, the grip below its card (source) and\n * the card itself (target): a drag from one node's grip onto another node\n * wires the pairs Lace's matcher finds between them. It names no pin, so it\n * never parses as one.\n */\nexport const NODE_HANDLE = 'node';\n\n/**\n * Extract the variable name from a handle ID of the form \"in:<name>\" or \"out:<name>\".\n * Returns null if the handle is missing or doesn't match the expected prefix.\n */\nexport function parseHandleId(\n handleId: string | null | undefined,\n prefix: 'in' | 'out',\n): string | null {\n if (!handleId) return null;\n const marker = `${prefix}:`;\n if (!handleId.startsWith(marker)) return null;\n const name = handleId.slice(marker.length);\n return name.length > 0 ? name : null;\n}\n\n/**\n * The source handle an edge leaves a node by: the handle of the output it\n * reads, or, for an edge that reads the whole call and names no output, the\n * node's call handle.\n */\nexport function sourceHandleId(output: string): string {\n return `out:${output}`;\n}\n","// A variable, output or pin as the canvas names it: its name and the type it\n// declares, or its name alone when it declares none — an empty type, as the IR\n// holds a variable with no type line.\nexport function typedName(name: string, type: string): string {\n return type ? `${name}: ${type}` : name;\n}\n","// A per-Canvas-instance channel for \"open this node's config\" requests.\n// ModuleNode's header click needs to reach Canvas.tsx's own selection +\n// go-to-node wiring; a window `CustomEvent` would cross-talk between two\n// Canvas mounts sharing one page (a global listener installed by one\n// mount fires for a click inside the other's tree too). A React context\n// scopes the channel to this Canvas's own component subtree instead —\n// there is exactly one provider per mounted Canvas, so exactly one\n// listener ever receives a given click.\nimport { createContext, type ReactNode, useContext, useRef } from 'react';\n\ntype OpenNodeConfig = (instanceId: string) => void;\n\nconst NodeConfigBusContext = createContext<OpenNodeConfig | null>(null);\n\nexport function NodeConfigBusProvider({\n onOpen,\n children,\n}: {\n onOpen: OpenNodeConfig;\n children: ReactNode;\n}) {\n // The callback Canvas passes in closes over per-render state (selection,\n // the xyflow-backed go-to-node ref) — capturing it in a ref keeps the\n // context value itself stable across renders while every call still\n // reaches the latest closure.\n const onOpenRef = useRef(onOpen);\n onOpenRef.current = onOpen;\n const stableRef = useRef<OpenNodeConfig>((instanceId) => onOpenRef.current(instanceId));\n return (\n <NodeConfigBusContext.Provider value={stableRef.current}>\n {children}\n </NodeConfigBusContext.Provider>\n );\n}\n\nexport function useOpenNodeConfig(): OpenNodeConfig {\n const fn = useContext(NodeConfigBusContext);\n if (!fn) throw new Error('useOpenNodeConfig: mount inside <NodeConfigBusProvider>');\n return fn;\n}\n","// pinColor maps a type family to a handle color, so inputs and outputs\n// of the same type family render with a consistent hue — Blender-style.\n//\n// Colors reference design tokens via CSS variable names. React accepts\n// `var(--…)` in inline style fields (`fill`, `background`, `borderColor`,\n// etc.), so xyflow's Handle + our SVG pins pick the tokenised color up\n// transparently.\n//\n// Palette is tuned to sit on the dark Lace canvas and stay legible\n// against the primary accent. These are the only socket colors — do\n// not add more families without discussing; too many hues become noise.\n\nexport type PinColor = {\n fill: string;\n stroke: string;\n};\n\nconst STRING: PinColor = {\n fill: 'var(--lace-pin-string-fill)',\n stroke: 'var(--lace-pin-string-stroke)',\n};\nconst NUMBER: PinColor = {\n fill: 'var(--lace-pin-number-fill)',\n stroke: 'var(--lace-pin-number-stroke)',\n};\nconst BOOL: PinColor = {\n fill: 'var(--lace-pin-bool-fill)',\n stroke: 'var(--lace-pin-bool-stroke)',\n};\nconst LIST: PinColor = {\n fill: 'var(--lace-pin-list-fill)',\n stroke: 'var(--lace-pin-list-stroke)',\n};\nconst MAP: PinColor = {\n fill: 'var(--lace-pin-map-fill)',\n stroke: 'var(--lace-pin-map-stroke)',\n};\nconst OBJECT: PinColor = {\n fill: 'var(--lace-pin-object-fill)',\n stroke: 'var(--lace-pin-object-stroke)',\n};\nconst ANY: PinColor = {\n fill: 'var(--lace-pin-any-fill)',\n stroke: 'var(--lace-pin-any-stroke)',\n};\n\nconst FAMILY_COLORS: Record<string, PinColor> = {\n string: STRING,\n number: NUMBER,\n bool: BOOL,\n boolean: BOOL,\n list: LIST,\n set: LIST,\n tuple: LIST,\n map: MAP,\n object: OBJECT,\n any: ANY,\n};\n\n/** Fallback pin color used when a pin's type family can't be matched.\n * Exported so downstream fallbacks don't duplicate the literal. */\nexport const ANY_PIN_COLOR: PinColor = ANY;\n\n/**\n * Infer type family from a raw HCL type string (fallback for when CLI\n * doesn't yet send type_family on NodePin).\n */\nfunction inferTypeFamily(type: string): string {\n const t = (type || '').trim().toLowerCase();\n if (t === '' || t === 'any') return 'any';\n // Check for compound types like \"list(string)\", \"map(object({...}))\"\n for (const family of ['list', 'set', 'tuple', 'map', 'object']) {\n if (t.startsWith(family)) return family;\n }\n return t; // \"string\", \"number\", \"bool\" fall through as-is\n}\n\n/**\n * Get the pin color for a NodePin. Prefers `type_family` if provided (from CLI),\n * falls back to inferring from the raw HCL type string.\n */\nexport function pinColor(pin: { type: string; type_family?: string }): PinColor {\n const family = pin.type_family ?? inferTypeFamily(pin.type);\n return FAMILY_COLORS[family] ?? ANY;\n}\n","// The canvas's surface: the brand's engineering paper, drawn with the\n// design tokens' own recipe (`.lace-paper-layers`: fine and major threads\n// in a 1:5 rhythm) on a layer behind the graph — so the forced-colors and\n// print escape that recipe carries applies here too.\n//\n// The paper is a backdrop: it stays where it is while the graph pans and\n// zooms over it, at the shell paper's own pitch and threads. Mounted as a\n// child of `ReactFlow`.\nimport './PaperGrid.css';\n\nexport default function PaperGrid() {\n return <div className=\"lace-paper-layers lace-canvas-paper\" aria-hidden=\"true\" />;\n}\n","// useActionKeys is the one keymap: every action's own `keys` (a declarative\n// binding, not a second imperative shortcut table) runs through the\n// identical `runner.run` a click does. A binding's `keyScope` names the\n// element that hears it, and each scope has one target an owner registers\n// (`registerKeyTarget`): `surface` is the canvas's own rendering surface\n// (Canvas.tsx), `app` the App root (App.tsx), which also holds the\n// drawer and the bottom panels — siblings of the surface a key\n// typed there never reaches. Never `window`: a window-level listener\n// intercepts every keydown on the page, including Mod+C over selected text\n// in a sibling panel that has nothing to do with the canvas.\n//\n// Focus guard, per scope: on the surface an event whose target is a form\n// control (input/textarea/select/contenteditable) is left alone — a\n// Backspace or Mod+Z typed into a node's rename field must keep the field's\n// own meaning; at the App root a form control's keys are matched too, so\n// Mod+S saves from an inspector field (no field uses the chord). Both skip\n// an event something upstream already handled (`defaultPrevented`). Node\n// delete itself stays on xyflow's own `deleteKeyCode` (Canvas.tsx), never a\n// second Backspace handler here.\n//\n// A handled key is consumed — `preventDefault` and `stopPropagation` — so\n// the host's own listener above the canvas (VS Code's undo and save on the\n// webview's window) never sees it; a key the keymap does not handle\n// propagates untouched.\n//\n// `App` (this hook's one call site) and `Canvas` (the surface owner) are\n// siblings under the same `CanvasCtx` object App builds each render, so the\n// registry keys on that object's identity — the one thing both share —\n// rather than threading DOM refs between components that don't otherwise\n// pass props to each other. With no target registered for a scope there is\n// nothing to bind its listener to, so the effect installs none.\n//\n// A key is delivered to the focused element, so the keymap hears it only\n// while focus is inside a target. A host can show the canvas with its\n// window focused and no element in it focused (a webview revealed without\n// taking focus, then activated by its tab header; a rebooted page): the\n// focused element is the body, outside every target. `useFocusWhenNoneHeld`\n// gives the `app` target's owner the remedy: the root takes focus when it\n// mounts with its window focused and when its window gains focus, each\n// time only while the body holds it, so focus in a field, or on any other\n// element inside or outside the App, stays where it is. A page whose window\n// is not focused when it mounts (a webview a host opened without taking\n// focus, beside the chat or editor that holds it) takes nothing: an unfocused\n// document's active element is its body too, and focusing the root from\n// inside that frame would pull the host's focus into it.\nimport { type RefObject, useEffect } from 'react';\nimport {\n type ActionContribution,\n type ActionTarget,\n type CanvasCtx,\n KEY_SCOPES,\n type KeyScope,\n} from '../contribution-types';\nimport { parseChord } from '../utils/key-chord';\nimport type { ActionRunner, EditorEnvExtras } from './run-binding';\n\n// One rule per scope, total over `KeyScope`: the effect binds a listener\n// for every name in `KEY_SCOPES` and reads that scope's rule here.\nexport type KeyScopeRules = Record<KeyScope, { handlesFormTargets: boolean }>;\n\nconst KEY_SCOPE_RULES: KeyScopeRules = {\n surface: { handlesFormTargets: false },\n app: { handlesFormTargets: true },\n};\n\nconst targetsByCtx = new WeakMap<CanvasCtx, Partial<Record<KeyScope, EventTarget>>>();\n\nexport function registerKeyTarget(\n ctx: CanvasCtx,\n scope: KeyScope,\n target: EventTarget | null,\n): void {\n const targets = targetsByCtx.get(ctx) ?? {};\n if (target) targets[scope] = target;\n else delete targets[scope];\n targetsByCtx.set(ctx, targets);\n}\n\nexport function isFormTarget(target: EventTarget | null): boolean {\n if (!(target instanceof HTMLElement)) return false;\n const tag = target.tagName;\n return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable;\n}\n\nexport function useFocusWhenNoneHeld(root: RefObject<HTMLElement>, mounted: boolean): void {\n useEffect(() => {\n const element = root.current;\n if (!mounted || !element) return;\n const doc = element.ownerDocument;\n const takeFocus = () => {\n if (doc.activeElement === null || doc.activeElement === doc.body) {\n element.focus({ preventScroll: true });\n }\n };\n if (doc.hasFocus()) takeFocus();\n const view = doc.defaultView;\n view?.addEventListener('focus', takeFocus);\n return () => view?.removeEventListener('focus', takeFocus);\n }, [root, mounted]);\n}\n\nfunction keyScopeOf(action: ActionContribution): KeyScope {\n return action.keyScope ?? 'surface';\n}\n\nfunction matchesKey(e: KeyboardEvent, spec: string): boolean {\n const chord = parseChord(spec);\n if (!chord) return false;\n if (!(e.metaKey || e.ctrlKey) || e.shiftKey !== chord.shift) return false;\n return e.key.toLowerCase() === chord.key.toLowerCase();\n}\n\nexport function useActionKeys(\n actions: readonly ActionContribution[],\n ctx: CanvasCtx | null,\n runner: ActionRunner,\n envExtras: EditorEnvExtras | null,\n): void {\n useEffect(() => {\n if (!ctx || !envExtras) return;\n // Rebind to `const`s TS can carry into the nested `onKeyDown` closure —\n // the guard above already proved both non-null for this effect run.\n const activeCtx = ctx;\n const activeEnvExtras = envExtras;\n const targets = targetsByCtx.get(ctx) ?? {};\n const target: ActionTarget = {};\n\n function bind(scope: KeyScope): (() => void) | undefined {\n const { handlesFormTargets } = KEY_SCOPE_RULES[scope];\n const element = targets[scope];\n if (!element) return undefined;\n const keyed = actions.filter((a) => (a.keys?.length ?? 0) > 0 && keyScopeOf(a) === scope);\n\n function onKeyDown(e: Event) {\n // `addEventListener`'s own type is generic over `Event` — the target\n // is whatever `EventTarget` its owner registered, so this narrows at\n // runtime rather than asserting a `KeyboardEvent` the type system\n // can't actually prove a `keydown` listener receives.\n if (!(e instanceof KeyboardEvent)) return;\n if (e.defaultPrevented) return;\n if (!handlesFormTargets && isFormTarget(e.target)) return;\n for (const action of keyed) {\n for (const spec of action.keys ?? []) {\n if (matchesKey(e, spec)) {\n e.preventDefault();\n e.stopPropagation();\n void runner.run(action, activeCtx, target, activeEnvExtras);\n return;\n }\n }\n }\n }\n\n element.addEventListener('keydown', onKeyDown);\n return () => element.removeEventListener('keydown', onKeyDown);\n }\n\n const unbind = KEY_SCOPES.map(bind);\n return () => {\n for (const off of unbind) off?.();\n };\n }, [actions, ctx, runner, envExtras]);\n}\n","// The React-free contribution types: overlays, actions, the bindings an\n// action runs, the contexts a binding runs over and what a panel declares.\n// The core registers through these, so a host extension registers through\n// the same surface its own features use — no canvas-private mechanism\n// bypasses the registry. Every capability the canvas renders is one of: a\n// `command` binding (a bound CLI path), an `editor` binding (an IR edit or\n// generate), or a `host` binding — a host-supplied handler for a capability\n// that is neither (a VS Code command, a webview message, the host's own\n// navigation). A `host` binding runs through the identical\n// available/confirm/tick path every other binding does (registry.ts,\n// core/run-binding.ts); the only extra thing it may touch is whatever the\n// host closure captures. Core never constructs one — a core capability is\n// always `command` or `editor` (contributions-contract.test.ts).\n//\n// This file holds the contribution types and the one value they are\n// derived from (`KEY_SCOPES`), and imports nothing from React, not even a type:\n// every module the React-free entry (`engine/index.ts`) reaches takes its\n// contribution types from here, so the entry's declarations typecheck in a\n// host with no React types installed (`__tests__/engine-entry-static.test.ts`).\n// The one React-typed shape, a panel's component, lives in contributions.ts.\n// The two constructors live beside the primitives they compose\n// (`defineCommand`, core/define-command.ts; `defineOverlay`,\n// core/define-overlay.ts), so importing a contract type loads nothing.\nimport type { CanvasView, Diagnostic } from '@lace-cloud/proto';\nimport type { ArgsOf, BoundPath, CommandFailure, JsonOf, LaceReason } from './contracts';\nimport type { Bundle } from './generated/state';\nimport type {\n CanvasPorts,\n CommandResult,\n ConfirmSpec,\n EditorPort,\n PortName,\n RunnerPorts,\n StackRef,\n} from './ports';\nimport type { CanvasArrangement } from './types/render';\nimport type { KeySpec } from './utils/key-chord';\n\n// The two edge endpoints an inspector shows — App resolves the pairing off\n// xyflow's own edge-click event and holds it as `CanvasCtx.selection.edge`.\nexport type EdgeRef = {\n id: string;\n source: string;\n target: string;\n sourceOutput: string;\n targetInput: string;\n};\n\nexport type ContextKey =\n | 'root'\n | 'sessionId'\n | 'stack'\n // Satisfied iff `ctx.editable` — the editor port is present and the\n // session is not source-refused. The one read-only derivation\n // (registry.ts's `contextSatisfied`); mutation contributions keep their\n // own `requiredPorts: ['editor']` for port presence and add this key to\n // gate on the lock too.\n | 'editable'\n // Satisfied iff `!ctx.view.unsaved` — nothing for Save to write.\n | 'saved'\n // Satisfied iff `ctx.view.unsaved` — an edit Save has not written yet.\n // The Unsaved marker's gate.\n | 'unsaved'\n // Satisfied iff `ctx.view.conflict === undefined` — no open Keep/Reload\n // conflict.\n | 'resolved'\n // Satisfied iff `ctx.view.conflict` is set — the tf changed under an\n // unsaved or ungenerated working IR and waits on Keep or Reload. The\n // conflict banner's gate.\n | 'conflict'\n // Satisfied iff `ctx.sourceRefused` — the engine refuses the module's tf,\n // and with it every edit, save, generate, Keep and Reload. The\n // source-refused banner's gate.\n | 'sourceRefused'\n // Satisfied iff `ctx.sourceRefused` and the refusal is lace shape's — a\n // `not_lace_shape` diagnostic among `ctx.diagnostics`: the tree is out of\n // lace shape. The source-refused banner's out-of-lace-shape opening, and\n // the gate Convert declares on its row.\n | 'needsConversion'\n | 'selection.node'\n | 'selection.edge'\n // Satisfied iff `ctx.diagnostics` is non-empty — the diagnostics panel's\n // own gate, so a mount with nothing to show never draws an empty bottom\n // tab (registry.ts's `contextSatisfied`).\n | 'diagnostics'\n // Satisfied iff `ctx.settingsOpen` — the settings panel's own gate, so a\n // closed settings panel resolves nothing and its column takes no space.\n | 'settingsOpen'\n // Satisfied iff `ctx.generating` is false — no Generate is running on the\n // session (`CanvasSource.generating`), the one gate that keeps the\n // canvas from asking for a second.\n | 'generateIdle'\n // Satisfied iff `ctx.generating` — a Generate is running. Generate's\n // `busy.when`: the toolbar draws it in flight.\n | 'generating'\n // Satisfied iff `ctx.view.ungenerated` — the saved IR has not been\n // generated into the module's tree. Generate's `primary.when`: the\n // toolbar draws it as the call to action while there is something to\n // generate; with `generateIdle`, the Not generated marker's gate.\n | 'ungenerated'\n // Satisfied iff `ctx.view.can_undo` / `ctx.view.can_redo` — the session\n // holds an edit to step back over / forward over again.\n | 'undoable'\n | 'redoable';\n\n// What a command or host binding runs over: the authoring root, the\n// session open on it and the stack the host chose. A host with no canvas\n// (an extension's stacks tree) runs the same bindings over this alone, one\n// runner for every root it holds: a command whose action declares `root`\n// runs in this `root` (`BindingRuntime.cwd`). `CanvasCtx` is this plus the\n// canvas's own facts, its three fields read off the host's `context` port.\nexport type RunCtx = {\n root?: string;\n sessionId?: string;\n stack?: StackRef;\n};\n\nexport type CanvasCtx = RunCtx & {\n ports: CanvasPorts;\n // `ports.editor !== undefined && !source.sourceRefused` — the one\n // read-only derivation, already threaded through xyflow's own props and\n // the keymap; carried here too so it doubles as the `'editable'` context\n // key.\n editable: boolean;\n // `source.generating` of this frame: a Generate is running on the\n // session, from the call until the engine answers it. The\n // `'generateIdle'` and `'generating'` context keys read it.\n generating: boolean;\n // `source.sourceRefused` of this frame: the engine refuses the module's\n // tf. `editable` is derived from it; the `'sourceRefused'` context key\n // reads it.\n sourceRefused: boolean;\n view: CanvasView;\n selection: { nodes: readonly string[]; edge: EdgeRef | null };\n // Whether the developer has the settings panel open — App's own state,\n // opened by the Settings toolbar toggle and closed by the panel's Close.\n // The `'settingsOpen'` context key reads it.\n settingsOpen: boolean;\n // `source.diagnostics` of this same frame — the engine's live findings,\n // unfiltered by scope resolution — merged with the current report's\n // findings (`diagnosticsOf`, core/diagnostics.ts). decorate and\n // DiagnosticsPanel both read this one list.\n diagnostics: readonly Diagnostic[];\n // The merged core + host contribution set (App's `merged`, unresolved) —\n // a panel's own row actions (`rowActionsFor`, core/panels/row-actions.ts)\n // resolve against this, so a host-supplied row action renders next to a\n // core one instead of the panel only ever seeing `CORE_ACTIONS`. A panel\n // in it is its `PanelSpec`: nothing reading a context renders a panel.\n contributions: ContributionSet;\n};\n\nexport type Badge = {\n id: string;\n label: string;\n tone: 'neutral' | 'warn' | 'error';\n title?: string;\n};\nexport type NodeDecoration = { badges: readonly Badge[] };\nexport type Decorations = { nodes: Readonly<Record<string, NodeDecoration>> };\n\nexport type OverlayContribution = {\n id: string;\n paths: readonly BoundPath[];\n useDecorations: (ctx: CanvasCtx) => Decorations;\n};\n\nexport type CommandRead<P extends BoundPath> = {\n path: P;\n args: (ctx: CanvasCtx, target: ActionTarget) => ArgsOf<P> | null; // null = don't fetch\n};\n\n// What a panel declares apart from the component that draws it: the fields\n// the registry resolves it on and the chrome lists it by. The React surface's\n// `Panel` (contributions.ts) is this plus its `Component`.\nexport type PanelSpec = {\n id: string;\n // The label chrome lists the panel by — the bottom-tab strip's tab, the\n // drawer's accessible name — never the bare `id`, which is a stable\n // identifier, not UI copy.\n title: string;\n // Where App draws it: a row under the toolbar (`banner`), in the toolbar,\n // in the right-hand drawer — one panel at a time, the first that resolves\n // — or as a tab under the canvas (`bottom`).\n slot: 'banner' | 'toolbar' | 'drawer' | 'bottom';\n requiredPorts: readonly PortName[];\n // requiredCommands is derived from `reads` + row actions, not declared —\n // a panel that reads through `useCommandRead` needs no second list naming\n // the same path.\n reads?: readonly { path: BoundPath }[];\n requiredContext?: readonly ContextKey[];\n // A toolbar panel's place in the row: the end of the section of actions it\n // names (`ActionContribution.section`); naming none, or a section no\n // action resolved into, the row's far end (the Settings toggle).\n section?: string;\n};\n\n// A row action's target is the row's own datum, passed through generically\n// — `diagnostic` for a diagnostics row, `runId` for a run a host lists,\n// `failure` for a failure row — never a single-purpose field minted for one\n// consumer; a host row action reads whichever row datum it needs off here.\nexport type ActionTarget = {\n // The node or group a menu opened on.\n nodeId?: string;\n // Set too when that node is a group: an action only a group takes\n // (Ungroup) requires it.\n groupId?: string;\n diagnostic?: Diagnostic;\n runId?: string;\n // A failure row's datum: the failure document a command ended on, whole,\n // which a host passes as `{ failure }`.\n failure?: CommandFailure;\n};\n\n// Where an action is offered: the toolbar; the menu a node or a group opens\n// on (`node-menu`, its target the node); the menu the empty canvas opens on\n// (`pane-menu`, no target — Paste); or a panel's row.\nexport type Placement = 'toolbar' | 'node-menu' | 'pane-menu' | { row: string };\n\nexport type ResultKind = 'run' | 'preview' | 'report' | 'notify' | 'follow';\n\n// The result kinds `ResultStore` actually holds a slot for — every kind but\n// `notify`, which routes straight to `presenter.notify` and never persists\n// (the store marks a notify invocation running while it runs, by the target\n// it runs on, and holds nothing of what it said).\n// `write` (below) is typed over this narrower set, not `ResultKind`: a\n// generic `K extends ResultKind` would range over `notify` too, and\n// `SinkInput['notify']` (`unknown`, since `notify` carries no shape of its\n// own) collapses `SinkInput[K]` back to `unknown` inside the function body —\n// forcing an `as` at the one place that indexes it.\nexport type SlotKind = Exclude<ResultKind, 'notify'>;\n\n// `report`'s input is no command's own event stream: it is the result of a\n// command that ran in the session's root, as the session publishes it to\n// every subscriber (`CommandResult`, ports.ts). No command binding's sink\n// writes it; the source subscription does (App).\nexport type SinkInput = {\n run: JsonOf<'stack apply'>;\n preview: JsonOf<'stack preview'>;\n report: CommandResult;\n notify: unknown;\n follow: JsonOf<'run logs'>;\n};\n\ntype ResultFor<P extends BoundPath> = {\n [K in ResultKind]: JsonOf<P> extends SinkInput[K] ? K : never;\n}[ResultKind];\n\n// A store write carries the token the runner minted for this invocation: a\n// write for a token the runner has since detached (a new invoke on the\n// same slot, or an explicit cancel/unmount) is dropped by the store, not\n// by the sink — the sink stays a pure mapping from an event to a value.\nexport type BindingRuntime = {\n ports: RunnerPorts;\n token: object;\n // The directory this run's command runs in (`CommandsPort.invoke`'s\n // `cwd`): the run's `root` when the action declares `root` in its\n // `requiredContext`, which the runner has checked is present; absent for\n // an action that declares none, which runs in the port's own directory.\n cwd?: string;\n write: <K extends SlotKind>(kind: K, token: object, value: SinkInput[K]) => void;\n detach: <K extends ResultKind>(kind: K, token: object) => void;\n // Seeds what this invocation's kind holds before any wire event exists —\n // its slot, or a notify invocation's running mark — not a fake wire event\n // through `write`; what a seed is per result kind is the ResultStore's\n // (core/results.ts `begin`), never the binding's.\n begin: () => void;\n // Settles this invocation's own slot on a failed stream; `false` when its\n // result kind has no failed state to render, so the binding surfaces the\n // failure itself.\n fail: (error: unknown) => boolean;\n tick: () => void;\n // Called once this invocation's own event-consuming loop actually ends\n // (success or failure) — not when `ErasedCommand.start` merely resolves,\n // which happens as soon as the invocation begins so the runner can hold\n // its `cancel(slot)` handle while consumption keeps running in the\n // background. A `notify` sink has no store slot of its own to ever\n // detach/supersede it, so this is the one hook the runner has to end its\n // running mark and prune its own bookkeeping (`notifyControllers`,\n // run-binding.ts) once the invocation is truly done.\n settled?: () => void;\n};\n\n// A `Sink<T>` is a value, not a function type, so `CommandBinding.result` is\n// cast-free: `SinkInput[K] extends T` narrows `consume`'s event parameter\n// without an `as` at the call site.\nexport type Sink<T> = { kind: ResultKind; consume: (rt: BindingRuntime, e: T) => void };\n\nexport type CommandBinding<P extends BoundPath> = {\n kind: 'command';\n path: P;\n args: (ctx: RunCtx, target: ActionTarget) => Partial<ArgsOf<P>>;\n confirm?: (ctx: RunCtx, args: ArgsOf<P>, target: ActionTarget) => ConfirmSpec;\n result: Sink<JsonOf<P>> & { kind: ResultFor<P> };\n invalidates?: true | 'start+settle';\n};\n\n// The runner owns one clipboard slot (copy/cut record the selection here;\n// paste reads and clears it) — module-scope state would leak across\n// concurrent runners (Storybook mounts several), so it travels through\n// EditorEnv like arrangement/layout rather than living in editor-actions.ts.\nexport type ClipboardStore = {\n get: () => { ids: readonly string[]; cut: boolean } | null;\n set: (ids: readonly string[], cut: boolean) => void;\n clear: () => void;\n};\n\n// A stable object Canvas overwrites with its own xyflow-backed\n// implementation once mounted. `panIntoView` is view chrome: it pans the\n// camera the least distance that brings a rect inside the pane, never a\n// node, never the zoom, and stores nothing. The canvas composes it to bring\n// what a frame adds into view and to go to a node. Shared by `EditorEnv`\n// and `CanvasContextValue` so App's toolbar-run extras and a panel's\n// row-run extras see the identical instance rather than each inventing\n// their own.\nexport type LayoutHandle = {\n panIntoView: (rect: { x: number; y: number; width: number; height: number }) => void;\n};\n\nexport type EditorEnv = {\n editor: EditorPort;\n // The one `editor.apply` entry point — the identical `applyActions`\n // helper `ActionRunner.apply` exposes for an ungoverned gesture\n // (run-binding.ts), so a registered binding's own multi-step mutation\n // (paste's copy-then-delete, group's create) reports a rejected batch to\n // `presenter.notify` at the exact call that failed, never a second time\n // from a wrapper reading the same result back.\n apply: (\n actions: readonly import('./generated/service').Action[],\n ) => Promise<import('./ports').ApplyResult>;\n ctx: CanvasCtx;\n target: ActionTarget;\n // The Bundle backing `ctx.view` — group/ungroup/paste resolve a canvas\n // path to its arrangement scope key (`scopeKeyForCanvasPath`), which\n // needs the Bundle the view was projected from, not the view itself.\n bundle: Bundle;\n clipboard: ClipboardStore;\n arrangement: { get: () => CanvasArrangement; update: (a: CanvasArrangement) => void };\n layout: LayoutHandle;\n};\n\nexport type EditorBinding = { kind: 'editor'; confirm?: (ctx: CanvasCtx) => ConfirmSpec } & (\n | { result: 'apply'; run: (env: EditorEnv) => Promise<import('./ports').ApplyResult> }\n | { result: 'generate'; run: (env: EditorEnv) => AsyncIterable<import('./ports').GenerateEvent> }\n | { result: 'none'; run: (env: EditorEnv) => Promise<void> }\n);\n\n// A host-supplied handler for a capability with no CLI command — e.g. a VS\n// Code command a canvas action merely triggers, or opening a diagnostic's\n// source file. `run` gets the same `BindingRuntime` a command binding's\n// `start` does, so a host action that does invalidate a read can call\n// `rt.tick()` (or set `invalidates` and let the runner call it at settle)\n// the same way a core action would; anything beyond that is the host's own\n// closure, not a second port the registry has to know about.\nexport type HostBinding = {\n kind: 'host';\n confirm?: (ctx: RunCtx) => ConfirmSpec;\n invalidates?: true;\n run: (rt: BindingRuntime, ctx: RunCtx, target: ActionTarget) => Promise<void>;\n};\n\n// Built by `defineCommand<P>` (core/define-command.ts): erases the\n// path-specific generics behind one shape the runner and registry share, so\n// an `ActionContribution[]` array mixing bindings for different paths\n// type-checks without a cast.\nexport type ErasedCommand = {\n kind: 'command';\n path: BoundPath;\n confirms: boolean;\n resultKind: ResultKind;\n invalidates?: true | 'start+settle';\n // The same `args(ctx, target)`, erased to a plain record rather than a\n // typed `Partial<ArgsOf<P>>` — the runner completes it with `completeArgs`\n // (a value-based required-key check; a key present with `undefined` still\n // counts as missing) before ever asking for a form.\n partialArgs: (ctx: RunCtx, target: ActionTarget) => Record<string, unknown>;\n // The binding's own confirm spec against the completed args (its own\n // `args` merged with any form-collected values via `completeArgs`) —\n // `undefined` when the binding declares no confirm, or when the args\n // aren't complete yet. Building the spec is this binding's own concern\n // (it alone knows its typed `args`/`confirm`); asking the user is the\n // runner's — `core/run-binding.ts` is the one `presenter.confirm(` call\n // site for every binding kind, command included.\n confirmSpec: (\n ctx: RunCtx,\n target: ActionTarget,\n formArgs: Record<string, unknown>,\n ) => ConfirmSpec | undefined;\n // Resolves as soon as the invocation starts, so the ActionRunner can hold\n // the returned handle for `cancel(slot)` while the event-consuming loop\n // keeps running in the background; `null` when the binding declined to\n // run (no `commands` port, or the args still aren't complete). Confirming\n // has already happened by the time `start` is called — this never asks.\n start: (\n rt: BindingRuntime,\n ctx: RunCtx,\n target: ActionTarget,\n formArgs: Record<string, unknown>,\n signal: AbortSignal,\n ) => Promise<{ cancel: () => Promise<void> } | null>;\n};\n\n// Which element hears an action's `keys` (`core/use-action-keys.ts`):\n// `surface` is the canvas's own rendering surface, where a form control\n// keeps every key for itself; `app` is the App root, which also covers the\n// drawer and the bottom panels, and where a bound chord is handled\n// even from a form control (a field has no use for Mod+S). The names are\n// declared once, here: the keymap binds one listener per entry and holds one\n// rule per `KeyScope`, so a scope added to this tuple has both or does not\n// compile.\nexport const KEY_SCOPES = ['surface', 'app'] as const;\nexport type KeyScope = (typeof KEY_SCOPES)[number];\n\n// The glyphs an action may name for the toolbar to draw\n// (components/icons.tsx).\nexport type ActionIcon = 'validate' | 'convert' | 'save' | 'generate' | 'undo' | 'redo' | 'clear';\n\nexport type ActionContribution = {\n id: string;\n label: string;\n // The sentence a banner says of this action as one of its choices: a\n // banner states its fact, then the `choice` of each action resolved on its\n // row, in resolve order (core/panels/RowActionBanner.tsx). The toolbar and\n // the menus ignore it.\n choice?: string;\n // How the toolbar draws the action. With `icon` and no `primary`, an\n // icon button whose tooltip names it (and its key); with `primary`, the\n // labelled call to action, its glyph beside the label, filled in the\n // accent while `primary.when` holds (always, with no `when`) and quiet\n // otherwise. With neither, a text button carrying the label — a host's\n // action with no glyph of its own still reads.\n icon?: ActionIcon;\n primary?: { when?: ContextKey };\n // While `busy.when` holds the action is running: the toolbar draws it\n // with a spinner and `busy.label` (Generate's \"Generating…\"). A command\n // binding's own running slot draws the same way, under the action's label.\n busy?: { when: ContextKey; label: string };\n // The toolbar and the menus draw their actions in sections by intent —\n // Validate and Convert check, Save and Generate write, Undo and Redo walk\n // history; Copy and Cut, then Group and Ungroup, then Delete — with a\n // hairline between sections, in the order each first appears. A toolbar\n // panel naming a section sits at its end (the Unsaved and Not generated\n // chips beside Generate). Actions naming none form one section after the\n // named ones.\n section?: string;\n // An action that removes something: a menu draws it in the danger tone.\n tone?: 'danger';\n // The keys that run the action, in the keymap's grammar: `Mod`, an\n // optional `Shift`, then the key. The type (`KeySpec`) checks the `Mod+`\n // prefix; `parseChord` refuses the rest at runtime.\n keys?: readonly KeySpec[];\n /** Defaults to `surface`. */\n keyScope?: KeyScope;\n placement: Placement;\n requiredPorts: readonly PortName[];\n requiredContext?: readonly ContextKey[];\n requiredTarget?: readonly (keyof ActionTarget)[];\n // The failure reasons the action answers. An action on the failure row\n // (`row: 'failure'`) names them: it resolves only on a target whose\n // `failure` has one of them, and one there that names none answers no\n // failure. An action elsewhere that names them resolves the same way.\n // Either needs no `requiredTarget: ['failure']` beside it.\n answers?: readonly LaceReason[];\n // The action still resolves (renders) when a key here fails — it's shown\n // disabled instead, carrying the first failing entry's `reason` for the\n // toolbar/menu/row renderer's disabled title and for `ActionRunner.run`'s\n // own refusal notify. Order matters: the first entry that fails wins, so\n // Generate lists `resolved` before `saved` (registry.ts's\n // `disabledReason`).\n enabledWhen?: readonly { key: ContextKey; reason: string }[];\n binding: ErasedCommand | EditorBinding | HostBinding;\n};\n\n// A contribution set over the panel shape its holder needs: the registry and\n// `CanvasCtx` read a panel's `PanelSpec` alone, so the default set carries\n// no component; the React surface's `Contributions` (contributions.ts) is the\n// set over `Panel`.\nexport type ContributionSet<P extends PanelSpec = PanelSpec> = {\n overlays: readonly OverlayContribution[];\n panels: readonly P[];\n actions: readonly ActionContribution[];\n};\n","import { useCallback, useState } from 'react';\n\nexport type ContextMenuState = {\n x: number;\n y: number;\n nodeId: string | null;\n groupId: string | null;\n} | null;\n\nexport type ContextMenuRequest = {\n instanceId: string | null;\n groupId: string | null;\n x: number;\n y: number;\n};\n\n// The state (and the `showContextMenu` setter below) is owned by the one\n// Canvas instance that calls this hook — xyflow's own\n// `onNodeContextMenu`/`onPaneContextMenu` handlers call `showContextMenu`\n// directly rather than a window `CustomEvent`, so two Canvas mounts on one\n// page never see each other's right-clicks (a window listener is global;\n// this state is per-component-tree).\nexport function useContextMenu() {\n const [contextMenu, setContextMenu] = useState<ContextMenuState>(null);\n\n const showContextMenu = useCallback((request: ContextMenuRequest) => {\n setContextMenu({\n x: request.x,\n y: request.y,\n nodeId: request.instanceId,\n groupId: request.groupId,\n });\n }, []);\n\n const dismissContextMenu = useCallback(() => {\n setContextMenu(null);\n }, []);\n\n return { contextMenu, showContextMenu, dismissContextMenu };\n}\n","// Turns the projected CanvasView into the nodes and edges xyflow draws.\n// Where everything is drawn is the projection's (packages/proto's\n// projectCanvasView): a card's top-left, a group's box and its members'\n// origin. This file only re-expresses it the way xyflow nests nodes — every\n// member, card or group, is a child of its group (`parentId`), positioned\n// from the group's box — and hides a collapsed group's members and the\n// wires between them behind its card. Every edge the projection draws joins\n// two children of one scope, so no wire crosses a group's boundary; a\n// collapsed group's card draws its interface's pins, and the wires that\n// read or feed them land there. Whether a group is collapsed lives in the\n// consumer-owned CanvasArrangement and never reaches Terraform.\n\nimport type { XY } from '@lace-cloud/proto';\nimport type { Edge, Node } from '@xyflow/react';\nimport { useMemo } from 'react';\nimport { DEPENDENCY_EDGE_TYPE } from '../components/edges/DependencyEdge';\nimport type { InterfacePin } from '../components/nodes/GroupNode';\nimport { pinColor } from '../components/nodes/pinColor';\n\nimport { type DrawnDecorations, hasErrorBadge } from '../core/decorate';\nimport type { NodePin, RenderEdge, RenderGroup, RenderNode } from '../types/render';\nimport { sourceHandleId } from '../utils/handleId';\n\ntype GroupLogicResult = {\n rfNodes: Node[];\n rfEdges: Edge[];\n};\n\n/**\n * Where an xyflow node is drawn, in canvas coordinates: its own position,\n * or — for a member, which xyflow positions from its group's box — that\n * position plus where the projection drew the box. The inverse of the\n * nesting `useGroupLogic` builds, read against the projected groups, so a\n * drag reads what the projection drew around it rather than where xyflow\n * has the group mid-gesture.\n */\nexport function drawnPosition(\n groups: readonly RenderGroup[],\n node: Pick<Node, 'position' | 'parentId'>,\n): XY {\n const parent = node.parentId ? groups.find((g) => g.id === node.parentId) : undefined;\n if (!parent) return node.position;\n return { x: parent.position.x + node.position.x, y: parent.position.y + node.position.y };\n}\n\n// ── Hook ──\n\nexport function useGroupLogic(\n nodes: RenderNode[],\n edges: RenderEdge[],\n groups: RenderGroup[],\n newNodeIds: Set<string>,\n decorations?: DrawnDecorations,\n): GroupLogicResult {\n return useMemo(() => {\n // Who contains whom: a group's `node_ids` name its members, cards and\n // groups alike. A collapsed group hides every member and every\n // descendant, however deep.\n const parentOf = new Map<string, RenderGroup>();\n for (const g of groups) {\n for (const id of g.node_ids) parentOf.set(id, g);\n }\n const hiddenCache = new Map<string, boolean>();\n // Whether the members of group `g` are hidden: it or an ancestor is\n // collapsed.\n const membersHidden = (g: RenderGroup): boolean => {\n const cached = hiddenCache.get(g.id);\n if (cached !== undefined) return cached;\n const parent = parentOf.get(g.id);\n const hidden = g.collapsed || (parent ? membersHidden(parent) : false);\n hiddenCache.set(g.id, hidden);\n return hidden;\n };\n // xyflow positions a child from its parent's box.\n const nested = (id: string, at: XY): Pick<Node, 'position' | 'parentId' | 'hidden'> => {\n const parent = parentOf.get(id);\n if (!parent) return { position: at };\n return {\n position: { x: at.x - parent.position.x, y: at.y - parent.position.y },\n parentId: parent.id,\n hidden: membersHidden(parent) || undefined,\n };\n };\n\n const rfNodes: Node[] = [];\n\n // Groups first, in the projection's order — a parent before its\n // children, which xyflow needs to place a child from its parent.\n for (const group of groups) {\n const memberCount = group.node_ids.length;\n const groupBadges = decorations?.nodes[group.id]?.badges ?? [];\n const base = {\n id: group.id,\n type: 'groupNode',\n ...nested(group.id, group.position),\n };\n if (group.collapsed) {\n // A diagnostic addressed to the group's own scope (a submodule\n // root) resolves through `nodeIdForAddress` to the group's own id,\n // not any member's — those badges live in `decorations.nodes[group.id]`\n // and, collapsed, are the only decoration a user can see at all\n // (every member carrying its own badge is hidden). `hasErrors`\n // also rolls up a hidden member's own error so the collapsed\n // group's border reflects it.\n const hasErrors =\n group.node_ids.some((id) => hasErrorBadge(decorations?.nodes[id]?.badges)) ||\n hasErrorBadge(groupBadges);\n rfNodes.push({\n ...base,\n data: {\n groupId: group.id,\n moduleKey: group.module_key ?? '',\n label: group.label,\n memberCount,\n collapsed: true,\n hasErrors,\n badges: groupBadges,\n interfacePins: pinsOf(group),\n },\n });\n } else {\n rfNodes.push({\n ...base,\n style: { width: group.size.width, height: group.size.height },\n data: {\n groupId: group.id,\n moduleKey: group.module_key ?? '',\n label: group.label,\n memberCount,\n collapsed: false,\n hasErrors: hasErrorBadge(groupBadges),\n badges: groupBadges,\n interfacePins: [],\n },\n });\n }\n }\n\n // Every card, a member placed from its group's box. A hidden member\n // stays in the list: xyflow still keeps its bookkeeping.\n for (const n of nodes) {\n rfNodes.push({\n id: n.id,\n type: 'moduleNode',\n ...nested(n.id, n.position),\n data: {\n ...n,\n isNew: newNodeIds.has(n.id),\n badges: decorations?.nodes[n.id]?.badges,\n pins: decorations?.nodes[n.id]?.pins,\n },\n });\n }\n\n // A wire joins two children of one scope, so it is hidden with them\n // when that scope is a group whose members are hidden.\n const rfEdges = edges\n .filter((e) => {\n const scope = parentOf.get(e.source);\n return !(scope && membersHidden(scope));\n })\n .map(renderEdgeToRfEdge);\n\n return { rfNodes, rfEdges };\n }, [nodes, edges, groups, newNodeIds, decorations]);\n}\n\n// ── Helpers ──\n\n// A collapsed group's pins: its module's Interface (`groupPins`, which\n// `projectGroup` reads), inputs on the left rail and outputs on the right,\n// each whether or not a wire reaches it.\nfunction pinsOf(group: RenderGroup): InterfacePin[] {\n const pins = (side: InterfacePin['side'], prefix: string, of: readonly NodePin[] = []) =>\n of.map((pin) => ({ ...pin, handleId: `${prefix}:${pin.name}`, side, color: pinColor(pin) }));\n return [...pins('input', 'in', group.inputs), ...pins('output', 'out', group.outputs)];\n}\n\n// The `data` shape every rfEdge this file builds carries.\nexport type RfEdgeData = {\n source_output: string;\n target_input: string;\n};\n\n// Runtime-narrows an xyflow `Edge.data` (typed `Record<string, unknown> |\n// undefined` by xyflow itself) back to the shape this file produced it in,\n// rather than a component reading it back (Canvas.tsx's edge click/delete\n// handlers) asserting the type with `as`. `null` when the edge wasn't one\n// of this file's own — a required field missing or the wrong type.\nexport function rfEdgeData(edge: Edge): RfEdgeData | null {\n const data = edge.data;\n const sourceOutput = data?.source_output;\n const targetInput = data?.target_input;\n if (typeof sourceOutput !== 'string' || typeof targetInput !== 'string') return null;\n return { source_output: sourceOutput, target_input: targetInput };\n}\n\nfunction renderEdgeToRfEdge(e: RenderEdge): Edge {\n return {\n id: e.id,\n source: e.source,\n target: e.target,\n sourceHandle: sourceHandleId(e.source_output),\n targetHandle: `in:${e.target_input}`,\n data: { source_output: e.source_output, target_input: e.target_input },\n type: DEPENDENCY_EDGE_TYPE,\n };\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\nimport type { CanvasView } from '../types/render';\n\n// What the frames after the session's first have added: `addedIds`, every\n// card a frame added that is still drawn — a module's card or a group's —\n// and of the module cards among them `newNodeIds`, the ones the developer\n// has not selected yet, which draw as new. An added card stays new across\n// later frames until the developer selects it — a click, a drag (xyflow\n// selects what it drags), opening it — and `clearNew` names the cards\n// selected; selecting one never takes it out of `addedIds`. A card a frame\n// no longer holds leaves both, so one a later frame adds again is added,\n// and new, again.\nexport function useNewNodeTracking(view: CanvasView | null) {\n const [addedIds, setAddedIds] = useState<Set<string>>(new Set());\n const [newNodeIds, setNewNodeIds] = useState<Set<string>>(new Set());\n const prevCardIdsRef = useRef<Set<string>>(new Set());\n const sessionLoadedRef = useRef(false);\n\n useEffect(() => {\n if (!view) return;\n const nodeIds = new Set(view.nodes.map((n) => n.id));\n const cardIds = new Set([...nodeIds, ...view.groups.map((g) => g.id)]);\n\n if (!sessionLoadedRef.current) {\n sessionLoadedRef.current = true;\n prevCardIdsRef.current = cardIds;\n return;\n }\n\n const prev = prevCardIdsRef.current;\n const added = [...cardIds].filter((id) => !prev.has(id));\n // `s` kept to the cards `drawn` holds, with what this frame added among\n // them.\n const track = (drawn: Set<string>) => (s: Set<string>) => {\n const arrived = added.filter((id) => drawn.has(id));\n const next = new Set([...s].filter((id) => drawn.has(id)));\n for (const id of arrived) next.add(id);\n return next.size !== s.size || arrived.length > 0 ? next : s;\n };\n setAddedIds(track(cardIds));\n setNewNodeIds(track(nodeIds));\n prevCardIdsRef.current = cardIds;\n }, [view]);\n\n const clearNew = useCallback((...ids: string[]) => {\n setNewNodeIds((s) => {\n const next = new Set(s);\n let changed = false;\n for (const id of ids) {\n if (next.delete(id)) changed = true;\n }\n return changed ? next : s;\n });\n }, []);\n\n return { addedIds, newNodeIds, clearNew };\n}\n","// Pure viewport-geometry helpers. A group made around members drawn near\n// the pane's edge has its card up and left of them, so it can sit outside\n// the visible area even though every member stays exactly where it was.\n// This computes the minimal camera pan — never a node move, never a zoom\n// change — that brings a flow-space rect fully inside the pane.\n\nexport type FlowRect = { x: number; y: number; width: number; height: number };\nexport type PaneSize = { width: number; height: number };\nexport type Viewport = { x: number; y: number; zoom: number };\n\n/**\n * The (dx, dy) to add to the current viewport's translation so `rect`\n * (in flow coordinates) is fully within the pane's [0, width] x [0, height]\n * screen bounds. Zero on either axis where `rect` is already fully\n * visible. Zoom never changes.\n */\nexport function computeMinimalPanDelta(\n rect: FlowRect,\n pane: PaneSize,\n viewport: Viewport,\n): { dx: number; dy: number } {\n const screenLeft = rect.x * viewport.zoom + viewport.x;\n const screenTop = rect.y * viewport.zoom + viewport.y;\n const screenRight = screenLeft + rect.width * viewport.zoom;\n const screenBottom = screenTop + rect.height * viewport.zoom;\n\n let dx = 0;\n if (screenLeft < 0) {\n dx = -screenLeft;\n } else if (screenRight > pane.width) {\n dx = pane.width - screenRight;\n }\n\n let dy = 0;\n if (screenTop < 0) {\n dy = -screenTop;\n } else if (screenBottom > pane.height) {\n dy = pane.height - screenBottom;\n }\n\n return { dx, dy };\n}\n\n/** `rect` grown by `margin` screen pixels on every side, in flow units at\n * `zoom`: room around a node brought into view, so it never lands flush\n * against the pane's edge. */\nexport function withMargin(rect: FlowRect, margin: number, zoom: number): FlowRect {\n const m = margin / zoom;\n return { x: rect.x - m, y: rect.y - m, width: rect.width + 2 * m, height: rect.height + 2 * m };\n}\n\nfunction fullyVisible(rect: FlowRect, pane: PaneSize, viewport: Viewport): boolean {\n const { dx, dy } = computeMinimalPanDelta(rect, pane, viewport);\n return dx === 0 && dy === 0;\n}\n\nexport type ResizeOutcome =\n | { kind: 'stay' }\n | { kind: 'fit' }\n | { kind: 'move'; viewport: Viewport };\n\n/**\n * Where the camera goes when the pane changes size from `before` to `after`\n * — the drawer opening or closing, the window resizing — so the developer\n * keeps what they were looking at:\n * - a graph that was wholly in view and still is stays put;\n * - a graph that was wholly in view and no longer fits is fitted again;\n * - otherwise the view keeps its centre, and `focus` (what is selected)\n * is then panned the least distance into view.\n * `graph` is null for an empty canvas, `focus` null when nothing is\n * selected. Zoom changes only by the fit.\n */\nexport function viewportAfterResize(\n viewport: Viewport,\n before: PaneSize,\n after: PaneSize,\n graph: FlowRect | null,\n focus: FlowRect | null,\n): ResizeOutcome {\n if (!graph) return { kind: 'stay' };\n if (fullyVisible(graph, before, viewport)) {\n return fullyVisible(graph, after, viewport) ? { kind: 'stay' } : { kind: 'fit' };\n }\n const centred: Viewport = {\n x: viewport.x + (after.width - before.width) / 2,\n y: viewport.y + (after.height - before.height) / 2,\n zoom: viewport.zoom,\n };\n if (!focus) return { kind: 'move', viewport: centred };\n const { dx, dy } = computeMinimalPanDelta(focus, after, centred);\n return { kind: 'move', viewport: { x: centred.x + dx, y: centred.y + dy, zoom: centred.zoom } };\n}\n","// The right-hand drawer App opens for a `slot: 'drawer'` panel — Settings,\n// or the inspector of what is selected. It is a column beside the canvas,\n// never over it, so the canvas's own width is what is left: Fit View fits\n// the graph beside an open drawer.\n//\n// The developer sizes it by its left edge, by pointer or by keyboard (a\n// focusable `separator`: arrows move it a step, Home and End take it to its\n// narrowest and widest). Its bounds are the design tokens\n// `--lace-size-drawer-min` / `-default` / `-max`, read where it is mounted;\n// the stylesheet clamps to the same tokens, so a width held from a wider\n// window still fits.\nimport type React from 'react';\nimport { type ReactNode, useCallback, useLayoutEffect, useRef, useState } from 'react';\nimport { readTokenPx, type StyleWithVars } from '../utils/style-vars';\nimport './Drawer.css';\n\nconst KEY_STEP = 16;\n\ntype Bounds = { min: number; max: number };\n\n// The drawer's bounds, in px, from the tokens in effect at `el`; null while\n// they are not loaded.\nexport function readDrawerBounds(el: Element): Bounds | null {\n const min = readTokenPx(el, '--lace-size-drawer-min');\n const max = readTokenPx(el, '--lace-size-drawer-max');\n return min > 0 && max >= min ? { min, max } : null;\n}\n\nexport function clampWidth(width: number, bounds: Bounds | null): number {\n if (!bounds) return width;\n return Math.min(bounds.max, Math.max(bounds.min, width));\n}\n\nexport default function Drawer({ label, children }: { label: string; children: ReactNode }) {\n const ref = useRef<HTMLElement>(null);\n const [bounds, setBounds] = useState<Bounds | null>(null);\n // Null until the developer sizes it: the stylesheet's default width.\n const [width, setWidth] = useState<number | null>(null);\n // The width it is drawn at, for the separator's value and a key's step.\n const [measured, setMeasured] = useState(0);\n const drag = useRef<{ x: number; width: number } | null>(null);\n\n useLayoutEffect(() => {\n if (ref.current) setBounds(readDrawerBounds(ref.current));\n }, []);\n // biome-ignore lint/correctness/useExhaustiveDependencies: re-measured whenever the developer resizes it.\n useLayoutEffect(() => {\n if (ref.current) setMeasured(Math.round(ref.current.getBoundingClientRect().width));\n }, [width]);\n\n const onPointerDown = useCallback((e: React.PointerEvent<HTMLDivElement>) => {\n e.preventDefault();\n e.currentTarget.setPointerCapture(e.pointerId);\n drag.current = { x: e.clientX, width: ref.current?.getBoundingClientRect().width ?? 0 };\n }, []);\n\n const onPointerMove = useCallback(\n (e: React.PointerEvent<HTMLDivElement>) => {\n if (!drag.current) return;\n // The handle is the drawer's left edge: moving it left widens it.\n setWidth(clampWidth(drag.current.width + drag.current.x - e.clientX, bounds));\n },\n [bounds],\n );\n\n const onPointerUp = useCallback((e: React.PointerEvent<HTMLDivElement>) => {\n drag.current = null;\n e.currentTarget.releasePointerCapture(e.pointerId);\n }, []);\n\n const onKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {\n const next =\n e.key === 'ArrowLeft'\n ? measured + KEY_STEP\n : e.key === 'ArrowRight'\n ? measured - KEY_STEP\n : e.key === 'Home' && bounds\n ? bounds.min\n : e.key === 'End' && bounds\n ? bounds.max\n : undefined;\n if (next === undefined) return;\n e.preventDefault();\n setWidth(clampWidth(next, bounds));\n };\n\n const style: StyleWithVars | undefined =\n width === null ? undefined : { '--drawer-width': `${width}px` };\n\n return (\n <aside ref={ref} className=\"lace-app__drawer\" aria-label={label} style={style}>\n <div\n className=\"lace-app__drawer-handle\"\n role=\"separator\"\n aria-orientation=\"vertical\"\n aria-label=\"Resize panel\"\n aria-valuenow={measured}\n aria-valuemin={bounds?.min}\n aria-valuemax={bounds?.max}\n tabIndex={0}\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerUp}\n onKeyDown={onKeyDown}\n />\n <div className=\"lace-app__drawer-body\">{children}</div>\n </aside>\n );\n}\n","import type { CSSProperties } from 'react';\n\n// An inline style that sets CSS custom properties beside the standard ones:\n// React hands a `--name` key straight to `style.setProperty`, so a\n// component's stylesheet can read a value only the component knows (the\n// viewport's zoom, a width the developer dragged).\nexport type StyleWithVars = CSSProperties & { [name: `--${string}`]: string | number };\n\n// A design token's length, in px, as it is in effect at `el`; NaN while it\n// is not set (the tokens' stylesheet not loaded) or not a length.\nexport function readTokenPx(el: Element, name: `--${string}`): number {\n return Number.parseFloat(getComputedStyle(el).getPropertyValue(name));\n}\n","import React from 'react';\nimport './ErrorBoundary.css';\n\ntype ErrorStateProps = { message: string };\n\nexport function ErrorState({ message }: ErrorStateProps) {\n return (\n <div className=\"lace-error-state\" role=\"alert\">\n <h3 className=\"lace-error-state__title\">Something went wrong</h3>\n <pre className=\"lace-error-state__message\">{message}</pre>\n <button\n type=\"button\"\n className=\"lace-error-state__reload\"\n onClick={() => window.location.reload()}\n >\n Reload\n </button>\n </div>\n );\n}\n\nexport default class ErrorBoundary extends React.Component<\n { children: React.ReactNode },\n { error: Error | null }\n> {\n state: { error: Error | null } = { error: null };\n\n static getDerivedStateFromError(error: Error) {\n return { error };\n }\n\n render() {\n if (this.state.error) {\n return <ErrorState message={this.state.error.message} />;\n }\n return this.props.children;\n }\n}\n","// One toolbar action, drawn with the design system's controls at the\n// toolbar's 28px rung:\n// - an action with `primary`: the labelled call to action, its glyph\n// beside the label, filled in the accent while it is the thing to do next\n// and a quiet secondary button otherwise;\n// - an action with an `icon`: an icon button;\n// - an action with neither: a text button carrying its label, so a host's\n// action with no glyph of its own still reads.\n// Each carries a themed tooltip naming the action, its key beside the name\n// and, while it cannot run, why under them; the key and the reason are what\n// the name lacks, and all that describes it. A running action shows a\n// spinner in place of its glyph, and a primary its `busy` label\n// (\"Generating…\").\nimport { Button, IconButton, Spinner, type TooltipPlacement } from '@lace-cloud/ui';\nimport type { ReactNode } from 'react';\nimport type { ActionContribution } from '../contributions';\nimport { formatChord, isMacPlatform } from '../utils/key-chord';\nimport { CanvasIcon } from './icons';\nimport './ToolbarAction.css';\n\ntype Props = {\n action: ActionContribution;\n // Why the action cannot run now; undefined while it can.\n disabledReason: string | undefined;\n // `primary.when` holds: the accent fill.\n emphasized: boolean;\n // The action is running: its `busy.label` when it declares one, else its\n // own label. Undefined while idle.\n busyLabel: string | undefined;\n onRun: () => void;\n};\n\n// A toolbar control's tooltip hangs under it from its start edge.\nconst TIP: TooltipPlacement = 'bottom-start';\n\n// The tooltip's description: the action's key, and why it cannot run.\n// Nothing when it has neither, so a control with no key that can run is\n// described by nothing.\nfunction actionTip(keys: readonly string[] | undefined, reason: string | undefined): ReactNode {\n const chord = keys?.[0] ? formatChord(keys[0], isMacPlatform()) : undefined;\n if (!chord && !reason) return undefined;\n return (\n <span className=\"lace-action-tip\">\n {chord ? <kbd className=\"lace-action-tip__key\">{chord}</kbd> : null}\n {reason ? <span className=\"lace-action-tip__reason\">{reason}</span> : null}\n </span>\n );\n}\n\nexport function ToolbarAction({ action, disabledReason, emphasized, busyLabel, onRun }: Props) {\n const busy = busyLabel !== undefined;\n const disabled = disabledReason !== undefined;\n const tooltip = actionTip(action.keys, disabledReason);\n const glyph = action.icon ? <CanvasIcon name={action.icon} /> : undefined;\n\n if (action.primary) {\n return (\n <Button\n rung\n size=\"sm\"\n variant={emphasized ? 'primary' : 'secondary'}\n icon={busy ? undefined : glyph}\n loading={busy}\n disabled={disabled}\n tooltip={tooltip}\n tooltipName={action.label}\n tooltipPlacement={TIP}\n className=\"lace-toolbar-action\"\n onClick={onRun}\n >\n {busyLabel ?? action.label}\n </Button>\n );\n }\n if (glyph) {\n return (\n <IconButton\n icon={busy ? <Spinner size={14} aria-hidden=\"true\" /> : glyph}\n aria-label={action.label}\n size=\"md\"\n disabled={disabled}\n tooltip={tooltip}\n tooltipPlacement={TIP}\n onClick={onRun}\n />\n );\n }\n return (\n <Button\n rung\n size=\"sm\"\n variant=\"ghost\"\n loading={busy}\n disabled={disabled}\n tooltip={tooltip}\n tooltipName={action.label}\n tooltipPlacement={TIP}\n className=\"lace-toolbar-action\"\n onClick={onRun}\n >\n {busyLabel ?? action.label}\n </Button>\n );\n}\n","// CommandArgsForm is the one form mechanism for every action: it renders\n// the `ActionRunner`'s own `pendingForm` (`core/run-binding.ts`) — the\n// missing required keys a binding's `args(ctx, target)` left unset — typed\n// from the golden (`COMMANDS[path]`) where the path is a bound command\n// (every `pendingForm.path` always is, since only `defineCommand`'s\n// `start()` opens one). Submit hands the values back to `runner`, which\n// re-runs `completeArgs` and invokes.\nimport { useState } from 'react';\nimport type { CommandPath } from '../contracts';\nimport { COMMANDS } from '../contracts';\nimport type { PendingForm } from './run-binding';\n\nexport type CommandArgsFormProps = {\n form: PendingForm;\n};\n\n// `pendingForm.path` is a plain `string` (run-binding.ts's `PendingForm`\n// erases the path-specific generic `ErasedCommand` already carries) — this\n// guard is the one narrowing back to a `CommandPath` so `COMMANDS[path]`\n// indexes without a cast.\nfunction isCommandPath(path: string): path is CommandPath {\n return path in COMMANDS;\n}\n\n// Every one of the golden's ~40 per-command flag records shares this\n// shape (`type`, and for a required one, `required`) — the return type\n// annotation is the one widening boundary from the golden's own literal\n// per-command flags type to a plain lookup, checked structurally, not\n// asserted.\nfunction flagsOf(path: CommandPath): Record<string, { type?: string }> {\n return COMMANDS[path].flags;\n}\n\nexport function CommandArgsForm({ form }: CommandArgsFormProps) {\n const [values, setValues] = useState<Record<string, string | boolean>>({});\n\n if (!form) return null;\n\n const flags = isCommandPath(form.path) ? flagsOf(form.path) : {};\n\n return (\n <form\n className=\"lace-command-args-form\"\n onSubmit={(e) => {\n e.preventDefault();\n form.submit(values);\n }}\n >\n {form.missing.map((key) => {\n const flagType = flags[key]?.type;\n return (\n <label className=\"lace-command-args-form__field\" key={key}>\n <span>{key}</span>\n {flagType === 'bool' ? (\n <input\n type=\"checkbox\"\n checked={Boolean(values[key])}\n onChange={(e) => setValues((prev) => ({ ...prev, [key]: e.target.checked }))}\n />\n ) : (\n <input\n type=\"text\"\n required\n value={typeof values[key] === 'string' ? values[key] : ''}\n onChange={(e) => setValues((prev) => ({ ...prev, [key]: e.target.value }))}\n />\n )}\n </label>\n );\n })}\n <div className=\"lace-command-args-form__actions\">\n <button type=\"submit\">Continue</button>\n <button type=\"button\" onClick={form.cancel}>\n Cancel\n </button>\n </div>\n </form>\n );\n}\n\nexport default CommandArgsForm;\n","// The describe overlay: the one overlay the canvas core registers. It\n// reads `stack describe` and decorates the view with the resource count\n// and drift state a stack's Terraform state carries per node, resolving\n// each resource's address to a node with `nodeIdForAddress`\n// (@lace-cloud/proto) — the same resolver `nodeIdForDiagnostic` composes\n// on for an address-carrying diagnostic.\n//\n// The describe command is suppressed for a historical/CR mount by that\n// mount's own `commands.available()` — the overlay itself declares no\n// run-id logic; `resolveContributions` (registry.ts) already checks the\n// declared path against `available()` before this ever fetches.\nimport type { CanvasView } from '@lace-cloud/proto';\nimport { nodeIdForAddress } from '@lace-cloud/proto';\nimport type { ArgsOf, JsonOf } from '../../contracts';\nimport type { Badge, CanvasCtx, Decorations } from '../../contributions';\nimport { defineOverlay } from '../define-overlay';\n\ntype DescribeData = JsonOf<'stack describe'>;\n\nexport function decorateDescribe(view: CanvasView, data: DescribeData): Decorations {\n const nodes: Record<string, { badges: Badge[] }> = {};\n const addBadge = (nodeId: string, badge: Badge) => {\n if (!nodes[nodeId]) nodes[nodeId] = { badges: [] };\n nodes[nodeId].badges.push(badge);\n };\n\n // A null `state` means the stack has never applied — there is nothing to\n // count, so no resource badge, not a \"0 resources\" one.\n if (data.state) {\n const countByNode = new Map<string, number>();\n for (const resource of data.state.resources) {\n const nodeId = nodeIdForAddress(view, resource.address);\n if (nodeId === null) continue;\n countByNode.set(nodeId, (countByNode.get(nodeId) ?? 0) + 1);\n }\n for (const [nodeId, count] of countByNode) {\n addBadge(nodeId, {\n id: 'resources',\n tone: 'neutral',\n label: `${count} resource${count === 1 ? '' : 's'}`,\n });\n }\n }\n\n // A null `drift` means no scan has run — that's not \"in sync\", so it\n // renders no drift badge either.\n if (data.drift) {\n const driftedNodes = new Set<string>();\n for (const resource of data.drift.driftedResources) {\n const nodeId = nodeIdForAddress(view, resource.address);\n if (nodeId === null) continue;\n driftedNodes.add(nodeId);\n }\n for (const nodeId of driftedNodes) {\n addBadge(nodeId, { id: 'drift', tone: 'warn', label: 'drifted' });\n }\n }\n\n return { nodes };\n}\n\nexport const describeOverlay = defineOverlay({\n id: 'describe',\n read: {\n path: 'stack describe',\n args: (ctx: CanvasCtx): ArgsOf<'stack describe'> | null =>\n ctx.stack ? { stack: ctx.stack.id } : null,\n },\n decorate: decorateDescribe,\n});\n","// The one overlay decoration hook: it composes `useCommandRead` (a mounting\n// OverlayRunner wraps every overlay in the same `PanelScope` a panel's\n// declared reads run inside), so an overlay fetches through the identical\n// registry-gated path a panel does — no second overlay-fetch mechanism.\n// The decorations are memoized on (view, data): OverlayRunner publishes them\n// from an effect keyed on their identity into App state, so a fresh object\n// every render would re-render App, re-run the effect, and never settle.\n// It lives apart from ../contributions.ts so the contract types load no\n// React of their own.\nimport type { CanvasView } from '@lace-cloud/proto';\nimport { useMemo } from 'react';\nimport type { BoundPath, JsonOf } from '../contracts';\nimport type { CommandRead, Decorations, OverlayContribution } from '../contributions';\nimport { useCommandRead } from './use-command-read';\n\nconst EMPTY_DECORATIONS: Decorations = { nodes: {} };\n\nexport function defineOverlay<P extends BoundPath>(o: {\n id: string;\n read: CommandRead<P>;\n decorate(v: CanvasView, d: JsonOf<P>): Decorations;\n}): OverlayContribution {\n return {\n id: o.id,\n paths: [o.read.path],\n useDecorations(ctx) {\n const { data } = useCommandRead(o.read);\n const view = ctx.view;\n return useMemo(\n () => (data ? o.decorate(view, data) : EMPTY_DECORATIONS),\n [o.decorate, view, data],\n );\n },\n };\n}\n","// useCommandRead is the only read: every panel and overlay that fetches\n// through `commands.invoke` goes through this one hook, keyed on the\n// declared read's own args plus the shared invalidation tick — never a\n// hand-rolled fetch loop. A refetch key change or unmount aborts the\n// in-flight signal — a\n// detach, never `Invocation.cancel()`; this hook never holds a `cancel`\n// reference at all.\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport type { BoundPath, JsonOf } from '../contracts';\nimport type { ActionTarget, CommandRead } from '../contributions';\nimport { isPlainObject } from '../utils/is-plain-object';\nimport { usePanelScope } from './panel-scope';\n\nexport type CommandReadState<P extends BoundPath> = {\n data: JsonOf<P> | null;\n error: Error | null;\n pending: boolean;\n};\n\nconst INITIAL = { data: null, error: null, pending: false };\n\n// Distinguishes \"no read has ever run yet\" from a real key of `null` (a\n// declared read whose `args` currently declines) — a plain `null` sentinel\n// for \"unset\" would make the very first effect run look like a tick-only\n// refetch of a declined read.\nconst NOT_YET_READ = Symbol('not-yet-read');\n\n// A deep, key-sorted JSON string: two args objects with the same content in\n// a different key order refetch key-equal, so a binding's own `args()`\n// building its return value in a different property order each render\n// never causes a spurious refetch.\nfunction stableJson(value: unknown): string {\n return JSON.stringify(value, (_key, val) => {\n if (isPlainObject(val)) {\n const sorted: Record<string, unknown> = {};\n for (const k of Object.keys(val).sort()) {\n sorted[k] = val[k];\n }\n return sorted;\n }\n return val;\n });\n}\n\nexport function useCommandRead<P extends BoundPath>(\n read: CommandRead<P>,\n target?: ActionTarget,\n): CommandReadState<P> {\n const scope = usePanelScope();\n if (!scope.paths.has(read.path)) {\n throw new Error(\n `useCommandRead('${read.path}') is not declared in this panel's reads — add it to the Panel's \\`reads\\``,\n );\n }\n\n const effectiveTarget = target ?? scope.target;\n const args = read.args(scope.ctx, effectiveTarget);\n const key = args === null ? null : stableJson(args);\n const [state, setState] = useState<CommandReadState<P>>(INITIAL);\n const prevKeyRef = useRef<string | null | typeof NOT_YET_READ>(NOT_YET_READ);\n\n // This render's inputs, read by the fetch effect below when it runs: the\n // refetch key is `stableJson(args)` + tick alone, so the commands port,\n // the error sink or `args` itself moving without moving either must not\n // refetch on their own — yet the run that does fire uses the latest of\n // each. Declared before the fetch effect, so it has already updated by\n // the time that one runs in the same commit.\n const inputs = {\n path: read.path,\n args,\n commands: scope.ctx.ports.commands,\n reportError: scope.reportError,\n };\n const inputsRef = useRef(inputs);\n useEffect(() => {\n inputsRef.current = inputs;\n });\n const request = useMemo(() => ({ key, tick: scope.tick }), [key, scope.tick]);\n\n useEffect(() => {\n const { path, args, commands, reportError } = inputsRef.current;\n // A tick-only refetch (the key itself hasn't moved) keeps the last\n // page's `data` and error on screen while the new one loads — only a\n // real key change (a different stack, a different target) clears both,\n // so switching from stack A to stack B never shows a beat of A's own\n // rows, badges or load error under B's own tab.\n const keyChanged = prevKeyRef.current !== request.key;\n prevKeyRef.current = request.key;\n // Narrows `args` itself (not just `key`, which is derived from it) so\n // the `commands.invoke` call below sees `ArgsOf<P>`, never `| null`.\n if (args === null || !commands) {\n setState(INITIAL);\n reportError(path, null);\n return;\n }\n if (keyChanged) {\n setState({ data: null, error: null, pending: true });\n reportError(path, null);\n } else {\n setState((s) => ({ ...s, pending: true }));\n }\n const controller = new AbortController();\n const invocation = commands.invoke(path, args, controller.signal);\n (async () => {\n try {\n for await (const event of invocation.events) {\n if (controller.signal.aborted) return;\n setState({ data: event, error: null, pending: false });\n reportError(path, null);\n }\n } catch (err) {\n if (controller.signal.aborted) return;\n const error = err instanceof Error ? err : new Error(String(err));\n setState({ data: null, error, pending: false });\n reportError(path, error);\n }\n })();\n return () => controller.abort();\n }, [request]);\n\n return state;\n}\n","// PanelScope declares, for the panel/overlay React is about to render, the\n// exact set of `BoundPath`s it may read and the `CanvasCtx`/`ActionTarget`/\n// tick generation those reads run against. `useCommandRead` asserts its own\n// path is in this set — an undeclared read is a defect the type system\n// can't catch (a path string, not a type), so this is the runtime guard.\n\nimport type { ReactNode } from 'react';\nimport { createContext, useContext, useMemo } from 'react';\nimport type { BoundPath } from '../contracts';\nimport type { ActionTarget, CanvasCtx } from '../contributions';\n\nexport type PanelScopeValue = {\n ctx: CanvasCtx;\n target: ActionTarget;\n paths: ReadonlySet<BoundPath>;\n tick: number;\n // `useCommandRead` reports every read's own success/failure here — the one\n // place a failed read surfaces, instead of each panel's own render\n // deciding whether to show the `error` its call site happens to destructure.\n // A scope with no `onReadError` wired up gets the no-op default.\n reportError(path: BoundPath, error: Error | null): void;\n};\n\nconst noopReportError = () => {};\n\nconst PanelScopeContext = createContext<PanelScopeValue | null>(null);\n\nexport function PanelScope({\n ctx,\n target = {},\n paths,\n tick,\n onReadError,\n children,\n}: {\n ctx: CanvasCtx;\n target?: ActionTarget;\n paths: readonly BoundPath[];\n tick: number;\n onReadError?: (path: BoundPath, error: Error | null) => void;\n children: ReactNode;\n}) {\n const reportError = onReadError ?? noopReportError;\n const value = useMemo<PanelScopeValue>(\n () => ({ ctx, target, paths: new Set(paths), tick, reportError }),\n [ctx, target, paths, tick, reportError],\n );\n return <PanelScopeContext.Provider value={value}>{children}</PanelScopeContext.Provider>;\n}\n\nexport function usePanelScope(): PanelScopeValue {\n const value = useContext(PanelScopeContext);\n if (!value) {\n throw new Error(\n 'usePanelScope: not inside a <PanelScope> — mount panels/overlays through App, which wraps every declared-read contribution',\n );\n }\n return value;\n}\n","// A banner over its panel's row actions, the one way a core banner draws\n// them: the opening sentence states the fact, the `choice` of each action\n// resolved on the panel's row (`rowActionsFor`) follows it in resolve order\n// — core's, then a host's — and the actions are its buttons, each run\n// through the runner like any row action. The buttons are drawn alike, none\n// as a call to action: the developer picks among them. An action with no\n// `choice` is a button that adds no sentence, and a row that resolves no\n// action leaves the opening alone. A button is drawn as the toolbar draws\n// its action (`actionState`): disabled, saying why, while another\n// command runs on its target, and spinning while its own does.\nimport { Button } from '@lace-cloud/ui';\nimport Banner from '../../components/Banner';\nimport type { ActionContribution, CanvasCtx } from '../../contributions';\nimport { actionState } from '../../registry';\nimport { useCanvas } from '../../state/canvas-context';\nimport { rowActionsFor, useEditorEnvExtras } from './row-actions';\n\ntype Props = {\n ctx: CanvasCtx;\n // The panel whose `row:` actions the banner draws.\n panelId: string;\n severity: 'warning' | 'error';\n // The banner's own hook class; each button carries `<className>__<action id>`.\n className: string;\n opening: string;\n};\n\nfunction bannerMessage(opening: string, actions: readonly ActionContribution[]): string {\n return [opening, ...actions.flatMap((action) => (action.choice ? [action.choice] : []))].join(\n ' ',\n );\n}\n\nexport function RowActionBanner({ ctx, panelId, severity, className, opening }: Props) {\n const { runner } = useCanvas();\n const envExtras = useEditorEnvExtras();\n const actions = rowActionsFor(ctx, panelId);\n\n return (\n <Banner\n severity={severity}\n className={className}\n message={bannerMessage(opening, actions)}\n actions={\n actions.length === 0\n ? undefined\n : actions.map((action) => {\n const state = actionState(action, ctx, runner.busy(action, ctx, {}));\n return (\n <Button\n key={action.id}\n rung\n size=\"sm\"\n variant=\"secondary\"\n className={`${className}__${action.id}`}\n disabled={state.disabledReason !== undefined}\n loading={state.busyLabel !== undefined}\n tooltip={state.disabledReason}\n onClick={() => void runner.run(action, ctx, {}, envExtras)}\n >\n {action.label}\n </Button>\n );\n })\n }\n />\n );\n}\n","// A banner row in App's strip under the toolbar: one fact that needs the\n// developer, then the choices that settle it — its severity's colour and\n// glyph, the message, then the actions as real buttons. `warning` is a\n// decision waiting (announced politely, `status`); `error` is something\n// locked (`alert`).\nimport type { ReactNode } from 'react';\nimport { CanvasIcon } from './icons';\nimport './Banner.css';\n\ntype Props = {\n severity: 'warning' | 'error';\n message: ReactNode;\n // The banner's own hook class (`lace-conflict-banner`, …).\n className: string;\n actions?: ReactNode;\n};\n\nexport default function Banner({ severity, message, className, actions }: Props) {\n return (\n <div\n className={`lace-banner lace-banner--${severity} ${className}`}\n role={severity === 'error' ? 'alert' : 'status'}\n >\n <span className=\"lace-banner__icon\">\n <CanvasIcon name={severity} />\n </span>\n <span className=\"lace-banner__message\">{message}</span>\n {actions ? <span className=\"lace-banner__actions\">{actions}</span> : null}\n </div>\n );\n}\n","// The conflict banner: the tf changed under an unsaved or ungenerated\n// working IR and needs Keep or Reload. Keep/Reload are `row:conflict`\n// editor bindings drawn through RowActionBanner, so Reload's own `confirm`\n// runs through the runner's one `presenter.confirm(` call site, never a\n// second inline confirm here. The banner resolves while a conflict is open\n// (its `requiredContext`, `conflict`), independently of `editable` — the\n// conflict stays visible under the lock too — but its row resolves no\n// actions there: Keep/Reload require `editable`, hidden alongside Save\n// and Generate.\nimport type { Panel, PanelProps } from '../../contributions';\nimport { RowActionBanner } from './RowActionBanner';\n\nexport function ConflictBanner({ ctx }: PanelProps) {\n return (\n <RowActionBanner\n ctx={ctx}\n panelId=\"conflict\"\n severity=\"warning\"\n className=\"lace-conflict-banner\"\n opening=\"The module's .tf files changed outside the canvas while it held edits of its own.\"\n />\n );\n}\n\nexport const conflictPanel: Panel = {\n id: 'conflict',\n title: 'Conflict',\n slot: 'banner',\n requiredPorts: [],\n requiredContext: ['conflict'],\n Component: ConflictBanner,\n};\n\nexport default ConflictBanner;\n","// The diagnostics panel: `ctx.diagnostics` is already\n// the one merged list (App's own `diagnosticsOf`, core/diagnostics.ts) of\n// the engine's live findings and the current report's — the fold over the\n// results of the commands that ran in the session's root, whichever client\n// ran them (core/report-fold.ts). The canvas runs no validator of its own,\n// and merging a second time here would double every report-derived row, so\n// this panel reads `ctx.diagnostics` directly, the same list `decorate`'s\n// per-node badges read.\n//\n// Every row passes its own datum — the whole `Diagnostic` — as the target\n// through `rowActionsFor(ctx, 'diagnostics', target)`, the same resolver\n// every other row-action panel (the conflict banner, the edge inspector)\n// uses, never a panel-private one. A host contributes its own row action (e.g. jump to\n// source) through the identical registry, reading whichever fields off\n// `target.diagnostic` it needs — that's the seam (seam-ports.test.tsx), not\n// a core mechanism or a field minted for one hypothetical consumer. Each\n// row's button is drawn as the toolbar draws its action (`actionState`).\n\nimport type { Diagnostic } from '@lace-cloud/proto';\nimport { Button } from '@lace-cloud/ui';\nimport Identifier from '../../components/Identifier';\nimport { CanvasIcon } from '../../components/icons';\nimport type { Panel, PanelProps } from '../../contributions';\nimport { actionState } from '../../registry';\nimport { useCanvas } from '../../state/canvas-context';\nimport { rowActionsFor, useEditorEnvExtras } from './row-actions';\nimport './DiagnosticsPanel.css';\n\nfunction rowKey(d: Diagnostic, index: number): string {\n return `${d.severity}:${d.module_key ?? ''}.${d.instance_id ?? ''}:${index}`;\n}\n\nexport function DiagnosticsPanel({ ctx }: PanelProps) {\n const { runner } = useCanvas();\n const envExtras = useEditorEnvExtras();\n const diagnostics = ctx.diagnostics;\n\n return (\n <ul className=\"lace-diagnostics-panel\" role=\"list\">\n {diagnostics.map((d, index) => {\n const key = rowKey(d, index);\n const target = { diagnostic: d };\n const actions = rowActionsFor(ctx, 'diagnostics', target);\n return (\n <li\n key={key}\n className={`lace-diagnostics-panel__row lace-diagnostics-panel__row--${d.severity}`}\n >\n <span className=\"lace-diagnostics-panel__icon\">\n <CanvasIcon name={d.severity} />\n </span>\n <span className=\"lace-diagnostics-panel__body\">\n <span className=\"lace-diagnostics-panel__message\">{d.message}</span>\n {d.instance_id !== undefined && (\n <Identifier\n className=\"lace-diagnostics-panel__where\"\n text={d.input_name ? `${d.instance_id}.${d.input_name}` : d.instance_id}\n />\n )}\n {d.code !== undefined && (\n <Identifier className=\"lace-diagnostics-panel__code\" text={d.code} />\n )}\n {actions.map((action) => {\n const state = actionState(action, ctx, runner.busy(action, ctx, target));\n return (\n <Button\n key={action.id}\n rung\n size=\"sm\"\n variant=\"ghost\"\n className=\"lace-diagnostics-panel__action\"\n disabled={state.disabledReason !== undefined}\n loading={state.busyLabel !== undefined}\n tooltip={state.disabledReason}\n onClick={() => void runner.run(action, ctx, target, envExtras)}\n >\n {action.label}\n </Button>\n );\n })}\n </span>\n </li>\n );\n })}\n </ul>\n );\n}\n\nexport const diagnosticsPanel: Panel = {\n id: 'diagnostics',\n title: 'Diagnostics',\n slot: 'bottom',\n requiredPorts: [],\n // Resolves only once there is something to show — `ctx.diagnostics`\n // non-empty (registry.ts's `contextSatisfied`) — so an otherwise-clean\n // mount never draws an empty 240px Diagnostics tab.\n requiredContext: ['diagnostics'],\n Component: DiagnosticsPanel,\n};\n\nexport default DiagnosticsPanel;\n","// An identifier as the canvas shows it — an instance, an input, an output,\n// a module address: monospace, and broken across lines only after a `_` or\n// a `.`, so a long snake_case name wraps at its word joins rather than\n// mid-word. Each join carries a <wbr>, a break the browser prefers to the\n// panel's last-resort `overflow-wrap: anywhere`, which still applies to a\n// single segment longer than a line.\nimport { Fragment } from 'react';\nimport './Identifier.css';\n\n// `text` cut after every `_` and `.`, each joint kept on the piece before\n// it: the places an identifier may break.\nexport function identifierSegments(text: string): string[] {\n return text.split(/(?<=[_.])/);\n}\n\nexport default function Identifier({ text, className }: { text: string; className?: string }) {\n return (\n <span className={className ? `lace-identifier ${className}` : 'lace-identifier'}>\n {identifierSegments(text).map((segment, i) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: a segment's place in the name is its identity.\n <Fragment key={i}>\n {i > 0 ? <wbr /> : null}\n {segment}\n </Fragment>\n ))}\n </span>\n );\n}\n","// The edge-inspector panel: a thin Panel wrapper around\n// `components/panels/EdgeInspectorPanel`, deriving its props from\n// `ctx.selection.edge` (already the exact `{source, target, sourceOutput,\n// targetInput}` shape the component wants).\n//\n// \"Delete connection\" is the panel's own `row: 'edge-inspector'` action\n// (`disconnectEdge`, below), resolved through `rowActionsFor` and dispatched\n// through `runner.run` — the same `ActionRunner` path every other IR edit\n// takes (confirm → apply → route the `ApplyResult` → tick), so a host's own\n// confirm or `run` on the resolved contribution is what executes. Like every\n// editor binding it declares the `editor` port and the `editable` context,\n// so it resolves nowhere a canvas is read-only (no `editor` port, or the\n// source-refused lock), and the component draws its button only for the\n// action that resolved. The inspector closes only by its own Close or when\n// a frame does not hold the wire (App's `reconcileSelection`): a\n// disconnect that lands closes it with the frame that drops the wire, and a\n// failing `ApplyResult` reaches `presenter.notify` and leaves it open over\n// the still-wired edge.\nimport { instanceAddress } from '@lace-cloud/proto';\nimport { createElement } from 'react';\nimport EdgeInspectorPanelComponent from '../../components/panels/EdgeInspectorPanel';\nimport type { ActionContribution, EditorBinding, Panel, PanelProps } from '../../contributions';\nimport { useCanvas } from '../../state/canvas-context';\nimport { rowActionsFor, useEditorEnvExtras } from './row-actions';\n\nconst disconnectBinding: EditorBinding = {\n kind: 'editor',\n result: 'apply',\n async run(env) {\n const edge = env.ctx.selection.edge;\n // `disconnectEdge`'s own `requiredContext` ('selection.edge') already\n // ensures this when the row action resolves at all — no edge means\n // nothing to disconnect, not a failure.\n if (!edge) return { success: true, errors: [], created: [], ties: [] };\n const target = instanceAddress(env.bundle, edge.target);\n return env.apply([\n { disconnect: { scope: target.scope, target: target.id, input_name: edge.targetInput } },\n ]);\n },\n};\n\nexport const disconnectEdge: ActionContribution = {\n id: 'disconnect',\n label: 'Delete connection',\n placement: { row: 'edge-inspector' },\n requiredPorts: ['editor'],\n requiredContext: ['editable', 'selection.edge'],\n binding: disconnectBinding,\n};\n\nfunction EdgeInspectorPanel({ ctx }: PanelProps) {\n const { runner, setSelection } = useCanvas();\n const envExtras = useEditorEnvExtras();\n const edge = ctx.selection.edge;\n if (!edge) return null;\n\n const disconnect = rowActionsFor(ctx, 'edge-inspector').find((a) => a.id === 'disconnect');\n\n return createElement(EdgeInspectorPanelComponent, {\n source: edge.source,\n target: edge.target,\n sourceOutput: edge.sourceOutput,\n targetInput: edge.targetInput,\n // The delete button exists exactly when `disconnect` resolved.\n ...(disconnect\n ? {\n onDelete: () => {\n void runner.run(disconnect, ctx, {}, envExtras);\n },\n }\n : {}),\n onClose: () => setSelection({ nodes: [], edge: null }),\n });\n}\n\nexport const edgeInspectorPanel: Panel = {\n id: 'edge-inspector',\n title: 'Connection',\n slot: 'drawer',\n requiredPorts: [],\n requiredContext: ['selection.edge'],\n Component: EdgeInspectorPanel,\n};\n\nexport default EdgeInspectorPanel;\n","import { callText } from '@lace-cloud/proto';\nimport { Button, Panel } from '@lace-cloud/ui';\nimport Identifier from '../Identifier';\nimport './EdgeInspectorPanel.css';\n\n// `onDelete` is present exactly when deleting the connection is an action\n// the canvas can take: its presence is the one decision whether the delete\n// button and its hint are drawn.\ntype Props = {\n source: string;\n target: string;\n sourceOutput: string;\n targetInput: string;\n onDelete?: () => void;\n onClose: () => void;\n};\n\nexport default function EdgeInspectorPanel({\n source,\n target,\n sourceOutput,\n targetInput,\n onDelete,\n onClose,\n}: Props) {\n const title = (\n <div>\n <div className=\"lace-edge-panel__title-eyebrow\">Connection</div>\n <div className=\"lace-edge-panel__title\">\n <Identifier text={source} /> → <Identifier text={target} />\n </div>\n </div>\n );\n\n const footer = onDelete ? (\n <Button rung variant=\"danger\" fullWidth onClick={onDelete}>\n Delete connection\n </Button>\n ) : undefined;\n\n return (\n <Panel title={title} footer={footer} onClose={onClose}>\n <div className=\"lace-edge-panel__section-label\">Wiring</div>\n <div className=\"lace-edge-panel__wiring\">\n <Identifier text={sourceOutput ? `${source}.outputs.${sourceOutput}` : callText(source)} />\n <div className=\"lace-edge-panel__wiring-arrow\">↓</div>\n <Identifier text={`${target}.inputs.${targetInput}`} />\n </div>\n {onDelete && (\n <div className=\"lace-edge-panel__hint\">\n Delete or press Backspace with the edge selected to remove this connection. Create new\n edges by dragging between the pins on each node's edge.\n </div>\n )}\n </Panel>\n );\n}\n","// The two state chips beside Generate (`section: 'write'`): \"Unsaved\"\n// in the warning tone, \"Not generated\" neutral, nothing when the IR is saved\n// and generated. Quiet chips, not banners — the conflict and source-refused\n// facts get the banner treatment. Both are `slot: 'toolbar'` panels, visible\n// under the source-refused lock too (requiredPorts `editor`, requiredContext\n// `root`, no `editable` requirement); each resolves only while the fact it\n// states holds (its other `requiredContext` keys).\nimport { Badge } from '@lace-cloud/ui';\nimport type { Panel } from '../../contributions';\n\nexport function UnsavedMarker() {\n return (\n <Badge variant=\"warning\" dot role=\"status\" className=\"lace-marker lace-marker--unsaved\">\n Unsaved\n </Badge>\n );\n}\n\nexport const unsavedMarker: Panel = {\n id: 'unsaved-marker',\n title: 'Unsaved',\n slot: 'toolbar',\n section: 'write',\n requiredPorts: ['editor'],\n requiredContext: ['root', 'unsaved'],\n Component: UnsavedMarker,\n};\n\nexport function UngeneratedMarker() {\n return (\n <Badge variant=\"neutral\" role=\"status\" className=\"lace-marker lace-marker--ungenerated\">\n Not generated\n </Badge>\n );\n}\n\n// While a Generate runs the chip says nothing (`generateIdle`): Generate\n// itself shows it in flight (`busy`), and the engine re-bases the session as\n// soon as it has written the tree (`ungenerated: false`) and only then\n// certifies it, so \"Not generated\" clearing mid-run would announce an\n// outcome the engine has not reached. The chip shows the outcome once the\n// engine has answered.\nexport const ungeneratedMarker: Panel = {\n id: 'ungenerated-marker',\n title: 'Not generated',\n slot: 'toolbar',\n section: 'write',\n requiredPorts: ['editor'],\n requiredContext: ['root', 'ungenerated', 'generateIdle'],\n Component: UngeneratedMarker,\n};\n","// The module-config inspector panel: a Panel wrapper around\n// `components/panels/ModuleConfigPanel`, which reads `editable`/`bundle`/\n// `runner` straight off `useCanvas()` and gates every mutating control on\n// `editable` itself — this file only derives the component's\n// `instance_id`/`onClose` props from `ctx.selection` and `setSelection`,\n// the one selection surface `useCanvas()` exposes.\nimport { createElement } from 'react';\nimport ModuleConfigPanelComponent from '../../components/panels/ModuleConfigPanel';\nimport type { Panel, PanelProps } from '../../contributions';\nimport { useCanvas } from '../../state/canvas-context';\n\nfunction ModuleConfigPanel({ ctx }: PanelProps) {\n const { setSelection } = useCanvas();\n const instanceId = ctx.selection.nodes[0];\n if (!instanceId) return null;\n\n return createElement(ModuleConfigPanelComponent, {\n instance_id: instanceId,\n onClose: () => setSelection({ nodes: [], edge: null }),\n });\n}\n\nexport const moduleConfigPanel: Panel = {\n id: 'module-config',\n title: 'Module',\n slot: 'drawer',\n requiredPorts: [],\n requiredContext: ['selection.node'],\n Component: ModuleConfigPanel,\n};\n\nexport default ModuleConfigPanel;\n","import { deriveNodeConfig, instanceAddress } from '@lace-cloud/proto';\nimport { Button, IconButton, Input, ModeToggle, Panel, Textarea } from '@lace-cloud/ui';\nimport type React from 'react';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { assertNever } from '../../exhaustive';\nimport type { Action } from '../../generated/service';\nimport { InputMode } from '../../generated/service';\nimport { useUpdateState } from '../../hooks/useUpdateState';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { NodeConfig, RenderInput, RenderOutput } from '../../types/render';\nimport AccordionSection from '../AccordionSection';\nimport Identifier from '../Identifier';\nimport { CanvasIcon } from '../icons';\nimport './ModuleConfigPanel.css';\nimport './panels-shared.css';\nimport UpdateButton from '../UpdateButton';\nimport ModuleDetails from './ModuleDetails';\n\n// ── Binding mode type ──\n\ntype BindingMode = 'empty' | 'literal' | 'variable' | 'expression' | 'wired';\n\nconst MODE_ITEMS: { value: BindingMode; label: string }[] = [\n { value: 'literal', label: 'Lit' },\n { value: 'variable', label: 'Var' },\n { value: 'expression', label: 'Expr' },\n { value: 'wired', label: 'Wired' },\n];\n\nfunction toInputMode(mode: BindingMode): InputMode {\n switch (mode) {\n case 'empty':\n return InputMode.INPUT_MODE_EMPTY;\n case 'literal':\n return InputMode.INPUT_MODE_LITERAL;\n case 'variable':\n return InputMode.INPUT_MODE_VARIABLE;\n case 'expression':\n return InputMode.INPUT_MODE_EXPRESSION;\n case 'wired':\n return InputMode.INPUT_MODE_WIRED;\n default:\n return assertNever(mode);\n }\n}\n\n// ── Props ──\n\ntype Props = {\n instance_id: string;\n onClose: () => void;\n onModified?: (instanceId: string) => void;\n};\n\n// ── Component ──\n\nexport default function ModuleConfigPanel({ instance_id, onClose, onModified }: Props) {\n const { editable, bundle, runner } = useCanvas();\n // Derived straight from the Bundle the canvas already has. No RPC\n // needed for either mode; only mutations go through `editor`.\n const config = useMemo<NodeConfig | null>(\n () => deriveNodeConfig(bundle, instance_id),\n [bundle, instance_id],\n );\n\n type InputState = {\n modes: Record<string, BindingMode>;\n values: Record<string, unknown>;\n variables: Record<string, string>;\n expressions: Record<string, string>;\n };\n const [inputState, setInputState] = useState<InputState>({\n modes: {},\n values: {},\n variables: {},\n expressions: {},\n });\n\n const {\n modes: localModes,\n values: localValues,\n variables: localVariables,\n expressions: localExpressions,\n } = inputState;\n\n // Memoized so callers using these in dep arrays (switchMode etc.)\n // get a stable reference. setInputState itself is React-stable.\n const setLocalModes = useCallback(\n (fn: (prev: Record<string, BindingMode>) => Record<string, BindingMode>) =>\n setInputState((s) => ({ ...s, modes: fn(s.modes) })),\n [],\n );\n const setLocalValues = useCallback(\n (fn: (prev: Record<string, unknown>) => Record<string, unknown>) =>\n setInputState((s) => ({ ...s, values: fn(s.values) })),\n [],\n );\n const setLocalVariables = useCallback(\n (fn: (prev: Record<string, string>) => Record<string, string>) =>\n setInputState((s) => ({ ...s, variables: fn(s.variables) })),\n [],\n );\n const setLocalExpressions = useCallback(\n (fn: (prev: Record<string, string>) => Record<string, string>) =>\n setInputState((s) => ({ ...s, expressions: fn(s.expressions) })),\n [],\n );\n\n const [localDependsOn, setLocalDependsOn] = useState<Set<string>>(new Set());\n // The module call's `providers = {}` map, held as ordered rows so the user\n // can edit both the child-local name (key) and the root reference (value).\n const [localProviders, setLocalProviders] = useState<Array<{ key: string; value: string }>>([]);\n // The call's `count` and `for_each`, as text.\n const [localRepetition, setLocalRepetition] = useState({ count: '', for_each: '' });\n\n // `config`'s identity is the re-seed trigger — a new Bundle (after a\n // save, a tool call, an undo) derives a new `config`, so local edit\n // state resyncs even though instance_id hasn't changed. Any in-progress\n // edit the user hasn't saved yet is discarded.\n useEffect(() => {\n if (!config) return;\n\n const modes: Record<string, BindingMode> = {};\n const values: Record<string, unknown> = {};\n const variables: Record<string, string> = {};\n const expressions: Record<string, string> = {};\n\n for (const input of config.inputs) {\n modes[input.name] = input.mode;\n if (input.value !== undefined) values[input.name] = input.value;\n if (input.variable) variables[input.name] = input.variable;\n if (input.expression) expressions[input.name] = input.expression;\n }\n\n setInputState({ modes, values, variables, expressions });\n setLocalDependsOn(new Set(config.depends_on));\n setLocalProviders(\n Object.entries(config.providers ?? {}).map(([key, value]) => ({ key, value })),\n );\n setLocalRepetition({ count: config.count, for_each: config.for_each });\n }, [config]);\n\n const switchMode = useCallback(\n (name: string, mode: BindingMode, input: RenderInput) => {\n setLocalModes((prev) => ({ ...prev, [name]: mode }));\n switch (mode) {\n case 'literal':\n setLocalValues((prev) => ({ ...prev, [name]: input.default_value ?? null }));\n break;\n case 'variable':\n setLocalVariables((prev) => ({ ...prev, [name]: '' }));\n break;\n case 'expression':\n setLocalExpressions((prev) => ({ ...prev, [name]: '' }));\n break;\n case 'empty':\n setLocalValues((prev) => {\n const next = { ...prev };\n delete next[name];\n return next;\n });\n break;\n case 'wired':\n // Cannot switch to wired manually.\n break;\n default:\n assertNever(mode);\n }\n },\n [setLocalModes, setLocalValues, setLocalVariables, setLocalExpressions],\n );\n\n const { requiredInputs, optionalInputs } = useMemo(\n () => ({\n requiredInputs: (config?.inputs ?? []).filter((i) => i.required),\n optionalInputs: (config?.inputs ?? []).filter((i) => !i.required),\n }),\n [config?.inputs],\n );\n\n // The instance this panel edits, as the engine addresses it: the module\n // whose scope owns it and its own id there.\n const address = useMemo(() => instanceAddress(bundle, instance_id), [bundle, instance_id]);\n\n // Every field this panel edits of the call — inputs, depends-on,\n // providers, repetition — lands in ONE `apply` batch (one undo entry), routed through `runner.apply`'s\n // shared notify-on-failure path, so a rejected write is read from the one\n // `ApplyResult` rather than assumed to have succeeded. Throwing on a\n // failed apply (rather than a silent return) is what lets `useUpdateState`\n // (below) show \"Update failed\" instead of reading back \"Updated!\" on a\n // write the engine refused.\n const { status: updateStatus, handleUpdate } = useUpdateState(async () => {\n if (!config || !editable) return;\n\n const actions: Action[] = [];\n\n for (const input of config.inputs) {\n const mode = localModes[input.name] ?? input.mode;\n if (mode === 'wired') continue;\n\n actions.push({\n update_input: {\n scope: address.scope,\n instance_id: address.id,\n input_name: input.name,\n mode: toInputMode(mode),\n value: mode === 'literal' ? localValues[input.name] : undefined,\n variable: mode === 'variable' ? (localVariables[input.name] ?? '') : '',\n expression: mode === 'expression' ? (localExpressions[input.name] ?? '') : '',\n },\n });\n }\n\n actions.push({\n set_depends_on: {\n scope: address.scope,\n instance_id: address.id,\n depends_on: [...localDependsOn],\n },\n });\n\n const providersRecord: Record<string, string> = {};\n for (const { key, value } of localProviders) {\n const name = key.trim();\n if (name) providersRecord[name] = value.trim();\n }\n actions.push({\n set_use_providers: {\n scope: address.scope,\n instance_id: address.id,\n providers: providersRecord,\n },\n });\n\n if (localRepetition.count !== config.count || localRepetition.for_each !== config.for_each) {\n actions.push({\n set_meta_arguments: {\n scope: address.scope,\n instance_id: address.id,\n count: localRepetition.count,\n for_each: localRepetition.for_each,\n provider: '',\n },\n });\n }\n\n const result = await runner.apply(actions);\n if (!result?.success) throw new Error('apply failed');\n\n const requiredToCheck = config.inputs.filter((i) => i.required);\n const hasFilledRequired =\n requiredToCheck.length === 0 ||\n requiredToCheck.some((input) => {\n const mode = localModes[input.name] ?? input.mode;\n if (mode === 'wired') return true;\n if (mode === 'literal') {\n const v = localValues[input.name];\n return v !== undefined && v !== null && v !== '';\n }\n if (mode === 'variable') {\n return (localVariables[input.name] ?? '').trim().length > 0;\n }\n if (mode === 'expression') {\n return (localExpressions[input.name] ?? '').trim().length > 0;\n }\n return false;\n });\n\n if (hasFilledRequired) {\n onModified?.(instance_id);\n }\n onClose();\n });\n\n const handleDisconnect = async (inputName: string) => {\n if (!editable) return;\n const result = await runner.apply([\n { disconnect: { scope: address.scope, target: address.id, input_name: inputName } },\n ]);\n // A rejected disconnect (a graph error, the engine gone) leaves the\n // input wired on the server; `runner.apply` already routed the failure\n // to `presenter.notify`, so setting local state to `empty` here too\n // would show a disconnected input the Subscribe stream is about to\n // contradict the moment its next frame lands.\n if (!result?.success) return;\n // The Subscribe stream pushes the post-disconnect Bundle; `config`\n // (derived from it) and the config-keyed re-seed effect above pick up\n // the now-empty mode without a manual re-query.\n setLocalModes((prev) => ({ ...prev, [inputName]: 'empty' }));\n };\n\n function renderModeSelector(input: RenderInput): React.ReactNode {\n const currentMode = localModes[input.name] ?? input.mode;\n const isWired = currentMode === 'wired';\n // Wired is always disabled (set by connect/disconnect). When the\n // current mode is wired, Lit/Var/Expr are also disabled so the user\n // can't silently overwrite a live binding. In read-only, every\n // item disables.\n const items = MODE_ITEMS.map((m) => ({\n ...m,\n disabled: !editable || m.value === 'wired' || isWired,\n }));\n return (\n <ModeToggle<BindingMode>\n value={currentMode}\n onChange={(next) => switchMode(input.name, next, input)}\n items={items}\n aria-label={`${input.name} binding mode`}\n />\n );\n }\n\n function renderInputField(input: RenderInput): React.ReactNode {\n const currentMode = localModes[input.name] ?? input.mode;\n\n return (\n <div key={input.name} className=\"lace-panel-field\">\n <label className=\"lace-panel-row-label\">\n <Identifier text={input.name} />\n {input.required && <span className=\"lace-mcp__required-star\">*</span>}\n </label>\n\n {renderModeSelector(input)}\n\n <div className=\"lace-panel-row-content\">\n {currentMode === 'wired' && renderWiredEditor(input)}\n {currentMode === 'variable' && renderVariableEditor(input)}\n {currentMode === 'expression' && renderExpressionEditor(input)}\n {currentMode === 'literal' && renderLiteralEditor(input)}\n </div>\n\n {input.description && (\n <div className=\"lace-panel-field__description\">{input.description}</div>\n )}\n </div>\n );\n }\n\n function renderWiredEditor(input: RenderInput): React.ReactNode {\n const label = input.wired_source ?? 'Not wired';\n return (\n <div className=\"lace-mcp__wired-row\">\n <div className=\"lace-mcp__wired-input\">\n <Input value={label} readOnly fullWidth mono />\n </div>\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label=\"Disconnect this input\"\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => handleDisconnect(input.name)}\n />\n )}\n </div>\n );\n }\n\n function renderVariableEditor(input: RenderInput): React.ReactNode {\n const currentVar = localVariables[input.name] ?? input.variable ?? '';\n return (\n <Input\n value={currentVar}\n onChange={(e) => {\n const raw = e.target.value;\n const name = raw.startsWith('var.') ? raw.slice(4) : raw;\n setLocalVariables((prev) => ({ ...prev, [input.name]: name }));\n }}\n placeholder=\"e.g. region\"\n fullWidth\n mono\n readOnly={!editable}\n />\n );\n }\n\n function renderExpressionEditor(input: RenderInput): React.ReactNode {\n const currentExpr = localExpressions[input.name] ?? input.expression ?? '';\n return (\n <Textarea\n value={currentExpr}\n onChange={(e) => setLocalExpressions((prev) => ({ ...prev, [input.name]: e.target.value }))}\n rows={3}\n placeholder='e.g. join(\"-\", [var.prefix, var.name])'\n fullWidth\n mono\n readOnly={!editable}\n />\n );\n }\n\n function renderLiteralEditor(input: RenderInput): React.ReactNode {\n const value = localValues[input.name] ?? input.value ?? input.default_value ?? null;\n const type = input.type || 'string';\n\n const updateValue = (val: unknown) => {\n setLocalValues((prev) => ({ ...prev, [input.name]: val }));\n };\n\n if (type === 'bool') {\n return (\n <select\n className=\"lace-mcp__select\"\n value={String(value ?? false)}\n onChange={(e) => updateValue(e.target.value === 'true')}\n disabled={!editable}\n >\n <option value=\"true\">True</option>\n <option value=\"false\">False</option>\n </select>\n );\n }\n\n if (type === 'number') {\n return (\n <Input\n type=\"number\"\n value={String(value ?? '')}\n onChange={(e) => updateValue(e.target.value === '' ? '' : Number(e.target.value))}\n fullWidth\n readOnly={!editable}\n />\n );\n }\n\n if (\n type.startsWith('list(') ||\n type.startsWith('map(') ||\n type.startsWith('set(') ||\n type === 'object' ||\n type.startsWith('object(')\n ) {\n const jsonStr = typeof value === 'string' ? value : JSON.stringify(value ?? null, null, 2);\n return (\n <Textarea\n value={jsonStr}\n onChange={(e) => {\n try {\n updateValue(JSON.parse(e.target.value));\n } catch {\n updateValue(e.target.value);\n }\n }}\n rows={4}\n fullWidth\n mono\n readOnly={!editable}\n />\n );\n }\n\n return (\n <Input\n value={String(value ?? '')}\n onChange={(e) => {\n let v = e.target.value;\n if (\n v.length >= 2 &&\n ((v[0] === '\"' && v[v.length - 1] === '\"') || (v[0] === \"'\" && v[v.length - 1] === \"'\"))\n ) {\n v = v.slice(1, -1);\n }\n updateValue(v);\n }}\n fullWidth\n readOnly={!editable}\n />\n );\n }\n\n if (!config) {\n return (\n <Panel title=\"Error\" onClose={onClose}>\n <div className=\"lace-mcp__error-title\">\n Failed to load configuration for \"{instance_id}\":\n </div>\n <div className=\"lace-mcp__error-detail\">Instance not found in the current Bundle.</div>\n </Panel>\n );\n }\n\n const dependsOnCount = localDependsOn.size;\n\n const title = (\n <div className=\"lace-mcp__title\">\n <div className=\"lace-mcp__title-eyebrow\">Module</div>\n <h3 className=\"lace-mcp__title-id\">\n <Identifier text={instance_id} />\n </h3>\n </div>\n );\n\n const footer = editable ? (\n <UpdateButton status={updateStatus} label=\"Update configuration\" onClick={handleUpdate} />\n ) : undefined;\n\n return (\n <Panel title={title} footer={footer} flush onClose={onClose}>\n {requiredInputs.length > 0 && (\n <AccordionSection title=\"Required Inputs\" defaultOpen badge={`(${requiredInputs.length})`}>\n {requiredInputs.map(renderInputField)}\n </AccordionSection>\n )}\n\n {optionalInputs.length > 0 && (\n <AccordionSection title=\"Optional Inputs\" defaultOpen badge={`(${optionalInputs.length})`}>\n {optionalInputs.map(renderInputField)}\n </AccordionSection>\n )}\n\n {config.sibling_ids.length > 0 && (\n <AccordionSection\n title=\"Depends On\"\n badge={dependsOnCount > 0 ? `(${dependsOnCount})` : undefined}\n >\n <div className=\"lace-mcp__depends-hint\">\n Select sibling instances this module depends on.\n </div>\n {config.sibling_ids.map((sibId) => {\n const depKey = `module.${sibId}`;\n return (\n <label key={sibId} className=\"lace-mcp__depends-item\">\n <input\n type=\"checkbox\"\n className=\"lace-mcp__depends-checkbox\"\n checked={localDependsOn.has(depKey)}\n disabled={!editable}\n onChange={(e) => {\n setLocalDependsOn((prev) => {\n const next = new Set(prev);\n if (e.target.checked) next.add(depKey);\n else next.delete(depKey);\n return next;\n });\n }}\n />\n <Identifier className=\"lace-mcp__depends-label\" text={depKey} />\n </label>\n );\n })}\n </AccordionSection>\n )}\n\n {(localProviders.length > 0 || editable) && (\n <AccordionSection\n title=\"Providers\"\n badge={localProviders.length > 0 ? `(${localProviders.length})` : undefined}\n >\n <div className=\"lace-mcp__depends-hint\">\n Map each child-local provider name to the root provider reference passed down (e.g.{' '}\n <code>aws</code> → <code>aws.west</code>).\n </div>\n {localProviders.map((row, i) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: rows are positional and freely editable\n <div key={i} className=\"lace-mcp__provider-row\">\n <Input\n value={row.key}\n onChange={(e) =>\n setLocalProviders((prev) =>\n prev.map((r, j) => (j === i ? { ...r, key: e.target.value } : r)),\n )\n }\n placeholder=\"child local (e.g. aws)\"\n mono\n readOnly={!editable}\n />\n <span className=\"lace-mcp__provider-arrow\">=</span>\n <Input\n value={row.value}\n onChange={(e) =>\n setLocalProviders((prev) =>\n prev.map((r, j) => (j === i ? { ...r, value: e.target.value } : r)),\n )\n }\n placeholder=\"root ref (e.g. aws.west)\"\n mono\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label=\"Remove this provider mapping\"\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => setLocalProviders((prev) => prev.filter((_, j) => j !== i))}\n />\n )}\n </div>\n ))}\n {editable && (\n <Button\n variant=\"secondary\"\n size=\"sm\"\n onClick={() => setLocalProviders((prev) => [...prev, { key: '', value: '' }])}\n >\n Add provider mapping\n </Button>\n )}\n </AccordionSection>\n )}\n\n {(localRepetition.count || localRepetition.for_each || editable) && (\n <AccordionSection title=\"Repetition\">\n <div className=\"lace-mcp__depends-hint\">\n The call's <code>count</code> or <code>for_each</code>: one module, called once per\n instance.\n </div>\n <Input\n label=\"count\"\n value={localRepetition.count}\n onChange={(e) => setLocalRepetition((prev) => ({ ...prev, count: e.target.value }))}\n placeholder=\"e.g. 2 or var.instances\"\n fullWidth\n mono\n readOnly={!editable}\n />\n <Input\n label=\"for_each\"\n value={localRepetition.for_each}\n onChange={(e) => setLocalRepetition((prev) => ({ ...prev, for_each: e.target.value }))}\n placeholder=\"e.g. var.regions\"\n fullWidth\n mono\n readOnly={!editable}\n />\n </AccordionSection>\n )}\n\n {config.outputs.length > 0 && (\n <AccordionSection title=\"Outputs\" badge={`(${config.outputs.length})`}>\n {config.outputs.map((o: RenderOutput) => (\n <div key={o.name} className=\"lace-mcp__output-card\">\n <div className=\"lace-mcp__output-header\">\n <Identifier className=\"lace-mcp__output-name\" text={o.name} />\n <Identifier className=\"lace-mcp__output-type\" text={o.type ?? ''} />\n </div>\n {o.description && <div className=\"lace-mcp__output-description\">{o.description}</div>}\n {o.sensitive && <div className=\"lace-mcp__output-sensitive\">sensitive</div>}\n </div>\n ))}\n </AccordionSection>\n )}\n\n {config.module_key && (\n <>\n <div className=\"lace-mcp__module-heading\">\n <div className=\"lace-mcp__title-eyebrow\">Called module</div>\n <Identifier text={config.module_key} />\n </div>\n <ModuleDetails key={config.module_key} moduleKey={config.module_key} />\n </>\n )}\n </Panel>\n );\n}\n","/** Compile-time exhaustiveness guard. See apps/api/src/lib/helpers.ts. */\nexport function assertNever(value: never): never {\n throw new Error(`Unhandled closed-enum branch: ${JSON.stringify(value)}`);\n}\n","import { useCallback, useEffect, useRef, useState } from 'react';\n\nexport type UpdateStatus = 'idle' | 'updating' | 'updated' | 'error';\n\n/**\n * Shared update state machine for settings panels — the panel's own commit\n * button writes the working IR (`env.apply`), a distinct operation from the\n * canvas's Save (which writes `state.lace`), hence \"Update\", not \"Save\".\n *\n * Handles: idle → updating → updated (1.5s) → idle\n * → error (2s) → idle\n *\n * A second update fired before the first resolves runs in parallel; this\n * is intentional — settings panels coalesce at the form level, not here.\n * A second update fired during the updated → idle window cancels the\n * pending timer so the new flow doesn't get yanked back to idle\n * mid-stream.\n */\nexport function useUpdateState(updateFn: () => Promise<void>) {\n const [status, setStatus] = useState<UpdateStatus>('idle');\n const mountedRef = useRef(true);\n const resetTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const safeSetStatus = useCallback((next: UpdateStatus) => {\n if (mountedRef.current) setStatus(next);\n }, []);\n\n const scheduleReset = useCallback(\n (delay: number) => {\n if (resetTimerRef.current !== null) clearTimeout(resetTimerRef.current);\n resetTimerRef.current = setTimeout(() => {\n resetTimerRef.current = null;\n safeSetStatus('idle');\n }, delay);\n },\n [safeSetStatus],\n );\n\n const handleUpdate = useCallback(async () => {\n safeSetStatus('updating');\n try {\n await updateFn();\n safeSetStatus('updated');\n scheduleReset(1500);\n } catch {\n safeSetStatus('error');\n scheduleReset(2000);\n }\n }, [updateFn, safeSetStatus, scheduleReset]);\n\n useEffect(() => {\n return () => {\n mountedRef.current = false;\n if (resetTimerRef.current !== null) {\n clearTimeout(resetTimerRef.current);\n resetTimerRef.current = null;\n }\n };\n }, []);\n\n return { status, handleUpdate };\n}\n","import type React from 'react';\nimport { useState } from 'react';\nimport './AccordionSection.css';\nimport { CanvasIcon } from './icons';\n\ntype Props = {\n title: string;\n defaultOpen?: boolean;\n badge?: string;\n children: React.ReactNode;\n};\n\nexport default function AccordionSection({ title, defaultOpen = false, badge, children }: Props) {\n const [open, setOpen] = useState(defaultOpen);\n\n return (\n <div className={`lace-accordion${open ? ' lace-accordion--open' : ''}`}>\n <button\n type=\"button\"\n className=\"lace-accordion__header\"\n onClick={() => setOpen((v) => !v)}\n aria-expanded={open}\n >\n <span className=\"lace-accordion__chevron\">\n <CanvasIcon name=\"chevron-right\" />\n </span>\n <span className=\"lace-accordion__title\">{title}</span>\n {badge && <span className=\"lace-accordion__badge\">{badge}</span>}\n </button>\n\n <div className=\"lace-accordion__body\">\n <div className=\"lace-accordion__body-inner\">\n <div className=\"lace-accordion__body-content\">{children}</div>\n </div>\n </div>\n </div>\n );\n}\n","import { Button, type ButtonVariant } from '@lace-cloud/ui';\nimport type { UpdateStatus } from '../hooks/useUpdateState';\nimport './UpdateButton.css';\n\ntype Props = {\n status: UpdateStatus;\n label: string;\n onClick: () => void;\n disabled?: boolean;\n disabledTitle?: string;\n};\n\n// Status → UI-primitive mapping. `idle` uses the caller-supplied label; the\n// other statuses carry their own user-facing text since the status itself\n// is the message (updating, updated, error). `updating` is represented by\n// loading state on the primary Button so the spinner renders consistently\n// with any other loading button in the app.\nconst variantByStatus: Record<UpdateStatus, ButtonVariant> = {\n idle: 'primary',\n updating: 'primary',\n updated: 'success',\n error: 'danger',\n};\n\nconst labelByStatus: Record<Exclude<UpdateStatus, 'idle'>, string> = {\n updating: 'Updating…',\n updated: 'Updated!',\n error: 'Update failed — try again',\n};\n\nexport default function UpdateButton({ status, label, onClick, disabled, disabledTitle }: Props) {\n // Pinned to the foot of the panel's scroll while its section is in view:\n // a long section's commit is never scrolled out of reach.\n return (\n <div className=\"lace-commit-foot\">\n <Button\n rung\n variant={variantByStatus[status]}\n fullWidth\n loading={status === 'updating'}\n disabled={disabled || status === 'updated'}\n onClick={onClick}\n tooltip={disabled ? disabledTitle : undefined}\n >\n {status === 'idle' ? label : labelByStatus[status]}\n </Button>\n </div>\n );\n}\n","// One module's details, every construct the IR holds of it beside its\n// calls (`deriveSettingsConfig`): a definition's resources and data\n// sources, interface, moved and import blocks, locals, providers and\n// terraform block, each section editing that module through actions that\n// name it (`module-actions.ts`); a reference's source, pin and the\n// interface the IR holds for it, read-only. The settings panel shows the\n// entry's, and a call's panel the module the call reads, so a definition\n// many calls read is edited once for all of them. Every definition shows\n// its resources and data sources, since a data source is a detail of any\n// module; it takes a managed resource only where lace shape lets it hold\n// one.\nimport { deriveSettingsConfig } from '@lace-cloud/proto';\nimport { Input } from '@lace-cloud/ui';\nimport { useMemo, useState } from 'react';\nimport type { Action } from '../../generated/service';\nimport { useUpdateState } from '../../hooks/useUpdateState';\nimport type { ApplyResult } from '../../ports';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { BlockConfig, SettingsConfig } from '../../types/render';\nimport { typedName } from '../../utils/typed-name';\nimport AccordionSection from '../AccordionSection';\nimport Identifier from '../Identifier';\nimport UpdateButton from '../UpdateButton';\nimport BlockEditor from './BlockEditor';\nimport { LocalsContent } from './LocalsPanel';\nimport { ModuleInterfaceContent } from './ModuleInterfacePanel';\nimport {\n addResource,\n removeResource,\n resourceActions,\n setDirectives,\n setLocals,\n setOutputs,\n setProviders,\n setTerraform,\n setVariables,\n} from './module-actions';\nimport './panels-shared.css';\nimport { ProvidersContent } from './ProvidersPanel';\nimport { ResourcesContent } from './ResourcesPanel';\nimport { TerraformConfigContent } from './TerraformConfigPanel';\n\n// A section's own update-state machine (`useUpdateState`, driving each\n// `UpdateButton`) reads success from whether its `onSave` promise rejects —\n// so a rejected `ApplyResult` has to reject here too, or the button reads\n// back \"Updated!\" on a write the engine refused. `runner.apply` already\n// routes the failure to `presenter.notify` once; this only turns that same\n// result into the rejection the update-state machine is watching for.\nfunction assertApplied(result: ApplyResult | undefined): asserts result is ApplyResult {\n if (!result?.success) throw new Error('apply failed');\n}\n\n// A section's key: a new frame that changes what the section shows\n// re-seeds its rows, so a change made in the tf shows in an open panel.\nconst keyOf = (value: unknown) => JSON.stringify(value);\n\ntype Props = {\n moduleKey: string;\n // Sections that open by default.\n open?: readonly string[];\n};\n\nexport default function ModuleDetails({ moduleKey, open = [] }: Props) {\n const { bundle, runner, editable } = useCanvas();\n const settings = useMemo(() => deriveSettingsConfig(bundle, moduleKey), [bundle, moduleKey]);\n if (!settings) return null;\n if (settings.reference) return <ReferenceDetails settings={settings} />;\n\n const apply = async (actions: Action[]) => {\n if (!editable) return;\n assertApplied(await runner.apply(actions));\n };\n return (\n <>\n <AccordionSection\n title=\"Resources\"\n defaultOpen={open.includes('Resources')}\n badge={`(${settings.resources.length})`}\n >\n <ResourcesContent\n resources={settings.resources}\n dependencyOptions={settings.dependency_options}\n managed={settings.holds_managed_resources}\n onUpdate={(before, after) => apply(resourceActions(moduleKey, before, after))}\n onRemove={(id) => apply([removeResource(moduleKey, id)])}\n onAdd={(kind, type, name) => apply([addResource(moduleKey, kind, type, name)])}\n />\n </AccordionSection>\n\n <AccordionSection title=\"Interface\" defaultOpen={open.includes('Interface')}>\n <ModuleInterfaceContent\n key={keyOf([settings.variables, settings.outputs, settings.call_outputs])}\n settings={settings}\n onSave={(variables, outputs) =>\n apply([setVariables(moduleKey, variables), setOutputs(moduleKey, outputs)])\n }\n />\n </AccordionSection>\n\n <AccordionSection\n title=\"Moved and import blocks\"\n defaultOpen={open.includes('Moved and import blocks')}\n badge={settings.directives.length > 0 ? `(${settings.directives.length})` : undefined}\n >\n <DirectivesContent\n key={keyOf(settings.directives)}\n directives={settings.directives}\n onSave={(blocks) => apply([setDirectives(moduleKey, blocks)])}\n />\n </AccordionSection>\n\n <AccordionSection title=\"Locals\" defaultOpen={open.includes('Locals')}>\n <LocalsContent\n key={keyOf(settings.locals)}\n locals={settings.locals}\n onSave={(locals) => apply([setLocals(moduleKey, locals)])}\n />\n </AccordionSection>\n\n <AccordionSection title=\"Providers\" defaultOpen={open.includes('Providers')}>\n <ProvidersContent\n key={keyOf(settings.providers)}\n providers={settings.providers}\n onSave={(providers) => apply([setProviders(moduleKey, providers)])}\n />\n </AccordionSection>\n\n <AccordionSection title=\"Terraform Config\" defaultOpen={open.includes('Terraform Config')}>\n <TerraformConfigContent\n key={keyOf(settings.terraform)}\n terraform={settings.terraform}\n onSave={(terraform) => apply([setTerraform(moduleKey, terraform)])}\n />\n </AccordionSection>\n </>\n );\n}\n\n// A module's moved and import blocks, set whole by one Update.\nfunction DirectivesContent({\n directives,\n onSave,\n}: {\n directives: BlockConfig[];\n onSave: (blocks: BlockConfig[]) => Promise<void>;\n}) {\n const { editable } = useCanvas();\n const [blocks, setBlocks] = useState(directives);\n const { status, handleUpdate } = useUpdateState(() => onSave(blocks));\n return (\n <>\n {blocks.length === 0 && <div className=\"lace-panel-hint\">No moved or import blocks.</div>}\n <BlockEditor\n blocks={blocks}\n editable={editable}\n onChange={setBlocks}\n templates={[\n { type: 'moved', attributes: ['from', 'to'] },\n { type: 'import', attributes: ['to', 'id'] },\n ]}\n />\n {editable && (\n <UpdateButton\n status={status}\n label=\"Update moved and import blocks\"\n onClick={handleUpdate}\n />\n )}\n </>\n );\n}\n\n// A reference holds no content the IR reads: its panel shows where its\n// source points, the version its calls pin, and the interface a placement\n// certified, and edits nothing.\nfunction ReferenceDetails({ settings }: { settings: SettingsConfig }) {\n const reference = settings.reference;\n if (!reference) return null;\n return (\n <>\n <AccordionSection title=\"Source\" defaultOpen>\n <div className=\"lace-panel-hint\">\n A reference: Lace reads it where its source points and never edits it.\n </div>\n <div className=\"lace-panel-row-actions lace-panel-row-actions--stacked\">\n <Input label=\"Source\" value={reference.source} fullWidth mono readOnly />\n <Input label=\"Version\" value={reference.version} fullWidth mono readOnly />\n </div>\n </AccordionSection>\n <AccordionSection title=\"Interface\" defaultOpen>\n <h4 className=\"lace-panel-section-title\">Inputs</h4>\n {settings.variables.length === 0 && (\n <div className=\"lace-panel-hint\">The IR holds no interface for this reference.</div>\n )}\n {settings.variables.map((v) => (\n <div key={v.name} className=\"lace-panel-depends-item\">\n <Identifier text={`${typedName(v.name, v.type)}${v.required ? ' (required)' : ''}`} />\n </div>\n ))}\n <h4 className=\"lace-panel-section-title\">Outputs</h4>\n {settings.outputs.map((o) => (\n <div key={o.name} className=\"lace-panel-depends-item\">\n <Identifier text={typedName(o.name, o.type)} />\n </div>\n ))}\n </AccordionSection>\n </>\n );\n}\n","// BlockEditor shows and edits a list of blocks — a resource's or a provider\n// configuration's nested blocks, a module's moved and import blocks — each\n// attribute's value as the HCL text the render writes for it\n// (`BlockConfig`), which the engine reads back as the parse reads it. It is\n// controlled: the list is its parent's, every edit a new list through\n// `onChange`. Read-only, it shows the same rows with no control.\nimport { Button, IconButton, Input } from '@lace-cloud/ui';\nimport { useState } from 'react';\nimport type { BlockConfig } from '../../types/render';\nimport Identifier from '../Identifier';\nimport { CanvasIcon } from '../icons';\nimport './panels-shared.css';\n\n// A block a list offers to add: its type and the attributes it starts with.\ntype BlockTemplate = { type: string; attributes: string[] };\n\ntype Props = {\n blocks: BlockConfig[];\n onChange: (blocks: BlockConfig[]) => void;\n editable: boolean;\n // The blocks the list offers to add, one button each. Unset, the list\n // adds a block of the type (and label) the developer names.\n templates?: BlockTemplate[];\n};\n\nfunction replaceAt<T>(list: readonly T[], index: number, item: T): T[] {\n return list.map((x, i) => (i === index ? item : x));\n}\n\nfunction blockTitle(block: BlockConfig): string {\n return [block.type, ...block.labels.map((l) => `\"${l}\"`)].join(' ');\n}\n\nexport default function BlockEditor({ blocks, onChange, editable, templates }: Props) {\n return (\n <>\n {blocks.map((block, i) => (\n <BlockCard\n // biome-ignore lint/suspicious/noArrayIndexKey: blocks are positional; the render writes them in this order\n key={i}\n block={block}\n editable={editable}\n onChange={(next) => onChange(replaceAt(blocks, i, next))}\n onRemove={() => onChange(blocks.filter((_, j) => j !== i))}\n />\n ))}\n {editable &&\n (templates ? (\n <div className=\"lace-panel-row-actions\">\n {templates.map((t) => (\n <Button\n key={t.type}\n variant=\"secondary\"\n size=\"sm\"\n onClick={() =>\n onChange([\n ...blocks,\n {\n type: t.type,\n labels: [],\n attributes: t.attributes.map((name) => ({ name, value: '' })),\n blocks: [],\n },\n ])\n }\n >\n + Add {t.type} block\n </Button>\n ))}\n </div>\n ) : (\n <NewBlockRow\n onAdd={(type, label) =>\n onChange([\n ...blocks,\n { type, labels: label ? [label] : [], attributes: [], blocks: [] },\n ])\n }\n />\n ))}\n </>\n );\n}\n\nfunction NewBlockRow({ onAdd }: { onAdd: (type: string, label: string) => void }) {\n const [type, setType] = useState('');\n const [label, setLabel] = useState('');\n return (\n <div className=\"lace-panel-row-actions\">\n <Input\n value={type}\n onChange={(e) => setType(e.target.value)}\n placeholder=\"Block type (e.g. lifecycle)\"\n aria-label=\"New block type\"\n mono\n />\n <Input\n value={label}\n onChange={(e) => setLabel(e.target.value)}\n placeholder=\"Label (optional)\"\n aria-label=\"New block label\"\n mono\n />\n <Button\n variant=\"secondary\"\n size=\"sm\"\n disabled={!type.trim()}\n onClick={() => {\n onAdd(type.trim(), label.trim());\n setType('');\n setLabel('');\n }}\n >\n + Add block\n </Button>\n </div>\n );\n}\n\ntype CardProps = {\n block: BlockConfig;\n editable: boolean;\n onChange: (block: BlockConfig) => void;\n onRemove: () => void;\n};\n\nfunction BlockCard({ block, editable, onChange, onRemove }: CardProps) {\n const setAttribute = (index: number, field: 'name' | 'value', value: string) =>\n onChange({\n ...block,\n attributes: replaceAt(block.attributes, index, {\n ...block.attributes[index],\n [field]: value,\n }),\n });\n return (\n <div className=\"lace-panel-validation-block\">\n <div className=\"lace-panel-row-actions\">\n <Identifier className=\"lace-panel-row-card__name\" text={blockTitle(block)} />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label={`Remove the ${block.type} block`}\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={onRemove}\n />\n )}\n </div>\n {block.attributes.map((attribute, i) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: attributes are positional; the render keeps their order\n <div key={i} className=\"lace-panel-row-actions\">\n <Input\n value={attribute.name}\n onChange={(e) => setAttribute(i, 'name', e.target.value)}\n placeholder=\"Argument\"\n aria-label={`${block.type} argument name`}\n mono\n readOnly={!editable}\n />\n <Input\n value={attribute.value}\n onChange={(e) => setAttribute(i, 'value', e.target.value)}\n placeholder=\"Value\"\n aria-label={`${attribute.name || block.type} value`}\n mono\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label={`Remove ${attribute.name || 'the argument'}`}\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() =>\n onChange({ ...block, attributes: block.attributes.filter((_, j) => j !== i) })\n }\n />\n )}\n </div>\n ))}\n {editable && (\n <Button\n variant=\"secondary\"\n size=\"sm\"\n onClick={() =>\n onChange({ ...block, attributes: [...block.attributes, { name: '', value: '' }] })\n }\n >\n + Add argument\n </Button>\n )}\n {(block.blocks.length > 0 || editable) && (\n <BlockEditor\n blocks={block.blocks}\n editable={editable}\n onChange={(blocks) => onChange({ ...block, blocks })}\n />\n )}\n </div>\n );\n}\n","import { Button, IconButton, Input, Panel, Textarea } from '@lace-cloud/ui';\nimport { useCallback, useState } from 'react';\nimport { useUpdateState } from '../../hooks/useUpdateState';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { SettingsConfig } from '../../types/render';\nimport { findDuplicateIndices } from '../../utils/duplicates';\nimport { CanvasIcon } from '../icons';\nimport UpdateButton from '../UpdateButton';\nimport './panels-shared.css';\n\n// ── Types derived from SettingsConfig ──\n\ntype LocalEntry = SettingsConfig['locals'][number];\n\n// A local's value is the HCL text the render writes for it — a literal,\n// `var.<name>`, or any expression — which the engine reads back as the\n// parse reads it, so one text field edits every kind of value.\n\ntype LocalRow = LocalEntry & {\n // Stable per-row id, used as React key. Generated when the row is\n // created (toRows / addLocal), survives edits + reorders. NOT\n // persisted — fromRows strips it before sending to the engine.\n id: string;\n};\n\nfunction toRows(locals: LocalEntry[] | undefined): LocalRow[] {\n return (locals ?? []).map((l) => ({ id: crypto.randomUUID(), ...l }));\n}\n\nfunction fromRows(rows: LocalRow[]): LocalEntry[] {\n return rows.filter((r) => r.name.trim()).map((r) => ({ name: r.name.trim(), value: r.value }));\n}\n\n// ── Content-only component (used by ModuleDetails) ──\n\ntype ContentProps = {\n locals: LocalEntry[] | undefined;\n onSave: (locals: LocalEntry[]) => void | Promise<void>;\n};\n\nexport function LocalsContent({ locals, onSave }: ContentProps) {\n const { editable } = useCanvas();\n const [rows, setRows] = useState<LocalRow[]>(() => toRows(locals));\n\n const addLocal = useCallback(() => {\n setRows((prev) => [...prev, { id: crypto.randomUUID(), name: '', value: '' }]);\n }, []);\n\n const removeLocal = useCallback((index: number) => {\n setRows((prev) => prev.filter((_, i) => i !== index));\n }, []);\n\n const updateRow = useCallback((index: number, field: 'name' | 'value', value: string) => {\n setRows((prev) => prev.map((r, i) => (i === index ? { ...r, [field]: value } : r)));\n }, []);\n\n const nameDupes = findDuplicateIndices(rows, (r) => r.name);\n const hasErrors = nameDupes.size > 0;\n\n const { status: updateStatus, handleUpdate } = useUpdateState(\n useCallback(async () => {\n if (hasErrors) return;\n await onSave(fromRows(rows));\n }, [onSave, rows, hasErrors]),\n );\n\n return (\n <>\n {rows.map((row, i) => (\n <div key={row.id} className=\"lace-panel-row-card lace-panel-row-card--with-footer\">\n <div className=\"lace-panel-row-actions\">\n <Input\n value={row.name}\n onChange={(e) => updateRow(i, 'name', e.target.value)}\n placeholder=\"Local name\"\n aria-label=\"Local name\"\n fullWidth\n mono\n error={nameDupes.has(i)}\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label=\"Remove local\"\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => removeLocal(i)}\n />\n )}\n </div>\n {nameDupes.has(i) && <div className=\"lace-panel-row-error\">Duplicate local name</div>}\n\n <div className=\"lace-panel-row-content\">\n <Textarea\n value={row.value}\n onChange={(e) => updateRow(i, 'value', e.target.value)}\n placeholder='e.g. \"my-bucket\" or \"${var.environment}-logs\"'\n aria-label={`${row.name || 'Local'} value`}\n rows={3}\n fullWidth\n mono\n readOnly={!editable}\n />\n </div>\n </div>\n ))}\n\n {editable && (\n <>\n <Button variant=\"secondary\" size=\"sm\" onClick={addLocal}>\n + Add local\n </Button>\n\n <UpdateButton\n status={updateStatus}\n label=\"Update locals\"\n onClick={handleUpdate}\n disabled={hasErrors}\n disabledTitle=\"Fix errors before saving\"\n />\n </>\n )}\n </>\n );\n}\n\n// ── The standalone panel ──\n\ntype Props = {\n locals: LocalEntry[] | undefined;\n onSave: (locals: LocalEntry[]) => void | Promise<void>;\n onClose: () => void;\n};\n\nexport default function LocalsPanel({ locals, onSave, onClose }: Props) {\n return (\n <Panel title=\"Locals\" onClose={onClose}>\n <LocalsContent locals={locals} onSave={onSave} />\n </Panel>\n );\n}\n","/**\n * Find indices of items with duplicate keys (case-insensitive).\n * Returns a Set of all indices that participate in a duplicate group.\n */\nexport function findDuplicateIndices<T>(items: T[], keyFn: (item: T) => string): Set<number> {\n const seen = new Map<string, number>();\n const dupes = new Set<number>();\n items.forEach((item, i) => {\n const key = keyFn(item).trim().toLowerCase();\n if (!key) return;\n if (seen.has(key)) {\n dupes.add(i);\n dupes.add(seen.get(key)!);\n }\n seen.set(key, i);\n });\n return dupes;\n}\n","import { Button, IconButton, Input, Panel, Select, Textarea } from '@lace-cloud/ui';\nimport { useCallback, useState } from 'react';\nimport { useUpdateState } from '../../hooks/useUpdateState';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { SettingsConfig } from '../../types/render';\nimport { findDuplicateIndices } from '../../utils/duplicates';\nimport Identifier from '../Identifier';\nimport { CanvasIcon } from '../icons';\nimport UpdateButton from '../UpdateButton';\nimport './panels-shared.css';\n\n// Host-facing DTOs for the batch this panel's Update issues (its variables\n// and its outputs) — distinct from the wire InputDef/OutputDef (e.g.\n// `default` not `default_value`) because the panel edits them as flat rows\n// before ModuleDetails converts to the SetVariablesAction /\n// SetExportsAction shape.\nexport type VariableDef = {\n name: string;\n type: string;\n required: boolean;\n description?: string;\n default?: unknown;\n validation?: { condition: string; error_message: string }[];\n ephemeral?: boolean;\n sensitive?: boolean;\n nullable?: boolean;\n};\n\n// An output: its name, its value as the HCL text the render writes for it,\n// and what its definition carries beside the value.\nexport type OutputDefEntry = {\n name: string;\n value: string;\n description?: string;\n sensitive?: boolean;\n depends_on?: string[];\n};\n\n// The Interface section is a module's public surface: the variables its\n// callers set and the outputs they read.\n//\n// A variable's name is what its readers read, so an existing one is shown,\n// not renamed; its type, description, flags and validation are edited, and\n// its default (written by the source or the call that declared it) is\n// shown as the render writes it and kept as it is. A variable is added by\n// name and removed whole. An empty type is no declared type, as the IR\n// holds a variable with no type line: it is shown as such and set as such,\n// never filled in.\n//\n// An output is its name and its value: a resource's attribute, a call's\n// output, a literal, a variable or any expression, as text. The outputs the\n// module's calls offer are listed to expose one in a step.\n\ntype ValidationRow = { id: string; condition: string; error_message: string };\n\ntype VariableRow = {\n id: string;\n name: string;\n // A variable the panel added: its name is still the panel's to set.\n added: boolean;\n type: string;\n required: boolean;\n description: string;\n // Round-tripped as it is; `defaultText` shows it.\n default_value?: unknown;\n defaultText: string;\n validation: ValidationRow[];\n ephemeral: boolean;\n sensitive: boolean;\n // `nullable` — whether `null` is an allowed value. Defaults to true\n // (Terraform's default); unchecking authors an explicit `nullable = false`.\n nullable: boolean;\n};\n\ntype OutputRow = {\n id: string;\n name: string;\n value: string;\n description: string;\n sensitive: boolean;\n depends_on: string[];\n};\n\nfunction variablesToRows(variables: SettingsConfig['variables']): VariableRow[] {\n return variables.map((v) => ({\n id: crypto.randomUUID(),\n name: v.name,\n added: false,\n type: v.type,\n required: v.required,\n description: v.description ?? '',\n default_value: v.default_value,\n defaultText: v.default,\n validation: (v.validation ?? []).map((b) => ({\n id: crypto.randomUUID(),\n condition: b.condition,\n error_message: b.error_message,\n })),\n ephemeral: v.ephemeral ?? false,\n sensitive: v.sensitive ?? false,\n // Wire `nullable` is tri-state: unset means Terraform's default (null\n // allowed), so an absent value shows the toggle ON.\n nullable: v.nullable ?? true,\n }));\n}\n\nfunction outputsToRows(outputs: SettingsConfig['outputs']): OutputRow[] {\n return outputs.map((o) => ({\n id: crypto.randomUUID(),\n name: o.name,\n value: o.value,\n description: o.description ?? '',\n sensitive: o.sensitive ?? false,\n depends_on: o.depends_on ?? [],\n }));\n}\n\n// The output a call's output text names: `module.<call>.<output>` exposes\n// as `<output>`.\nfunction outputName(text: string): string {\n return text.slice(text.lastIndexOf('.') + 1);\n}\n\n// ── Content-only component (used by ModuleDetails) ──\n\ntype ContentProps = {\n settings: SettingsConfig;\n // One Update sets the variables and the outputs in one batch.\n onSave: (variables: VariableDef[], outputs: OutputDefEntry[]) => void | Promise<void>;\n};\n\nexport function ModuleInterfaceContent({ settings, onSave }: ContentProps) {\n const { editable } = useCanvas();\n const [variables, setVariables] = useState<VariableRow[]>(() =>\n variablesToRows(settings.variables),\n );\n const [outputs, setOutputs] = useState<OutputRow[]>(() => outputsToRows(settings.outputs));\n\n const updateVariable = useCallback(\n <K extends keyof VariableRow>(index: number, field: K, value: VariableRow[K]) => {\n setVariables((prev) => prev.map((v, i) => (i === index ? { ...v, [field]: value } : v)));\n },\n [],\n );\n\n const addVariable = useCallback(() => {\n setVariables((prev) => [\n ...prev,\n {\n id: crypto.randomUUID(),\n name: '',\n added: true,\n type: '',\n required: true,\n description: '',\n defaultText: '',\n validation: [],\n ephemeral: false,\n sensitive: false,\n nullable: true,\n },\n ]);\n }, []);\n\n const addValidation = useCallback((index: number) => {\n setVariables((prev) =>\n prev.map((v, i) =>\n i === index\n ? {\n ...v,\n validation: [\n ...v.validation,\n { id: crypto.randomUUID(), condition: '', error_message: '' },\n ],\n }\n : v,\n ),\n );\n }, []);\n\n const removeValidation = useCallback((index: number, vIndex: number) => {\n setVariables((prev) =>\n prev.map((v, i) =>\n i === index ? { ...v, validation: v.validation.filter((_, j) => j !== vIndex) } : v,\n ),\n );\n }, []);\n\n const updateValidation = useCallback(\n (index: number, vIndex: number, field: keyof ValidationRow, value: string) => {\n setVariables((prev) =>\n prev.map((v, i) =>\n i === index\n ? {\n ...v,\n validation: v.validation.map((b, j) =>\n j === vIndex ? { ...b, [field]: value } : b,\n ),\n }\n : v,\n ),\n );\n },\n [],\n );\n\n const updateOutput = useCallback(\n <K extends keyof OutputRow>(index: number, field: K, value: OutputRow[K]) => {\n setOutputs((prev) => prev.map((o, i) => (i === index ? { ...o, [field]: value } : o)));\n },\n [],\n );\n\n const addOutput = useCallback((name: string, value: string) => {\n setOutputs((prev) => [\n ...prev,\n { id: crypto.randomUUID(), name, value, description: '', sensitive: false, depends_on: [] },\n ]);\n }, []);\n\n const toggleDependsOn = useCallback((index: number, dep: string) => {\n setOutputs((prev) =>\n prev.map((o, i) => {\n if (i !== index) return o;\n const has = o.depends_on.includes(dep);\n return {\n ...o,\n depends_on: has ? o.depends_on.filter((k) => k !== dep) : [...o.depends_on, dep],\n };\n }),\n );\n }, []);\n\n const variableDupes = findDuplicateIndices(variables, (v) => v.name);\n const outputDupes = findDuplicateIndices(outputs, (o) => o.name);\n const unnamedOutput = outputs.some((o) => !o.name.trim() || !o.value.trim());\n const hasErrors = variableDupes.size > 0 || outputDupes.size > 0 || unnamedOutput;\n\n const { status: updateStatus, handleUpdate } = useUpdateState(\n useCallback(async () => {\n if (hasErrors) return;\n const variableDefs: VariableDef[] = variables\n .filter((v) => v.name.trim())\n .map((v) => {\n const validation = v.validation\n .map((b) => ({ condition: b.condition.trim(), error_message: b.error_message.trim() }))\n .filter((b) => b.condition || b.error_message);\n return {\n name: v.name.trim(),\n type: v.type.trim(),\n required: v.required,\n description: v.description.trim() || undefined,\n default: v.default_value,\n validation: validation.length > 0 ? validation : undefined,\n ephemeral: v.ephemeral || undefined,\n // `false` turns sensitive off: the variables are set whole.\n sensitive: v.sensitive,\n // `nullable` is tri-state on the wire (unset = default true). The\n // toggle ON keeps the default by omitting the field; OFF authors\n // an explicit `false`.\n nullable: v.nullable ? undefined : false,\n };\n });\n const outputDefs: OutputDefEntry[] = outputs.map((o) => ({\n name: o.name.trim(),\n value: o.value,\n description: o.description || undefined,\n sensitive: o.sensitive || undefined,\n depends_on: o.depends_on.length > 0 ? o.depends_on : undefined,\n }));\n await onSave(variableDefs, outputDefs);\n }, [variables, outputs, hasErrors, onSave]),\n );\n\n const exposable = settings.call_outputs.filter((text) => !outputs.some((o) => o.value === text));\n\n return (\n <>\n <div className=\"lace-panel-hint\">\n The module's public surface: the variables its callers set and the outputs they read.\n </div>\n\n <h4 className=\"lace-panel-section-title\">Inputs</h4>\n {variables.length === 0 && <div className=\"lace-panel-hint\">No variables.</div>}\n {variables.map((v, i) => (\n <div key={v.id} className=\"lace-panel-row-card lace-panel-row-card--with-footer\">\n <div className=\"lace-panel-row-actions\">\n {v.added ? (\n <Input\n label=\"Name\"\n value={v.name}\n onChange={(e) => updateVariable(i, 'name', e.target.value)}\n placeholder=\"Variable name\"\n fullWidth\n mono\n error={variableDupes.has(i)}\n />\n ) : (\n <Identifier className=\"lace-panel-row-card__name\" text={v.name} />\n )}\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label={`Remove variable ${v.name}`}\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => setVariables((prev) => prev.filter((_, j) => j !== i))}\n />\n )}\n </div>\n {variableDupes.has(i) && (\n <div className=\"lace-panel-row-error\">Duplicate variable name</div>\n )}\n <div className=\"lace-panel-row-actions\">\n <Input\n label=\"Type\"\n value={v.type}\n onChange={(e) => updateVariable(i, 'type', e.target.value)}\n placeholder=\"No declared type\"\n fullWidth\n mono\n readOnly={!editable}\n />\n </div>\n {v.defaultText && (\n <div className=\"lace-panel-row-actions\">\n <Input label=\"Default\" value={v.defaultText} fullWidth mono readOnly />\n </div>\n )}\n <div className=\"lace-panel-row-content\">\n <Textarea\n label=\"Description\"\n value={v.description}\n onChange={(e) => updateVariable(i, 'description', e.target.value)}\n placeholder=\"Optional\"\n rows={2}\n fullWidth\n readOnly={!editable}\n />\n </div>\n <div className=\"lace-panel-row-actions\">\n <label className=\"lace-panel-checkbox-row\">\n <input\n type=\"checkbox\"\n checked={v.required}\n onChange={(e) => updateVariable(i, 'required', e.target.checked)}\n disabled={!editable}\n />\n <span>Required</span>\n </label>\n <label className=\"lace-panel-checkbox-row\">\n <input\n type=\"checkbox\"\n checked={v.ephemeral}\n onChange={(e) => updateVariable(i, 'ephemeral', e.target.checked)}\n disabled={!editable}\n />\n <span>Ephemeral</span>\n </label>\n <label className=\"lace-panel-checkbox-row\">\n <input\n type=\"checkbox\"\n checked={v.sensitive}\n onChange={(e) => updateVariable(i, 'sensitive', e.target.checked)}\n disabled={!editable}\n />\n <span>Sensitive</span>\n </label>\n <label className=\"lace-panel-checkbox-row\">\n <input\n type=\"checkbox\"\n checked={v.nullable}\n onChange={(e) => updateVariable(i, 'nullable', e.target.checked)}\n disabled={!editable}\n />\n <span>Nullable</span>\n </label>\n </div>\n {(v.validation.length > 0 || editable) && (\n <div className=\"lace-panel-row-content\">\n <div className=\"lace-panel-subsection-label\">Validation</div>\n {v.validation.map((block, j) => (\n <div key={block.id} className=\"lace-panel-validation-block\">\n <Input\n value={block.condition}\n onChange={(e) => updateValidation(i, j, 'condition', e.target.value)}\n placeholder=\"condition (e.g. length(var.x) > 0)\"\n aria-label=\"Validation condition\"\n fullWidth\n mono\n readOnly={!editable}\n />\n <Input\n value={block.error_message}\n onChange={(e) => updateValidation(i, j, 'error_message', e.target.value)}\n placeholder=\"error message\"\n aria-label=\"Validation error message\"\n fullWidth\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label=\"Remove validation rule\"\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => removeValidation(i, j)}\n />\n )}\n </div>\n ))}\n {editable && (\n <Button variant=\"secondary\" size=\"sm\" onClick={() => addValidation(i)}>\n + Add validation rule\n </Button>\n )}\n </div>\n )}\n </div>\n ))}\n {editable && (\n <Button variant=\"secondary\" size=\"sm\" onClick={addVariable}>\n + Add variable\n </Button>\n )}\n\n <h4 className=\"lace-panel-section-title\">Outputs</h4>\n {outputs.length === 0 && <div className=\"lace-panel-hint\">No outputs.</div>}\n {outputs.map((o, i) => (\n <div key={o.id} className=\"lace-panel-row-card lace-panel-row-card--with-footer\">\n <div className=\"lace-panel-row-actions\">\n <Input\n label=\"Name\"\n value={o.name}\n onChange={(e) => updateOutput(i, 'name', e.target.value)}\n placeholder=\"Output name\"\n fullWidth\n mono\n readOnly={!editable}\n error={outputDupes.has(i) || (editable && !o.name.trim())}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label={`Remove output ${o.name}`}\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => setOutputs((prev) => prev.filter((_, j) => j !== i))}\n />\n )}\n </div>\n <div className=\"lace-panel-row-actions\">\n <Input\n label=\"Value\"\n value={o.value}\n onChange={(e) => updateOutput(i, 'value', e.target.value)}\n placeholder=\"e.g. aws_s3_bucket.this.arn\"\n fullWidth\n mono\n readOnly={!editable}\n error={editable && !o.value.trim()}\n />\n </div>\n <div className=\"lace-panel-row-content\">\n <Textarea\n label=\"Description\"\n value={o.description}\n onChange={(e) => updateOutput(i, 'description', e.target.value)}\n placeholder=\"Optional\"\n rows={2}\n fullWidth\n readOnly={!editable}\n />\n </div>\n <label className=\"lace-panel-checkbox-row\">\n <input\n type=\"checkbox\"\n checked={o.sensitive}\n onChange={(e) => updateOutput(i, 'sensitive', e.target.checked)}\n disabled={!editable}\n />\n <span>Sensitive</span>\n </label>\n {(o.depends_on.length > 0 || (editable && settings.dependency_options.length > 0)) && (\n <div className=\"lace-panel-row-content\">\n <div className=\"lace-panel-subsection-label\">Depends on</div>\n {!editable\n ? o.depends_on.map((dep) => (\n <div key={dep} className=\"lace-panel-depends-item\">\n <Identifier text={dep} />\n </div>\n ))\n : settings.dependency_options.map((dep) => (\n <label key={dep} className=\"lace-panel-checkbox-row\">\n <input\n type=\"checkbox\"\n checked={o.depends_on.includes(dep)}\n onChange={() => toggleDependsOn(i, dep)}\n />\n <Identifier text={dep} />\n </label>\n ))}\n </div>\n )}\n {outputDupes.has(i) && (\n <div className=\"lace-panel-row-error\">Output names must be unique.</div>\n )}\n </div>\n ))}\n\n {editable && (\n <div className=\"lace-panel-row-actions\">\n <Button variant=\"secondary\" size=\"sm\" onClick={() => addOutput('', '')}>\n + Add output\n </Button>\n {exposable.length > 0 && (\n <Select\n aria-label=\"Expose a call's output\"\n options={[\n { value: '', label: \"Expose a call's output…\" },\n ...exposable.map((text) => ({ value: text, label: text })),\n ]}\n value=\"\"\n onChange={(e) => {\n const text = e.target.value;\n if (text) addOutput(outputName(text), text);\n }}\n />\n )}\n </div>\n )}\n\n {editable && (\n <UpdateButton\n status={updateStatus}\n label=\"Update interface\"\n onClick={handleUpdate}\n disabled={hasErrors}\n disabledTitle=\"Give every output a unique name and a value, and every variable a unique name\"\n />\n )}\n </>\n );\n}\n\n// ── The standalone panel ──\n\ntype Props = ContentProps & { onClose: () => void };\n\nexport default function ModuleInterfacePanel({ onClose, ...content }: Props) {\n return (\n <Panel title=\"Module Interface\" onClose={onClose}>\n <ModuleInterfaceContent {...content} />\n </Panel>\n );\n}\n","// The actions a module's panel sends, each naming the module it edits by\n// `scope`: its declarations set whole by the settings actions, a resource's\n// arguments, meta-arguments, nested blocks and depends_on edited by the\n// actions the engine addresses to the resource's id. Every value is the\n// HCL text the panel shows, which the engine reads as the parse reads it.\n// Pure: a panel composes them into one `apply` batch, one undo entry.\nimport type { Action, InputDef } from '../../generated/service';\nimport { InputMode } from '../../generated/service';\nimport type { BlockConfig, ResourceConfig, SettingsConfig } from '../../types/render';\nimport type { OutputDefEntry, VariableDef } from './ModuleInterfacePanel';\n\nexport function setVariables(scope: string, variables: readonly VariableDef[]): Action {\n return {\n set_variables: {\n scope,\n variables: variables.map(\n (v): InputDef => ({\n name: v.name,\n type: v.type,\n required: v.required,\n description: v.description ?? '',\n default_value: v.default,\n validation: v.validation ?? [],\n ephemeral: v.ephemeral,\n nullable: v.nullable,\n sensitive: v.sensitive ?? false,\n }),\n ),\n },\n };\n}\n\nexport function setOutputs(scope: string, outputs: readonly OutputDefEntry[]): Action {\n return {\n set_exports: {\n scope,\n outputs: outputs.map((o) => ({ name: o.name, value: o.value })),\n output_defs: outputs.map((o) => ({\n name: o.name,\n type: '',\n description: o.description ?? '',\n sensitive: o.sensitive ?? false,\n depends_on: o.depends_on ?? [],\n })),\n },\n };\n}\n\nexport function setTerraform(scope: string, terraform: SettingsConfig['terraform']): Action {\n return {\n set_terraform: {\n scope,\n required_version: terraform.required_version,\n required_providers: terraform.required_providers.map((p) => ({\n name: p.name,\n source: p.source,\n version: p.version,\n configuration_aliases: p.configuration_aliases ?? [],\n })),\n },\n };\n}\n\nexport function setProviders(scope: string, providers: SettingsConfig['providers']): Action {\n return { set_providers: { scope, providers: providers.map((p) => ({ ...p })) } };\n}\n\nexport function setLocals(scope: string, locals: SettingsConfig['locals']): Action {\n return { set_locals: { scope, locals: locals.map((l) => ({ ...l })) } };\n}\n\nexport function setDirectives(scope: string, blocks: readonly BlockConfig[]): Action {\n return { set_directives: { scope, blocks: [...blocks] } };\n}\n\nexport function addResource(\n scope: string,\n kind: ResourceConfig['kind'],\n type: string,\n name: string,\n): Action {\n return { add_resource: { scope, kind, type, name } };\n}\n\nexport function removeResource(scope: string, id: string): Action {\n return { delete_instance: { scope, instance_id: id } };\n}\n\n// resourceActions is the batch that takes a resource from `before` to\n// `after`, the edits a panel made: an argument set or changed is its text\n// as an expression input, one removed is disconnected, and the\n// meta-arguments, nested blocks and depends_on are each set when they\n// changed. Nothing the panel left as it was is sent, so an unchanged\n// construct is never rewritten.\nexport function resourceActions(\n scope: string,\n before: ResourceConfig,\n after: ResourceConfig,\n): Action[] {\n const actions: Action[] = [];\n const was = new Map(before.arguments.map((a) => [a.name, a.value]));\n const now = new Map(after.arguments.map((a) => [a.name, a.value]));\n for (const [name, value] of now) {\n if (was.get(name) === value) continue;\n actions.push({\n update_input: {\n scope,\n instance_id: before.id,\n input_name: name,\n mode: InputMode.INPUT_MODE_EXPRESSION,\n value: undefined,\n variable: '',\n expression: value,\n },\n });\n }\n for (const name of was.keys()) {\n if (!now.has(name)) {\n actions.push({ disconnect: { scope, target: before.id, input_name: name } });\n }\n }\n if (\n before.count !== after.count ||\n before.for_each !== after.for_each ||\n before.provider !== after.provider\n ) {\n actions.push({\n set_meta_arguments: {\n scope,\n instance_id: before.id,\n count: after.count,\n for_each: after.for_each,\n provider: after.provider,\n },\n });\n }\n if (JSON.stringify(before.blocks) !== JSON.stringify(after.blocks)) {\n actions.push({ set_blocks: { scope, instance_id: before.id, blocks: after.blocks } });\n }\n if (JSON.stringify(before.depends_on) !== JSON.stringify(after.depends_on)) {\n actions.push({\n set_depends_on: { scope, instance_id: before.id, depends_on: after.depends_on },\n });\n }\n return actions;\n}\n","import { Button, IconButton, Input, Panel } from '@lace-cloud/ui';\nimport { useCallback, useState } from 'react';\nimport { useUpdateState } from '../../hooks/useUpdateState';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { BlockConfig, SettingsConfig } from '../../types/render';\nimport { CanvasIcon } from '../icons';\nimport UpdateButton from '../UpdateButton';\nimport BlockEditor from './BlockEditor';\nimport './panels-shared.css';\n\n// A provider configuration is edited whole: its settings, each value as\n// the HCL text the render writes for it, and its nested blocks\n// (default_tags, assume_role, …) through the one block editor.\n\n// ── Types derived from SettingsConfig ──\n\ntype ProviderEntry = SettingsConfig['providers'][number];\n\n// ── Local editing state ──\n\n// Stable per-row id, used as React key. Generated when rows are\n// created (toRows / addProvider / addConfigEntry), survives edits +\n// reorders. NOT persisted — fromRows discards it.\ntype ProviderRow = {\n id: string;\n name: string;\n alias: string;\n configEntries: Array<{ id: string; key: string; value: string }>;\n blocks: BlockConfig[];\n};\n\nfunction toRows(providers: ProviderEntry[] | undefined): ProviderRow[] {\n if (!providers || providers.length === 0) return [];\n return providers.map((p) => ({\n id: crypto.randomUUID(),\n name: p.name,\n alias: p.alias ?? '',\n configEntries: Object.entries(p.config).map(([key, value]) => ({\n id: crypto.randomUUID(),\n key,\n value: String(value),\n })),\n blocks: p.blocks,\n }));\n}\n\nfunction fromRows(rows: ProviderRow[]): ProviderEntry[] {\n return rows\n .filter((r) => r.name.trim())\n .map((r) => {\n const config: Record<string, string> = {};\n for (const c of r.configEntries) {\n if (c.key.trim()) {\n config[c.key.trim()] = c.value;\n }\n }\n return { name: r.name.trim(), alias: r.alias.trim() || '', config, blocks: r.blocks };\n });\n}\n\n// ── Content-only component (used by ModuleDetails) ──\n\ntype ContentProps = {\n providers: ProviderEntry[] | undefined;\n onSave: (providers: ProviderEntry[]) => void | Promise<void>;\n};\n\nexport function ProvidersContent({ providers, onSave }: ContentProps) {\n const { editable } = useCanvas();\n const [rows, setRows] = useState<ProviderRow[]>(() => toRows(providers));\n\n const addProvider = useCallback(() => {\n setRows((prev) => [\n ...prev,\n {\n id: crypto.randomUUID(),\n name: '',\n alias: '',\n configEntries: [{ id: crypto.randomUUID(), key: '', value: '' }],\n blocks: [],\n },\n ]);\n }, []);\n\n const removeProvider = useCallback((index: number) => {\n setRows((prev) => prev.filter((_, i) => i !== index));\n }, []);\n\n const updateField = useCallback((index: number, field: 'name' | 'alias', value: string) => {\n setRows((prev) => prev.map((r, i) => (i === index ? { ...r, [field]: value } : r)));\n }, []);\n\n const updateBlocks = useCallback((index: number, blocks: BlockConfig[]) => {\n setRows((prev) => prev.map((r, i) => (i === index ? { ...r, blocks } : r)));\n }, []);\n\n const addConfigEntry = useCallback((providerIndex: number) => {\n setRows((prev) =>\n prev.map((r, i) =>\n i === providerIndex\n ? {\n ...r,\n configEntries: [...r.configEntries, { id: crypto.randomUUID(), key: '', value: '' }],\n }\n : r,\n ),\n );\n }, []);\n\n const removeConfigEntry = useCallback((providerIndex: number, entryIndex: number) => {\n setRows((prev) =>\n prev.map((r, i) =>\n i === providerIndex\n ? { ...r, configEntries: r.configEntries.filter((_, ei) => ei !== entryIndex) }\n : r,\n ),\n );\n }, []);\n\n const updateConfigEntry = useCallback(\n (providerIndex: number, entryIndex: number, field: 'key' | 'value', value: string) => {\n setRows((prev) =>\n prev.map((r, i) =>\n i === providerIndex\n ? {\n ...r,\n configEntries: r.configEntries.map((c, ei) =>\n ei === entryIndex ? { ...c, [field]: value } : c,\n ),\n }\n : r,\n ),\n );\n },\n [],\n );\n\n const { status: updateStatus, handleUpdate } = useUpdateState(\n useCallback(async () => {\n await onSave(fromRows(rows));\n }, [onSave, rows]),\n );\n\n return (\n <>\n {rows.map((row, pi) => (\n <div key={row.id} className=\"lace-panel-row-card lace-panel-row-card--with-footer\">\n <div className=\"lace-panel-row-actions\">\n <Input\n value={row.name}\n onChange={(e) => updateField(pi, 'name', e.target.value)}\n placeholder=\"Provider name (e.g. aws)\"\n fullWidth\n readOnly={!editable}\n />\n <Input\n value={row.alias}\n onChange={(e) => updateField(pi, 'alias', e.target.value)}\n placeholder=\"Alias (optional)\"\n fullWidth\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label=\"Remove provider\"\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => removeProvider(pi)}\n />\n )}\n </div>\n\n <div className=\"lace-panel-row-sublabel\">Config</div>\n {row.configEntries.map((entry, ei) => (\n <div key={entry.id} className=\"lace-panel-row-actions\">\n <Input\n value={entry.key}\n onChange={(e) => updateConfigEntry(pi, ei, 'key', e.target.value)}\n placeholder=\"Key\"\n fullWidth\n readOnly={!editable}\n />\n <Input\n value={entry.value}\n onChange={(e) => updateConfigEntry(pi, ei, 'value', e.target.value)}\n placeholder=\"Value\"\n fullWidth\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label=\"Remove config key\"\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => removeConfigEntry(pi, ei)}\n />\n )}\n </div>\n ))}\n {editable && (\n <Button variant=\"secondary\" size=\"sm\" onClick={() => addConfigEntry(pi)}>\n + Add config key\n </Button>\n )}\n\n {(row.blocks.length > 0 || editable) && (\n <>\n <div className=\"lace-panel-row-sublabel\">Nested blocks</div>\n <BlockEditor\n blocks={row.blocks}\n editable={editable}\n onChange={(blocks) => updateBlocks(pi, blocks)}\n />\n </>\n )}\n </div>\n ))}\n\n {editable && (\n <>\n <Button variant=\"secondary\" size=\"sm\" onClick={addProvider}>\n + Add provider\n </Button>\n\n <UpdateButton status={updateStatus} label=\"Update providers\" onClick={handleUpdate} />\n </>\n )}\n </>\n );\n}\n\n// ── The standalone panel ──\n\ntype Props = {\n providers: ProviderEntry[] | undefined;\n onSave: (providers: ProviderEntry[]) => void | Promise<void>;\n onClose: () => void;\n};\n\nexport default function ProvidersPanel({ providers, onSave, onClose }: Props) {\n return (\n <Panel title=\"Providers\" onClose={onClose}>\n <ProvidersContent providers={providers} onSave={onSave} />\n </Panel>\n );\n}\n","// A module's resources and data sources, each one card: its kind, type and\n// name, its meta-arguments, its arguments, its nested blocks and what it\n// depends on, every value the HCL text the render writes for it. A\n// resource is one block however many instances its count or for_each\n// makes. Editable, a card's Update sends what the developer changed as one\n// batch, and a resource or data source is added by kind, type and name and\n// removed whole. A data source may be added to any module; a managed\n// resource only where lace shape lets the module hold one.\nimport { Badge, Button, IconButton, Input, Select } from '@lace-cloud/ui';\nimport { useCallback, useState } from 'react';\nimport { useUpdateState } from '../../hooks/useUpdateState';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { ResourceConfig } from '../../types/render';\nimport { findDuplicateIndices } from '../../utils/duplicates';\nimport Identifier from '../Identifier';\nimport { CanvasIcon } from '../icons';\nimport UpdateButton from '../UpdateButton';\nimport BlockEditor from './BlockEditor';\nimport './panels-shared.css';\n\ntype ContentProps = {\n resources: ResourceConfig[];\n // What a depends_on in the module names (`SettingsConfig.dependency_options`).\n dependencyOptions: string[];\n // Whether the module may hold a managed resource\n // (`SettingsConfig.holds_managed_resources`): the add row offers one only\n // then, and a data source always.\n managed: boolean;\n onUpdate: (before: ResourceConfig, after: ResourceConfig) => Promise<void>;\n onRemove: (id: string) => Promise<void>;\n onAdd: (kind: ResourceConfig['kind'], type: string, name: string) => Promise<void>;\n};\n\nexport function ResourcesContent({\n resources,\n dependencyOptions,\n managed,\n onUpdate,\n onRemove,\n onAdd,\n}: ContentProps) {\n const { editable } = useCanvas();\n return (\n <>\n {resources.length === 0 && (\n <div className=\"lace-panel-hint\">No resources or data sources.</div>\n )}\n {resources.map((resource) => (\n <ResourceCard\n // A new frame that changes the resource re-seeds the card.\n key={JSON.stringify(resource)}\n resource={resource}\n dependencyOptions={dependencyOptions.filter(\n (dep) => dep !== resource.id.replace(/^resource\\./, ''),\n )}\n editable={editable}\n onUpdate={onUpdate}\n onRemove={onRemove}\n />\n ))}\n {editable && <NewResourceRow managed={managed} onAdd={onAdd} />}\n </>\n );\n}\n\nconst MANAGED_OPTION = { value: 'resource', label: 'Resource' };\nconst DATA_OPTION = { value: 'data', label: 'Data source' };\n\nfunction NewResourceRow({\n managed,\n onAdd,\n}: {\n managed: ContentProps['managed'];\n onAdd: ContentProps['onAdd'];\n}) {\n const options = managed ? [MANAGED_OPTION, DATA_OPTION] : [DATA_OPTION];\n const [chosen, setChosen] = useState<ResourceConfig['kind']>('resource');\n const kind = managed ? chosen : 'data';\n const [type, setType] = useState('');\n const [name, setName] = useState('');\n return (\n <div className=\"lace-panel-row-card\">\n <div className=\"lace-panel-subsection-label\">Add a resource</div>\n <div className=\"lace-panel-row-actions\">\n <Select\n aria-label=\"New resource kind\"\n options={options}\n value={kind}\n onChange={(e) => setChosen(e.target.value === 'data' ? 'data' : 'resource')}\n />\n <Input\n value={type}\n onChange={(e) => setType(e.target.value)}\n placeholder=\"Type (e.g. aws_s3_bucket)\"\n aria-label=\"New resource type\"\n mono\n />\n <Input\n value={name}\n onChange={(e) => setName(e.target.value)}\n placeholder=\"Name\"\n aria-label=\"New resource name\"\n mono\n />\n <Button\n variant=\"secondary\"\n size=\"sm\"\n disabled={!type.trim() || !name.trim()}\n onClick={async () => {\n await onAdd(kind, type.trim(), name.trim());\n setType('');\n setName('');\n }}\n >\n + Add\n </Button>\n </div>\n </div>\n );\n}\n\ntype CardProps = {\n resource: ResourceConfig;\n dependencyOptions: string[];\n editable: boolean;\n onUpdate: ContentProps['onUpdate'];\n onRemove: ContentProps['onRemove'];\n};\n\nfunction ResourceCard({ resource, dependencyOptions, editable, onUpdate, onRemove }: CardProps) {\n const [draft, setDraft] = useState<ResourceConfig>(resource);\n const set = useCallback(\n <K extends keyof ResourceConfig>(field: K, value: ResourceConfig[K]) =>\n setDraft((prev) => ({ ...prev, [field]: value })),\n [],\n );\n const setArgument = (index: number, field: 'name' | 'value', value: string) =>\n set(\n 'arguments',\n draft.arguments.map((a, i) => (i === index ? { ...a, [field]: value } : a)),\n );\n\n const argumentDupes = findDuplicateIndices(draft.arguments, (a) => a.name);\n const hasErrors = argumentDupes.size > 0 || draft.arguments.some((a) => !a.name.trim());\n\n const { status, handleUpdate } = useUpdateState(\n useCallback(async () => {\n if (hasErrors) return;\n await onUpdate(resource, draft);\n }, [onUpdate, resource, draft, hasErrors]),\n );\n\n const metaArguments: Array<{ field: 'count' | 'for_each' | 'provider'; placeholder: string }> = [\n { field: 'count', placeholder: 'e.g. 2 or var.instances' },\n { field: 'for_each', placeholder: 'e.g. var.names' },\n { field: 'provider', placeholder: 'e.g. aws.west' },\n ];\n\n return (\n <div className=\"lace-panel-row-card lace-panel-row-card--with-footer\">\n <div className=\"lace-panel-row-actions\">\n <Badge variant={resource.kind === 'data' ? 'info' : 'neutral'}>\n {resource.kind === 'data' ? 'data' : 'resource'}\n </Badge>\n <Identifier\n className=\"lace-panel-row-card__name\"\n text={`${resource.type}.${resource.name}`}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label={`Remove ${resource.type}.${resource.name}`}\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => onRemove(resource.id)}\n />\n )}\n </div>\n\n {metaArguments.map(({ field, placeholder }) =>\n draft[field] || editable ? (\n <div key={field} className=\"lace-panel-row-actions\">\n <Input\n label={field}\n value={draft[field]}\n onChange={(e) => set(field, e.target.value)}\n placeholder={placeholder}\n fullWidth\n mono\n readOnly={!editable}\n />\n </div>\n ) : null,\n )}\n\n <div className=\"lace-panel-row-sublabel\">Arguments</div>\n {draft.arguments.map((argument, i) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: argument rows are positional while edited\n <div key={i} className=\"lace-panel-row-actions\">\n <Input\n value={argument.name}\n onChange={(e) => setArgument(i, 'name', e.target.value)}\n placeholder=\"Argument\"\n aria-label=\"Argument name\"\n mono\n readOnly={!editable}\n error={argumentDupes.has(i)}\n />\n <Input\n value={argument.value}\n onChange={(e) => setArgument(i, 'value', e.target.value)}\n placeholder=\"Value\"\n aria-label={`${argument.name || 'Argument'} value`}\n mono\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label={`Remove ${argument.name || 'the argument'}`}\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() =>\n set(\n 'arguments',\n draft.arguments.filter((_, j) => j !== i),\n )\n }\n />\n )}\n </div>\n ))}\n {editable && (\n <Button\n variant=\"secondary\"\n size=\"sm\"\n onClick={() => set('arguments', [...draft.arguments, { name: '', value: '' }])}\n >\n + Add argument\n </Button>\n )}\n\n {(draft.blocks.length > 0 || editable) && (\n <>\n <div className=\"lace-panel-row-sublabel\">Nested blocks</div>\n <BlockEditor\n blocks={draft.blocks}\n editable={editable}\n onChange={(blocks) => set('blocks', blocks)}\n />\n </>\n )}\n\n {(draft.depends_on.length > 0 || (editable && dependencyOptions.length > 0)) && (\n <>\n <div className=\"lace-panel-row-sublabel\">Depends on</div>\n {!editable\n ? draft.depends_on.map((dep) => (\n <div key={dep} className=\"lace-panel-depends-item\">\n <Identifier text={dep} />\n </div>\n ))\n : dependencyOptions.map((dep) => (\n <label key={dep} className=\"lace-panel-checkbox-row\">\n <input\n type=\"checkbox\"\n checked={draft.depends_on.includes(dep)}\n onChange={(e) =>\n set(\n 'depends_on',\n e.target.checked\n ? [...draft.depends_on, dep]\n : draft.depends_on.filter((d) => d !== dep),\n )\n }\n />\n <Identifier text={dep} />\n </label>\n ))}\n </>\n )}\n\n {editable && (\n <UpdateButton\n status={status}\n label=\"Update resource\"\n onClick={handleUpdate}\n disabled={hasErrors}\n disabledTitle=\"Give every argument a unique name\"\n />\n )}\n </div>\n );\n}\n","import { Button, IconButton, Input, Panel } from '@lace-cloud/ui';\nimport { useCallback, useState } from 'react';\nimport { useUpdateState } from '../../hooks/useUpdateState';\nimport { useCanvas } from '../../state/canvas-context';\nimport type { SettingsConfig } from '../../types/render';\nimport { CanvasIcon } from '../icons';\nimport UpdateButton from '../UpdateButton';\nimport './panels-shared.css';\n\n// ── Types derived from SettingsConfig ──\n\ntype TerraformConfig = SettingsConfig['terraform'];\n\n// Stable per-row id, used as React key. NOT persisted.\ntype ProviderRequirementRow = {\n id: string;\n name: string;\n source: string;\n version: string;\n // The provider configurations the module takes from its callers\n // (`configuration_aliases = [aws.src, aws.dst]`), comma-separated.\n aliases: string;\n};\n\n// ── Content-only component (used by ModuleDetails) ──\n\ntype ContentProps = {\n terraform: TerraformConfig | undefined;\n onSave: (terraform: TerraformConfig) => void | Promise<void>;\n};\n\nexport function TerraformConfigContent({ terraform, onSave }: ContentProps) {\n const { editable } = useCanvas();\n const [requiredVersion, setRequiredVersion] = useState(terraform?.required_version ?? '');\n const [providers, setProviders] = useState<ProviderRequirementRow[]>(() => {\n if (!terraform?.required_providers) return [];\n return terraform.required_providers.map((req) => ({\n id: crypto.randomUUID(),\n name: req.name,\n source: req.source ?? '',\n version: req.version ?? '',\n aliases: (req.configuration_aliases ?? []).join(', '),\n }));\n });\n\n const addProvider = useCallback(() => {\n setProviders((prev) => [\n ...prev,\n { id: crypto.randomUUID(), name: '', source: '', version: '', aliases: '' },\n ]);\n }, []);\n\n const removeProvider = useCallback((index: number) => {\n setProviders((prev) => prev.filter((_, i) => i !== index));\n }, []);\n\n const updateProvider = useCallback(\n (index: number, field: 'name' | 'source' | 'version' | 'aliases', value: string) => {\n setProviders((prev) => prev.map((p, i) => (i === index ? { ...p, [field]: value } : p)));\n },\n [],\n );\n\n const { status: updateStatus, handleUpdate } = useUpdateState(\n useCallback(async () => {\n const block: TerraformConfig = {\n required_version: requiredVersion.trim() || '',\n required_providers: providers\n .filter((p) => p.name.trim())\n .map((p) => ({\n name: p.name.trim(),\n source: p.source.trim(),\n version: p.version.trim(),\n configuration_aliases: p.aliases\n .split(',')\n .map((alias) => alias.trim())\n .filter((alias) => alias !== ''),\n })),\n };\n await onSave(block);\n }, [onSave, requiredVersion, providers]),\n );\n\n return (\n <>\n <h4 className=\"lace-panel-section-title\">Required Version</h4>\n <div className=\"lace-panel-field\">\n <Input\n value={requiredVersion}\n onChange={(e) => setRequiredVersion(e.target.value)}\n placeholder=\">= 1.5\"\n fullWidth\n readOnly={!editable}\n />\n </div>\n\n <h4 className=\"lace-panel-section-title\">Required Providers</h4>\n {providers.map((p, i) => (\n <div key={p.id} className=\"lace-panel-row-card lace-panel-row-card--with-footer\">\n <div className=\"lace-panel-row-actions\">\n <Input\n value={p.name}\n onChange={(e) => updateProvider(i, 'name', e.target.value)}\n placeholder=\"Name (e.g. aws)\"\n fullWidth\n readOnly={!editable}\n />\n {editable && (\n <IconButton\n icon={<CanvasIcon name=\"close\" />}\n aria-label=\"Remove provider\"\n size=\"md\"\n tooltipPlacement=\"bottom-end\"\n onClick={() => removeProvider(i)}\n />\n )}\n </div>\n <div className=\"lace-panel-row-actions\">\n <Input\n value={p.source}\n onChange={(e) => updateProvider(i, 'source', e.target.value)}\n placeholder=\"Source (e.g. hashicorp/aws)\"\n fullWidth\n readOnly={!editable}\n />\n </div>\n <div className=\"lace-panel-row-actions\">\n <Input\n value={p.version}\n onChange={(e) => updateProvider(i, 'version', e.target.value)}\n placeholder=\"Version (e.g. ~> 5.0)\"\n fullWidth\n readOnly={!editable}\n />\n </div>\n {(p.aliases || editable) && (\n <div className=\"lace-panel-row-actions\">\n <Input\n value={p.aliases}\n onChange={(e) => updateProvider(i, 'aliases', e.target.value)}\n aria-label={`${p.name || 'provider'} configuration_aliases`}\n placeholder=\"configuration_aliases (e.g. aws.src, aws.dst)\"\n fullWidth\n mono\n readOnly={!editable}\n />\n </div>\n )}\n </div>\n ))}\n {editable && (\n <Button variant=\"secondary\" size=\"sm\" onClick={addProvider}>\n + Add provider\n </Button>\n )}\n\n <h4 className=\"lace-panel-section-title\">Backend</h4>\n <div className=\"lace-panel-hint\">\n Terraform state is managed by Lace Cloud. The HTTP backend is configured automatically\n during generation.\n </div>\n\n {editable && (\n <UpdateButton status={updateStatus} label=\"Update terraform block\" onClick={handleUpdate} />\n )}\n </>\n );\n}\n\n// ── The standalone panel ──\n\ntype Props = {\n terraform: TerraformConfig | undefined;\n onSave: (terraform: TerraformConfig) => void | Promise<void>;\n onClose: () => void;\n};\n\nexport default function TerraformConfigPanel({ terraform, onSave, onClose }: Props) {\n return (\n <Panel title=\"Terraform Configuration\" onClose={onClose}>\n <TerraformConfigContent terraform={terraform} onSave={onSave} />\n </Panel>\n );\n}\n","// The source-refused banner: it shows whenever the engine refuses the\n// module's tf (`requiredContext: ['sourceRefused']`, the fact itself),\n// whatever ports the host supplies. Its opening states the lock or, when\n// the refusal's cause is lace shape (`needsConversion`), that the tree is\n// not in lace shape yet; its choices and buttons are the actions resolved\n// on its row (RowActionBanner): Convert, and any a host adds. The\n// diagnostics render once, through the DiagnosticsPanel's own\n// `ctx.diagnostics` (`diagnosticsOf`) — this banner never lists them a\n// second time.\nimport type { Panel, PanelProps } from '../../contributions';\nimport { keySatisfied } from '../../registry';\nimport { RowActionBanner } from './RowActionBanner';\n\nconst LOCKED =\n \"The canvas can't take this module's .tf, so editing, saving and generating are locked until it can; the Diagnostics tab says why.\";\nconst OUT_OF_LACE_SHAPE =\n 'This Terraform is not in lace shape yet, so the canvas shows it read-only.';\n\nexport function SourceRefusedBanner({ ctx }: PanelProps) {\n return (\n <RowActionBanner\n ctx={ctx}\n panelId=\"source-refused\"\n severity=\"error\"\n className=\"lace-source-refused-banner\"\n opening={keySatisfied(ctx, 'needsConversion') ? OUT_OF_LACE_SHAPE : LOCKED}\n />\n );\n}\n\nexport const sourceRefusedPanel: Panel = {\n id: 'source-refused',\n title: 'Source refused',\n slot: 'banner',\n requiredPorts: [],\n requiredContext: ['sourceRefused'],\n Component: SourceRefusedBanner,\n};\n\nexport default SourceRefusedBanner;\n","// The settings panel: a drawer panel wrapping\n// `components/panels/UnifiedSettingsPanel`, the entry's details, which\n// reads `editable`/`bundle`/`runner` straight off `useCanvas()` and gates\n// every section's Update control on `editable` itself. It resolves only\n// while the developer has it open (`requiredContext: ['settingsOpen']`,\n// App's own state carried on `ctx`), so a closed settings panel draws\n// nothing and opens no drawer; this file derives `onClose` from\n// `setSettingsOpen` (state/canvas-context.ts).\n//\n// `settingsToggle` is the toolbar's gear that opens and closes it — a\n// contribution like every other capability, not a button App hard-codes. It\n// needs no port: the entry's details are constructs the Bundle holds, which\n// every canvas shows (invariant bundle-shows-on-canvas), and a read-only\n// canvas shows them with no control. It names no toolbar group, so it sits\n// at the row's far end.\nimport { IconButton } from '@lace-cloud/ui';\nimport { createElement } from 'react';\nimport { CanvasIcon } from '../../components/icons';\nimport UnifiedSettingsPanelComponent from '../../components/panels/UnifiedSettingsPanel';\nimport type { Panel, PanelProps } from '../../contributions';\nimport { useCanvas } from '../../state/canvas-context';\n\nfunction SettingsPanel(_props: PanelProps) {\n const { setSettingsOpen } = useCanvas();\n return createElement(UnifiedSettingsPanelComponent, {\n onClose: () => setSettingsOpen(false),\n });\n}\n\nexport const settingsPanel: Panel = {\n id: 'settings',\n title: 'Settings',\n slot: 'drawer',\n requiredPorts: [],\n requiredContext: ['settingsOpen'],\n Component: SettingsPanel,\n};\n\n// A gear, pressed while the panel is open; a second press closes it. A\n// toggle: its name is Settings either way, and its tooltip that name alone.\nfunction SettingsToggle({ ctx }: PanelProps) {\n const { setSettingsOpen } = useCanvas();\n return createElement(IconButton, {\n icon: createElement(CanvasIcon, { name: 'settings' }),\n 'aria-label': 'Settings',\n size: 'md',\n tooltipPlacement: 'bottom-end',\n pressed: ctx.settingsOpen,\n onClick: () => setSettingsOpen(!ctx.settingsOpen),\n });\n}\n\nexport const settingsToggle: Panel = {\n id: 'settings-toggle',\n title: 'Settings',\n slot: 'toolbar',\n requiredPorts: [],\n Component: SettingsToggle,\n};\n\nexport default SettingsPanel;\n","// The settings panel: the entry's details (`ModuleDetails`), the module\n// the canvas's top scope is. A called module's details are its call's\n// panel's (ModuleConfigPanel).\nimport { Panel } from '@lace-cloud/ui';\nimport { useCanvas } from '../../state/canvas-context';\nimport ModuleDetails from './ModuleDetails';\nimport './panels-shared.css';\n\ntype Props = {\n onClose: () => void;\n};\n\nexport default function UnifiedSettingsPanel({ onClose }: Props) {\n const { bundle } = useCanvas();\n return (\n <Panel title=\"Settings\" flush onClose={onClose}>\n <ModuleDetails key={bundle.entry} moduleKey={bundle.entry} open={['Interface']} />\n </Panel>\n );\n}\n","// CORE_CONTRIBUTIONS: what the canvas draws, which is module authoring,\n// registered through the same Contributions surface a host extension uses —\n// no core feature bypasses the registry. `App` merges this set with\n// whatever a host passes: the conflict and source-refused banners, the\n// Unsaved/Not-generated toolbar chips, the diagnostics list, the module\n// and edge inspectors and the settings panel in the drawer, Validate and Convert, every\n// editor action, and the describe overlay (node badges for the stack the\n// host supplies), each gated only by its own declared ports/context like\n// any other contribution.\n//\n// The stack and run commands (`STACK_COMMAND_ACTIONS`, core/actions.ts) are\n// not in this set: the package carries their bindings, the runner and the\n// reducers over their output, and a host draws them in its own UI.\nimport type { Contributions } from '../contributions';\nimport { MODULE_COMMAND_ACTIONS } from './actions';\nimport { CORE_EDITOR_ACTIONS } from './editor-actions';\nimport { describeOverlay } from './overlays/describe';\nimport { conflictPanel } from './panels/ConflictBanner';\nimport { diagnosticsPanel } from './panels/DiagnosticsPanel';\nimport { disconnectEdge, edgeInspectorPanel } from './panels/edge-inspector';\nimport { ungeneratedMarker, unsavedMarker } from './panels/Markers';\nimport { moduleConfigPanel } from './panels/module-config';\nimport { sourceRefusedPanel } from './panels/SourceRefusedBanner';\nimport { settingsPanel, settingsToggle } from './panels/settings';\n\nexport const CORE_CONTRIBUTIONS: Contributions = {\n overlays: [describeOverlay],\n panels: [\n conflictPanel,\n sourceRefusedPanel,\n unsavedMarker,\n ungeneratedMarker,\n diagnosticsPanel,\n // The drawer shows the first of these that resolves: Settings while it\n // is open, else the inspector of what is selected.\n settingsPanel,\n moduleConfigPanel,\n edgeInspectorPanel,\n settingsToggle,\n ],\n actions: [...MODULE_COMMAND_ACTIONS, ...CORE_EDITOR_ACTIONS, disconnectEdge],\n};\n","// snapshotSource is the read-only `SourcePort` a host without a live engine\n// mounts — portal's control-plane dashboards, any inspection-only view.\n// It fetches one Bundle proto snapshot and never changes: `unsaved`,\n// `ungenerated` and `conflict` are always false/null, `sourceRefused` and\n// `generating` are always false, `diagnostics` is always empty — a RunSnapshot has no\n// live validator, and the run's own certification already vouched for it —\n// and `treeHash` is always '': no session stands behind it to observe a\n// tree or publish a command's result.\n// No `editor`/`commands` port — a host that omits them renders read-only by\n// the absence of those ports, never a flag.\nimport { Bundle as BundleCodec } from '../generated/state';\nimport type { CanvasSource, SourcePort } from '../ports';\n\nexport type SnapshotSourceInput = {\n bundleUrl: string;\n /** Fetch impl override — used by tests. Defaults to globalThis.fetch. */\n fetch?: typeof fetch;\n /**\n * Extra request headers sent with the bundle GET. Same-origin portal\n * fetches carry the session cookie via `credentials: include`, but the\n * API still resolves org/team scope from `x-org-slug`/`x-team-slug`\n * headers — the caller must supply them here or the read 400s. Embed\n * routes authenticate via the token in the URL and omit this.\n */\n headers?: Record<string, string>;\n};\n\n/**\n * The error of the `failed` end a snapshot source reports when the server\n * answered its fetch with a failure: `status` is that answer's HTTP status, as\n * data, so a host words the failure by it and never by the message. A fetch no\n * response answered ends with the transport's own error.\n */\nexport class SnapshotFetchError extends Error {\n constructor(readonly status: number) {\n super(`snapshotSource: failed to fetch bundle (status ${status})`);\n this.name = 'SnapshotFetchError';\n }\n}\n\nexport function snapshotSource(input: SnapshotSourceInput): SourcePort {\n const fetchImpl = input.fetch ?? globalThis.fetch.bind(globalThis);\n let cached: CanvasSource | null = null;\n let loadPromise: Promise<CanvasSource> | null = null;\n\n async function load(): Promise<CanvasSource> {\n if (cached) return cached;\n const res = await fetchImpl(input.bundleUrl, {\n method: 'GET',\n headers: { accept: 'application/octet-stream', ...input.headers },\n credentials: 'include',\n });\n if (!res.ok) throw new SnapshotFetchError(res.status);\n const bytes = new Uint8Array(await res.arrayBuffer());\n const source: CanvasSource = {\n bundle: BundleCodec.decode(bytes),\n canUndo: false,\n canRedo: false,\n unsaved: false,\n ungenerated: false,\n conflict: null,\n sourceRefused: false,\n generating: false,\n diagnostics: [],\n treeHash: '',\n };\n cached = source;\n return source;\n }\n\n return {\n subscribe(on, onEnd) {\n let cancelled = false;\n if (cached) {\n const source = cached;\n queueMicrotask(() => {\n if (!cancelled) on(source);\n });\n } else {\n loadPromise ??= load();\n void loadPromise\n .then((source) => {\n if (!cancelled) on(source);\n })\n .catch((err: unknown) => {\n if (cancelled) return;\n // The one fetch is this source's whole stream: its failure is\n // the stream's end, and no session stands behind a snapshot.\n onEnd({ kind: 'failed', error: err instanceof Error ? err : new Error(String(err)) });\n });\n }\n return () => {\n cancelled = true;\n };\n },\n };\n}\n"],"mapp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Q,IAAI,WAAW,MAAM,IAAI,YAAY,CAAC;AACpD,UAAM,SAAuB;AAAA,MAC3B,QAAQ,OAAY,OAAO,KAAK;AAAA,MAChC,SAAS;AAAA,MACT,SAAS;AAAA,MACT,SAAS;AAAA,MACT,aAAa;AAAA,MACb,UAAU;AAAA,MACV,eAAe;AAAA,MACf,YAAY;AAAA,MACZ,aAAa,CAAC;AAAA,MACd,UAAU;AAAA,IACZ;AACA,aAAS;AACT,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,UAAU,IAAI,OAAO;AACnB,UAAI,YAAY;AAChB,UAAI,QAAQ;AACV,cAAM,SAAS;AACf,uBAAe,MAAM;AACnB,cAAI,CAAC,UAAW,IAAG,MAAM;AAAA,QAC3B,CAAC;AAAA,MACH,OAAO;AACL,sCAAgB,KAAK;AACrB,aAAK,YACF,KAAK,CAAC,WAAW;AAChB,cAAI,CAAC,UAAW,IAAG,MAAM;AAAA,QAC3B,CAAC,EACA,MAAM,CAAC,QAAiB;AACvB,cAAI,UAAW;AAGf,gBAAM,EAAE,MAAM,UAAU,OAAO,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC,EAAE,CAAC;AAAA,QACtF,CAAC;AAAA,MACL;AACA,aAAO,MAAM;AACX,oBAAY;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF;","names":["projectCanvasView","Fragment","useCallback","useEffect","useLayoutEffect","useMemo","useRef","useState","drawnRect","extentOf","instanceAddress","localIn","useReactFlow","useCallback","useEffect","useMemo","useRef","useState","jsx","Fragment","useState","Fragment","jsx","jsxs","useState","at","jsx","useStore","clearanceY","railX1","railX2","jsx","useStore","useCallback","useEffect","useRef","useState","localIn","splitPath","group","localIn","cut","splitPath","keyOf","group","instanceAddress","useRef","useEffect","useState","useRef","instanceAddress","jsx","jsxs","useState","useRef","useEffect","useCallback","instanceAddress","NODE_ROW_HEIGHT","Handle","Position","useStore","useCallback","useEffect","useRef","useState","createContext","useContext","useRef","jsx","Fragment","jsx","jsxs","NODE_ROW_HEIGHT","Handle","Position","useStore","useState","useRef","useEffect","useCallback","instanceAddress","jsx","useEffect","useEffect","useCallback","useState","useMemo","useMemo","group","useCallback","useEffect","useRef","useState","jsx","jsxs","useReactFlow","useEffect","useRef","drawnRect","extentOf","useMemo","useState","useCallback","localIn","instanceAddress","useCallback","useLayoutEffect","useRef","useState","jsx","jsxs","useRef","useState","useLayoutEffect","useCallback","jsx","jsxs","IconButton","jsx","jsxs","disabledReason","IconButton","useState","jsx","jsxs","useState","useMemo","useEffect","useMemo","useRef","useState","createContext","useContext","useMemo","jsx","useState","useRef","useEffect","useMemo","args","EMPTY_DECORATIONS","useMemo","Button","jsx","jsxs","jsx","Button","jsx","Button","Fragment","jsx","jsxs","jsx","jsxs","Button","instanceAddress","Button","jsx","jsxs","Button","instanceAddress","EdgeInspectorPanel","jsx","createElement","instanceAddress","Button","IconButton","Input","Panel","Textarea","useCallback","useEffect","useMemo","useState","useCallback","useEffect","useRef","useState","useState","jsx","jsxs","useState","Button","jsx","Input","useMemo","useState","Button","IconButton","useState","Fragment","jsx","jsxs","Button","useState","IconButton","Button","IconButton","Input","Panel","useCallback","useState","Fragment","jsx","jsxs","useState","useCallback","Input","IconButton","Button","Panel","Button","IconButton","Input","Panel","Textarea","useCallback","useState","Fragment","jsx","jsxs","setVariables","useState","setOutputs","useCallback","Input","IconButton","Textarea","Button","Panel","Button","IconButton","Input","Panel","useCallback","useState","Fragment","jsx","jsxs","toRows","fromRows","useState","useCallback","Input","IconButton","Button","Panel","Badge","Button","IconButton","Input","Select","useCallback","useState","Fragment","jsx","jsxs","useState","Select","Input","Button","useCallback","Badge","IconButton","Button","IconButton","Input","Panel","useCallback","useState","Fragment","jsx","jsxs","useState","setProviders","useCallback","Input","IconButton","Button","Panel","Fragment","jsx","jsxs","useMemo","useState","Input","Fragment","jsx","jsxs","useMemo","useState","useCallback","useEffect","instanceAddress","Input","IconButton","Textarea","Panel","Button","ModuleConfigPanel","createElement","jsx","IconButton","createElement","Panel","jsx","Panel","createElement","IconButton","jsx","jsxs","useRef","useCallback","useEffect","useState","next","useMemo","session","useLayoutEffect","Fragment"]}