Image Pipeline Playground
feat(frontend): typed augment ports, annotations editor, overlays
Mohammad Rajaei2e41bf3a3143
diff --git a/frontend/src/features/canvas/PipelineCanvas.tsx b/frontend/src/features/canvas/PipelineCanvas.tsxindex d821ec6..b922041 100644--- a/frontend/src/features/canvas/PipelineCanvas.tsx+++ b/frontend/src/features/canvas/PipelineCanvas.tsx@@ -16,7 +16,8 @@ import { Box } from '@mui/material'import { useGraphStore } from '../../store/graphStore'import { PipelineNodeView } from './PipelineNode'import { EditableEdge } from './EditableEdge'-import type { NodeMetadata } from '../../types'+import type { NodeMetadata, PortSpec } from '../../types'+import { portsCompatible } from '../../lib/portTypes'function FitViewOnGraphChange() {const { fitView } = useReactFlow()@@ -34,6 +35,19 @@ function FitViewOnGraphChange() {return null}+function findPort(+ nodes: ReturnType<typeof useGraphStore.getState>['nodes'],+ nodeId: string | null | undefined,+ handleId: string | null | undefined,+ direction: 'input' | 'output',+): PortSpec | undefined {+ if (!nodeId) return undefined+ const node = nodes.find((item) => item.id === nodeId)+ const ports = node?.data.ports ?? []+ const portId = handleId ?? 'image'+ return ports.find((port) => port.id === portId && port.direction === direction)+}+export function PipelineCanvas() {const nodes = useGraphStore((s) => s.nodes)const edges = useGraphStore((s) => s.edges)@@ -66,7 +80,12 @@ export function PipelineCanvas() {const isValidConnection = useCallback((connection: Connection | Edge) => {if (!connection.source || !connection.target) return false- return connection.source !== connection.target+ if (connection.source === connection.target) return false+ const nodes = useGraphStore.getState().nodes+ const sourcePort = findPort(nodes, connection.source, connection.sourceHandle, 'output')+ const targetPort = findPort(nodes, connection.target, connection.targetHandle, 'input')+ if (!sourcePort || !targetPort) return true+ return portsCompatible(sourcePort.data_type, targetPort.data_type)}, [])const onReconnect = useCallback(diff --git a/frontend/src/features/canvas/PipelineNode.tsx b/frontend/src/features/canvas/PipelineNode.tsxindex b3ab00c..d8a15e0 100644--- a/frontend/src/features/canvas/PipelineNode.tsx+++ b/frontend/src/features/canvas/PipelineNode.tsx@@ -17,6 +17,7 @@ import {import type { GraphNodeData, PortSpec } from '../../types'import { useGraphStore, type NodeImageState } from '../../store/graphStore'import { useNodeMenu } from './NodeMenu'+import { isImageLikePort, portTypeColor } from '../../lib/portTypes'type PipelineFlowNode = Node<GraphNodeData, 'pipeline'>@@ -156,22 +157,25 @@ function buildPreviewGrid({outputPorts: PortSpec[]localPreviewUrls: string[]}): { columns: string[]; rows: ImageItem[][]; sectionPorts: PortSpec[] } {- // Only multi-output nodes (e.g. Split) get one column per port.- // Multi-input nodes (e.g. Merge) stay a single preview body.- const multiOut = outputPorts.length > 1+ // Prefer image-like output ports for the preview grid; annotation ports are+ // overlaid on the image by the backend and shown as caption chips.+ const imagePorts = outputPorts.filter((port) => isImageLikePort(port.data_type))+ const multiOut = imagePorts.length > 1const sectionPorts = multiOut- ? outputPorts- : outputPorts.length > 0- ? outputPorts- : [- {- id: 'image',- name: 'Image',- direction: 'output' as const,- data_type: 'image',- multiple: false,- },- ]+ ? imagePorts+ : imagePorts.length > 0+ ? imagePorts+ : outputPorts.length > 0 && isImageLikePort(outputPorts[0].data_type)+ ? [outputPorts[0]]+ : [+ {+ id: 'image',+ name: 'Image',+ direction: 'output' as const,+ data_type: 'image',+ multiple: false,+ },+ ]const columns = multiOut? sectionPorts.map((port) => port.id): [sectionPorts[0]?.id ?? 'image']@@ -266,7 +270,21 @@ export function PipelineNodeView({ id, data, selected }: NodeProps<PipelineFlowNconst emptyHint =data.type === 'load_image' || inputPorts.length === 0? 'Choose images or a folder'- : 'Connect upstream, then Run'+ : data.type === 'annotations'+ ? 'Edit bboxes & keypoints in the inspector'+ : 'Connect upstream, then Run'++ const annotationSummary = useMemo(() => {+ const annotations = nodeImages[id]?.annotations+ if (!annotations) return null+ const boxCount = Array.isArray(annotations.bboxes) ? annotations.bboxes.length : 0+ const kpCount = Array.isArray(annotations.keypoints) ? annotations.keypoints.length : 0+ if (boxCount === 0 && kpCount === 0) return null+ const parts: string[] = []+ if (boxCount > 0) parts.push(`${boxCount} bbox${boxCount === 1 ? '' : 's'}`)+ if (kpCount > 0) parts.push(`${kpCount} kp`)+ return parts.join(' · ')+ }, [id, nodeImages])return (<>@@ -376,6 +394,31 @@ export function PipelineNodeView({ id, data, selected }: NodeProps<PipelineFlowN{timing.cacheHit ? ' · cache' : ''}</Box>)}+ {annotationSummary && (+ <Box+ component="span"+ title="Annotation targets from last run"+ sx={{+ position: 'absolute',+ bottom: 6,+ left: 6,+ zIndex: 2,+ px: 0.7,+ py: 0.25,+ borderRadius: 0.75,+ bgcolor: 'rgba(0,0,0,0.72)',+ border: '1px solid rgba(245,176,65,0.45)',+ color: '#f5b041',+ fontSize: 10,+ fontWeight: 700,+ letterSpacing: '0.02em',+ whiteSpace: 'nowrap',+ pointerEvents: 'none',+ }}+ >+ {annotationSummary}+ </Box>+ )}{grid.rows.length === 0? (<Box@@ -521,7 +564,7 @@ export function PipelineNodeView({ id, data, selected }: NodeProps<PipelineFlowN...handleBaseStyle,top,left: -7,- background: '#7dcea0',+ background: portTypeColor(port.data_type, '#7dcea0'),}}/>{showLabel && (@@ -548,7 +591,7 @@ export function PipelineNodeView({ id, data, selected }: NodeProps<PipelineFlowNtop,right: -7,left: 'auto',- background: '#e67e22',+ background: portTypeColor(port.data_type, '#e67e22'),}}/>{showLabel && (diff --git a/frontend/src/features/inspector/AnnotationsParams.tsx b/frontend/src/features/inspector/AnnotationsParams.tsxnew file mode 100644index 0000000..6ada116--- /dev/null+++ b/frontend/src/features/inspector/AnnotationsParams.tsx@@ -0,0 +1,249 @@+import { useMemo, useState } from 'react'+import {+ Box,+ Button,+ IconButton,+ Stack,+ TextField,+ Typography,+} from '@mui/material'++type BBoxRow = {+ xMin: string+ yMin: string+ xMax: string+ yMax: string+ label: string+}++type KeypointRow = {+ x: string+ y: string+}++type AnnotationsParamsProps = {+ bboxesJson: string+ keypointsJson: string+ onChange: (next: { bboxes_json: string; keypoints_json: string }) => void+}++function parseBBoxes(raw: string): BBoxRow[] {+ try {+ const parsed = JSON.parse(raw) as unknown+ if (!Array.isArray(parsed) || parsed.length === 0) {+ return [{ xMin: '10', yMin: '10', xMax: '100', yMax: '80', label: 'object' }]+ }+ return parsed.map((item) => {+ const row = Array.isArray(item) ? item : []+ return {+ xMin: String(row[0] ?? 0),+ yMin: String(row[1] ?? 0),+ xMax: String(row[2] ?? 0),+ yMax: String(row[3] ?? 0),+ label: String(row[4] ?? 'object'),+ }+ })+ } catch {+ return [{ xMin: '10', yMin: '10', xMax: '100', yMax: '80', label: 'object' }]+ }+}++function parseKeypoints(raw: string): KeypointRow[] {+ try {+ const parsed = JSON.parse(raw) as unknown+ if (!Array.isArray(parsed) || parsed.length === 0) {+ return [{ x: '40', y: '40' }]+ }+ return parsed.map((item) => {+ const row = Array.isArray(item) ? item : []+ return { x: String(row[0] ?? 0), y: String(row[1] ?? 0) }+ })+ } catch {+ return [{ x: '40', y: '40' }]+ }+}++function serializeBBoxes(rows: BBoxRow[]): string {+ const payload = rows.map((row) => [+ Number(row.xMin),+ Number(row.yMin),+ Number(row.xMax),+ Number(row.yMax),+ row.label || 'object',+ ])+ return JSON.stringify(payload)+}++function serializeKeypoints(rows: KeypointRow[]): string {+ const payload = rows.map((row) => [Number(row.x), Number(row.y)])+ return JSON.stringify(payload)+}++export function AnnotationsParams({+ bboxesJson,+ keypointsJson,+ onChange,+}: AnnotationsParamsProps) {+ const [bboxes, setBboxes] = useState(() => parseBBoxes(bboxesJson))+ const [keypoints, setKeypoints] = useState(() => parseKeypoints(keypointsJson))+ const [advanced, setAdvanced] = useState(false)++ const commit = (nextBoxes: BBoxRow[], nextPoints: KeypointRow[]) => {+ setBboxes(nextBoxes)+ setKeypoints(nextPoints)+ onChange({+ bboxes_json: serializeBBoxes(nextBoxes),+ keypoints_json: serializeKeypoints(nextPoints),+ })+ }++ const jsonPreview = useMemo(+ () => ({+ bboxes: serializeBBoxes(bboxes),+ keypoints: serializeKeypoints(keypoints),+ }),+ [bboxes, keypoints],+ )++ return (+ <Stack spacing={2}>+ <Box>+ <Typography variant="caption" sx={{ color: 'rgba(244,241,234,0.65)' }}>+ Pascal VOC bboxes · [x_min, y_min, x_max, y_max, label]+ </Typography>+ <Stack spacing={1} sx={{ mt: 1 }}>+ {bboxes.map((row, index) => (+ <Stack+ key={`bbox-${index}`}+ direction="row"+ spacing={0.75}+ sx={{ alignItems: 'center' }}+ >+ {(['xMin', 'yMin', 'xMax', 'yMax', 'label'] as const).map((key) => (+ <TextField+ key={key}+ size="small"+ label={key}+ value={row[key]}+ onChange={(event) => {+ const next = bboxes.map((item, i) =>+ i === index ? { ...item, [key]: event.target.value } : item,+ )+ commit(next, keypoints)+ }}+ sx={{ flex: key === 'label' ? 1.2 : 1 }}+ />+ ))}+ <IconButton+ size="small"+ aria-label="Remove bbox"+ onClick={() => commit(bboxes.filter((_, i) => i !== index), keypoints)}+ disabled={bboxes.length <= 1}+ >+ ×+ </IconButton>+ </Stack>+ ))}+ <Button+ size="small"+ variant="outlined"+ onClick={() =>+ commit(+ [...bboxes, { xMin: '0', yMin: '0', xMax: '50', yMax: '50', label: 'object' }],+ keypoints,+ )+ }+ >+ Add bbox+ </Button>+ </Stack>+ </Box>++ <Box>+ <Typography variant="caption" sx={{ color: 'rgba(244,241,234,0.65)' }}>+ Keypoints · [x, y]+ </Typography>+ <Stack spacing={1} sx={{ mt: 1 }}>+ {keypoints.map((row, index) => (+ <Stack+ key={`kp-${index}`}+ direction="row"+ spacing={0.75}+ sx={{ alignItems: 'center' }}+ >+ <TextField+ size="small"+ label="x"+ value={row.x}+ onChange={(event) => {+ const next = keypoints.map((item, i) =>+ i === index ? { ...item, x: event.target.value } : item,+ )+ commit(bboxes, next)+ }}+ sx={{ flex: 1 }}+ />+ <TextField+ size="small"+ label="y"+ value={row.y}+ onChange={(event) => {+ const next = keypoints.map((item, i) =>+ i === index ? { ...item, y: event.target.value } : item,+ )+ commit(bboxes, next)+ }}+ sx={{ flex: 1 }}+ />+ <IconButton+ size="small"+ aria-label="Remove keypoint"+ onClick={() => commit(bboxes, keypoints.filter((_, i) => i !== index))}+ disabled={keypoints.length <= 1}+ >+ ×+ </IconButton>+ </Stack>+ ))}+ <Button+ size="small"+ variant="outlined"+ onClick={() => commit(bboxes, [...keypoints, { x: '0', y: '0' }])}+ >+ Add keypoint+ </Button>+ </Stack>+ </Box>++ <Button size="small" onClick={() => setAdvanced((value) => !value)}>+ {advanced ? 'Hide JSON' : 'Show JSON'}+ </Button>+ {advanced && (+ <Stack spacing={1}>+ <TextField+ size="small"+ label="BBoxes JSON"+ multiline+ minRows={2}+ value={jsonPreview.bboxes}+ onChange={(event) => {+ const next = parseBBoxes(event.target.value)+ commit(next, keypoints)+ }}+ />+ <TextField+ size="small"+ label="Keypoints JSON"+ multiline+ minRows={2}+ value={jsonPreview.keypoints}+ onChange={(event) => {+ const next = parseKeypoints(event.target.value)+ commit(bboxes, next)+ }}+ />+ </Stack>+ )}+ </Stack>+ )+}diff --git a/frontend/src/features/inspector/NodeInspector.tsx b/frontend/src/features/inspector/NodeInspector.tsxindex 09d971f..3261d43 100644--- a/frontend/src/features/inspector/NodeInspector.tsx+++ b/frontend/src/features/inspector/NodeInspector.tsx@@ -12,6 +12,7 @@ import { useGraphStore } from '../../store/graphStore'import type { ParamField } from '../../types'import { FileParamInput } from './FileParamInput'import { SaveImageParams } from './SaveImageParams'+import { AnnotationsParams } from './AnnotationsParams'function buildSchema(fields: ParamField[]) {const shape: Record<string, z.ZodTypeAny> = {}@@ -44,6 +45,7 @@ export function NodeInspector() {const fields = meta?.params ?? []const schema = buildSchema(fields)const isSaveImage = selected?.data.type === 'save_image'+ const isAnnotations = selected?.data.type === 'annotations'const { register, handleSubmit, reset, setValue, formState } = useForm({resolver: zodResolver(schema),@@ -79,7 +81,7 @@ export function NodeInspector() {lineHeight: 1.7,}}>- <li>Connect green inputs to orange outputs</li>+ <li>Connect matching port types (image, mask, bboxes, keypoints)</li><li>Press Run to execute with live previews</li><li>Export saves workflow JSON; Export Python codegen</li></Box>@@ -112,6 +114,27 @@ export function NodeInspector() {updateNodeParams(selected.id, { filename })}}/>+ ) : isAnnotations ? (+ <AnnotationsParams+ key={selected.id}+ bboxesJson={String(+ selected.data.params.bboxes_json ?? '[[10, 10, 100, 80, "object"]]',+ )}+ keypointsJson={String(+ selected.data.params.keypoints_json ?? '[[40, 40], [80, 60]]',+ )}+ onChange={(next) => {+ setValue('bboxes_json', next.bboxes_json, {+ shouldDirty: true,+ shouldValidate: true,+ })+ setValue('keypoints_json', next.keypoints_json, {+ shouldDirty: true,+ shouldValidate: true,+ })+ updateNodeParams(selected.id, next)+ }}+ />) : (<>{fields.length === 0 && (diff --git a/frontend/src/features/palette/NodePalette.tsx b/frontend/src/features/palette/NodePalette.tsxindex 3872263..90858b8 100644--- a/frontend/src/features/palette/NodePalette.tsx+++ b/frontend/src/features/palette/NodePalette.tsx@@ -28,6 +28,7 @@ const CATEGORY_ACCENT: Record<string, string> = {analysis: '#5dade2',math: '#58d68d',stochastic: '#f5b041',+ augment: '#e74c3c',}function categoryAccent(category: string): string {diff --git a/frontend/src/hooks/useExecutionSocket.ts b/frontend/src/hooks/useExecutionSocket.tsindex ae8aa6a..15646b3 100644--- a/frontend/src/hooks/useExecutionSocket.ts+++ b/frontend/src/hooks/useExecutionSocket.ts@@ -89,14 +89,17 @@ export function useExecutionSocket() {appendLog(event.message)}}- if (event.type === 'preview' && event.node_id && event.image_b64) {- addPreview({- nodeId: event.node_id,- sampleIndex: event.sample_index ?? 0,- imageB64: event.image_b64,- portId: event.port_id,- cacheHit: event.cache_hit,- })+ if (event.type === 'preview' && event.node_id) {+ if (event.image_b64 || event.data) {+ addPreview({+ nodeId: event.node_id,+ sampleIndex: event.sample_index ?? 0,+ imageB64: event.image_b64 ?? '',+ portId: event.port_id,+ cacheHit: event.cache_hit,+ data: event.data,+ })+ }}if (event.type === 'log' && event.message) appendLog(event.message)if (event.type === 'error') {diff --git a/frontend/src/lib/portTypes.ts b/frontend/src/lib/portTypes.tsnew file mode 100644index 0000000..35226c1--- /dev/null+++ b/frontend/src/lib/portTypes.ts@@ -0,0 +1,25 @@+/** Port data-type colors and connection rules for multi-target graphs. */++export const PORT_TYPE_COLORS: Record<string, string> = {+ image: '#7dcea0',+ mask: '#5dade2',+ bboxes: '#f5b041',+ keypoints: '#af7ac5',+}++export const IMAGE_LIKE_PORT_TYPES = new Set(['image', 'mask'])++export function portTypeColor(dataType: string, fallback = '#95a5a6'): string {+ return PORT_TYPE_COLORS[dataType] ?? fallback+}++export function portsCompatible(sourceType: string, targetType: string): boolean {+ if (sourceType === targetType) return true+ // Allow wiring a grayscale image into a mask port as a convenience.+ if (sourceType === 'image' && targetType === 'mask') return true+ return false+}++export function isImageLikePort(dataType: string): boolean {+ return IMAGE_LIKE_PORT_TYPES.has(dataType)+}diff --git a/frontend/src/store/graphStore.ts b/frontend/src/store/graphStore.tsindex 7697c1e..5cfecfb 100644--- a/frontend/src/store/graphStore.ts+++ b/frontend/src/store/graphStore.ts@@ -11,6 +11,7 @@ import {import { create } from 'zustand'import type { ExecutionPreview, GraphNodeData, NodeMetadata } from '../types'import type { WorkflowDocument, WorkflowGraphPayload } from '../workflow/io'+import { portTypeColor } from '../lib/portTypes'type PipelineNode = Node<GraphNodeData>@@ -24,6 +25,11 @@ export type NodeImageState = {ports: Record<string, string>/** Per-port sample stacks: portId → images[sampleIndex]. */portSamples: Record<string, string[]>+ /** Latest bbox / keypoint payloads from preview events. */+ annotations?: {+ bboxes?: unknown+ keypoints?: unknown+ }}/** Latest measured execution duration per node id. */@@ -179,7 +185,15 @@ export const useGraphStore = create<GraphState>((set, get) => ({onEdgesChange: (changes) =>set({ edges: applyEdgeChanges(changes, get().edges) }),- onConnect: (connection) =>+ onConnect: (connection) => {+ const nodes = get().nodes+ const sourceNode = nodes.find((node) => node.id === connection.source)+ const sourcePort = sourceNode?.data.ports.find(+ (port) =>+ port.direction === 'output' &&+ port.id === (connection.sourceHandle ?? 'image'),+ )+ const stroke = portTypeColor(sourcePort?.data_type ?? 'image', '#7dcea0')set({edges: addEdge({@@ -189,11 +203,13 @@ export const useGraphStore = create<GraphState>((set, get) => ({zIndex: 1000,reconnectable: true,selectable: true,- data: { waypoints: [] },+ style: { stroke, strokeWidth: 2 },+ data: { waypoints: [], dataType: sourcePort?.data_type ?? 'image' },},get().edges,),- }),+ })+ },onReconnect: (oldEdge, connection) => {const next = get().edges@@ -374,21 +390,36 @@ export const useGraphStore = create<GraphState>((set, get) => ({addPreview: (preview) => {const portId = preview.portId ?? 'image'const existing = get().nodeImages[preview.nodeId] ?? emptyNodeImages()- const ports = { ...existing.ports, [portId]: preview.imageB64 }+ const ports = { ...existing.ports }const portSamples = { ...existing.portSamples }- const portStack = [...(portSamples[portId] ?? [])]- while (portStack.length <= preview.sampleIndex) {- portStack.push('')+ const nextSamples = [...existing.samples]+ let annotations = existing.annotations++ if (preview.imageB64) {+ ports[portId] = preview.imageB64+ const portStack = [...(portSamples[portId] ?? [])]+ while (portStack.length <= preview.sampleIndex) {+ portStack.push('')+ }+ portStack[preview.sampleIndex] = preview.imageB64+ portSamples[portId] = portStack++ if (portId === 'image' || Object.keys(ports).length === 1) {+ while (nextSamples.length <= preview.sampleIndex) {+ nextSamples.push('')+ }+ nextSamples[preview.sampleIndex] = preview.imageB64+ }}- portStack[preview.sampleIndex] = preview.imageB64- portSamples[portId] = portStack- const nextSamples = [...existing.samples]- if (portId === 'image' || Object.keys(ports).length === 1) {- while (nextSamples.length <= preview.sampleIndex) {- nextSamples.push('')+ if (preview.data) {+ annotations = {+ ...annotations,+ ...(preview.data.bboxes !== undefined ? { bboxes: preview.data.bboxes } : {}),+ ...(preview.data.keypoints !== undefined+ ? { keypoints: preview.data.keypoints }+ : {}),}- nextSamples[preview.sampleIndex] = preview.imageB64}set({@@ -396,10 +427,11 @@ export const useGraphStore = create<GraphState>((set, get) => ({nodeImages: {...get().nodeImages,[preview.nodeId]: {- result: ports.image ?? Object.values(ports)[0] ?? preview.imageB64,+ result: ports.image ?? Object.values(ports)[0] ?? existing.result,samples: nextSamples,ports,portSamples,+ annotations,},},})diff --git a/frontend/src/types/graph.ts b/frontend/src/types/graph.tsindex 3e4d970..24b692f 100644--- a/frontend/src/types/graph.ts+++ b/frontend/src/types/graph.ts@@ -52,6 +52,7 @@ export interface ExecutionPreview {imageB64: stringportId?: string | nullcacheHit?: boolean | null+ data?: Record<string, unknown> | null}export type ExecutionEventType =