Skip to content

Image Pipeline Playground

feat: implement custom code trust mechanism for Python nodes

Mohammad Rajaeica701d39d229
diff --git a/frontend/src/app/App.tsx b/frontend/src/app/App.tsx
index 634b9f4..d32615b 100644
--- a/frontend/src/app/App.tsx
+++ b/frontend/src/app/App.tsx
@@ -32,6 +32,8 @@ import {
} from '../workflow/workflowActions'
import type { WorkflowTemplate } from '../workflow/templates'
import { AppHeader } from './AppHeader'
+import { CustomCodeTrustBanner } from '../features/execution/CustomCodeTrustBanner'
+import { CustomCodeTrustDialog } from '../features/execution/CustomCodeTrustDialog'
type NamePrompt = 'save' | 'export' | 'rename' | null
@@ -210,6 +212,8 @@ export default function App() {
onOpenTemplates={onOpenTemplates}
onOpenRecent={onOpenRecent}
/>
+ <CustomCodeTrustBanner />
+ <CustomCodeTrustDialog />
<WorkflowNameDialog
open={namePrompt != null}
title={
diff --git a/frontend/src/features/execution/CustomCodeTrustBanner.tsx b/frontend/src/features/execution/CustomCodeTrustBanner.tsx
new file mode 100644
index 0000000..b08982b
--- /dev/null
+++ b/frontend/src/features/execution/CustomCodeTrustBanner.tsx
@@ -0,0 +1,50 @@
+import { Box, Button, Typography } from '@mui/material'
+import { useGraphStore } from '../../store/graphStore'
+import { isCustomCodeTrusted } from '../../workflow/customCodeTrust'
+
+export function CustomCodeTrustBanner() {
+ const nodes = useGraphStore((s) => s.nodes)
+ const trustedCustomCodeHash = useGraphStore((s) => s.trustedCustomCodeHash)
+ const openCustomCodeTrustDialog = useGraphStore((s) => s.openCustomCodeTrustDialog)
+
+ const trusted = isCustomCodeTrusted(nodes, trustedCustomCodeHash)
+ const hasCustom = nodes.some((node) => node.data.type === 'custom_python')
+
+ if (!hasCustom || trusted) return null
+
+ return (
+ <Box
+ sx={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 1.5,
+ px: 2,
+ py: 1,
+ bgcolor: 'rgba(192, 57, 43, 0.14)',
+ borderBottom: '1px solid rgba(192, 57, 43, 0.35)',
+ }}
+ >
+ <Typography sx={{ flex: 1, fontSize: 13, color: '#f0ebe3', lineHeight: 1.4 }}>
+ This workflow includes custom Python. Review and trust the code before running.
+ </Typography>
+ <Button
+ size="small"
+ variant="outlined"
+ onClick={() => openCustomCodeTrustDialog(undefined, false)}
+ sx={{
+ textTransform: 'none',
+ fontWeight: 650,
+ color: '#f0ebe3',
+ borderColor: 'rgba(240,235,227,0.35)',
+ whiteSpace: 'nowrap',
+ '&:hover': {
+ borderColor: 'rgba(240,235,227,0.55)',
+ bgcolor: 'rgba(255,255,255,0.06)',
+ },
+ }}
+ >
+ Review & trust
+ </Button>
+ </Box>
+ )
+}
diff --git a/frontend/src/features/execution/CustomCodeTrustDialog.tsx b/frontend/src/features/execution/CustomCodeTrustDialog.tsx
new file mode 100644
index 0000000..1b6e99e
--- /dev/null
+++ b/frontend/src/features/execution/CustomCodeTrustDialog.tsx
@@ -0,0 +1,129 @@
+import {
+ Box,
+ Button,
+ Dialog,
+ DialogContent,
+ Stack,
+ Typography,
+} from '@mui/material'
+import { useGraphStore } from '../../store/graphStore'
+import {
+ listCustomPythonNodes,
+ truncateCodePreview,
+} from '../../workflow/customCodeTrust'
+import { runPipeline } from '../../hooks/useExecutionSocket'
+
+export function CustomCodeTrustDialog() {
+ const open = useGraphStore((s) => s.customCodeTrustDialogOpen)
+ const nodes = useGraphStore((s) => s.nodes)
+ const pendingRunOptions = useGraphStore((s) => s.pendingRunOptions)
+ const pendingRunAfterTrust = useGraphStore((s) => s.pendingRunAfterTrust)
+ const trustCustomCode = useGraphStore((s) => s.trustCustomCode)
+ const closeCustomCodeTrustDialog = useGraphStore((s) => s.closeCustomCodeTrustDialog)
+
+ const customNodes = listCustomPythonNodes(nodes)
+
+ const onConfirm = () => {
+ const options = pendingRunOptions
+ const shouldRun = pendingRunAfterTrust
+ trustCustomCode()
+ closeCustomCodeTrustDialog()
+ if (shouldRun) {
+ runPipeline(options ?? undefined)
+ }
+ }
+
+ return (
+ <Dialog
+ open={open}
+ onClose={closeCustomCodeTrustDialog}
+ maxWidth="sm"
+ fullWidth
+ slotProps={{
+ paper: {
+ sx: {
+ bgcolor: '#161616',
+ color: '#f0ebe3',
+ border: '1px solid rgba(255,255,255,0.1)',
+ borderRadius: 2,
+ backgroundImage: 'none',
+ },
+ },
+ }}
+ >
+ <DialogContent sx={{ pt: 2.5, pb: 2.5, px: 2.5 }}>
+ <Typography
+ sx={{
+ mb: 1,
+ fontFamily: '"Fraunces", Georgia, serif',
+ fontWeight: 700,
+ fontSize: 20,
+ letterSpacing: '-0.02em',
+ }}
+ >
+ Trust custom Python?
+ </Typography>
+ <Typography sx={{ fontSize: 13, color: 'rgba(244,241,234,0.6)', lineHeight: 1.5, mb: 2 }}>
+ This workflow includes Custom Python nodes. The code runs on your machine with full
+ access (same as any local script). Only continue if you reviewed the code and trust
+ its source.
+ </Typography>
+
+ <Stack spacing={1.25} sx={{ mb: 2.25, maxHeight: 220, overflow: 'auto' }}>
+ {customNodes.map((node) => (
+ <Box
+ key={node.id}
+ sx={{
+ p: 1.25,
+ borderRadius: 1.25,
+ bgcolor: 'rgba(255,255,255,0.04)',
+ border: '1px solid rgba(255,255,255,0.08)',
+ }}
+ >
+ <Typography sx={{ fontSize: 12, fontWeight: 650, mb: 0.5 }}>
+ {node.data.label ?? 'Custom Python'}{' '}
+ <Typography component="span" sx={{ color: 'rgba(244,241,234,0.4)', fontWeight: 500 }}>
+ ({node.id})
+ </Typography>
+ </Typography>
+ <Typography
+ component="pre"
+ sx={{
+ m: 0,
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace',
+ fontSize: 11,
+ color: 'rgba(244,241,234,0.55)',
+ whiteSpace: 'pre-wrap',
+ wordBreak: 'break-word',
+ }}
+ >
+ {truncateCodePreview(String(node.data.params.code ?? ''), 160)}
+ </Typography>
+ </Box>
+ ))}
+ </Stack>
+
+ <Box sx={{ display: 'flex', gap: 1, justifyContent: 'flex-end' }}>
+ <Button
+ onClick={closeCustomCodeTrustDialog}
+ sx={{ textTransform: 'none', color: 'rgba(244,241,234,0.65)' }}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="contained"
+ onClick={onConfirm}
+ sx={{
+ textTransform: 'none',
+ fontWeight: 650,
+ bgcolor: '#c0392b',
+ '&:hover': { bgcolor: '#a93226' },
+ }}
+ >
+ {pendingRunAfterTrust ? 'Trust and run' : 'Trust'}
+ </Button>
+ </Box>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/features/inspector/CustomPythonParams.tsx b/frontend/src/features/inspector/CustomPythonParams.tsx
new file mode 100644
index 0000000..fc661be
--- /dev/null
+++ b/frontend/src/features/inspector/CustomPythonParams.tsx
@@ -0,0 +1,253 @@
+import { useRef, useState } from 'react'
+import Editor, { type OnMount } from '@monaco-editor/react'
+import {
+ Box,
+ Button,
+ Dialog,
+ DialogContent,
+ Typography,
+} from '@mui/material'
+
+type CustomPythonParamsProps = {
+ code: string
+ onCodeChange: (code: string) => void
+}
+
+const ICON_COLOR = '#f0ebe3'
+
+const readOnlyOptions = {
+ readOnly: true,
+ domReadOnly: true,
+ minimap: { enabled: false },
+ fontSize: 12,
+ scrollBeyondLastLine: false,
+ wordWrap: 'on' as const,
+ lineNumbers: 'on' as const,
+ tabSize: 4,
+ automaticLayout: true,
+ renderLineHighlight: 'none' as const,
+ quickSuggestions: false,
+ suggestOnTriggerCharacters: false,
+ parameterHints: { enabled: false },
+ hover: { enabled: 'off' as const },
+ contextmenu: false,
+ accessibilitySupport: 'off' as const,
+}
+
+const editOptions = {
+ ...readOnlyOptions,
+ readOnly: false,
+ domReadOnly: false,
+ fontSize: 14,
+ minimap: { enabled: true },
+ renderLineHighlight: 'line' as const,
+ contextmenu: true,
+ // Keep IntelliSense off so typing stays predictable.
+ acceptSuggestionOnEnter: 'off' as const,
+ tabCompletion: 'off' as const,
+ wordBasedSuggestions: 'off' as const,
+ snippetSuggestions: 'none' as const,
+ suggestOnTriggerCharacters: false,
+ quickSuggestions: {
+ other: false,
+ comments: false,
+ strings: false,
+ },
+}
+
+function EditIcon({ color = ICON_COLOR }: { color?: string }) {
+ return (
+ <svg width="16" height="16" viewBox="0 0 24 24" aria-hidden focusable="false">
+ <path
+ fill={color}
+ d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1.003 1.003 0 0 0 0-1.42l-2.34-2.34a1.003 1.003 0 0 0-1.42 0l-1.83 1.83 3.75 3.75 1.84-1.82z"
+ />
+ </svg>
+ )
+}
+
+export function CustomPythonParams({ code, onCodeChange }: CustomPythonParamsProps) {
+ const [editing, setEditing] = useState(false)
+ const [editorSeed, setEditorSeed] = useState(code)
+ const draftRef = useRef(code)
+
+ const openEditor = () => {
+ draftRef.current = code
+ setEditorSeed(code)
+ setEditing(true)
+ }
+
+ const closeEditor = (save: boolean) => {
+ if (save) {
+ onCodeChange(draftRef.current)
+ }
+ setEditing(false)
+ }
+
+ const onEditMount: OnMount = (ed, monaco) => {
+ // React Flow skips keyboard shortcuts inside `.nokey`.
+ ed.getContainerDomNode().classList.add('nokey')
+ ed.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.Space, () => {})
+ ed.focus()
+ }
+
+ return (
+ <Box sx={{ display: 'grid', gap: 1.25 }}>
+ <Typography sx={{ fontSize: 13, color: 'rgba(244,241,234,0.55)', lineHeight: 1.45 }}>
+ Define <code>process(image, seed=0)</code> and return a BGR numpy ndarray.{' '}
+ <code>cv2</code>, <code>np</code>, and <code>numpy</code> are available. Code runs with
+ full local privileges — only run workflows you trust.
+ </Typography>
+
+ <Box
+ sx={{
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ gap: 1,
+ }}
+ >
+ <Typography sx={{ fontSize: 12, fontWeight: 650, color: 'rgba(244,241,234,0.7)' }}>
+ Code
+ </Typography>
+ <Button
+ size="small"
+ variant="outlined"
+ startIcon={<EditIcon />}
+ onClick={openEditor}
+ sx={{
+ textTransform: 'none',
+ fontWeight: 650,
+ fontSize: 12,
+ color: ICON_COLOR,
+ borderColor: 'rgba(255,255,255,0.16)',
+ '& .MuiButton-startIcon': { color: ICON_COLOR },
+ '&:hover': {
+ borderColor: 'rgba(125,206,160,0.45)',
+ bgcolor: 'rgba(125,206,160,0.08)',
+ },
+ }}
+ >
+ Edit code
+ </Button>
+ </Box>
+
+ <Box
+ className="nokey"
+ sx={{
+ height: 280,
+ border: '1px solid rgba(255,255,255,0.12)',
+ borderRadius: 1,
+ overflow: 'hidden',
+ opacity: 0.92,
+ }}
+ >
+ <Editor
+ height="100%"
+ defaultLanguage="python"
+ value={code}
+ theme="vs-dark"
+ options={readOnlyOptions}
+ />
+ </Box>
+
+ <Dialog
+ open={editing}
+ onClose={() => closeEditor(true)}
+ fullScreen
+ // Keep canvas shortcuts from seeing editor key events.
+ className="nokey"
+ slotProps={{
+ paper: {
+ className: 'nokey',
+ sx: {
+ bgcolor: '#0f0f0f',
+ color: ICON_COLOR,
+ backgroundImage: 'none',
+ display: 'flex',
+ flexDirection: 'column',
+ },
+ },
+ }}
+ >
+ <Box
+ className="nokey"
+ sx={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 1,
+ px: 2,
+ py: 1.25,
+ borderBottom: '1px solid rgba(255,255,255,0.1)',
+ flexShrink: 0,
+ }}
+ >
+ <Typography
+ sx={{
+ flex: 1,
+ fontFamily: '"Fraunces", Georgia, serif',
+ fontWeight: 700,
+ fontSize: 18,
+ letterSpacing: '-0.02em',
+ }}
+ >
+ Edit Custom Python
+ </Typography>
+ <Button
+ size="small"
+ onClick={() => closeEditor(false)}
+ sx={{
+ textTransform: 'none',
+ color: 'rgba(244,241,234,0.65)',
+ }}
+ >
+ Cancel
+ </Button>
+ <Button
+ size="small"
+ variant="contained"
+ onClick={() => closeEditor(true)}
+ sx={{
+ textTransform: 'none',
+ fontWeight: 650,
+ bgcolor: '#7dcea0',
+ color: '#0f0f0f',
+ '&:hover': { bgcolor: '#6bbd8e' },
+ }}
+ >
+ Save
+ </Button>
+ </Box>
+ <DialogContent
+ className="nokey"
+ sx={{
+ p: 0,
+ flex: 1,
+ minHeight: 0,
+ display: 'flex',
+ flexDirection: 'column',
+ }}
+ // Stop React Flow (window listeners) from seeing these keys while editing.
+ onKeyDown={(event) => event.stopPropagation()}
+ onKeyUp={(event) => event.stopPropagation()}
+ >
+ <Box className="nokey" sx={{ flex: 1, minHeight: 0 }}>
+ {editing ? (
+ <Editor
+ height="100%"
+ defaultLanguage="python"
+ defaultValue={editorSeed}
+ theme="vs-dark"
+ onChange={(value) => {
+ draftRef.current = value ?? ''
+ }}
+ onMount={onEditMount}
+ options={editOptions}
+ />
+ ) : null}
+ </Box>
+ </DialogContent>
+ </Dialog>
+ </Box>
+ )
+}
diff --git a/frontend/src/features/inspector/NodeInspector.tsx b/frontend/src/features/inspector/NodeInspector.tsx
index d255b9e..faef9c9 100644
--- a/frontend/src/features/inspector/NodeInspector.tsx
+++ b/frontend/src/features/inspector/NodeInspector.tsx
@@ -13,6 +13,7 @@ import type { ParamField } from '../../types'
import { FileParamInput } from './FileParamInput'
import { SaveImageParams } from './SaveImageParams'
import { AnnotationsParams } from './AnnotationsParams'
+import { CustomPythonParams } from './CustomPythonParams'
function buildSchema(fields: ParamField[]) {
const shape: Record<string, z.ZodTypeAny> = {}
@@ -46,6 +47,7 @@ export function NodeInspector() {
const isSaveImage = selected?.data.type === 'save_image'
const isLoadImage = selected?.data.type === 'load_image'
const isAnnotations = selected?.data.type === 'annotations'
+ const isCustomPython = selected?.data.type === 'custom_python'
const { register, handleSubmit, reset, setValue, formState } = useForm({
resolver: zodResolver(schema),
@@ -126,6 +128,15 @@ export function NodeInspector() {
updateNodeParams(selected.id, { packaging })
}}
/>
+ ) : isCustomPython ? (
+ <CustomPythonParams
+ key={selected.id}
+ code={String(selected.data.params.code ?? '')}
+ onCodeChange={(nextCode) => {
+ setValue('code', nextCode, { shouldDirty: true, shouldValidate: true })
+ updateNodeParams(selected.id, { code: nextCode })
+ }}
+ />
) : isLoadImage ? (
<FileParamInput
field={{
diff --git a/frontend/src/hooks/useExecutionSocket.ts b/frontend/src/hooks/useExecutionSocket.ts
index 4e01bc7..334284b 100644
--- a/frontend/src/hooks/useExecutionSocket.ts
+++ b/frontend/src/hooks/useExecutionSocket.ts
@@ -49,9 +49,16 @@ export function useExecutionSocket() {
const run = useCallback(
(options?: RunOptions) => {
+ const state = useGraphStore.getState()
+ if (!state.isCustomCodeTrusted()) {
+ state.openCustomCodeTrustDialog(options)
+ return
+ }
+
clearExecution()
setIsExecuting(true)
targetLabelRef.current = options?.targetNodeId ?? null
+ const allowCustomCode = state.graphHasCustomCode()
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws'
const socket = new WebSocket(`${protocol}://${window.location.host}/ws/execute`)
@@ -64,6 +71,7 @@ export function useExecutionSocket() {
seed,
sample_count: iterationCount,
cache: true,
+ allow_custom_code: allowCustomCode,
...(options?.targetNodeId
? { target_node_id: options.targetNodeId }
: {}),
diff --git a/frontend/src/store/graphStore.ts b/frontend/src/store/graphStore.ts
index ea1f86d..1663110 100644
--- a/frontend/src/store/graphStore.ts
+++ b/frontend/src/store/graphStore.ts
@@ -15,6 +15,11 @@ import {
type WorkflowDocument,
type WorkflowGraphPayload,
} from '../workflow/io'
+import {
+ computeCustomCodeHash,
+ graphHasCustomCode,
+ isCustomCodeTrusted,
+} from '../workflow/customCodeTrust'
import { portTypeColor } from '../lib/portTypes'
@@ -69,6 +74,12 @@ interface GraphState {
workflowCreatedAt: string | null
workflowUpdatedAt: string | null
workflowDirty: boolean
+ /** Session-only fingerprint of trusted custom_python code; null = untrusted when code exists. */
+ trustedCustomCodeHash: string | null
+ customCodeTrustDialogOpen: boolean
+ pendingRunOptions: { targetNodeId?: string } | null
+ /** When true, confirming the trust dialog also starts a pipeline run. */
+ pendingRunAfterTrust: boolean
setNodeCatalog: (catalog: NodeMetadata[]) => void
onNodesChange: (changes: NodeChange<PipelineNode>[]) => void
onEdgesChange: (changes: EdgeChange[]) => void
@@ -111,6 +122,14 @@ interface GraphState {
toGraphPayload: () => WorkflowGraphPayload
toWorkflowDocument: () => WorkflowDocument
loadWorkflow: (doc: WorkflowDocument) => { skippedTypes: string[] }
+ trustCustomCode: () => void
+ openCustomCodeTrustDialog: (
+ options?: { targetNodeId?: string },
+ runAfterTrust?: boolean,
+ ) => void
+ closeCustomCodeTrustDialog: () => void
+ isCustomCodeTrusted: () => boolean
+ graphHasCustomCode: () => boolean
}
const STRUCTURAL_NODE_CHANGE_TYPES = new Set(['add', 'remove', 'position', 'replace'])
@@ -179,6 +198,10 @@ export const useGraphStore = create<GraphState>((set, get) => ({
workflowCreatedAt: null,
workflowUpdatedAt: null,
workflowDirty: false,
+ trustedCustomCodeHash: null,
+ customCodeTrustDialogOpen: false,
+ pendingRunOptions: null,
+ pendingRunAfterTrust: false,
setNodeCatalog: (catalog) => set({ nodeCatalog: catalog }),
@@ -310,7 +333,14 @@ export const useGraphStore = create<GraphState>((set, get) => ({
localPreviewUrls: [],
},
}
- set({ nodes: [...get().nodes, node], selectedNodeId: id, workflowDirty: true })
+ set({
+ nodes: [...get().nodes, node],
+ selectedNodeId: id,
+ workflowDirty: true,
+ ...(meta.type === 'custom_python'
+ ? { trustedCustomCodeHash: computeCustomCodeHash([...get().nodes, node]) }
+ : {}),
+ })
},
removeNode: (nodeId) => {
@@ -341,20 +371,34 @@ export const useGraphStore = create<GraphState>((set, get) => ({
nodes: [...get().nodes.map((node) => ({ ...node, selected: false })), copy],
selectedNodeId: id,
workflowDirty: true,
+ ...(source.data.type === 'custom_python'
+ ? {
+ trustedCustomCodeHash: computeCustomCodeHash([
+ ...get().nodes,
+ copy,
+ ]),
+ }
+ : {}),
})
},
selectNode: (nodeId) => set({ selectedNodeId: nodeId }),
- updateNodeParams: (nodeId, params) =>
+ updateNodeParams: (nodeId, params) => {
+ const nodes = get().nodes.map((node) =>
+ node.id === nodeId
+ ? { ...node, data: { ...node.data, params: { ...node.data.params, ...params } } }
+ : node,
+ )
+ const target = nodes.find((node) => node.id === nodeId)
+ const autoTrust =
+ target?.data.type === 'custom_python' && Object.prototype.hasOwnProperty.call(params, 'code')
set({
- nodes: get().nodes.map((node) =>
- node.id === nodeId
- ? { ...node, data: { ...node.data, params: { ...node.data.params, ...params } } }
- : node,
- ),
+ nodes,
workflowDirty: true,
- }),
+ ...(autoTrust ? { trustedCustomCodeHash: computeCustomCodeHash(nodes) } : {}),
+ })
+ },
setLocalPreview: (nodeId, dataUrl) =>
set({
@@ -574,6 +618,10 @@ export const useGraphStore = create<GraphState>((set, get) => ({
workflowCreatedAt: null,
workflowUpdatedAt: null,
workflowDirty: false,
+ trustedCustomCodeHash: null,
+ customCodeTrustDialogOpen: false,
+ pendingRunOptions: null,
+ pendingRunAfterTrust: false,
})
},
@@ -744,8 +792,35 @@ export const useGraphStore = create<GraphState>((set, get) => ({
workflowCreatedAt: doc.createdAt ?? null,
workflowUpdatedAt: doc.updatedAt ?? null,
workflowDirty: false,
+ // Imported / restored / template workflows with custom code start untrusted.
+ trustedCustomCodeHash: null,
+ customCodeTrustDialogOpen: false,
+ pendingRunOptions: null,
+ pendingRunAfterTrust: false,
})
return { skippedTypes: [...skipped].sort() }
},
+
+ trustCustomCode: () => {
+ set({ trustedCustomCodeHash: computeCustomCodeHash(get().nodes) })
+ },
+
+ openCustomCodeTrustDialog: (options, runAfterTrust = true) =>
+ set({
+ customCodeTrustDialogOpen: true,
+ pendingRunOptions: options ?? {},
+ pendingRunAfterTrust: runAfterTrust,
+ }),
+
+ closeCustomCodeTrustDialog: () =>
+ set({
+ customCodeTrustDialogOpen: false,
+ pendingRunOptions: null,
+ pendingRunAfterTrust: false,
+ }),
+
+ isCustomCodeTrusted: () => isCustomCodeTrusted(get().nodes, get().trustedCustomCodeHash),
+
+ graphHasCustomCode: () => graphHasCustomCode(get().nodes),
}))
diff --git a/frontend/src/workflow/customCodeTrust.ts b/frontend/src/workflow/customCodeTrust.ts
new file mode 100644
index 0000000..af9a319
--- /dev/null
+++ b/frontend/src/workflow/customCodeTrust.ts
@@ -0,0 +1,58 @@
+/** Custom Python trust fingerprint helpers (session-only; not persisted in workflow JSON). */
+
+export const CUSTOM_PYTHON_TYPE = 'custom_python'
+
+export type CustomCodeNodeLike = {
+ id: string
+ data: {
+ type: string
+ label?: string
+ params: Record<string, unknown>
+ }
+}
+
+/** Stable non-cryptographic hash for code fingerprints. */
+export function hashString(input: string): string {
+ let hash = 2166136261
+ for (let i = 0; i < input.length; i += 1) {
+ hash ^= input.charCodeAt(i)
+ hash = Math.imul(hash, 16777619)
+ }
+ return (hash >>> 0).toString(16).padStart(8, '0')
+}
+
+export function listCustomPythonNodes(nodes: CustomCodeNodeLike[]): CustomCodeNodeLike[] {
+ return nodes
+ .filter((node) => node.data.type === CUSTOM_PYTHON_TYPE)
+ .sort((a, b) => a.id.localeCompare(b.id))
+}
+
+export function graphHasCustomCode(nodes: CustomCodeNodeLike[]): boolean {
+ return nodes.some((node) => node.data.type === CUSTOM_PYTHON_TYPE)
+}
+
+/** Hash of all custom_python code params, or null if none present. */
+export function computeCustomCodeHash(nodes: CustomCodeNodeLike[]): string | null {
+ const parts: string[] = []
+ for (const node of listCustomPythonNodes(nodes)) {
+ const code = String(node.data.params.code ?? '')
+ parts.push(`${node.id}\0${code}`)
+ }
+ if (parts.length === 0) return null
+ return hashString(parts.join('\n'))
+}
+
+export function isCustomCodeTrusted(
+ nodes: CustomCodeNodeLike[],
+ trustedHash: string | null,
+): boolean {
+ const hash = computeCustomCodeHash(nodes)
+ if (hash === null) return true
+ return trustedHash === hash
+}
+
+export function truncateCodePreview(code: string, max = 120): string {
+ const flat = code.replace(/\s+/g, ' ').trim()
+ if (flat.length <= max) return flat
+ return `${flat.slice(0, max - 1)}…`
+}
diff --git a/frontend/src/workflow/templates.ts b/frontend/src/workflow/templates.ts
index ddc698a..3275d28 100644
--- a/frontend/src/workflow/templates.ts
+++ b/frontend/src/workflow/templates.ts
@@ -5,6 +5,7 @@ export type TemplateCategory =
| 'structure'
| 'augment'
| 'color'
+ | 'script'
export type WorkflowTemplate = {
id: string
@@ -27,6 +28,7 @@ export const TEMPLATE_CATEGORY_META: Record<
structure: { label: 'Structure', accent: '#af7ac5' },
augment: { label: 'Augment', accent: '#e74c3c' },
color: { label: 'Color', accent: '#f5b041' },
+ script: { label: 'Script', accent: '#58d68d' },
}
export const WORKFLOW_TEMPLATES: WorkflowTemplate[] = [
@@ -118,4 +120,13 @@ export const WORKFLOW_TEMPLATES: WorkflowTemplate[] = [
category: 'color',
steps: ['Load', 'K-Means'],
},
+ {
+ id: 'custom_python_sepia',
+ name: 'Custom Python Sepia',
+ description:
+ 'Load Lena, then apply a sepia look via inline Custom Python (requires trust before Run).',
+ path: '/examples/custom_python_sepia.json',
+ category: 'script',
+ steps: ['Load', 'Custom Python'],
+ },
]