configure mcp, refactors

This commit is contained in:
2026-03-06 20:43:43 +01:00
parent b526f99982
commit 7b08db2791
7 changed files with 1023 additions and 210 deletions

View File

@@ -0,0 +1,88 @@
import type { ComponentProps } from "react";
import { cn } from "@/lib/utils";
export function BaseNode({ className, ...props }: ComponentProps<"div">) {
return (
<div
className={cn(
"bg-card text-card-foreground relative rounded-md border",
"hover:ring-1",
// React Flow displays node elements inside of a `NodeWrapper` component,
// which compiles down to a div with the class `react-flow__node`.
// When a node is selected, the class `selected` is added to the
// `react-flow__node` element. This allows us to style the node when it
// is selected, using Tailwind's `&` selector.
"[.react-flow\\_\\_node.selected_&]:border-muted-foreground",
"[.react-flow\\_\\_node.selected_&]:shadow-lg",
className,
)}
tabIndex={0}
{...props}
/>
);
}
/**
* A container for a consistent header layout intended to be used inside the
* `<BaseNode />` component.
*/
export function BaseNodeHeader({
className,
...props
}: ComponentProps<"header">) {
return (
<header
{...props}
className={cn(
"mx-0 my-0 -mb-1 flex flex-row items-center justify-between gap-2 px-3 py-2",
// Remove or modify these classes if you modify the padding in the
// `<BaseNode />` component.
className,
)}
/>
);
}
/**
* The title text for the node. To maintain a native application feel, the title
* text is not selectable.
*/
export function BaseNodeHeaderTitle({
className,
...props
}: ComponentProps<"h3">) {
return (
<h3
data-slot="base-node-title"
className={cn("user-select-none flex-1 font-semibold", className)}
{...props}
/>
);
}
export function BaseNodeContent({
className,
...props
}: ComponentProps<"div">) {
return (
<div
data-slot="base-node-content"
className={cn("flex flex-col gap-y-2 p-3", className)}
{...props}
/>
);
}
export function BaseNodeFooter({ className, ...props }: ComponentProps<"div">) {
return (
<div
data-slot="base-node-footer"
className={cn(
"flex flex-col items-center gap-y-2 border-t px-3 pt-2 pb-3",
className,
)}
{...props}
/>
);
}

View File

@@ -0,0 +1,149 @@
import React, { memo, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
import { Handle, Position } from 'reactflow'
import Editor, { loader } from '@monaco-editor/react'
import FlowContext from '../../lib/flowContext'
import {
BaseNode,
BaseNodeContent,
BaseNodeFooter,
BaseNodeHeader,
BaseNodeHeaderTitle,
} from './BaseNode'
import { Pencil } from 'lucide-react'
// Ensure Monaco can load its web workers under Vite by pointing to a CDN
loader.config({ paths: { vs: 'https://unpkg.com/monaco-editor@latest/min/vs' } })
type Props = {
id: string
data: any
}
export const ConfigNode = memo(function ConfigNode({ id, data }: Props) {
const [value, setValue] = useState<string>(data?.yaml ?? '# Enter YAML here\n')
const ctx = useContext(FlowContext)
const setNodes = ctx?.setNodes
const storedYaml = ctx?.nodes?.find((n: any) => n.id === id)?.data?.yaml ?? ''
const editorRef = useRef<any>(null)
const monacoRef = useRef<any>(null)
const incomingEdges = ctx?.edges?.filter((e: any) => e.target === id) ?? []
const incomingIds = incomingEdges.map((e: any) => e.source).sort()
const connectedConfigNodes = (ctx?.nodes ?? []).filter((n: any) => incomingIds.includes(n.id) && n.type === 'config')
useEffect(() => {
if (setNodes) {
setNodes((nds: any[]) => nds.map((n) => (n.id === id ? { ...n, data: { ...n.data, yaml: value } } : n)))
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const onChange = useCallback(
(val?: string) => {
const v = val ?? ''
setValue(v)
// eslint-disable-next-line no-console
console.debug('ConfigNode:onChange', id, v.substring(0, 60))
if (setNodes) {
setNodes((nds: any[]) => nds.map((n) => (n.id === id ? { ...n, data: { ...n.data, yaml: v } } : n)))
}
},
[id, setNodes]
)
const handleEditorMount = useCallback((editor: any, monaco: any) => {
editorRef.current = editor
monacoRef.current = monaco
}, [])
const insertIncludeFromNode = useCallback(
(sourceNode: any) => {
const ref = `${sourceNode.id}.yaml`
const includeText = `!include ${ref}\n`
const editor = editorRef.current
const monaco = monacoRef.current
try {
if (editor && monaco) {
const selection = editor.getSelection()
let range
if (selection) {
range = new monaco.Range(selection.startLineNumber, selection.startColumn, selection.startLineNumber, selection.startColumn)
} else {
const model = editor.getModel()
const lineCount = model.getLineCount()
range = new monaco.Range(lineCount + 1, 1, lineCount + 1, 1)
}
editor.executeEdits('insert-include', [{ range, text: includeText, forceMoveMarkers: true }])
const newVal = editor.getModel().getValue()
onChange(newVal)
return
}
onChange(value + '\n' + includeText)
} catch (err) {
// eslint-disable-next-line no-console
console.error('Insert include failed', err)
}
},
[onChange, value]
)
return (
<BaseNode className="w-80">
<BaseNodeHeader className="border-b">
<Pencil className="size-4" />
<BaseNodeHeaderTitle>{id}.yml</BaseNodeHeaderTitle>
</BaseNodeHeader>
<BaseNodeContent>
{connectedConfigNodes.length > 0 && (
<div className="px-0 py-0 text-xs bg-gray-50 border-b border-gray-100 w-full">
<div className="text-xs font-medium text-gray-600 px-3 pt-3">Connected configs</div>
<div className="mt-1 space-y-1 px-3 pb-3">
{connectedConfigNodes.map((n: any) => (
<div key={n.id} className="flex items-center justify-between">
<div className="text-xs text-gray-700">{n.data?.title ?? n.id}</div>
<div>
<button
className="text-xs px-2 py-0.5 bg-white border rounded text-gray-600"
onClick={() => insertIncludeFromNode(n)}
>
Insert include
</button>
</div>
</div>
))}
</div>
</div>
)}
<div style={{ height: 180 }} className="w-full">
<Editor
height="100%"
defaultLanguage="yaml"
value={value}
theme="vs-light"
onMount={handleEditorMount}
onChange={onChange}
options={{ minimap: { enabled: false }, fontSize: 12 }}
/>
</div>
</BaseNodeContent>
<BaseNodeFooter>
<div className="w-full text-xs text-gray-500">Stored YAML: {storedYaml ? `${storedYaml.length} chars` : 'none'}</div>
</BaseNodeFooter>
<Handle type="target" position={Position.Left} id="ain" style={{ background: '#F97316', top: 20, width: 12, height: 12, borderRadius: 3 }} />
<Handle type="source" position={Position.Right} id="out" style={{ background: '#10B981', top: 20, width: 12, height: 12, borderRadius: 3 }} />
</BaseNode>
)
})
ConfigNode.displayName = 'ConfigNode'
export default ConfigNode

View File

@@ -0,0 +1,171 @@
import { memo, useContext, useEffect, useMemo, useState } from 'react'
import { Handle, Position } from 'reactflow'
import yaml from 'js-yaml'
import FlowContext from '../../lib/flowContext'
import { Empty, EmptyHeader, EmptyTitle, EmptyDescription, EmptyContent, EmptyMedia } from '../ui/empty'
import {
BaseNode,
BaseNodeContent,
BaseNodeFooter,
BaseNodeHeader,
BaseNodeHeaderTitle,
} from './BaseNode'
import { Rocket } from 'lucide-react'
type Props = {
id: string
data?: any
}
export const RenderingNode = memo(function RenderingNode({ id }: Props) {
const [output, setOutput] = useState<string>('')
const [error, setError] = useState<null | { kind: string; message: string }>(null)
const ctx = useContext(FlowContext)
const nodes = ctx?.nodes ?? []
const edges = ctx?.edges ?? []
const setNodes = ctx?.setNodes
const setEdges = ctx?.setEdges
const incomingEdges = useMemo(() => edges.filter((e: any) => e.target === id), [edges, id])
const incomingIds = useMemo(() => incomingEdges.map((e: any) => e.source).sort(), [incomingEdges])
const srcId = incomingIds.length > 0 ? incomingIds[0] : null
const srcNode = nodes.find((n: any) => n.id === srcId)
const yamlText = srcNode && srcNode.type === 'config' ? srcNode?.data?.yaml ?? '' : ''
const srcData = srcNode?.data ?? {}
useEffect(() => {
// debug
// eslint-disable-next-line no-console
console.debug('RenderingNode:selection', {
id,
incomingIds,
srcNode: srcNode ? { id: srcNode.id, type: srcNode.type, yaml: (srcNode.data?.yaml ?? '').slice(0, 60) } : null,
})
if (!yamlText) {
if (incomingIds.length === 0) {
setOutput('')
setError(null)
return
}
setOutput('')
setError({ kind: 'no-yaml', message: 'No YAML found on connected configuration node' })
return
}
try {
const resolveIncludes = (text: string, visited = new Set<string>()): string => {
const includeRegex = /^(\s*)!include\s+([^\s]+)\s*$/gm
return text.replace(includeRegex, (match: string, indent: string, ref: string) => {
const refName = ref.endsWith('.yaml') ? ref.slice(0, -5) : ref
const refNode = nodes.find((n: any) => n.id === refName || n.data?.title === refName)
if (!refNode) throw new Error(`Included node not found: ${ref}`)
if (visited.has(refNode.id)) throw new Error(`Circular include detected: ${ref}`)
const isReachable = (startId: string, targetId: string) => {
const q: string[] = [startId]
const seen = new Set<string>([startId])
while (q.length) {
const cur = q.shift()!
if (cur === targetId) return true
for (const e of edges) {
if (e.source === cur && !seen.has(e.target)) {
seen.add(e.target)
q.push(e.target)
}
}
}
return false
}
if (!isReachable(refNode.id, id)) throw new Error(`Included node not connected to renderer: ${ref}`)
visited.add(refNode.id)
const includedRaw = String(refNode.data?.yaml ?? '')
const resolved = resolveIncludes(includedRaw, visited)
visited.delete(refNode.id)
const indented = resolved
.split('\n')
.map((line: string) => (line === '' ? '' : indent + line))
.join('\n')
return indented
})
}
const resolvedYaml = resolveIncludes(yamlText)
const parsed = yaml.load(resolvedYaml)
const newOutput = JSON.stringify(parsed, null, 2)
setError(null)
setOutput((prev) => (prev === newOutput ? prev : newOutput))
} catch (err: any) {
const msg = 'YAML parse/include error: ' + err.message
setOutput('')
setError({ kind: 'parse', message: msg })
}
}, [id, incomingIds.join(','), yamlText, nodes.length, edges.length])
return (
<BaseNode className="w-96">
<BaseNodeHeader className="border-b">
<Rocket className="size-4" />
<BaseNodeHeaderTitle>{id}</BaseNodeHeaderTitle>
</BaseNodeHeader>
<BaseNodeContent>
{incomingIds.length === 0 ? (
<Empty>
<EmptyHeader>
<EmptyMedia variant="icon">
<Rocket className="size-6" />
</EmptyMedia>
<EmptyTitle>No configuration connected</EmptyTitle>
<EmptyDescription>Connect a Configuration node or create one. The renderer will display parsed YAML.</EmptyDescription>
</EmptyHeader>
<EmptyContent>
<button
className="inline-flex items-center rounded bg-primary px-3 py-1 text-xs text-primary-foreground"
onClick={() => {
if (!setNodes || !setEdges) return
const genId = () => `node_${Math.random().toString(36).slice(2, 9)}`
const nid = genId()
const thisNode = nodes.find((n: any) => n.id === id)
const pos = thisNode?.position ?? { x: 0, y: 0 }
const newPos = { x: pos.x - 220, y: pos.y }
const newNode = { id: nid, type: 'config', position: newPos, data: { yaml: '# Enter YAML\n', title: `config-${nid}` } }
setNodes((nds: any[]) => nds.concat(newNode))
const edgeId = `e-${nid}-${id}`
setEdges((eds: any[]) => eds.concat({ id: edgeId, source: nid, target: id }))
}}
>
Create Config
</button>
</EmptyContent>
</Empty>
) : error ? (
srcData?.renderError ? (
srcData.renderError(error)
) : srcData?.errorHtml ? (
<div className="p-3 text-xs text-red-700" dangerouslySetInnerHTML={{ __html: String(srcData.errorHtml) }} />
) : (
<div className="p-3 text-xs text-red-700">{error.message}</div>
)
) : (
<pre className="text-xs text-gray-800 max-h-48 overflow-auto">{output}</pre>
)}
</BaseNodeContent>
<BaseNodeFooter>
<div className="w-full text-xs text-muted-foreground">Parsed YAML output</div>
</BaseNodeFooter>
<Handle type="target" position={Position.Left} id="ain" style={{ background: '#F97316', top: 20, width: 12, height: 12, borderRadius: 3 }} />
<Handle type="source" position={Position.Right} id="out" style={{ background: '#10B981', top: 20, width: 12, height: 12, borderRadius: 3 }} />
</BaseNode>
)
})
RenderingNode.displayName = 'RenderingNode'
export default RenderingNode